eve 0.24.6 → 0.25.0

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 (147) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/src/chunks/{use-eve-agent-6BO9gFVq.js → use-eve-agent-CQIeqmKc.js} +69 -64
  3. package/dist/src/chunks/{use-eve-agent-B1MJNRE-.js → use-eve-agent-Cy73lgA6.js} +69 -64
  4. package/dist/src/cli/commands/agent-instructions.js +1 -1
  5. package/dist/src/cli/commands/channels.js +1 -1
  6. package/dist/src/cli/commands/extension-build.d.ts +1 -1
  7. package/dist/src/cli/commands/extension-build.js +1 -1
  8. package/dist/src/client/output-schema.d.ts +0 -7
  9. package/dist/src/client/output-schema.js +1 -1
  10. package/dist/src/client/session.js +1 -1
  11. package/dist/src/compiler/extension-compatibility.d.ts +56 -0
  12. package/dist/src/compiler/extension-compatibility.js +1 -0
  13. package/dist/src/compiler/normalize-agent-config.js +1 -1
  14. package/dist/src/compiler/normalize-subagent.js +1 -1
  15. package/dist/src/context/build-dynamic-tools.js +1 -1
  16. package/dist/src/context/dynamic-tool-lifecycle.d.ts +1 -1
  17. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  18. package/dist/src/discover/discover-agent.d.ts +29 -7
  19. package/dist/src/discover/discover-agent.js +1 -1
  20. package/dist/src/discover/extensions.d.ts +43 -8
  21. package/dist/src/discover/extensions.js +1 -1
  22. package/dist/src/discover/filesystem.d.ts +3 -1
  23. package/dist/src/discover/filesystem.js +1 -1
  24. package/dist/src/discover/named-source-directory.js +1 -1
  25. package/dist/src/discover/skills.js +1 -1
  26. package/dist/src/evals/autoevals-client.js +2 -2
  27. package/dist/src/execution/node-step.js +1 -1
  28. package/dist/src/execution/sandbox/bindings/docker.js +1 -1
  29. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +1 -1
  30. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
  31. package/dist/src/execution/sandbox/bindings/microsandbox-templates.js +1 -1
  32. package/dist/src/execution/sandbox/development-cleanup.d.ts +1 -1
  33. package/dist/src/execution/sandbox/development-cleanup.js +1 -1
  34. package/dist/src/execution/sandbox/development-run.d.ts +0 -3
  35. package/dist/src/execution/sandbox/development-run.js +1 -1
  36. package/dist/src/execution/sandbox/ensure.js +1 -1
  37. package/dist/src/execution/subagent-tool.js +1 -1
  38. package/dist/src/harness/emission.js +1 -1
  39. package/dist/src/harness/input-extraction.d.ts +10 -1
  40. package/dist/src/harness/input-extraction.js +1 -1
  41. package/dist/src/harness/input-requests.d.ts +12 -2
  42. package/dist/src/harness/input-requests.js +1 -1
  43. package/dist/src/harness/messages.d.ts +8 -1
  44. package/dist/src/harness/messages.js +1 -1
  45. package/dist/src/harness/stale-input-responses.d.ts +26 -0
  46. package/dist/src/harness/stale-input-responses.js +3 -0
  47. package/dist/src/harness/step-hooks.d.ts +1 -12
  48. package/dist/src/harness/step-hooks.js +1 -1
  49. package/dist/src/harness/tool-call-input-errors.d.ts +11 -0
  50. package/dist/src/harness/tool-call-input-errors.js +1 -1
  51. package/dist/src/harness/tool-loop.js +2 -2
  52. package/dist/src/harness/workflow-sandbox.d.ts +1 -1
  53. package/dist/src/harness/workflow-sandbox.js +1 -1
  54. package/dist/src/internal/application/optional-package-install.d.ts +5 -0
  55. package/dist/src/internal/application/optional-package-install.js +1 -1
  56. package/dist/src/internal/application/package.js +1 -1
  57. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  58. package/dist/src/internal/authored-module-loader.d.ts +17 -0
  59. package/dist/src/internal/authored-module-loader.js +2 -2
  60. package/dist/src/internal/authored-module-map-loader.js +1 -1
  61. package/dist/src/internal/authored-package-boundary.d.ts +8 -0
  62. package/dist/src/internal/authored-package-boundary.js +1 -1
  63. package/dist/src/internal/nitro/dev-runtime-source-snapshot.d.ts +4 -0
  64. package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
  65. package/dist/src/internal/nitro/host/build-extension.d.ts +6 -21
  66. package/dist/src/internal/nitro/host/build-extension.js +2 -4
  67. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -1
  68. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  69. package/dist/src/internal/nitro/host/dev-workspace-extensions.d.ts +18 -0
  70. package/dist/src/internal/nitro/host/dev-workspace-extensions.js +1 -0
  71. package/dist/src/internal/nitro/host/extension-build-config.d.ts +18 -0
  72. package/dist/src/internal/nitro/host/extension-build-config.js +1 -0
  73. package/dist/src/internal/nitro/host/extension-capability-requirements.d.ts +10 -0
  74. package/dist/src/internal/nitro/host/extension-capability-requirements.js +1 -0
  75. package/dist/src/internal/nitro/host/extension-declarations.d.ts +10 -0
  76. package/dist/src/internal/nitro/host/extension-declarations.js +2 -0
  77. package/dist/src/internal/nitro/host/extension-distribution.d.ts +32 -0
  78. package/dist/src/internal/nitro/host/extension-distribution.js +3 -0
  79. package/dist/src/internal/nitro/host/extension-state-usage.d.ts +7 -0
  80. package/dist/src/internal/nitro/host/extension-state-usage.js +1 -0
  81. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +5 -1
  82. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  83. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  84. package/dist/src/internal/nitro/host/types.d.ts +2 -0
  85. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  86. package/dist/src/public/definitions/tool.d.ts +2 -2
  87. package/dist/src/public/tools/internal.js +1 -1
  88. package/dist/src/runtime/agent/mock-model-fixtures.js +2 -2
  89. package/dist/src/runtime/connections/openapi-client.js +1 -1
  90. package/dist/src/runtime/framework-tools/ask-question.d.ts +23 -9
  91. package/dist/src/runtime/framework-tools/ask-question.js +1 -1
  92. package/dist/src/runtime/framework-tools/bash.d.ts +10 -3
  93. package/dist/src/runtime/framework-tools/bash.js +1 -1
  94. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
  95. package/dist/src/runtime/framework-tools/final-output.d.ts +1 -1
  96. package/dist/src/runtime/framework-tools/final-output.js +1 -1
  97. package/dist/src/runtime/framework-tools/glob.d.ts +12 -3
  98. package/dist/src/runtime/framework-tools/glob.js +1 -1
  99. package/dist/src/runtime/framework-tools/grep.d.ts +16 -3
  100. package/dist/src/runtime/framework-tools/grep.js +1 -1
  101. package/dist/src/runtime/framework-tools/read-file.d.ts +13 -3
  102. package/dist/src/runtime/framework-tools/read-file.js +1 -1
  103. package/dist/src/runtime/framework-tools/skill.d.ts +5 -2
  104. package/dist/src/runtime/framework-tools/skill.js +1 -1
  105. package/dist/src/runtime/framework-tools/todo.d.ts +57 -10
  106. package/dist/src/runtime/framework-tools/todo.js +3 -3
  107. package/dist/src/runtime/framework-tools/web-fetch.d.ts +16 -3
  108. package/dist/src/runtime/framework-tools/web-fetch.js +1 -1
  109. package/dist/src/runtime/framework-tools/write-file.d.ts +9 -3
  110. package/dist/src/runtime/framework-tools/write-file.js +1 -1
  111. package/dist/src/runtime/loaders/compile-metadata.js +1 -1
  112. package/dist/src/runtime/loaders/manifest.js +1 -1
  113. package/dist/src/runtime/loaders/module-map.js +1 -1
  114. package/dist/src/runtime/resolve-tool.d.ts +4 -5
  115. package/dist/src/runtime/resolve-tool.js +1 -1
  116. package/dist/src/runtime/subagents/registry.d.ts +6 -3
  117. package/dist/src/runtime/subagents/registry.js +1 -1
  118. package/dist/src/runtime/tools/registry.js +1 -1
  119. package/dist/src/runtime/types.d.ts +7 -9
  120. package/dist/src/setup/boxes/deploy-project.d.ts +11 -1
  121. package/dist/src/setup/boxes/deploy-project.js +1 -1
  122. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  123. package/dist/src/setup/scaffold/create/extension.js +2 -2
  124. package/dist/src/setup/scaffold/create/project.js +2 -2
  125. package/dist/src/setup/scaffold/update/channels.js +1 -1
  126. package/dist/src/setup/scaffold/update/connections.js +1 -1
  127. package/dist/src/setup/vercel-project-framework.d.ts +4 -2
  128. package/dist/src/shared/extension-package-contract.d.ts +11 -0
  129. package/dist/src/shared/extension-package-contract.js +1 -0
  130. package/dist/src/shared/json.d.ts +4 -0
  131. package/dist/src/shared/json.js +1 -1
  132. package/dist/src/shared/tool-schema.d.ts +52 -0
  133. package/dist/src/shared/tool-schema.js +1 -0
  134. package/dist/src/svelte/index.js +1 -1
  135. package/dist/src/svelte/use-eve-agent.js +1 -1
  136. package/dist/src/vue/index.js +1 -1
  137. package/dist/src/vue/use-eve-agent.js +1 -1
  138. package/docs/concepts/sessions-runs-and-streaming.md +6 -0
  139. package/docs/extensions.md +22 -6
  140. package/docs/reference/cli.md +2 -2
  141. package/package.json +1 -1
  142. package/dist/src/internal/json-schema.d.ts +0 -1
  143. package/dist/src/internal/json-schema.js +0 -1
  144. package/dist/src/setup/boxes/reconcile-host-framework-preset.d.ts +0 -26
  145. package/dist/src/setup/boxes/reconcile-host-framework-preset.js +0 -1
  146. package/dist/src/shared/json-schema.d.ts +0 -9
  147. package/dist/src/shared/json-schema.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # eve
2
2
 
