eve 0.47.3 → 0.47.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.
Files changed (178) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/bin/eve.js +4 -0
  3. package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
  4. package/dist/src/compiled/.vendor-stamp.json +1 -1
  5. package/dist/src/compiled/@opentelemetry/api/index.d.ts +37 -0
  6. package/dist/src/compiled/@vercel/otel/index.d.ts +11 -0
  7. package/dist/src/compiler/extension-compatibility.d.ts +7 -5
  8. package/dist/src/compiler/extension-compatibility.js +1 -1
  9. package/dist/src/compiler/manifest.d.ts +14 -2
  10. package/dist/src/compiler/manifest.js +1 -1
  11. package/dist/src/compiler/normalize-connection.d.ts +9 -2
  12. package/dist/src/compiler/normalize-connection.js +1 -1
  13. package/dist/src/compiler/normalize-manifest.js +1 -1
  14. package/dist/src/compiler/validate-artifact.js +1 -1
  15. package/dist/src/context/dynamic-connection-lifecycle.d.ts +9 -0
  16. package/dist/src/context/dynamic-connection-lifecycle.js +1 -0
  17. package/dist/src/context/keys.d.ts +3 -1
  18. package/dist/src/context/memory-tools.js +1 -1
  19. package/dist/src/context/providers/connection.js +1 -1
  20. package/dist/src/dynamic/definition.d.ts +6 -3
  21. package/dist/src/dynamic/definition.js +1 -1
  22. package/dist/src/execution/authorization-callback-match.js +1 -1
  23. package/dist/src/execution/cancelled-turn-message.d.ts +2 -0
  24. package/dist/src/execution/cancelled-turn-message.js +1 -0
  25. package/dist/src/execution/dynamic-connections.d.ts +9 -0
  26. package/dist/src/execution/dynamic-connections.js +1 -0
  27. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  28. package/dist/src/execution/node-step.d.ts +2 -0
  29. package/dist/src/execution/node-step.js +1 -1
  30. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  31. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  32. package/dist/src/execution/tools/connection-search.js +2 -2
  33. package/dist/src/execution/tools/load-skill.js +1 -1
  34. package/dist/src/execution/tools/subagent/local.js +1 -1
  35. package/dist/src/execution/turn-workflow.js +1 -1
  36. package/dist/src/execution/workflow-runtime.js +1 -1
  37. package/dist/src/execution/workflow-steps.js +1 -1
  38. package/dist/src/execution/workflow-trace-context.d.ts +3 -6
  39. package/dist/src/execution/workflow-trace-context.js +1 -1
  40. package/dist/src/harness/authorization.d.ts +11 -4
  41. package/dist/src/harness/authorization.js +1 -1
  42. package/dist/src/harness/inline-tool-authorization.d.ts +13 -1
  43. package/dist/src/harness/inline-tool-authorization.js +1 -1
  44. package/dist/src/harness/model-call-error.js +1 -1
  45. package/dist/src/harness/semantic-errors/rule.d.ts +5 -2
  46. package/dist/src/harness/semantic-errors/rules/gateway.js +1 -1
  47. package/dist/src/harness/tool-loop.js +2 -2
  48. package/dist/src/harness/turn-tag-state.d.ts +1 -1
  49. package/dist/src/harness/types.d.ts +2 -2
  50. package/dist/src/{harness → instrumentation}/ai-sdk-hook-bridge.d.ts +1 -1
  51. package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -0
  52. package/dist/src/{harness/channel-delivery-instrumentation.d.ts → instrumentation/channel-delivery.d.ts} +5 -7
  53. package/dist/src/instrumentation/channel-delivery.js +1 -0
  54. package/dist/src/{harness/instrumentation → instrumentation}/config.d.ts +0 -10
  55. package/dist/src/instrumentation/config.js +1 -0
  56. package/dist/src/{harness/instrumentation → instrumentation}/content-policy.d.ts +1 -1
  57. package/dist/src/instrumentation/content-policy.js +1 -0
  58. package/dist/src/{harness/instrumentation → instrumentation}/content.d.ts +1 -1
  59. package/dist/src/{harness/instrumentation → instrumentation}/dispatch.d.ts +1 -1
  60. package/dist/src/instrumentation/dispatch.js +1 -0
  61. package/dist/src/{harness/instrumentation → instrumentation}/lifecycle.d.ts +26 -33
  62. package/dist/src/instrumentation/lifecycle.js +1 -0
  63. package/dist/src/{harness/instrumentation → instrumentation}/native-events.d.ts +1 -1
  64. package/dist/src/instrumentation/native-events.js +1 -0
  65. package/dist/src/{harness → instrumentation}/parent-lineage.d.ts +1 -1
  66. package/dist/src/{harness → instrumentation}/prepare-trace-context.d.ts +8 -5
  67. package/dist/src/instrumentation/prepare-trace-context.js +1 -0
  68. package/dist/src/instrumentation/provider.d.ts +13 -9
  69. package/dist/src/{harness/instrumentation → instrumentation}/providers.d.ts +1 -1
  70. package/dist/src/instrumentation/providers.js +1 -0
  71. package/dist/src/{harness/instrumentation → instrumentation}/runtime-context.d.ts +13 -2
  72. package/dist/src/instrumentation/runtime-context.js +1 -0
  73. package/dist/src/instrumentation/runtime.d.ts +100 -0
  74. package/dist/src/instrumentation/runtime.js +1 -0
  75. package/dist/src/{harness/instrumentation → instrumentation}/state.d.ts +2 -11
  76. package/dist/src/internal/application/compiled-artifacts.js +3 -3
  77. package/dist/src/internal/application/package.js +1 -1
  78. package/dist/src/internal/authored-definition/connection.js +1 -1
  79. package/dist/src/internal/instrumentation.d.ts +1 -1
  80. package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +4 -6
  81. package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
  82. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  83. package/dist/src/public/channels/slack/defaults.js +6 -3
  84. package/dist/src/public/channels/slack/index.d.ts +1 -1
  85. package/dist/src/public/channels/slack/interactions.d.ts +8 -5
  86. package/dist/src/public/channels/slack/interactions.js +1 -1
  87. package/dist/src/public/channels/slack/slackChannel.d.ts +66 -1
  88. package/dist/src/public/channels/slack/slash-command.d.ts +9 -0
  89. package/dist/src/public/channels/slack/slash-command.js +1 -0
  90. package/dist/src/public/connections/index.d.ts +2 -0
  91. package/dist/src/public/connections/index.js +1 -1
  92. package/dist/src/public/definitions/connections/dynamic.d.ts +23 -0
  93. package/dist/src/public/definitions/connections/dynamic.js +1 -0
  94. package/dist/src/public/definitions/connections/mcp.d.ts +8 -0
  95. package/dist/src/public/definitions/connections/openapi.d.ts +8 -0
  96. package/dist/src/public/definitions/connections/protocol.d.ts +6 -0
  97. package/dist/src/public/definitions/connections/protocol.js +1 -1
  98. package/dist/src/runtime/connections/authorization-tokens.d.ts +11 -10
  99. package/dist/src/runtime/connections/instance-identity.d.ts +12 -0
  100. package/dist/src/runtime/connections/instance-identity.js +1 -0
  101. package/dist/src/runtime/connections/mcp-client.js +1 -1
  102. package/dist/src/runtime/connections/registry.d.ts +2 -0
  103. package/dist/src/runtime/connections/registry.js +1 -1
  104. package/dist/src/runtime/connections/scoped-authorization.d.ts +10 -6
  105. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  106. package/dist/src/runtime/resolve-agent.js +1 -1
  107. package/dist/src/runtime/resolve-connection.d.ts +5 -0
  108. package/dist/src/runtime/resolve-connection.js +1 -1
  109. package/dist/src/runtime/resolve-dynamic-connection.d.ts +5 -0
  110. package/dist/src/runtime/resolve-dynamic-connection.js +1 -0
  111. package/dist/src/runtime/types.d.ts +11 -0
  112. package/dist/src/setup/flows/registry.js +1 -1
  113. package/dist/src/setup/scaffold/create/project.js +1 -1
  114. package/dist/src/shared/trace-policy.d.ts +20 -0
  115. package/dist/src/shared/trace-policy.js +1 -0
  116. package/dist/src/tracing/agent-action-instrumentation.d.ts +1 -1
  117. package/dist/src/tracing/agent-action-instrumentation.js +1 -1
  118. package/dist/src/tracing/agent-approval-instrumentation.d.ts +1 -1
  119. package/dist/src/tracing/agent-channel-delivery-instrumentation.d.ts +1 -1
  120. package/dist/src/tracing/agent-channel-delivery-instrumentation.js +1 -1
  121. package/dist/src/tracing/agent-otel-provider.d.ts +2 -2
  122. package/dist/src/tracing/agent-otel-provider.js +2 -2
  123. package/dist/src/tracing/agent-otel-runtime-context.d.ts +5 -0
  124. package/dist/src/tracing/agent-otel-runtime-context.js +1 -0
  125. package/dist/src/tracing/agent-otel-session-context.d.ts +1 -1
  126. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  127. package/dist/src/tracing/agent-otel-usage.d.ts +4 -2
  128. package/dist/src/tracing/agent-otel-usage.js +1 -1
  129. package/dist/src/tracing/agent-span-id-generator.d.ts +1 -1
  130. package/dist/src/tracing/agent-tool-instrumentation.d.ts +1 -1
  131. package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
  132. package/dist/src/tracing/agent-trace-context-store.d.ts +3 -0
  133. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  134. package/dist/src/tracing/agent-trace-context.d.ts +3 -0
  135. package/dist/src/tracing/agent-trace-context.js +1 -0
  136. package/dist/src/tracing/agent-trace-state.d.ts +8 -1
  137. package/dist/src/tracing/agent-trace-state.js +1 -1
  138. package/dist/src/tracing/install-instrumentation-runtime.d.ts +3 -2
  139. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  140. package/dist/src/tracing/local-instrumentation-runtime.d.ts +1 -1
  141. package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
  142. package/dist/src/tracing/local-trace-reader.d.ts +1 -0
  143. package/dist/src/tracing/local-trace-reader.js +1 -1
  144. package/dist/src/tracing/otel-declaration.d.ts +13 -16
  145. package/dist/src/tracing/otel-declaration.js +1 -1
  146. package/dist/src/tracing/otel-registration.js +1 -1
  147. package/dist/src/tracing/sampled-trace.d.ts +1 -14
  148. package/dist/src/tracing/sampled-trace.js +1 -1
  149. package/docs/channels/slack.mdx +25 -5
  150. package/docs/connections/overview.mdx +46 -2
  151. package/docs/extensions.md +2 -2
  152. package/docs/getting-started.mdx +1 -1
  153. package/docs/guides/dynamic-capabilities.md +91 -5
  154. package/docs/memory.md +7 -4
  155. package/docs/reference/cli.md +4 -4
  156. package/docs/reference/typescript-api.md +32 -23
  157. package/package.json +1 -1
  158. package/dist/src/execution/subagent-usage-span.d.ts +0 -9
  159. package/dist/src/execution/subagent-usage-span.js +0 -1
  160. package/dist/src/harness/ai-sdk-hook-bridge.js +0 -1
  161. package/dist/src/harness/channel-delivery-instrumentation.js +0 -1
  162. package/dist/src/harness/instrumentation/config.js +0 -1
  163. package/dist/src/harness/instrumentation/content-policy.js +0 -1
  164. package/dist/src/harness/instrumentation/dispatch.js +0 -1
  165. package/dist/src/harness/instrumentation/lifecycle.js +0 -1
  166. package/dist/src/harness/instrumentation/native-events.js +0 -1
  167. package/dist/src/harness/instrumentation/providers.js +0 -1
  168. package/dist/src/harness/instrumentation/runtime-context.js +0 -1
  169. package/dist/src/harness/instrumentation/runtime.d.ts +0 -21
  170. package/dist/src/harness/instrumentation/runtime.js +0 -1
  171. package/dist/src/harness/prepare-trace-context.js +0 -1
  172. /package/dist/src/{harness → instrumentation}/ai-sdk-telemetry.d.ts +0 -0
  173. /package/dist/src/{harness → instrumentation}/ai-sdk-telemetry.js +0 -0
  174. /package/dist/src/{harness/instrumentation → instrumentation}/content.js +0 -0
  175. /package/dist/src/{harness → instrumentation}/parent-lineage.js +0 -0
  176. /package/dist/src/{harness/instrumentation → instrumentation}/setup-context.d.ts +0 -0
  177. /package/dist/src/{harness/instrumentation → instrumentation}/setup-context.js +0 -0
  178. /package/dist/src/{harness/instrumentation → instrumentation}/state.js +0 -0
