eve 0.45.2 → 0.46.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/src/channel/types.d.ts +2 -0
  3. package/dist/src/chunks/{use-eve-agent-DI2j5XK8.js → use-eve-agent-CacMaX4P.js} +91 -43
  4. package/dist/src/chunks/{use-eve-agent-BH7Z6SDu.js → use-eve-agent-kmlFdOBB.js} +91 -43
  5. package/dist/src/cli/commands/info.d.ts +2 -0
  6. package/dist/src/cli/commands/info.js +2 -2
  7. package/dist/src/cli/dev/tui/agent-header.d.ts +5 -14
  8. package/dist/src/cli/dev/tui/agent-header.js +1 -1
  9. package/dist/src/cli/dev/tui/prompt-commands.d.ts +2 -0
  10. package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
  11. package/dist/src/cli/dev/tui/runner.d.ts +7 -5
  12. package/dist/src/cli/dev/tui/runner.js +1 -1
  13. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +3 -3
  14. package/dist/src/cli/run.js +3 -3
  15. package/dist/src/client/message-reducer-primitives.d.ts +8 -0
  16. package/dist/src/client/message-reducer-primitives.js +1 -0
  17. package/dist/src/client/message-reducer-types.d.ts +2 -0
  18. package/dist/src/client/message-reducer.js +1 -1
  19. package/dist/src/compiled/.vendor-stamp.json +1 -1
  20. package/dist/src/compiled/@linqapp/chat-sdk-adapter/index.d.ts +2 -1
  21. package/dist/src/compiled/@linqapp/chat-sdk-adapter/index.js +3 -3
  22. package/dist/src/compiler/channel-route-plan.d.ts +2 -2
  23. package/dist/src/compiler/extension-compatibility.d.ts +18 -18
  24. package/dist/src/compiler/extension-compatibility.js +1 -1
  25. package/dist/src/compiler/instrumentation-layout-config.d.ts +3 -0
  26. package/dist/src/compiler/instrumentation-layout-config.js +1 -0
  27. package/dist/src/compiler/load-binding-namespace.d.ts +5 -3
  28. package/dist/src/compiler/load-binding-namespace.js +1 -1
  29. package/dist/src/compiler/manifest.d.ts +2 -2
  30. package/dist/src/compiler/manifest.js +1 -1
  31. package/dist/src/compiler/module-lifecycle.d.ts +14 -0
  32. package/dist/src/compiler/module-lifecycle.js +1 -0
  33. package/dist/src/compiler/module-map.d.ts +2 -2
  34. package/dist/src/compiler/module-map.js +2 -2
  35. package/dist/src/compiler/node-source-state.d.ts +6 -3
  36. package/dist/src/compiler/node-source-state.js +1 -1
  37. package/dist/src/compiler/normalize-agent-config.d.ts +2 -2
  38. package/dist/src/compiler/normalize-helpers.d.ts +4 -4
  39. package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
  40. package/dist/src/compiler/normalize-manifest.js +1 -1
  41. package/dist/src/compiler/remote-agent-node.js +1 -1
  42. package/dist/src/compiler/source-graph.d.ts +12 -2
  43. package/dist/src/compiler/source-graph.js +1 -1
  44. package/dist/src/compiler/validate-artifact.js +1 -1
  45. package/dist/src/context/keys.d.ts +2 -0
  46. package/dist/src/execution/tools/connection-search.js +1 -1
  47. package/dist/src/execution/workflow-runtime.js +1 -1
  48. package/dist/src/framework/sources/registry.js +1 -1
  49. package/dist/src/harness/channel-delivery-instrumentation.js +1 -1
  50. package/dist/src/harness/emission.d.ts +1 -8
  51. package/dist/src/harness/emission.js +1 -1
  52. package/dist/src/harness/instrumentation/content-policy.d.ts +3 -2
  53. package/dist/src/harness/instrumentation/content-policy.js +1 -1
  54. package/dist/src/harness/instrumentation/content.d.ts +11 -0
  55. package/dist/src/harness/instrumentation/content.js +1 -1
  56. package/dist/src/harness/ordered-stream-emitter.js +1 -1
  57. package/dist/src/harness/tool-loop.js +2 -2
  58. package/dist/src/internal/application/compiled-artifacts.d.ts +7 -7
  59. package/dist/src/internal/application/compiled-artifacts.js +2 -3
  60. package/dist/src/internal/application/package.js +1 -1
  61. package/dist/src/internal/authored-asset-import-plugin.d.ts +6 -2
  62. package/dist/src/internal/authored-asset-import-plugin.js +1 -1
  63. package/dist/src/internal/authored-module-loader.js +3 -3
  64. package/dist/src/internal/authored-module-map-loader.js +1 -1
  65. package/dist/src/internal/authored-runtime-modules.d.ts +15 -0
  66. package/dist/src/internal/authored-runtime-modules.js +1 -0
  67. package/dist/src/internal/materialized-authored-modules.d.ts +2 -18
  68. package/dist/src/internal/materialized-authored-modules.js +1 -1
  69. package/dist/src/internal/nitro/development-generation.js +1 -1
  70. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  71. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  72. package/dist/src/protocol/message.d.ts +29 -2
  73. package/dist/src/protocol/message.js +2 -2
  74. package/dist/src/public/channels/slack/inbound-content.js +2 -2
  75. package/dist/src/public/definitions/connections/tool-call.d.ts +2 -0
  76. package/dist/src/public/definitions/hook.d.ts +1 -0
  77. package/dist/src/public/instrumentation/otel.d.ts +1 -1
  78. package/dist/src/runtime/connections/mcp-client.d.ts +1 -1
  79. package/dist/src/runtime/connections/mcp-client.js +1 -1
  80. package/dist/src/runtime/connections/openapi-client.d.ts +1 -1
  81. package/dist/src/runtime/connections/openapi-client.js +1 -1
  82. package/dist/src/runtime/connections/provided-arguments.d.ts +1 -0
  83. package/dist/src/runtime/connections/provided-arguments.js +1 -1
  84. package/dist/src/setup/integrations/registry.js +1 -1
  85. package/dist/src/setup/integrations/shopify/setup.d.ts +20 -0
  86. package/dist/src/setup/integrations/shopify/setup.js +1 -0
  87. package/dist/src/setup/integrations/shopify/templates.d.ts +1 -0
  88. package/dist/src/setup/integrations/shopify/templates.js +88 -0
  89. package/dist/src/setup/scaffold/create/project.js +1 -1
  90. package/dist/src/shared/connection-types.d.ts +3 -1
  91. package/dist/src/shared/instrumentation-content.d.ts +6 -0
  92. package/dist/src/shared/instrumentation-content.js +1 -0
  93. package/dist/src/shared/instrumentation-decision.d.ts +8 -0
  94. package/dist/src/shared/instrumentation-decision.js +1 -0
  95. package/dist/src/svelte/index.js +1 -1
  96. package/dist/src/svelte/use-eve-agent.js +1 -1
  97. package/dist/src/tracing/agent-trace-context-store.d.ts +3 -3
  98. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  99. package/dist/src/tracing/otel-declaration.d.ts +14 -3
  100. package/dist/src/tracing/sampled-trace.d.ts +8 -1
  101. package/dist/src/tracing/sampled-trace.js +1 -1
  102. package/dist/src/vue/index.js +1 -1
  103. package/dist/src/vue/use-eve-agent.js +1 -1
  104. package/docs/agent-config.md +2 -0
  105. package/docs/channels/slack.mdx +2 -0
  106. package/docs/concepts/sessions-runs-and-streaming.md +5 -2
  107. package/docs/connections/mcp.mdx +1 -1
  108. package/docs/connections/openapi.mdx +1 -1
  109. package/docs/guides/client/streaming.mdx +18 -15
  110. package/docs/guides/dev-tui.md +2 -1
  111. package/docs/guides/dynamic-capabilities.md +2 -0
  112. package/docs/instructions.mdx +3 -1
  113. package/docs/reference/typescript-api.md +25 -0
  114. package/docs/schedules.mdx +2 -0
  115. package/docs/skills.mdx +2 -0
  116. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import type { ModuleSourceRef } from "#shared/source-ref.js";
2
2
  import type { ProjectedAgentSources, ProjectedSource, ProjectedSubagentSource } from "#compiler/project-sources.js";