3
+ ## 0.25.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b9bb8b2: Scaffold extensions with separate source and dist roots, a required wildcard eve peer, and dist-only publication. `eve extension build` now emits an agent-shaped JavaScript distribution with declarations, assets, and capability compatibility metadata instead of requiring author TypeScript in the published package.
8
+
9
+ ### Patch Changes
10
+
11
+ - 29ecffc: Build mounted source-backed workspace extensions before `eve dev` compiles the agent, then rebuild only the affected extension when its source changes. Failed extension builds keep the previous dist and active development generation serving.
12
+ - 46b78b8: Stop development microsandboxes on `eve dev` shutdown by discovering resources from their run labels and loading the application's installed microsandbox version during cleanup.
13
+ - 6a5a36a: Deliver stale HITL responses — answers to a question or approval that is no longer pending — as a new user message, letting the model decide whether the old selection still matters. A stale approval never authorizes the earlier tool call.
14
+ - f7c69b1: The Vercel Framework Preset is now reconciled with the host framework on disk when running `/deploy` via the TUI.
15
+ - bbec675: Extensions installed with a registry-style store layout (e.g. from npm with pnpm) now work in `eve dev` and `eve eval`. Extension modules reached through a node_modules symlink resolve their dependencies from the package's real location — matching standard resolver semantics — instead of failing with `UNRESOLVED_IMPORT`/`ERR_MODULE_NOT_FOUND` or silently picking up another copy of the dependency from the consuming app.
16
+ - 14501dc: Every eve-owned tool input is now validated against its schema before execution, so invalid calls are returned to the model for retry instead of failing the run. Subagent calls treat an empty `outputSchema` as absent, and OpenAPI operations with invalid schemas are omitted with a warning.
17
+
3
18
  ## 0.24.6
4
19
 
5
20
  ### Patch Changes
@@ -302,71 +302,8 @@ const CancelTurnResponseSchema = z.object({
302
302
  status: z.enum(["accepted", "no_active_turn"])
303
303
  });
304
304
 