@@ -1,7 +1,8 @@
1
- import type { InstrumentationStateSlot } from "#harness/instrumentation/state.js";
1
+ import type { InstrumentationStateSlot } from "#instrumentation/state.js";
2
2
  import type { RuntimeTraceContext } from "#protocol/message.js";
3
3
  import type { ChannelAudience } from "#shared/channel-audience.js";
4
4
  import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
5
+ import type { InstrumentationCapture, TraceCaptureContext, TraceCapturePolicy } from "#shared/trace-policy.js";
5
6
  /**
6
7
  * Stable eve identity for one actual model attempt.
7
8
  *
@@ -93,22 +94,6 @@ export type InstrumentationActionOutput = {
93
94
  readonly type: "error";
94
95
  readonly error?: unknown;
95
96
  };
96
- /**
97
- * How much of an event a provider is handed.
98
- *
99
- * `"metadata"` — the default — is structure, identity, usage, and timing: every
100
- * field except what the conversation actually said. `"content"` adds the
101
- * prompt, the response, tool arguments, and tool results.
102
- *
103
- * Declared per provider rather than per process, because two consumers of one
104
- * bus rarely have the same retention path. Content is built at all only when
105
- * some provider asked for it, and a provider that did not ask never receives
106
- * it — which is the same guarantee a destination that declines content gets,
107
- * one layer lower and without an OpenTelemetry pipeline to route it through.
108
- * OpenTelemetry trace policy is applied only inside the OTel provider and does
109
- * not narrow this provider-level projection.
110
- */
111
- export type InstrumentationCapture = "content" | "metadata";
112
97
  /**
113
98
  * Every event carries an `idempotencyKey` naming the operation it is about: a
114
99
  * start and its terminal share one, and two operations never collide.
@@ -154,13 +139,13 @@ interface InstrumentationChannelDeliveryScope {
154
139
  export interface InstrumentationChannelDeliveryStartedEvent extends InstrumentationChannelDeliveryScope {
155
140
  readonly parentTraceContext?: InstrumentationTraceContext;
156
141
  readonly type: "channel.delivery.started";
157
- /** Content. Absent unless this provider declared `capture: "content"`. */
142
+ /** Content. Absent unless this provider's trace policy records this direction. */
158
143
  readonly input?: InstrumentationChannelDeliveryInput;
159
144
  }
160
145
  export type InstrumentationChannelDeliveryOutcome = "cancelled" | "completed" | "failed";
