@agentfield/sdk 0.1.110 → 0.1.111-rc.2

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/dist/index.d.ts CHANGED
@@ -150,6 +150,15 @@ declare class AIClient {
150
150
  * Exposed for use by the tool-calling loop.
151
151
  */
152
152
  getModel(options?: AIRequestOptions): _ai_sdk_provider.LanguageModelV3;
153
+ /**
154
+ * Resolve the effective provider/model pair for a request without building
155
+ * the model. Used by usage tracking to attribute token/cost entries to the
156
+ * model actually called.
157
+ */
158
+ resolveModelChoice(options?: AIRequestOptions): {
159
+ provider: NonNullable<AIConfig['provider']>;
160
+ modelName: string;
161
+ };
153
162
  private buildModel;
154
163
  private buildEmbeddingModel;
155
164
  private openRouterHeaders;
@@ -372,6 +381,142 @@ declare class ExecutionLogger {
372
381
  }
373
382
  declare function createExecutionLogger(options?: ExecutionLoggerOptions): ExecutionLogger;
374
383
 
384
+ /**
385
+ * Per-execution LLM cost and token-usage tracking.
386
+ *
387
+ * Mirrors the Python SDK's `agentfield/cost_tracker.py`: a `CostTracker`
388
+ * accumulates one `CostEntry` per LLM (or coding-agent harness) call made
389
+ * during a single reasoner execution, and `serialize()` emits the
390
+ * cross-language wire contract consumed by the control plane's usage-ingest
391
+ * path (see the Go `parseUsageEntries`).
392
+ */
393
+ /**
394
+ * Reserved envelope key used to attach the serialized usage summary to a
395
+ * synchronous 200 result body. Namespaced so it cannot collide with user data:
396
+ * a plain "usage" key in an agent's own result object is user payload and must
397
+ * never be touched. The control plane strips exactly this key back out (see
398
+ * the Go `extractUsageFromResult`). `__agentfield_`-prefixed keys are reserved
399
+ * for SDK<->control-plane transport.
400
+ */
401
+ declare const USAGE_ENVELOPE_KEY = "__agentfield_usage__";
402
+ /** A single LLM (or harness) call usage record. */
403
+ interface CostEntry {
404
+ model: string;
405
+ inputTokens: number;
406
+ outputTokens: number;
407
+ totalTokens: number;
408
+ /**
409
+ * Cost may be unknown (provider gave no figure) — tokens are recorded
410
+ * regardless, so cost is nullable and never gates them.
411
+ */
412
+ costUsd: number | null;
413
+ reasonerName: string | null;
414
+ /** "llm" for direct model calls, "harness" for coding-agent runs. */
415
+ source: 'llm' | 'harness';
416
+ /** e.g. "anthropic", "openrouter" — derived from the model slug if unset. */
417
+ provider: string | null;
418
+ /** e.g. "claude_code" for harness-originated entries; null for plain LLM. */
419
+ harness: string | null;
420
+ cacheReadTokens: number;
421
+ cacheCreationTokens: number;
422
+ /** Where costUsd came from: "provider" | null. */
423
+ costSource: string | null;
424
+ }
425
+ /** Input accepted by {@link CostTracker.record}. */
426
+ interface CostEntryInit {
427
+ model: string;
428
+ inputTokens?: number;
429
+ outputTokens?: number;
430
+ totalTokens?: number;
431
+ costUsd?: number | null;
432
+ reasonerName?: string | null;
433
+ source?: 'llm' | 'harness';
434
+ provider?: string | null;
435
+ harness?: string | null;
436
+ cacheReadTokens?: number;
437
+ cacheCreationTokens?: number;
438
+ costSource?: string | null;
439
+ }
440
+ /** Wire form of a single usage entry (snake_case cross-language contract). */
441
+ interface UsageEntryWire {
442
+ source: string;
443
+ provider: string | null;
444
+ model: string;
445
+ harness: string | null;
446
+ reasoner: string | null;
447
+ input_tokens: number;
448
+ output_tokens: number;
449
+ cache_read_tokens: number;
450
+ cache_creation_tokens: number;
451
+ total_tokens: number;
452
+ cost_usd: number | null;
453
+ cost_source: string | null;
454
+ }
455
+ /** Wire form of the usage summary attached to execution envelopes. */
456
+ interface UsageSummaryWire {
457
+ /** Null when no entry had a known cost; otherwise sum rounded to 6 decimals. */
458
+ total_cost_usd: number | null;
459
+ total_input_tokens: number;
460
+ total_output_tokens: number;
461
+ total_tokens: number;
462
+ entries: UsageEntryWire[];
463
+ }
464
+ /**
465
+ * Best-effort provider name from a model slug.
466
+ *
467
+ * `anthropic/claude-opus-4-8` -> `anthropic`,
468
+ * `openrouter/anthropic/claude` -> `openrouter`,
469
+ * a bare `gpt-4o` (no provider prefix) -> `null`.
470
+ */
471
+ declare function deriveProvider(model: string | null | undefined): string | null;
472
+ /** Accumulates LLM/harness usage for a single execution run. */
473
+ declare class CostTracker {
474
+ private entries;
475
+ /**
476
+ * Record a single call's usage.
477
+ *
478
+ * Cost is optional: a call with known token counts but unknown price is
479
+ * still recorded (`costUsd: null`) so tokens are never discarded.
480
+ */
481
+ record(init: CostEntryInit): void;
482
+ /** Total accumulated cost in USD (unknown costs count as zero). */
483
+ get totalCostUsd(): number;
484
+ /** Total tokens used across all calls (per-entry total, no fallback). */
485
+ get totalTokens(): number;
486
+ /** Number of calls tracked. */
487
+ get callCount(): number;
488
+ get hasEntries(): boolean;
489
+ /**
490
+ * Return the transport contract form attached to execution envelopes.
491
+ *
492
+ * Matches the Python SDK's `CostTracker.serialize()` byte-for-byte in shape:
493
+ * unset string fields serialize as null, `total_cost_usd` is null when no
494
+ * entry had a known cost, and a per-entry `total_tokens` of zero falls back
495
+ * to input + output.
496
+ */
497
+ serialize(): UsageSummaryWire;
498
+ /** Clear all tracked entries. */
499
+ reset(): void;
500
+ }
501
+ /**
502
+ * Return the transport `usage` object, or null when there is nothing to
503
+ * report. Zero entries means no usage key at all per the contract, so callers
504
+ * must skip attaching `usage` on null.
505
+ */
506
+ declare function usageSummaryOrNull(tracker: CostTracker | undefined | null): UsageSummaryWire | null;
507
+ /**
508
+ * Attach usage to a synchronous 200 result body.
509
+ *
510
+ * The summary is merged as a sibling under the reserved
511
+ * {@link USAGE_ENVELOPE_KEY}; the control plane strips exactly that key back
512
+ * out, so a user result that legitimately contains its own "usage" key is
513
+ * never touched. Only plain-object results can carry usage this way —
514
+ * non-object results (arrays, scalars, class instances, null) are returned
515
+ * unchanged and their usage flows via the async status-callback path instead
516
+ * (the production path). No-usage trackers leave any result unchanged.
517
+ */
518
+ declare function attachUsageToSyncResult(result: unknown, tracker: CostTracker | undefined | null): unknown;
519
+
375
520
  interface ExecutionStatusUpdate {
376
521
  status?: string;
377
522
  result?: Record<string, any>;
@@ -531,6 +676,13 @@ declare class AgentFieldClient {
531
676
  durationMs?: number;
532
677
  completedAt?: string;
533
678
  reasoner?: string;
679
+ /**
680
+ * Serialized token/cost usage summary for the execution (the
681
+ * CostTracker wire contract). Omitted entirely when the execution
682
+ * recorded no usage. Attached on failure/timeout/cancelled terminal
683
+ * reports too — a reasoner may have consumed tokens before ending.
684
+ */
685
+ usage?: UsageSummaryWire;
534
686
  }, maxRetries?: number): Promise<boolean>;
535
687
  discoverCapabilities(options?: DiscoveryOptions): Promise<DiscoveryResult>;
536
688
  private mapDiscoveryResponse;
@@ -598,12 +750,21 @@ declare class ExecutionContext {
598
750
  readonly req: express.Request;
599
751
  readonly res: express.Response;
600
752
  readonly agent: Agent;
753
+ /**
754
+ * Per-execution LLM/harness usage accumulator. Each top-level execution
755
+ * binds a fresh tracker (isolated across concurrent executions via the
756
+ * AsyncLocalStorage this context lives in); nested local `agent.call()`
757
+ * executions inherit the parent's tracker so their usage rolls up into the
758
+ * parent's report.
759
+ */
760
+ readonly costTracker: CostTracker;
601
761
  constructor(params: {
602
762
  input: any;
603
763
  metadata: ExecutionMetadata;
604
764
  req: express.Request;
605
765
  res: express.Response;
606
766
  agent: Agent;
767
+ costTracker?: CostTracker;
607
768
  });
608
769
  get logger(): ExecutionLogger;
609
770
  static run<T>(ctx: ExecutionContext, fn: () => T): T;
@@ -838,103 +999,14 @@ declare function buildToolConfig(toolsParam: ToolsOption, agent: Agent): Promise
838
999
  config: ToolCallConfig;
839
1000
  needsLazyHydration: boolean;
840
1001
  }>;
841
- declare function executeToolCallLoop(agent: Agent, prompt: string, toolMap: ToolSet, config: ToolCallConfig, needsLazyHydration: boolean, buildModel: () => any, options?: AIRequestOptions): Promise<{
1002
+ declare function executeToolCallLoop(agent: Agent, prompt: string, toolMap: ToolSet, config: ToolCallConfig, needsLazyHydration: boolean, buildModel: () => any, options?: AIRequestOptions, modelChoice?: {
1003
+ provider?: string;
1004
+ modelName?: string;
1005
+ }): Promise<{
842
1006
  text: string;
843
1007
  trace: ToolCallTrace;
844
1008
  }>;
845
1009
 
846
- declare class ReasonerContext<TInput = any> {
847
- readonly input: TInput;
848
- readonly executionId: string;
849
- readonly runId?: string;
850
- readonly sessionId?: string;
851
- readonly actorId?: string;
852
- readonly workflowId?: string;
853
- readonly rootWorkflowId?: string;
854
- readonly parentExecutionId?: string;
855
- readonly reasonerId?: string;
856
- readonly callerDid?: string;
857
- readonly targetDid?: string;
858
- readonly agentNodeDid?: string;
859
- readonly req: express.Request;
860
- readonly res: express.Response;
861
- readonly agent: Agent;
862
- readonly logger: ExecutionLogger;
863
- readonly aiClient: AIClient;
864
- readonly memory: MemoryInterface;
865
- readonly workflow: WorkflowReporter;
866
- readonly did: DidInterface;
867
- /**
868
- * AbortSignal that fires when the control plane cancels this execution
869
- * (per-execution cancel, the bottom-up cancel-tree endpoint, or any
870
- * future source that flips the bus). Pass it through to `fetch`, the
871
- * @anthropic-ai/sdk, the openai SDK, or anywhere that accepts
872
- * `{ signal }` to short-circuit in-flight work mid-call. For pure-JS
873
- * CPU loops, check `ctx.signal.aborted` periodically and throw.
874
- */
875
- readonly signal: AbortSignal;
876
- constructor(params: {
877
- input: TInput;
878
- executionId: string;
879
- runId?: string;
880
- sessionId?: string;
881
- actorId?: string;
882
- workflowId?: string;
883
- rootWorkflowId?: string;
884
- parentExecutionId?: string;
885
- reasonerId?: string;
886
- callerDid?: string;
887
- targetDid?: string;
888
- agentNodeDid?: string;
889
- req: express.Request;
890
- res: express.Response;
891
- agent: Agent;
892
- logger: ExecutionLogger;
893
- aiClient: AIClient;
894
- memory: MemoryInterface;
895
- workflow: WorkflowReporter;
896
- did: DidInterface;
897
- signal?: AbortSignal;
898
- });
899
- ai<T>(prompt: string, options: AIRequestOptions & {
900
- schema: ZodSchema<T>;
901
- }): Promise<T>;
902
- ai(prompt: string, options?: AIToolRequestOptions): Promise<string>;
903
- /**
904
- * AI call with automatic tool calling via discover -> ai -> call loop.
905
- *
906
- * Discovers available capabilities, presents them as tools to the LLM,
907
- * dispatches tool calls via agent.call(), and iterates until a final response.
908
- *
909
- * @returns Object with `text` (final response) and `trace` (observability data).
910
- */
911
- aiWithTools(prompt: string, options?: AIToolRequestOptions): Promise<{
912
- text: string;
913
- trace: ToolCallTrace;
914
- }>;
915
- aiStream(prompt: string, options?: AIRequestOptions): Promise<AIStream>;
916
- call(target: string, input: any): Promise<any>;
917
- /**
918
- * Pause this execution for external approval / resumption.
919
- *
920
- * Transitions the execution to `waiting` on the control plane and blocks
921
- * until a decision arrives via the agent's approval webhook, or the timeout
922
- * elapses (returning `{ decision: 'expired' }`). The caller creates the
923
- * approval request on an external service first and passes its
924
- * `approvalRequestId`. Delegates to {@link Agent.pause}. See its docs for the
925
- * async-execution requirement that lets a pause outlive the dispatch ceiling.
926
- */
927
- pause(opts: {
928
- approvalRequestId: string;
929
- approvalRequestUrl?: string;
930
- expiresInHours?: number;
931
- timeoutMs?: number;
932
- }): Promise<ApprovalResult>;
933
- discover(options?: DiscoveryOptions): Promise<DiscoveryResult>;
934
- note(message: string, tags?: string[]): void;
935
- }
936
- declare function getCurrentContext<TInput = any>(): ReasonerContext<TInput> | undefined;
937
-
938
1010
  /**
939
1011
  * Trigger binding types for AgentField TypeScript SDK.
940
1012
  *
@@ -1039,6 +1111,113 @@ interface ScheduleTriggerBinding {
1039
1111
  spec: ScheduleTriggerSpec;
1040
1112
  }
1041
1113
 
1114
+ declare class ReasonerContext<TInput = any> {
1115
+ readonly input: TInput;
1116
+ readonly executionId: string;
1117
+ readonly runId?: string;
1118
+ readonly sessionId?: string;
1119
+ readonly actorId?: string;
1120
+ readonly workflowId?: string;
1121
+ readonly rootWorkflowId?: string;
1122
+ readonly parentExecutionId?: string;
1123
+ readonly reasonerId?: string;
1124
+ readonly callerDid?: string;
1125
+ readonly targetDid?: string;
1126
+ readonly agentNodeDid?: string;
1127
+ readonly req: express.Request;
1128
+ readonly res: express.Response;
1129
+ readonly agent: Agent;
1130
+ readonly logger: ExecutionLogger;
1131
+ readonly aiClient: AIClient;
1132
+ readonly memory: MemoryInterface;
1133
+ readonly workflow: WorkflowReporter;
1134
+ readonly did: DidInterface;
1135
+ /**
1136
+ * Per-execution token/cost usage accumulator. LLM calls made through
1137
+ * `ctx.ai()` / `ctx.aiWithTools()` and harness runs record into it
1138
+ * automatically; reasoner authors may also `record()` custom entries. Its
1139
+ * serialized summary is attached to the execution's terminal report.
1140
+ */
1141
+ readonly costTracker: CostTracker;
1142
+ /**
1143
+ * AbortSignal that fires when the control plane cancels this execution
1144
+ * (per-execution cancel, the bottom-up cancel-tree endpoint, or any
1145
+ * future source that flips the bus). Pass it through to `fetch`, the
1146
+ * @anthropic-ai/sdk, the openai SDK, or anywhere that accepts
1147
+ * `{ signal }` to short-circuit in-flight work mid-call. For pure-JS
1148
+ * CPU loops, check `ctx.signal.aborted` periodically and throw.
1149
+ */
1150
+ readonly signal: AbortSignal;
1151
+ /**
1152
+ * Trigger context populated when the reasoner was invoked by an inbound
1153
+ * webhook event or cron schedule. `undefined` for direct calls via
1154
+ * `app.call(...)` or HTTP POST without a dispatcher envelope.
1155
+ */
1156
+ readonly trigger?: TriggerContext;
1157
+ constructor(params: {
1158
+ input: TInput;
1159
+ executionId: string;
1160
+ runId?: string;
1161
+ sessionId?: string;
1162
+ actorId?: string;
1163
+ workflowId?: string;
1164
+ rootWorkflowId?: string;
1165
+ parentExecutionId?: string;
1166
+ reasonerId?: string;
1167
+ callerDid?: string;
1168
+ targetDid?: string;
1169
+ agentNodeDid?: string;
1170
+ req: express.Request;
1171
+ res: express.Response;
1172
+ agent: Agent;
1173
+ logger: ExecutionLogger;
1174
+ aiClient: AIClient;
1175
+ memory: MemoryInterface;
1176
+ workflow: WorkflowReporter;
1177
+ did: DidInterface;
1178
+ signal?: AbortSignal;
1179
+ costTracker?: CostTracker;
1180
+ trigger?: TriggerContext;
1181
+ });
1182
+ ai<T>(prompt: string, options: AIRequestOptions & {
1183
+ schema: ZodSchema<T>;
1184
+ }): Promise<T>;
1185
+ ai(prompt: string, options?: AIToolRequestOptions): Promise<string>;
1186
+ /**
1187
+ * AI call with automatic tool calling via discover -> ai -> call loop.
1188
+ *
1189
+ * Discovers available capabilities, presents them as tools to the LLM,
1190
+ * dispatches tool calls via agent.call(), and iterates until a final response.
1191
+ *
1192
+ * @returns Object with `text` (final response) and `trace` (observability data).
1193
+ */
1194
+ aiWithTools(prompt: string, options?: AIToolRequestOptions): Promise<{
1195
+ text: string;
1196
+ trace: ToolCallTrace;
1197
+ }>;
1198
+ aiStream(prompt: string, options?: AIRequestOptions): Promise<AIStream>;
1199
+ call(target: string, input: any): Promise<any>;
1200
+ /**
1201
+ * Pause this execution for external approval / resumption.
1202
+ *
1203
+ * Transitions the execution to `waiting` on the control plane and blocks
1204
+ * until a decision arrives via the agent's approval webhook, or the timeout
1205
+ * elapses (returning `{ decision: 'expired' }`). The caller creates the
1206
+ * approval request on an external service first and passes its
1207
+ * `approvalRequestId`. Delegates to {@link Agent.pause}. See its docs for the
1208
+ * async-execution requirement that lets a pause outlive the dispatch ceiling.
1209
+ */
1210
+ pause(opts: {
1211
+ approvalRequestId: string;
1212
+ approvalRequestUrl?: string;
1213
+ expiresInHours?: number;
1214
+ timeoutMs?: number;
1215
+ }): Promise<ApprovalResult>;
1216
+ discover(options?: DiscoveryOptions): Promise<DiscoveryResult>;
1217
+ note(message: string, tags?: string[]): void;
1218
+ }
1219
+ declare function getCurrentContext<TInput = any>(): ReasonerContext<TInput> | undefined;
1220
+
1042
1221
  interface ReasonerDefinition<TInput = any, TOutput = any> {
1043
1222
  name: string;
1044
1223
  handler: ReasonerHandler<TInput, TOutput>;
@@ -1177,6 +1356,14 @@ interface Metrics {
1177
1356
  totalCostUsd?: number;
1178
1357
  usage?: Record<string, unknown>;
1179
1358
  sessionId: string;
1359
+ /** Token counts parsed from the provider's result payload (best effort). */
1360
+ inputTokens?: number;
1361
+ outputTokens?: number;
1362
+ cacheReadTokens?: number;
1363
+ cacheCreationTokens?: number;
1364
+ totalTokens?: number;
1365
+ /** Model reported by the provider, when available. */
1366
+ model?: string;
1180
1367
  }
1181
1368
  interface RawResult {
1182
1369
  result?: string;
@@ -1195,6 +1382,14 @@ interface HarnessResult {
1195
1382
  durationMs: number;
1196
1383
  sessionId: string;
1197
1384
  messages: Array<Record<string, unknown>>;
1385
+ /** Token counts reported by the harness provider, when available. */
1386
+ inputTokens?: number;
1387
+ outputTokens?: number;
1388
+ cacheReadTokens?: number;
1389
+ cacheCreationTokens?: number;
1390
+ totalTokens?: number;
1391
+ /** Model reported by the harness provider, when available. */
1392
+ model?: string;
1198
1393
  readonly text: string;
1199
1394
  }
1200
1395
  declare function createHarnessResult(partial?: Partial<Omit<HarnessResult, 'text'>>): HarnessResult;
@@ -1552,6 +1747,33 @@ declare class Agent {
1552
1747
  */
1553
1748
  private resolvePublicUrl;
1554
1749
  reasoner<TInput = any, TOutput = any>(name: string, handler: ReasonerHandler<TInput, TOutput>, options?: ReasonerOptions): this;
1750
+ /**
1751
+ * Sugar for registering an event-triggered reasoner.
1752
+ *
1753
+ * Equivalent to:
1754
+ * ```ts
1755
+ * app.reasoner(name, handler, { triggers: [eventTrigger(spec)] });
1756
+ * ```
1757
+ *
1758
+ * The reasoner name defaults to `handler.name` when not provided.
1759
+ */
1760
+ onEvent<TInput = any, TOutput = any>(spec: Omit<EventTriggerSpec, 'codeOrigin'> & {
1761
+ name?: string;
1762
+ }, handler: ReasonerHandler<TInput, TOutput>, options?: Omit<ReasonerOptions, 'triggers'>): this;
1763
+ /**
1764
+ * Sugar for registering a schedule-triggered (cron) reasoner.
1765
+ *
1766
+ * Equivalent to:
1767
+ * ```ts
1768
+ * app.reasoner(name, handler, { triggers: [scheduleTrigger({ cron })] });
1769
+ * ```
1770
+ *
1771
+ * The reasoner name defaults to `handler.name` when not provided.
1772
+ */
1773
+ onSchedule<TInput = any, TOutput = any>(cron: string, handler: ReasonerHandler<TInput, TOutput>, options?: Omit<ReasonerOptions, 'triggers'> & {
1774
+ name?: string;
1775
+ timezone?: string;
1776
+ }): this;
1555
1777
  skill<TInput = any, TOutput = any>(name: string, handler: SkillHandler<TInput, TOutput>, options?: SkillOptions): this;
1556
1778
  includeRouter(router: AgentRouter): void;
1557
1779
  session(name: string, options: SessionOptions, handler: (session: RealtimeSession) => Promise<unknown> | unknown): this;
@@ -1566,6 +1788,15 @@ declare class Agent {
1566
1788
  getExecutionLogger(): ExecutionLogger;
1567
1789
  getHarnessRunner(): Promise<HarnessRunner>;
1568
1790
  harness(prompt: string, options?: HarnessOptions): Promise<HarnessResult>;
1791
+ /**
1792
+ * Record a harness run's token/cost usage into the current execution's
1793
+ * tracker. Mirrors the Python SDK's `_record_harness_usage`: a no-op when
1794
+ * the harness reported neither tokens nor cost (the common case for
1795
+ * providers that don't expose usage) so empty entries are never emitted;
1796
+ * cost is threaded even when tokens are unknown, and vice versa. Never
1797
+ * throws — usage capture is best-effort.
1798
+ */
1799
+ private recordHarnessUsage;
1569
1800
  getMemoryInterface(metadata?: ExecutionMetadata): MemoryInterface;
1570
1801
  getWorkflowReporter(metadata: ExecutionMetadata): WorkflowReporter;
1571
1802
  getDidInterface(metadata: ExecutionMetadata, defaultInput?: any, targetName?: string): DidInterface;
@@ -2574,4 +2805,165 @@ declare function scheduleTrigger(spec: ScheduleTriggerSpec): ScheduleTriggerBind
2574
2805
  */
2575
2806
  declare function triggerToPayload(trigger: TriggerBinding): Record<string, unknown>;
2576
2807
 
2577
- export { ACTIVE_STATUSES, AIClient, type AIConfig, type AIEmbeddingOptions, type AIRequestOptions, type AIStream, type AIToolRequestOptions, Agent, type AgentCapability, type AgentConfig, type AgentHandler, AgentRouter, type AgentRouterOptions, type AgentState, ApprovalClient, type ApprovalDecision, type ApprovalRequestResponse, ApprovalResult, type ApprovalStatusResponse, Audio, type AudioOutput, type AudioRequest, type AuditTrailExport, type AuditTrailFilters, type Awaitable, CANONICAL_STATUSES, type CompactCapability, type CompactDiscoveryResponse, DIDAuthenticator, type DIDIdentity, type DIDIdentityPackage, type DIDRegistrationRequest, type DIDRegistrationResponse, type DeploymentType, DidClient, DidInterface, DidManager, type DidResolver, type DiscoveryFormat, type DiscoveryOptions, type DiscoveryPagination, type DiscoveryResponse, type DiscoveryResult, type EventTriggerBinding, type EventTriggerSpec, ExecutionContext, type ExecutionCredential, type ExecutionLogAttributes, type ExecutionLogBatchPayload, type ExecutionLogContext, type ExecutionLogEmitOptions, type ExecutionLogEntry, type ExecutionLogLevel, type ExecutionLogTransport, type ExecutionLogTransportPayload, type ExecutionLogWireEntry, ExecutionLogger, type ExecutionLoggerOptions, type ExecutionMetadata, ExecutionStatus, type ExecutionStatusValue, File, type FileOutput, type GenerateCredentialOptions, type GenerateCredentialParams, HEADER_CALLER_DID, HEADER_DID_NONCE, HEADER_DID_SIGNATURE, HEADER_DID_TIMESTAMP, type HarnessConfig, type HarnessOptions, type HarnessProvider, type HarnessResult, HarnessRunner, type HealthStatus, Image, type ImageOutput, type ImageRequest, JWE_ALG, JWE_ENC, KEY_AGREEMENT_TYPE, type MediaProvider, MediaProviderError, type MediaResponse, MediaRouter, type MemoryChangeEvent, MemoryClient, MemoryClientBase, type MemoryConfig, MemoryEventClient, type MemoryEventHandler, type MemoryEventHistoryOptions, MemoryInterface, type MemoryRequestMetadata, type MemoryRequestOptions, type MemoryScope, type MemoryWatchHandler, type Metrics, type MultimodalContent, MultimodalResponse, OpenRouterMediaProvider, type OpenRouterMediaProviderOptions, PauseClock, PauseManager, type Payload, PayloadEncryptionError, RateLimitError, type RateLimiterOptions, type RawExecutionContext, type RawResult, RealtimeSession, type ReasonerCapability, ReasonerContext, type ReasonerDefinition, type ReasonerHandler, type ReasonerOptions, type RequestApprovalPayload, SUPPORTED_PROVIDERS, SUPPORTED_SESSION_TRANSPORTS, type ScheduleTriggerBinding, type ScheduleTriggerSpec, type ServerlessAdapter, type ServerlessEvent, type ServerlessResponse, type SessionDefinition, type SessionOptions, type SessionProvider, type SessionTransport, type SessionTransportCapability, SessionTransportError, type SessionTurn, type SkillCapability, SkillContext, type SkillDefinition, type SkillHandler, type SkillOptions, StatelessRateLimiter, TERMINAL_STATUSES, Text, type ToolCallConfig, type ToolCallRecord, type ToolCallTrace, type ToolsOption, type TriggerBinding, type TriggerContext, type VectorSearchOptions, type VectorSearchResult, Video, type VideoFrameImage, type VideoInputReference, type VideoRequest, type WaitForApprovalOptions, type WorkflowCredential, type WorkflowMetadata, type WorkflowProgressOptions, WorkflowReporter, type ZodSchema, audioFromBase64, audioFromBuffer, audioFromFile, audioFromUrl, buildProvider, buildSessionDefinition, buildToolConfig, capabilitiesToTools, capabilityToMetadataTool, capabilityToTool, createExecutionLogger, createHarnessResult, createMetrics, createMultimodalResponse, createRawResult, decrypt, decryptToString, encryptForDid, encryptToJwk, eventTrigger, executeToolCallLoop, extractKeyAgreementJwk, fileFromBase64, fileFromBuffer, fileFromPath, fileFromUrl, generateX25519KeyPair, getCurrentContext, getCurrentSkillContext, imageFromBase64, imageFromBuffer, imageFromFile, imageFromUrl, installApprovalWebhookRoute, isActive, isExecutionLogBatchPayload, isTerminal, normalizeExecutionLogEntry, normalizeSessionTransportValue, normalizeStatus, scheduleTrigger, serializeExecutionLogEntry, text, triggerToPayload, validateSessionTransport, videoFromBase64, videoFromBuffer, videoFromFile, videoFromUrl };
2808
+ /**
2809
+ * Trigger dispatch envelope detection and TriggerContext construction.
2810
+ *
2811
+ * When the control plane dispatches a webhook event to a reasoner, it wraps
2812
+ * the payload in an envelope: `{ event: <payload>, _meta: <trigger metadata> }`.
2813
+ * This module detects that shape, unwraps the event, constructs a TriggerContext,
2814
+ * and applies the binding's `transform` if one is declared.
2815
+ *
2816
+ * Direct calls (no envelope) pass through unchanged — the handler receives
2817
+ * its input as before.
2818
+ *
2819
+ * @module triggers/dispatch
2820
+ */
2821
+
2822
+ /**
2823
+ * Shape of the dispatcher's envelope sent by the control plane for
2824
+ * webhook-triggered executions.
2825
+ */
2826
+ interface TriggerEnvelope {
2827
+ event: Record<string, unknown>;
2828
+ _meta: {
2829
+ trigger_id: string;
2830
+ source: string;
2831
+ event_type: string;
2832
+ event_id: string;
2833
+ idempotency_key: string;
2834
+ received_at: string;
2835
+ vc_id?: string;
2836
+ };
2837
+ }
2838
+ /**
2839
+ * Result of envelope detection and unwrap.
2840
+ */
2841
+ interface UnwrapResult {
2842
+ /** The unwrapped input (event payload or original input for direct calls). */
2843
+ input: unknown;
2844
+ /** TriggerContext if this was a trigger dispatch; undefined for direct calls. */
2845
+ triggerContext?: TriggerContext;
2846
+ }
2847
+ /**
2848
+ * Detect whether a request body is a dispatcher trigger envelope.
2849
+ *
2850
+ * The envelope shape is `{ event: ..., _meta: { trigger_id, source, ... } }`.
2851
+ * Only objects with both `event` and `_meta` keys (where `_meta` contains
2852
+ * `trigger_id`) are considered envelopes.
2853
+ */
2854
+ declare function isTriggerEnvelope(body: unknown): body is TriggerEnvelope;
2855
+ /**
2856
+ * Unwrap a trigger envelope (if present) and construct TriggerContext.
2857
+ *
2858
+ * For trigger dispatches: extracts the event payload and builds a typed
2859
+ * TriggerContext from `_meta`. For direct calls: returns the body unchanged
2860
+ * with `triggerContext: undefined`.
2861
+ */
2862
+ declare function unwrapEnvelope(body: unknown): UnwrapResult;
2863
+ /**
2864
+ * Apply the matching binding's `transform` function to the unwrapped event.
2865
+ *
2866
+ * Matching logic (mirrors Python SDK's `_apply_trigger_transform`):
2867
+ * 1. Find bindings where `binding.spec.source === triggerContext.source`
2868
+ * 2. For event bindings with non-empty `types`, check prefix match against
2869
+ * `triggerContext.eventType`
2870
+ * 3. Most specific match (non-empty types) wins over catch-all (empty types)
2871
+ * 4. Apply `transform` if the matched binding declares one
2872
+ *
2873
+ * Returns the (possibly transformed) input.
2874
+ */
2875
+ declare function applyTriggerTransform(triggerContext: TriggerContext, bindings: TriggerBinding[], input: unknown): unknown;
2876
+
2877
+ /**
2878
+ * Testing helpers for reasoners that handle webhook triggers.
2879
+ *
2880
+ * The standard SDK runtime delivers trigger events via the agent's HTTP
2881
+ * endpoint — your reasoner sees `ctx.trigger` populated and (when `transform`
2882
+ * is set) the unwrapped, transformed input. For unit tests you want the same
2883
+ * shape without spinning up a control plane, an HTTP server, or a real
2884
+ * provider. `simulateTrigger` gives you that: it crafts the `TriggerContext`
2885
+ * the agent runtime would have produced, applies any matching `transform`
2886
+ * from the reasoner's declared bindings, and invokes the handler directly
2887
+ * with a minimal ReasonerContext-like object. No HTTP, no workflow
2888
+ * registration, no VC mint.
2889
+ *
2890
+ * @module triggers/testing
2891
+ */
2892
+
2893
+ /**
2894
+ * Options for `simulateTrigger`.
2895
+ */
2896
+ interface SimulateTriggerOptions {
2897
+ /** Provider source name (e.g. "stripe", "github", "cron"). */
2898
+ source: string;
2899
+ /** Inbound event body. Defaults to `{}`. */
2900
+ body?: Record<string, unknown>;
2901
+ /** Provider's event type (e.g. "payment_intent.succeeded"). Defaults to "". */
2902
+ eventType?: string;
2903
+ /** Override the generated event ID. */
2904
+ eventId?: string;
2905
+ /** Override the generated idempotency key. */
2906
+ idempotencyKey?: string;
2907
+ /** Override the generated trigger ID. */
2908
+ triggerId?: string;
2909
+ /** Override the received-at timestamp. Defaults to `new Date()`. */
2910
+ receivedAt?: Date;
2911
+ /** Optional VC ID. */
2912
+ vcId?: string;
2913
+ /**
2914
+ * Trigger bindings for the handler. Used to find the matching binding's
2915
+ * `transform`. If not provided, the body is passed through as-is.
2916
+ */
2917
+ bindings?: TriggerBinding[];
2918
+ }
2919
+ /**
2920
+ * Options for `simulateSchedule`.
2921
+ */
2922
+ interface SimulateScheduleOptions {
2923
+ /** Cron expression (for test introspection). */
2924
+ cron?: string;
2925
+ /** Override the received-at timestamp. Defaults to `new Date()`. */
2926
+ receivedAt?: Date;
2927
+ /** Trigger bindings for the handler. */
2928
+ bindings?: TriggerBinding[];
2929
+ }
2930
+ /**
2931
+ * Minimal execution context surface exposed as `ctx` in simulate tests.
2932
+ * Only carries the bits a webhook reasoner is likely to read.
2933
+ */
2934
+ interface SimulatedContext<TInput = unknown> {
2935
+ input: TInput;
2936
+ trigger: TriggerContext;
2937
+ executionId: string;
2938
+ }
2939
+ /**
2940
+ * Simulate a trigger dispatch and invoke the handler.
2941
+ *
2942
+ * Builds a synthetic `TriggerContext`, optionally applies the matched
2943
+ * binding's `transform`, and calls the handler with a minimal context
2944
+ * object that mirrors what the real dispatch path produces.
2945
+ *
2946
+ * @param handler - Function accepting `(ctx: { input, trigger, executionId })`.
2947
+ * The same shape a `ReasonerHandler` receives, but trimmed to the fields
2948
+ * relevant for trigger-driven logic.
2949
+ * @param options - Trigger simulation options.
2950
+ * @returns Whatever the handler returns (awaits async handlers transparently).
2951
+ */
2952
+ declare function simulateTrigger<R>(handler: (ctx: SimulatedContext) => R | Promise<R>, options: SimulateTriggerOptions): Promise<R>;
2953
+ /**
2954
+ * Simulate a schedule (cron) trigger dispatch.
2955
+ *
2956
+ * Convenience wrapper around `simulateTrigger` for cron-triggered reasoners.
2957
+ * Passes an empty body and `source: 'cron'`, `eventType: 'tick'`.
2958
+ */
2959
+ declare function simulateSchedule<R>(handler: (ctx: SimulatedContext) => R | Promise<R>, options?: SimulateScheduleOptions): Promise<R>;
2960
+ /**
2961
+ * Load a captured provider payload from the SDK fixture library.
2962
+ *
2963
+ * Fixtures live at `src/triggers/fixtures/<source>.json` relative to the
2964
+ * package root. Returns a parsed object — each call re-reads from disk so
2965
+ * tests can mutate freely.
2966
+ */
2967
+ declare function loadFixture(source: string): Record<string, unknown>;
2968
+
2969
+ export { ACTIVE_STATUSES, AIClient, type AIConfig, type AIEmbeddingOptions, type AIRequestOptions, type AIStream, type AIToolRequestOptions, Agent, type AgentCapability, type AgentConfig, type AgentHandler, AgentRouter, type AgentRouterOptions, type AgentState, ApprovalClient, type ApprovalDecision, type ApprovalRequestResponse, ApprovalResult, type ApprovalStatusResponse, Audio, type AudioOutput, type AudioRequest, type AuditTrailExport, type AuditTrailFilters, type Awaitable, CANONICAL_STATUSES, type CompactCapability, type CompactDiscoveryResponse, type CostEntry, type CostEntryInit, CostTracker, DIDAuthenticator, type DIDIdentity, type DIDIdentityPackage, type DIDRegistrationRequest, type DIDRegistrationResponse, type DeploymentType, DidClient, DidInterface, DidManager, type DidResolver, type DiscoveryFormat, type DiscoveryOptions, type DiscoveryPagination, type DiscoveryResponse, type DiscoveryResult, type EventTriggerBinding, type EventTriggerSpec, ExecutionContext, type ExecutionCredential, type ExecutionLogAttributes, type ExecutionLogBatchPayload, type ExecutionLogContext, type ExecutionLogEmitOptions, type ExecutionLogEntry, type ExecutionLogLevel, type ExecutionLogTransport, type ExecutionLogTransportPayload, type ExecutionLogWireEntry, ExecutionLogger, type ExecutionLoggerOptions, type ExecutionMetadata, ExecutionStatus, type ExecutionStatusValue, File, type FileOutput, type GenerateCredentialOptions, type GenerateCredentialParams, HEADER_CALLER_DID, HEADER_DID_NONCE, HEADER_DID_SIGNATURE, HEADER_DID_TIMESTAMP, type HarnessConfig, type HarnessOptions, type HarnessProvider, type HarnessResult, HarnessRunner, type HealthStatus, Image, type ImageOutput, type ImageRequest, JWE_ALG, JWE_ENC, KEY_AGREEMENT_TYPE, type MediaProvider, MediaProviderError, type MediaResponse, MediaRouter, type MemoryChangeEvent, MemoryClient, MemoryClientBase, type MemoryConfig, MemoryEventClient, type MemoryEventHandler, type MemoryEventHistoryOptions, MemoryInterface, type MemoryRequestMetadata, type MemoryRequestOptions, type MemoryScope, type MemoryWatchHandler, type Metrics, type MultimodalContent, MultimodalResponse, OpenRouterMediaProvider, type OpenRouterMediaProviderOptions, PauseClock, PauseManager, type Payload, PayloadEncryptionError, RateLimitError, type RateLimiterOptions, type RawExecutionContext, type RawResult, RealtimeSession, type ReasonerCapability, ReasonerContext, type ReasonerDefinition, type ReasonerHandler, type ReasonerOptions, type RequestApprovalPayload, SUPPORTED_PROVIDERS, SUPPORTED_SESSION_TRANSPORTS, type ScheduleTriggerBinding, type ScheduleTriggerSpec, type ServerlessAdapter, type ServerlessEvent, type ServerlessResponse, type SessionDefinition, type SessionOptions, type SessionProvider, type SessionTransport, type SessionTransportCapability, SessionTransportError, type SessionTurn, type SimulateScheduleOptions, type SimulateTriggerOptions, type SimulatedContext, type SkillCapability, SkillContext, type SkillDefinition, type SkillHandler, type SkillOptions, StatelessRateLimiter, TERMINAL_STATUSES, Text, type ToolCallConfig, type ToolCallRecord, type ToolCallTrace, type ToolsOption, type TriggerBinding, type TriggerContext, type TriggerEnvelope, USAGE_ENVELOPE_KEY, type UnwrapResult, type UsageEntryWire, type UsageSummaryWire, type VectorSearchOptions, type VectorSearchResult, Video, type VideoFrameImage, type VideoInputReference, type VideoRequest, type WaitForApprovalOptions, type WorkflowCredential, type WorkflowMetadata, type WorkflowProgressOptions, WorkflowReporter, type ZodSchema, applyTriggerTransform, attachUsageToSyncResult, audioFromBase64, audioFromBuffer, audioFromFile, audioFromUrl, buildProvider, buildSessionDefinition, buildToolConfig, capabilitiesToTools, capabilityToMetadataTool, capabilityToTool, createExecutionLogger, createHarnessResult, createMetrics, createMultimodalResponse, createRawResult, decrypt, decryptToString, deriveProvider, encryptForDid, encryptToJwk, eventTrigger, executeToolCallLoop, extractKeyAgreementJwk, fileFromBase64, fileFromBuffer, fileFromPath, fileFromUrl, generateX25519KeyPair, getCurrentContext, getCurrentSkillContext, imageFromBase64, imageFromBuffer, imageFromFile, imageFromUrl, installApprovalWebhookRoute, isActive, isExecutionLogBatchPayload, isTerminal, isTriggerEnvelope, loadFixture, normalizeExecutionLogEntry, normalizeSessionTransportValue, normalizeStatus, scheduleTrigger, serializeExecutionLogEntry, simulateSchedule, simulateTrigger, text, triggerToPayload, unwrapEnvelope, usageSummaryOrNull, validateSessionTransport, videoFromBase64, videoFromBuffer, videoFromFile, videoFromUrl };