305
- //#endregion
306
- //#region src/shared/json.ts
307
- const INVALID_JSON_VALUE_CANDIDATE = Symbol("invalid-json-value-candidate");
308
- const JSON_VALUE_ERROR_MESSAGE = "Expected a JSON-serializable value.";
309
- const JSON_OBJECT_ERROR_MESSAGE = "Expected a JSON-serializable object.";
310
- function parseJsonValue(value) {
311
- const normalized = normalizeJsonValueCandidate(value);
312
- if (normalized === INVALID_JSON_VALUE_CANDIDATE) throw new TypeError(JSON_VALUE_ERROR_MESSAGE);
313
- return normalized;
314
- }
315
- function parseJsonObject(value) {
316
- const normalized = parseJsonValue(value);
317
- if (!isJsonObjectValue(normalized)) throw new TypeError(JSON_OBJECT_ERROR_MESSAGE);
318
- return normalized;
319
- }
320
- function normalizeJsonValueCandidate(value, seen = /* @__PURE__ */ new WeakSet()) {
321
- if (value === null || typeof value === "boolean" || typeof value === "string") return value;
322
- if (typeof value === "number") return Number.isFinite(value) ? value : INVALID_JSON_VALUE_CANDIDATE;
323
- if (Array.isArray(value)) {
324
- const normalizedItems = [];
325
- for (const item of value) {
326
- const normalizedItem = normalizeJsonValueCandidate(item, seen);
327
- if (normalizedItem === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
328
- normalizedItems.push(normalizedItem);
329
- }
330
- return normalizedItems;
331
- }
332
- if (typeof value !== "object" || value === void 0) return INVALID_JSON_VALUE_CANDIDATE;
333
- if (!isPlainObject(value)) return INVALID_JSON_VALUE_CANDIDATE;
334
- if (seen.has(value)) return INVALID_JSON_VALUE_CANDIDATE;
335
- seen.add(value);
336
- const normalized = {};
337
- for (const [key, entry] of Object.entries(value)) {
338
- if (entry === void 0) continue;
339
- const normalizedEntry = normalizeJsonValueCandidate(entry, seen);
340
- if (normalizedEntry === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
341
- normalized[key] = normalizedEntry;
342
- }
343
- seen.delete(value);
344
- return normalized;
345
- }
346
- function isJsonObjectValue(value) {
347
- return value !== null && !Array.isArray(value) && typeof value === "object";
348
- }
349
- function isPlainObject(value) {
350
- const prototype = Object.getPrototypeOf(value);
351
- return prototype === null || prototype === Object.prototype;
352
- }
353
-
354
- //#endregion
355
- //#region src/shared/json-schema.ts
356
- const STANDARD_JSON_SCHEMA_TARGET = "draft-07";
357
- function normalizeJsonSchemaDefinition(value, direction = "input") {
358
- if (isStandardSchema(value)) return parseJsonObject(value["~standard"].jsonSchema[direction]({ target: STANDARD_JSON_SCHEMA_TARGET }));
359
- return parseJsonObject(value);
360
- }
361
- function isStandardSchema(value) {
362
- return value !== null && typeof value === "object" && "~standard" in value;
363
- }
364
-
365
305
  //#endregion
366
306
  //#region src/client/output-schema.ts
367
- function normalizeOutputSchemaForRequest(schema) {
368
- return schema === void 0 ? void 0 : normalizeJsonSchemaDefinition(schema, "output");
369
- }
370
307
  function extractCompletedResult(events) {
371
308
  let result;
372
309
  for (const event of events) if (isResultCompletedEvent(event)) result = event.data.result;
@@ -588,6 +525,74 @@ async function sleep$1(ms) {
588
525
  await new Promise((resolve) => setTimeout(resolve, ms));
589
526
  }
590
527
 
528
+ //#endregion
529
+ //#region src/shared/json.ts
530
+ const INVALID_JSON_VALUE_CANDIDATE = Symbol("invalid-json-value-candidate");
531
+ const JSON_VALUE_ERROR_MESSAGE = "Expected a JSON-serializable value.";
532
+ const JSON_OBJECT_ERROR_MESSAGE = "Expected a JSON-serializable object.";
533
+ function parseJsonValue(value) {
534
+ const normalized = normalizeJsonValueCandidate(value);
535
+ if (normalized === INVALID_JSON_VALUE_CANDIDATE) throw new TypeError(JSON_VALUE_ERROR_MESSAGE);
536
+ return normalized;
537
+ }
538
+ function parseJsonObject(value) {
539
+ const normalized = parseJsonValue(value);
540
+ if (!isJsonObjectValue(normalized)) throw new TypeError(JSON_OBJECT_ERROR_MESSAGE);
541
+ return normalized;
542
+ }
543
+ function normalizeJsonValueCandidate(value, seen = /* @__PURE__ */ new WeakSet()) {
544
+ if (value === null || typeof value === "boolean" || typeof value === "string") return value;
545
+ if (typeof value === "number") return Number.isFinite(value) ? value : INVALID_JSON_VALUE_CANDIDATE;
546
+ if (Array.isArray(value)) {
547
+ const normalizedItems = [];
548
+ for (const item of value) {
549
+ const normalizedItem = normalizeJsonValueCandidate(item, seen);
550
+ if (normalizedItem === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
551
+ normalizedItems.push(normalizedItem);
552
+ }
553
+ return normalizedItems;
554
+ }
555
+ if (typeof value !== "object" || value === void 0) return INVALID_JSON_VALUE_CANDIDATE;
556
+ if (!isPlainObject(value)) return INVALID_JSON_VALUE_CANDIDATE;
557
+ if (seen.has(value)) return INVALID_JSON_VALUE_CANDIDATE;
558
+ seen.add(value);
559
+ const normalized = {};
560
+ for (const [key, entry] of Object.entries(value)) {
561
+ if (entry === void 0) continue;
562
+ const normalizedEntry = normalizeJsonValueCandidate(entry, seen);
563
+ if (normalizedEntry === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
564
+ normalized[key] = normalizedEntry;
565
+ }
566
+ seen.delete(value);
567
+ return normalized;
568
+ }
569
+ function isJsonObjectValue(value) {
570
+ return value !== null && !Array.isArray(value) && typeof value === "object";
571
+ }
572
+ function isPlainObject(value) {
573
+ const prototype = Object.getPrototypeOf(value);
574
+ return prototype === null || prototype === Object.prototype;
575
+ }
576
+
577
+ //#endregion
578
+ //#region src/shared/tool-schema.ts
579
+ const JSON_SCHEMA_TARGET = "draft-07";
580
+ function serializeOutputSchema(source) {
581
+ return serializeSchema(source, "output");
582
+ }
583
+ const UNSPECIFIED_INPUT_SCHEMA = z.fromJSONSchema({});
584
+ function serializeSchema(source, direction) {
585
+ if (source === null || source === void 0) return source;
586
+ return toJsonObject(source, direction);
587
+ }
588
+ function toJsonObject(source, direction) {
589
+ const { $schema: _schemaVersion, ...canonical } = isStandardJsonSchema(source) ? parseJsonObject(source["~standard"].jsonSchema[direction]({ target: JSON_SCHEMA_TARGET })) : parseJsonObject(source);
590
+ return canonical;
591
+ }
592
+ function isStandardJsonSchema(value) {
593
+ return value !== null && typeof value === "object" && "~standard" in value;
594
+ }
595
+
591
596
  //#endregion
592
597
  //#region src/client/session.ts
593
598
  const DELIVER_RETRY_ATTEMPTS = 10;
@@ -654,7 +659,7 @@ var ClientSession = class {
654
659
  headers.set("content-type", "application/json");
655
660
  const body = createHandleMessageBody({
656
661
  input,
657
- outputSchema: normalizeOutputSchemaForRequest(input.outputSchema),
662
+ outputSchema: serializeOutputSchema(input.outputSchema),
658
663
  session
659
664
  });
660
665
  if (body === null) throw new Error("Session.send requires a non-empty message, inputResponses, or both.");
@@ -302,71 +302,8 @@ const CancelTurnResponseSchema = z.object({
302
302
  status: z.enum(["accepted", "no_active_turn"])
303
303
  });
304
304
 
305
- //#endregion
306
- //#region src/shared/json.ts
307
- const INVALID_JSON_VALUE_CANDIDATE = Symbol("invalid-json-value-candidate");
308
- const JSON_VALUE_ERROR_MESSAGE = "Expected a JSON-serializable value.";
309
- const JSON_OBJECT_ERROR_MESSAGE = "Expected a JSON-serializable object.";
310
- function parseJsonValue(value) {
311
- const normalized = normalizeJsonValueCandidate(value);
312
- if (normalized === INVALID_JSON_VALUE_CANDIDATE) throw new TypeError(JSON_VALUE_ERROR_MESSAGE);
313
- return normalized;
314
- }
315
- function parseJsonObject(value) {
316
- const normalized = parseJsonValue(value);
317
- if (!isJsonObjectValue(normalized)) throw new TypeError(JSON_OBJECT_ERROR_MESSAGE);
318
- return normalized;
319
- }
320
- function normalizeJsonValueCandidate(value, seen = /* @__PURE__ */ new WeakSet()) {
321
- if (value === null || typeof value === "boolean" || typeof value === "string") return value;
322
- if (typeof value === "number") return Number.isFinite(value) ? value : INVALID_JSON_VALUE_CANDIDATE;
323
- if (Array.isArray(value)) {
324
- const normalizedItems = [];
325
- for (const item of value) {
326
- const normalizedItem = normalizeJsonValueCandidate(item, seen);
327
- if (normalizedItem === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
328
- normalizedItems.push(normalizedItem);
329
- }
330
- return normalizedItems;
331
- }
332
- if (typeof value !== "object" || value === void 0) return INVALID_JSON_VALUE_CANDIDATE;
333
- if (!isPlainObject(value)) return INVALID_JSON_VALUE_CANDIDATE;
334
- if (seen.has(value)) return INVALID_JSON_VALUE_CANDIDATE;
335
- seen.add(value);
336
- const normalized = {};
337
- for (const [key, entry] of Object.entries(value)) {
338
- if (entry === void 0) continue;
339
- const normalizedEntry = normalizeJsonValueCandidate(entry, seen);
340
- if (normalizedEntry === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
341
- normalized[key] = normalizedEntry;
342
- }
343
- seen.delete(value);
344
- return normalized;
345
- }
346
- function isJsonObjectValue(value) {
347
- return value !== null && !Array.isArray(value) && typeof value === "object";
348
- }
349
- function isPlainObject(value) {
350
- const prototype = Object.getPrototypeOf(value);
351
- return prototype === null || prototype === Object.prototype;
352
- }
353
-
354
- //#endregion
355
- //#region src/shared/json-schema.ts
356
- const STANDARD_JSON_SCHEMA_TARGET = "draft-07";
357
- function normalizeJsonSchemaDefinition(value, direction = "input") {
358
- if (isStandardSchema(value)) return parseJsonObject(value["~standard"].jsonSchema[direction]({ target: STANDARD_JSON_SCHEMA_TARGET }));
359
- return parseJsonObject(value);
360
- }
361
- function isStandardSchema(value) {
362
- return value !== null && typeof value === "object" && "~standard" in value;
363
- }
364
-
365
305
  //#endregion
366
306
  //#region src/client/output-schema.ts
367
- function normalizeOutputSchemaForRequest(schema) {
368
- return schema === void 0 ? void 0 : normalizeJsonSchemaDefinition(schema, "output");
369
- }
370
307
  function extractCompletedResult(events) {
371
308
  let result;
372
309
  for (const event of events) if (isResultCompletedEvent(event)) result = event.data.result;
@@ -588,6 +525,74 @@ async function sleep$1(ms) {
588
525
  await new Promise((resolve) => setTimeout(resolve, ms));
589
526
  }
590
527
 
528
+ //#endregion
529
+ //#region src/shared/json.ts
530
+ const INVALID_JSON_VALUE_CANDIDATE = Symbol("invalid-json-value-candidate");
531
+ const JSON_VALUE_ERROR_MESSAGE = "Expected a JSON-serializable value.";
532
+ const JSON_OBJECT_ERROR_MESSAGE = "Expected a JSON-serializable object.";
533
+ function parseJsonValue(value) {
534
+ const normalized = normalizeJsonValueCandidate(value);
535
+ if (normalized === INVALID_JSON_VALUE_CANDIDATE) throw new TypeError(JSON_VALUE_ERROR_MESSAGE);
536
+ return normalized;
537
+ }
538
+ function parseJsonObject(value) {
539
+ const normalized = parseJsonValue(value);
540
+ if (!isJsonObjectValue(normalized)) throw new TypeError(JSON_OBJECT_ERROR_MESSAGE);
541
+ return normalized;
542
+ }
543
+ function normalizeJsonValueCandidate(value, seen = /* @__PURE__ */ new WeakSet()) {
544
+ if (value === null || typeof value === "boolean" || typeof value === "string") return value;
545
+ if (typeof value === "number") return Number.isFinite(value) ? value : INVALID_JSON_VALUE_CANDIDATE;
546
+ if (Array.isArray(value)) {
547
+ const normalizedItems = [];
548
+ for (const item of value) {
549
+ const normalizedItem = normalizeJsonValueCandidate(item, seen);
550
+ if (normalizedItem === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
551
+ normalizedItems.push(normalizedItem);
552
+ }
553
+ return normalizedItems;
554
+ }
555
+ if (typeof value !== "object" || value === void 0) return INVALID_JSON_VALUE_CANDIDATE;
556
+ if (!isPlainObject(value)) return INVALID_JSON_VALUE_CANDIDATE;
557
+ if (seen.has(value)) return INVALID_JSON_VALUE_CANDIDATE;
558
+ seen.add(value);
559
+ const normalized = {};
560
+ for (const [key, entry] of Object.entries(value)) {
561
+ if (entry === void 0) continue;
562
+ const normalizedEntry = normalizeJsonValueCandidate(entry, seen);
563
+ if (normalizedEntry === INVALID_JSON_VALUE_CANDIDATE) return INVALID_JSON_VALUE_CANDIDATE;
564
+ normalized[key] = normalizedEntry;
565
+ }
566
+ seen.delete(value);
567
+ return normalized;
568
+ }
569
+ function isJsonObjectValue(value) {
570
+ return value !== null && !Array.isArray(value) && typeof value === "object";
571
+ }
572
+ function isPlainObject(value) {
573
+ const prototype = Object.getPrototypeOf(value);
574
+ return prototype === null || prototype === Object.prototype;
575
+ }
576
+
577
+ //#endregion
578
+ //#region src/shared/tool-schema.ts
579
+ const JSON_SCHEMA_TARGET = "draft-07";
580
+ function serializeOutputSchema(source) {
581
+ return serializeSchema(source, "output");
582
+ }
583
+ const UNSPECIFIED_INPUT_SCHEMA = z.fromJSONSchema({});
584
+ function serializeSchema(source, direction) {
585
+ if (source === null || source === void 0) return source;
586
+ return toJsonObject(source, direction);
587
+ }
588
+ function toJsonObject(source, direction) {
589
+ const { $schema: _schemaVersion, ...canonical } = isStandardJsonSchema(source) ? parseJsonObject(source["~standard"].jsonSchema[direction]({ target: JSON_SCHEMA_TARGET })) : parseJsonObject(source);
590
+ return canonical;
591
+ }
592
+ function isStandardJsonSchema(value) {
593
+ return value !== null && typeof value === "object" && "~standard" in value;
594
+ }
595
+
591
596
  //#endregion
592
597
  //#region src/client/session.ts
593
598
  const DELIVER_RETRY_ATTEMPTS = 10;
@@ -654,7 +659,7 @@ var ClientSession = class {
654
659
  headers.set("content-type", "application/json");
655
660
  const body = createHandleMessageBody({
656
661
  input,
657
- outputSchema: normalizeOutputSchemaForRequest(input.outputSchema),
662
+ outputSchema: serializeOutputSchema(input.outputSchema),
658
663
  session
659
664
  });
660
665
  if (body === null) throw new Error("Session.send requires a non-empty message, inputResponses, or both.");
@@ -1,5 +1,5 @@
1
1
  import{readFileSync}from"node:fs";const SETUP_SECTIONS=[`intro-setup.md`,`collect-intent.md`,`vercel-connect.md`,`scaffold.md`,`build-and-verify.md`],HANDOFF_SECTIONS=[`intro-handoff.md`,`collect-intent.md`,`vercel-connect.md`,`build-and-verify.md`];function compose(t,n){let r=t.map(t=>readFileSync(new URL(`./agent-prompt/${t}`,import.meta.url),`utf8`).trim()).join(`
2
2
 
3
3
  `).replaceAll(`{{devCommand}}`,()=>n.devCommand),{workingDirectory:i}=n;return i===void 0?r:r.replaceAll(`{{workingDirectory}}`,()=>i)}function initAgentInstructions(){return compose(SETUP_SECTIONS,{devCommand:`npx eve dev`})}function initAgentDevHandoff(e){return compose(HANDOFF_SECTIONS,{devCommand:e.devCommand,workingDirectory:e.projectPath})}function initAgentReplPrompt(e){return compose(HANDOFF_SECTIONS,{devCommand:e.devCommand,workingDirectory:`.`})}function initExtensionInstructions(){return[`You are scaffolding an eve extension package (a reusable package of tools,`,`connections, skills, and hooks that a consuming agent mounts under`,`agent/extensions/).`,``,`Ask the user for a package directory name, then run:`,``,` npx eve@latest extension init <name>`,``,`That creates the package, installs dependencies, and initializes Git. It`,`prints what was set up and how to author, build, and mount the extension —`,`it does not start eve dev (extensions are not standalone agents).`,``,"Build with `eve extension build` (or the package `build` script)."].join(`
4
- `)}function initExtensionHandoff(e){return[``,`What we set up:`,` - package.json with eve.extension ./extension, peer+dev eve, and zod`,` - extension/extension.ts (config schema via defineExtension)`,` - build/prepare scripts → eve extension build`,``,`Next:`,` - Add tools, skills, hooks, or connections under extension/`,` (see AGENTS.md and node_modules/eve/docs/extensions.md)`,` - ${`${e.packageManager} run build`} # fills dist/ and package exports`,` - Mount from a consumer agent:`,` // agent/extensions/${e.packageName}.ts`,` import ext from "${e.packageName}";`,` export default ext({ apiKey: process.env.API_KEY });`,``,`Working directory: ${e.projectPath}`].join(`
4
+ `)}function initExtensionHandoff(e){return[``,`What we set up:`,` - package.json with eve.extension source/dist roots, peer+dev eve, and zod`,` - extension/extension.ts (config schema via defineExtension)`,` - build/prepare scripts → eve extension build`,``,`Next:`,` - Add tools, skills, hooks, or connections under extension/`,` (see AGENTS.md and node_modules/eve/docs/extensions.md)`,` - ${`${e.packageManager} run build`} # builds dist/extension and package exports`,` - Mount from a consumer agent:`,` // agent/extensions/${e.packageName}.ts`,` import ext from "${e.packageName}";`,` export default ext({ apiKey: process.env.API_KEY });`,``,`Working directory: ${e.projectPath}`].join(`
5
5
  `)}export{HANDOFF_SECTIONS,SETUP_SECTIONS,initAgentDevHandoff,initAgentInstructions,initAgentReplPrompt,initExtensionHandoff,initExtensionInstructions};
@@ -1 +1 @@
1
- import{assertCanAddSelectedChannels,inspectExistingChannelRegistrations}from"./channel-add-conflicts.js";import{NOT_AN_AGENT_MESSAGE}from"./preconditions.js";import{isEveProject,listAuthoredChannels}from"#setup/scaffold/index.js";import{interactiveAsker}from"#setup/ask.js";import{addChannels}from"#setup/boxes/add-channels.js";import{deployProject}from"#setup/boxes/deploy-project.js";import{reconcileHostFrameworkPreset}from"#setup/boxes/reconcile-host-framework-preset.js";import{selectChannels}from"#setup/boxes/select-channels.js";import{detectDeployment,projectResolutionFromDeployment}from"#setup/project-resolution.js";import{createPrompter}from"#setup/prompter.js";import{runInteractive}from"#setup/runner.js";import{createDefaultSetupState,snapshotSetupState}from"#setup/state.js";const KNOWN_CHANNEL_KINDS=[`slack`,`web`];function isChannelKind(e){return KNOWN_CHANNEL_KINDS.includes(e)}function parseChannelKind(e){if(!isChannelKind(e))throw Error(`Unknown channel kind "${e}". Known: ${KNOWN_CHANNEL_KINDS.join(`, `)}.`);return e}const defaultChannelsAddDependencies={detectDeployment};async function runAddChannelsFlow(n,r,i,s){if(r===void 0&&(i.yes||!process.stdin.isTTY||!process.stdout.isTTY))throw Error(`Pass a channel kind: \`eve channels add <${KNOWN_CHANNEL_KINDS.join(`|`)}>\`.`);let c=s.createPrompter?.()??createPrompter();c.intro(`Add channels to your eve agent`),c.log.message(`Checking the current Vercel project...`);let l={...createDefaultSetupState(),project:projectResolutionFromDeployment(await s.detectDeployment(n)),projectPath:{kind:`resolved`,inPlace:!0,path:n}},u;function inspectRegistrations(){return u===void 0&&(c.log.message(`Inspecting existing channel registrations...`),u=inspectExistingChannelRegistrations(n)),u}let d=r===void 0?(await inspectRegistrations()).disabledChannelReasons:void 0,f=await runInteractive([selectChannels({asker:interactiveAsker(c),variant:`channels-add`,presetChannels:r===void 0?void 0:[r],disabledChannelReasons:d,validateSelection:async t=>{!t.includes(`web`)&&!t.includes(`slack`)||assertCanAddSelectedChannels(t,await inspectRegistrations())}}),addChannels({asker:interactiveAsker(c),prompter:c,presetCreateSlackbot:i.yes?!0:void 0,force:i.force,configureVercelServices:!0,ensureLinkedProject:`interactive-vercel-link`,deps:s.addChannelsDeps}),reconcileHostFrameworkPreset({prompter:c}),deployProject({prompter:c,ensureLinkedProject:`interactive-vercel-link`,deps:s.deployProjectDeps})],l,{write:e=>c.log.message(e)},{snapshot:snapshotSetupState});f.kind!==`cancelled`&&c.outro(f.state.channels.length===0?`No channels added.`:`Channels added.`)}async function runChannelsAddCommand(e,t,i,a=defaultChannelsAddDependencies){if(!await isEveProject(t)){e.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}try{await runAddChannelsFlow(t,i.kind===void 0?void 0:parseChannelKind(i.kind),i.options,a)}catch(t){e.error(t instanceof Error?t.message:String(t)),process.exitCode=1}}async function runChannelsListCommand(e,t,a){if(!await isEveProject(t)){e.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}let o=await listAuthoredChannels(t);if(a.json){e.log(JSON.stringify({channels:o},null,2));return}if(o.length===0){e.log("No channels defined. Run `eve channels add` to add one.");return}for(let t of o)e.log(t)}export{runChannelsAddCommand,runChannelsListCommand};
1
+ import{assertCanAddSelectedChannels,inspectExistingChannelRegistrations}from"./channel-add-conflicts.js";import{NOT_AN_AGENT_MESSAGE}from"./preconditions.js";import{isEveProject,listAuthoredChannels}from"#setup/scaffold/index.js";import{interactiveAsker}from"#setup/ask.js";import{addChannels}from"#setup/boxes/add-channels.js";import{deployProject}from"#setup/boxes/deploy-project.js";import{selectChannels}from"#setup/boxes/select-channels.js";import{detectDeployment,projectResolutionFromDeployment}from"#setup/project-resolution.js";import{createPrompter}from"#setup/prompter.js";import{runInteractive}from"#setup/runner.js";import{createDefaultSetupState,snapshotSetupState}from"#setup/state.js";const KNOWN_CHANNEL_KINDS=[`slack`,`web`];function isChannelKind(e){return KNOWN_CHANNEL_KINDS.includes(e)}function parseChannelKind(e){if(!isChannelKind(e))throw Error(`Unknown channel kind "${e}". Known: ${KNOWN_CHANNEL_KINDS.join(`, `)}.`);return e}const defaultChannelsAddDependencies={detectDeployment};async function runAddChannelsFlow(n,r,i,s){if(r===void 0&&(i.yes||!process.stdin.isTTY||!process.stdout.isTTY))throw Error(`Pass a channel kind: \`eve channels add <${KNOWN_CHANNEL_KINDS.join(`|`)}>\`.`);let c=s.createPrompter?.()??createPrompter();c.intro(`Add channels to your eve agent`),c.log.message(`Checking the current Vercel project...`);let l={...createDefaultSetupState(),project:projectResolutionFromDeployment(await s.detectDeployment(n)),projectPath:{kind:`resolved`,inPlace:!0,path:n}},u;function inspectRegistrations(){return u===void 0&&(c.log.message(`Inspecting existing channel registrations...`),u=inspectExistingChannelRegistrations(n)),u}let d=r===void 0?(await inspectRegistrations()).disabledChannelReasons:void 0,f=await runInteractive([selectChannels({asker:interactiveAsker(c),variant:`channels-add`,presetChannels:r===void 0?void 0:[r],disabledChannelReasons:d,validateSelection:async t=>{!t.includes(`web`)&&!t.includes(`slack`)||assertCanAddSelectedChannels(t,await inspectRegistrations())}}),addChannels({asker:interactiveAsker(c),prompter:c,presetCreateSlackbot:i.yes?!0:void 0,force:i.force,configureVercelServices:!0,ensureLinkedProject:`interactive-vercel-link`,deps:s.addChannelsDeps}),deployProject({prompter:c,ensureLinkedProject:`interactive-vercel-link`,deps:s.deployProjectDeps})],l,{write:e=>c.log.message(e)},{snapshot:snapshotSetupState});f.kind!==`cancelled`&&c.outro(f.state.channels.length===0?`No channels added.`:`Channels added.`)}async function runChannelsAddCommand(e,t,i,a=defaultChannelsAddDependencies){if(!await isEveProject(t)){e.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}try{await runAddChannelsFlow(t,i.kind===void 0?void 0:parseChannelKind(i.kind),i.options,a)}catch(t){e.error(t instanceof Error?t.message:String(t)),process.exitCode=1}}async function runChannelsListCommand(e,t,a){if(!await isEveProject(t)){e.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}let o=await listAuthoredChannels(t);if(a.json){e.log(JSON.stringify({channels:o},null,2));return}if(o.length===0){e.log("No channels defined. Run `eve channels add` to add one.");return}for(let t of o)e.log(t)}export{runChannelsAddCommand,runChannelsListCommand};
@@ -4,6 +4,6 @@ export interface ExtensionBuildCliLogger {
4
4
  }
5
5
  /**
6
6
  * Builds the current package as an eve extension. Requires
7
- * `package.json#eve.extension` pointing at the source root (e.g. `./extension`).
7
+ * `package.json#eve.extension` declaring distinct source and dist roots.
8
8
  */
9
9
  export declare function runExtensionBuildCommand(logger: ExtensionBuildCliLogger, appRoot: string): Promise<void>;
@@ -1 +1 @@
1
- import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{createLogger}from"#internal/logging.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{buildExtensionPackage,tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";var import_picocolors=__toESM(require_picocolors(),1);const buildLog=createLogger(`extension-build`);async function runExtensionBuildCommand(e,t){let n=await tryReadExtensionBuildConfig(t);if(n===null)throw Error('This package is not an eve extension. Add `"eve": { "extension": "./extension" }` to package.json, or run `eve build` for an agent app.');buildLog.debug(`building extension package`,{packageName:n.packageName,sourceRoot:n.sourceRoot});let r=await buildExtensionPackage(t,n),i=createCliTheme();e.log(renderCliTaggedLine(i,{message:`built extension ${import_picocolors.default.bold(n.packageName)} at ${r}`,tag:`build`,tone:`success`}))}export{runExtensionBuildCommand};
1
+ import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{createLogger}from"#internal/logging.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{buildExtensionPackage,tryReadExtensionBuildConfig}from"#internal/nitro/host/build-extension.js";var import_picocolors=__toESM(require_picocolors(),1);const buildLog=createLogger(`extension-build`);async function runExtensionBuildCommand(e,t){let n=await tryReadExtensionBuildConfig(t);if(n===null)throw Error('This package is not an eve extension. Add `"eve": { "extension": { "source": "./extension", "dist": "./dist/extension" } }` to package.json, or run `eve build` for an agent app.');buildLog.debug(`building extension package`,{packageName:n.packageName,sourceRoot:n.sourceRoot});let r=await buildExtensionPackage(t,n),i=createCliTheme();e.log(renderCliTaggedLine(i,{message:`built extension ${import_picocolors.default.bold(n.packageName)} at ${r}`,tag:`build`,tone:`success`}))}export{runExtensionBuildCommand};
@@ -1,11 +1,4 @@
1
- import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
2
1
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
3
- import type { JsonObject } from "#shared/json.js";
4
- /**
5
- * Normalizes a client-supplied output schema into the wire-safe JSON Schema
6
- * representation accepted by eve message routes.
7
- */
8
- export declare function normalizeOutputSchemaForRequest<TOutput>(schema: StandardJSONSchemaV1<unknown, TOutput> | JsonObject | undefined): JsonObject | undefined;
9
2
  /**
10
3
  * Extracts the most recent finalized structured result from a turn event list.
11
4
  */
@@ -1 +1 @@
1
- import{normalizeJsonSchemaDefinition}from"#shared/json-schema.js";function normalizeOutputSchemaForRequest(t){return t===void 0?void 0:normalizeJsonSchemaDefinition(t,`output`)}function extractCompletedResult(e){let t;for(let n of e)isResultCompletedEvent(n)&&(t=n.data.result);return t}function isResultCompletedEvent(e){return e.type===`result.completed`}export{extractCompletedResult,normalizeOutputSchemaForRequest};
1
+ function extractCompletedResult(e){let t;for(let n of e)isResultCompletedEvent(n)&&(t=n.data.result);return t}function isResultCompletedEvent(e){return e.type===`result.completed`}export{extractCompletedResult};
@@ -1 +1 @@
1
- import{EVE_CREATE_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{advanceSession}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{normalizeOutputSchemaForRequest}from"#client/output-schema.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{openStreamBody,openStreamIterable}from"#client/open-stream.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);return this.#t===n&&(this.#t={...n,sessionId:i}),new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}async cancel(e){let n=this.#t.sessionId;if(!n)throw Error(`Session has no session ID. Send a message first.`);let i=createClientUrl(this.#e.host,createEveCancelTurnRoutePath(n)),o=await this.#e.resolveHeaders();o.set(`content-type`,`application/json`);let s=await fetch(i,withRedirectPolicy({headers:o,method:`POST`,body:e?JSON.stringify(e):void 0},this.#e.redirect)),c=await s.text();if(!s.ok)throw new ClientError(s.status,c,s.headers);let l;try{l=JSON.parse(c)}catch{throw Error(`Cancel route returned invalid JSON (${s.status}).`)}let u=CancelTurnResponseSchema.safeParse(l);if(!u.success||u.data.sessionId!==n)throw Error(`Cancel route returned an invalid response (${s.status}).`);return{sessionId:u.data.sessionId,status:u.data.status}}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return this.#a(t,e)}async#n(t,r){let i=r.sessionId?createEveContinueSessionRoutePath(r.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,o=createClientUrl(this.#e.host,i),c=await this.#e.resolveHeaders(t.headers);c.set(`content-type`,`application/json`);let u=createHandleMessageBody({input:t,outputSchema:normalizeOutputSchemaForRequest(t.outputSchema),session:r});if(u===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let d=await postTurnWithRetry({body:JSON.stringify(u),headers:c,mustDeliver:(t.inputResponses?.length??0)>0,redirect:this.#e.redirect,signal:t.signal,url:o}),f=await d.json(),p=(typeof f.sessionId==`string`?f.sessionId:void 0)??d.headers.get(EVE_SESSION_ID_HEADER)?.trim()??r.sessionId;if(!p)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof f.continuationToken==`string`?f.continuationToken:void 0,sessionId:p}}async*#r(e,t,n,r){let a=[];try{let t=n.sessionId===e?n.streamIndex:0,i=this.#e.maxReconnectAttempts;for(;;){let n=await this.#i(e,t,r.signal,r.headers),o=!1;try{for await(let e of readNdjsonStream(n))if(a.push(e),t+=1,yield e,isCurrentTurnBoundaryEvent(e)){o=!0;break}}catch(e){if(!isStreamDisconnectError(e))throw e}if(o||r.signal?.aborted||i<=0)break;--i}}finally{this.#t=advanceSession({continuationToken:t,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async#i(e,t,n,r){return await openStreamBody({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r),redirect:this.#e.redirect,sessionId:e,signal:n,startIndex:t})}async*#a(e,t){let n=this.#t,r=t?.startIndex??n.streamIndex,a=[];try{for await(let n of openStreamIterable({host:this.#e.host,maxReconnectAttempts:this.#e.maxReconnectAttempts,resolveHeaders:()=>this.#e.resolveHeaders(),redirect:this.#e.redirect,sessionId:e,signal:t?.signal,startIndex:r}))a.push(n),yield n}finally{r>=0&&(this.#t=advanceSession({continuationToken:n.continuationToken,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:r},sessionId:e}))}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,n,i,a;for(let o=0;o<t;o+=1){let s=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,redirect:e.redirect,signal:e.signal??null});if(s.ok)return s;if(n=s.status,i=await s.text(),a=s.headers,!isRetryableDeliveryFailure(s.status,i))throw new ClientError(s.status,i,s.headers);o<t-1&&await sleep(200)}throw new ClientError(n??0,i??`Failed to deliver session turn.`,a)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}export{ClientSession};
1
+ import{EVE_CREATE_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{advanceSession}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{openStreamBody,openStreamIterable}from"#client/open-stream.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);return this.#t===n&&(this.#t={...n,sessionId:i}),new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}async cancel(e){let n=this.#t.sessionId;if(!n)throw Error(`Session has no session ID. Send a message first.`);let i=createClientUrl(this.#e.host,createEveCancelTurnRoutePath(n)),o=await this.#e.resolveHeaders();o.set(`content-type`,`application/json`);let s=await fetch(i,withRedirectPolicy({headers:o,method:`POST`,body:e?JSON.stringify(e):void 0},this.#e.redirect)),c=await s.text();if(!s.ok)throw new ClientError(s.status,c,s.headers);let l;try{l=JSON.parse(c)}catch{throw Error(`Cancel route returned invalid JSON (${s.status}).`)}let u=CancelTurnResponseSchema.safeParse(l);if(!u.success||u.data.sessionId!==n)throw Error(`Cancel route returned an invalid response (${s.status}).`);return{sessionId:u.data.sessionId,status:u.data.status}}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return this.#a(t,e)}async#n(t,r){let i=r.sessionId?createEveContinueSessionRoutePath(r.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,o=createClientUrl(this.#e.host,i),c=await this.#e.resolveHeaders(t.headers);c.set(`content-type`,`application/json`);let l=createHandleMessageBody({input:t,outputSchema:serializeOutputSchema(t.outputSchema),session:r});if(l===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let u=await postTurnWithRetry({body:JSON.stringify(l),headers:c,mustDeliver:(t.inputResponses?.length??0)>0,redirect:this.#e.redirect,signal:t.signal,url:o}),d=await u.json(),f=(typeof d.sessionId==`string`?d.sessionId:void 0)??u.headers.get(EVE_SESSION_ID_HEADER)?.trim()??r.sessionId;if(!f)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof d.continuationToken==`string`?d.continuationToken:void 0,sessionId:f}}async*#r(e,t,n,r){let a=[];try{let t=n.sessionId===e?n.streamIndex:0,i=this.#e.maxReconnectAttempts;for(;;){let n=await this.#i(e,t,r.signal,r.headers),o=!1;try{for await(let e of readNdjsonStream(n))if(a.push(e),t+=1,yield e,isCurrentTurnBoundaryEvent(e)){o=!0;break}}catch(e){if(!isStreamDisconnectError(e))throw e}if(o||r.signal?.aborted||i<=0)break;--i}}finally{this.#t=advanceSession({continuationToken:t,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async#i(e,t,n,r){return await openStreamBody({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r),redirect:this.#e.redirect,sessionId:e,signal:n,startIndex:t})}async*#a(e,t){let n=this.#t,r=t?.startIndex??n.streamIndex,a=[];try{for await(let n of openStreamIterable({host:this.#e.host,maxReconnectAttempts:this.#e.maxReconnectAttempts,resolveHeaders:()=>this.#e.resolveHeaders(),redirect:this.#e.redirect,sessionId:e,signal:t?.signal,startIndex:r}))a.push(n),yield n}finally{r>=0&&(this.#t=advanceSession({continuationToken:n.continuationToken,events:a,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:r},sessionId:e}))}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,n,i,a;for(let o=0;o<t;o+=1){let s=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,redirect:e.redirect,signal:e.signal??null});if(s.ok)return s;if(n=s.status,i=await s.text(),a=s.headers,!isRetryableDeliveryFailure(s.status,i))throw new ClientError(s.status,i,s.headers);o<t-1&&await sleep(200)}throw new ClientError(n??0,i??`Failed to deliver session turn.`,a)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}export{ClientSession};
@@ -0,0 +1,56 @@
1
+ /** Stable kind for an extension distribution compatibility manifest. */
2
+ export declare const EXTENSION_COMPATIBILITY_MANIFEST_KIND = "eve-extension";
3
+ /** Current compatibility-manifest JSON format. */
4
+ export declare const EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION = 1;
5
+ /** Filename emitted at the root of an extension's agent-shaped dist tree. */
6
+ export declare const EXTENSION_COMPATIBILITY_MANIFEST_FILENAME = "_manifest.json";
7
+ /** Current producer contract version for each extension-facing capability. */
8
+ export declare const EXTENSION_CAPABILITY_VERSIONS: {
9
+ readonly extension: 1;
10
+ readonly tool: 1;
11
+ readonly dynamicTool: 1;
12
+ readonly connection: 1;
13
+ readonly hook: 1;
14
+ readonly skill: 1;
15
+ readonly dynamicSkill: 1;
16
+ readonly instructions: 1;
17
+ readonly dynamicInstructions: 1;
18
+ readonly config: 1;
19
+ readonly state: 1;
20
+ };
21
+ /** One independently versioned extension-facing contract. */
22
+ export type ExtensionCapability = keyof typeof EXTENSION_CAPABILITY_VERSIONS;
23
+ /** Capability requirements stamped by one extension build. */
24
+ export type ExtensionCapabilityRequirements = Partial<Record<ExtensionCapability, number>>;
25
+ /**
26
+ * Capability contract versions this eve release can consume. Derived from
27
+ * {@link EXTENSION_CAPABILITY_VERSIONS} so the version this release stamps is
28
+ * always one it accepts.
29
+ */
30
+ export declare const EXTENSION_CAPABILITY_SUPPORT: Readonly<Record<ExtensionCapability, readonly number[]>>;
31
+ /** Consumer support table used to validate one extension distribution. */
32
+ export type ExtensionCapabilitySupport = Readonly<Record<string, readonly number[]>>;
33
+ /** Compatibility-only metadata emitted by `eve extension build`. */
34
+ export interface ExtensionCompatibilityManifest {
35
+ readonly kind: typeof EXTENSION_COMPATIBILITY_MANIFEST_KIND;
36
+ readonly formatVersion: typeof EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION;
37
+ /** Diagnostic producer version; capability requirements decide compatibility. */
38
+ readonly builtWithEve: string;
39
+ readonly requires: Readonly<Record<string, number>>;
40
+ }
41
+ /** One requirement the consuming eve cannot satisfy. */
42
+ export interface UnsupportedExtensionCapability {
43
+ readonly capability: string;
44
+ readonly requiredVersion: number;
45
+ readonly supportedVersions: readonly number[];
46
+ }
47
+ /** Serializes a compatibility manifest deterministically. */
48
+ export declare function serializeExtensionCompatibilityManifest(manifest: ExtensionCompatibilityManifest): string;
49
+ /** Parses and validates compatibility-manifest JSON. */
50
+ export declare function parseExtensionCompatibilityManifest(raw: string, manifestPath: string): ExtensionCompatibilityManifest;
51
+ /** Reads and validates an extension compatibility manifest. */
52
+ export declare function readExtensionCompatibilityManifest(manifestPath: string): Promise<ExtensionCompatibilityManifest>;
53
+ /** Writes `_manifest.json` into an agent-shaped extension dist root. */
54
+ export declare function writeExtensionCompatibilityManifest(distRoot: string, manifest: ExtensionCompatibilityManifest): Promise<void>;
55
+ /** Finds unknown or unsupported capability requirements without executing extension code. */
56
+ export declare function findUnsupportedExtensionCapabilities(manifest: ExtensionCompatibilityManifest, support?: ExtensionCapabilitySupport): UnsupportedExtensionCapability[];
@@ -0,0 +1 @@
1
+ import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{readFile,writeFile}from"node:fs/promises";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_VERSIONS={extension:1,tool:1,dynamicTool:1,connection:1,hook:1,skill:1,dynamicSkill:1,instructions:1,dynamicInstructions:1,config:1,state:1},ADDITIONAL_SUPPORTED_CAPABILITY_VERSIONS={};function deriveCapabilitySupport(){let e={};for(let t of Object.keys(EXTENSION_CAPABILITY_VERSIONS))e[t]=[...ADDITIONAL_SUPPORTED_CAPABILITY_VERSIONS[t]??[],EXTENSION_CAPABILITY_VERSIONS[t]];return e}const EXTENSION_CAPABILITY_SUPPORT=deriveCapabilitySupport(),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(e){return parseExtensionCompatibilityManifest(await readFile(e,`utf8`),e)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
@@ -1 +1 @@
1
- import{isAbsolute,join,relative,resolve}from"node:path";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeJsonSchemaDefinition}from"#shared/json-schema.js";import{normalizeLogicalPath}from"#discover/filesystem.js";import{classifyModelRouting}from"#internal/classify-model-routing.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{parseJsonObject}from"#shared/json.js";import{isDynamicModelDefinition}from"#shared/agent-definition.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileAgentConfig(e,t){let n=e.configModule,r=n===void 0?void 0:formatAgentConfigModulePath(e,n),a=normalizeAgentDefinition(n===void 0?{model:DEFAULT_AGENT_MODEL_ID}:await loadModuleBackedDefinition({agentRoot:e.agentRoot,displayPath:r,kind:`agent config`,source:n}),n===void 0?`Expected the default agent config to match the public eve shape.`:`Expected the agent config export "${n.exportName??`default`}" from "${r}" to match the public eve shape.`),o=isDynamicModelDefinition(a.model)?a.model.fallback:a.model,s=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:a.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:n,sourcePath:r,value:o}),c={},l={compaction:c,model:s,name:e.agentId};if(a.description!==void 0&&(l.description=a.description),isDynamicModelDefinition(a.model)){if(n===void 0)throw Error(`Expected dynamic model definitions to be authored in agent.ts.`);l.dynamicModel={eventNames:Object.keys(a.model.events),exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId}}let u=normalizeExperimentalDefinition(a.experimental);return u!==void 0&&(l.experimental=u),a.build!==void 0&&(l.build={externalDependencies:a.build.externalDependencies===void 0?void 0:[...a.build.externalDependencies]}),a.outputSchema!==void 0&&(l.outputSchema=normalizeJsonSchemaDefinition(a.outputSchema,`output`)),a.reasoning!==void 0&&(l.reasoning=a.reasoning),a.limits!==void 0&&(l.limits={maxInputTokensPerSession:a.limits.maxInputTokensPerSession,maxOutputTokensPerSession:a.limits.maxOutputTokensPerSession}),n!==void 0&&(l.source={exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId}),a.compaction?.model!==void 0&&(c.model=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,contextWindowTokens:a.compaction.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:n,sourcePath:r,value:a.compaction.model})),a.compaction?.thresholdPercent!==void 0&&(c.thresholdPercent=a.compaction.thresholdPercent),l}function normalizeExperimentalDefinition(e){if(e===void 0)return;let t={};return e.workflow!==void 0&&(t.workflow={world:e.workflow.world}),t}async function normalizeAuthoredModelReference(e){if(typeof e.value==`string`)return await withCompiledRuntimeModelLimits({id:formatLanguageModelGatewayId(e.value),providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:classifyModelRouting(e.value,e.providerOptions)},e);let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${e.sourcePath??t.logicalPath}" to provide a valid AI SDK language model.`);let i={id:formatLanguageModelGatewayId(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:classifyModelRouting(n,e.providerOptions)};if(e.contextWindowTokens===void 0){let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...i,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens}}return await withCompiledRuntimeModelLimits(i,e)}function formatAgentConfigModulePath(e,r){let i=join(e.agentRoot,r.logicalPath);return normalizeLogicalPath(relative(resolveTopLevelAgentRoot(e),i))}function resolveTopLevelAgentRoot(e){let t=resolve(e.appRoot),n=resolve(t,`agent`);return isPathInsideOrEqual(n,resolve(e.agentRoot))?n:t}function isPathInsideOrEqual(t,r){let i=relative(t,r);return i===``||!i.startsWith(`..`)&&!isAbsolute(i)}async function withCompiledRuntimeModelLimits(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${toErrorMessage(n)}`)}if(n===null)throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`);return{...e,contextWindowTokens:n.contextWindowTokens}}function parseProviderOptionsRecord(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n]=parseJsonObject(r);return t}export{compileAgentConfig};
1
+ import{isAbsolute,join,relative,resolve}from"node:path";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{toErrorMessage}from"#shared/errors.js";import{serializeOutputSchema}from"#shared/tool-schema.js";import{normalizeLogicalPath}from"#discover/filesystem.js";import{classifyModelRouting}from"#internal/classify-model-routing.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{parseJsonObject}from"#shared/json.js";import{isDynamicModelDefinition}from"#shared/agent-definition.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileAgentConfig(e,t){let n=e.configModule,r=n===void 0?void 0:formatAgentConfigModulePath(e,n),a=normalizeAgentDefinition(n===void 0?{model:DEFAULT_AGENT_MODEL_ID}:await loadModuleBackedDefinition({agentRoot:e.agentRoot,displayPath:r,kind:`agent config`,source:n}),n===void 0?`Expected the default agent config to match the public eve shape.`:`Expected the agent config export "${n.exportName??`default`}" from "${r}" to match the public eve shape.`),o=isDynamicModelDefinition(a.model)?a.model.fallback:a.model,s=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,contextWindowTokens:a.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:n,sourcePath:r,value:o}),c={},l={compaction:c,model:s,name:e.agentId};if(a.description!==void 0&&(l.description=a.description),isDynamicModelDefinition(a.model)){if(n===void 0)throw Error(`Expected dynamic model definitions to be authored in agent.ts.`);l.dynamicModel={eventNames:Object.keys(a.model.events),exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId}}let u=normalizeExperimentalDefinition(a.experimental);return u!==void 0&&(l.experimental=u),a.build!==void 0&&(l.build={externalDependencies:a.build.externalDependencies===void 0?void 0:[...a.build.externalDependencies]}),a.outputSchema!==void 0&&(l.outputSchema=serializeOutputSchema(a.outputSchema)),a.reasoning!==void 0&&(l.reasoning=a.reasoning),a.limits!==void 0&&(l.limits={maxInputTokensPerSession:a.limits.maxInputTokensPerSession,maxOutputTokensPerSession:a.limits.maxOutputTokensPerSession}),n!==void 0&&(l.source={exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId}),a.compaction?.model!==void 0&&(c.model=await normalizeAuthoredModelReference({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,contextWindowTokens:a.compaction.modelContextWindowTokens,providerOptions:a.modelOptions?.providerOptions,source:n,sourcePath:r,value:a.compaction.model})),a.compaction?.thresholdPercent!==void 0&&(c.thresholdPercent=a.compaction.thresholdPercent),l}function normalizeExperimentalDefinition(e){if(e===void 0)return;let t={};return e.workflow!==void 0&&(t.workflow={world:e.workflow.world}),t}async function normalizeAuthoredModelReference(e){if(typeof e.value==`string`)return await withCompiledRuntimeModelLimits({id:formatLanguageModelGatewayId(e.value),providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:classifyModelRouting(e.value,e.providerOptions)},e);let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${e.sourcePath??t.logicalPath}" to provide a valid AI SDK language model.`);let i={id:formatLanguageModelGatewayId(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:parseProviderOptionsRecord(e.providerOptions),routing:classifyModelRouting(n,e.providerOptions)};if(e.contextWindowTokens===void 0){let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...i,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens}}return await withCompiledRuntimeModelLimits(i,e)}function formatAgentConfigModulePath(e,r){let i=join(e.agentRoot,r.logicalPath);return normalizeLogicalPath(relative(resolveTopLevelAgentRoot(e),i))}function resolveTopLevelAgentRoot(e){let t=resolve(e.appRoot),n=resolve(t,`agent`);return isPathInsideOrEqual(n,resolve(e.agentRoot))?n:t}function isPathInsideOrEqual(t,r){let i=relative(t,r);return i===``||!i.startsWith(`..`)&&!isAbsolute(i)}async function withCompiledRuntimeModelLimits(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${toErrorMessage(n)}`)}if(n===null)throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`);return{...e,contextWindowTokens:n.contextWindowTokens}}function parseProviderOptionsRecord(e){if(e===void 0)return;let t={};for(let[n,r]of Object.entries(e))t[n]=parseJsonObject(r);return t}export{compileAgentConfig};
@@ -1 +1 @@
1
- import{expectObjectRecord,expectOnlyKnownKeys,expectString}from"#internal/authored-module.js";import{EVE_CREATE_SESSION_ROUTE_PATH}from"#protocol/routes.js";import{normalizeJsonSchemaDefinition}from"#shared/json-schema.js";import{createCompiledSubagentNodeId}from"#compiler/manifest.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{createPathDerivedSourceId}from"#discover/manifest.js";async function compileSubagentGraph(e){let t=[],n=[],r=[];for(let i of e.subagents){let a=await compileSubagentDefinition({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,externalDependencies:e.externalDependencies,parentNodeId:e.parentNodeId,source:i});if(a.kind===`remote`){r.push(a.node);continue}t.push(a.node,...a.descendants.nodes),n.push({childNodeId:a.node.nodeId,parentNodeId:e.parentNodeId},...a.descendants.edges)}return{edges:n,nodes:t,remoteAgents:r}}async function compileSubagentDefinition(e){let t=e.source.manifest.configModule;if(t===void 0)throw Error(`Subagent "${e.source.logicalPath}" is missing an agent config module.`);let n=createSubagentConfigModuleSourceRef(e.source,t),r=await loadModuleBackedDefinition({agentRoot:e.source.manifest.agentRoot,displayPath:n.logicalPath,externalDependencies:e.externalDependencies,kind:`subagent config`,source:t});return readAgentDefinitionKind(r)===`remote`?{kind:`remote`,node:compileRemoteAgent({source:e.source,value:r})}:{kind:`local`,...await compileLocalSubagent(e)}}async function compileSubagent(e){let t=createCompiledSubagentNodeId(e.parentNodeId,e.source.sourceId),n=e.source.subagentId,r=await e.compileAgentNodeManifest({...e.source.manifest,appRoot:e.appRoot},e.context,{allowWorkflowConfig:!1,externalDependencies:e.externalDependencies}),i=r.config.description;if(!i)throw Error(`Local subagent "${e.source.logicalPath}" is missing a "description" field on its agent config. Add \`description\` to \`defineAgent({ ... })\` so the parent agent can decide when to delegate to this subagent.`);let o=await compileSubagentGraph({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,externalDependencies:r.config.build?.externalDependencies,parentNodeId:t,subagents:e.source.manifest.subagents});return{descendants:o,node:{agent:{...r,remoteAgents:[...o.remoteAgents]},description:i,entryPath:e.source.entryPath,logicalPath:e.source.logicalPath,name:n,nodeId:t,rootPath:e.source.rootPath,sourceId:e.source.sourceId,sourceKind:`module`}}}const compileLocalSubagent=compileSubagent;function compileRemoteAgent(e){let t=e.source.manifest.configModule;if(t===void 0)throw Error(`Remote agent "${e.source.logicalPath}" is missing a config module.`);assertRemoteAgentDefinitionHasNoLocalPackageEntries(e.source);let n=createSubagentConfigModuleSourceRef(e.source,t),r=normalizeRemoteAgentDefinition(e.value,`Expected the remote agent config export "${t.exportName??`default`}" from "${n.logicalPath}" to match the public eve shape.`),i={...n,description:r.description,entryPath:e.source.entryPath,name:e.source.subagentId,nodeId:e.source.sourceId,outputSchema:r.outputSchema,path:r.path,rootPath:e.source.rootPath};return r.url===void 0?i:{...i,url:r.url}}function createSubagentConfigModuleSourceRef(e,t){let n=e.logicalPath===t.logicalPath?t.logicalPath:`${e.logicalPath}/${t.logicalPath}`,r={logicalPath:n,sourceId:createPathDerivedSourceId(n),sourceKind:`module`};return t.exportName!==void 0&&(r.exportName=t.exportName),r}function readAgentDefinitionKind(e){return typeof e!=`object`||!e?`local`:e.kind===`remote`?`remote`:`local`}function normalizeRemoteAgentDefinition(a,o){let s=expectObjectRecord(a,o);if(expectOnlyKnownKeys(s,[`auth`,`description`,`headers`,`kind`,`outputSchema`,`path`,`url`],o),s.kind!==`remote`)throw Error(`${o} Expected "kind" to be "remote".`);return{description:expectString(s.description,o),outputSchema:s.outputSchema===void 0?void 0:normalizeJsonSchemaDefinition(s.outputSchema,`output`),path:s.path===void 0?EVE_CREATE_SESSION_ROUTE_PATH:expectString(s.path,o),url:typeof s.url==`function`?void 0:expectString(s.url,o)}}function assertRemoteAgentDefinitionHasNoLocalPackageEntries(e){let t=e.manifest,n=[t.connections.length>0?`connections/`:void 0,t.hooks.length>0?`hooks/`:void 0,t.instructions.length>0?`instructions`:void 0,t.lib.length>0?`lib/`:void 0,t.sandbox===null?void 0:`sandbox/`,t.sandboxWorkspaces.length>0?`sandbox/workspace/`:void 0,t.schedules.length>0?`schedules/`:void 0,t.skills.length>0?`skills/`:void 0,t.subagents.length>0?`subagents/`:void 0,t.tools.length>0?`tools/`:void 0].filter(e=>e!==void 0);if(n.length!==0)throw Error(`Remote subagent definition "${e.logicalPath}" cannot include local package entries. Remove unsupported entries: ${n.join(`, `)}.`)}export{compileSubagentGraph};
1
+ import{expectObjectRecord,expectOnlyKnownKeys,expectString}from"#internal/authored-module.js";import{EVE_CREATE_SESSION_ROUTE_PATH}from"#protocol/routes.js";import{serializeOutputSchema}from"#shared/tool-schema.js";import{createCompiledSubagentNodeId}from"#compiler/manifest.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{createPathDerivedSourceId}from"#discover/manifest.js";async function compileSubagentGraph(e){let t=[],n=[],r=[];for(let i of e.subagents){let a=await compileSubagentDefinition({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,externalDependencies:e.externalDependencies,parentNodeId:e.parentNodeId,source:i});if(a.kind===`remote`){r.push(a.node);continue}t.push(a.node,...a.descendants.nodes),n.push({childNodeId:a.node.nodeId,parentNodeId:e.parentNodeId},...a.descendants.edges)}return{edges:n,nodes:t,remoteAgents:r}}async function compileSubagentDefinition(e){let t=e.source.manifest.configModule;if(t===void 0)throw Error(`Subagent "${e.source.logicalPath}" is missing an agent config module.`);let n=createSubagentConfigModuleSourceRef(e.source,t),r=await loadModuleBackedDefinition({agentRoot:e.source.manifest.agentRoot,displayPath:n.logicalPath,externalDependencies:e.externalDependencies,kind:`subagent config`,source:t});return readAgentDefinitionKind(r)===`remote`?{kind:`remote`,node:compileRemoteAgent({source:e.source,value:r})}:{kind:`local`,...await compileLocalSubagent(e)}}async function compileSubagent(e){let t=createCompiledSubagentNodeId(e.parentNodeId,e.source.sourceId),n=e.source.subagentId,r=await e.compileAgentNodeManifest({...e.source.manifest,appRoot:e.appRoot},e.context,{allowWorkflowConfig:!1,externalDependencies:e.externalDependencies}),i=r.config.description;if(!i)throw Error(`Local subagent "${e.source.logicalPath}" is missing a "description" field on its agent config. Add \`description\` to \`defineAgent({ ... })\` so the parent agent can decide when to delegate to this subagent.`);let o=await compileSubagentGraph({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,externalDependencies:r.config.build?.externalDependencies,parentNodeId:t,subagents:e.source.manifest.subagents});return{descendants:o,node:{agent:{...r,remoteAgents:[...o.remoteAgents]},description:i,entryPath:e.source.entryPath,logicalPath:e.source.logicalPath,name:n,nodeId:t,rootPath:e.source.rootPath,sourceId:e.source.sourceId,sourceKind:`module`}}}const compileLocalSubagent=compileSubagent;function compileRemoteAgent(e){let t=e.source.manifest.configModule;if(t===void 0)throw Error(`Remote agent "${e.source.logicalPath}" is missing a config module.`);assertRemoteAgentDefinitionHasNoLocalPackageEntries(e.source);let n=createSubagentConfigModuleSourceRef(e.source,t),r=normalizeRemoteAgentDefinition(e.value,`Expected the remote agent config export "${t.exportName??`default`}" from "${n.logicalPath}" to match the public eve shape.`),i={...n,description:r.description,entryPath:e.source.entryPath,name:e.source.subagentId,nodeId:e.source.sourceId,outputSchema:r.outputSchema,path:r.path,rootPath:e.source.rootPath};return r.url===void 0?i:{...i,url:r.url}}function createSubagentConfigModuleSourceRef(e,t){let n=e.logicalPath===t.logicalPath?t.logicalPath:`${e.logicalPath}/${t.logicalPath}`,r={logicalPath:n,sourceId:createPathDerivedSourceId(n),sourceKind:`module`};return t.exportName!==void 0&&(r.exportName=t.exportName),r}function readAgentDefinitionKind(e){return typeof e!=`object`||!e?`local`:e.kind===`remote`?`remote`:`local`}function normalizeRemoteAgentDefinition(a,o){let s=expectObjectRecord(a,o);if(expectOnlyKnownKeys(s,[`auth`,`description`,`headers`,`kind`,`outputSchema`,`path`,`url`],o),s.kind!==`remote`)throw Error(`${o} Expected "kind" to be "remote".`);return{description:expectString(s.description,o),outputSchema:serializeOutputSchema(s.outputSchema),path:s.path===void 0?EVE_CREATE_SESSION_ROUTE_PATH:expectString(s.path,o),url:typeof s.url==`function`?void 0:expectString(s.url,o)}}function assertRemoteAgentDefinitionHasNoLocalPackageEntries(e){let t=e.manifest,n=[t.connections.length>0?`connections/`:void 0,t.hooks.length>0?`hooks/`:void 0,t.instructions.length>0?`instructions`:void 0,t.lib.length>0?`lib/`:void 0,t.sandbox===null?void 0:`sandbox/`,t.sandboxWorkspaces.length>0?`sandbox/workspace/`:void 0,t.schedules.length>0?`schedules/`:void 0,t.skills.length>0?`skills/`:void 0,t.subagents.length>0?`subagents/`:void 0,t.tools.length>0?`tools/`:void 0].filter(e=>e!==void 0);if(n.length!==0)throw Error(`Remote subagent definition "${e.logicalPath}" cannot include local package entries. Remove unsupported entries: ${n.join(`, `)}.`)}export{compileSubagentGraph};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{jsonSchema}from"ai";import{buildBaseToolContext}from"#context/build-base-tool-context.js";const log=createLogger(`dynamic-tools`);function lookupStepFunction(e){try{let t=globalThis[Symbol.for(`@workflow/core//registeredSteps`)];return t===void 0?null:t.get(e)||null}catch{return null}}function replayTools(e){let t=[];for(let n of e){if(!n.executeStepFnName||!n.closureVars){log.warn(`Dynamic tool "${n.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(n.executeStepFnName);if(!e){log.warn(`Dynamic tool "${n.name}" references step function "${n.executeStepFnName}" which is not registered — skipping on this step.`);continue}t.push({description:n.description,execute:(t,r)=>e(n.closureVars,t,buildBaseToolContext({options:r,toolName:n.name})),inputSchema:jsonSchema(n.inputSchema),name:n.name,approval:buildReplayedApproval(n),outputSchema:n.outputSchema===void 0?void 0:jsonSchema(n.outputSchema)})}return t}function buildReplayedApproval(e){if(e.approvalStepFnName===void 0)return;let t=lookupStepFunction(e.approvalStepFnName);return t===null?(log.warn(`Dynamic tool "${e.name}" references approval function "${e.approvalStepFnName}" which is not registered — requiring approval by default.`),()=>`user-approval`):async n=>await t(e.closureVars??{},n)}function buildDynamicTools(e){let i=e.get(LiveStepToolsKey)??[],a=replayTools(e.get(TurnDynamicToolMetadataKey)??[]),o=replayTools(e.get(SessionDynamicToolMetadataKey)??[]);return[...i,...a,...o]}export{buildDynamicTools};
1
+ import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toInputSchema,toOutputSchema}from"#shared/tool-schema.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";const log=createLogger(`dynamic-tools`);function lookupStepFunction(e){try{let t=globalThis[Symbol.for(`@workflow/core//registeredSteps`)];return t===void 0?null:t.get(e)||null}catch{return null}}function replayTools(e){let t=[];for(let n of e){if(!n.executeStepFnName||!n.closureVars){log.warn(`Dynamic tool "${n.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(n.executeStepFnName);if(!e){log.warn(`Dynamic tool "${n.name}" references step function "${n.executeStepFnName}" which is not registered — skipping on this step.`);continue}t.push({description:n.description,execute:(t,r)=>e(n.closureVars,t,buildBaseToolContext({options:r,toolName:n.name})),inputSchema:toInputSchema(n.inputSchema),name:n.name,approval:buildReplayedApproval(n),outputSchema:toOutputSchema(n.outputSchema)})}return t}function buildReplayedApproval(e){if(e.approvalStepFnName===void 0)return;let t=lookupStepFunction(e.approvalStepFnName);return t===null?(log.warn(`Dynamic tool "${e.name}" references approval function "${e.approvalStepFnName}" which is not registered — requiring approval by default.`),()=>`user-approval`):async n=>await t(e.closureVars??{},n)}function buildDynamicTools(e){let i=e.get(LiveStepToolsKey)??[],a=replayTools(e.get(TurnDynamicToolMetadataKey)??[]),o=replayTools(e.get(SessionDynamicToolMetadataKey)??[]);return[...i,...a,...o]}export{buildDynamicTools};
@@ -1,4 +1,4 @@
1
- import { type ModelMessage } from "ai";
1
+ import type { ModelMessage } from "ai";
2
2
  import type { HarnessToolDefinition } from "#harness/execute-tool.js";
3
3
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
4
4
  import type { ResolvedDynamicToolResolver } from "#runtime/types.js";
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS,isBrandedToolEntry}from"#shared/dynamic-tool-definition.js";import{jsonSchema,zodSchema}from"ai";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{normalizeJsonSchemaDefinition}from"#internal/json-schema.js";const log=createLogger(`dynamic-tools`);function toHarnessToolDefinition(e,t){return{description:t.description,execute:(n,r)=>t.execute(n,buildBaseToolContext({options:r,toolName:e})),inputSchema:convertInputSchema(t.inputSchema),name:e,approval:t.approval,outputSchema:convertOptionalOutputSchema(t.outputSchema),...t.toModelOutput===void 0?{}:{toModelOutput:t.toModelOutput}}}function convertInputSchema(e){return typeof e==`object`&&e&&`~standard`in e?zodSchema(e):jsonSchema(e)}function convertOptionalOutputSchema(e){if(e!==void 0)return typeof e==`object`&&e&&`~standard`in e?zodSchema(e):jsonSchema(e)}function qualifyDynamicToolNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t)return i.push({name:e.slug,entryKey:r[0],entry:n[r[0]]}),i;let a=e.extensionNamespace===void 0?``:`${e.extensionNamespace}__`;for(let e of r)i.push({name:`${a}${e}`,entryKey:e,entry:n[e]});return i}function replayDynamicSessionTools(e,t){let n=[];for(let t of e){if(!t.executeStepFnName||!t.closureVars){log.warn(`Dynamic tool "${t.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(t.executeStepFnName);if(!e){log.warn(`Dynamic tool "${t.name}" references step function "${t.executeStepFnName}" which is not registered — skipping on this step.`);continue}n.push({description:t.description,execute:(n,r)=>e(t.closureVars,n,buildBaseToolContext({options:r,toolName:t.name})),inputSchema:jsonSchema(t.inputSchema),name:t.name,outputSchema:t.outputSchema===void 0?void 0:jsonSchema(t.outputSchema)})}return n}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function lookupStepFunction(e){try{return getStepRegistry().get(e)||null}catch{return null}}function registerStepFunction(e,t){getStepRegistry().set(e,t)}function safeSerialize(e){try{return JSON.parse(JSON.stringify(e))}catch{return{}}}function durableKeyForEvent(e){switch(e){case`session.started`:return SessionDynamicToolMetadataKey;case`turn.started`:return TurnDynamicToolMetadataKey;default:return}}async function resolveToolsFromEvent(e,t,n,r){let a=await Promise.allSettled(t.map(async t=>{let i=t.events[n.type];if(i===void 0)return null;let a=await i(n,buildResolveContext(e,r));if(a==null)return null;let s,c;return isBrandedToolEntry(a)?(s={_single:a},c=!0):(s=a,c=!1),{resolver:t,entries:s,isSingle:c}})),s=[],c=[],l=new Map;for(let e of a){if(e.status===`rejected`){log.error(`Dynamic tool resolver (${n.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}if(e.value===null)continue;let{resolver:t,entries:r,isSingle:a}=e.value,o=qualifyDynamicToolNames(t,a,r);for(let{name:e,entryKey:r,entry:i}of o){let a=l.get(e);if(a!==void 0&&a!==t.slug)throw Error(`Dynamic tool "${e}" from resolver "${t.slug}" collides with dynamic resolver "${a}". Namespace the map key manually, e.g. "${t.slug}__${e}".`);if(l.set(e,t.slug),c.push(toHarnessToolDefinition(e,i)),n.type===`step.started`)continue;let o=`__executeStepFn`in i?i.__executeStepFn:void 0,u=`__closureVars`in i?i.__closureVars:void 0,f=o?.stepId,p=u===void 0?void 0:safeSerialize(u);if(f===void 0){let e=`eve:framework-dynamic:${t.slug}:${r}`,n=i.execute.bind(i);registerStepFunction(e,(e,t,r)=>n(t,r)),f=e,p={}}let m;if(i.approval!==void 0){m=`eve:dynamic-tool-approval:${t.slug}:${r}`;let e=i.approval.bind(i);registerStepFunction(m,(t,n)=>e(n))}s.push({name:e,description:i.description,inputSchema:normalizeJsonSchemaDefinition(i.inputSchema),outputSchema:i.outputSchema===void 0?void 0:normalizeJsonSchemaDefinition(i.outputSchema,`output`),resolverSlug:t.slug,entryKey:r,executeStepFnName:f,approvalStepFnName:m,closureVars:p})}}return{metadata:s,liveTools:c}}async function dispatchDynamicToolEvent(e){let{ctx:n,resolvers:r,event:i,messages:o}=e;if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(i.type))return;let s=r.filter(e=>e.eventNames.includes(i.type));if(s.length===0)return;let{metadata:c,liveTools:l}=await resolveToolsFromEvent(n,s,i,o);if(i.type===`step.started`){n.setVirtualContext(LiveStepToolsKey,l);return}let u=durableKeyForEvent(i.type);if(u===void 0)return;let d=new Set(s.map(e=>e.slug)),f=(n.get(u)??[]).filter(e=>!d.has(e.resolverSlug));n.set(u,[...f,...c])}export{dispatchDynamicToolEvent,replayDynamicSessionTools};
1
+ import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{serializeInputSchema,serializeOutputSchema,toInputSchema,toOutputSchema}from"#shared/tool-schema.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS,isBrandedToolEntry}from"#shared/dynamic-tool-definition.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";const log=createLogger(`dynamic-tools`);function toHarnessToolDefinition(e,t){return{description:t.description,execute:(n,r)=>t.execute(n,buildBaseToolContext({options:r,toolName:e})),inputSchema:toInputSchema(t.inputSchema),name:e,approval:t.approval,outputSchema:toOutputSchema(t.outputSchema),...t.toModelOutput===void 0?{}:{toModelOutput:t.toModelOutput}}}function qualifyDynamicToolNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t)return i.push({name:e.slug,entryKey:r[0],entry:n[r[0]]}),i;let a=e.extensionNamespace===void 0?``:`${e.extensionNamespace}__`;for(let e of r)i.push({name:`${a}${e}`,entryKey:e,entry:n[e]});return i}function replayDynamicSessionTools(e,t){let n=[];for(let t of e){if(!t.executeStepFnName||!t.closureVars){log.warn(`Dynamic tool "${t.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(t.executeStepFnName);if(!e){log.warn(`Dynamic tool "${t.name}" references step function "${t.executeStepFnName}" which is not registered — skipping on this step.`);continue}n.push({description:t.description,execute:(n,r)=>e(t.closureVars,n,buildBaseToolContext({options:r,toolName:t.name})),inputSchema:toInputSchema(t.inputSchema),name:t.name,outputSchema:toOutputSchema(t.outputSchema)})}return n}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function lookupStepFunction(e){try{return getStepRegistry().get(e)||null}catch{return null}}function registerStepFunction(e,t){getStepRegistry().set(e,t)}function safeSerialize(e){try{return JSON.parse(JSON.stringify(e))}catch{return{}}}function durableKeyForEvent(e){switch(e){case`session.started`:return SessionDynamicToolMetadataKey;case`turn.started`:return TurnDynamicToolMetadataKey;default:return}}async function resolveToolsFromEvent(e,t,n,r){let s=await Promise.allSettled(t.map(async t=>{let i=t.events[n.type];if(i===void 0)return null;let a=await i(n,buildResolveContext(e,r));if(a==null)return null;let o,s;return isBrandedToolEntry(a)?(o={_single:a},s=!0):(o=a,s=!1),{resolver:t,entries:o,isSingle:s}})),c=[],l=[],d=new Map;for(let e of s){if(e.status===`rejected`){log.error(`Dynamic tool resolver (${n.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}if(e.value===null)continue;let{resolver:t,entries:r,isSingle:s}=e.value,u=qualifyDynamicToolNames(t,s,r);for(let{name:e,entryKey:r,entry:i}of u){let s=d.get(e);if(s!==void 0&&s!==t.slug)throw Error(`Dynamic tool "${e}" from resolver "${t.slug}" collides with dynamic resolver "${s}". Namespace the map key manually, e.g. "${t.slug}__${e}".`);if(d.set(e,t.slug),l.push(toHarnessToolDefinition(e,i)),n.type===`step.started`)continue;let u=`__executeStepFn`in i?i.__executeStepFn:void 0,f=`__closureVars`in i?i.__closureVars:void 0,p=u?.stepId,m=f===void 0?void 0:safeSerialize(f);if(p===void 0){let e=`eve:framework-dynamic:${t.slug}:${r}`,n=i.execute.bind(i);registerStepFunction(e,(e,t,r)=>n(t,r)),p=e,m={}}let h;if(i.approval!==void 0){h=`eve:dynamic-tool-approval:${t.slug}:${r}`;let e=i.approval.bind(i);registerStepFunction(h,(t,n)=>e(n))}c.push({name:e,description:i.description,inputSchema:serializeInputSchema(i.inputSchema),outputSchema:serializeOutputSchema(i.outputSchema),resolverSlug:t.slug,entryKey:r,executeStepFnName:p,approvalStepFnName:h,closureVars:m})}}return{metadata:c,liveTools:l}}async function dispatchDynamicToolEvent(e){let{ctx:n,resolvers:r,event:i,messages:a}=e;if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(i.type))return;let o=r.filter(e=>e.eventNames.includes(i.type));if(o.length===0)return;let{metadata:s,liveTools:c}=await resolveToolsFromEvent(n,o,i,a);if(i.type===`step.started`){n.setVirtualContext(LiveStepToolsKey,c);return}let u=durableKeyForEvent(i.type);if(u===void 0)return;let d=new Set(o.map(e=>e.slug)),f=(n.get(u)??[]).filter(e=>!d.has(e.resolverSlug));n.set(u,[...f,...s])}export{dispatchDynamicToolEvent,replayDynamicSessionTools};