3
- import { type AgentModuleCandidate, type AgentSourceCandidate, type ComposedAgentModuleCandidates, type CompiledModuleBinding } from "#compiler/source-graph.js";
3
+ import { type AgentModuleBinding, type AgentModuleCandidate, type AgentSourceCandidate, type ComposedAgentModuleCandidates } from "#compiler/source-graph.js";
4
+ import type { NodeModuleEvaluationContext } from "#compiler/module-lifecycle.js";
4
5
  export interface ComposedNodeSourceGraph {
5
6
  composed: ComposedAgentModuleCandidates;
6
7
  readonly orderedCandidates: readonly AgentSourceCandidate[];
@@ -9,16 +10,18 @@ export interface ComposedNodeSourceGraph {
9
10
  readonly subagentsBySourceId: ReadonlyMap<string, ProjectedSubagentSource>;
10
11
  }
11
12
  export interface SelectedNodeConfig {
12
- readonly binding: CompiledModuleBinding;
13
+ readonly binding: AgentModuleBinding;
13
14
  readonly candidate: AgentModuleCandidate;
14
15
  readonly definition: unknown;
15
16
  readonly source: ModuleSourceRef;
16
17
  }
17
18
  export interface PhaseOneNodeSourceState {
19
+ readonly evaluation: NodeModuleEvaluationContext;
18
20
  readonly graph: ComposedNodeSourceGraph;
19
21
  readonly selectedConfig: SelectedNodeConfig;
20
22
  }
21
23
  export interface FinalizedNodeSourceState extends ComposedNodeSourceGraph {
22
- readonly bindings: Record<string, CompiledModuleBinding>;
24
+ readonly bindings: Record<string, AgentModuleBinding>;
25
+ readonly evaluation: NodeModuleEvaluationContext;
23
26
  }
24
27
  export declare function finalizeNodeSourceState(phaseOne: PhaseOneNodeSourceState, externalDependencies: readonly string[]): FinalizedNodeSourceState;
@@ -1 +1 @@
1
- import{createCompiledModuleBinding}from"#compiler/source-graph.js";import{collectSelectedSourceIds,mergeExternalDependencies}from"#compiler/normalize-manifest-helpers.js";function finalizeNodeSourceState(n,r){let i=n.graph,a=new Map(i.orderedCandidates.map(e=>{let t=finalizeCandidateExternalDependencies(e,r);return[e.sourceId,t]})),candidateFor=e=>{let t=a.get(e.sourceId);if(t===void 0)throw Error(`Agent source candidate "${e.sourceId}" is missing from its node.`);return t},o={candidates:i.projected.candidates.map(candidateFor),resources:i.projected.resources.map(e=>({...e,candidate:candidateFor(e.candidate)})),subagents:i.projected.subagents.map(e=>({...e,candidate:candidateFor(e.candidate)}))},s={composition:{entries:i.composed.composition.entries.map(e=>({...e,source:finalizeDescriptorExternalDependencies(e.source,r)}))},selected:new Map([...i.composed.selected].map(([e,t])=>[e,candidateFor(t)]))},c=collectSelectedSourceIds(s);return{bindings:Object.fromEntries([...a.values()].filter(e=>c.has(e.sourceId)&&e.backing.kind!==`resource`).map(t=>[t.sourceId,createCompiledModuleBinding(t)])),composed:s,orderedCandidates:i.orderedCandidates.map(candidateFor),projected:o,sourcesBySourceId:new Map([...i.sourcesBySourceId].map(([e,t])=>[e,{...t,candidate:candidateFor(t.candidate)}])),subagentsBySourceId:new Map(o.subagents.map(e=>[e.candidate.sourceId,e]))}}function finalizeCandidateExternalDependencies(e,t){return e.backing.kind===`filesystem`?{...e,backing:finalizeBackingExternalDependencies(e.backing,t)}:e}function finalizeDescriptorExternalDependencies(e,t){return e.backing.kind===`filesystem`?{...e,backing:finalizeBackingExternalDependencies(e.backing,t)}:e}function finalizeBackingExternalDependencies(e,t){return{...e,externalDependencies:mergeExternalDependencies(t,e.externalDependencies)}}export{finalizeNodeSourceState};
1
+ import{createAgentModuleBinding}from"#compiler/source-graph.js";import{collectSelectedSourceIds,mergeExternalDependencies}from"#compiler/normalize-manifest-helpers.js";function finalizeNodeSourceState(n,r){let i=n.graph,a=new Map(i.orderedCandidates.map(e=>{let t=finalizeCandidateExternalDependencies(e,r);return[e.sourceId,t]})),candidateFor=e=>{let t=a.get(e.sourceId);if(t===void 0)throw Error(`Agent source candidate "${e.sourceId}" is missing from its node.`);return t},o={candidates:i.projected.candidates.map(candidateFor),resources:i.projected.resources.map(e=>({...e,candidate:candidateFor(e.candidate)})),subagents:i.projected.subagents.map(e=>({...e,candidate:candidateFor(e.candidate)}))},s={composition:{entries:i.composed.composition.entries.map(e=>({...e,source:finalizeDescriptorExternalDependencies(e.source,r)}))},selected:new Map([...i.composed.selected].map(([e,t])=>[e,candidateFor(t)]))},c=collectSelectedSourceIds(s),l=Object.fromEntries([...a.values()].filter(e=>c.has(e.sourceId)&&e.backing.kind!==`resource`).map(t=>[t.sourceId,createAgentModuleBinding(t)]));return n.evaluation.setBindings(l),{bindings:l,composed:s,orderedCandidates:i.orderedCandidates.map(candidateFor),projected:o,sourcesBySourceId:new Map([...i.sourcesBySourceId].map(([e,t])=>[e,{...t,candidate:candidateFor(t.candidate)}])),subagentsBySourceId:new Map(o.subagents.map(e=>[e.candidate.sourceId,e])),evaluation:n.evaluation}}function finalizeCandidateExternalDependencies(e,t){return e.backing.kind===`filesystem`?{...e,backing:finalizeBackingExternalDependencies(e.backing,t)}:e}function finalizeDescriptorExternalDependencies(e,t){return e.backing.kind===`filesystem`?{...e,backing:finalizeBackingExternalDependencies(e.backing,t)}:e}function finalizeBackingExternalDependencies(e,t){return{...e,externalDependencies:mergeExternalDependencies(t,e.externalDependencies)}}export{finalizeNodeSourceState};
@@ -2,13 +2,13 @@ import type { AgentSourceManifest } from "#discover/manifest.js";
2
2
  import type { ModuleSourceRef } from "#shared/source-ref.js";
3
3
  import type { CompiledAgentDefinition } from "#compiler/manifest.js";
4
4
  import { type ManifestCompileContext } from "#compiler/normalize-helpers.js";
5
- import type { CompiledModuleBinding } from "#compiler/source-graph.js";
5
+ import type { AgentModuleBinding } from "#compiler/source-graph.js";
6
6
  /**
7
7
  * Compiles the agent-level configuration (model, compaction, build,
8
8
  * workspace) for one authored agent node.
9
9
  */
10
10
  export declare function compileAgentConfig(manifest: AgentSourceManifest, context: ManifestCompileContext, options: {
11
- readonly binding: CompiledModuleBinding;
11
+ readonly binding: AgentModuleBinding;
12
12
  readonly definition?: unknown;
13
13
  readonly source: ModuleSourceRef;
14
14
  }): Promise<CompiledAgentDefinition>;
@@ -1,6 +1,6 @@
1
1
  import type { ModuleSourceRef } from "#shared/source-ref.js";
2
2
  import type { CompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
3
- import { type AgentSourceRegistry, type CompiledModuleBinding, type AgentSourceOwner, type ProgrammaticModuleNamespace } from "#compiler/source-graph.js";
3
+ import { type AgentModuleBinding, type AgentSourceRegistry, type AgentSourceOwner, type ProgrammaticModuleNamespace } from "#compiler/source-graph.js";
4
4
  import type { CompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
5
5
  /**
6
6
  * Shared compile-time context threaded through every per-primitive
@@ -15,11 +15,11 @@ export interface ManifestCompileContext {
15
15
  readonly registries: readonly AgentSourceRegistry[];
16
16
  }
17
17
  export interface ModuleBackedDefinitionLoadOptions {
18
- readonly binding: CompiledModuleBinding;
18
+ readonly binding: AgentModuleBinding;
19
19
  readonly loadNamespace: CompiledBindingNamespaceLoader;
20
20
  }
21
21
  export interface SourceDefinitionCompileOptions {
22
- readonly binding?: CompiledModuleBinding;
22
+ readonly binding?: AgentModuleBinding;
23
23
  readonly loadNamespace?: CompiledBindingNamespaceLoader;
24
24
  readonly owner: AgentSourceOwner;
25
25
  }
@@ -34,7 +34,7 @@ export declare function requireModuleBackedDefinitionLoadOptions(options: Source
34
34
  * authored file failed.
35
35
  */
36
36
  export declare function loadModuleBackedDefinition(input: {
37
- readonly binding: CompiledModuleBinding;
37
+ readonly binding: AgentModuleBinding;
38
38
  readonly dependencyNamespaces?: Readonly<Record<string, ProgrammaticModuleNamespace>>;
39
39
  readonly displayPath?: string;
40
40
  readonly kind: string;
@@ -1 +1 @@
1
- import{posix}from"node:path";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{canonicalSourceSlot}from"#compiler/source-graph.js";import{mountRefNamespace,packageStateNamespace}from"#discover/extensions.js";import"#compiler/normalize-subagent.js";function collectSelectedSourceIds(e){return new Set([...e.selected.values()].map(e=>e.sourceId))}function assertRootOnlyConfig(e,t,n){if(!t){if(e.experimental?.workflow!==void 0)throw Error(`Workflow runtime configuration is only supported on the root agent config. Remove "experimental.workflow" from "${n}".`);if(e.experimental?.tasks!==void 0)throw Error(`Background tasks are only supported on the root agent config. Remove "experimental.tasks" from "${n}".`)}}function assertApplicationOverlayCanApplyToAllNodes(e){let t=e.find(e=>{let t=canonicalSourceSlot(e);return t===`agent`||t.startsWith(`channels/`)||t.startsWith(`schedules/`)||t.startsWith(`subagents/`)||t.startsWith(`extensions/`)});if(t!==void 0)throw Error(`Application programmatic source registered for all local nodes cannot declare "${t}".`)}function assertUniqueRegistryIds(e){let t=new Set;for(let n of e)for(let e of n.sources.keys()){if(t.has(e))throw Error(`Programmatic agent source id "${e}" is registered more than once.`);t.add(e)}}function assertRootOwnedSpecialTool(e,n){if(e.nodeId!==ROOT_COMPILED_AGENT_NODE_ID)throw Error(`${n} can only be enabled on the root agent.`);assertNonExtensionSpecialTool(e,n)}function assertNonExtensionSpecialTool(e,t){if(e.owner.kind===`extension`)throw Error(`${t} cannot be configured by an extension source.`)}function withExtensionNamespace(e,t){return t.kind===`extension`?{...e,extensionNamespace:t.namespace}:e}function assertUniqueBy(e,t,n){let r=new Set;for(let i of e){let e=t(i);if(r.has(e))throw Error(`Compiled ${n} "${e}" is declared more than once.`);r.add(e)}}function expectSubagentDescription(e,t){if(e.description===void 0||e.description.trim().length===0)throw Error(`Subagent "${t.logicalPath}" must define a non-empty description.`);return e.description}function createCompiledRemoteAgent(t){let n=t.source.logicalPath.endsWith(`.ts`)||t.source.logicalPath.endsWith(`.js`)?t.source.logicalPath:posix.join(t.source.logicalPath,`agent.ts`),r=t.source.sourceId,i={backing:t.binding.backing,logicalPath:n,owner:t.owner},a={backing:{kind:`resource`,sourcePath:t.source.entryPath},binding:i,description:t.definition.description,entryPath:t.source.entryPath,logicalPath:n,name:t.source.subagentId,nodeId:t.nodeId,owner:t.owner,parentNodeId:t.parentNodeId,path:t.definition.path,rootPath:t.source.rootPath,sourceId:r,sourceKind:`module`};return t.sourceRef.exportName!==void 0&&Object.assign(a,{exportName:t.sourceRef.exportName}),t.definition.outputSchema!==void 0&&Object.assign(a,{outputSchema:t.definition.outputSchema}),t.definition.url!==void 0&&Object.assign(a,{url:t.definition.url}),a}function compileExtensionMounts(e,t){let n=collectSelectedSourceIds(t);return e.resolvedExtensions.flatMap(t=>{let a=e.extensions.find(e=>mountRefNamespace(e.logicalPath)===t.namespace);return a===void 0||!n.has(a.sourceId)?[]:[{externalDependencies:[...t.externalDependencies],mountLogicalPath:a.logicalPath,mountSourceId:a.sourceId,namespace:t.namespace,packageName:t.packageName,packageNamespace:packageStateNamespace(t.packageName),sourceRoot:t.sourceRoot}]})}function mergeExternalDependencies(...e){return[...new Set(e.flatMap(e=>e??[]))]}export{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withExtensionNamespace};
1
+ import{posix}from"node:path";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{canonicalSourceSlot}from"#compiler/source-graph.js";import{mountRefNamespace,packageStateNamespace}from"#discover/extensions.js";import"#compiler/normalize-subagent.js";function collectSelectedSourceIds(e){return new Set([...e.selected.values()].map(e=>e.sourceId))}function assertRootOnlyConfig(e,t,n){if(!t){if(e.experimental?.workflow!==void 0)throw Error(`Workflow runtime configuration is only supported on the root agent config. Remove "experimental.workflow" from "${n}".`);if(e.experimental?.tasks!==void 0)throw Error(`Background tasks are only supported on the root agent config. Remove "experimental.tasks" from "${n}".`)}}function assertApplicationOverlayCanApplyToAllNodes(e){let t=e.find(e=>{let t=canonicalSourceSlot(e);return t===`agent`||t.startsWith(`channels/`)||t.startsWith(`schedules/`)||t.startsWith(`subagents/`)||t.startsWith(`extensions/`)});if(t!==void 0)throw Error(`Application programmatic source registered for all local nodes cannot declare "${t}".`)}function assertUniqueRegistryIds(e){let t=new Set;for(let n of e)for(let e of n.sources.keys()){if(t.has(e))throw Error(`Programmatic agent source id "${e}" is registered more than once.`);t.add(e)}}function assertRootOwnedSpecialTool(e,n){if(e.nodeId!==ROOT_COMPILED_AGENT_NODE_ID)throw Error(`${n} can only be enabled on the root agent.`);assertNonExtensionSpecialTool(e,n)}function assertNonExtensionSpecialTool(e,t){if(e.owner.kind===`extension`)throw Error(`${t} cannot be configured by an extension source.`)}function withExtensionNamespace(e,t){return t.kind===`extension`?{...e,extensionNamespace:t.namespace}:e}function assertUniqueBy(e,t,n){let r=new Set;for(let i of e){let e=t(i);if(r.has(e))throw Error(`Compiled ${n} "${e}" is declared more than once.`);r.add(e)}}function expectSubagentDescription(e,t){if(e.description===void 0||e.description.trim().length===0)throw Error(`Subagent "${t.logicalPath}" must define a non-empty description.`);return e.description}function createCompiledRemoteAgent(t){let n=t.source.logicalPath.endsWith(`.ts`)||t.source.logicalPath.endsWith(`.js`)?t.source.logicalPath:posix.join(t.source.logicalPath,`agent.ts`),r=t.source.sourceId,i={backing:t.binding.backing,logicalPath:n,owner:t.owner,usage:t.binding.usage},a={backing:{kind:`resource`,sourcePath:t.source.entryPath},binding:i,description:t.definition.description,entryPath:t.source.entryPath,logicalPath:n,name:t.source.subagentId,nodeId:t.nodeId,owner:t.owner,parentNodeId:t.parentNodeId,path:t.definition.path,rootPath:t.source.rootPath,sourceId:r,sourceKind:`module`};return t.sourceRef.exportName!==void 0&&Object.assign(a,{exportName:t.sourceRef.exportName}),t.definition.outputSchema!==void 0&&Object.assign(a,{outputSchema:t.definition.outputSchema}),t.definition.url!==void 0&&Object.assign(a,{url:t.definition.url}),a}function compileExtensionMounts(e,t){let n=collectSelectedSourceIds(t);return e.resolvedExtensions.flatMap(t=>{let a=e.extensions.find(e=>mountRefNamespace(e.logicalPath)===t.namespace);return a===void 0||!n.has(a.sourceId)?[]:[{externalDependencies:[...t.externalDependencies],mountLogicalPath:a.logicalPath,mountSourceId:a.sourceId,namespace:t.namespace,packageName:t.packageName,packageNamespace:packageStateNamespace(t.packageName),sourceRoot:t.sourceRoot}]})}function mergeExternalDependencies(...e){return[...new Set(e.flatMap(e=>e??[]))]}export{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withExtensionNamespace};
@@ -1 +1 @@
1
- import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId}from"#compiler/manifest.js";import{summarizeCompilerDiagnostics}from"#compiler/diagnostics.js";import{canonicalSourceSlot,composeAgentModuleCandidates,createCompiledModuleBinding,createProgrammaticModuleCandidates,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate}from"#compiler/source-graph.js";import{frameworkAgentSourceRegistry,memoryWrapperTemplate}from"#framework/sources/registry.js";import{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withExtensionNamespace}from"#compiler/normalize-manifest-helpers.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{assertRemoteAgentDefinitionHasNoLocalPackageEntries,normalizeSubagentConfig}from"#compiler/normalize-subagent.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileInstructionsEntry}from"#compiler/normalize-instructions.js";import{compileMemoryDefinition,deriveMemorySlot}from"#compiler/normalize-memory.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileSkillSource}from"#compiler/normalize-skill.js";import{compileToolEntry}from"#compiler/normalize-tool.js";import{createCompiledChannelRoutePlan}from"#compiler/channel-route-plan.js";import{finalizeNodeSourceState}from"#compiler/node-source-state.js";import{projectAgentSources,projectSelectedSources}from"#compiler/project-sources.js";async function compileAgentManifest(e,t={}){let i=[frameworkAgentSourceRegistry,...t.sourceRegistries??[]];assertUniqueRegistryIds(i);let a={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot),registries:i},o=t.diagnostics??[],c=await new AgentGraphCompiler(a,i,o).compileStaticNode({inheritedExternalDependencies:[],isRoot:!0,layer:`application`,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID,owner:{kind:`application`}}),l=[c.manifest,...c.descendants.map(e=>e.agent)].flatMap(e=>e.tools).find(e=>e.execution===`background`);if(l!==void 0&&c.manifest.config.experimental?.tasks!==!0)throw Error(`Background tool "${l.name}" requires experimental.tasks: true in the root agent config.`);let u=summarizeCompilerDiagnostics(o),d=c.descendants.map(e=>(e.configResolver,{...e,agent:{...e.agent,diagnosticsSummary:u}}));return createCompiledAgentManifest({...c.manifest,diagnosticsSummary:u,subagents:d})}var AgentGraphCompiler=class{context;registries;diagnostics;constructor(e,t,n){this.context=e,this.registries=t,this.diagnostics=n}async compileStaticNode(e){let t=await this.createPhaseOneNodeSourceState(e,e.inheritedExternalDependencies),n=await compileAgentConfig(e.manifest,this.context,{binding:t.selectedConfig.binding,definition:t.selectedConfig.definition,source:t.selectedConfig.source});assertRootOnlyConfig(n,e.isRoot,e.manifest.agentId);let r=mergeExternalDependencies(e.inheritedExternalDependencies,n.build?.externalDependencies,e.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));r.length>0&&(n={...n,build:{...n.build,externalDependencies:r}});let a=finalizeNodeSourceState(t,r);assertInstrumentationLayoutConfig(n,a);let o=await this.compileResources(e,a),s=await this.compileChildren(e,a,r),c=createCompiledAgentNodeManifest({...o,config:n,remoteAgents:s.remoteAgents});return{descendants:s.nodes,manifest:c}}async compileChildren(e,t,n){let r=[],s=[],c=collectSelectedSourceIds(t.composed),l=t.projected.subagents.filter(e=>c.has(e.candidate.sourceId));for(let t of l){let c=t.source,l=createCompiledSubagentNodeId(e.nodeId,c.sourceId),u={extensionScope:t.extensionScope??e.extensionScope,inheritedExternalDependencies:n,isRoot:!1,layer:t.candidate.layer,manifest:c.manifest,nodeId:l,owner:t.owner,parentNodeId:e.nodeId},d=await this.createPhaseOneNodeSourceState(u,n),f=normalizeSubagentConfig(d.selectedConfig.definition,`Expected the subagent config export "${d.selectedConfig.source.exportName??`default`}" from "${c.entryPath}" to match the public eve shape.`);if(f.kind===`remote`){assertRemoteAgentDefinitionHasNoLocalPackageEntries(c),s.push(createCompiledRemoteAgent({binding:d.selectedConfig.binding,definition:f,nodeId:l,owner:t.owner,parentNodeId:e.nodeId,source:c,sourceRef:d.selectedConfig.source}));continue}let p,m;f.kind===`local`?(p=await compileAgentConfig(c.manifest,this.context,{binding:d.selectedConfig.binding,definition:f.definition,source:d.selectedConfig.source}),assertRootOnlyConfig(p,!1,c.manifest.agentId)):m=f.build?.externalDependencies;let h=mergeExternalDependencies(n,p?.build?.externalDependencies,m,c.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));p!==void 0&&h.length>0&&(p={...p,build:{...p.build,externalDependencies:h}});let g=finalizeNodeSourceState(d,h);p!==void 0&&assertInstrumentationLayoutConfig(p,g);let _=await this.compileResources(u,g),v=await this.compileChildren(u,g,h),b={backing:t.candidate.backing,entryPath:c.entryPath,logicalPath:c.logicalPath,name:c.subagentId,nodeId:l,owner:t.owner,parentNodeId:e.nodeId,rootPath:c.rootPath,sourceId:c.sourceId,sourceKind:`module`},x;x=p===void 0?{...b,agent:createCompiledAgentResources({..._,remoteAgents:v.remoteAgents}),configResolver:{build:f.kind===`dynamic`?f.build:void 0,eventNames:f.kind===`dynamic`?f.eventNames:[],exportName:d.selectedConfig.source.exportName,logicalPath:d.selectedConfig.source.logicalPath,sourceId:d.selectedConfig.source.sourceId,sourceKind:`module`}}:{...b,agent:createCompiledAgentNodeManifest({..._,config:p,remoteAgents:v.remoteAgents}),description:expectSubagentDescription(p,c)},r.push(x,...v.nodes)}return{nodes:r,remoteAgents:s}}composeNodeSources(e,t){let n=projectAgentSources({externalDependencies:t,extensionScope:e.extensionScope,layer:e.layer,manifest:e.manifest,nodeId:e.nodeId,owner:e.owner}),r=[],i=[];for(let t of this.registries){let n=t===frameworkAgentSourceRegistry;for(let a of t.registrations){if(a.applyTo===`root`&&!e.isRoot)continue;!n&&a.applyTo===`all-local-nodes`&&assertApplicationOverlayCanApplyToAllNodes(a.source.modules.map(e=>e.logicalPath));let t=createProgrammaticModuleCandidates({layer:n?`framework-default`:`application`,nodeId:e.nodeId,owner:n?{feature:a.source.id,kind:`framework`}:{kind:`application`},registration:a});(n?r:i).push(...t)}}let a=[...n.candidates,...i].filter(e=>e.backing.kind!==`resource`&&(canonicalSourceSlot(e.logicalPath)===`memory`||canonicalSourceSlot(e.logicalPath).startsWith(`memory/`))).map(e=>{let t=deriveMemorySlot(e.logicalPath);return instantiateProgrammaticTemplate({anchor:e,dependencies:{memory:e},logicalPath:`tools/${t}.ts`,owner:{feature:`memory`,kind:`framework`},parameters:{memoryExportName:e.exportName??`default`,memoryLogicalPath:e.logicalPath,slot:t},template:memoryWrapperTemplate})}),o=[...r,...n.candidates,...a,...i],s=composeAgentModuleCandidates(o),u=projectSelectedSources({candidates:s.selected.values(),resources:n.resources});return{composed:s,orderedCandidates:o,projected:n,sourcesBySourceId:new Map(u.map(e=>[e.candidate.sourceId,e])),subagentsBySourceId:new Map(n.subagents.map(e=>[e.candidate.sourceId,e]))}}async createPhaseOneNodeSourceState(e,t){let n=this.composeNodeSources(e,t);return{graph:n,selectedConfig:await this.loadSelectedConfig(n)}}async loadSelectedConfig(e){let n=e.composed.selected.get(`agent`);if(n===void 0||!isModuleCandidate(n))throw Error(`Every local agent node requires a selected module-backed agent.ts source.`);let r=createCompiledModuleBinding(n),i=e.sourcesBySourceId.get(n.sourceId);if(i?.source.sourceKind!==`module`)throw Error(`Selected agent config source "${n.sourceId}" was not projected.`);let a=i.source;return{binding:r,candidate:n,definition:await loadModuleBackedDefinition({binding:r,kind:`agent config`,loadNamespace:createCompiledBindingNamespaceLoader({bindings:{[n.sourceId]:r},registries:this.registries}),source:a}),source:a}}async compileResources(n,r){let i=[],o=[],c=[],l=[],u=[],d=[],m=[],h=[],g=[],_=[],y=[],S,C,w,T,E=collectSelectedSourceIds(r.composed),D=createCompiledBindingNamespaceLoader({bindings:r.bindings,registries:this.registries});for(let t of r.orderedCandidates){if(!E.has(t.sourceId))continue;let a=r.sourcesBySourceId.get(t.sourceId);if(a===void 0)continue;let s=r.bindings[t.sourceId],f={binding:s,loadNamespace:D,owner:t.owner};switch(a.kind){case`config`:case`extension`:break;case`channel`:{let i=await compileChannelDefinition(n.manifest.agentRoot,a.source,{binding:s,loadNamespace:D});i.kind===`disabled`?(r.composed=disableComposedCandidate({candidate:t,composed:r.composed}),delete r.bindings[t.sourceId],E.delete(t.sourceId)):y.push(...i.definitions);break}case`connection`:m.push(await compileConnectionDefinition(n.manifest.agentRoot,a.source,{binding:s,loadNamespace:D}));break;case`hook`:g.push(await compileHookEntry(a.source,{binding:s,loadNamespace:D}));break;case`instructions`:{let e=await compileInstructionsEntry(n.manifest.agentRoot,a.source,f);e.kind===`instructions`?u.push(e.definition):d.push(e.definition);break}case`instrumentation`:C=a.source;break;case`memory`:h.push(await compileMemoryDefinition(a.source,{binding:s,loadNamespace:D}));break;case`sandbox`:S=await compileSandboxDefinition(n.manifest.agentRoot,a.source,{binding:s,loadNamespace:D});break;case`schedule`:_.push(await compileScheduleDefinition(n.manifest.agentRoot,a.source,f));break;case`skill`:{let e=await compileSkillSource(n.manifest.agentRoot,a.source,f);e.kind===`skill`?c.push(e.definition):l.push(withExtensionNamespace(e.definition,t.owner));break}case`tool`:{let e=await compileToolEntry(n.manifest.agentRoot,a.source,{binding:s,loadNamespace:D});e.kind===`disabled`?(r.composed=disableComposedCandidate({candidate:t,composed:r.composed}),delete r.bindings[t.sourceId],E.delete(t.sourceId)):e.kind===`tool`?i.push(e.definition):e.kind===`dynamic-tool`?o.push(withExtensionNamespace(e.definition,t.owner)):e.kind===`workflow-tool`?(assertRootOwnedSpecialTool(t,`Workflow`),w={...a.source,maxSubagents:e.maxSubagents}):(assertNonExtensionSpecialTool(t,`Web search`),i.push(e.definition),T=e.provider);break}}}if(S===void 0)throw Error(`Agent node "${n.nodeId}" has no selected sandbox source.`);assertUniqueBy(i,e=>e.name,`tool name`),assertUniqueBy(o,e=>e.slug,`dynamic tool slug`),assertUniqueBy(m,e=>e.connectionName,`connection name`),assertUniqueBy(c,e=>e.name,`skill name`);let O=createCompiledChannelRoutePlan({bindings:r.bindings,channels:y,diagnostics:this.diagnostics,nodeId:n.nodeId,sources:Object.fromEntries(r.orderedCandidates.map(e=>[e.sourceId,describeAgentSourceCandidate(e)]))});return createCompiledAgentResources({agentRoot:n.manifest.agentRoot,appRoot:n.manifest.appRoot,bindings:r.bindings,channelRoutes:O,connections:m,diagnosticsSummary:summarizeCompilerDiagnostics(this.diagnostics),dynamicInstructions:d,dynamicSkills:l,dynamicTools:o,extensionMounts:compileExtensionMounts(n.manifest,r.composed),hooks:g,memories:h,instructions:u,instrumentation:C,sandbox:S,sandboxWorkspaces:n.manifest.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:_,skills:c,sourceComposition:r.composed.composition,tools:i,webSearchProvider:T,workflowTool:w})}};function isModuleCandidate(e){return e.backing.kind!==`resource`}function assertInstrumentationLayoutConfig(e,t){if(e.experimental?.instrumentationProviders===!0&&t.composed.selected.has(`instrumentation`))throw Error(`A selected instrumentation.ts source cannot be used with experimental.instrumentationProviders. Move the declaration into the instrumentation/ provider directory.`)}export{compileAgentManifest};
1
+ import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId}from"#compiler/manifest.js";import{summarizeCompilerDiagnostics}from"#compiler/diagnostics.js";import{canonicalSourceSlot,composeAgentModuleCandidates,createAgentModuleBinding,createProgrammaticModuleCandidates,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate,isAgentModuleCandidate}from"#compiler/source-graph.js";import{frameworkAgentSourceRegistry,memoryWrapperTemplate}from"#framework/sources/registry.js";import{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withExtensionNamespace}from"#compiler/normalize-manifest-helpers.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{assertRemoteAgentDefinitionHasNoLocalPackageEntries,normalizeSubagentConfig}from"#compiler/normalize-subagent.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{NodeModuleEvaluationContext,markConfigRuntimeEntries}from"#compiler/module-lifecycle.js";import{assertInstrumentationLayoutConfig}from"#compiler/instrumentation-layout-config.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileInstructionsEntry}from"#compiler/normalize-instructions.js";import{compileMemoryDefinition,deriveMemorySlot}from"#compiler/normalize-memory.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileSkillSource}from"#compiler/normalize-skill.js";import{compileToolEntry}from"#compiler/normalize-tool.js";import{createCompiledChannelRoutePlan}from"#compiler/channel-route-plan.js";import{finalizeNodeSourceState}from"#compiler/node-source-state.js";import{projectAgentSources,projectSelectedSources}from"#compiler/project-sources.js";async function compileAgentManifest(e,r={}){let i=[frameworkAgentSourceRegistry,...r.sourceRegistries??[]];assertUniqueRegistryIds(i);let a={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot),registries:i},s=r.diagnostics??[],c=await new AgentGraphCompiler(a,i,s).compileStaticNode({inheritedExternalDependencies:[],isRoot:!0,layer:`application`,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID,owner:{kind:`application`}}),l=[c.manifest,...c.descendants.map(e=>e.agent)].flatMap(e=>e.tools).find(e=>e.execution===`background`);if(l!==void 0&&c.manifest.config.experimental?.tasks!==!0)throw Error(`Background tool "${l.name}" requires experimental.tasks: true in the root agent config.`);let u=summarizeCompilerDiagnostics(s),d=c.descendants.map(e=>(e.configResolver,{...e,agent:{...e.agent,diagnosticsSummary:u}}));return createCompiledAgentManifest({...c.manifest,diagnosticsSummary:u,subagents:d})}var AgentGraphCompiler=class{context;registries;diagnostics;constructor(e,t,n){this.context=e,this.registries=t,this.diagnostics=n}async compileStaticNode(e){let t=await this.createPhaseOneNodeSourceState(e,e.inheritedExternalDependencies),n=await compileAgentConfig(e.manifest,this.context,{binding:t.selectedConfig.binding,definition:t.selectedConfig.definition,source:t.selectedConfig.source});assertRootOnlyConfig(n,e.isRoot,e.manifest.agentId);let i=mergeExternalDependencies(e.inheritedExternalDependencies,n.build?.externalDependencies,e.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));i.length>0&&(n={...n,build:{...n.build,externalDependencies:i}});let a=finalizeNodeSourceState(t,i);markConfigRuntimeEntries(n,a.evaluation),assertInstrumentationLayoutConfig(n,a);let o=await this.compileResources(e,a),s=await this.compileChildren(e,a,i),c=createCompiledAgentNodeManifest({...o,config:n,remoteAgents:s.remoteAgents});return{descendants:s.nodes,manifest:c}}async compileChildren(e,t,n){let o=[],s=[],c=collectSelectedSourceIds(t.composed),l=t.projected.subagents.filter(e=>c.has(e.candidate.sourceId));for(let t of l){let c=t.source,l=createCompiledSubagentNodeId(e.nodeId,c.sourceId),u={extensionScope:t.extensionScope??e.extensionScope,inheritedExternalDependencies:n,isRoot:!1,layer:t.candidate.layer,manifest:c.manifest,nodeId:l,owner:t.owner,parentNodeId:e.nodeId},d=await this.createPhaseOneNodeSourceState(u,n),f=normalizeSubagentConfig(d.selectedConfig.definition,`Expected the subagent config export "${d.selectedConfig.source.exportName??`default`}" from "${c.entryPath}" to match the public eve shape.`);if(f.kind===`remote`){assertRemoteAgentDefinitionHasNoLocalPackageEntries(c);let n=d.selectedConfig.source.sourceId;d.evaluation.setBindings({[n]:d.selectedConfig.binding}),d.evaluation.requireRuntimeEntry(n);let r=d.evaluation.finalizeBindings()[n];if(r===void 0)throw Error(`Remote subagent "${l}" has no finalized config binding.`);s.push(createCompiledRemoteAgent({binding:r,definition:f,nodeId:l,owner:t.owner,parentNodeId:e.nodeId,source:c,sourceRef:d.selectedConfig.source}));continue}let p,m;f.kind===`local`?(p=await compileAgentConfig(c.manifest,this.context,{binding:d.selectedConfig.binding,definition:f.definition,source:d.selectedConfig.source}),assertRootOnlyConfig(p,!1,c.manifest.agentId)):m=f.build?.externalDependencies;let h=mergeExternalDependencies(n,p?.build?.externalDependencies,m,c.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));p!==void 0&&h.length>0&&(p={...p,build:{...p.build,externalDependencies:h}});let g=finalizeNodeSourceState(d,h);p===void 0?g.evaluation.requireRuntimeEntry(d.selectedConfig.source.sourceId):markConfigRuntimeEntries(p,g.evaluation),p!==void 0&&assertInstrumentationLayoutConfig(p,g);let _=await this.compileResources(u,g),v=await this.compileChildren(u,g,h),b={backing:t.candidate.backing,entryPath:c.entryPath,logicalPath:c.logicalPath,name:c.subagentId,nodeId:l,owner:t.owner,parentNodeId:e.nodeId,rootPath:c.rootPath,sourceId:c.sourceId,sourceKind:`module`},x;x=p===void 0?{...b,agent:createCompiledAgentResources({..._,remoteAgents:v.remoteAgents}),configResolver:{build:f.kind===`dynamic`?f.build:void 0,eventNames:f.kind===`dynamic`?f.eventNames:[],exportName:d.selectedConfig.source.exportName,logicalPath:d.selectedConfig.source.logicalPath,sourceId:d.selectedConfig.source.sourceId,sourceKind:`module`}}:{...b,agent:createCompiledAgentNodeManifest({..._,config:p,remoteAgents:v.remoteAgents}),description:expectSubagentDescription(p,c)},o.push(x,...v.nodes)}return{nodes:o,remoteAgents:s}}composeNodeSources(e,t){let n=projectAgentSources({externalDependencies:t,extensionScope:e.extensionScope,layer:e.layer,manifest:e.manifest,nodeId:e.nodeId,owner:e.owner}),r=[],i=[];for(let t of this.registries){let n=t===frameworkAgentSourceRegistry;for(let a of t.registrations){if(a.applyTo===`root`&&!e.isRoot)continue;!n&&a.applyTo===`all-local-nodes`&&assertApplicationOverlayCanApplyToAllNodes(a.source.modules.map(e=>e.logicalPath));let t=createProgrammaticModuleCandidates({layer:n?`framework-default`:`application`,nodeId:e.nodeId,owner:n?{feature:a.source.id,kind:`framework`}:{kind:`application`},registration:a});(n?r:i).push(...t)}}let a=[...n.candidates,...i].filter(e=>e.backing.kind!==`resource`&&(canonicalSourceSlot(e.logicalPath)===`memory`||canonicalSourceSlot(e.logicalPath).startsWith(`memory/`))).map(e=>{let t=deriveMemorySlot(e.logicalPath);return instantiateProgrammaticTemplate({anchor:e,dependencies:{memory:e},logicalPath:`tools/${t}.ts`,owner:{feature:`memory`,kind:`framework`},parameters:{memoryExportName:e.exportName??`default`,memoryLogicalPath:e.logicalPath,slot:t},template:memoryWrapperTemplate})}),o=[...r,...n.candidates,...a,...i],l=composeAgentModuleCandidates(o),d=projectSelectedSources({candidates:l.selected.values(),resources:n.resources});return{composed:l,orderedCandidates:o,projected:n,sourcesBySourceId:new Map(d.map(e=>[e.candidate.sourceId,e])),subagentsBySourceId:new Map(n.subagents.map(e=>[e.candidate.sourceId,e]))}}async createPhaseOneNodeSourceState(e,t){let n=this.composeNodeSources(e,t),r=new NodeModuleEvaluationContext(this.registries);return r.setBindings(Object.fromEntries([...n.composed.selected.values()].filter(isAgentModuleCandidate).map(e=>[e.sourceId,createAgentModuleBinding(e)]))),{evaluation:r,graph:n,selectedConfig:await this.loadSelectedConfig(n,r)}}async loadSelectedConfig(e,t){let n=e.composed.selected.get(`agent`);if(n===void 0||!isAgentModuleCandidate(n))throw Error(`Every local agent node requires a selected module-backed agent.ts source.`);let r=createAgentModuleBinding(n),i=e.sourcesBySourceId.get(n.sourceId);if(i?.source.sourceKind!==`module`)throw Error(`Selected agent config source "${n.sourceId}" was not projected.`);let a=i.source;return{binding:r,candidate:n,definition:await loadModuleBackedDefinition({binding:r,kind:`agent config`,loadNamespace:t.loadNamespace,source:a}),source:a}}async compileResources(t,n){let r=[],a=[],s=[],c=[],l=[],u=[],p=[],m=[],h=[],g=[],_=[],y,S,C,w,T=collectSelectedSourceIds(n.composed),E=n.evaluation.loadNamespace;for(let i of n.orderedCandidates){if(!T.has(i.sourceId))continue;let o=n.sourcesBySourceId.get(i.sourceId);if(o===void 0)continue;let d=n.bindings[i.sourceId],x={binding:d,loadNamespace:E,owner:i.owner};switch(o.kind){case`config`:case`extension`:break;case`channel`:{let r=await compileChannelDefinition(t.manifest.agentRoot,o.source,{binding:d,loadNamespace:E});r.kind===`disabled`?(n.composed=disableComposedCandidate({candidate:i,composed:n.composed}),delete n.bindings[i.sourceId],T.delete(i.sourceId)):_.push(...r.definitions);break}case`connection`:p.push(await compileConnectionDefinition(t.manifest.agentRoot,o.source,{binding:d,loadNamespace:E})),n.evaluation.requireRuntimeEntry(i.sourceId);break;case`hook`:h.push(await compileHookEntry(o.source,{binding:d,loadNamespace:E})),n.evaluation.requireRuntimeEntry(i.sourceId);break;case`instructions`:{let e=await compileInstructionsEntry(t.manifest.agentRoot,o.source,x);e.kind===`instructions`?l.push(e.definition):(u.push(e.definition),n.evaluation.requireRuntimeEntry(i.sourceId));break}case`instrumentation`:S=o.source,n.evaluation.requireRuntimeEntry(i.sourceId);break;case`memory`:m.push(await compileMemoryDefinition(o.source,{binding:d,loadNamespace:E})),n.evaluation.requireRuntimeEntry(i.sourceId);break;case`sandbox`:y=await compileSandboxDefinition(t.manifest.agentRoot,o.source,{binding:d,loadNamespace:E}),y.inheritsParent||n.evaluation.requireRuntimeEntry(i.sourceId);break;case`schedule`:{let e=await compileScheduleDefinition(t.manifest.agentRoot,o.source,x);g.push(e),e.sourceKind===`module`&&e.hasRun&&n.evaluation.requireRuntimeEntry(i.sourceId);break}case`skill`:{let e=await compileSkillSource(t.manifest.agentRoot,o.source,x);e.kind===`skill`?s.push(e.definition):(c.push(withExtensionNamespace(e.definition,i.owner)),n.evaluation.requireRuntimeEntry(i.sourceId));break}case`tool`:{let e=await compileToolEntry(t.manifest.agentRoot,o.source,{binding:d,loadNamespace:E});e.kind===`disabled`?(n.composed=disableComposedCandidate({candidate:i,composed:n.composed}),delete n.bindings[i.sourceId],T.delete(i.sourceId)):e.kind===`tool`?(r.push(e.definition),n.evaluation.requireRuntimeEntry(i.sourceId)):e.kind===`dynamic-tool`?(a.push(withExtensionNamespace(e.definition,i.owner)),n.evaluation.requireRuntimeEntry(i.sourceId)):e.kind===`workflow-tool`?(assertRootOwnedSpecialTool(i,`Workflow`),C={...o.source,maxSubagents:e.maxSubagents}):(assertNonExtensionSpecialTool(i,`Web search`),r.push(e.definition),w=e.provider);break}}}if(y===void 0)throw Error(`Agent node "${t.nodeId}" has no selected sandbox source.`);assertUniqueBy(r,e=>e.name,`tool name`),assertUniqueBy(a,e=>e.slug,`dynamic tool slug`),assertUniqueBy(p,e=>e.connectionName,`connection name`),assertUniqueBy(s,e=>e.name,`skill name`);let D=createCompiledChannelRoutePlan({bindings:n.bindings,channels:_,diagnostics:this.diagnostics,nodeId:t.nodeId,sources:Object.fromEntries(n.orderedCandidates.map(e=>[e.sourceId,describeAgentSourceCandidate(e)]))});for(let e of D.effective)n.evaluation.requireRuntimeEntry(e.sourceId);let O=compileExtensionMounts(t.manifest,n.composed);for(let e of O)n.evaluation.requireRuntimeEntry(e.mountSourceId);let k=n.evaluation.finalizeBindings();return createCompiledAgentResources({agentRoot:t.manifest.agentRoot,appRoot:t.manifest.appRoot,bindings:k,channelRoutes:D,connections:p,diagnosticsSummary:summarizeCompilerDiagnostics(this.diagnostics),dynamicInstructions:u,dynamicSkills:c,dynamicTools:a,extensionMounts:O,hooks:h,memories:m,instructions:l,instrumentation:S,sandbox:y,sandboxWorkspaces:t.manifest.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:g,skills:s,sourceComposition:n.composed.composition,tools:r,webSearchProvider:w,workflowTool:C})}};export{compileAgentManifest};
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const compiledRemoteAgentNodeSchema=z.object({backing:z.object({kind:z.literal(`resource`),sourcePath:z.string()}).strict(),binding:z.object({backing:z.discriminatedUnion(`kind`,[z.object({externalDependencies:z.array(z.string()).readonly(),extensionScope:z.object({namespace:z.string(),sourceRoot:z.string()}).strict().optional(),kind:z.literal(`filesystem`),sourcePath:z.string()}).strict(),z.object({kind:z.literal(`programmatic`),moduleId:z.string(),registryId:z.string(),revision:z.string(),semanticRevision:z.string().optional()}).strict()]),logicalPath:z.string(),owner:z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}).strict(),z.object({feature:z.string(),kind:z.literal(`framework`)}).strict(),z.object({kind:z.literal(`extension`),namespace:z.string(),packageName:z.string()}).strict()])}).strict(),description:z.string(),entryPath:z.string(),exportName:z.string().optional(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),owner:z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}).strict(),z.object({feature:z.string(),kind:z.literal(`framework`)}).strict(),z.object({kind:z.literal(`extension`),namespace:z.string(),packageName:z.string()}).strict()]),parentNodeId:z.string(),outputSchema:jsonObjectSchema.optional(),path:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string().optional()}).strict();export{compiledRemoteAgentNodeSchema};
1
+ import{z}from"#compiled/zod/index.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const compiledRemoteAgentNodeSchema=z.object({backing:z.object({kind:z.literal(`resource`),sourcePath:z.string()}).strict(),binding:z.object({backing:z.discriminatedUnion(`kind`,[z.object({externalDependencies:z.array(z.string()).readonly(),extensionScope:z.object({namespace:z.string(),sourceRoot:z.string()}).strict().optional(),kind:z.literal(`filesystem`),sourcePath:z.string()}).strict(),z.object({kind:z.literal(`programmatic`),moduleId:z.string(),registryId:z.string(),revision:z.string(),semanticRevision:z.string().optional()}).strict()]),logicalPath:z.string(),owner:z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}).strict(),z.object({feature:z.string(),kind:z.literal(`framework`)}).strict(),z.object({kind:z.literal(`extension`),namespace:z.string(),packageName:z.string()}).strict()]),usage:z.object({compile:z.boolean(),runtimeEntry:z.boolean()}).strict()}).strict(),description:z.string(),entryPath:z.string(),exportName:z.string().optional(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),owner:z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`application`)}).strict(),z.object({feature:z.string(),kind:z.literal(`framework`)}).strict(),z.object({kind:z.literal(`extension`),namespace:z.string(),packageName:z.string()}).strict()]),parentNodeId:z.string(),outputSchema:jsonObjectSchema.optional(),path:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string().optional()}).strict();export{compiledRemoteAgentNodeSchema};
@@ -76,11 +76,20 @@ export interface AgentModuleCandidate {
76
76
  readonly owner: AgentSourceOwner;
77
77
  readonly sourceId: string;
78
78
  }
79
- export interface CompiledModuleBinding {
79
+ export interface AgentModuleBinding {
80
80
  readonly backing: AgentModuleBacking;
81
81
  readonly logicalPath: string;
82
82
  readonly owner: AgentSourceOwner;
83
83
  }
84
+ export interface CompiledModuleBinding extends AgentModuleBinding {
85
+ /** Compiler-owned namespace usage for this selected binding. */
86
+ readonly usage: {
87
+ /** The compiler evaluated this namespace while normalizing the node. */
88
+ readonly compile: boolean;
89
+ /** The namespace is an entry in the runtime module map. */
90
+ readonly runtimeEntry: boolean;
91
+ };
92
+ }
84
93
  export interface AgentSourceDescriptor {
85
94
  readonly backing: AgentSourceBacking;
86
95
  readonly form: AgentSourceForm;
@@ -101,6 +110,7 @@ export interface AgentResourceCandidate {
101
110
  readonly sourceId: string;
102
111
  }
103
112
  export type AgentSourceCandidate = AgentModuleCandidate | AgentResourceCandidate;
113
+ export declare function isAgentModuleCandidate(candidate: AgentSourceCandidate): candidate is AgentModuleCandidate;
104
114
  export type AgentSourceCompositionEntry = {
105
115
  readonly kind: "shadowed";
106
116
  readonly source: AgentSourceDescriptor;
@@ -137,7 +147,7 @@ export declare function disableComposedCandidate(input: {
137
147
  readonly candidate: AgentSourceCandidate;
138
148
  readonly composed: ComposedAgentModuleCandidates;
139
149
  }): ComposedAgentModuleCandidates;
140
- export declare function createCompiledModuleBinding(candidate: AgentModuleCandidate): CompiledModuleBinding;
150
+ export declare function createAgentModuleBinding(candidate: AgentModuleCandidate): AgentModuleBinding;
141
151
  export declare function loadProgrammaticModuleNamespace(input: {
142
152
  readonly backing: Extract<AgentModuleBacking, {
143
153
  readonly kind: "programmatic";
@@ -1 +1 @@
1
- import{isAbsolute,posix}from"node:path";import{getSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension}from"#discover/filesystem.js";import{parseJsonObject}from"#shared/json.js";function memoizeModuleNamespaceFactories(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>{if(typeof t!=`function`)return[e,t];let n;return[e,new Proxy(t,{apply(e,t,r){return r.length>0?Reflect.apply(e,t,r):(n??=Promise.resolve().then(()=>Reflect.apply(e,t,r)),n)}})]})))}var ImmutableProgrammaticSourceMap=class{#e;constructor(e){this.#e=new Map(e),Object.freeze(this)}get size(){return this.#e.size}get[Symbol.toStringTag](){return`ImmutableProgrammaticSourceMap`}[Symbol.iterator](){return this.#e[Symbol.iterator]()}entries(){return this.#e.entries()}forEach(e,t){this.#e.forEach((n,r)=>e.call(t,n,r,this))}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}keys(){return this.#e.keys()}values(){return this.#e.values()}};const LAYER_PRECEDENCE={"framework-default":0,"extension-package":1,"extension-override":2,application:3},FORM_PRECEDENCE={derived:0,direct:1},registeredProgrammaticTemplates=new WeakSet;function defineProgrammaticAgentSource(e){let t=expectNonEmpty(e.id,`Programmatic agent source id`),n=expectNonEmpty(e.revision,`Programmatic agent source "${t}" revision`),r=new Set,i=e.modules.map(e=>{let n=validateProgrammaticLogicalPath(e.logicalPath);if(r.has(n))throw Error(`Programmatic agent source "${t}" declares "${n}" more than once.`);r.add(n);let i=e.semanticRevision===void 0?void 0:expectNonEmpty(e.semanticRevision,`Programmatic module "${t}:${n}" semanticRevision`);return Object.freeze({exportName:e.exportName,loadNamespace:e.loadNamespace,logicalPath:n,semanticRevision:i})});return Object.freeze({id:t,modules:Object.freeze(i),revision:n})}function createAgentSourceRegistry(e,t={}){let n=new Map,r=new Map,addSource=e=>{let t=defineProgrammaticAgentSource(e);if(n.has(t.id))throw Error(`Programmatic agent source id "${t.id}" is registered more than once.`);return n.set(t.id,t),t},i=e.map(e=>{let t=addSource(e.source);return Object.freeze({applyTo:e.applyTo,source:t})});for(let e of t.templates??[]){let t=addSource(e);if(t.modules.length!==1)throw Error(`Programmatic template source "${t.id}" must register exactly one module.`);let n=Object.freeze({module:t.modules[0],source:t});registeredProgrammaticTemplates.add(n),r.set(t.id,n)}return Object.freeze({registrations:Object.freeze(i),sources:new ImmutableProgrammaticSourceMap(n),templates:new ImmutableProgrammaticSourceMap(r)})}function createProgrammaticModuleCandidates(e){return e.registration.source.modules.map(t=>{let n=`${e.registration.source.id}:${t.logicalPath}`;return Object.freeze({backing:Object.freeze({kind:`programmatic`,moduleId:t.logicalPath,registryId:e.registration.source.id,revision:e.registration.source.revision,semanticRevision:t.semanticRevision}),exportName:t.exportName,form:`direct`,layer:e.layer,logicalPath:t.logicalPath,nodeId:e.nodeId,owner:e.owner,sourceId:n})})}function instantiateProgrammaticTemplate(e){if(!registeredProgrammaticTemplates.has(e.template))throw Error(`Derived programmatic modules require a registered template.`);let t=validateProgrammaticLogicalPath(e.logicalPath),n=expectNonEmpty(e.anchor.sourceId,`Derived programmatic module anchor source id`),r=`${e.template.source.id}:${t}:from:${n}`;if(!Object.values(e.dependencies).some(e=>e.sourceId===n))throw Error(`Derived programmatic module "${r}" must include its anchor source as a dependency.`);let i=Object.freeze(Object.fromEntries(Object.entries(e.dependencies).sort(([e],[t])=>e.localeCompare(t)).map(([t,n])=>{if(expectNonEmpty(t,`Derived programmatic module dependency alias`),n.nodeId!==e.anchor.nodeId)throw Error(`Derived programmatic module "${r}" cannot depend on source "${n.sourceId}" from another node.`);return[t,n.sourceId]}))),o=Object.freeze(parseJsonObject(e.parameters??{}));return Object.freeze({backing:Object.freeze({dependencies:i,kind:`programmatic`,moduleId:e.template.module.logicalPath,parameters:o,registryId:e.template.source.id,revision:e.template.source.revision,semanticRevision:e.template.module.semanticRevision}),exportName:e.template.module.exportName,form:`derived`,layer:e.anchor.layer,logicalPath:t,nodeId:e.anchor.nodeId,owner:e.owner,sourceId:r})}function composeAgentModuleCandidates(e){let t=new Map,n=new Set;for(let r of e){if(n.has(r.sourceId))throw Error(`Agent source id "${r.sourceId}" is declared more than once in node "${r.nodeId}".`);n.add(r.sourceId);let e=canonicalSourceSlot(r.logicalPath),i=t.get(e)??[];i.push(r),t.set(e,i)}let r=new Map,i=[];for(let[e,n]of[...t].sort(([e],[t])=>e.localeCompare(t))){let t=new Set;for(let r of n){let n=`${r.layer}:${r.form}`;if(t.has(n))throw Error(`Agent source slot "${e}" has more than one ${r.layer} ${r.form} candidate.`);t.add(n)}let a=[...n].sort((e,t)=>LAYER_PRECEDENCE[t.layer]-LAYER_PRECEDENCE[e.layer]||FORM_PRECEDENCE[t.form]-FORM_PRECEDENCE[e.form]),c=a[0];r.set(e,c);for(let e of a.slice(1))i.push({kind:`shadowed`,source:describeAgentSourceCandidate(e),winnerSourceId:c.sourceId})}return validateSelectedCandidateDependencies(r),{composition:{entries:Object.freeze(i)},selected:r}}function disableComposedCandidate(e){let t=canonicalSourceSlot(e.candidate.logicalPath),n=new Map(e.composed.selected);if(n.get(t)?.sourceId!==e.candidate.sourceId)throw Error(`Only the selected source for "${t}" can disable that slot.`);if(!e.composed.composition.entries.some(t=>t.kind===`shadowed`&&t.winnerSourceId===e.candidate.sourceId))throw Error(`Source "${e.candidate.logicalPath}" disables a slot with no lower-precedence source.`);return n.delete(t),{composition:{entries:Object.freeze([...e.composed.composition.entries,{kind:`disabled`,source:describeAgentSourceCandidate(e.candidate)}])},selected:n}}function createCompiledModuleBinding(e){return Object.freeze({backing:e.backing,logicalPath:e.logicalPath,owner:e.owner})}async function loadProgrammaticModuleNamespace(e){let t=e.registries.map(t=>t.sources.get(e.backing.registryId)).filter(e=>e!==void 0);if(t.length!==1)throw Error(`Expected exactly one registered programmatic source "${e.backing.registryId}", found ${t.length}.`);let n=t[0];if(n.revision!==e.backing.revision)throw Error(`Programmatic source "${n.id}" revision mismatch: artifact requires "${e.backing.revision}", registry provides "${n.revision}".`);let r=n.modules.find(t=>t.logicalPath===e.backing.moduleId);if(r===void 0)throw Error(`Programmatic source "${n.id}" does not register module "${e.backing.moduleId}".`);if(r.semanticRevision!==e.backing.semanticRevision)throw Error(`Programmatic module "${n.id}:${r.logicalPath}" semantic revision does not match the compiled binding.`);let i=Object.fromEntries(Object.entries(e.backing.dependencies??{}).map(([t,i])=>{let a=e.dependencyNamespaces?.[t];if(a===void 0)throw Error(`Programmatic module "${n.id}:${r.logicalPath}" requires unresolved binding "${i}" as dependency "${t}".`);return[t,a]})),a=await r.loadNamespace({dependencies:Object.freeze(i),parameters:Object.freeze(e.backing.parameters??{})});if(typeof a!=`object`||!a)throw Error(`Programmatic module "${n.id}:${r.logicalPath}" loader must return a module namespace object.`);return a}function canonicalModuleSlot(e){return validateProgrammaticLogicalPath(e),canonicalSourceSlot(e)}function canonicalSourceSlot(e){let n=normalizeLogicalPath(e);if(n.length===0||n===`.`||n.startsWith(`../`)||n.includes(`/../`)||posix.normalize(n)!==n)throw Error(`Agent source logical path "${e}" is invalid.`);let a=stripLogicalPathExtension(n),o=a.match(/^connections\/([^/]+)\/connection$/);if(o!==null)return`connections/${o[1]}`;if(a===`sandbox/sandbox`)return`sandbox`;let s=a.match(/^skills\/([^/]+)\/SKILL$/);return s===null?a:`skills/${s[1]}`}function validateProgrammaticLogicalPath(a){if(a.length===0||isAbsolute(a)||a.includes(`\\`))throw Error(`Programmatic module logical path "${a}" must be a relative POSIX path.`);let o=normalizeLogicalPath(a);if(o===`.`||o.startsWith(`../`)||o.includes(`/../`)||posix.normalize(o)!==o)throw Error(`Programmatic module logical path "${a}" may not traverse directories.`);let s=o.split(`/`),c=s.at(-1);if(getSupportedModuleBaseName(c)===null)throw Error(`Programmatic module logical path "${a}" must use a supported JavaScript or TypeScript extension.`);let l=s[0],u=stripLogicalPathExtension(o);if(!(s.length===1&&[`agent`,`memory`,`sandbox`,`instrumentation`].includes(u)||l===`sandbox`&&s.length===2&&getSupportedModuleBaseName(c)===`sandbox`||[`channels`,`connections`,`hooks`,`instructions`,`memory`,`schedules`,`skills`,`tools`].includes(l)&&s.length>=2))throw Error(`Programmatic module logical path "${a}" does not select an eve module slot.`);return o}function describeAgentSourceCandidate(e){return Object.freeze({backing:e.backing,form:e.form,layer:e.layer,logicalPath:e.logicalPath,owner:e.owner,sourceId:e.sourceId})}function validateSelectedCandidateDependencies(e){let t=new Set([...e.values()].map(e=>e.sourceId));for(let n of e.values())if(n.backing.kind===`programmatic`){for(let e of Object.values(n.backing.dependencies??{}))if(!t.has(e))throw Error(`Derived programmatic source "${n.sourceId}" depends on unselected source "${e}".`)}}function expectNonEmpty(e,t){if(e.trim().length===0)throw Error(`${t} must be non-empty.`);return e}export{canonicalModuleSlot,canonicalSourceSlot,composeAgentModuleCandidates,createAgentSourceRegistry,createCompiledModuleBinding,createProgrammaticModuleCandidates,defineProgrammaticAgentSource,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories,validateProgrammaticLogicalPath};
1
+ import{isAbsolute,posix}from"node:path";import{getSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension}from"#discover/filesystem.js";import{parseJsonObject}from"#shared/json.js";function memoizeModuleNamespaceFactories(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>{if(typeof t!=`function`)return[e,t];let n;return[e,new Proxy(t,{apply(e,t,r){return r.length>0?Reflect.apply(e,t,r):(n??=Promise.resolve().then(()=>Reflect.apply(e,t,r)),n)}})]})))}var ImmutableProgrammaticSourceMap=class{#e;constructor(e){this.#e=new Map(e),Object.freeze(this)}get size(){return this.#e.size}get[Symbol.toStringTag](){return`ImmutableProgrammaticSourceMap`}[Symbol.iterator](){return this.#e[Symbol.iterator]()}entries(){return this.#e.entries()}forEach(e,t){this.#e.forEach((n,r)=>e.call(t,n,r,this))}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}keys(){return this.#e.keys()}values(){return this.#e.values()}};function isAgentModuleCandidate(e){return e.backing.kind!==`resource`}const LAYER_PRECEDENCE={"framework-default":0,"extension-package":1,"extension-override":2,application:3},FORM_PRECEDENCE={derived:0,direct:1},registeredProgrammaticTemplates=new WeakSet;function defineProgrammaticAgentSource(e){let t=expectNonEmpty(e.id,`Programmatic agent source id`),n=expectNonEmpty(e.revision,`Programmatic agent source "${t}" revision`),r=new Set,i=e.modules.map(e=>{let n=validateProgrammaticLogicalPath(e.logicalPath);if(r.has(n))throw Error(`Programmatic agent source "${t}" declares "${n}" more than once.`);r.add(n);let i=e.semanticRevision===void 0?void 0:expectNonEmpty(e.semanticRevision,`Programmatic module "${t}:${n}" semanticRevision`);return Object.freeze({exportName:e.exportName,loadNamespace:e.loadNamespace,logicalPath:n,semanticRevision:i})});return Object.freeze({id:t,modules:Object.freeze(i),revision:n})}function createAgentSourceRegistry(e,t={}){let n=new Map,r=new Map,addSource=e=>{let t=defineProgrammaticAgentSource(e);if(n.has(t.id))throw Error(`Programmatic agent source id "${t.id}" is registered more than once.`);return n.set(t.id,t),t},i=e.map(e=>{let t=addSource(e.source);return Object.freeze({applyTo:e.applyTo,source:t})});for(let e of t.templates??[]){let t=addSource(e);if(t.modules.length!==1)throw Error(`Programmatic template source "${t.id}" must register exactly one module.`);let n=Object.freeze({module:t.modules[0],source:t});registeredProgrammaticTemplates.add(n),r.set(t.id,n)}return Object.freeze({registrations:Object.freeze(i),sources:new ImmutableProgrammaticSourceMap(n),templates:new ImmutableProgrammaticSourceMap(r)})}function createProgrammaticModuleCandidates(e){return e.registration.source.modules.map(t=>{let n=`${e.registration.source.id}:${t.logicalPath}`;return Object.freeze({backing:Object.freeze({kind:`programmatic`,moduleId:t.logicalPath,registryId:e.registration.source.id,revision:e.registration.source.revision,semanticRevision:t.semanticRevision}),exportName:t.exportName,form:`direct`,layer:e.layer,logicalPath:t.logicalPath,nodeId:e.nodeId,owner:e.owner,sourceId:n})})}function instantiateProgrammaticTemplate(e){if(!registeredProgrammaticTemplates.has(e.template))throw Error(`Derived programmatic modules require a registered template.`);let t=validateProgrammaticLogicalPath(e.logicalPath),n=expectNonEmpty(e.anchor.sourceId,`Derived programmatic module anchor source id`),r=`${e.template.source.id}:${t}:from:${n}`;if(!Object.values(e.dependencies).some(e=>e.sourceId===n))throw Error(`Derived programmatic module "${r}" must include its anchor source as a dependency.`);let i=Object.freeze(Object.fromEntries(Object.entries(e.dependencies).sort(([e],[t])=>e.localeCompare(t)).map(([t,n])=>{if(expectNonEmpty(t,`Derived programmatic module dependency alias`),n.nodeId!==e.anchor.nodeId)throw Error(`Derived programmatic module "${r}" cannot depend on source "${n.sourceId}" from another node.`);return[t,n.sourceId]}))),o=Object.freeze(parseJsonObject(e.parameters??{}));return Object.freeze({backing:Object.freeze({dependencies:i,kind:`programmatic`,moduleId:e.template.module.logicalPath,parameters:o,registryId:e.template.source.id,revision:e.template.source.revision,semanticRevision:e.template.module.semanticRevision}),exportName:e.template.module.exportName,form:`derived`,layer:e.anchor.layer,logicalPath:t,nodeId:e.anchor.nodeId,owner:e.owner,sourceId:r})}function composeAgentModuleCandidates(e){let t=new Map,n=new Set;for(let r of e){if(n.has(r.sourceId))throw Error(`Agent source id "${r.sourceId}" is declared more than once in node "${r.nodeId}".`);n.add(r.sourceId);let e=canonicalSourceSlot(r.logicalPath),i=t.get(e)??[];i.push(r),t.set(e,i)}let r=new Map,i=[];for(let[e,n]of[...t].sort(([e],[t])=>e.localeCompare(t))){let t=new Set;for(let r of n){let n=`${r.layer}:${r.form}`;if(t.has(n))throw Error(`Agent source slot "${e}" has more than one ${r.layer} ${r.form} candidate.`);t.add(n)}let a=[...n].sort((e,t)=>LAYER_PRECEDENCE[t.layer]-LAYER_PRECEDENCE[e.layer]||FORM_PRECEDENCE[t.form]-FORM_PRECEDENCE[e.form]),c=a[0];r.set(e,c);for(let e of a.slice(1))i.push({kind:`shadowed`,source:describeAgentSourceCandidate(e),winnerSourceId:c.sourceId})}return validateSelectedCandidateDependencies(r),{composition:{entries:Object.freeze(i)},selected:r}}function disableComposedCandidate(e){let t=canonicalSourceSlot(e.candidate.logicalPath),n=new Map(e.composed.selected);if(n.get(t)?.sourceId!==e.candidate.sourceId)throw Error(`Only the selected source for "${t}" can disable that slot.`);if(!e.composed.composition.entries.some(t=>t.kind===`shadowed`&&t.winnerSourceId===e.candidate.sourceId))throw Error(`Source "${e.candidate.logicalPath}" disables a slot with no lower-precedence source.`);return n.delete(t),{composition:{entries:Object.freeze([...e.composed.composition.entries,{kind:`disabled`,source:describeAgentSourceCandidate(e.candidate)}])},selected:n}}function createAgentModuleBinding(e){return Object.freeze({backing:e.backing,logicalPath:e.logicalPath,owner:e.owner})}async function loadProgrammaticModuleNamespace(e){let t=e.registries.map(t=>t.sources.get(e.backing.registryId)).filter(e=>e!==void 0);if(t.length!==1)throw Error(`Expected exactly one registered programmatic source "${e.backing.registryId}", found ${t.length}.`);let n=t[0];if(n.revision!==e.backing.revision)throw Error(`Programmatic source "${n.id}" revision mismatch: artifact requires "${e.backing.revision}", registry provides "${n.revision}".`);let r=n.modules.find(t=>t.logicalPath===e.backing.moduleId);if(r===void 0)throw Error(`Programmatic source "${n.id}" does not register module "${e.backing.moduleId}".`);if(r.semanticRevision!==e.backing.semanticRevision)throw Error(`Programmatic module "${n.id}:${r.logicalPath}" semantic revision does not match the compiled binding.`);let i=Object.fromEntries(Object.entries(e.backing.dependencies??{}).map(([t,i])=>{let a=e.dependencyNamespaces?.[t];if(a===void 0)throw Error(`Programmatic module "${n.id}:${r.logicalPath}" requires unresolved binding "${i}" as dependency "${t}".`);return[t,a]})),a=await r.loadNamespace({dependencies:Object.freeze(i),parameters:Object.freeze(e.backing.parameters??{})});if(typeof a!=`object`||!a)throw Error(`Programmatic module "${n.id}:${r.logicalPath}" loader must return a module namespace object.`);return a}function canonicalModuleSlot(e){return validateProgrammaticLogicalPath(e),canonicalSourceSlot(e)}function canonicalSourceSlot(e){let n=normalizeLogicalPath(e);if(n.length===0||n===`.`||n.startsWith(`../`)||n.includes(`/../`)||posix.normalize(n)!==n)throw Error(`Agent source logical path "${e}" is invalid.`);let a=stripLogicalPathExtension(n),o=a.match(/^connections\/([^/]+)\/connection$/);if(o!==null)return`connections/${o[1]}`;if(a===`sandbox/sandbox`)return`sandbox`;let s=a.match(/^skills\/([^/]+)\/SKILL$/);return s===null?a:`skills/${s[1]}`}function validateProgrammaticLogicalPath(a){if(a.length===0||isAbsolute(a)||a.includes(`\\`))throw Error(`Programmatic module logical path "${a}" must be a relative POSIX path.`);let o=normalizeLogicalPath(a);if(o===`.`||o.startsWith(`../`)||o.includes(`/../`)||posix.normalize(o)!==o)throw Error(`Programmatic module logical path "${a}" may not traverse directories.`);let s=o.split(`/`),c=s.at(-1);if(getSupportedModuleBaseName(c)===null)throw Error(`Programmatic module logical path "${a}" must use a supported JavaScript or TypeScript extension.`);let l=s[0],u=stripLogicalPathExtension(o);if(!(s.length===1&&[`agent`,`memory`,`sandbox`,`instrumentation`].includes(u)||l===`sandbox`&&s.length===2&&getSupportedModuleBaseName(c)===`sandbox`||[`channels`,`connections`,`hooks`,`instructions`,`memory`,`schedules`,`skills`,`tools`].includes(l)&&s.length>=2))throw Error(`Programmatic module logical path "${a}" does not select an eve module slot.`);return o}function describeAgentSourceCandidate(e){return Object.freeze({backing:e.backing,form:e.form,layer:e.layer,logicalPath:e.logicalPath,owner:e.owner,sourceId:e.sourceId})}function validateSelectedCandidateDependencies(e){let t=new Set([...e.values()].map(e=>e.sourceId));for(let n of e.values())if(n.backing.kind===`programmatic`){for(let e of Object.values(n.backing.dependencies??{}))if(!t.has(e))throw Error(`Derived programmatic source "${n.sourceId}" depends on unselected source "${e}".`)}}function expectNonEmpty(e,t){if(e.trim().length===0)throw Error(`${t} must be non-empty.`);return e}export{canonicalModuleSlot,canonicalSourceSlot,composeAgentModuleCandidates,createAgentModuleBinding,createAgentSourceRegistry,createProgrammaticModuleCandidates,defineProgrammaticAgentSource,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate,isAgentModuleCandidate,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories,validateProgrammaticLogicalPath};
@@ -1 +1 @@
1
- import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{collectModuleBindingsForManifest}from"#compiler/module-map.js";import{HOST_HTTP_INVENTORY}from"#framework/host-inventory.js";function validateCompiledAgentManifest(t){let n=new Map([[ROOT_COMPILED_AGENT_NODE_ID,t]]);for(let e of t.subagents)n.has(e.nodeId)&&fail(`subagent node id "${e.nodeId}" is duplicated`),n.set(e.nodeId,e.agent),validateSubagentRecord(e);validateSubagentTree(t,n),validateCompiledAgentResources(t,{activeResourceSourceIds:t.subagents.filter(t=>t.parentNodeId===ROOT_COMPILED_AGENT_NODE_ID).map(e=>e.sourceId)});for(let e of t.subagents)validateCompiledAgentResources(e.agent,{additionalModuleSources:e.configResolver===void 0?[]:[e.configResolver],activeResourceSourceIds:t.subagents.filter(t=>t.parentNodeId===e.nodeId).map(e=>e.sourceId)});for(let[e,r]of n)validateUniqueIdentities([...r.tools.map(e=>({identity:e.name,kind:`tool`})),...r.remoteAgents.map(e=>({identity:e.name,kind:`remote agent`})),...t.subagents.filter(t=>t.parentNodeId===e).map(e=>({identity:e.name,kind:`local agent`}))],`tool and subagent public name`)}function validateSubagentTree(t,n){let r=new Map(t.subagents.map(e=>[e.nodeId,e.parentNodeId]));for(let i of t.subagents){n.has(i.parentNodeId)||fail(`subagent node "${i.nodeId}" has missing parent "${i.parentNodeId}"`);let t=new Set,a=i.nodeId;for(;a!==ROOT_COMPILED_AGENT_NODE_ID;){t.has(a)&&fail(`subagent graph contains a cycle at node "${a}"`),t.add(a);let e=r.get(a);e===void 0&&fail(`subagent node "${i.nodeId}" is not reachable from the root`),a=e}}}function validateCompiledModuleMap(e,n){let r=new Map([[`__root__`,new Set(collectModuleBindingsForManifest(e).map(e=>e.sourceId))],...e.subagents.map(e=>[e.nodeId,new Set(collectModuleBindingsForManifest(e.agent).map(e=>e.sourceId))])]),i=Object.keys(n.nodes);(i.length!==r.size||i.some(e=>!r.has(e)))&&fail(`compiled module map node set does not match the manifest`);for(let[e,t]of r){let r=n.nodes[e];r===void 0&&fail(`compiled module map node "${e}" is missing`);let i=Object.keys(r.modules);(i.length!==t.size||i.some(e=>!t.has(e)))&&fail(`compiled module map sources for node "${e}" do not match its bindings`)}}function validateCompiledAgentResources(e,t={}){validateUniqueIdentities(e.tools.map(e=>({identity:e.name,kind:`tool`})),`tool name`),validateUniqueIdentities(e.dynamicTools.map(e=>({identity:e.slug,kind:`dynamic tool`})),`dynamic tool slug`),validateUniqueIdentities(e.skills.map(e=>({identity:e.name,kind:`skill`})),`skill name`),validateUniqueIdentities(e.dynamicSkills.map(e=>({identity:e.slug,kind:`dynamic skill`})),`dynamic skill slug`),validateUniqueIdentities(e.instructions.map(e=>({identity:e.name,kind:`instructions`})),`instructions name`),validateUniqueIdentities(e.dynamicInstructions.map(e=>({identity:e.slug,kind:`dynamic instructions`})),`dynamic instructions slug`),validateUniqueIdentities(e.connections.map(e=>({identity:e.connectionName,kind:`connection`})),`connection name`),validateUniqueIdentities(e.hooks.map(e=>({identity:e.slug,kind:`hook`})),`hook slug`),validateUniqueIdentities(e.memories.map(e=>({identity:e.slot,kind:`memory`})),`memory slot`),validateUniqueIdentities(e.schedules.map(e=>({identity:e.name,kind:`schedule`})),`schedule name`);let n=collectReferencedModuleSources(e);for(let e of t.additionalModuleSources??[])n.set(e.sourceId,{logicalPath:e.logicalPath});for(let[t,r]of n){let n=e.bindings[t];n===void 0&&fail(`module source "${t}" has no compiled binding`),validateBinding(t,r.logicalPath,n)}for(let t of Object.keys(e.bindings))n.has(t)||fail(`compiled binding "${t}" is not referenced by its node manifest`);validateProgrammaticBindingDependencies(e.bindings);let r=new Set([...n.keys(),...collectActiveResourceSourceIds(e),...e.remoteAgents.map(e=>e.sourceId),...t.activeResourceSourceIds??[]]),i=new Set;for(let n of e.sourceComposition.entries){if(n.kind===`disabled`){i.has(n.source.sourceId)&&fail(`disabled composition source "${n.source.sourceId}" is duplicated`),i.add(n.source.sourceId),e.bindings[n.source.sourceId]!==void 0&&fail(`disabled source "${n.source.sourceId}" retains an active binding`);continue}!r.has(n.winnerSourceId)&&!i.has(n.winnerSourceId)&&!e.sourceComposition.entries.some(e=>e.kind===`disabled`&&e.source.sourceId===n.winnerSourceId)&&t.allowUnknownResourceWinners!==!0&&fail(`shadowed source "${n.source.sourceId}" has dangling winner "${n.winnerSourceId}"`)}validateChannelRoutePlan(e);for(let t of e.remoteAgents)validateBinding(t.sourceId,t.logicalPath,t.binding),t.parentNodeId.length===0&&fail(`remote agent "${t.sourceId}" has no parent`)}function validateSubagentRecord(e){if((e.backing.kind!==`resource`||e.backing.sourcePath.length===0)&&fail(`subagent "${e.nodeId}" has no physical resource backing`),e.parentNodeId.length===0&&fail(`subagent "${e.nodeId}" has no parent`),e.configResolver!==void 0){let t=e.agent.bindings[e.configResolver.sourceId];t===void 0&&fail(`dynamic subagent "${e.nodeId}" config resolver has no binding`),validateBinding(e.configResolver.sourceId,e.configResolver.logicalPath,t)}}function validateBinding(e,t,n){n.logicalPath!==t&&fail(`compiled binding "${e}" targets "${n.logicalPath}", not "${t}"`),n.owner.kind===`extension`&&n.backing.kind===`filesystem`&&n.backing.extensionScope===void 0&&fail(`extension-owned filesystem binding "${e}" has no extension scope`)}function validateProgrammaticBindingDependencies(e){let t=new Set,n=new Set,visit=r=>{if(n.has(r))return;t.has(r)&&fail(`programmatic binding dependency cycle includes "${r}"`);let i=e[r];if(i===void 0&&fail(`programmatic binding dependency "${r}" is missing`),t.add(r),i.backing.kind===`programmatic`)for(let[t,n]of Object.entries(i.backing.dependencies??{}))t.trim().length===0&&fail(`programmatic binding "${r}" has an empty dependency alias`),e[n]===void 0&&fail(`programmatic binding "${r}" depends on missing binding "${n}"`),visit(n);t.delete(r),n.add(r)};for(let t of Object.keys(e))visit(t)}function collectReferencedModuleSources(e){let t=new Map,add=e=>{let n=t.get(e.sourceId);n!==void 0&&n.logicalPath!==e.logicalPath&&fail(`module source "${e.sourceId}" is referenced with two logical paths`),t.set(e.sourceId,{logicalPath:e.logicalPath})};`config`in e&&(add(e.config.source),e.config.model?.source!==void 0&&add(e.config.model.source),e.config.dynamicModel!==void 0&&add(e.config.dynamicModel));for(let t of e.channelRoutes.effective)add(t);for(let t of e.channelRoutes.shadowed)t.source.backing.kind!==`resource`&&add(t.source);for(let t of e.connections)add(t);for(let t of e.tools)add(t);for(let t of e.dynamicInstructions)add(t);for(let t of e.dynamicSkills)add(t);for(let t of e.dynamicTools)add(t);for(let t of e.hooks)add(t);for(let t of e.memories)add(t);for(let t of e.instructions)t.sourceKind===`module`&&add(t);e.instrumentation!==void 0&&add(e.instrumentation),e.workflowTool!==void 0&&add(e.workflowTool);for(let t of e.skills)t.sourceKind===`module`&&add(t);for(let t of e.schedules)t.sourceKind===`module`&&add(t);add(e.sandbox);for(let t of e.extensionMounts)add({logicalPath:t.mountLogicalPath,sourceId:t.mountSourceId});return t}function collectActiveResourceSourceIds(e){return[...e.instructions.filter(e=>e.sourceKind!==`module`).map(e=>e.sourceId),...e.skills.filter(e=>e.sourceKind!==`module`).map(e=>e.sourceId),...e.schedules.filter(e=>e.sourceKind!==`module`).map(e=>e.sourceId),...e.sandboxWorkspaces.map(e=>e.sourceId)]}function validateChannelRoutePlan(e){let t=new Set,r=new Set;for(let i of e.channelRoutes.effective){let a=routeIdentity(i);t.has(a)&&fail(`effective channel route "${a}" is duplicated`),t.add(a),r.add(i.sourceId),e.bindings[i.sourceId]===void 0&&fail(`effective channel route source "${i.sourceId}" has no binding`),HOST_HTTP_INVENTORY.find(e=>methodsOverlap(i.method,e.method)&&patternsOverlap(i.urlPath,e.path))!==void 0&&fail(`effective route ${i.method} ${i.urlPath} overlaps reserved host route`)}for(let t of e.channelRoutes.shadowed)r.has(t.winnerSourceId)||fail(`shadowed channel route has dangling winner "${t.winnerSourceId}"`);let i=new Set;for(let t of e.channelRoutes.preflight){let n=normalizePattern(t.urlPath);i.has(n)&&fail(`generated preflight "${n}" is duplicated`),i.add(n),t.sourceIds.length===0&&fail(`generated preflight "${n}" has no causes`);for(let r of t.sourceIds)e.channelRoutes.effective.find(e=>e.sourceId===r&&e.cors!==void 0&&e.method!==`WEBSOCKET`&&patternsOverlap(e.urlPath,t.urlPath))===void 0&&fail(`generated preflight "${n}" has invalid cause "${r}"`)}}function routeIdentity(e){return`${e.method} ${normalizePattern(e.urlPath)}`}function normalizePattern(e){return splitPath(e).map(e=>isParameter(e)?`:`:e).join(`/`)}function patternsOverlap(e,t){let n=splitPath(e),r=splitPath(t);return n.length===r.length&&n.every((e,t)=>e===r[t]||isParameter(e)||isParameter(r[t]))}function splitPath(e){return e.replace(/^\/+|\/+$/g,``).split(`/`)}function isParameter(e){return e.startsWith(`:`)||/^\[[^\]]+\]$/.test(e)}function methodsOverlap(e,t){return e===`ALL`||t===`ALL`||e===t}function validateUniqueIdentities(e,t){let n=new Map;for(let r of e){let e=n.get(r.identity);e!==void 0&&fail(`${t} "${r.identity}" is shared by ${e} and ${r.kind}`),n.set(r.identity,r.kind)}}function fail(e){throw Error(`Invalid compiled eve artifact: ${e}.`)}export{validateCompiledAgentManifest,validateCompiledAgentResources,validateCompiledModuleMap};
1
+ import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{collectRuntimeModuleBindingsForManifest}from"#compiler/module-map.js";import{HOST_HTTP_INVENTORY}from"#framework/host-inventory.js";function validateCompiledAgentManifest(t){let n=new Map([[ROOT_COMPILED_AGENT_NODE_ID,t]]);for(let e of t.subagents)n.has(e.nodeId)&&fail(`subagent node id "${e.nodeId}" is duplicated`),n.set(e.nodeId,e.agent),validateSubagentRecord(e);validateSubagentTree(t,n),validateCompiledAgentResources(t,{activeResourceSourceIds:t.subagents.filter(t=>t.parentNodeId===ROOT_COMPILED_AGENT_NODE_ID).map(e=>e.sourceId)});for(let e of t.subagents)validateCompiledAgentResources(e.agent,{additionalModuleSources:e.configResolver===void 0?[]:[e.configResolver],activeResourceSourceIds:t.subagents.filter(t=>t.parentNodeId===e.nodeId).map(e=>e.sourceId)});for(let[e,r]of n)validateUniqueIdentities([...r.tools.map(e=>({identity:e.name,kind:`tool`})),...r.remoteAgents.map(e=>({identity:e.name,kind:`remote agent`})),...t.subagents.filter(t=>t.parentNodeId===e).map(e=>({identity:e.name,kind:`local agent`}))],`tool and subagent public name`)}function validateSubagentTree(t,n){let r=new Map(t.subagents.map(e=>[e.nodeId,e.parentNodeId]));for(let i of t.subagents){n.has(i.parentNodeId)||fail(`subagent node "${i.nodeId}" has missing parent "${i.parentNodeId}"`);let t=new Set,a=i.nodeId;for(;a!==ROOT_COMPILED_AGENT_NODE_ID;){t.has(a)&&fail(`subagent graph contains a cycle at node "${a}"`),t.add(a);let e=r.get(a);e===void 0&&fail(`subagent node "${i.nodeId}" is not reachable from the root`),a=e}}}function validateCompiledModuleMap(e,n){let r=new Map([[`__root__`,new Set(collectRuntimeModuleBindingsForManifest(e).map(e=>e.sourceId))],...e.subagents.map(e=>[e.nodeId,new Set(collectRuntimeModuleBindingsForManifest(e.agent).map(e=>e.sourceId))])]),i=Object.keys(n.nodes);(i.length!==r.size||i.some(e=>!r.has(e)))&&fail(`compiled module map node set does not match the manifest`);for(let[e,t]of r){let r=n.nodes[e];r===void 0&&fail(`compiled module map node "${e}" is missing`);let i=Object.keys(r.modules);(i.length!==t.size||i.some(e=>!t.has(e)))&&fail(`compiled module map sources for node "${e}" do not match its bindings`)}}function validateCompiledAgentResources(e,t={}){validateUniqueIdentities(e.tools.map(e=>({identity:e.name,kind:`tool`})),`tool name`),validateUniqueIdentities(e.dynamicTools.map(e=>({identity:e.slug,kind:`dynamic tool`})),`dynamic tool slug`),validateUniqueIdentities(e.skills.map(e=>({identity:e.name,kind:`skill`})),`skill name`),validateUniqueIdentities(e.dynamicSkills.map(e=>({identity:e.slug,kind:`dynamic skill`})),`dynamic skill slug`),validateUniqueIdentities(e.instructions.map(e=>({identity:e.name,kind:`instructions`})),`instructions name`),validateUniqueIdentities(e.dynamicInstructions.map(e=>({identity:e.slug,kind:`dynamic instructions`})),`dynamic instructions slug`),validateUniqueIdentities(e.connections.map(e=>({identity:e.connectionName,kind:`connection`})),`connection name`),validateUniqueIdentities(e.hooks.map(e=>({identity:e.slug,kind:`hook`})),`hook slug`),validateUniqueIdentities(e.memories.map(e=>({identity:e.slot,kind:`memory`})),`memory slot`),validateUniqueIdentities(e.schedules.map(e=>({identity:e.name,kind:`schedule`})),`schedule name`);let n=collectReferencedModuleSources(e);for(let e of t.additionalModuleSources??[])n.set(e.sourceId,{logicalPath:e.logicalPath});for(let[t,r]of n){let n=e.bindings[t];n===void 0&&fail(`module source "${t}" has no compiled binding`),validateBinding(t,r.logicalPath,n)}for(let t of Object.keys(e.bindings))n.has(t)||fail(`compiled binding "${t}" is not referenced by its node manifest`);validateProgrammaticBindingDependencies(e.bindings);let r=new Set([...n.keys(),...collectActiveResourceSourceIds(e),...e.remoteAgents.map(e=>e.sourceId),...t.activeResourceSourceIds??[]]),i=new Set;for(let n of e.sourceComposition.entries){if(n.kind===`disabled`){i.has(n.source.sourceId)&&fail(`disabled composition source "${n.source.sourceId}" is duplicated`),i.add(n.source.sourceId),e.bindings[n.source.sourceId]!==void 0&&fail(`disabled source "${n.source.sourceId}" retains an active binding`);continue}!r.has(n.winnerSourceId)&&!i.has(n.winnerSourceId)&&!e.sourceComposition.entries.some(e=>e.kind===`disabled`&&e.source.sourceId===n.winnerSourceId)&&t.allowUnknownResourceWinners!==!0&&fail(`shadowed source "${n.source.sourceId}" has dangling winner "${n.winnerSourceId}"`)}validateChannelRoutePlan(e);for(let t of e.remoteAgents)validateBinding(t.sourceId,t.logicalPath,t.binding),t.parentNodeId.length===0&&fail(`remote agent "${t.sourceId}" has no parent`)}function validateSubagentRecord(e){if((e.backing.kind!==`resource`||e.backing.sourcePath.length===0)&&fail(`subagent "${e.nodeId}" has no physical resource backing`),e.parentNodeId.length===0&&fail(`subagent "${e.nodeId}" has no parent`),e.configResolver!==void 0){let t=e.agent.bindings[e.configResolver.sourceId];t===void 0&&fail(`dynamic subagent "${e.nodeId}" config resolver has no binding`),validateBinding(e.configResolver.sourceId,e.configResolver.logicalPath,t)}}function validateBinding(e,t,n){!n.usage.compile&&!n.usage.runtimeEntry&&fail(`compiled binding "${e}" has no compile or runtime usage`),n.logicalPath!==t&&fail(`compiled binding "${e}" targets "${n.logicalPath}", not "${t}"`),n.owner.kind===`extension`&&n.backing.kind===`filesystem`&&n.backing.extensionScope===void 0&&fail(`extension-owned filesystem binding "${e}" has no extension scope`)}function validateProgrammaticBindingDependencies(e){let t=new Set,n=new Set,visit=r=>{if(n.has(r))return;t.has(r)&&fail(`programmatic binding dependency cycle includes "${r}"`);let i=e[r];if(i===void 0&&fail(`programmatic binding dependency "${r}" is missing`),t.add(r),i.backing.kind===`programmatic`)for(let[t,n]of Object.entries(i.backing.dependencies??{}))t.trim().length===0&&fail(`programmatic binding "${r}" has an empty dependency alias`),e[n]===void 0&&fail(`programmatic binding "${r}" depends on missing binding "${n}"`),i.usage.runtimeEntry&&e[n]?.usage.runtimeEntry!==!0&&fail(`runtime binding "${r}" depends on non-runtime binding "${n}"`),visit(n);t.delete(r),n.add(r)};for(let t of Object.keys(e))visit(t)}function collectReferencedModuleSources(e){let t=new Map,add=e=>{let n=t.get(e.sourceId);n!==void 0&&n.logicalPath!==e.logicalPath&&fail(`module source "${e.sourceId}" is referenced with two logical paths`),t.set(e.sourceId,{logicalPath:e.logicalPath})};`config`in e&&(add(e.config.source),e.config.model?.source!==void 0&&add(e.config.model.source),e.config.dynamicModel!==void 0&&add(e.config.dynamicModel));for(let t of e.channelRoutes.effective)add(t);for(let t of e.channelRoutes.shadowed)t.source.backing.kind!==`resource`&&add(t.source);for(let t of e.connections)add(t);for(let t of e.tools)add(t);for(let t of e.dynamicInstructions)add(t);for(let t of e.dynamicSkills)add(t);for(let t of e.dynamicTools)add(t);for(let t of e.hooks)add(t);for(let t of e.memories)add(t);for(let t of e.instructions)t.sourceKind===`module`&&add(t);e.instrumentation!==void 0&&add(e.instrumentation),e.workflowTool!==void 0&&add(e.workflowTool);for(let t of e.skills)t.sourceKind===`module`&&add(t);for(let t of e.schedules)t.sourceKind===`module`&&add(t);add(e.sandbox);for(let t of e.extensionMounts)add({logicalPath:t.mountLogicalPath,sourceId:t.mountSourceId});return t}function collectActiveResourceSourceIds(e){return[...e.instructions.filter(e=>e.sourceKind!==`module`).map(e=>e.sourceId),...e.skills.filter(e=>e.sourceKind!==`module`).map(e=>e.sourceId),...e.schedules.filter(e=>e.sourceKind!==`module`).map(e=>e.sourceId),...e.sandboxWorkspaces.map(e=>e.sourceId)]}function validateChannelRoutePlan(e){let t=new Set,r=new Set;for(let i of e.channelRoutes.effective){let a=routeIdentity(i);t.has(a)&&fail(`effective channel route "${a}" is duplicated`),t.add(a),r.add(i.sourceId),e.bindings[i.sourceId]===void 0&&fail(`effective channel route source "${i.sourceId}" has no binding`),HOST_HTTP_INVENTORY.find(e=>methodsOverlap(i.method,e.method)&&patternsOverlap(i.urlPath,e.path))!==void 0&&fail(`effective route ${i.method} ${i.urlPath} overlaps reserved host route`)}for(let t of e.channelRoutes.shadowed)r.has(t.winnerSourceId)||fail(`shadowed channel route has dangling winner "${t.winnerSourceId}"`);let i=new Set;for(let t of e.channelRoutes.preflight){let n=normalizePattern(t.urlPath);i.has(n)&&fail(`generated preflight "${n}" is duplicated`),i.add(n),t.sourceIds.length===0&&fail(`generated preflight "${n}" has no causes`);for(let r of t.sourceIds)e.channelRoutes.effective.find(e=>e.sourceId===r&&e.cors!==void 0&&e.method!==`WEBSOCKET`&&patternsOverlap(e.urlPath,t.urlPath))===void 0&&fail(`generated preflight "${n}" has invalid cause "${r}"`)}}function routeIdentity(e){return`${e.method} ${normalizePattern(e.urlPath)}`}function normalizePattern(e){return splitPath(e).map(e=>isParameter(e)?`:`:e).join(`/`)}function patternsOverlap(e,t){let n=splitPath(e),r=splitPath(t);return n.length===r.length&&n.every((e,t)=>e===r[t]||isParameter(e)||isParameter(r[t]))}function splitPath(e){return e.replace(/^\/+|\/+$/g,``).split(`/`)}function isParameter(e){return e.startsWith(`:`)||/^\[[^\]]+\]$/.test(e)}function methodsOverlap(e,t){return e===`ALL`||t===`ALL`||e===t}function validateUniqueIdentities(e,t){let n=new Map;for(let r of e){let e=n.get(r.identity);e!==void 0&&fail(`${t} "${r.identity}" is shared by ${e} and ${r.kind}`),n.set(r.identity,r.kind)}}function fail(e){throw Error(`Invalid compiled eve artifact: ${e}.`)}export{validateCompiledAgentManifest,validateCompiledAgentResources,validateCompiledModuleMap};
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { LanguageModel, ModelMessage, SystemModelMessage } from "ai";
7
7
  import type { JsonObject } from "#shared/json.js";
8
+ import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
8
9
  import type { ChannelInstrumentationProjection, ChannelDeliveryMetadata, SessionAuthContext, SessionCallback, SessionCapabilities, SessionParent, SessionTraceContext, SessionTurn } from "#channel/types.js";
9
10
  import { ContextKey } from "#context/key.js";
10
11
  import type { InstrumentationChannelDeliveryRef } from "#harness/instrumentation/lifecycle.js";
@@ -67,6 +68,7 @@ export declare const ParentSessionKey: ContextKey<SessionParent>;
67
68
  /** Separate from {@link ParentSessionKey} so it stays out of what extensions read. */
68
69
  export declare const ParentTraceContextKey: ContextKey<SessionTraceContext>;
69
70
  export interface SessionTraceSeed {
71
+ readonly decision?: InstrumentationDecision;
70
72
  readonly traceId: string;
71
73
  readonly spanId: string;
72
74
  readonly traceFlags: number;
@@ -1,2 +1,2 @@
1
1
  import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{defineTool}from"#tools/definition.js";import{loadContext}from"#context/container.js";import{stampDurableDynamicToolCallbacks}from"#tools/durable-callbacks.js";import{ContextKey}from"#context/key.js";import{resolveApprovalPolicy}from"#approval/definition.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{consumeAuthorizationResult,createAuthorizationAttempt,requestAuthorization}from"#harness/authorization.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e,t){let n=loadContext(),r=new Set;for(let i of t){let t=consumeAuthorizationResult(i.connectionName);if(!t)continue;let a=await resolveInteractiveAuth(e,i.connectionName);if(!a)continue;let o=t.principal??resolveConnectionPrincipal(i.connectionName,a),s=await a.completeAuthorization({callbackUrl:t.hookUrl,connection:{url:i.url??``},principal:o,resume:t.resume,callback:t.callback});writeCachedToken(n,i.connectionName,principalKey(o),s),r.add(i.connectionName)}return r}async function executeConnectionSearch(e){let t=loadContext(),r=t.get(ConnectionRegistryKey);if(r===void 0)return[];let a=e.limit??10,o=tokenize(e.keywords),s=[],l=[],u=e.connection!==void 0&&e.connection!==``?r.getConnections().filter(t=>t.connectionName===e.connection):r.getConnections();if(e.connection&&u.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${r.getConnectionNames().join(`, `)}.`);let f=await completePendingAuthorizations(r,u),p=[];for(let e of u){let t;try{t=await r.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(f.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),l.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(r,e.connectionName);if(t){let r=createAuthorizationAttempt(e.connectionName);if(r){let i=resolveConnectionPrincipal(e.connectionName,t),a=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:r.hookUrl});try{let{challenge:n,resume:o}=await t.startAuthorization({callbackUrl:a,connection:{url:e.url??``},principal:i});p.push({attemptId:r.attemptId,name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:a,principal:i,resume:o})}catch(t){let r=toError(t);logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:r}),l.push({connection:e.connectionName,description:e.description,error:`Failed to start authorization for "${e.connectionName}": ${r.message}`});continue}}}l.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),l.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let i=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:i}),l.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${i.message}`});continue}for(let n of t){let t=scoreMatch(o,n);t>0&&s.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(p.length>0)return requestAuthorization(p);let m=l.filter(e=>e.error!==void 0);if(u.length>0&&m.length===u.length)throw Error(m.map(e=>e.error).join(`
2
- `));s.sort((e,t)=>t.score-e.score);let h=s.slice(0,a).map(e=>e.item);if(h.length>0){let e=[...h,...l],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of h)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return u.map(e=>l.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function readDiscoveredToolClosure(e){let t=e.connectionName,n=e.toolName;if(typeof t!=`string`||typeof n!=`string`)throw Error(`Discovered connection tool callback metadata is invalid.`);return{connectionName:t,toolName:n}}async function executeDiscoveredConnectionTool(e,t,n){let{connectionName:r,toolName:a}=readDiscoveredToolClosure(e),o=loadContext().get(ConnectionRegistryKey);if(o===void 0)throw Error(`Connection registry is unavailable while replaying a discovered tool.`);let s=o.getConnections().find(e=>e.connectionName===r),d=await resolveInteractiveAuth(o,r),f=!1;if(d){let e=consumeAuthorizationResult(r);if(e){f=!0;let t=loadContext(),n=e.principal??resolveConnectionPrincipal(r,d),a=await d.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:s?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,r,principalKey(n),a)}}try{return await o.getClient(r).executeTool(a,t,{abortSignal:n.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!d)throw e;if(f)throw new ConnectionAuthorizationFailedError(r,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${r}" rejected the token immediately after authorization.`});let t=createAuthorizationAttempt(r);if(!t)throw e;let n=resolveConnectionPrincipal(r,d),i=resolveAuthorizationCallbackUrl({authorization:d,callbackUrl:t.hookUrl}),{challenge:a,resume:o}=await d.startAuthorization({callbackUrl:i,connection:{url:s?.url??``},principal:n});return requestAuthorization([{attemptId:t.attemptId,name:r,challenge:stampChallengeDisplayName(a,d),hookUrl:i,principal:n,resume:o}])}}async function requestDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n);return r===void 0?`not-applicable`:await resolveApprovalPolicy(r)(t)}async function authorizeDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n),a=r===void 0||typeof r==`function`?void 0:r.response;return a===void 0?{reason:`Approval response authorization is unavailable.`,status:`rejected`}:await a(t)}async function resolveConnectionSearchDynamicTools(){let e=loadContext().get(ConnectionRegistryKey);if(!e||e.getConnections().length===0)return null;let t=e.getConnections().map(e=>e.connectionName),n=loadContext().get(ConnectionSearchResultsKey)??[],o={},s=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${t.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});stampDurableDynamicToolCallbacks(s,{execute:{callback:(e,t)=>executeConnectionSearch(t),closure:{}}}),o.connection_search=s;for(let t of n){let n=t.connection,i=t.tool,s=e.getConnectionApproval(n),c={connectionName:n,toolName:i},l=defineTool({description:t.description,inputSchema:t.inputSchema??{type:`object`},approval:s,outputSchema:t.outputSchema,async execute(e,t){return await executeDiscoveredConnectionTool(c,e,t)}});stampDurableDynamicToolCallbacks(l,{execute:{callback:executeDiscoveredConnectionTool,closure:c},...s===void 0?{}:{approvalRequest:{callback:requestDiscoveredConnectionToolApproval,closure:c}},...s===void 0||typeof s==`function`||s.response===void 0?{}:{approvalResponse:{callback:authorizeDiscoveredConnectionToolApproval,closure:c}}}),o[qualifiedConnectionToolName(n,i)]=l}return o}export{resolveConnectionSearchDynamicTools};
2
+ `));s.sort((e,t)=>t.score-e.score);let h=s.slice(0,a).map(e=>e.item);if(h.length>0){let e=[...h,...l],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of h)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return u.map(e=>l.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function readDiscoveredToolClosure(e){let t=e.connectionName,n=e.toolName;if(typeof t!=`string`||typeof n!=`string`)throw Error(`Discovered connection tool callback metadata is invalid.`);return{connectionName:t,toolName:n}}async function executeDiscoveredConnectionTool(e,t,n){let{connectionName:r,toolName:a}=readDiscoveredToolClosure(e),o=loadContext().get(ConnectionRegistryKey);if(o===void 0)throw Error(`Connection registry is unavailable while replaying a discovered tool.`);let s=o.getConnections().find(e=>e.connectionName===r),d=await resolveInteractiveAuth(o,r),f=!1;if(d){let e=consumeAuthorizationResult(r);if(e){f=!0;let t=loadContext(),n=e.principal??resolveConnectionPrincipal(r,d),a=await d.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:s?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,r,principalKey(n),a)}}try{return await o.getClient(r).executeTool(a,t,{abortSignal:n.abortSignal,callId:n.callId})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!d)throw e;if(f)throw new ConnectionAuthorizationFailedError(r,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${r}" rejected the token immediately after authorization.`});let t=createAuthorizationAttempt(r);if(!t)throw e;let n=resolveConnectionPrincipal(r,d),i=resolveAuthorizationCallbackUrl({authorization:d,callbackUrl:t.hookUrl}),{challenge:a,resume:o}=await d.startAuthorization({callbackUrl:i,connection:{url:s?.url??``},principal:n});return requestAuthorization([{attemptId:t.attemptId,name:r,challenge:stampChallengeDisplayName(a,d),hookUrl:i,principal:n,resume:o}])}}async function requestDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n);return r===void 0?`not-applicable`:await resolveApprovalPolicy(r)(t)}async function authorizeDiscoveredConnectionToolApproval(e,t){let{connectionName:n}=readDiscoveredToolClosure(e),r=loadContext().get(ConnectionRegistryKey)?.getConnectionApproval(n),a=r===void 0||typeof r==`function`?void 0:r.response;return a===void 0?{reason:`Approval response authorization is unavailable.`,status:`rejected`}:await a(t)}async function resolveConnectionSearchDynamicTools(){let e=loadContext().get(ConnectionRegistryKey);if(!e||e.getConnections().length===0)return null;let t=e.getConnections().map(e=>e.connectionName),n=loadContext().get(ConnectionSearchResultsKey)??[],o={},s=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${t.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});stampDurableDynamicToolCallbacks(s,{execute:{callback:(e,t)=>executeConnectionSearch(t),closure:{}}}),o.connection_search=s;for(let t of n){let n=t.connection,i=t.tool,s=e.getConnectionApproval(n),c={connectionName:n,toolName:i},l=defineTool({description:t.description,inputSchema:t.inputSchema??{type:`object`},approval:s,outputSchema:t.outputSchema,async execute(e,t){return await executeDiscoveredConnectionTool(c,e,t)}});stampDurableDynamicToolCallbacks(l,{execute:{callback:executeDiscoveredConnectionTool,closure:c},...s===void 0?{}:{approvalRequest:{callback:requestDiscoveredConnectionToolApproval,closure:c}},...s===void 0||typeof s==`function`||s.response===void 0?{}:{approvalResponse:{callback:authorizeDiscoveredConnectionToolApproval,closure:c}}}),o[qualifiedConnectionToolName(n,i)]=l}return o}export{resolveConnectionSearchDynamicTools};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ChannelInstrumentationKey,OtelTraceEnabledKey,SessionTraceSeedKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getHookByToken,getRun,start}from"#internal/workflow/runtime.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{evaluateTracePolicy}from"#tracing/sampled-trace.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,TASK_RUN_WORKFLOW_NAME=`taskRunWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME,TASK_RUN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`},taskRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(a){let o=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),s=buildRunContext({bundle:o,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:a}),c=resolveEffectiveAgentRuntime(o,s),l=s.get(ChannelInstrumentationKey),u=allocateSessionTraceSeed({agentName:c.turnAgent.id,audience:normalizeChannelAudience(l?.metadata.audience),channelType:l?.channelType,parentTraceContext:a.parentTraceContext});u!==void 0&&s.set(SessionTraceSeedKey,u),s.set(OtelTraceEnabledKey,getInstrumentationRuntime()?.prepareSessionTrace!==void 0);let d=serializeContext(s),f=readParentLineage(d),p=c.limits?.sessionTimeoutMs,m={input:a.input,limits:a.limits,serializedContext:d};p!==void 0&&(m.sessionTimeoutMs=p);let h={...f.sessionId===void 0?buildSessionAttributes({inputMessage:a.title??a.input.message,serializedContext:d}):buildSubagentRootAttributes({identity:{nodeId:o.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:f.callId,parentSessionId:f.sessionId,parentTurnId:f.turnId,rootSessionId:f.rootSessionId??f.sessionId,serializedContext:d}),...a.externalInvocation===void 0?{}:buildInvocationAttributes(a.externalInvocation)},g;try{g=await startWorkflowPreferLatest(workflowEntryReference,[m],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(h)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:a.continuationToken}),e}if(a.continuationToken){let e=await waitForCommandHookOwner(a.continuationToken);if(e.runId!==g.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:a.continuationToken,ownerSessionId:e.runId,sessionId:g.runId})}await waitForOwnedCommandHook(sessionCommandHookToken(g.runId),g.runId);let _,getEvents=()=>(_??=parseNdjsonStream(()=>getRun(g.runId).getReadable()),_);return{get events(){return getEvents()},sessionId:g.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function dispatchWorkflowCommand(e,n){let i;try{i=normalizeWorkflowHook(await resumeSessionInbox(e,n))}catch(r){if(isInactiveCommandTarget(r))return inactiveCommandResult(n);throw logError(log,`failed to dispatch session command`,r,{command:n.kind,token:e}),r}return n.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(i.runId),i.runId),activeCommandResult(n,i.runId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.taskId!==void 0&&(t.taskId=e.taskId),e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),t)}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForOwnedCommandHook(e,t){let r=await waitForCommandHookOwner(e);if(r.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:r.runId,sessionId:t})}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}function allocateSessionTraceSeed(e){if(e.parentTraceContext!==void 0)return{spanId:e.parentTraceContext.spanId,traceFlags:e.parentTraceContext.traceFlags,traceId:e.parentTraceContext.traceId};let t=getInstrumentationRuntime();if(t?.prepareSessionTrace===void 0||t.idGenerator===void 0)return;let n=evaluateTracePolicy(t.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType});return{spanId:t.idGenerator.allocateSpanId(),traceFlags:+!!n,traceId:t.idGenerator.generateTraceId()}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,taskRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference};
1
+ import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ChannelInstrumentationKey,OtelTraceEnabledKey,SessionTraceSeedKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getHookByToken,getRun,start}from"#internal/workflow/runtime.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,TASK_RUN_WORKFLOW_NAME=`taskRunWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME,TASK_RUN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`},taskRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(a){let o=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),s=buildRunContext({bundle:o,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:a}),c=resolveEffectiveAgentRuntime(o,s),l=s.get(ChannelInstrumentationKey),u=allocateSessionTraceSeed({agentName:c.turnAgent.id,audience:normalizeChannelAudience(l?.metadata.audience),channelType:l?.channelType,parentTraceContext:a.parentTraceContext});u!==void 0&&s.set(SessionTraceSeedKey,u),s.set(OtelTraceEnabledKey,getInstrumentationRuntime()?.prepareSessionTrace!==void 0);let d=serializeContext(s),f=readParentLineage(d),p=c.limits?.sessionTimeoutMs,m={input:a.input,limits:a.limits,serializedContext:d};p!==void 0&&(m.sessionTimeoutMs=p);let h={...f.sessionId===void 0?buildSessionAttributes({inputMessage:a.title??a.input.message,serializedContext:d}):buildSubagentRootAttributes({identity:{nodeId:o.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:f.callId,parentSessionId:f.sessionId,parentTurnId:f.turnId,rootSessionId:f.rootSessionId??f.sessionId,serializedContext:d}),...a.externalInvocation===void 0?{}:buildInvocationAttributes(a.externalInvocation)},g;try{g=await startWorkflowPreferLatest(workflowEntryReference,[m],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(h)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:a.continuationToken}),e}if(a.continuationToken){let e=await waitForCommandHookOwner(a.continuationToken);if(e.runId!==g.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:a.continuationToken,ownerSessionId:e.runId,sessionId:g.runId})}await waitForOwnedCommandHook(sessionCommandHookToken(g.runId),g.runId);let _,getEvents=()=>(_??=parseNdjsonStream(()=>getRun(g.runId).getReadable()),_);return{get events(){return getEvents()},sessionId:g.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function dispatchWorkflowCommand(e,n){let i;try{i=normalizeWorkflowHook(await resumeSessionInbox(e,n))}catch(r){if(isInactiveCommandTarget(r))return inactiveCommandResult(n);throw logError(log,`failed to dispatch session command`,r,{command:n.kind,token:e}),r}return n.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(i.runId),i.runId),activeCommandResult(n,i.runId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.taskId!==void 0&&(t.taskId=e.taskId),e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),t)}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForOwnedCommandHook(e,t){let r=await waitForCommandHookOwner(e);if(r.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:r.runId,sessionId:t})}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}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};let t=getInstrumentationRuntime();if(t?.prepareSessionTrace===void 0||t.idGenerator===void 0)return;let n=resolveTracePolicy(t.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType});return{decision:n,spanId:t.idGenerator.allocateSpanId(),traceFlags:+(n.action===`record`),traceId:t.idGenerator.generateTraceId()}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,taskRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference};
@@ -1 +1 @@
1
- import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createAgentSourceRegistry,defineProgrammaticAgentSource,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories}from"#compiler/source-graph.js";const revision=`eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v43`,localDefaults=defineProgrammaticAgentSource({id:`eve:defaults`,revision,modules:[{logicalPath:`agent.ts`,loadNamespace:()=>import(`#framework/sources/modules/agent.js`)},{logicalPath:`sandbox.ts`,semanticRevision:`eve:default-sandbox:v1`,loadNamespace:()=>import(`#framework/sources/modules/sandbox.js`)},{logicalPath:`tools/bash.ts`,loadNamespace:()=>import(`#tools/provided/bash.js`)},{logicalPath:`tools/read_file.ts`,loadNamespace:()=>import(`#tools/provided/read-file.js`)},{logicalPath:`tools/write_file.ts`,loadNamespace:()=>import(`#tools/provided/write-file.js`)},{logicalPath:`tools/todo.ts`,loadNamespace:()=>import(`#tools/provided/todo.js`)},{logicalPath:`tools/web_fetch.ts`,loadNamespace:()=>import(`#tools/provided/web-fetch.js`)},{logicalPath:`tools/load_skill.ts`,loadNamespace:()=>import(`#tools/provided/load-skill.js`)},{logicalPath:`tools/connection_search.ts`,loadNamespace:()=>import(`#tools/framework/connection-search.js`)},{logicalPath:`tools/ask_question.ts`,loadNamespace:()=>import(`#tools/framework/ask-question.js`)},{logicalPath:`tools/web_search.ts`,loadNamespace:()=>import(`#tools/provided/web-search.js`)}]}),rootDefaults=defineProgrammaticAgentSource({id:`eve:root-defaults`,revision,modules:[{logicalPath:`tools/agent.ts`,loadNamespace:()=>import(`#tools/framework/agent.js`)},{logicalPath:`tools/task_update.ts`,loadNamespace:()=>import(`#tools/framework/task-update.js`)},{logicalPath:`tools/task_cancel.ts`,loadNamespace:()=>import(`#tools/framework/task-cancel.js`)},{logicalPath:`channels/eve.ts`,loadNamespace:()=>import(`#framework/sources/modules/eve-channel.js`)},{logicalPath:`channels/home.ts`,loadNamespace:()=>import(`#framework/sources/modules/home-channel.js`)}]}),memoryWrapperTemplateSource=defineProgrammaticAgentSource({id:`eve:memory-wrapper`,revision,modules:[{logicalPath:`tools/memory-wrapper.ts`,loadNamespace:async e=>{let{loadMemoryWrapperNamespace:t}=await import(`#framework/sources/modules/memory-wrapper.js`);return await t(e)}}]}),frameworkAgentSourceRegistry=createAgentSourceRegistry([{applyTo:`all-local-nodes`,source:localDefaults},{applyTo:`root`,source:rootDefaults}],{templates:[memoryWrapperTemplateSource]}),memoryWrapperTemplate=frameworkAgentSourceRegistry.templates.get(memoryWrapperTemplateSource.id);async function loadFrameworkProgrammaticModule(e,t){return memoizeModuleNamespaceFactories(await loadProgrammaticModuleNamespace({backing:e,dependencyNamespaces:t,registries:[frameworkAgentSourceRegistry]}))}export{frameworkAgentSourceRegistry,loadFrameworkProgrammaticModule,memoryWrapperTemplate};
1
+ import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createAgentSourceRegistry,defineProgrammaticAgentSource,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories}from"#compiler/source-graph.js";const revision=`eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v44`,localDefaults=defineProgrammaticAgentSource({id:`eve:defaults`,revision,modules:[{logicalPath:`agent.ts`,loadNamespace:()=>import(`#framework/sources/modules/agent.js`)},{logicalPath:`sandbox.ts`,semanticRevision:`eve:default-sandbox:v1`,loadNamespace:()=>import(`#framework/sources/modules/sandbox.js`)},{logicalPath:`tools/bash.ts`,loadNamespace:()=>import(`#tools/provided/bash.js`)},{logicalPath:`tools/read_file.ts`,loadNamespace:()=>import(`#tools/provided/read-file.js`)},{logicalPath:`tools/write_file.ts`,loadNamespace:()=>import(`#tools/provided/write-file.js`)},{logicalPath:`tools/todo.ts`,loadNamespace:()=>import(`#tools/provided/todo.js`)},{logicalPath:`tools/web_fetch.ts`,loadNamespace:()=>import(`#tools/provided/web-fetch.js`)},{logicalPath:`tools/load_skill.ts`,loadNamespace:()=>import(`#tools/provided/load-skill.js`)},{logicalPath:`tools/connection_search.ts`,loadNamespace:()=>import(`#tools/framework/connection-search.js`)},{logicalPath:`tools/ask_question.ts`,loadNamespace:()=>import(`#tools/framework/ask-question.js`)},{logicalPath:`tools/web_search.ts`,loadNamespace:()=>import(`#tools/provided/web-search.js`)}]}),rootDefaults=defineProgrammaticAgentSource({id:`eve:root-defaults`,revision,modules:[{logicalPath:`tools/agent.ts`,loadNamespace:()=>import(`#tools/framework/agent.js`)},{logicalPath:`tools/task_update.ts`,loadNamespace:()=>import(`#tools/framework/task-update.js`)},{logicalPath:`tools/task_cancel.ts`,loadNamespace:()=>import(`#tools/framework/task-cancel.js`)},{logicalPath:`channels/eve.ts`,loadNamespace:()=>import(`#framework/sources/modules/eve-channel.js`)},{logicalPath:`channels/home.ts`,loadNamespace:()=>import(`#framework/sources/modules/home-channel.js`)}]}),memoryWrapperTemplateSource=defineProgrammaticAgentSource({id:`eve:memory-wrapper`,revision,modules:[{logicalPath:`tools/memory-wrapper.ts`,loadNamespace:async e=>{let{loadMemoryWrapperNamespace:t}=await import(`#framework/sources/modules/memory-wrapper.js`);return await t(e)}}]}),frameworkAgentSourceRegistry=createAgentSourceRegistry([{applyTo:`all-local-nodes`,source:localDefaults},{applyTo:`root`,source:rootDefaults}],{templates:[memoryWrapperTemplateSource]}),memoryWrapperTemplate=frameworkAgentSourceRegistry.templates.get(memoryWrapperTemplateSource.id);async function loadFrameworkProgrammaticModule(e,t){return memoizeModuleNamespaceFactories(await loadProgrammaticModuleNamespace({backing:e,dependencyNamespaces:t,registries:[frameworkAgentSourceRegistry]}))}export{frameworkAgentSourceRegistry,loadFrameworkProgrammaticModule,memoryWrapperTemplate};
@@ -1 +1 @@
1
- import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ActiveChannelDeliveriesKey,ChannelInstrumentationKey,ParentTraceContextKey,SessionTraceSeedKey}from"#context/keys.js";import{instrumentationHooksForAudience}from"#harness/instrumentation/content-policy.js";import{channelDeliveryIdempotencyKey}from"#harness/instrumentation/lifecycle.js";async function instrumentChannelDelivery(a){if(!(`delivery`in a)){let n=a.ctx.get(ActiveChannelDeliveriesKey);if(n===void 0||a.hooks===void 0)return;let r=`channel.delivery.${a.outcome}`;for(let t of n)await instrumentationHooksForAudience(a.hooks,normalizeChannelAudience(t.delivery.channelAudience))?.publish({agentName:t.agentName,delivery:t.delivery,error:a.error,errorCode:a.errorCode,idempotencyKey:channelDeliveryIdempotencyKey(t.sessionId,t.delivery.deliveryId),outcome:a.outcome,rootSessionId:t.rootSessionId,sequence:a.includeTurn?t.sequence:void 0,sessionId:t.sessionId,turnId:a.includeTurn?t.turnId:void 0,type:r});a.ctx.delete(ActiveChannelDeliveriesKey);return}if(a.hooks===void 0||a.delivery.deliveryMetadata===void 0)return;let o=[],s=normalizeChannelAudience(a.ctx.get(ChannelInstrumentationKey)?.metadata.audience),c=instrumentationHooksForAudience(a.hooks,s);for(let e of a.delivery.deliveryMetadata){let t=a.delivery.payloads[e.payloadIndex],n={channelAudience:s,channelKind:e.channelKind,channelName:e.channelName,deliveryId:e.deliveryId,requestId:e.requestId,requestTraceContext:e.requestTraceContext},i=!c?.capturesContent||t===void 0?void 0:projectDeliveryInput(t),l={agentName:a.agentName,delivery:n,rootSessionId:a.rootSessionId,sequence:a.sequence,sessionId:a.sessionId,turnId:a.turnId};o.push(l),await c?.publish({agentName:l.agentName,delivery:n,idempotencyKey:channelDeliveryIdempotencyKey(a.sessionId,n.deliveryId),input:i,parentTraceContext:a.ctx.get(ParentTraceContextKey),rootSessionId:a.rootSessionId,sessionId:a.sessionId,traceSeed:a.ctx.get(SessionTraceSeedKey),type:`channel.delivery.started`})}o.length>0&&a.ctx.set(ActiveChannelDeliveriesKey,o)}function projectDeliveryInput(e){let t={};return e.context!==void 0&&(t.context=e.context),e.message!==void 0&&(t.message=e.message),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.inputResponses!==void 0&&(t.inputResponses=e.inputResponses.map(e=>{let t={};return e.optionId!==void 0&&(t.optionId=e.optionId),e.text!==void 0&&(t.text=e.text),t})),t}function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}export{channelDeliveryErrorCode,instrumentChannelDelivery};
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ActiveChannelDeliveriesKey,ChannelInstrumentationKey,ParentTraceContextKey,SessionTraceSeedKey}from"#context/keys.js";import{instrumentationHooksForAudience,instrumentationHooksForDecision}from"#harness/instrumentation/content-policy.js";import{channelDeliveryIdempotencyKey}from"#harness/instrumentation/lifecycle.js";async function instrumentChannelDelivery(i){if(!(`delivery`in i)){let n=i.ctx.get(ActiveChannelDeliveriesKey);if(n===void 0||i.hooks===void 0)return;let r=`channel.delivery.${i.outcome}`;for(let t of n)await hooksForContext(i.ctx,i.hooks,normalizeChannelAudience(t.delivery.channelAudience))?.publish({agentName:t.agentName,delivery:t.delivery,error:i.error,errorCode:i.errorCode,idempotencyKey:channelDeliveryIdempotencyKey(t.sessionId,t.delivery.deliveryId),outcome:i.outcome,rootSessionId:t.rootSessionId,sequence:i.includeTurn?t.sequence:void 0,sessionId:t.sessionId,turnId:i.includeTurn?t.turnId:void 0,type:r});i.ctx.delete(ActiveChannelDeliveriesKey);return}if(i.hooks===void 0||i.delivery.deliveryMetadata===void 0)return;let a=[],o=normalizeChannelAudience(i.ctx.get(ChannelInstrumentationKey)?.metadata.audience),s=hooksForContext(i.ctx,i.hooks,o);for(let e of i.delivery.deliveryMetadata){let t=i.delivery.payloads[e.payloadIndex],n={channelAudience:o,channelKind:e.channelKind,channelName:e.channelName,deliveryId:e.deliveryId,requestId:e.requestId,requestTraceContext:e.requestTraceContext},c=!s?.capturesContent||t===void 0?void 0:projectDeliveryInput(t),l={agentName:i.agentName,delivery:n,rootSessionId:i.rootSessionId,sequence:i.sequence,sessionId:i.sessionId,turnId:i.turnId};a.push(l),await s?.publish({agentName:l.agentName,delivery:n,idempotencyKey:channelDeliveryIdempotencyKey(i.sessionId,n.deliveryId),input:c,parentTraceContext:i.ctx.get(ParentTraceContextKey),rootSessionId:i.rootSessionId,sessionId:i.sessionId,traceSeed:i.ctx.get(SessionTraceSeedKey),type:`channel.delivery.started`})}a.length>0&&i.ctx.set(ActiveChannelDeliveriesKey,a)}function hooksForContext(e,t,n){let r=e.get(SessionTraceSeedKey)?.decision;return r===void 0?instrumentationHooksForAudience(t,n):instrumentationHooksForDecision(t,r,n)}function projectDeliveryInput(e){let t={};return e.context!==void 0&&(t.context=e.context),e.message!==void 0&&(t.message=e.message),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.inputResponses!==void 0&&(t.inputResponses=e.inputResponses.map(e=>{let t={};return e.optionId!==void 0&&(t.optionId=e.optionId),e.text!==void 0&&(t.text=e.text),t})),t}function channelDeliveryErrorCode(e){if(typeof e==`object`&&e&&`code`in e){let t=e.code;if(typeof t==`string`&&t.length>0)return t}return`CHANNEL_DELIVERY_FAILED`}export{channelDeliveryErrorCode,instrumentChannelDelivery};
@@ -76,12 +76,5 @@ interface StreamActionEmissionOptions {
76
76
  readonly excludedActionToolNames: ReadonlySet<string>;
77
77
  readonly tools: HarnessToolMap;
78
78
  }
79
- /**
80
- * Consumes the AI SDK `fullStream` and emits real-time text and reasoning
81
- * events.
82
- *
83
- * Emits local tool events in source order. Provider calls that arrive in one
84
- * stream batch into one request event before their first result. A result
85
- * without a streamed call resumes a call from an earlier step.
86
- */
79
+ /** Consumes `fullStream` in source order, batching provider calls before their first result. */
87
80
  export declare function emitStreamContent(emitFn: HarnessEmitFn, state: HarnessEmissionState, fullStream: AsyncIterable<TextStreamPart<ToolSet>>, options?: StreamActionEmissionOptions): Promise<EmittedStreamContent>;
@@ -1 +1 @@
1
- import{createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission-state.js";async function emitTurnPreamble(e,t,n,r,i){let o=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r,trace:i})),await e(createTurnStartedEvent({sequence:n.sequence,trace:i,turnId:o})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:o})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:o}}async function emitStepStarted(e,t,n,r){await e(createStepStartedEvent({modelId:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),r)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n,r){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId}),r),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(e,t,n,r){let i=createOrderedStreamEmitter(e),a=createProviderStreamActionBatch({emitFn:i.emit,state:t});try{return await consumeStreamContent(i.emit,t,interruptStreamOnFailure(n,i.failureSignal),a,r)}finally{try{await a.cancel()}finally{await i.closeAndDrain()}}}async function consumeStreamContent(a,s,c,l,u){let d=``,f=``,p=`stop`,m,h=new Set,g=new Set,_=new Set,v=new Set,y=new Set,b=new Set,x=[],S=[],flushCurrentMessage=async()=>{f.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),f=``)},emitActionRequest=async e=>{g.has(e.callId)||(f.trim().length>0&&await flushCurrentMessage(),g.add(e.callId),await a(createActionsRequestedEvent({actions:[e],sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})))},collectProviderToolCall=async e=>{if(v.has(e.toolCallId)||(v.add(e.toolCallId),g.has(e.toolCallId)))return;g.add(e.toolCallId),f.trim().length>0&&await flushCurrentMessage();let t=resolveProviderToolCallRequest(e);if(t.toolError!==void 0){b.add(e.toolCallId),await emitActionResult(createRuntimeToolResultFromToolError(t.toolError)),y.add(e.toolCallId),S.push(createToolResultMessagePartFromToolError(t.toolError));return}l.observe(t.request)},emitActionResult=async e=>{_.has(e.callId)||(_.add(e.callId),await a(createActionResultEvent({result:e,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})))},emitActionPartial=async t=>{await a(createActionPartialEvent({result:t,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}))},emitToolCall=async e=>{if(isInvalidToolCall(e)){b.add(e.toolCallId);return}if(!(u===void 0||u.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:u.tools}))}catch(t){if(t instanceof TypeError){let n=createInvalidToolCallInputError({error:t,toolCall:e});b.add(e.toolCallId),f.trim().length>0&&await flushCurrentMessage(),await emitActionResult(createRuntimeToolResultFromToolError(n)),y.add(e.toolCallId),S.push(createToolResultMessagePartFromToolError(n));return}throw t}};for await(let e of c)if(m===void 0)switch(e.type){case`reasoning-delta`:await l.flush(),d+=e.text,await a(createReasoningAppendedEvent({reasoningDelta:e.text,reasoningSoFar:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}));break;case`text-delta`:await l.flush(),d.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),d=``),f+=e.text,await a(createMessageAppendedEvent({messageDelta:e.text,messageSoFar:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}));break;case`tool-call`:{let t=e;h.add(t.toolCallId),t.providerExecuted===!0?await collectProviderToolCall(t):(await l.flush(),await emitToolCall(t));break}case`tool-result`:{let t=e;if(t.preliminary===!0){t.providerExecuted!==!0&&await emitActionPartial(createRuntimeToolResultFromStepResult(t));break}if(t.providerExecuted===!0){await collectProviderToolCall({input:`input`in t?t.input:void 0,toolCallId:t.toolCallId,toolName:t.toolName}),await l.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(t));break}if(h.has(e.toolCallId)){if(isInlineAuthorizationToolResult(t))break;g.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(t)),y.add(e.toolCallId));break}if(await l.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(t)){y.add(e.toolCallId),x.push(t);break}await emitActionResult(createRuntimeToolResultFromStepResult(t)),y.add(e.toolCallId);break}case`tool-error`:{let t=e;t.providerExecuted===!0?(await collectProviderToolCall(t),await l.flush(),await emitActionResult(createRuntimeToolResultFromToolError(t))):g.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(t)),y.add(t.toolCallId),S.push(createToolResultMessagePartFromToolError(t)));break}case`finish-step`:p=normalizeAssistantStepFinishReason(e.finishReason),await l.flush();break;case`error`:m=normalizeModelStreamError(e.error);break;case`abort`:throw new DOMException(e.reason??`The model stream was aborted.`,`AbortError`);default:break}if(await l.flush(),m!==void 0)throw m;return d.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),p!==`tool-calls`&&hasEmptyDeliverySentinel(f)?await a(createMessageCompletedEvent({finishReason:p,message:null,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})):f.trim().length>0&&await a(createMessageCompletedEvent({finishReason:p,message:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),{emittedActionCallIds:g,handledInlineToolResultCallIds:y,invalidInputToolCallIds:b,inlineAuthorizationResults:x,trailingInlineToolResultParts:S}}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
1
+ import{createActionInputAppendedEvent,createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{createInvalidToolCallInputError,isInvalidToolCall,resolveProviderToolCallRequest}from"#harness/tool-call-input-errors.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.js";import{normalizeModelStreamError}from"#harness/model-call-error.js";import{createOrderedStreamEmitter}from"#harness/ordered-stream-emitter.js";import{interruptStreamOnFailure}from"#harness/interruptible-stream.js";import{isInlineAuthorizationToolResult}from"#harness/inline-tool-authorization.js";import{getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission-state.js";async function emitTurnPreamble(e,t,n,r,i){let a=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r,trace:i})),await e(createTurnStartedEvent({sequence:n.sequence,trace:i,turnId:a})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:a})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:a}}async function emitStepStarted(e,t,n,r){await e(createStepStartedEvent({modelId:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),r)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n,r){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId}),r),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(e,t,n,r){let i=createOrderedStreamEmitter(e),a=createProviderStreamActionBatch({emitFn:i.emit,state:t});try{return await consumeStreamContent(i.emit,t,interruptStreamOnFailure(n,i.failureSignal),a,r)}finally{try{await a.cancel()}finally{await i.closeAndDrain()}}}async function consumeStreamContent(o,s,c,l,u){let d=``,f=``,p=`stop`,m,h=new Set,g=new Set,_=new Set,v=new Set,y=new Set,b=new Set,x=[],S=[],C=new Map,flushCurrentMessage=async()=>{f.length!==0&&(await o(createMessageCompletedEvent({finishReason:`tool-calls`,message:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),f=``)},emitActionInput=async(t,n,r,i)=>o(createActionInputAppendedEvent({callId:t,inputTextDelta:r,inputTextOffset:i,sequence:s.sequence,stepIndex:s.stepIndex,toolName:n,turnId:s.turnId})),emitActionRequest=async e=>{g.has(e.callId)||(f.trim().length>0&&await flushCurrentMessage(),g.add(e.callId),await o(createActionsRequestedEvent({actions:[e],sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})))},collectProviderToolCall=async e=>{if(v.has(e.toolCallId)||(v.add(e.toolCallId),g.has(e.toolCallId)))return;g.add(e.toolCallId),f.trim().length>0&&await flushCurrentMessage();let t=resolveProviderToolCallRequest(e);if(t.toolError!==void 0){b.add(e.toolCallId),await emitActionResult(createRuntimeToolResultFromToolError(t.toolError)),y.add(e.toolCallId),S.push(createToolResultMessagePartFromToolError(t.toolError));return}l.observe(t.request)},emitActionResult=async e=>{_.has(e.callId)||(_.add(e.callId),await o(createActionResultEvent({result:e,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})))},emitActionPartial=async e=>{await o(createActionPartialEvent({result:e,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}))},emitToolCall=async e=>{if(isInvalidToolCall(e)){b.add(e.toolCallId);return}if(!(u===void 0||u.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:u.tools}))}catch(t){if(t instanceof TypeError){let n=createInvalidToolCallInputError({error:t,toolCall:e});b.add(e.toolCallId),f.trim().length>0&&await flushCurrentMessage(),await emitActionResult(createRuntimeToolResultFromToolError(n)),y.add(e.toolCallId),S.push(createToolResultMessagePartFromToolError(n));return}throw t}};for await(let e of c)if(m===void 0)switch(e.type){case`reasoning-delta`:await l.flush(),d+=e.text,await o(createReasoningAppendedEvent({reasoningDelta:e.text,reasoningSoFar:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}));break;case`text-delta`:await l.flush(),d.trim().length>0&&(await o(createReasoningCompletedEvent({reasoning:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),d=``),f+=e.text,await o(createMessageAppendedEvent({messageDelta:e.text,messageSoFar:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId}));break;case`tool-input-start`:if(u===void 0||e.providerExecuted===!0||u.excludedActionToolNames.has(e.toolName)){C.delete(e.id);break}await l.flush(),f.trim().length>0&&await flushCurrentMessage(),C.set(e.id,{offset:0,toolName:e.toolName}),await emitActionInput(e.id,e.toolName,``,0);break;case`tool-input-delta`:{let t=C.get(e.id);if(t===void 0)break;await l.flush();let n=t.offset;t.offset+=e.delta.length,await emitActionInput(e.id,t.toolName,e.delta,n);break}case`tool-input-end`:C.delete(e.id);break;case`tool-call`:{let t=e;C.delete(t.toolCallId),h.add(t.toolCallId),t.providerExecuted===!0?await collectProviderToolCall(t):(await l.flush(),await emitToolCall(t));break}case`tool-result`:{let t=e;if(t.preliminary===!0){t.providerExecuted!==!0&&await emitActionPartial(createRuntimeToolResultFromStepResult(t));break}if(t.providerExecuted===!0){await collectProviderToolCall({input:`input`in t?t.input:void 0,toolCallId:t.toolCallId,toolName:t.toolName}),await l.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(t));break}if(h.has(e.toolCallId)){if(isInlineAuthorizationToolResult(t))break;g.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(t)),y.add(e.toolCallId));break}if(await l.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(t)){y.add(e.toolCallId),x.push(t);break}await emitActionResult(createRuntimeToolResultFromStepResult(t)),y.add(e.toolCallId);break}case`tool-error`:{let t=e;t.providerExecuted===!0?(await collectProviderToolCall(t),await l.flush(),await emitActionResult(createRuntimeToolResultFromToolError(t))):g.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(t)),y.add(t.toolCallId),S.push(createToolResultMessagePartFromToolError(t)));break}case`finish-step`:p=normalizeAssistantStepFinishReason(e.finishReason),await l.flush();break;case`error`:m=normalizeModelStreamError(e.error);break;case`abort`:throw new DOMException(e.reason??`The model stream was aborted.`,`AbortError`);default:break}if(await l.flush(),m!==void 0)throw m;return d.trim().length>0&&await o(createReasoningCompletedEvent({reasoning:d,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),p!==`tool-calls`&&hasEmptyDeliverySentinel(f)?await o(createMessageCompletedEvent({finishReason:p,message:null,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})):f.trim().length>0&&await o(createMessageCompletedEvent({finishReason:p,message:f,sequence:s.sequence,stepIndex:s.stepIndex,turnId:s.turnId})),{emittedActionCallIds:g,handledInlineToolResultCallIds:y,invalidInputToolCallIds:b,inlineAuthorizationResults:x,trailingInlineToolResultParts:S}}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
@@ -1,6 +1,7 @@
1
1
  import type { InstrumentationHooks } from "#harness/instrumentation/lifecycle.js";
2
2
  import type { ChannelAudience } from "#shared/channel-audience.js";
3
- /** Hosted instrumentation records conversation content only for known-public channels. */
4
- export declare function shouldCaptureInstrumentationContent(audience: ChannelAudience): boolean;
3
+ import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
4
+ export { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
5
+ export declare function instrumentationHooksForDecision(hooks: InstrumentationHooks | undefined, decision: InstrumentationDecision, audience: ChannelAudience): InstrumentationHooks | undefined;
5
6
  /** Applies the audience ceiling before any content-capable provider sees an event. */
6
7
  export declare function instrumentationHooksForAudience(hooks: InstrumentationHooks | undefined, audience: ChannelAudience): InstrumentationHooks | undefined;
@@ -1 +1 @@
1
- import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{withoutInstrumentationContent}from"#harness/instrumentation/content.js";function shouldCaptureInstrumentationContent(t){return t===`public`||t===`unknown`&&isEveDevEnvironment()}function instrumentationHooksForAudience(e,n){return e===void 0||!e.capturesContent||shouldCaptureInstrumentationContent(n)?e:{capturesContent:!1,publish:n=>e.publish(withoutInstrumentationContent(n))}}export{instrumentationHooksForAudience,shouldCaptureInstrumentationContent};
1
+ import{withInstrumentationDecision,withoutInstrumentationContent}from"#harness/instrumentation/content.js";import{applyAudienceCeiling,shouldCaptureInstrumentationContent,shouldCaptureInstrumentationContent as shouldCaptureInstrumentationContent$1}from"#shared/instrumentation-content.js";function instrumentationHooksForDecision(t,r,i){if(r.action===`drop`)return instrumentationHooksForAudience(t,i);let a=applyAudienceCeiling(r,i);return a.action===`drop`||t===void 0||!t.capturesContent||a.recordInputs&&a.recordOutputs?t:{capturesContent:a.recordInputs||a.recordOutputs,publish:n=>t.publish(withInstrumentationDecision(n,a))}}function instrumentationHooksForAudience(e,n){return e===void 0||!e.capturesContent||shouldCaptureInstrumentationContent$1(n)?e:{capturesContent:!1,publish:n=>e.publish(withoutInstrumentationContent(n))}}export{instrumentationHooksForAudience,instrumentationHooksForDecision,shouldCaptureInstrumentationContent};
@@ -1,5 +1,16 @@
1
1
  import type { InstrumentationEvent } from "#harness/instrumentation/lifecycle.js";
2
+ import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
2
3
  /** Returns an immutable event projection with conversation content removed. */
3
4
  export declare function withoutInstrumentationContent(event: InstrumentationEvent): InstrumentationEvent;
5
+ /**
6
+ * Projects lifecycle content by direction.
7
+ *
8
+ * Inputs are data entering the agent: delivery/action/tool/model starts and a
9
+ * resolved user's response. Outputs are data produced by the agent: requests
10
+ * for user input, action/tool/model terminals, provider metadata, and errors.
11
+ */
12
+ export declare function withInstrumentationDecision(event: InstrumentationEvent, decision: Extract<InstrumentationDecision, {
13
+ action: "record";
14
+ }>): InstrumentationEvent;
4
15
  /** Provider metadata fields that describe cost/identity rather than content. */
5
16
  export declare function structuralProviderMetadata(metadata: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>>;
@@ -1 +1 @@
1
- function withoutInstrumentationContent(e){switch(e.type){case`channel.delivery.started`:return Object.freeze({...e,input:void 0});case`action.started`:return Object.freeze({...e,input:void 0});case`action.completed`:return Object.freeze({...e,output:Object.freeze({type:e.output.type})});case`input.requested`:return Object.freeze({...e,request:void 0});case`input.resolved`:return Object.freeze({...e,error:void 0,response:void 0});case`tool.call.started`:return Object.freeze({...e,input:void 0});case`tool.call.completed`:return Object.freeze({...e,output:Object.freeze({type:e.output.type})});case`model.call.started`:return Object.freeze({...e,input:void 0});case`model.call.completed`:return Object.freeze({...e,content:void 0});case`step.attempt.metadata`:return Object.freeze({...e,providerMetadata:structuralProviderMetadata(e.providerMetadata)});case`action.failed`:case`model.call.failed`:case`session.failed`:case`step.attempt.failed`:case`tool.call.failed`:case`turn.failed`:case`channel.delivery.failed`:return Object.freeze({...e,error:void 0});default:return e}}function structuralProviderMetadata(e){let t=e.gateway;if(typeof t!=`object`||!t||Array.isArray(t))return Object.freeze({});let n=t,r={};for(let e of[`cost`,`generationId`]){let t=n[e];(typeof t==`string`||typeof t==`number`)&&(r[e]=t)}return Object.freeze(Object.keys(r).length===0?{}:{gateway:Object.freeze(r)})}export{structuralProviderMetadata,withoutInstrumentationContent};
1
+ function withoutInstrumentationContent(e){return withInstrumentationDecision(e,{action:`record`,recordInputs:!1,recordOutputs:!1})}function withInstrumentationDecision(e,t){switch(e.type){case`channel.delivery.started`:return t.recordInputs?e:Object.freeze({...e,input:void 0});case`action.started`:return t.recordInputs?e:Object.freeze({...e,input:void 0});case`action.completed`:return t.recordOutputs?e:Object.freeze({...e,output:Object.freeze({type:e.output.type})});case`input.requested`:return t.recordOutputs?e:Object.freeze({...e,request:void 0});case`input.resolved`:return t.recordInputs&&t.recordOutputs?e:Object.freeze({...e,error:t.recordOutputs?e.error:void 0,response:t.recordInputs?e.response:void 0});case`tool.call.started`:return t.recordInputs?e:Object.freeze({...e,input:void 0});case`tool.call.completed`:return t.recordOutputs?e:Object.freeze({...e,output:Object.freeze({type:e.output.type})});case`model.call.started`:return t.recordInputs?e:Object.freeze({...e,input:void 0});case`model.call.completed`:return t.recordOutputs?e:Object.freeze({...e,content:void 0});case`step.attempt.metadata`:return t.recordOutputs?e:Object.freeze({...e,providerMetadata:structuralProviderMetadata(e.providerMetadata)});case`action.failed`:case`model.call.failed`:case`session.failed`:case`step.attempt.failed`:case`tool.call.failed`:case`turn.failed`:case`channel.delivery.failed`:return t.recordOutputs?e:Object.freeze({...e,error:void 0});default:return e}}function structuralProviderMetadata(e){let t=e.gateway;if(typeof t!=`object`||!t||Array.isArray(t))return Object.freeze({});let n=t,r={};for(let e of[`cost`,`generationId`]){let t=n[e];(typeof t==`string`||typeof t==`number`)&&(r[e]=t)}return Object.freeze(Object.keys(r).length===0?{}:{gateway:Object.freeze(r)})}export{structuralProviderMetadata,withInstrumentationDecision,withoutInstrumentationContent};
@@ -1 +1 @@
1
- const MAX_PENDING_DELTA_CHARACTERS=64*1024;function createOrderedStreamEmitter(t,n={}){let r=n.maxPendingEvents??64;if(!Number.isInteger(r)||r<1)throw RangeError(`maxPendingEvents must be a positive integer.`);let i=[],a=new Set,o=new Set,s=!1,c=0,l=0,u,d=!1,f=!1,p=new AbortController,throwIfFailed=()=>{if(d)throw u},settleIdleWaiters=()=>{for(let e of o)e();o.clear()},hasCapacity=()=>l<r&&c<MAX_PENDING_DELTA_CHARACTERS,settleCapacityWaiters=()=>{if(hasCapacity()){for(let e of a)e();a.clear()}},pump=async()=>{if(!(f||d)){for(f=!0;i.length>0;){let e=i.shift();if(e===void 0)break;c-=e.deltaCharacters,l-=e.sourceEvents,settleCapacityWaiters();try{await t(materializeEvent(e),e.messages)}catch(e){d||(u=e,d=!0,p.abort(e)),i.length=0,c=0,l=0,settleCapacityWaiters();break}}f=!1,settleIdleWaiters()}},waitForIdle=async()=>{if(!f&&i.length===0){throwIfFailed();return}await new Promise(e=>{o.add(e)}),throwIfFailed()},waitForCapacity=async()=>{hasCapacity()||(await new Promise(e=>{a.add(e)}),throwIfFailed())};return{async closeAndDrain(){s=!0,pump(),await waitForIdle()},async emit(t,n){if(throwIfFailed(),s)throw TypeError(`Cannot emit after the ordered stream emitter has closed.`);let a=i.length-1,o=i[a],u=appendDelta(t);o===void 0||!mergeAdjacentEmissions(o,t,n)?i.push({deltaCharacters:u?.length??0,event:t,messages:n,sourceEvents:1}):(o.deltaCharacters+=u?.length??0,o.sourceEvents+=1),c+=u?.length??0,l+=1,pump(),(l>=r||c>=MAX_PENDING_DELTA_CHARACTERS)&&await waitForCapacity(),throwIfFailed()},failureSignal:p.signal}}function mergeAdjacentEmissions(e,t,n){return e.event.type===`message.appended`&&t.type===`message.appended`?sameCoordinates(e.event,t)?(e.deltaParts??=[e.event.data.messageDelta],e.deltaParts.push(t.data.messageDelta),e.event=t,e.messages=n,!0):!1:e.event.type===`reasoning.appended`&&t.type===`reasoning.appended`?sameCoordinates(e.event,t)?(e.deltaParts??=[e.event.data.reasoningDelta],e.deltaParts.push(t.data.reasoningDelta),e.event=t,e.messages=n,!0):!1:e.event.type===`action.partial`&&t.type===`action.partial`&&e.event.data.result.callId===t.data.result.callId?(e.event=t,e.messages=n,!0):!1}function appendDelta(e){if(e.type===`message.appended`)return e.data.messageDelta;if(e.type===`reasoning.appended`)return e.data.reasoningDelta}function materializeEvent(e){return e.deltaParts===void 0?e.event:e.event.type===`message.appended`?{...e.event,data:{...e.event.data,messageDelta:e.deltaParts.join(``)}}:e.event.type===`reasoning.appended`?{...e.event,data:{...e.event.data,reasoningDelta:e.deltaParts.join(``)}}:e.event}function sameCoordinates(e,t){return e.data.sequence===t.data.sequence&&e.data.stepIndex===t.data.stepIndex&&e.data.turnId===t.data.turnId}export{createOrderedStreamEmitter};
1
+ const MAX_PENDING_DELTA_CHARACTERS=64*1024;function createOrderedStreamEmitter(t,n={}){let r=n.maxPendingEvents??64;if(!Number.isInteger(r)||r<1)throw RangeError(`maxPendingEvents must be a positive integer.`);let i=[],a=new Set,o=new Set,s=!1,c=0,l=0,u,d=!1,f=!1,p=new AbortController,throwIfFailed=()=>{if(d)throw u},settleIdleWaiters=()=>{for(let e of o)e();o.clear()},hasCapacity=()=>l<r&&c<MAX_PENDING_DELTA_CHARACTERS,settleCapacityWaiters=()=>{if(hasCapacity()){for(let e of a)e();a.clear()}},pump=async()=>{if(!(f||d)){for(f=!0;i.length>0;){let e=i.shift();if(e===void 0)break;c-=e.deltaCharacters,l-=e.sourceEvents,settleCapacityWaiters();try{await t(materializeEvent(e),e.messages)}catch(e){d||(u=e,d=!0,p.abort(e)),i.length=0,c=0,l=0,settleCapacityWaiters();break}}f=!1,settleIdleWaiters()}},waitForIdle=async()=>{if(!f&&i.length===0){throwIfFailed();return}await new Promise(e=>{o.add(e)}),throwIfFailed()},waitForCapacity=async()=>{hasCapacity()||(await new Promise(e=>{a.add(e)}),throwIfFailed())};return{async closeAndDrain(){s=!0,pump(),await waitForIdle()},async emit(t,n){if(throwIfFailed(),s)throw TypeError(`Cannot emit after the ordered stream emitter has closed.`);let a=i.length-1,o=i[a],u=appendDelta(t);o===void 0||!mergeAdjacentEmissions(o,t,n)?i.push({deltaCharacters:u?.length??0,event:t,messages:n,sourceEvents:1}):(o.deltaCharacters+=u?.length??0,o.sourceEvents+=1),c+=u?.length??0,l+=1,pump(),(l>=r||c>=MAX_PENDING_DELTA_CHARACTERS)&&await waitForCapacity(),throwIfFailed()},failureSignal:p.signal}}function mergeAdjacentEmissions(e,t,n){let r=appendKey(e.event),i=appendKey(t);return r!==void 0||i!==void 0?r===void 0||r!==i||!isAppendEvent(e.event)||!isAppendEvent(t)||!sameCoordinates(e.event,t)?!1:(e.deltaParts??=[appendDelta(e.event)],e.deltaParts.push(appendDelta(t)),e.event=e.event.type===`action.input.appended`&&t.type===`action.input.appended`?{...t,data:{...t.data,inputTextOffset:e.event.data.inputTextOffset}}:t,e.messages=n,!0):e.event.type===`action.partial`&&t.type===`action.partial`&&e.event.data.result.callId===t.data.result.callId?(e.event=t,e.messages=n,!0):!1}function appendKey(e){switch(e.type){case`message.appended`:case`reasoning.appended`:return e.type;case`action.input.appended`:return`${e.type}:${e.data.callId}`;default:return}}function isAppendEvent(e){return appendKey(e)!==void 0}function appendDelta(e){switch(e.type){case`message.appended`:return e.data.messageDelta;case`reasoning.appended`:return e.data.reasoningDelta;case`action.input.appended`:return e.data.inputTextDelta;default:return}}function materializeEvent(e){return e.deltaParts===void 0?e.event:e.event.type===`message.appended`?{...e.event,data:{...e.event.data,messageDelta:e.deltaParts.join(``)}}:e.event.type===`reasoning.appended`?{...e.event,data:{...e.event.data,reasoningDelta:e.deltaParts.join(``)}}:e.event.type===`action.input.appended`?{...e.event,data:{...e.event.data,inputTextDelta:e.deltaParts.join(``)}}:e.event}function sameCoordinates(e,t){return e.data.sequence===t.data.sequence&&e.data.stepIndex===t.data.stepIndex&&e.data.turnId===t.data.turnId}export{createOrderedStreamEmitter};