161
146
  export interface InstrumentationChannelDeliveryTerminalEvent extends InstrumentationChannelDeliveryScope {
162
147
  readonly type: "channel.delivery.cancelled" | "channel.delivery.completed" | "channel.delivery.failed";
163
- /** Content. Absent unless this provider declared `capture: "content"`. */
148
+ /** Content. Absent unless this provider's trace policy records this direction. */
164
149
  readonly error?: unknown;
165
150
  readonly errorCode?: string;
166
151
  readonly outcome: InstrumentationChannelDeliveryOutcome;
@@ -194,7 +179,7 @@ export interface InstrumentationInputRequestedEvent {
194
179
  };
195
180
  readonly idempotencyKey: string;
196
181
  readonly kind: InstrumentationInputKind;
197
- /** Content. Absent unless this provider declared `capture: "content"`. */
182
+ /** Content. Absent unless this provider's trace policy records this direction. */
198
183
  readonly request?: InstrumentationInputRequest;
199
184
  readonly requestId: string;
200
185
  readonly scope: InstrumentationAttemptScope;
@@ -206,7 +191,7 @@ export interface InstrumentationInputResolvedEvent {
206
191
  readonly kind: InstrumentationInputKind;
207
192
  readonly outcome: InstrumentationInputOutcome;
208
193
  readonly requestId: string;
209
- /** Content. Absent unless this provider declared `capture: "content"`. */
194
+ /** Content. Absent unless this provider's trace policy records this direction. */
210
195
  readonly response?: InstrumentationInputResponse;
211
196
  readonly scope: InstrumentationAttemptScope;
212
197
  }
@@ -260,7 +245,7 @@ export interface InstrumentationSessionSettledEvent {
260
245
  }
261
246
  export interface InstrumentationSessionFailedEvent {
262
247
  readonly type: "session.failed";
263
- /** Content. Absent unless this provider declared `capture: "content"`. */
248
+ /** Content. Absent unless this provider's trace policy records this direction. */
264
249
  readonly error?: unknown;
265
250
  readonly idempotencyKey: string;
266
251
  readonly sessionId: string;
@@ -269,6 +254,7 @@ export interface InstrumentationSessionFailedEvent {
269
254
  export type InstrumentationSessionTransitionEvent = InstrumentationSessionSettledEvent | InstrumentationSessionFailedEvent;
270
255
  export interface InstrumentationTurnStartedEvent {
271
256
  readonly type: "turn.started";
257
+ readonly agentName?: string;
272
258
  readonly idempotencyKey: string;
273
259
  readonly parentLineage?: InstrumentationParentLineage;
274
260
  readonly parentTraceContext?: InstrumentationTraceContext;
@@ -292,7 +278,7 @@ export interface InstrumentationTurnSettledEvent {
292
278
  }
293
279
  export interface InstrumentationTurnFailedEvent {
294
280
  readonly type: "turn.failed";
295
- /** Content. Absent unless this provider declared `capture: "content"`. */
281
+ /** Content. Absent unless this provider's trace policy records this direction. */
296
282
  readonly error?: unknown;
297
283
  readonly idempotencyKey: string;
298
284
  readonly sessionId: string;
@@ -306,7 +292,7 @@ export interface InstrumentationStepAttemptCompletedEvent {
306
292
  }
307
293
  export interface InstrumentationStepAttemptFailedEvent {
308
294
  readonly type: "step.attempt.failed";
309
- /** Content. Absent unless this provider declared `capture: "content"`. */
295
+ /** Content. Absent unless this provider's trace policy records this direction. */
310
296
  readonly error?: unknown;
311
297
  readonly idempotencyKey: string;
312
298
  readonly scope: InstrumentationAttemptScope;
@@ -326,7 +312,7 @@ export interface InstrumentationStepAttemptMetadataEvent {
326
312
  export interface InstrumentationModelCallStartedEvent {
327
313
  readonly type: "model.call.started";
328
314
  readonly idempotencyKey: string;
329
- /** Content. Absent unless this provider declared `capture: "content"`. */
315
+ /** Content. Absent unless this provider's trace policy records this direction. */
330
316
  readonly input?: InstrumentationModelInput;
331
317
  readonly model: InstrumentationModelRef;
332
318
  readonly runtimeContext?: Readonly<Record<string, unknown>>;
@@ -334,7 +320,7 @@ export interface InstrumentationModelCallStartedEvent {
334
320
  }
335
321
  export interface InstrumentationModelCallCompletedEvent {
336
322
  readonly type: "model.call.completed";
337
- /** Content. Absent unless this provider declared `capture: "content"`. */
323
+ /** Content. Absent unless this provider's trace policy records this direction. */
338
324
  readonly content?: readonly InstrumentationContentPart[];
339
325
  readonly finishReason: string;
340
326
  readonly idempotencyKey: string;
@@ -343,7 +329,7 @@ export interface InstrumentationModelCallCompletedEvent {
343
329
  }
344
330
  export interface InstrumentationModelCallFailedEvent {
345
331
  readonly type: "model.call.failed";
346
- /** Content. Absent unless this provider declared `capture: "content"`. */
332
+ /** Content. Absent unless this provider's trace policy records this direction. */
347
333
  readonly error?: unknown;
348
334
  readonly idempotencyKey: string;
349
335
  readonly scope: InstrumentationAttemptScope;
@@ -366,7 +352,7 @@ export interface InstrumentationToolCallCompletedEvent {
366
352
  }
367
353
  export interface InstrumentationToolCallFailedEvent {
368
354
  readonly type: "tool.call.failed";
369
- /** Content. Absent unless this provider declared `capture: "content"`. */
355
+ /** Content. Absent unless this provider's trace policy records this direction. */
370
356
  readonly error?: unknown;
371
357
  readonly idempotencyKey: string;
372
358
  readonly scope: InstrumentationAttemptScope;
@@ -381,7 +367,7 @@ export interface InstrumentationActionStartedEvent {
381
367
  readonly type: "action.started";
382
368
  readonly callId: string;
383
369
  readonly idempotencyKey: string;
384
- /** Content. Absent unless this provider declared `capture: "content"`. */
370
+ /** Content. Absent unless this provider's trace policy records this direction. */
385
371
  readonly input?: unknown;
386
372
  readonly kind: InstrumentationActionKind;
387
373
  readonly name: string;
@@ -400,7 +386,7 @@ export interface InstrumentationActionCompletedEvent {
400
386
  export interface InstrumentationActionFailedEvent {
401
387
  readonly type: "action.failed";
402
388
  readonly acceptedAtMs?: number;
403
- /** Content. Absent unless this provider declared `capture: "content"`. */
389
+ /** Content. Absent unless this provider's trace policy records this direction. */
404
390
  readonly error?: unknown;
405
391
  readonly errorCode?: string;
406
392
  readonly idempotencyKey: string;
@@ -423,12 +409,14 @@ export type InstrumentationEventHandler<TEvent> = (event: TEvent, ctx: Instrumen
423
409
  /** Internal provider shape mirrored by the future public hook contract. */
424
410
  export interface InstrumentationProviderDefinition {
425
411
  readonly name: string;
412
+ /** @deprecated Use `tracePolicy` to select directional content. */
413
+ readonly capture?: InstrumentationCapture;
426
414
  /** Durable state identity, separate from the human-readable log name. */
427
415
  readonly stateNamespace?: string;
428
416
  /** Internal provider-specific projection applied after capture filtering. */
429
417
  readonly projectEvent?: (event: InstrumentationEvent) => InstrumentationEvent | PromiseLike<InstrumentationEvent>;
430
- /** Defaults to `"metadata"`. See {@link InstrumentationCapture}. */
431
- readonly capture?: InstrumentationCapture;
418
+ /** Provider-specific event admission and directional content policy. */
419
+ readonly tracePolicy?: TraceCapturePolicy;
432
420
  readonly events?: {
433
421
  readonly "channel.delivery.started"?: InstrumentationEventHandler<InstrumentationChannelDeliveryStartedEvent>;
434
422
  readonly "channel.delivery.cancelled"?: InstrumentationEventHandler<InstrumentationChannelDeliveryTerminalEvent>;
@@ -491,13 +479,18 @@ export type InstrumentationExecutionOperation = {
491
479
  /** Provider-neutral hook operations consumed by the AI SDK bridge. */
492
480
  export interface InstrumentationHooks {
493
481
  /**
494
- * Whether any registered provider declared `capture: "content"`.
482
+ * Whether any provider admitted by this bound trace requests content.
495
483
  *
496
484
  * False means nothing downstream can read what was said, so the publisher
497
485
  * should not serialize it in the first place. This is the only way the
498
486
  * projection is skipped rather than merely withheld.
499
487
  */
500
488
  readonly capturesContent: boolean;
489
+ /** Input-content demand for publishers that can project directions separately. */
490
+ readonly capturesInputs?: boolean;
491
+ /** Output-content demand for publishers that can project directions separately. */
492
+ readonly capturesOutputs?: boolean;
493
+ readonly forTrace?: (trace: TraceCaptureContext) => InstrumentationHooks;
501
494
  publish(event: InstrumentationEvent): Promise<void>;
502
495
  }
503
496
  export interface CreateInstrumentationHooksOptions {
@@ -0,0 +1 @@
1
+ import{createInstrumentationDispatcher}from"#instrumentation/dispatch.js";function sessionIdempotencyKey(e){return`session:${e}`}function turnIdempotencyKey(e,t){return`turn:${e}:${t}`}function attemptIdempotencyKey(e){return`step:${e.attemptId}`}function modelCallIdempotencyKey(e,t){return`model:${e.attemptId}:${String(t)}`}function toolCallIdempotencyKey(e,t,n){return`tool:${e.attemptId}:${t}:${String(n)}`}function inputIdempotencyKey(e,t,n){return`input:${e}:${t}:${n}`}function channelDeliveryIdempotencyKey(e,t){return`channel-delivery:${e}:${t}`}function actionIdempotencyKey(e,t,n){return`action:${e}:${t}:${n}`}function createInstrumentationHooks(t,n={}){return createInstrumentationDispatcher(t,n)}export{actionIdempotencyKey,attemptIdempotencyKey,channelDeliveryIdempotencyKey,createInstrumentationHooks,inputIdempotencyKey,modelCallIdempotencyKey,sessionIdempotencyKey,toolCallIdempotencyKey,turnIdempotencyKey};
@@ -1,4 +1,4 @@
1
- import type { InstrumentationAttemptScope, InstrumentationHooks, InstrumentationParentLineage, InstrumentationTraceContext } from "#harness/instrumentation/lifecycle.js";
1
+ import type { InstrumentationAttemptScope, InstrumentationHooks, InstrumentationParentLineage, InstrumentationTraceContext } from "#instrumentation/lifecycle.js";
2
2
  import type { ResolvedInputBatch } from "#harness/input-requests.js";
3
3
  import type { HandleEventFn } from "#harness/types.js";
4
4
  import type { ChannelAudience } from "#shared/channel-audience.js";
@@ -0,0 +1 @@
1
+ import{contextStorage}from"#context/container.js";import{rememberInstrumentationActionScope,rememberInstrumentationInputScope,takeInstrumentationActionScopeForCall,takeInstrumentationInputScope}from"#instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{actionIdempotencyKey,inputIdempotencyKey,sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";function createInstrumentationHandleEvent(t){if(t.hooks===void 0)return t.handleEvent;if(t.handleEvent===void 0)return;let n=t.handleEvent,r=t.hooks,i=new Set,a=new Set,o=t.turnId;return async(s,c)=>{await n(s,c);let l=toLifecycleEvent(s,t,o);if(s.type===`turn.started`&&(o=s.data.turnId),s.type===`turn.cancelled`||s.type===`turn.completed`||s.type===`turn.failed`||s.type===`session.completed`||s.type===`session.failed`){let t=contextStorage.getStore();t!==void 0&&await instrumentChannelDelivery({ctx:t,error:s.type===`turn.failed`||s.type===`session.failed`?Error(s.data.message):void 0,errorCode:s.type===`turn.failed`||s.type===`session.failed`?s.data.code:void 0,hooks:r,includeTurn:s.type===`turn.cancelled`||s.type===`turn.completed`||s.type===`turn.failed`,outcome:s.type===`turn.failed`||s.type===`session.failed`?`failed`:s.type===`turn.cancelled`?`cancelled`:`completed`})}l!==void 0&&await r.publish(l),s.type===`actions.requested`?await publishActionStarts(s,t,r,i):s.type===`action.result`?await publishActionTerminal(s,t,r):s.type===`input.requested`&&await publishInputStarts(s,t,r,a)}}async function publishInputStarts(e,t,r,i){let a=t.getAttemptScope?.();if(a===void 0)return;let o=r.capturesOutputs??r.capturesContent;for(let c of e.data.requests){let l=inputIdempotencyKey(t.sessionId,e.data.turnId,c.requestId);i.has(l)||(i.add(l),rememberInstrumentationInputScope(l,a),await r.publish(Object.freeze({action:Object.freeze({callId:c.action.callId,name:c.action.toolName}),idempotencyKey:l,kind:c.kind,request:o?Object.freeze({allowFreeform:c.allowFreeform,display:c.display,options:c.options,prompt:c.prompt}):void 0,requestId:c.requestId,scope:a,type:`input.requested`})))}}async function publishInputResolutions(e){let t=e.hooks.capturesInputs??e.hooks.capturesContent;for(let n of e.batch.inputs){let r=inputIdempotencyKey(e.sessionId,e.batch.event.turnId,n.request.requestId),a=takeInstrumentationInputScope(r);a!==void 0&&await e.hooks.publish(Object.freeze({idempotencyKey:r,kind:n.request.kind,outcome:n.outcome,requestId:n.request.requestId,response:!t||n.response===void 0?void 0:Object.freeze({optionId:n.response.optionId,text:n.response.text}),scope:a,type:`input.resolved`}))}}async function publishActionStarts(e,n,r,i){let a=n.getAttemptScope?.();if(a===void 0)return;let s=r.capturesInputs??r.capturesContent;for(let c of e.data.actions){let l=actionIdempotencyKey(n.sessionId,e.data.turnId,c.callId);i.has(l)||(i.add(l),rememberInstrumentationActionScope(l,a),await r.publish(Object.freeze({callId:c.callId,idempotencyKey:l,input:s?c.input:void 0,kind:c.kind,name:actionName(c),scope:a,type:`action.started`})))}}async function publishActionTerminal(t,n,i){let o=takeInstrumentationActionScopeForCall(n.sessionId,t.data.result.callId);if(o===void 0)return;let{idempotencyKey:s,scope:c}=o,l=i.capturesOutputs??i.capturesContent;if(t.data.status===`completed`){await i.publish(Object.freeze({acceptedAtMs:contextStorage.getStore()?.get(RuntimeActionSettlementTimesKey)?.[t.data.result.callId],idempotencyKey:s,outcome:`completed`,output:Object.freeze(l?{output:t.data.result.output,type:`result`}:{type:`result`}),scope:c,type:`action.completed`,usage:actionUsage(t.data.result)}));return}let u=l?t.data.error===void 0?t.data.result.output:Object.assign(Error(t.data.error.message),{code:t.data.error.code}):void 0;await i.publish(Object.freeze({acceptedAtMs:contextStorage.getStore()?.get(RuntimeActionSettlementTimesKey)?.[t.data.result.callId],error:u,errorCode:t.data.error?.code,idempotencyKey:s,outcome:t.data.status,scope:c,type:`action.failed`}))}function actionUsage(e){if(!(e.kind!==`subagent-result`||e.origin!==`child`||e.usage===void 0))return{inputTokenDetails:{cacheReadTokens:e.usage.cacheReadTokens,cacheWriteTokens:e.usage.cacheWriteTokens},inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens}}function actionName(e){return e.kind===`tool-call`?e.toolName:e.kind===`load-skill`?`load_skill`:e.name}function toLifecycleEvent(e,t,n){switch(e.type){case`session.started`:return{agentName:t.agentName,channelAudience:t.channelAudience,channelKind:t.channelKind,idempotencyKey:sessionIdempotencyKey(t.sessionId),parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId??t.sessionId,sessionId:t.sessionId,type:`session.started`};case`session.completed`:case`session.waiting`:return{idempotencyKey:sessionIdempotencyKey(t.sessionId),sessionId:t.sessionId,turnId:n,type:e.type};case`session.failed`:return{error:Error(e.data.message),idempotencyKey:sessionIdempotencyKey(t.sessionId),sessionId:t.sessionId,turnId:n,type:`session.failed`};case`turn.started`:return{idempotencyKey:turnIdempotencyKey(t.sessionId,e.data.turnId),parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId??t.sessionId,sequence:e.data.sequence,sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.started`};case`turn.completed`:case`turn.cancelled`:return{idempotencyKey:turnIdempotencyKey(t.sessionId,e.data.turnId),sessionId:t.sessionId,turnId:e.data.turnId,type:e.type};case`turn.failed`:return{error:Error(e.data.message),idempotencyKey:turnIdempotencyKey(t.sessionId,e.data.turnId),sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.failed`};default:return}}export{createInstrumentationHandleEvent,publishInputResolutions};
@@ -1,5 +1,5 @@
1
1
  import type { SessionParent } from "#channel/types.js";
2
- import type { InstrumentationParentLineage } from "#harness/instrumentation/lifecycle.js";
2
+ import type { InstrumentationParentLineage } from "#instrumentation/lifecycle.js";
3
3
  /**
4
4
  * Resolves the dispatch that created the running session, if any. Dispatch
5
5
  * splits the lineage across two owners — the identifiers onto
@@ -1,14 +1,16 @@
1
1
  import type { RuntimeTraceContext } from "#protocol/message.js";
2
- import type { InstrumentationParentLineage, InstrumentationTraceSeed } from "#harness/instrumentation/lifecycle.js";
3
- import type { HarnessInstrumentation } from "#harness/instrumentation/runtime.js";
2
+ import type { InstrumentationParentLineage, InstrumentationSessionStartedEvent, InstrumentationTraceSeed, InstrumentationTurnStartedEvent } from "#instrumentation/lifecycle.js";
4
3
  import type { ChannelAudience } from "#shared/channel-audience.js";
5
4
  import { type SessionTraceSeed } from "#context/keys.js";
6
5
  /** Prepares native session/turn tracing before their durable stream events. */
7
- export declare function prepareTurnTraceContext(input: {
6
+ export interface PrepareTurnTraceContextInput {
8
7
  readonly agentName?: string;
9
8
  readonly channelAudience?: ChannelAudience;
10
9
  readonly channelType?: string;
11
- readonly instrumentation?: HarnessInstrumentation;
10
+ readonly instrumentation?: {
11
+ readonly prepareSessionTrace?: (event: InstrumentationSessionStartedEvent) => Promise<InstrumentationTraceSeed>;
12
+ readonly prepareTurnTrace?: (event: InstrumentationTurnStartedEvent) => Promise<InstrumentationTraceSeed>;
13
+ };
12
14
  readonly parentLineage?: InstrumentationParentLineage;
13
15
  readonly parentTraceContext?: InstrumentationTraceSeed;
14
16
  readonly rootSessionId: string;
@@ -18,4 +20,5 @@ export declare function prepareTurnTraceContext(input: {
18
20
  readonly traceContext?: RuntimeTraceContext;
19
21
  readonly traceSeed?: SessionTraceSeed;
20
22
  readonly turnId: string;
21
- }): Promise<RuntimeTraceContext | undefined>;
23
+ }
24
+ export declare function prepareTurnTraceContext(input: PrepareTurnTraceContextInput): Promise<RuntimeTraceContext | undefined>;
@@ -0,0 +1 @@
1
+ import{createLogger,formatError}from"#internal/logging.js";import{contextStorage}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";const log=createLogger(`harness.prepare-trace-context`);async function prepareTurnTraceContext(e){let t;if(!e.sessionStarted&&e.instrumentation?.prepareSessionTrace!==void 0)try{t=await e.instrumentation.prepareSessionTrace({agentName:e.agentName,channelAudience:e.channelAudience,channelType:e.channelType,idempotencyKey:sessionIdempotencyKey(e.sessionId),parentTraceContext:e.parentTraceContext,rootSessionId:e.rootSessionId,sessionId:e.sessionId,traceSeed:e.traceSeed,type:`session.started`})}catch(e){warn(`session.started`,e)}if(e.instrumentation?.prepareTurnTrace!==void 0)try{t=await e.instrumentation.prepareTurnTrace({agentName:e.agentName,idempotencyKey:turnIdempotencyKey(e.sessionId,e.turnId),parentLineage:e.parentLineage,parentTraceContext:e.parentTraceContext,rootSessionId:e.rootSessionId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId,type:`turn.started`})}catch(e){warn(`turn.started`,e)}return e.traceSeed===void 0&&t?.decision!==void 0&&contextStorage.getStore()?.set(SessionTraceSeedKey,t),e.traceContext??t}function warn(e,n){log.warn(`instrumentation trace preparation failed`,{boundary:e,error:formatError(n)})}export{prepareTurnTraceContext};
@@ -4,10 +4,12 @@
4
4
  * Reachable only with `experimental.instrumentationProviders` on. With the flag
5
5
  * off nothing discovers that directory, so these types compile but never run.
6
6
  */
7
- import type { InstrumentationCapture, InstrumentationEvent } from "#harness/instrumentation/lifecycle.js";
7
+ import type { InstrumentationEvent } from "#instrumentation/lifecycle.js";
8
8
  import type { JsonValue } from "#shared/json.js";
9
+ import type { InstrumentationCapture, TraceCapturePolicy } from "#shared/trace-policy.js";
9
10
  export type { JsonValue } from "#shared/json.js";
10
- export type { InstrumentationActionCompletedEvent, InstrumentationActionFailedEvent, InstrumentationActionKind, InstrumentationActionOutcome, InstrumentationActionOutput, InstrumentationActionStartedEvent, InstrumentationAttemptScope, InstrumentationCapture, InstrumentationChannelDeliveryInput, InstrumentationChannelDeliveryOutcome, InstrumentationChannelDeliveryRef, InstrumentationChannelDeliveryStartedEvent, InstrumentationChannelDeliveryTerminalEvent, InstrumentationContentPart, InstrumentationEvent, InstrumentationInputKind, InstrumentationInputOption, InstrumentationInputOutcome, InstrumentationInputRequest, InstrumentationInputRequestedEvent, InstrumentationInputResolvedEvent, InstrumentationInputResponse, InstrumentationModelCallCompletedEvent, InstrumentationModelCallFailedEvent, InstrumentationModelCallStartedEvent, InstrumentationModelRef, InstrumentationOperationRef, InstrumentationParentLineage, InstrumentationSessionFailedEvent, InstrumentationSessionSettledEvent, InstrumentationSessionStartedEvent, InstrumentationSessionTransitionEvent, InstrumentationStepAttemptMetadataEvent, InstrumentationStepAttemptCompletedEvent, InstrumentationStepAttemptFailedEvent, InstrumentationStepAttemptStartedEvent, InstrumentationStepAttemptTerminalEvent, InstrumentationToolCallCompletedEvent, InstrumentationToolCallFailedEvent, InstrumentationToolCallStartedEvent, InstrumentationToolOutput, InstrumentationTraceContext, InstrumentationTurnFailedEvent, InstrumentationTurnSettledEvent, InstrumentationTurnStartedEvent, InstrumentationTurnTerminalEvent, InstrumentationUsage, } from "#harness/instrumentation/lifecycle.js";
11
+ export type { InstrumentationActionCompletedEvent, InstrumentationActionFailedEvent, InstrumentationActionKind, InstrumentationActionOutcome, InstrumentationActionOutput, InstrumentationActionStartedEvent, InstrumentationAttemptScope, InstrumentationChannelDeliveryInput, InstrumentationChannelDeliveryOutcome, InstrumentationChannelDeliveryRef, InstrumentationChannelDeliveryStartedEvent, InstrumentationChannelDeliveryTerminalEvent, InstrumentationContentPart, InstrumentationEvent, InstrumentationInputKind, InstrumentationInputOption, InstrumentationInputOutcome, InstrumentationInputRequest, InstrumentationInputRequestedEvent, InstrumentationInputResolvedEvent, InstrumentationInputResponse, InstrumentationModelCallCompletedEvent, InstrumentationModelCallFailedEvent, InstrumentationModelCallStartedEvent, InstrumentationModelRef, InstrumentationOperationRef, InstrumentationParentLineage, InstrumentationSessionFailedEvent, InstrumentationSessionSettledEvent, InstrumentationSessionStartedEvent, InstrumentationSessionTransitionEvent, InstrumentationStepAttemptMetadataEvent, InstrumentationStepAttemptCompletedEvent, InstrumentationStepAttemptFailedEvent, InstrumentationStepAttemptStartedEvent, InstrumentationStepAttemptTerminalEvent, InstrumentationToolCallCompletedEvent, InstrumentationToolCallFailedEvent, InstrumentationToolCallStartedEvent, InstrumentationToolOutput, InstrumentationTraceContext, InstrumentationTurnFailedEvent, InstrumentationTurnSettledEvent, InstrumentationTurnStartedEvent, InstrumentationTurnTerminalEvent, InstrumentationUsage, } from "#instrumentation/lifecycle.js";
12
+ export type { InstrumentationCapture, TraceCaptureContext, TraceCapturePolicy, TracePolicyDecision, } from "#shared/trace-policy.js";
11
13
  /**
12
14
  * Marks a value as having come from `defineInstrumentation` or a built-in
13
15
  * factory.
@@ -80,15 +82,17 @@ export type ProviderEvents = {
80
82
  * completion order.
81
83
  */
82
84
  export interface ProviderDefinition {
85
+ /** @deprecated Use `tracePolicy`. Ignored when `tracePolicy` is also set. */
86
+ readonly capture?: InstrumentationCapture;
83
87
  /**
84
- * How much of each event this provider is handed. Defaults to `"metadata"`:
85
- * structure, identity, usage, and timing, but not what was said.
86
- *
87
- * `"content"` adds the prompt, the response, tool arguments, and tool
88
- * results. Asking is what makes eve build the projection at all, so a
89
- * directory in which nobody asks never serializes a prompt.
88
+ * Whether this provider receives events and which content directions they
89
+ * include. Defaults to emitting every audience, with content only for public
90
+ * conversations. Boolean `true` uses the same audience-aware content rule;
91
+ * an explicit emitted decision can authorize either direction independently.
92
+ * A thrown error disables this provider for the trace. The policy can run
93
+ * again across durable steps, so it must be deterministic.
90
94
  */
91
- readonly capture?: InstrumentationCapture;
95
+ readonly tracePolicy?: TraceCapturePolicy;
92
96
  readonly events?: ProviderEvents;
93
97
  /** Runs once at server startup, before any event is published. */
94
98
  readonly setup?: (context: ProviderSetupContext) => void | PromiseLike<void>;
@@ -1,4 +1,4 @@
1
- import { type InstrumentationRuntime } from "#harness/instrumentation/runtime.js";
1
+ import { type InstrumentationRuntime } from "#instrumentation/runtime.js";
2
2
  import { type InstrumentationProvider } from "#public/instrumentation/provider.js";
3
3
  /** One provider and the `instrumentation/<slot>.ts` file it came from. */
4
4
  export interface RegisteredInstrumentationProvider {
@@ -0,0 +1 @@
1
+ import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{getInstrumentationRuntime}from"#instrumentation/runtime.js";import{DEVELOPMENT_WORKER_APP_ROOT_ENV}from"#internal/workflow/development-world-protocol.js";import{createInstrumentationSetupContext}from"#instrumentation/setup-context.js";import{agentRuns,localTraces}from"#public/instrumentation/otel.js";import{installInstrumentationRuntime}from"#tracing/install-instrumentation-runtime.js";import{collectOtelPipeline}from"#tracing/otel-declaration.js";import{isInstrumentationDisabled,isInstrumentationProvider}from"#public/instrumentation/provider.js";const INSTRUMENTATION_PROVIDERS_GLOBAL_KEY=Symbol.for(`eve.harness-instrumentation-providers`),globalContainer=globalThis;function providerRegistry(){let e=globalContainer[INSTRUMENTATION_PROVIDERS_GLOBAL_KEY];if(e!==void 0)return e;let t=new Map;return globalContainer[INSTRUMENTATION_PROVIDERS_GLOBAL_KEY]=t,t}function seedInstrumentationProviders(){let e=providerRegistry();process.env.VERCEL_ENV===`production`&&e.set(`agent-runs`,agentRuns()),process.env[DEVELOPMENT_WORKER_APP_ROOT_ENV]!==void 0&&e.set(`local`,localTraces())}async function registerInstrumentationProvider(e){if(isInstrumentationDisabled(e.value)){providerRegistry().delete(e.slot);return}if(!isInstrumentationProvider(e.value))throw Error(`The default export of "instrumentation/${e.slot}" is not an instrumentation provider. Return the result of \`defineInstrumentation\` or \`disableInstrumentation\` from it.`);providerRegistry().set(e.slot,e.value),await e.value.setup?.(createInstrumentationSetupContext(e.agentName))}function getInstrumentationProviders(){return[...providerRegistry()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({provider:t,slot:e}))}function finalizeInstrumentationProviders(t){let n=getInstrumentationProviders(),r=n.map(toProviderDefinition),i=collectOtelPipeline(n.map(e=>e.provider));return installInstrumentationRuntime({collected:i,frameworkVersion:resolveInstalledPackageInfo().version,instrumentationProviders:!0,providers:r,runtimeContextResolvers:i.runtimeContextResolvers,serviceName:t.serviceName})}async function shutdownInstrumentationProviders(){await getInstrumentationRuntime()?.shutdown()}function toProviderDefinition(e){return{capture:e.provider.capture,events:e.provider.events,flush:e.provider.flush,name:e.slot,shutdown:e.provider.shutdown,stateNamespace:`authored:${e.slot}`,tracePolicy:e.provider.tracePolicy}}export{finalizeInstrumentationProviders,getInstrumentationProviders,registerInstrumentationProvider,seedInstrumentationProviders,shutdownInstrumentationProviders};
@@ -1,11 +1,14 @@
1
1
  import type { ModelMessage, SystemModelMessage } from "ai";
2
+ import type { ChannelInstrumentationProjection, SessionAuthContext, SessionParent } from "#channel/types.js";
3
+ import type { AlsContext } from "#context/container.js";
2
4
  import type { HarnessEmissionState } from "#harness/emission.js";
3
5
  import type { HarnessSession } from "#harness/types.js";
4
6
  import type { RuntimeContextResolver } from "#tracing/otel-declaration.js";
5
- import type { InstrumentationDefinition } from "#public/instrumentation/index.js";
7
+ import type { InstrumentationEvents } from "#public/instrumentation/index.js";
6
8
  export interface BuildTelemetryRuntimeContextInput {
9
+ readonly capturesContent: boolean;
10
+ readonly context?: InstrumentationRuntimeContextSnapshot;
7
11
  readonly eveVersion: string;
8
- readonly authored: InstrumentationDefinition | undefined;
9
12
  readonly emissionState: HarnessEmissionState;
10
13
  readonly environment: string;
11
14
  readonly modelInput: {
@@ -14,7 +17,15 @@ export interface BuildTelemetryRuntimeContextInput {
14
17
  };
15
18
  readonly providerResolvers?: readonly RuntimeContextResolver[];
16
19
  readonly session: HarnessSession;
20
+ readonly stepStartedResolver: InstrumentationEvents["step.started"];
17
21
  }
22
+ export interface InstrumentationRuntimeContextSnapshot {
23
+ readonly channel?: ChannelInstrumentationProjection;
24
+ readonly currentAuth: SessionAuthContext | null;
25
+ readonly initiatorAuth: SessionAuthContext | null;
26
+ readonly parent?: SessionParent;
27
+ }
28
+ export declare function snapshotInstrumentationRuntimeContext(context: AlsContext | undefined): InstrumentationRuntimeContextSnapshot;
18
29
  /**
19
30
  * Builds per-model-call runtime context for AI SDK telemetry spans.
20
31
  *
@@ -0,0 +1 @@
1
+ import{createLogger,formatError}from"#internal/logging.js";import{normalizeInstrumentationChannelKind,resolveInstrumentationProjection}from"#internal/instrumentation.js";import{contextStorage}from"#context/container.js";import{AuthKey,ChannelInstrumentationKey,InitiatorAuthKey,ParentSessionKey}from"#context/keys.js";import{parseJsonObject,parseJsonValue}from"#shared/json.js";const log=createLogger(`harness.instrumentation-runtime-context`);function snapshotInstrumentationRuntimeContext(e){let t=e?.get(AuthKey)??null;return{channel:snapshotForInstrumentation(e?.get(ChannelInstrumentationKey),`channel.instrumentation`),currentAuth:snapshotForInstrumentation(t,`session.auth.current`)??null,initiatorAuth:snapshotForInstrumentation(e?.get(InitiatorAuthKey)??t,`session.auth.initiator`)??null,parent:snapshotForInstrumentation(e?.get(ParentSessionKey),`session.parent`)}}function buildTelemetryRuntimeContext(e){let t=e.stepStartedResolver!==void 0,r=e.providerResolvers!==void 0&&e.providerResolvers.length>0;if(!t&&!r)return;let a=resolveStepStartedRuntimeContext(e),o=resolveProviderRuntimeContext(e),s=(e.context??snapshotInstrumentationRuntimeContext(contextStorage.getStore())).channel;return{...a,...o,"eve.channel.kind":normalizeInstrumentationChannelKind(s?.kind),"eve.environment":e.environment,"eve.session.id":e.session.sessionId,"eve.step.index":String(e.emissionState.stepIndex),"eve.turn.id":e.emissionState.turnId,"eve.turn.sequence":String(e.emissionState.sequence),"eve.version":e.eveVersion}}function buildInstrumentationStepStartedInput(e){let t=e.context??snapshotInstrumentationRuntimeContext(contextStorage.getStore()),r=t.channel;return{channel:{kind:normalizeInstrumentationChannelKind(r?.kind),metadata:snapshotForInstrumentation(r?.metadata,`channel.metadata`)??{}},modelInput:e.capturesContent?snapshotForInstrumentation(e.modelInput,`modelInput`)??{instructions:void 0,messages:[]}:{instructions:void 0,messages:[]},session:{auth:projectSessionAuth(t),id:e.session.sessionId,parent:t.parent},step:{index:e.emissionState.stepIndex},turn:{id:e.emissionState.turnId,sequence:e.emissionState.sequence}}}function filterAuthoredRuntimeContext(e,t){let n={};for(let[r,i]of Object.entries(e)){if(r.startsWith(`eve.`)){log.warn(`ignoring reserved instrumentation runtime context key`,{key:r,source:t});continue}n[r]=i}return Object.keys(n).length>0?n:void 0}function resolveStepStartedRuntimeContext(e){let n=e.stepStartedResolver;if(n===void 0)return;let i=`events["step.started"]`,a=resolveInstrumentationProjection({invoke:()=>{let t=buildInstrumentationStepStartedInput(e);return n(t)},log,source:i});if(a===void 0)return;if(!(`runtimeContext`in a)){log.warn(`ignoring instrumentation event result because runtimeContext is missing`,{source:i});return}let o;try{o=parseJsonObject(a.runtimeContext)}catch(e){log.warn(`ignoring instrumentation event result because runtimeContext is invalid`,{error:formatError(e),source:i});return}return filterAuthoredRuntimeContext(o,i)}function resolveProviderRuntimeContext(e){let t=e.providerResolvers;if(t===void 0||t.length===0)return;let n={},i=!1;for(let a of t){let t=`provider.runtimeContext`,o=resolveInstrumentationProjection({invoke:()=>{let t=buildInstrumentationStepStartedInput(e);return a(t)},log,source:t});if(o===void 0)continue;let s=filterAuthoredRuntimeContext(o,t);s!==void 0&&(Object.assign(n,s),i=!0)}return i?n:void 0}function projectSessionAuth(e){return{current:e.currentAuth,initiator:e.initiatorAuth}}function snapshotForInstrumentation(e,n){if(e!==void 0)try{return parseJsonValue(e)}catch(e){log.warn(`dropping non-serializable instrumentation snapshot`,{error:formatError(e),source:n});return}}export{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext};
@@ -0,0 +1,100 @@
1
+ import type { TelemetryOptions } from "ai";
2
+ import type { InstrumentationEvents } from "#public/instrumentation/index.js";
3
+ import type { InstrumentationAttemptScope, InstrumentationContextRunner, InstrumentationHooks, InstrumentationSessionStartedEvent, InstrumentationTraceContext, InstrumentationTraceSeed, InstrumentationTurnStartedEvent } from "#instrumentation/lifecycle.js";
4
+ import { type BuildTelemetryRuntimeContextInput } from "#instrumentation/runtime-context.js";
5
+ import { type CreateInstrumentationHandleEventInput } from "#instrumentation/native-events.js";
6
+ import type { ResolvedInputBatch } from "#harness/input-requests.js";
7
+ import type { HandleEventFn } from "#harness/types.js";
8
+ import { type ChannelDeliveryStartInstrumentation, type ChannelDeliveryTerminalInstrumentation } from "#instrumentation/channel-delivery.js";
9
+ import { type PrepareTurnTraceContextInput } from "#instrumentation/prepare-trace-context.js";
10
+ import type { RuntimeTraceContext } from "#protocol/message.js";
11
+ import type { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
12
+ import type { OtelHarnessSettings, RuntimeContextResolver } from "#tracing/otel-declaration.js";
13
+ import { type ContextContainer } from "#context/container.js";
14
+ import type { SessionTraceContext } from "#channel/types.js";
15
+ interface InstrumentedStepSession {
16
+ readonly sessionId: string;
17
+ readonly state?: Readonly<Record<string, unknown>>;
18
+ }
19
+ export interface InstrumentationStepScope<TSession> {
20
+ readonly createHandleEvent: (input: Omit<CreateInstrumentationHandleEventInput, "agentName" | "channelAudience" | "channelKind" | "hooks" | "parentLineage" | "parentTraceContext" | "rootSessionId" | "sessionId">) => HandleEventFn | undefined;
21
+ readonly prepareAttempt: (input: {
22
+ readonly attemptIndex: number;
23
+ readonly runtimeContext?: Readonly<Record<string, unknown>>;
24
+ readonly stepIndex: number;
25
+ readonly turnId: string;
26
+ }) => PreparedInstrumentationAttempt;
27
+ readonly preparePreamble: (input: Omit<PrepareTurnTraceContextInput, "agentName" | "channelAudience" | "channelType" | "instrumentation" | "parentLineage" | "parentTraceContext" | "rootSessionId" | "sessionId" | "traceSeed">) => Promise<RuntimeTraceContext | undefined>;
28
+ readonly publishInputResolutions: (input: {
29
+ readonly batch: ResolvedInputBatch;
30
+ readonly sessionId: string;
31
+ }) => Promise<void>;
32
+ readonly recordError: (error: unknown) => void;
33
+ readonly resolveRuntimeContext: (input: Omit<BuildTelemetryRuntimeContextInput, "capturesContent" | "context" | "providerResolvers" | "stepStartedResolver">) => Record<string, unknown> | undefined;
34
+ readonly session: TSession;
35
+ readonly setTurnId: (turnId: string) => void;
36
+ readonly telemetry: () => TelemetryOptions | undefined;
37
+ readonly traceContext?: InstrumentationTraceContext;
38
+ }
39
+ export interface PreparedInstrumentationAttempt {
40
+ readonly complete: () => Promise<void>;
41
+ readonly fail: (error: unknown) => Promise<void>;
42
+ readonly scope: InstrumentationAttemptScope;
43
+ readonly telemetry: TelemetryOptions | undefined;
44
+ }
45
+ export type InstrumentationAttempt = InstrumentationAttemptScope;
46
+ export interface BoundInstrumentationSession {
47
+ readonly agentName: string;
48
+ readonly rootSessionId: string;
49
+ readonly sessionId: string;
50
+ }
51
+ /** Process-wide runtime consumed by every harness execution surface. */
52
+ export interface InstrumentationRuntime {
53
+ readonly forceFlush: () => Promise<void>;
54
+ readonly hooks: InstrumentationHooks;
55
+ readonly idGenerator?: AgentSpanIdGenerator;
56
+ readonly instrumentationProviders?: boolean;
57
+ readonly prepareSessionTrace?: (event: InstrumentationSessionStartedEvent) => Promise<InstrumentationTraceSeed>;
58
+ readonly prepareTurnTrace?: (event: InstrumentationTurnStartedEvent) => Promise<InstrumentationTraceSeed>;
59
+ otelSettings: OtelHarnessSettings | undefined;
60
+ readonly runtimeContextResolvers?: readonly RuntimeContextResolver[];
61
+ readonly runInContext: InstrumentationContextRunner;
62
+ readonly shutdown: () => Promise<void>;
63
+ stepStartedRuntimeContextResolver?: InstrumentationEvents["step.started"];
64
+ }
65
+ /** Worker-bound instrumentation operations consumed by one session execution. */
66
+ export interface SessionInstrumentation {
67
+ readonly runStep: <TSession extends InstrumentedStepSession, TResult>(input: {
68
+ readonly environment: string;
69
+ readonly eveVersion: string;
70
+ readonly hasInput: boolean;
71
+ readonly session: TSession;
72
+ }, execute: (scope: InstrumentationStepScope<TSession>) => Promise<TResult>) => Promise<TResult>;
73
+ }
74
+ export interface ExecutionInstrumentation {
75
+ readonly createCancellationHandleEvent: (input: {
76
+ readonly handleEvent?: HandleEventFn;
77
+ readonly turnId: string;
78
+ }) => HandleEventFn | undefined;
79
+ readonly flush: () => Promise<void>;
80
+ readonly instrumentChannelDelivery: (input: Omit<ChannelDeliveryStartInstrumentation, "hooks" | "policyAgentName"> | Omit<ChannelDeliveryTerminalInstrumentation, "hooks">) => Promise<void>;
81
+ readonly prepareExecution: () => SessionInstrumentation;
82
+ readonly preparePreamble: InstrumentationStepScope<never>["preparePreamble"];
83
+ }
84
+ export declare function bindInstrumentationRuntime(runtime: InstrumentationRuntime | undefined, ctx: ContextContainer, boundSession: BoundInstrumentationSession): ExecutionInstrumentation | undefined;
85
+ export declare function bindSessionInstrumentation(input: {
86
+ readonly agentName: string;
87
+ readonly ctx: ContextContainer;
88
+ readonly rootSessionId: string;
89
+ readonly sessionId: string;
90
+ }): ExecutionInstrumentation | undefined;
91
+ export declare function initializeSessionInstrumentation(input: {
92
+ readonly agentName: string;
93
+ readonly ctx: ContextContainer;
94
+ readonly parentTraceContext?: SessionTraceContext;
95
+ }): void;
96
+ /** Registers the process instrumentation runtime before agent execution begins. */
97
+ export declare function registerInstrumentationRuntime(runtime: InstrumentationRuntime): InstrumentationRuntime;
98
+ /** Returns the process instrumentation runtime, when one was installed. */
99
+ export declare function getInstrumentationRuntime(): InstrumentationRuntime | undefined;
100
+ export {};
@@ -0,0 +1 @@
1
+ import{recordErrorOnSpan}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{ChannelInstrumentationKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,SessionTraceSeedKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{readSessionTraceDecision}from"#tracing/agent-trace-context-store.js";import{applyAudienceCeiling,shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import{resolveParentLineage}from"#instrumentation/parent-lineage.js";const INSTRUMENTATION_RUNTIME_KEY=Symbol.for(`eve.instrumentation-runtime`),TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function bindInstrumentationRuntime(i,l,u){if(i===void 0)return;let d=i.hooks,readSessionContext=()=>{let e=contextStorage.getStore()??l;return{channel:e.get(ChannelKey),context:e,instrumentation:e.get(ChannelInstrumentationKey),parent:e.get(ParentSessionKey),parentTraceContext:e.get(ParentTraceContextKey),traceSeed:e.get(SessionTraceSeedKey)}},bindHooks=e=>{let n=e.instrumentation;return d.forTrace?.({agentName:u.agentName,audience:normalizeChannelAudience(n?.metadata.audience),channelType:n?.channelType})??d},captureExecutionRuntime=()=>{let e=i.otelSettings;return e!==void 0&&ensureOtelIntegration(),{otelSettings:e,runtimeContextResolvers:i.runtimeContextResolvers,stepStartedRuntimeContextResolver:i.stepStartedRuntimeContextResolver,tracer:e===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(e,n)=>{let r=n.instrumentation,a=normalizeChannelAudience(r?.metadata.audience);return prepareTurnTraceContext({...e,agentName:u.agentName,channelAudience:a,channelType:r?.channelType,instrumentation:i,parentLineage:resolveParentLineage(n.parent,n.channel),parentTraceContext:n.parentTraceContext,rootSessionId:n.parent?.rootSessionId??u.rootSessionId,sessionId:u.sessionId,traceSeed:n.traceSeed})};return{createCancellationHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:u.agentName,channelKind:t.instrumentation?.kind,handleEvent:e.handleEvent,hooks:bindHooks(t),sessionId:u.sessionId,turnId:e.turnId})},flush:i.forceFlush,instrumentChannelDelivery:e=>instrumentChannelDelivery({...e,hooks:d,policyAgentName:u.agentName}),prepareExecution:()=>{let n=captureExecutionRuntime();return{runStep:async(r,a)=>{let o=readSessionContext(),s=bindHooks(o),c=n.otelSettings,l=resolveStepInstrumentationDecision(c,u.agentName,o.instrumentation,o.traceSeed,readSessionTraceDecision(o.context,u.sessionId)),d=n.tracer,f={"eve.environment":r.environment,"eve.session.id":r.session.sessionId,"eve.version":r.eveVersion},p=c?.functionId??u.agentName;p&&(f[`ai.telemetry.functionId`]=p);let m=d!==void 0&&l?.action!==`drop`&&r.hasInput?d.startSpan(`ai.eve.turn`,{attributes:f}):void 0,h=m?.spanContext(),g=h===void 0?r.session:{...r.session,state:{...r.session.state,[TURN_TRACE_STATE_KEY]:{spanId:h.spanId,traceFlags:h.traceFlags,traceId:h.traceId}}},_=m===void 0?void 0:trace.setSpan(context.active(),m);if(_===void 0&&d!==void 0){let e=r.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(_=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let v=readSessionContext(),y=snapshotInstrumentationRuntimeContext(v.context),b=v.instrumentation,x=normalizeChannelAudience(b?.metadata.audience),S=shouldCaptureInstrumentationContent(x),C=l===void 0?void 0:applyAudienceCeiling(l,x),w=l?.action===`drop`,T={recordInputs:!w&&(C?.action===`record`?C.recordInputs:S)&&(c?.recordInputs??!1),recordOutputs:!w&&(C?.action===`record`?C.recordOutputs:S)&&(c?.recordOutputs??!1)},telemetry=e=>{if(c===void 0&&e.bridgeIntegration===void 0)return;let t={};for(let n of Object.keys(e.runtimeContext??{}))t[n]=!0;let n=c!==void 0&&!(T.recordInputs&&T.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({sanitizeEveOtelErrors:n});return{functionId:c?.functionId??u.agentName,includeRuntimeContext:t,integrations:e.bridgeIntegration===void 0?n?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:T.recordInputs,recordOutputs:T.recordOutputs}},run=()=>a({createHandleEvent:e=>createInstrumentationHandleEvent({...e,agentName:u.agentName,channelAudience:x,channelKind:b?.kind,hooks:s,parentLineage:resolveParentLineage(v.parent,v.channel),parentTraceContext:v.parentTraceContext,rootSessionId:v.parent?.rootSessionId,sessionId:u.sessionId}),prepareAttempt:e=>{let t={attemptId:`${u.sessionId}:${e.turnId}:${e.stepIndex}:${e.attemptIndex}`,attemptIndex:e.attemptIndex,channelAudience:x,functionId:c?.functionId??u.agentName,rootSessionId:v.parent?.rootSessionId??u.sessionId,sessionId:u.sessionId,stepIndex:e.stepIndex,turnId:e.turnId},n=createAiSdkHookBridge(t,s,i.runInContext,e.runtimeContext);return{complete:()=>s.publish({idempotencyKey:attemptIdempotencyKey(t),scope:t,type:`step.attempt.completed`}),fail:e=>s.publish({error:e,idempotencyKey:attemptIdempotencyKey(t),scope:t,type:`step.attempt.failed`}),scope:t,telemetry:telemetry({bridgeIntegration:n,runtimeContext:e.runtimeContext})}},preparePreamble:e=>preparePreamble(e,v),publishInputResolutions:e=>publishInputResolutions({...e,hooks:s}),recordError:t=>{m!==void 0&&recordErrorOnSpan(m,t)},resolveRuntimeContext:e=>{let r=normalizeChannelAudience(y.channel?.metadata.audience);return buildTelemetryRuntimeContext({...e,capturesContent:shouldCaptureInstrumentationContent(r),context:y,providerResolvers:n.runtimeContextResolvers,stepStartedResolver:n.stepStartedRuntimeContextResolver})},session:g,setTurnId:e=>m?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:h===void 0||!isValidSpanContext(h)?void 0:{spanId:h.spanId,traceFlags:h.traceFlags,traceId:h.traceId}});try{return _===void 0?await run():await context.with(_,run)}finally{m?.end(),m=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,{agentName:e.agentName,rootSessionId:e.rootSessionId,sessionId:e.sessionId})}function initializeSessionInstrumentation(e){let n=getInstrumentationRuntime(),a=e.ctx.get(ChannelInstrumentationKey),o=normalizeChannelAudience(a?.metadata.audience),c=allocateSessionTraceSeed({agentName:e.agentName,audience:o,channelType:a?.channelType,parentTraceContext:e.parentTraceContext,runtime:n});c!==void 0&&e.ctx.set(SessionTraceSeedKey,c),e.ctx.set(OtelTraceEnabledKey,n?.prepareSessionTrace!==void 0)}function allocateSessionTraceSeed(e){if(e.parentTraceContext!==void 0)return{decision:e.parentTraceContext.decision??resolveTracePolicyDecision(isSampledTrace(e.parentTraceContext),e.audience),spanId:e.parentTraceContext.spanId,traceFlags:e.parentTraceContext.traceFlags,traceId:e.parentTraceContext.traceId};if(e.runtime?.prepareSessionTrace===void 0||e.runtime.idGenerator===void 0)return;let t=resolveTracePolicy(e.runtime.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType});return{decision:t,spanId:e.runtime.idGenerator.allocateSpanId(),traceFlags:+(t.action===`record`),traceId:e.runtime.idGenerator.generateTraceId()}}function resolveStepInstrumentationDecision(e,n,r,i,a){if(e===void 0)return;if(i?.decision!==void 0)return i.decision;if(a!==void 0)return a;let o=normalizeChannelAudience(r?.metadata.audience);return i===void 0?resolveTracePolicy(e.tracePolicy,{agentName:n,audience:o,channelType:r?.channelType}):resolveTracePolicyDecision(isSampledTrace(i),o)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}const globalRuntime=globalThis;function registerInstrumentationRuntime(e){let t=globalRuntime[INSTRUMENTATION_RUNTIME_KEY];return t===void 0?(globalRuntime[INSTRUMENTATION_RUNTIME_KEY]=e,e):(t.otelSettings=e.otelSettings,t)}function getInstrumentationRuntime(){return globalRuntime[INSTRUMENTATION_RUNTIME_KEY]}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
@@ -1,20 +1,11 @@
1
1
  import { type JsonValue } from "#shared/json.js";
2
- import type { InstrumentationAttemptScope } from "#harness/instrumentation/lifecycle.js";
2
+ import type { InstrumentationAttemptScope } from "#instrumentation/lifecycle.js";
3
3
  export interface InstrumentationStateOwner {
4
4
  readonly attemptId?: string;
5
5
  readonly sessionId?: string;
6
6
  readonly turnId?: string;
7
7
  }
8
- /**
9
- * Keeps provider state from an interrupted step's context changes.
10
- *
11
- * A cancelled step's context writes are discarded wholesale. Provider state has
12
- * to be an exception for the same reason eve's own trace state is: the
13
- * cancellation epilogue still publishes `turn.cancelled`, and a provider that
14
- * staged something at the start of the operation being cancelled needs it there
15
- * to close cleanly. Without this, the terminal arrives with an empty slot and
16
- * whatever the provider opened is never closed.
17
- */
8
+ /** Keeps only provider state needed to settle an interrupted operation. */
18
9
  export declare function preserveSerializedInstrumentationState(original: Record<string, unknown>, interrupted: Record<string, unknown>): Record<string, unknown>;
19
10
  /** One provider's view of its own state for one operation. */
20
11
  export interface InstrumentationStateSlot {
@@ -11,7 +11,7 @@ const workflowWorld = await workflowWorldModule.createWorld({
11
11
  headers: { "User-Agent": ${JSON.stringify(buildPackageUserAgent())} },
12
12
  });`.trimStart()}:{moduleImportSpecifier:e,extraImportLines:[],runtimeImports:`createWorldFromModule, getWorld, setWorld`,createWorldSource:`const workflowWorld = await createWorldFromModule(workflowWorldModule);`}}function createWorkflowWorldPluginSource(e){let t=resolveWorkflowWorldWiring(resolveWorkflowWorldImport(e.configuredWorld??e.defaultWorld)),n=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),r=resolvePackageSourceFilePath(`src/internal/workflow/validate-world.ts`);return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(e.compiledArtifactsBootstrapPath)};`,`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(t.moduleImportSpecifier)};`,...t.extraImportLines,`import { ${t.runtimeImports} } from ${stringifyEsmImportSpecifier(n)};`,`import { validateWorkflowWorld } from ${stringifyEsmImportSpecifier(r)};`,``,t.createWorldSource,`validateWorkflowWorld({ packageName: ${JSON.stringify(e.configuredWorld)}, world: workflowWorld });`,`setWorld(workflowWorld);`,`await getWorld();`,`await workflowWorld.start?.();`,``,`export default function installWorkflowWorldPlugin() {}`,``].join(`
13
13
  `)}function createDevelopmentWorkflowWorldPluginSource(e){if(!usesParentDevelopmentWorkflowWorld(e.configuredWorld))return createWorkflowWorldPluginSource({...e,defaultWorld:`local`});let t=resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`),n=resolvePackageSourceFilePath(`src/internal/workflow/development-world-client.ts`);return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(e.compiledArtifactsBootstrapPath)};`,`import { getWorld, setWorld } from ${stringifyEsmImportSpecifier(t)};`,`import { createDevelopmentWorkflowWorld } from ${stringifyEsmImportSpecifier(n)};`,``,`setWorld(createDevelopmentWorkflowWorld());`,`await getWorld();`,``,`export default function installDevelopmentWorkflowWorldPlugin() {}`,``].join(`
14
- `)}function createInstrumentationPluginSource(e){let t=JSON.stringify(e.agentName);if(e.layout.kind===`module-map`){let n=resolvePackageSourceFilePath(`src/harness/instrumentation/config.ts`);return[`// Generated by eve. Do not edit by hand.`,`import { moduleMap } from ${stringifyEsmImportSpecifier(e.layout.moduleMapPath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(n)};`,``,`const instrumentationModule = moduleMap.nodes["__root__"].modules[${JSON.stringify(e.layout.sourceId)}];`,`if (instrumentationModule.default != null) {`,` await registerInstrumentationConfig(instrumentationModule.default, { agentName: ${t} });`,`}`,``,`export default function installInstrumentationPlugin() {}`,``].join(`
15
- `)}if(e.layout.kind===`file`){let n=resolvePackageSourceFilePath(`src/harness/instrumentation/config.ts`);return[`// Generated by eve. Do not edit by hand.`,`import * as instrumentationModule from ${stringifyEsmImportSpecifier(e.layout.modulePath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(n)};`,``,`if (instrumentationModule.default != null) {`,` await registerInstrumentationConfig(instrumentationModule.default, { agentName: ${t} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
16
- `)}let n=resolvePackageSourceFilePath(`src/harness/instrumentation/providers.ts`),r=Object.entries(e.layout.modulePathsBySlot);return[`// Generated by eve. Do not edit by hand.`,...r.map(([e,t],n)=>`import * as provider${n} from ${stringifyEsmImportSpecifier(t)}; // ${e}`),`import { finalizeInstrumentationProviders, registerInstrumentationProvider, seedInstrumentationProviders, shutdownInstrumentationProviders } from ${stringifyEsmImportSpecifier(n)};`,``,`seedInstrumentationProviders();`,``,...r.flatMap(([e],n)=>[`await registerInstrumentationProvider({`,` agentName: ${t},`,` slot: ${JSON.stringify(e)},`,` value: provider${n}.default,`,`});`]),``,`finalizeInstrumentationProviders({ serviceName: ${t} });`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin(nitroApp) {`,` // The last point a buffered exporter can still reach the network.`,` nitroApp?.hooks?.hook('close', async () => {`,` await shutdownInstrumentationProviders();`,` });`,`}`,``].join(`
14
+ `)}function createInstrumentationPluginSource(e){let t=JSON.stringify(e.agentName);if(e.layout.kind===`module-map`){let n=resolvePackageSourceFilePath(`src/instrumentation/config.ts`);return[`// Generated by eve. Do not edit by hand.`,`import { moduleMap } from ${stringifyEsmImportSpecifier(e.layout.moduleMapPath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(n)};`,``,`const instrumentationModule = moduleMap.nodes["__root__"].modules[${JSON.stringify(e.layout.sourceId)}];`,`if (instrumentationModule.default != null) {`,` await registerInstrumentationConfig(instrumentationModule.default, { agentName: ${t} });`,`}`,``,`export default function installInstrumentationPlugin() {}`,``].join(`
15
+ `)}if(e.layout.kind===`file`){let n=resolvePackageSourceFilePath(`src/instrumentation/config.ts`);return[`// Generated by eve. Do not edit by hand.`,`import * as instrumentationModule from ${stringifyEsmImportSpecifier(e.layout.modulePath)};`,`import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(n)};`,``,`if (instrumentationModule.default != null) {`,` await registerInstrumentationConfig(instrumentationModule.default, { agentName: ${t} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
16
+ `)}let n=resolvePackageSourceFilePath(`src/instrumentation/providers.ts`),r=Object.entries(e.layout.modulePathsBySlot);return[`// Generated by eve. Do not edit by hand.`,...r.map(([e,t],n)=>`import * as provider${n} from ${stringifyEsmImportSpecifier(t)}; // ${e}`),`import { finalizeInstrumentationProviders, registerInstrumentationProvider, seedInstrumentationProviders, shutdownInstrumentationProviders } from ${stringifyEsmImportSpecifier(n)};`,``,`seedInstrumentationProviders();`,``,...r.flatMap(([e],n)=>[`await registerInstrumentationProvider({`,` agentName: ${t},`,` slot: ${JSON.stringify(e)},`,` value: provider${n}.default,`,`});`]),``,`finalizeInstrumentationProviders({ serviceName: ${t} });`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin(nitroApp) {`,` // The last point a buffered exporter can still reach the network.`,` nitroApp?.hooks?.hook('close', async () => {`,` await shutdownInstrumentationProviders();`,` });`,`}`,``].join(`
17
17
  `)}export{createCompiledArtifactsBootstrapSource,createDevelopmentWorkflowWorldPluginSource,createWorkflowWorldPluginSource,writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles};
@@ -1 +1 @@
1
- import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.47.3`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
1
+ import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.47.5`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
@@ -1 +1 @@
1
- import{expectObjectRecord,expectOnlyKnownKeys}from"#internal/authored-module.js";import{parseJsonValue}from"#shared/json.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";const KNOWN_TOP_LEVEL_KEYS=[`approval`,`auth`,`description`,`headers`,`toolCall`,`tools`,`url`],KNOWN_OPENAPI_TOP_LEVEL_KEYS=[`approval`,`auth`,`baseUrl`,`description`,`headers`,`operations`,`spec`,`toolCall`],KNOWN_AUTHORIZATION_KEYS=[`completeAuthorization`,`evict`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`],KNOWN_TOOL_CALL_KEYS=[`providedArguments`];function normalizeMcpClientConnectionDefinition(n,r){let o=expectObjectRecord(n,r);expectOnlyKnownKeys(o,KNOWN_TOP_LEVEL_KEYS,r),validateUrl(o,r),validateDescription(o,r);let s=normalizeAuthorization(o,r),c=normalizeHeaders(o,r),l=normalizeConnectionToolCall(o,r),u=normalizeToolFilter(o,r);if(s!==void 0&&c!==void 0&&typeof c!=`function`&&Object.keys(c).some(e=>e.toLowerCase()===`authorization`))throw Error(`${r} "headers" must not include an "Authorization" key when "auth" is also provided.`);let d={description:o.description,url:o.url};return s!==void 0&&(d.auth=s),c!==void 0&&(d.headers=c),l!==void 0&&(d.toolCall=l),u!==void 0&&(d.tools=u),o.approval!==void 0&&(d.approval=normalizeApproval(o.approval,r)),d}function normalizeConnectionToolCall(r,i){if(r.toolCall===void 0)return;let a=expectObjectRecord(r.toolCall,`${i} The "toolCall" field must be a plain object.`);if(expectOnlyKnownKeys(a,KNOWN_TOOL_CALL_KEYS,`${i} The "toolCall" field`),a.providedArguments===void 0)return{};let o=expectObjectRecord(a.providedArguments,`${i} The "toolCall.providedArguments" field must be a plain object.`);for(let[e,t]of Object.entries(o))if(typeof t!=`function`&&!(typeof t==`object`&&t&&typeof t.then==`function`))try{parseJsonValue(t)}catch{throw Error(`${i} The "toolCall.providedArguments.${e}" value must be JSON-serializable, a Promise, or a function.`)}return{providedArguments:o}}function normalizeOpenApiConnectionDefinition(n,r){let a=expectObjectRecord(n,r);expectOnlyKnownKeys(a,KNOWN_OPENAPI_TOP_LEVEL_KEYS,r),validateSpec(a,r),validateBaseUrl(a,r),validateDescription(a,r);let s=normalizeAuthorization(a,r),c=normalizeHeaders(a,r),l=normalizeFilterField(a,`operations`,r),u=normalizeConnectionToolCall(a,r);if(s!==void 0&&c!==void 0&&typeof c!=`function`&&Object.keys(c).some(e=>e.toLowerCase()===`authorization`))throw Error(`${r} "headers" must not include an "Authorization" key when "auth" is also provided.`);let d={description:a.description,spec:a.spec};return a.baseUrl!==void 0&&(d.baseUrl=a.baseUrl),s!==void 0&&(d.auth=s),c!==void 0&&(d.headers=c),u!==void 0&&(d.toolCall=u),l!==void 0&&(d.operations=l),a.approval!==void 0&&(d.approval=normalizeApproval(a.approval,r)),d}function validateSpec(e,t){let n=e.spec;if(typeof n==`string`){if(!URL.canParse(n))throw Error(`${t} The "spec" field must be a valid URL when provided as a string.`);let e=new URL(n);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw Error(`${t} The "spec" URL must use the http or https protocol, got "${e.protocol}".`);return}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`${t} The "spec" field must be a URL string or an inline OpenAPI document object.`)}function validateBaseUrl(e,t){if(e.baseUrl===void 0)return;if(typeof e.baseUrl!=`string`||!URL.canParse(e.baseUrl))throw Error(`${t} The "baseUrl" field must be a valid URL when provided.`);let n=new URL(e.baseUrl);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "baseUrl" field must use the http or https protocol, got "${n.protocol}".`)}function validateUrl(e,t){if(typeof e.url!=`string`||!URL.canParse(e.url))throw Error(`${t} The "url" field must be a valid URL.`);let n=new URL(e.url);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "url" field must use the http or https protocol, got "${n.protocol}".`)}function validateDescription(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function normalizeAuthorization(n,i){if(n.auth===void 0)return;if(typeof n.auth==`function`)return n.auth;let a=expectObjectRecord(n.auth,`${i} The "auth" field must be an object with a "getToken" method or a function.`);return expectOnlyKnownKeys(a,KNOWN_AUTHORIZATION_KEYS,`${i} The "auth" field`),normalizeAuthorizationSpec(a,i)}function normalizeHeaders(e,t){if(e.headers===void 0)return;if(typeof e.headers==`function`)return e.headers;if(typeof e.headers!=`object`||e.headers===null||Array.isArray(e.headers))throw Error(`${t} The "headers" field must be a plain object or a function.`);let n=e.headers;for(let[e,r]of Object.entries(n)){let n=typeof r;if(n!==`string`&&n!==`function`&&n!==`object`||n===`object`&&(r===null||typeof r.then!=`function`))throw Error(`${t} The "headers.${e}" value must be a string, Promise, or function.`)}return n}function normalizeToolFilter(e,t){return normalizeFilterField(e,`tools`,t)}function normalizeFilterField(e,t,n){let r=e[t];if(r===void 0)return;if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);let i=r,a=`allow`in i,o=`block`in i;if(a&&o)throw Error(`${n} The "${t}" field must specify either "allow" or "block", not both.`);if(!a&&!o)throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);return a?(validateStringArray(i.allow,`${n} The "${t}.allow"`),{allow:i.allow}):(validateStringArray(i.block,`${n} The "${t}.block"`),{block:i.block})}function validateStringArray(e,t){if(!Array.isArray(e))throw Error(`${t} field must be an array of strings.`);for(let n=0;n<e.length;n++)if(typeof e[n]!=`string`)throw Error(`${t}[${n}] must be a string.`)}export{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition};
1
+ import{expectObjectRecord,expectOnlyKnownKeys}from"#internal/authored-module.js";import{parseJsonValue}from"#shared/json.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";const KNOWN_TOP_LEVEL_KEYS=[`approval`,`auth`,`description`,`headers`,`instanceKey`,`toolCall`,`tools`,`url`],KNOWN_OPENAPI_TOP_LEVEL_KEYS=[`approval`,`auth`,`baseUrl`,`description`,`headers`,`instanceKey`,`operations`,`spec`,`toolCall`],KNOWN_AUTHORIZATION_KEYS=[`completeAuthorization`,`evict`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`],KNOWN_TOOL_CALL_KEYS=[`providedArguments`];function normalizeMcpClientConnectionDefinition(n,r){let o=expectObjectRecord(n,r);expectOnlyKnownKeys(o,KNOWN_TOP_LEVEL_KEYS,r),validateUrl(o,r),validateDescription(o,r),validateInstanceKey(o,r);let s=normalizeAuthorization(o,r),c=normalizeHeaders(o,r),l=normalizeConnectionToolCall(o,r),u=normalizeToolFilter(o,r);if(s!==void 0&&c!==void 0&&typeof c!=`function`&&Object.keys(c).some(e=>e.toLowerCase()===`authorization`))throw Error(`${r} "headers" must not include an "Authorization" key when "auth" is also provided.`);let d={description:o.description,url:o.url};return o.instanceKey!==void 0&&(d.instanceKey=o.instanceKey),s!==void 0&&(d.auth=s),c!==void 0&&(d.headers=c),l!==void 0&&(d.toolCall=l),u!==void 0&&(d.tools=u),o.approval!==void 0&&(d.approval=normalizeApproval(o.approval,r)),d}function normalizeConnectionToolCall(r,i){if(r.toolCall===void 0)return;let a=expectObjectRecord(r.toolCall,`${i} The "toolCall" field must be a plain object.`);if(expectOnlyKnownKeys(a,KNOWN_TOOL_CALL_KEYS,`${i} The "toolCall" field`),a.providedArguments===void 0)return{};let o=expectObjectRecord(a.providedArguments,`${i} The "toolCall.providedArguments" field must be a plain object.`);for(let[e,t]of Object.entries(o))if(typeof t!=`function`&&!(typeof t==`object`&&t&&typeof t.then==`function`))try{parseJsonValue(t)}catch{throw Error(`${i} The "toolCall.providedArguments.${e}" value must be JSON-serializable, a Promise, or a function.`)}return{providedArguments:o}}function normalizeOpenApiConnectionDefinition(n,r){let a=expectObjectRecord(n,r);expectOnlyKnownKeys(a,KNOWN_OPENAPI_TOP_LEVEL_KEYS,r),validateSpec(a,r),validateBaseUrl(a,r),validateDescription(a,r),validateInstanceKey(a,r);let s=normalizeAuthorization(a,r),c=normalizeHeaders(a,r),l=normalizeFilterField(a,`operations`,r),u=normalizeConnectionToolCall(a,r);if(s!==void 0&&c!==void 0&&typeof c!=`function`&&Object.keys(c).some(e=>e.toLowerCase()===`authorization`))throw Error(`${r} "headers" must not include an "Authorization" key when "auth" is also provided.`);let d={description:a.description,spec:a.spec};return a.baseUrl!==void 0&&(d.baseUrl=a.baseUrl),a.instanceKey!==void 0&&(d.instanceKey=a.instanceKey),s!==void 0&&(d.auth=s),c!==void 0&&(d.headers=c),u!==void 0&&(d.toolCall=u),l!==void 0&&(d.operations=l),a.approval!==void 0&&(d.approval=normalizeApproval(a.approval,r)),d}function validateSpec(e,t){let n=e.spec;if(typeof n==`string`){if(!URL.canParse(n))throw Error(`${t} The "spec" field must be a valid URL when provided as a string.`);let e=new URL(n);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw Error(`${t} The "spec" URL must use the http or https protocol, got "${e.protocol}".`);return}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`${t} The "spec" field must be a URL string or an inline OpenAPI document object.`)}function validateBaseUrl(e,t){if(e.baseUrl===void 0)return;if(typeof e.baseUrl!=`string`||!URL.canParse(e.baseUrl))throw Error(`${t} The "baseUrl" field must be a valid URL when provided.`);let n=new URL(e.baseUrl);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "baseUrl" field must use the http or https protocol, got "${n.protocol}".`)}function validateUrl(e,t){if(typeof e.url!=`string`||!URL.canParse(e.url))throw Error(`${t} The "url" field must be a valid URL.`);let n=new URL(e.url);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "url" field must use the http or https protocol, got "${n.protocol}".`)}function validateDescription(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function validateInstanceKey(e,t){if(e.instanceKey!==void 0&&(typeof e.instanceKey!=`string`||e.instanceKey.length===0))throw Error(`${t} The "instanceKey" field must be a non-empty string.`)}function normalizeAuthorization(n,i){if(n.auth===void 0)return;if(typeof n.auth==`function`)return n.auth;let a=expectObjectRecord(n.auth,`${i} The "auth" field must be an object with a "getToken" method or a function.`);return expectOnlyKnownKeys(a,KNOWN_AUTHORIZATION_KEYS,`${i} The "auth" field`),normalizeAuthorizationSpec(a,i)}function normalizeHeaders(e,t){if(e.headers===void 0)return;if(typeof e.headers==`function`)return e.headers;if(typeof e.headers!=`object`||e.headers===null||Array.isArray(e.headers))throw Error(`${t} The "headers" field must be a plain object or a function.`);let n=e.headers;for(let[e,r]of Object.entries(n)){let n=typeof r;if(n!==`string`&&n!==`function`&&n!==`object`||n===`object`&&(r===null||typeof r.then!=`function`))throw Error(`${t} The "headers.${e}" value must be a string, Promise, or function.`)}return n}function normalizeToolFilter(e,t){return normalizeFilterField(e,`tools`,t)}function normalizeFilterField(e,t,n){let r=e[t];if(r===void 0)return;if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);let i=r,a=`allow`in i,o=`block`in i;if(a&&o)throw Error(`${n} The "${t}" field must specify either "allow" or "block", not both.`);if(!a&&!o)throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);return a?(validateStringArray(i.allow,`${n} The "${t}.allow"`),{allow:i.allow}):(validateStringArray(i.block,`${n} The "${t}.block"`),{block:i.block})}function validateStringArray(e,t){if(!Array.isArray(e))throw Error(`${t} field must be an array of strings.`);for(let n=0;n<e.length;n++)if(typeof e[n]!=`string`)throw Error(`${t}[${n}] must be a string.`)}export{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition};