eve 0.64.1 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/src/channel/resolve-text.d.ts +11 -7
  3. package/dist/src/channel/resolve-text.js +1 -1
  4. package/dist/src/channel/types.d.ts +4 -5
  5. package/dist/src/chunks/{use-eve-agent-BdKlQF32.js → use-eve-agent-BIouJCii.js} +2 -10
  6. package/dist/src/chunks/{use-eve-agent-IIuxkn6y.js → use-eve-agent-BRvEh9sO.js} +2 -10
  7. package/dist/src/cli/dev/command-options.d.ts +1 -0
  8. package/dist/src/cli/dev/command.js +2 -2
  9. package/dist/src/cli/dev/local-server-process.js +1 -1
  10. package/dist/src/cli/dev/tui/blocks.d.ts +1 -1
  11. package/dist/src/cli/dev/tui/blocks.js +1 -1
  12. package/dist/src/cli/dev/tui/question-panel.d.ts +3 -2
  13. package/dist/src/cli/dev/tui/rail.d.ts +1 -1
  14. package/dist/src/cli/dev/tui/terminal-renderer.js +11 -12
  15. package/dist/src/cli/dev/tui/theme.d.ts +1 -1
  16. package/dist/src/cli/dev/tui/tool-presentation.d.ts +4 -4
  17. package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
  18. package/dist/src/client/agent-info-schema.d.ts +0 -2
  19. package/dist/src/client/agent-info-schema.js +1 -1
  20. package/dist/src/compiled/.vendor-stamp.json +1 -2
  21. package/dist/src/compiler/artifacts.d.ts +2 -0
  22. package/dist/src/compiler/artifacts.js +1 -1
  23. package/dist/src/compiler/bundled-extension.d.ts +17 -0
  24. package/dist/src/compiler/bundled-extension.js +1 -0
  25. package/dist/src/compiler/compile-agent.d.ts +4 -0
  26. package/dist/src/compiler/compile-agent.js +1 -1
  27. package/dist/src/compiler/compile-from-memory.js +1 -1
  28. package/dist/src/compiler/development-extensions.d.ts +23 -0
  29. package/dist/src/compiler/development-extensions.js +1 -0
  30. package/dist/src/compiler/extension-compatibility.d.ts +2 -2
  31. package/dist/src/compiler/extension-compatibility.js +1 -1
  32. package/dist/src/compiler/load-binding-namespace.js +1 -1
  33. package/dist/src/compiler/manifest.js +1 -1
  34. package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
  35. package/dist/src/compiler/normalize-manifest-types.d.ts +23 -0
  36. package/dist/src/compiler/normalize-manifest-types.js +1 -0
  37. package/dist/src/compiler/normalize-manifest.d.ts +2 -7
  38. package/dist/src/compiler/normalize-manifest.js +1 -1
  39. package/dist/src/compiler/source-graph-paths.d.ts +2 -0
  40. package/dist/src/compiler/source-graph-paths.js +1 -0
  41. package/dist/src/compiler/source-graph.d.ts +4 -1
  42. package/dist/src/compiler/source-graph.js +1 -1
  43. package/dist/src/context/dynamic-skill-lifecycle.js +1 -1
  44. package/dist/src/discover/bundled-extension.d.ts +11 -0
  45. package/dist/src/discover/bundled-extension.js +1 -0
  46. package/dist/src/discover/discover-agent.js +1 -1
  47. package/dist/src/discover/manifest.d.ts +5 -0
  48. package/dist/src/evals/assertions/collector.js +1 -1
  49. package/dist/src/evals/cli/eval.js +2 -2
  50. package/dist/src/evals/runner/artifacts.js +1 -1
  51. package/dist/src/evals/types.d.ts +2 -0
  52. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  53. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  54. package/dist/src/execution/node-step.d.ts +2 -4
  55. package/dist/src/execution/node-step.js +1 -1
  56. package/dist/src/execution/proxied-deliver-step.js +1 -1
  57. package/dist/src/execution/sandbox/glob-tool.js +1 -1
  58. package/dist/src/execution/sandbox/grep-tool.js +1 -1
  59. package/dist/src/execution/sandbox/read-file.js +1 -1
  60. package/dist/src/execution/session-workflow-tool-run.js +1 -1
  61. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  62. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  63. package/dist/src/execution/tools/ask-question-workflow.d.ts +11 -0
  64. package/dist/src/execution/tools/ask-question-workflow.js +1 -0
  65. package/dist/src/execution/tools/ask-question.d.ts +20 -0
  66. package/dist/src/execution/tools/ask-question.js +2 -0
  67. package/dist/src/execution/tools/file-state.d.ts +1 -7
  68. package/dist/src/execution/tools/file-state.js +1 -1
  69. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  70. package/dist/src/execution/tools/workflow/answer.d.ts +2 -0
  71. package/dist/src/execution/tools/workflow/answer.js +1 -1
  72. package/dist/src/execution/tools/workflow/ask.d.ts +3 -2
  73. package/dist/src/execution/tools/workflow/ask.js +1 -1
  74. package/dist/src/execution/tools/workflow/body.d.ts +5 -0
  75. package/dist/src/execution/tools/workflow/body.js +1 -1
  76. package/dist/src/execution/tools/workflow/cancel.d.ts +0 -4
  77. package/dist/src/execution/tools/workflow/cancel.js +1 -1
  78. package/dist/src/execution/tools/workflow/start.d.ts +1 -0
  79. package/dist/src/execution/tools/workflow/start.js +1 -1
  80. package/dist/src/framework/sources/registry.js +1 -1
  81. package/dist/src/harness/compaction-prompt.d.ts +0 -6
  82. package/dist/src/harness/compaction-prompt.js +2 -2
  83. package/dist/src/harness/compaction.js +1 -1
  84. package/dist/src/harness/hitl/approval-input-requests.d.ts +0 -2
  85. package/dist/src/harness/hitl/approval-input-requests.js +1 -1
  86. package/dist/src/harness/input-extraction.d.ts +4 -15
  87. package/dist/src/harness/input-extraction.js +1 -1
  88. package/dist/src/harness/input-request-class.d.ts +0 -20
  89. package/dist/src/harness/input-request-class.js +1 -1
  90. package/dist/src/harness/input-requests.d.ts +1 -1
  91. package/dist/src/harness/input-requests.js +1 -1
  92. package/dist/src/harness/pending-input-batches.d.ts +1 -1
  93. package/dist/src/harness/proxy-input-requests.d.ts +9 -1
  94. package/dist/src/harness/proxy-input-requests.js +1 -1
  95. package/dist/src/harness/stale-input-responses.d.ts +1 -2
  96. package/dist/src/harness/stale-input-responses.js +1 -1
  97. package/dist/src/harness/tool-loop.js +2 -2
  98. package/dist/src/harness/tools.d.ts +0 -9
  99. package/dist/src/harness/tools.js +1 -1
  100. package/dist/src/harness/types.d.ts +2 -9
  101. package/dist/src/internal/application/package.js +1 -1
  102. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  103. package/dist/src/internal/authored-module-loader.js +1 -1
  104. package/dist/src/internal/development-programmatic-source-loader.d.ts +6 -0
  105. package/dist/src/internal/development-programmatic-source-loader.js +1 -0
  106. package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
  107. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  108. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.d.ts +2 -0
  109. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -1
  110. package/dist/src/internal/nitro/host/dev-workspace-extensions.js +1 -1
  111. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +2 -0
  112. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  113. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  114. package/dist/src/internal/nitro/host/types.d.ts +3 -0
  115. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  116. package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +0 -2
  117. package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
  118. package/dist/src/public/tools/ask-question.d.ts +1 -1
  119. package/dist/src/public/tools/ask-question.js +1 -1
  120. package/dist/src/runtime/agent/mock-model-fixtures.js +2 -2
  121. package/dist/src/self-modification/extension/subagents/agent/instructions.js +6 -2
  122. package/dist/src/setup/scaffold/create/project.js +1 -1
  123. package/dist/src/shared/input.d.ts +1 -6
  124. package/dist/src/subagents/hitl-proxy.d.ts +11 -1
  125. package/dist/src/subagents/hitl-proxy.js +1 -1
  126. package/dist/src/svelte/index.js +1 -1
  127. package/dist/src/svelte/use-eve-agent.js +1 -1
  128. package/dist/src/tools/behavior.d.ts +2 -5
  129. package/dist/src/tools/definition.d.ts +23 -5
  130. package/dist/src/tools/provided/ask-question.d.ts +18 -0
  131. package/dist/src/tools/provided/ask-question.js +1 -0
  132. package/dist/src/tools/provided/sleep.d.ts +2 -2
  133. package/dist/src/vue/index.js +1 -1
  134. package/dist/src/vue/use-eve-agent.js +1 -1
  135. package/docs/agent-config.md +11 -11
  136. package/docs/concepts/built-in-tools.md +16 -66
  137. package/docs/concepts/default-harness.md +1 -3
  138. package/docs/concepts/execution-model-and-durability.mdx +1 -1
  139. package/docs/concepts/sessions-runs-and-streaming.md +2 -2
  140. package/docs/evals/assertions.mdx +2 -2
  141. package/docs/evals/judge.mdx +3 -3
  142. package/docs/getting-started.mdx +1 -1
  143. package/docs/guides/dev-tui.md +1 -1
  144. package/docs/guides/evaluate.md +12 -9
  145. package/docs/guides/frontend/overview.mdx +1 -1
  146. package/docs/reference/cli.md +10 -7
  147. package/docs/reference/typescript-api.md +42 -41
  148. package/docs/skills.mdx +2 -0
  149. package/docs/subagents/index.mdx +7 -5
  150. package/docs/tools/human-in-the-loop.md +22 -11
  151. package/docs/tools/workflows.mdx +44 -19
  152. package/docs/tutorial/guard-the-spend.mdx +1 -1
  153. package/package.json +1 -9
  154. package/dist/src/cli/dev/tui/todo-panel.d.ts +0 -44
  155. package/dist/src/cli/dev/tui/todo-panel.js +0 -1
  156. package/dist/src/compiled/@workflow/builders/LICENSE.md +0 -201
  157. package/dist/src/compiled/@workflow/builders/index.d.ts +0 -62
  158. package/dist/src/compiled/@workflow/builders/index.js +0 -1
  159. package/dist/src/execution/compaction.d.ts +0 -14
  160. package/dist/src/execution/compaction.js +0 -1
  161. package/dist/src/execution/tools/todo.d.ts +0 -91
  162. package/dist/src/execution/tools/todo.js +0 -2
  163. package/dist/src/harness/hitl/question-input-requests.d.ts +0 -15
  164. package/dist/src/harness/hitl/question-input-requests.js +0 -1
  165. package/dist/src/harness/request-input-tool.d.ts +0 -4
  166. package/dist/src/harness/request-input-tool.js +0 -1
  167. package/dist/src/public/tools/todo.d.ts +0 -3
  168. package/dist/src/public/tools/todo.js +0 -1
  169. package/dist/src/tools/framework/ask-question.d.ts +0 -38
  170. package/dist/src/tools/framework/ask-question.js +0 -1
  171. package/dist/src/tools/provided/todo.d.ts +0 -8
  172. package/dist/src/tools/provided/todo.js +0 -2
@@ -0,0 +1 @@
1
+ import{isAbsolute,posix}from"node:path";import{getSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension}from"#discover/filesystem.js";function validateProgrammaticLogicalPath(e){return validateProgrammaticLogicalPathInternal(e,!1)}function validateProgrammaticLogicalPathInternal(e,t){if(e.length===0||isAbsolute(e)||e.includes(`\\`))throw Error(`Programmatic module logical path "${e}" must be a relative POSIX path.`);let n=normalizeLogicalPath(e);if(n===`.`||n.startsWith(`../`)||n.includes(`/../`)||posix.normalize(n)!==n)throw Error(`Programmatic module logical path "${e}" may not traverse directories.`);let r=n.split(`/`),i=r.at(-1);if(getSupportedModuleBaseName(i)===null)throw Error(`Programmatic module logical path "${e}" must use a supported JavaScript or TypeScript extension.`);let a=r[0],o=stripLogicalPathExtension(n);if(!(r.length===1&&[`agent`,`memory`,`sandbox`,`instrumentation`].includes(o)||a===`sandbox`&&r.length===2&&getSupportedModuleBaseName(i)===`sandbox`||[`channels`,`connections`,`hooks`,`instructions`,`memory`,`schedules`,`skills`,`tools`].includes(a)&&r.length>=2||t&&a===`extensions`&&r.length===2))throw Error(`Programmatic module logical path "${e}" does not select an eve module slot.`);return n}export{validateProgrammaticLogicalPath,validateProgrammaticLogicalPathInternal};
@@ -1,3 +1,4 @@
1
+ export { validateProgrammaticLogicalPath } from "#compiler/source-graph-paths.js";
1
2
  import { type JsonObject } from "#shared/json.js";
2
3
  export type ProgrammaticModuleNamespace = Readonly<Record<string, unknown>>;
3
4
  /** Shares zero-argument definition-factory results within one module-map load. */
@@ -22,6 +23,8 @@ export interface AgentSourceRegistration {
22
23
  readonly source: ProgrammaticAgentSource;
23
24
  }
24
25
  export interface AgentSourceRegistryOptions {
26
+ /** Programmatic extension declarations loaded by compiled virtual mounts. */
27
+ readonly extensionDeclarations?: readonly ProgrammaticAgentSource[];
25
28
  readonly templates?: readonly ProgrammaticAgentSource[];
26
29
  }
27
30
  export interface RegisteredProgrammaticTemplate {
@@ -127,6 +130,7 @@ export interface ComposedAgentModuleCandidates {
127
130
  readonly selected: ReadonlyMap<string, AgentSourceCandidate>;
128
131
  }
129
132
  export declare function defineProgrammaticAgentSource(input: ProgrammaticAgentSource): ProgrammaticAgentSource;
133
+ export declare function defineProgrammaticExtensionMountDeclaration(input: ProgrammaticAgentSource): ProgrammaticAgentSource;
130
134
  export declare function createAgentSourceRegistry(registrations: readonly AgentSourceRegistration[], options?: AgentSourceRegistryOptions): AgentSourceRegistry;
131
135
  export declare function createProgrammaticModuleCandidates(input: {
132
136
  readonly layer: AgentSourceLayer;
@@ -162,5 +166,4 @@ export declare function canonicalModuleSlot(logicalPath: string): string;
162
166
  * forms, and skill packages collapse onto the same authored primitive identity.
163
167
  */
164
168
  export declare function canonicalSourceSlot(logicalPath: string): string;
165
- export declare function validateProgrammaticLogicalPath(input: string): string;
166
169
  export declare function describeAgentSourceCandidate(candidate: AgentSourceCandidate): AgentSourceDescriptor;
@@ -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()}};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]}))),a=Object.freeze(parseJsonObject(e.parameters??{}));return Object.freeze({backing:Object.freeze({dependencies:i,kind:`programmatic`,moduleId:e.template.module.logicalPath,parameters:a,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]),o=a[0];r.set(e,o);for(let e of a.slice(1))i.push({kind:`shadowed`,source:describeAgentSourceCandidate(e),winnerSourceId:o.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)&&e.allowUnmatched!==!0)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 t=normalizeLogicalPath(e);if(t.length===0||t===`.`||t.startsWith(`../`)||t.includes(`/../`)||posix.normalize(t)!==t)throw Error(`Agent source logical path "${e}" is invalid.`);let n=stripLogicalPathExtension(t),r=n.match(/^connections\/([^/]+)\/connection$/);if(r!==null)return`connections/${r[1]}`;if(n===`sandbox/sandbox`)return`sandbox`;let i=n.match(/^skills\/([^/]+)\/SKILL$/);return i===null?n:`skills/${i[1]}`}function validateProgrammaticLogicalPath(e){if(e.length===0||isAbsolute(e)||e.includes(`\\`))throw Error(`Programmatic module logical path "${e}" must be a relative POSIX path.`);let t=normalizeLogicalPath(e);if(t===`.`||t.startsWith(`../`)||t.includes(`/../`)||posix.normalize(t)!==t)throw Error(`Programmatic module logical path "${e}" may not traverse directories.`);let n=t.split(`/`),r=n.at(-1);if(getSupportedModuleBaseName(r)===null)throw Error(`Programmatic module logical path "${e}" must use a supported JavaScript or TypeScript extension.`);let i=n[0],a=stripLogicalPathExtension(t);if(!(n.length===1&&[`agent`,`memory`,`sandbox`].includes(a)||i===`sandbox`&&n.length===2&&getSupportedModuleBaseName(r)===`sandbox`||[`channels`,`connections`,`hooks`,`instructions`,`memory`,`schedules`,`skills`,`tools`].includes(i)&&n.length>=2))throw Error(`Programmatic module logical path "${e}" does not select an eve module slot.`);return t}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
+ import{posix}from"node:path";import{normalizeLogicalPath,stripLogicalPathExtension}from"#discover/filesystem.js";import{parseJsonObject}from"#shared/json.js";import{validateProgrammaticLogicalPath,validateProgrammaticLogicalPath as validateProgrammaticLogicalPath$1,validateProgrammaticLogicalPathInternal}from"#compiler/source-graph-paths.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){return defineProgrammaticAgentSourceInternal(e,!1)}function defineProgrammaticAgentSourceInternal(e,t){let n=expectNonEmpty(e.id,`Programmatic agent source id`),r=expectNonEmpty(e.revision,`Programmatic agent source "${n}" revision`),i=new Set,a=e.modules.map(e=>{let r=validateProgrammaticLogicalPathInternal(e.logicalPath,t);if(i.has(r))throw Error(`Programmatic agent source "${n}" declares "${r}" more than once.`);i.add(r);let a=e.semanticRevision===void 0?void 0:expectNonEmpty(e.semanticRevision,`Programmatic module "${n}:${r}" semanticRevision`);return Object.freeze({exportName:e.exportName,loadNamespace:e.loadNamespace,logicalPath:r,semanticRevision:a})});return Object.freeze({id:n,modules:Object.freeze(a),revision:r})}function defineProgrammaticExtensionMountDeclaration(e){return defineProgrammaticAgentSourceInternal(e,!0)}function createAgentSourceRegistry(e,t={}){let n=new Map,r=new Map,addSource=(e,t=!1)=>{let r=defineProgrammaticAgentSourceInternal(e,t);if(n.has(r.id))throw Error(`Programmatic agent source id "${r.id}" is registered more than once.`);return n.set(r.id,r),r},i=e.map(e=>{let t=addSource(e.source);return Object.freeze({applyTo:e.applyTo,source:t})});for(let e of t.extensionDeclarations??[])addSource(e,!0);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$1(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]}))),a=Object.freeze(parseJsonObject(e.parameters??{}));return Object.freeze({backing:Object.freeze({dependencies:i,kind:`programmatic`,moduleId:e.template.module.logicalPath,parameters:a,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]),o=a[0];r.set(e,o);for(let e of a.slice(1))i.push({kind:`shadowed`,source:describeAgentSourceCandidate(e),winnerSourceId:o.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)&&e.allowUnmatched!==!0)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$1(e),canonicalSourceSlot(e)}function canonicalSourceSlot(e){let t=normalizeLogicalPath(e);if(t.length===0||t===`.`||t.startsWith(`../`)||t.includes(`/../`)||posix.normalize(t)!==t)throw Error(`Agent source logical path "${e}" is invalid.`);let n=stripLogicalPathExtension(t),r=n.match(/^connections\/([^/]+)\/connection$/);if(r!==null)return`connections/${r[1]}`;if(n===`sandbox/sandbox`)return`sandbox`;let i=n.match(/^skills\/([^/]+)\/SKILL$/);return i===null?n:`skills/${i[1]}`}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,defineProgrammaticExtensionMountDeclaration,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate,isAgentModuleCandidate,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories,validateProgrammaticLogicalPath};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{DynamicSkillManifestKey,SandboxKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{ALLOWED_DYNAMIC_SKILL_EVENTS}from"#dynamic/definition.js";import{normalizeSkillPackage,removeSkillPackageFromSandbox,writeSkillPackageToSandbox}from"#shared/skill-package.js";import{ContextKey}from"#context/key.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{isBrandedSkillEntry}from"#shared/skill-definition.js";import{formatAvailableSkillsSection}from"#execution/skills/instructions.js";import{resolveSandboxSkillRoot}from"#shared/skill-paths.js";const log=createLogger(`dynamic-skills`);function qualifyDynamicSkillNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t)return i.push({name:e.slug,entryKey:r[0],entry:n[r[0]]}),i;let a=e.extensionNamespace===void 0?``:`${e.extensionNamespace}__`;for(let e of r)i.push({name:`${a}${e}`,entryKey:e,entry:n[e]});return i}async function formatDynamicSkillAnnouncement(e){let t=await e.ctx.require(SandboxKey).get(),n=t===null?void 0:await resolveSandboxSkillRoot({sandbox:t});return formatAvailableSkillsSection(Object.values(e.manifest).flat(),{skillRoot:n})??`Available skills: none`}const PendingSkillAnnouncementKey=new ContextKey(`eve.pendingSkillAnnouncement`);async function dispatchDynamicSkillEvent(e){let{ctx:t,resolvers:n,event:r,messages:i}=e;if(t.get(PendingSkillAnnouncementKey)===void 0){let e=t.get(DynamicSkillManifestKey);e!==void 0&&Object.keys(e).length>0&&t.setVirtualContext(PendingSkillAnnouncementKey,await formatDynamicSkillAnnouncement({ctx:t,manifest:e}))}if(!ALLOWED_DYNAMIC_SKILL_EVENTS.has(r.type))return;let a=n.filter(e=>e.eventNames.includes(r.type));if(a.length===0)return;let o=buildResolveContext(t,i),s=t.get(DynamicSkillManifestKey)??{},c=[],l=await Promise.allSettled(a.map(async e=>{let t=e.events[r.type];if(t===void 0)return null;let n=await t(r,o);if(n==null)return{resolver:e,named:[]};let i,a;return isBrandedSkillEntry(n)?(i={_single:n},a=!0):(i=n,a=!1),{resolver:e,named:qualifyDynamicSkillNames(e,a,i)}}));for(let e of l){if(e.status===`rejected`){log.error(`Dynamic skill resolver (${r.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}e.value!==null&&c.push({resolver:e.value.resolver,skills:e.value.named.map(({name:e,entry:t})=>normalizeSkillPackage({...t,name:e}))})}if(c.length===0)return;let u={...s};for(let{resolver:e,skills:t}of c)t.length===0?delete u[e.slug]:u[e.slug]=t.map(e=>({description:e.description,name:e.name}));let d=new Map;for(let[e,t]of Object.entries(u))for(let{name:n}of t){let t=d.get(n);if(t!==void 0)throw Error(`Dynamic skill "${n}" from resolver "${e}" collides with dynamic resolver "${t}". Namespace the map key manually, e.g. "${e}__${n}".`);d.set(n,e)}let f=await t.require(SandboxKey).get();if(f!==null){let e=new Set(Object.values(u).flat().map(e=>e.name)),t=new Set;for(let{resolver:n}of c)for(let r of s[n.slug]??[])e.has(r.name)||t.add(r.name);for(let e of t)await removeSkillPackageFromSandbox({name:e,sandbox:f});for(let{skills:e}of c)for(let t of e)await writeSkillPackageToSandbox({sandbox:f,skill:t})}t.set(DynamicSkillManifestKey,u),t.setVirtualContext(PendingSkillAnnouncementKey,await formatDynamicSkillAnnouncement({ctx:t,manifest:u}))}export{PendingSkillAnnouncementKey,dispatchDynamicSkillEvent};
1
+ import{createLogger}from"#internal/logging.js";import{DynamicSkillManifestKey,SandboxKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{ALLOWED_DYNAMIC_SKILL_EVENTS}from"#dynamic/definition.js";import{normalizeSkillPackage,removeSkillPackageFromSandbox,writeSkillPackageToSandbox}from"#shared/skill-package.js";import{ContextKey}from"#context/key.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{isBrandedSkillEntry}from"#shared/skill-definition.js";import{formatAvailableSkillsSection}from"#execution/skills/instructions.js";import{resolveSandboxSkillRoot}from"#shared/skill-paths.js";const log=createLogger(`dynamic-skills`);function qualifyDynamicSkillNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t)return i.push({name:e.slug,entryKey:r[0],entry:n[r[0]]}),i;let a=e.extensionNamespace===void 0?``:`${e.extensionNamespace}__`;for(let e of r)i.push({name:`${a}${e}`,entryKey:e,entry:n[e]});return i}async function formatDynamicSkillAnnouncement(e){let t=await e.ctx.require(SandboxKey).get(),n=t===null?void 0:await resolveSandboxSkillRoot({sandbox:t});return formatAvailableSkillsSection(Object.values(e.manifest).flat(),{skillRoot:n})??`Available skills: none`}const PendingSkillAnnouncementKey=new ContextKey(`eve.pendingSkillAnnouncement`);async function dispatchDynamicSkillEvent(e){let{ctx:t,resolvers:n,event:r,messages:i}=e;if(!ALLOWED_DYNAMIC_SKILL_EVENTS.has(r.type)&&r.type!==`step.started`)return;if(t.get(PendingSkillAnnouncementKey)===void 0){let e=t.get(DynamicSkillManifestKey);e!==void 0&&Object.keys(e).length>0&&t.setVirtualContext(PendingSkillAnnouncementKey,await formatDynamicSkillAnnouncement({ctx:t,manifest:e}))}if(!ALLOWED_DYNAMIC_SKILL_EVENTS.has(r.type))return;let a=n.filter(e=>e.eventNames.includes(r.type));if(a.length===0)return;let o=buildResolveContext(t,i),s=t.get(DynamicSkillManifestKey)??{},c=[],l=await Promise.allSettled(a.map(async e=>{let t=e.events[r.type];if(t===void 0)return null;let n=await t(r,o);if(n==null)return{resolver:e,named:[]};let i,a;return isBrandedSkillEntry(n)?(i={_single:n},a=!0):(i=n,a=!1),{resolver:e,named:qualifyDynamicSkillNames(e,a,i)}}));for(let e of l){if(e.status===`rejected`){log.error(`Dynamic skill resolver (${r.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}e.value!==null&&c.push({resolver:e.value.resolver,skills:e.value.named.map(({name:e,entry:t})=>normalizeSkillPackage({...t,name:e}))})}if(c.length===0)return;let u={...s};for(let{resolver:e,skills:t}of c)t.length===0?delete u[e.slug]:u[e.slug]=t.map(e=>({description:e.description,name:e.name}));let d=new Map;for(let[e,t]of Object.entries(u))for(let{name:n}of t){let t=d.get(n);if(t!==void 0)throw Error(`Dynamic skill "${n}" from resolver "${e}" collides with dynamic resolver "${t}". Namespace the map key manually, e.g. "${e}__${n}".`);d.set(n,e)}let f=await t.require(SandboxKey).get();if(f!==null){let e=new Set(Object.values(u).flat().map(e=>e.name)),t=new Set;for(let{resolver:n}of c)for(let r of s[n.slug]??[])e.has(r.name)||t.add(r.name);for(let e of t)await removeSkillPackageFromSandbox({name:e,sandbox:f});for(let{skills:e}of c)for(let t of e)await writeSkillPackageToSandbox({sandbox:f,skill:t})}t.set(DynamicSkillManifestKey,u),t.setVirtualContext(PendingSkillAnnouncementKey,await formatDynamicSkillAnnouncement({ctx:t,manifest:u}))}export{PendingSkillAnnouncementKey,dispatchDynamicSkillEvent};
@@ -0,0 +1,11 @@
1
+ import { type ProjectSource } from "#discover/project-source.js";
2
+ import type { DiscoverDiagnostic } from "#discover/diagnostics.js";
3
+ import type { ResolvedExtensionMount } from "#discover/manifest.js";
4
+ import type { BundledExtensionMount } from "#compiler/bundled-extension.js";
5
+ export declare function discoverBundledExtension(input: {
6
+ readonly mount: BundledExtensionMount;
7
+ readonly source?: ProjectSource;
8
+ }): Promise<{
9
+ readonly diagnostics: readonly DiscoverDiagnostic[];
10
+ readonly mount: ResolvedExtensionMount;
11
+ }>;
@@ -0,0 +1 @@
1
+ import{discoverAgent}from"#discover/discover-agent.js";import{createDiskProjectSource}from"#discover/project-source.js";async function discoverBundledExtension(e){let t=e.source??createDiskProjectSource(),n=await discoverAgent({agentRoot:e.mount.sourceRoot,appRoot:e.mount.packageRoot,role:`extension`,source:t}),r=e.mount.declaration.modules[0];if(r===void 0)throw Error(`Bundled extension "${e.mount.namespace}" has no declaration module.`);return{diagnostics:n.diagnostics,mount:{externalDependencies:[],manifest:n.manifest,namespace:e.mount.namespace,packageName:e.mount.packageName,packageRoot:e.mount.packageRoot,programmaticDeclaration:{logicalPath:r.logicalPath,sourceId:`${e.mount.declaration.id}:${r.logicalPath}`},sourceRoot:e.mount.sourceRoot,specifier:e.mount.specifier}}}export{discoverBundledExtension};
@@ -1 +1 @@
1
- import{join,resolve}from"node:path";import{classifyAgentRootEntry,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{createDiskProjectSource}from"#discover/project-source.js";import{createAgentSourceManifest,createModuleSourceRef}from"#discover/manifest.js";import{DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,DISCOVER_EXTENSION_INSTRUMENTATION_UNSUPPORTED,DISCOVER_EXTENSION_MEMORY_UNSUPPORTED,DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,locateExtensionMount,mountNamespace}from"#discover/extensions.js";import{DISCOVER_CHANNELS_DIRECTORY_INVALID,DISCOVER_EXTENSIONS_DIRECTORY_INVALID,DISCOVER_HOOKS_DIRECTORY_INVALID,DISCOVER_TOOLS_DIRECTORY_INVALID,createChannelNameDiagnostic,createExtensionNameDiagnostic,createHookNameDiagnostic,createToolNameDiagnostic,createUnsupportedRootDirectoryDiagnostics,discoverFlatModuleSource,discoverInstructionsSource,discoverNamedSourceDirectory,readSortedDirectoryEntries}from"#discover/grammar.js";import{discoverConnectionSources}from"#discover/connections.js";import{discoverSubagents}from"#discover/discover-subagent.js";import{discoverLibSources}from"#discover/lib.js";import{discoverMemorySources}from"#discover/memory.js";import{discoverSandboxSource}from"#discover/sandbox.js";import{discoverScheduleSources}from"#discover/schedules.js";import{discoverSkills}from"#discover/skills.js";import{stripNpmPackageScope}from"#shared/package-name.js";async function discoverAgent(e){let t=e.source??createDiskProjectSource(),n=resolve(e.appRoot),r=resolve(e.agentRoot),i=e.role??`agent`,a=[],o=await tryReadPackageJsonName(t,n),s=await readSortedDirectoryEntries(t,r);a.push(...createUnsupportedRootDirectoryDiagnostics({classifyEntry:classifyAgentRootEntry,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:s,rootPath:r}));let c=await discoverInstructionsSource({rootEntries:s,rootPath:r,source:t,required:i!==`extension`});a.push(...c.diagnostics);let l=discoverFlatModuleSource({rootEntries:s,rootPath:r,slotName:`agent`});a.push(...l.diagnostics);let u=await discoverNamedSourceDirectory({directoryName:`channels`,invalidDirectoryCode:DISCOVER_CHANNELS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:createChannelNameDiagnostic});a.push(...u.diagnostics);let d=await discoverLibSources({agentRoot:r,rootEntries:s,source:t});a.push(...d.diagnostics);let f=await discoverScheduleSources({agentRoot:r,rootEntries:s,source:t});a.push(...f.diagnostics);let p=await discoverConnectionSources({rootEntries:s,rootPath:r,source:t});a.push(...p.diagnostics);let m=await discoverMemorySources({rootEntries:s,rootPath:r,source:t});a.push(...m.diagnostics);let h=await discoverSandboxSource({rootEntries:s,rootPath:r,source:t});if(a.push(...h.diagnostics),i===`extension`){l.module!==void 0&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,message:`An extension may not declare agent config (agent.ts) — model, limits, and sandbox are the consuming agent's to own.`,sourcePath:join(r,l.module.logicalPath)}));let e=s.find(e=>e.name===`instrumentation`&&e.isDirectory());e!==void 0&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_INSTRUMENTATION_UNSUPPORTED,message:`An extension may not declare instrumentation providers — process-wide observability belongs to the consuming agent.`,sourcePath:join(r,e.name)}));let[t]=m.memories;t!==void 0&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MEMORY_UNSUPPORTED,message:`An extension may not declare memory — scope and lifecycle state belong to the consuming application.`,sourcePath:join(r,t.logicalPath)})),h.sandbox!==null&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,message:`An extension may not declare a sandbox — it is the consuming agent's to own.`,sourcePath:join(r,h.sandbox.logicalPath)}))}let g=await discoverNamedSourceDirectory({directoryName:`tools`,invalidDirectoryCode:DISCOVER_TOOLS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:createToolNameDiagnostic});a.push(...g.diagnostics);let _=await discoverNamedSourceDirectory({directoryName:`hooks`,invalidDirectoryCode:DISCOVER_HOOKS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:createHookNameDiagnostic});a.push(..._.diagnostics);let v=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:s,rootPath:r,source:t,validateSegment:createExtensionNameDiagnostic});a.push(...v.diagnostics);let y=await discoverSkills({agentRoot:r,source:t});a.push(...y.diagnostics);let b=await discoverSubagents({agentRoot:r,appRoot:n,source:t});a.push(...b.diagnostics);let x=await collectExtensionMounts({agentRoot:r,fileMounts:v.sources,rootEntries:s,source:t});a.push(...x.diagnostics);let S=[];if(i!==`agent`)for(let e of x.mounts)a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,message:`"${e.mountRef.logicalPath}" mounts an extension from inside an extension, which is not supported yet. Extensions cannot mount other extensions; remove the "extensions/" slot.`,sourcePath:join(r,e.mountRef.logicalPath)}));else{let e=await resolveExtensionMounts({agentRoot:r,appRoot:n,mounts:x.mounts,source:t});a.push(...e.diagnostics),S=e.mounts}let C={agentRoot:r,appRoot:n,channels:u.sources,connections:p.connections,packageName:o,diagnostics:a,extensions:i===`extension`?[]:x.mounts.map(e=>e.mountRef),resolvedExtensions:S,hooks:_.sources,memories:i===`extension`?[]:m.memories,lib:d.lib,instructions:c.instructions,sandbox:i===`extension`?null:h.sandbox,sandboxWorkspaces:i===`extension`||h.sandboxWorkspace===null?[]:[h.sandboxWorkspace],schedules:f.schedules,skills:y.skills,tools:g.sources,subagents:b.subagents};return i!==`extension`&&l.module!==void 0&&(C.configModule=l.module),{diagnostics:a,manifest:createAgentSourceManifest(C)}}async function resolveExtensionMounts(e){let t=[],n=[];for(let r of e.mounts){let i=await locateExtensionMount({source:e.source,agentRoot:e.agentRoot,appRoot:e.appRoot,mount:r.mountRef,namespace:r.namespace});if(t.push(...i.diagnostics),i.location===void 0)continue;let a=await discoverAgent({agentRoot:i.location.sourceRoot,appRoot:i.location.packageRoot,source:e.source,role:`extension`});t.push(...a.diagnostics);let o;if(r.overridesRoot!==void 0){let n=await discoverAgent({agentRoot:r.overridesRoot,appRoot:e.appRoot,source:e.source,role:`extension`});t.push(...n.diagnostics),o=n.manifest}n.push({namespace:i.location.namespace,specifier:i.location.specifier,packageName:i.location.packageName,packageRoot:i.location.packageRoot,sourceRoot:i.location.sourceRoot,manifest:a.manifest,externalDependencies:i.location.externalDependencies,overrides:o})}return{diagnostics:t,mounts:n}}async function discoverExtensionMountDeclarations(e){let t=e.source??createDiskProjectSource(),n=resolve(e.agentRoot),r=await readSortedDirectoryEntries(t,n),i=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(n,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:r,rootPath:n,source:t,validateSegment:createExtensionNameDiagnostic}),a=await collectExtensionMounts({agentRoot:n,fileMounts:i.sources,rootEntries:r,source:t});return{diagnostics:[...i.diagnostics,...a.diagnostics],mounts:a.mounts}}async function collectExtensionMounts(e){let t=[],n=join(e.agentRoot,`extensions`),r=e.fileMounts.map(e=>({namespace:mountNamespace(e.logicalPath),mountRef:e})),i=new Set(r.map(e=>e.namespace)),a=e.rootEntries.find(e=>e.name===`extensions`),o=[],s=new Set;if(a?.isDirectory()===!0){let r=await readSortedDirectoryEntries(e.source,n);for(let a of r){if(!a.isDirectory())continue;let r=a.name,c=join(n,r),l=createExtensionNameDiagnostic(r,c);if(l!==null){t.push(l);continue}let u=discoverFlatModuleSource({rootEntries:await readSortedDirectoryEntries(e.source,c),rootPath:c,slotName:`extension`});if(t.push(...u.diagnostics),u.module===void 0){t.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,message:`Extension mount directory "extensions/${r}/" must declare its mount in "extension.ts" (or another supported module extension).`,sourcePath:c}));continue}i.has(r)&&s.add(r),o.push({namespace:r,mountRef:createModuleSourceRef({logicalPath:normalizeLogicalPath(join(`extensions`,r,u.module.logicalPath))}),overridesRoot:c})}}for(let e of s)t.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,message:`Extension namespace "${e}" is claimed by both a file mount ("extensions/${e}.ts") and a directory mount ("extensions/${e}/"). Keep only one.`,sourcePath:n}));return{diagnostics:t,mounts:[...r,...o].filter(e=>!s.has(e.namespace))}}async function tryReadPackageJsonName(e,t){try{let n=join(t,`package.json`),r=JSON.parse(await e.readTextFile(n)).name;return typeof r!=`string`||r.length===0?void 0:stripNpmPackageScope(r)}catch{return}}export{discoverAgent,discoverExtensionMountDeclarations,resolveExtensionMounts};
1
+ import{join,resolve}from"node:path";import{classifyAgentRootEntry,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,DISCOVER_EXTENSION_INSTRUMENTATION_UNSUPPORTED,DISCOVER_EXTENSION_MEMORY_UNSUPPORTED,DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,locateExtensionMount,mountNamespace}from"#discover/extensions.js";import{createDiskProjectSource}from"#discover/project-source.js";import{createAgentSourceManifest,createModuleSourceRef}from"#discover/manifest.js";import{DISCOVER_CHANNELS_DIRECTORY_INVALID,DISCOVER_EXTENSIONS_DIRECTORY_INVALID,DISCOVER_HOOKS_DIRECTORY_INVALID,DISCOVER_TOOLS_DIRECTORY_INVALID,createChannelNameDiagnostic,createExtensionNameDiagnostic,createHookNameDiagnostic,createToolNameDiagnostic,createUnsupportedRootDirectoryDiagnostics,discoverFlatModuleSource,discoverInstructionsSource,discoverNamedSourceDirectory,readSortedDirectoryEntries}from"#discover/grammar.js";import{discoverConnectionSources}from"#discover/connections.js";import{discoverSubagents}from"#discover/discover-subagent.js";import{discoverLibSources}from"#discover/lib.js";import{discoverMemorySources}from"#discover/memory.js";import{discoverSandboxSource}from"#discover/sandbox.js";import{discoverScheduleSources}from"#discover/schedules.js";import{discoverSkills}from"#discover/skills.js";import{stripNpmPackageScope}from"#shared/package-name.js";async function discoverAgent(e){let t=e.source??createDiskProjectSource(),n=resolve(e.appRoot),r=resolve(e.agentRoot),i=e.role??`agent`,a=[],o=await tryReadPackageJsonName(t,n),s=await readSortedDirectoryEntries(t,r);a.push(...createUnsupportedRootDirectoryDiagnostics({classifyEntry:classifyAgentRootEntry,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:s,rootPath:r}));let c=await discoverInstructionsSource({rootEntries:s,rootPath:r,source:t,required:i!==`extension`});a.push(...c.diagnostics);let l=discoverFlatModuleSource({rootEntries:s,rootPath:r,slotName:`agent`});a.push(...l.diagnostics);let u=await discoverNamedSourceDirectory({directoryName:`channels`,invalidDirectoryCode:DISCOVER_CHANNELS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:createChannelNameDiagnostic});a.push(...u.diagnostics);let d=await discoverLibSources({agentRoot:r,rootEntries:s,source:t});a.push(...d.diagnostics);let f=await discoverScheduleSources({agentRoot:r,rootEntries:s,source:t});a.push(...f.diagnostics);let p=await discoverConnectionSources({rootEntries:s,rootPath:r,source:t});a.push(...p.diagnostics);let m=await discoverMemorySources({rootEntries:s,rootPath:r,source:t});a.push(...m.diagnostics);let h=await discoverSandboxSource({rootEntries:s,rootPath:r,source:t});if(a.push(...h.diagnostics),i===`extension`){l.module!==void 0&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,message:`An extension may not declare agent config (agent.ts) — model, limits, and sandbox are the consuming agent's to own.`,sourcePath:join(r,l.module.logicalPath)}));let e=s.find(e=>e.name===`instrumentation`&&e.isDirectory());e!==void 0&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_INSTRUMENTATION_UNSUPPORTED,message:`An extension may not declare instrumentation providers — process-wide observability belongs to the consuming agent.`,sourcePath:join(r,e.name)}));let[t]=m.memories;t!==void 0&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MEMORY_UNSUPPORTED,message:`An extension may not declare memory — scope and lifecycle state belong to the consuming application.`,sourcePath:join(r,t.logicalPath)})),h.sandbox!==null&&a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,message:`An extension may not declare a sandbox — it is the consuming agent's to own.`,sourcePath:join(r,h.sandbox.logicalPath)}))}let g=await discoverNamedSourceDirectory({directoryName:`tools`,invalidDirectoryCode:DISCOVER_TOOLS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:createToolNameDiagnostic});a.push(...g.diagnostics);let _=await discoverNamedSourceDirectory({directoryName:`hooks`,invalidDirectoryCode:DISCOVER_HOOKS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:s,rootPath:r,source:t,validateSegment:createHookNameDiagnostic});a.push(..._.diagnostics);let v=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(r,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:s,rootPath:r,source:t,validateSegment:createExtensionNameDiagnostic});a.push(...v.diagnostics);let y=await discoverSkills({agentRoot:r,source:t});a.push(...y.diagnostics);let b=await discoverSubagents({agentRoot:r,appRoot:n,source:t});a.push(...b.diagnostics);let x=await collectExtensionMounts({agentRoot:r,fileMounts:v.sources,rootEntries:s,source:t});a.push(...x.diagnostics);let S=[];if(i!==`agent`)for(let e of x.mounts)a.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,message:`"${e.mountRef.logicalPath}" mounts an extension from inside an extension, which is not supported yet. Extensions cannot mount other extensions; remove the "extensions/" slot.`,sourcePath:join(r,e.mountRef.logicalPath)}));else{let e=await resolveExtensionMounts({agentRoot:r,appRoot:n,mounts:x.mounts,source:t});a.push(...e.diagnostics),S=e.mounts}let C={agentRoot:r,appRoot:n,channels:u.sources,connections:p.connections,packageName:o,diagnostics:a,extensions:i===`extension`?[]:x.mounts.map(e=>e.mountRef),resolvedExtensions:S,hooks:_.sources,memories:i===`extension`?[]:m.memories,lib:d.lib,instructions:c.instructions,sandbox:i===`extension`?null:h.sandbox,sandboxWorkspaces:i===`extension`||h.sandboxWorkspace===null?[]:[h.sandboxWorkspace],schedules:f.schedules,skills:y.skills,tools:g.sources,subagents:b.subagents};return i!==`extension`&&l.module!==void 0&&(C.configModule=l.module),{diagnostics:a,manifest:createAgentSourceManifest(C)}}async function resolveExtensionMounts(e){let t=[],n=[];for(let r of e.mounts){let i=await locateExtensionMount({source:e.source,agentRoot:e.agentRoot,appRoot:e.appRoot,mount:r.mountRef,namespace:r.namespace});if(t.push(...i.diagnostics),i.location===void 0)continue;let a=await discoverAgent({agentRoot:i.location.sourceRoot,appRoot:i.location.packageRoot,source:e.source,role:`extension`});t.push(...a.diagnostics);let o;if(r.overridesRoot!==void 0){let n=await discoverAgent({agentRoot:r.overridesRoot,appRoot:e.appRoot,source:e.source,role:`extension`});t.push(...n.diagnostics),o=n.manifest}n.push({namespace:i.location.namespace,specifier:i.location.specifier,packageName:i.location.packageName,packageRoot:i.location.packageRoot,sourceRoot:i.location.sourceRoot,manifest:a.manifest,externalDependencies:i.location.externalDependencies,overrides:o})}return{diagnostics:t,mounts:n}}async function discoverExtensionMountDeclarations(e){let t=e.source??createDiskProjectSource(),n=resolve(e.agentRoot),r=await readSortedDirectoryEntries(t,n),i=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(n,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:r,rootPath:n,source:t,validateSegment:createExtensionNameDiagnostic}),a=await collectExtensionMounts({agentRoot:n,fileMounts:i.sources,rootEntries:r,source:t});return{diagnostics:[...i.diagnostics,...a.diagnostics],mounts:a.mounts}}async function collectExtensionMounts(e){let t=[],n=join(e.agentRoot,`extensions`),r=e.fileMounts.map(e=>({namespace:mountNamespace(e.logicalPath),mountRef:e})),i=new Set(r.map(e=>e.namespace)),a=e.rootEntries.find(e=>e.name===`extensions`),o=[],s=new Set;if(a?.isDirectory()===!0){let r=await readSortedDirectoryEntries(e.source,n);for(let a of r){if(!a.isDirectory())continue;let r=a.name,c=join(n,r),l=createExtensionNameDiagnostic(r,c);if(l!==null){t.push(l);continue}let u=discoverFlatModuleSource({rootEntries:await readSortedDirectoryEntries(e.source,c),rootPath:c,slotName:`extension`});if(t.push(...u.diagnostics),u.module===void 0){t.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,message:`Extension mount directory "extensions/${r}/" must declare its mount in "extension.ts" (or another supported module extension).`,sourcePath:c}));continue}i.has(r)&&s.add(r),o.push({namespace:r,mountRef:createModuleSourceRef({logicalPath:normalizeLogicalPath(join(`extensions`,r,u.module.logicalPath))}),overridesRoot:c})}}for(let e of s)t.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,message:`Extension namespace "${e}" is claimed by both a file mount ("extensions/${e}.ts") and a directory mount ("extensions/${e}/"). Keep only one.`,sourcePath:n}));return{diagnostics:t,mounts:[...r,...o].filter(e=>!s.has(e.namespace))}}async function tryReadPackageJsonName(e,t){try{let n=join(t,`package.json`),r=JSON.parse(await e.readTextFile(n)).name;return typeof r!=`string`||r.length===0?void 0:stripNpmPackageScope(r)}catch{return}}export{discoverAgent,discoverExtensionMountDeclarations,resolveExtensionMounts};
@@ -121,6 +121,11 @@ export type ExtensionSourceRef = ModuleSourceRef;
121
121
  * consuming agent, prefixing contributions with {@link namespace}.
122
122
  */
123
123
  export interface ResolvedExtensionMount {
124
+ /** Programmatic declaration used when the mount does not exist on disk. */
125
+ readonly programmaticDeclaration?: {
126
+ readonly logicalPath: string;
127
+ readonly sourceId: string;
128
+ };
124
129
  /** Mount namespace derived from the mount filename (e.g. `crm`). */
125
130
  readonly namespace: string;
126
131
  /** Package specifier the mount imports (e.g. `@acme/crm`). */
@@ -1 +1 @@
1
- import{toErrorMessage}from"#shared/errors.js";import{formatAssertionName}from"#evals/diagnostics.js";var AssertionCollector=class{#e=[];#t=[];get hasEntries(){return this.#e.length>0}recordScoped(e,t,n=`gate`){let r={baseName:e.name,name:e.name,severity:n,threshold:void 0,kind:`deferred`,spec:e,selectSubject:t,score:0,failed:!1};return this.#e.push(r),makeHandle(r)}recordValue(e){let t={baseName:e.name,name:e.name,severity:e.severity,threshold:e.threshold,kind:`resolved`,score:0,failed:!1};this.#e.push(t);let n=settleEntry(t,e.score);return this.#t.push(n),makeHandle(t)}recordOutcome(e){let t={baseName:e.name,name:e.name,severity:`gate`,threshold:void 0,kind:`resolved`,score:e.outcome.score,message:e.outcome.message,metadata:e.outcome.metadata,failed:!1};return this.#e.push(t),computePassed(t.severity,t.threshold,t.score,t.failed)}async recordRequirement(e){let t={baseName:e.name,name:e.name,severity:`gate`,threshold:e.threshold,kind:`resolved`,score:0,failed:!1};return this.#e.push(t),await settleEntry(t,e.score),computePassed(t.severity,t.threshold,t.score,t.failed)}async finalize(e){await Promise.all(this.#t);let t=[];for(let n of this.#e){if(n.kind===`deferred`&&n.spec!==void 0){let t=await n.spec.evaluate(n.selectSubject?.(e)??e);n.score=t.score,n.message=t.message,n.metadata=t.metadata}t.push({name:n.name,score:n.score,severity:n.severity,threshold:n.threshold,passed:computePassed(n.severity,n.threshold,n.score,n.failed),message:n.message,metadata:n.metadata})}return t}};function computePassed(e,t,n,r){if(r)return!1;let i=t??(e===`gate`?1:void 0);return i===void 0||n>=i}async function settleEntry(e,t){try{let n=await t();e.score=n.score,e.message=n.message,e.metadata=n.metadata}catch(t){e.score=0,e.severity=`gate`,e.threshold=void 0,e.message=toErrorMessage(t),e.failed=!0}}function makeHandle(e){let t={gate(n){return e.severity=`gate`,e.threshold=n,t},soft(n){return e.severity=`soft`,e.threshold=n,t},atLeast(n){return e.severity=`soft`,e.threshold=n,t},label(n){return e.name=formatAssertionName(e.baseName,n),t}};return t}export{AssertionCollector};
1
+ import{toErrorMessage}from"#shared/errors.js";import{formatAssertionName}from"#evals/diagnostics.js";var AssertionCollector=class{#e=[];#t=[];get hasEntries(){return this.#e.length>0}recordScoped(e,t,n=`gate`){let r={baseName:e.name,name:e.name,severity:n,threshold:void 0,kind:`deferred`,spec:e,selectSubject:t,score:0,errored:!1};return this.#e.push(r),makeHandle(r)}recordValue(e){let t={baseName:e.name,name:e.name,severity:e.severity,threshold:e.threshold,kind:`resolved`,score:0,errored:!1};this.#e.push(t);let n=settleEntry(t,e.score);return this.#t.push(n),makeHandle(t)}recordOutcome(e){let t={baseName:e.name,name:e.name,severity:`gate`,threshold:void 0,kind:`resolved`,score:e.outcome.score,message:e.outcome.message,metadata:e.outcome.metadata,errored:!1};return this.#e.push(t),computePassed(t.severity,t.threshold,t.score,t.errored)}async recordRequirement(e){let t={baseName:e.name,name:e.name,severity:`gate`,threshold:e.threshold,kind:`resolved`,score:0,errored:!1};return this.#e.push(t),await settleEntry(t,e.score),computePassed(t.severity,t.threshold,t.score,t.errored)}async finalize(e){await Promise.all(this.#t);let t=[];for(let n of this.#e){if(n.kind===`deferred`&&n.spec!==void 0){let t=await n.spec.evaluate(n.selectSubject?.(e)??e);n.score=t.score,n.message=t.message,n.metadata=t.metadata}t.push({name:n.name,score:n.score,severity:n.severity,threshold:n.threshold,passed:computePassed(n.severity,n.threshold,n.score,n.errored),errored:n.errored,message:n.message,metadata:n.metadata})}return t}};function computePassed(e,t,n,r){if(r)return!1;let i=t??(e===`gate`?1:void 0);return i===void 0||n>=i}async function settleEntry(e,t){try{let n=await t();e.score=n.score,e.message=n.message,e.metadata=n.metadata}catch(t){e.score=0,e.severity=`gate`,e.threshold=void 0,e.message=toErrorMessage(t),e.errored=!0}}function makeHandle(e){let t={gate(n){return e.severity=`gate`,e.threshold=n,t},soft(n){return e.severity=`soft`,e.threshold=n,t},atLeast(n){return e.severity=`soft`,e.threshold=n,t},label(n){return e.name=formatAssertionName(e.baseName,n),t}};return t}export{AssertionCollector};
@@ -1,4 +1,4 @@
1
- import{randomUUID}from"node:crypto";import{readFile}from"node:fs/promises";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{basename,join}from"node:path";import{EVE_EVALUATION_ENV_FLAG,EVE_EVALUATION_RUN_ID_ENV}from"#internal/application/dev-environment.js";import{shutdownActiveSandboxHandles}from"#execution/sandbox/active-handles.js";import{createDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{filterEvalsByTags}from"#evals/cli/filter.js";import{discoverAndImportEvals,discoverEvalConfig,findMisplacedEvalDirs}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{Console}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n,r=process.cwd()){await loadDevelopmentEnvironmentFiles(r);let i=e.length>0?e:void 0,a=await discoverAndImportEvals(r,i);if(a.length===0){let e=await findMisplacedEvalDirs(r);e.length>0?n.error(`No evals found under evals/, but eval files are present inside agent/:
1
+ import{randomUUID}from"node:crypto";import{readFile}from"node:fs/promises";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{basename,join}from"node:path";import{noDevelopmentExtensions}from"#compiler/development-extensions.js";import{EVE_EVALUATION_ENV_FLAG,EVE_EVALUATION_RUN_ID_ENV}from"#internal/application/dev-environment.js";import{shutdownActiveSandboxHandles}from"#execution/sandbox/active-handles.js";import{createDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{filterEvalsByTags}from"#evals/cli/filter.js";import{discoverAndImportEvals,discoverEvalConfig,findMisplacedEvalDirs}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{Console}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n,r=process.cwd()){await loadDevelopmentEnvironmentFiles(r);let i=e.length>0?e:void 0,a=await discoverAndImportEvals(r,i);if(a.length===0){let e=await findMisplacedEvalDirs(r);e.length>0?n.error(`No evals found under evals/, but eval files are present inside agent/:
2
2
  `+e.map(e=>` - ${e}`).join(`
3
3
  `)+`
4
- eve eval only scans the top-level evals/ directory (a sibling of agent/). Move these files there.`):i?n.error(`No evals found matching: ${i.join(`, `)}`):n.error(`No evals found. Create files under evals/ with the *.eval.ts extension.`),process.exitCode=2;return}let o=t.tag??[],s=t.excludeTag??[],c=filterEvalsByTags({evaluations:a,includeTags:o,excludeTags:[]});if(c.length===0){n.error(`No evals matched the provided tags (${o.join(`, `)}).`),process.exitCode=2;return}let l=filterEvalsByTags({evaluations:c,includeTags:[],excludeTags:s});if(t.list===!0){printEvalList(l,t.json===!0,n);return}if(l.length===0){n.log(`All ${c.length} matching evals are excluded by tags (${s.join(`, `)}); nothing to run.`);return}let u,d;try{u=parsePositiveInteger(t.maxConcurrency,`--max-concurrency`),d=parseNonNegativeInteger(t.timeout,`--timeout`)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let f;try{f=await discoverEvalConfig(r)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let p,m,h,g;try{if(g=await f.setup?.(),t.url)h=await createEvalClient({kind:`remote`,url:t.url},{workspaceRoot:r}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(r),kind:`remote`,url:t.url});else{process.env[EVE_EVALUATION_ENV_FLAG]=`1`,process.env[EVE_EVALUATION_RUN_ID_ENV]=randomUUID(),p=createDevelopmentServer(r,{host:`127.0.0.1`,port:0});let e=await p.start();h=await createEvalClient({kind:`local`,url:e.url}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(r),kind:`local`,url:e.url})}let e=t.json===!0?[]:[Console()];t.junit!==void 0&&e.push(JUnit({filePath:t.junit}));let i=await runEvals({evaluations:l,config:f,setupContext:g,target:m,client:h,appRoot:r,reporters:e,includeEvalReporters:t.skipReport!==!0,maxConcurrency:u,timeoutMs:d,onEvalLog:t.verbose===!0?(e,t)=>n.log(`[${e}] ${t}`):void 0});t.json&&n.log(JSON.stringify(i,null,2));let a=i.failed>0,o=t.strict===!0&&i.scored>0;(a||o)&&(process.exitCode=1)}finally{for(let e of[()=>p?.close(),()=>p&&shutdownActiveSandboxHandles({log:e=>n.error(e)}),()=>f.teardown?.(g)])try{await e()}catch(e){n.error(`Eval cleanup failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}let _=typeof process.exitCode==`number`?process.exitCode:0;await flushStandardStreams(),process.exit(_)}async function flushStandardStreams(){await Promise.all([flushStream(process.stdout),flushStream(process.stderr)])}async function flushStream(e){await new Promise(t=>{let n=!1,settle=()=>{n||(n=!0,setImmediate(()=>{e.off(`error`,settle),t()}))};e.once(`error`,settle);try{e.write(``,settle)}catch{settle()}})}function parsePositiveInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<1)throw Error(`${t} must be a positive integer; got "${e}".`);return n}function parseNonNegativeInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw Error(`${t} must be a non-negative integer; got "${e}".`);return n}function printEvalList(e,t,n){if(t){let t=e.map(e=>({id:e.id,description:e.description,tags:e.tags}));n.log(JSON.stringify(t,null,2));return}for(let t of e){let e=t.description===void 0?``:` — ${t.description}`,r=t.tags!==void 0&&t.tags.length>0?` [${t.tags.join(`, `)}]`:``;n.log(`${t.id}${r}${e}`)}}async function readExpectedAgentName(e){try{let t=JSON.parse(await readFile(join(e,`package.json`),`utf8`));return typeof t.name==`string`&&t.name.length>0?t.name:basename(e)}catch{return basename(e)}}export{runEvalCommand};
4
+ eve eval only scans the top-level evals/ directory (a sibling of agent/). Move these files there.`):i?n.error(`No evals found matching: ${i.join(`, `)}`):n.error(`No evals found. Create files under evals/ with the *.eval.ts extension.`),process.exitCode=2;return}let o=t.tag??[],s=t.excludeTag??[],c=filterEvalsByTags({evaluations:a,includeTags:o,excludeTags:[]});if(c.length===0){n.error(`No evals matched the provided tags (${o.join(`, `)}).`),process.exitCode=2;return}let l=filterEvalsByTags({evaluations:c,includeTags:[],excludeTags:s});if(t.list===!0){printEvalList(l,t.json===!0,n);return}if(l.length===0){n.log(`All ${c.length} matching evals are excluded by tags (${s.join(`, `)}); nothing to run.`);return}let u,d;try{u=parsePositiveInteger(t.maxConcurrency,`--max-concurrency`),d=parseNonNegativeInteger(t.timeout,`--timeout`)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let f;try{f=await discoverEvalConfig(r)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let p,m,h,g;try{if(g=await f.setup?.(),t.url)h=await createEvalClient({kind:`remote`,url:t.url},{workspaceRoot:r}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(r),kind:`remote`,url:t.url});else{process.env[EVE_EVALUATION_ENV_FLAG]=`1`,process.env[EVE_EVALUATION_RUN_ID_ENV]=randomUUID(),p=createDevelopmentServer(r,{developmentExtensions:noDevelopmentExtensions(),host:`127.0.0.1`,port:0});let e=await p.start();h=await createEvalClient({kind:`local`,url:e.url}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(r),kind:`local`,url:e.url})}let e=t.json===!0?[]:[Console()];t.junit!==void 0&&e.push(JUnit({filePath:t.junit}));let i=await runEvals({evaluations:l,config:f,setupContext:g,target:m,client:h,appRoot:r,reporters:e,includeEvalReporters:t.skipReport!==!0,maxConcurrency:u,timeoutMs:d,onEvalLog:t.verbose===!0?(e,t)=>n.log(`[${e}] ${t}`):void 0});t.json&&n.log(JSON.stringify(i,null,2));let a=i.failed>0,o=t.strict===!0&&i.scored>0;(a||o)&&(process.exitCode=1)}finally{for(let e of[()=>p?.close(),()=>p&&shutdownActiveSandboxHandles({log:e=>n.error(e)}),()=>f.teardown?.(g)])try{await e()}catch(e){n.error(`Eval cleanup failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}let _=typeof process.exitCode==`number`?process.exitCode:0;await flushStandardStreams(),process.exit(_)}async function flushStandardStreams(){await Promise.all([flushStream(process.stdout),flushStream(process.stderr)])}async function flushStream(e){await new Promise(t=>{let n=!1,settle=()=>{n||(n=!0,setImmediate(()=>{e.off(`error`,settle),t()}))};e.once(`error`,settle);try{e.write(``,settle)}catch{settle()}})}function parsePositiveInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<1)throw Error(`${t} must be a positive integer; got "${e}".`);return n}function parseNonNegativeInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw Error(`${t} must be a non-negative integer; got "${e}".`);return n}function printEvalList(e,t,n){if(t){let t=e.map(e=>({id:e.id,description:e.description,tags:e.tags}));n.log(JSON.stringify(t,null,2));return}for(let t of e){let e=t.description===void 0?``:` — ${t.description}`,r=t.tags!==void 0&&t.tags.length>0?` [${t.tags.join(`, `)}]`:``;n.log(`${t.id}${r}${e}`)}}async function readExpectedAgentName(e){try{let t=JSON.parse(await readFile(join(e,`package.json`),`utf8`));return typeof t.name==`string`&&t.name.length>0?t.name:basename(e)}catch{return basename(e)}}export{runEvalCommand};
@@ -1,3 +1,3 @@
1
1
  import{mkdir,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";function resolveArtifactDirectory(e){let t=new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19);return join(e,`.eve`,`evals`,t)}async function writeArtifacts(e,t){let n=join(e,`evals`);await mkdir(n,{recursive:!0}),await writeFile(join(e,`summary.json`),JSON.stringify(buildSummaryArtifact(t),null,2));let r=t.results.map(e=>JSON.stringify(buildResultLine(e))).join(`
2
2
  `);await writeFile(join(e,`results.jsonl`),`${r}\n`),await Promise.all(t.results.map(async e=>{let t=join(n,`${sanitizeArtifactPath(e.id)}.json`);await mkdir(dirname(t),{recursive:!0}),await writeFile(t,JSON.stringify(buildEvalArtifact(e),null,2));let r=e.result.events.map(e=>JSON.stringify(e)).join(`
3
- `);await writeFile(join(n,`${sanitizeArtifactPath(e.id)}.events.ndjson`),`${r}\n`)}))}function buildSummaryArtifact(e){return{target:e.target,startedAt:e.startedAt,completedAt:e.completedAt,passed:e.passed,failed:e.failed,scored:e.scored,skipped:e.skipped,errored:e.errored,totalEvals:e.results.length,evals:e.results.map(e=>({id:e.id,verdict:e.verdict,status:e.result.status,assertions:e.assertions.map(e=>({name:e.name,score:e.score,severity:e.severity,threshold:e.threshold,passed:e.passed,message:e.message,metadata:e.metadata})),error:e.error,skipReason:e.skipReason,traceContexts:e.result.traceContexts}))}}function buildResultLine(e){return{id:e.id,verdict:e.verdict,status:e.result.status,output:e.result.output,assertions:e.assertions,error:e.error,skipReason:e.skipReason,traceContexts:e.result.traceContexts}}function buildEvalArtifact(e){return{id:e.id,result:{output:e.result.output,finalMessage:e.result.finalMessage,sessionId:e.result.sessionId,status:e.result.status,logs:e.result.logs,derived:e.result.derived,runtimeIdentity:e.result.runtimeIdentity,sessions:e.result.sessions,traceContexts:e.result.traceContexts},verdict:e.verdict,assertions:e.assertions,error:e.error,skipReason:e.skipReason}}function sanitizeArtifactPath(e){return e.split(`/`).map(e=>e.replace(/[^a-zA-Z0-9_-]/g,`_`)).join(`/`)}export{resolveArtifactDirectory,writeArtifacts};
3
+ `);await writeFile(join(n,`${sanitizeArtifactPath(e.id)}.events.ndjson`),`${r}\n`)}))}function buildSummaryArtifact(e){return{target:e.target,startedAt:e.startedAt,completedAt:e.completedAt,passed:e.passed,failed:e.failed,scored:e.scored,skipped:e.skipped,errored:e.errored,totalEvals:e.results.length,evals:e.results.map(e=>({id:e.id,verdict:e.verdict,status:e.result.status,assertions:e.assertions.map(e=>({name:e.name,score:e.score,severity:e.severity,threshold:e.threshold,passed:e.passed,errored:e.errored,message:e.message,metadata:e.metadata})),error:e.error,skipReason:e.skipReason,traceContexts:e.result.traceContexts}))}}function buildResultLine(e){return{id:e.id,verdict:e.verdict,status:e.result.status,output:e.result.output,assertions:e.assertions,error:e.error,skipReason:e.skipReason,traceContexts:e.result.traceContexts}}function buildEvalArtifact(e){return{id:e.id,result:{output:e.result.output,finalMessage:e.result.finalMessage,sessionId:e.result.sessionId,status:e.result.status,logs:e.result.logs,derived:e.result.derived,runtimeIdentity:e.result.runtimeIdentity,sessions:e.result.sessions,traceContexts:e.result.traceContexts},verdict:e.verdict,assertions:e.assertions,error:e.error,skipReason:e.skipReason}}function sanitizeArtifactPath(e){return e.split(`/`).map(e=>e.replace(/[^a-zA-Z0-9_-]/g,`_`)).join(`/`)}export{resolveArtifactDirectory,writeArtifacts};
@@ -180,6 +180,8 @@ export interface AssertionResult {
180
180
  readonly severity: AssertionSeverity;
181
181
  readonly threshold?: number;
182
182
  readonly passed: boolean;
183
+ /** Whether the assertion failed because its scorer threw instead of producing a score. */
184
+ readonly errored: boolean;
183
185
  /** Human-readable failure detail, shown in console output and artifacts. */
184
186
  readonly message?: string;
185
187
  readonly metadata?: Readonly<Record<string, unknown>>;
@@ -1 +1 @@
1
- import{createDurableSessionState}from"#execution/durable-session-store.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";async function dispatchCoordinationStep(e){"use step";let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],sessionState:e.sessionState};let{batch:n,session:r}=t,i=r,a=[];for(let r of t.plan){if(r.kind===`workflow-task`){let o=await startWorkflowTask({agents:t.workflowAgents,auth:t.auth,batchEvent:n.event,initiatorAuth:t.initiatorAuth,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r.task});i=o.session,o.result!==void 0&&a.push(o.result);continue}if(r.kind===`task-control`){let e=await executeTaskControlAction({action:r.action,cancelOwnedWork:cancelBackgroundAgentTask,serializedContext:t.serializedContext,session:i});i=e.session,a.push(e.result)}}return{results:a,sessionState:i===r?t.sessionState:createDurableSessionState({session:i})}}export{dispatchCoordinationStep};
1
+ import{createDurableSessionState}from"#execution/durable-session-store.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";import{prepareCoordinationDispatch}from"#execution/coordination-dispatch-shared.js";import{startWorkflowTask}from"#execution/tools/workflow/start.js";async function dispatchCoordinationStep(e){"use step";let t=await prepareCoordinationDispatch({serializedContext:e.serializedContext,sessionState:e.sessionState});if(t===void 0)return{results:[],sessionState:e.sessionState};let{batch:n,session:r}=t,i=r,a=[];for(let r of t.plan){if(r.kind===`workflow-task`){let o=await startWorkflowTask({agents:t.workflowAgents,auth:t.auth,batchEvent:n.event,canRequestInput:t.capabilities?.requestInput===!0,initiatorAuth:t.initiatorAuth,owner:e.workflowToolRunOwner,parentSession:t.parentSession,session:i,task:r.task});i=o.session,o.result!==void 0&&a.push(o.result);continue}if(r.kind===`task-control`){let e=await executeTaskControlAction({action:r.action,cancelOwnedWork:cancelBackgroundAgentTask,serializedContext:t.serializedContext,session:i});i=e.session,a.push(e.result)}}return{results:a,sessionState:i===r?t.sessionState:createDurableSessionState({session:i})}}export{dispatchCoordinationStep};
@@ -1 +1 @@
1
- import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.64.1//executeWorkflowProgram`;export{executeWorkflowProgram};
1
+ import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.65.0//executeWorkflowProgram`;export{executeWorkflowProgram};
@@ -25,10 +25,8 @@ export interface CreateExecutionNodeStepInput {
25
25
  /** Cancellation signal forwarded to the tool-loop harness. */
26
26
  readonly abortSignal?: AbortSignal;
27
27
  /**
28
- * Session-level capabilities propagated from the runtime. The
29
- * harness passes this through to `buildToolSet` so `ask_question`
30
- * registration and any other capability-gated behavior tracks the
31
- * current run.
28
+ * Session-level capabilities propagated from the runtime, so
29
+ * capability-gated behavior tracks the current run.
32
30
  */
33
31
  readonly capabilities?: SessionCapabilities;
34
32
  /** Runs only a context clear and returns to the parked session. */
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#tools/schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition}from"#execution/tools/workflow/background.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{preparePersistedStepDynamicToolMetadata}from"#context/dynamic-tool-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{createTaskToolHarnessDefinitions}from"#execution/tools/tasks.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";import{ASK_QUESTION_TOOL_NAME}from"#harness/request-input-tool.js";import{WEB_SEARCH_TOOL_NAME,resolveWebSearchActivityLabel}from"#harness/provider-tool-schemas.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel,e.abortSignal),r=createNodeHarnessTools({node:e.node}),i=e.instrumentation,a=i?.prepareExecution(),o=createToolLoopHarness({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,handleEvent:e.handleEvent,historyProjector:e.historyProjector,historyView:e.historyView,instrumentation:a,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,resolveStepDynamicTools:t=>preparePersistedStepDynamicToolMetadata({...t,resolvers:e.node.agent.dynamicToolResolvers??[]}),dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?o:async(e,t)=>{try{return await o(e,t)}finally{await i.flush()}}}function buildRuntimeIdentity(e){let t=resolveInstalledPackageInfo(),n={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:t.version},r=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),i=process.env.VERCEL_GIT_COMMIT_REF?.trim(),a=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return r||i||a?{...n,build:{deployedAt:a||void 0,gitBranch:i||void 0,gitSha:r||void 0}}:n}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t,n){return r=>dispatchDynamicModelEvent({abortSignal:n,ctx:r.ctx,dynamicModel:t,event:r.event,messages:r.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return t}function resolveHarnessToolDefinition(e){let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);return isPreparedRuntimeWorkflowTool(e.tool)?t===null?createPreparedWorkflowToolHarnessDefinition(e.tool):createWorkflowToolHarnessDefinition({executeInput:t.definition.executeInput,definition:createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly}),nodeId:e.tool.task.nodeId,workflowId:e.tool.task.workflowId}):t===null?(log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null):createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly})}function isPreparedRuntimeWorkflowTool(e){return e.task!==void 0}function createRegisteredHarnessToolDefinition(e){let t=e.definition;if(t.owner.kind===`framework`){let n=createTaskToolHarnessDefinitions().find(e=>e.name===t.name);if(n!==void 0)return{...n,behavior:e.behavior}}let n=t.execute,r=t.owner.kind===`framework`&&t.name===ASK_QUESTION_TOOL_NAME;return{availableInSubagents:t.availableInSubagents,label:t.label??(t.owner.kind===`framework`&&t.name===WEB_SEARCH_TOOL_NAME?{start:resolveWebSearchActivityLabel}:void 0),approvalKey:t.approvalKey,behavior:e.behavior,description:t.description,execution:t.execution,executeInput:t.executeInput,execute:r?void 0:resolveAuthoredExecute({rawExecute:n,scope:t.name}),frameworkAction:t.owner.kind===`framework`&&t.name===LOAD_SKILL_TOOL_NAME?`load-skill`:void 0,inputSchema:t.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:t.name,approval:t.approval,outputSchema:t.outputSchema,rootOnly:e.rootOnly,toModelOutput:t.toModelOutput}}function resolveAuthoredExecute(e){let{rawExecute:t,scope:n}=e;return t===void 0?void 0:createToolExecuteWithAuth({execute:t,scope:n})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
1
+ import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#tools/schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createPreparedWorkflowToolHarnessDefinition,createWorkflowToolHarnessDefinition}from"#execution/tools/workflow/background.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{preparePersistedStepDynamicToolMetadata}from"#context/dynamic-tool-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{createTaskToolHarnessDefinitions}from"#execution/tools/tasks.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{WEB_SEARCH_TOOL_NAME,resolveWebSearchActivityLabel}from"#harness/provider-tool-schemas.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel,e.abortSignal),r=createNodeHarnessTools({node:e.node}),i=e.instrumentation,a=i?.prepareExecution(),o=createToolLoopHarness({steeringSignal:e.steeringSignal,abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,handleEvent:e.handleEvent,historyProjector:e.historyProjector,historyView:e.historyView,instrumentation:a,mode:e.mode,resolveStepDynamicTools:t=>preparePersistedStepDynamicToolMetadata({...t,resolvers:e.node.agent.dynamicToolResolvers??[]}),dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?o:async(e,t)=>{try{return await o(e,t)}finally{await i.flush()}}}function buildRuntimeIdentity(e){let t=resolveInstalledPackageInfo(),n={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:t.version},r=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),i=process.env.VERCEL_GIT_COMMIT_REF?.trim(),a=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return r||i||a?{...n,build:{deployedAt:a||void 0,gitBranch:i||void 0,gitSha:r||void 0}}:n}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t,n){return r=>dispatchDynamicModelEvent({abortSignal:n,ctx:r.ctx,dynamicModel:t,event:r.event,messages:r.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return t}function resolveHarnessToolDefinition(e){let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);return isPreparedRuntimeWorkflowTool(e.tool)?t===null?createPreparedWorkflowToolHarnessDefinition(e.tool):createWorkflowToolHarnessDefinition({executeInput:t.definition.executeInput,definition:createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly}),nodeId:e.tool.task.nodeId,workflowId:e.tool.task.workflowId}):t===null?(log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null):createRegisteredHarnessToolDefinition({behavior:e.tool.behavior,definition:t.definition,rootOnly:e.tool.rootOnly})}function isPreparedRuntimeWorkflowTool(e){return e.task!==void 0}function createRegisteredHarnessToolDefinition(e){let t=e.definition;if(t.owner.kind===`framework`){let n=createTaskToolHarnessDefinitions().find(e=>e.name===t.name);if(n!==void 0)return{...n,behavior:e.behavior}}let n=t.execute;return{availableInSubagents:t.availableInSubagents,label:t.label??(t.owner.kind===`framework`&&t.name===WEB_SEARCH_TOOL_NAME?{start:resolveWebSearchActivityLabel}:void 0),approvalKey:t.approvalKey,behavior:e.behavior,description:t.description,execution:t.execution,executeInput:t.executeInput,execute:resolveAuthoredExecute({rawExecute:n,scope:t.name}),frameworkAction:t.owner.kind===`framework`&&t.name===LOAD_SKILL_TOOL_NAME?`load-skill`:void 0,inputSchema:t.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:t.name,approval:t.approval,outputSchema:t.outputSchema,rootOnly:e.rootOnly,toModelOutput:t.toModelOutput}}function resolveAuthoredExecute(e){let{rawExecute:t,scope:n}=e;return t===void 0?void 0:createToolExecuteWithAuth({execute:t,scope:n})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
@@ -1 +1 @@
1
- import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{findBackgroundWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{createTaskInputRequestId,retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeDeliverPayload}from"#subagents/hitl-proxy.js";import{sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{resumeWorkflowToolRunAnswers}from"#execution/tools/workflow/answer.js";async function routeProxiedDeliverStep(e){"use step";let t=readDurableSession(e.sessionState),n=e.delivery,r=new Map,i=new Map,a;for(let[e,o]of n.payloads.entries()){let s=routeDeliverPayload({allowRoute:(e,n)=>n.taskId===void 0||findBackgroundWorkflowToolRun(t.state,n.taskId)!==void 0,payload:o,state:t.state});a??=s.parentAction,s.forSelf!==void 0&&r.set(e,s.forSelf);for(let[t,r]of s.forChildren.entries()){let a=[r.childContinuationToken,r.childSessionInbox?.sessionId??``,r.childResponseUrl??``,r.taskId??``].join(`\0`),o=i.get(a)??{answerHook:r.answerHook,childContinuationToken:r.childContinuationToken,childSessionInbox:r.childSessionInbox,childResponseUrl:r.childResponseUrl,metadata:[],payloads:[],retireRequestIds:[],sourcePayloadIndexes:[],taskId:r.taskId},c=o.payloads.length;if(o.payloads.push(r.payload),o.retireRequestIds.push(...r.retireRequestIds),o.sourcePayloadIndexes.push(e),s.forSelf===void 0&&t===0)for(let t of n.deliveryMetadata??[])t.payloadIndex===e&&o.metadata.push({...t,payloadIndex:c});i.set(a,o)}}let o=!1;for(let e of i.values()){let i=e.taskId;if(i!==void 0){let a=findBackgroundWorkflowToolRun(t.state,i);if(a===void 0){mergeStrandedResponses(r,e,i);continue}if(await sendTaskInboundPayload({taskInboxToken:a.address.hookToken,payload:{auth:n.auth,childContinuationToken:e.childContinuationToken,childSessionInbox:e.childSessionInbox,childResponseUrl:e.childResponseUrl,inputResponses:coalesceDeliverPayloads(e.payloads).inputResponses??[],kind:`input-response`,taskId:i}})===`unreachable`){mergeStrandedResponses(r,e,i);continue}t=retireProxyInputRequests(t,e.retireRequestIds),o=!0;continue}if(e.answerHook!==void 0){await resumeWorkflowToolRunAnswers(e.childContinuationToken,coalesceDeliverPayloads(e.payloads).inputResponses),t=retireProxyInputRequests(t,e.retireRequestIds),o=!0;continue}let a={...n,deliveryMetadata:e.metadata.length===0?void 0:e.metadata,payloads:e.payloads};await resumeSessionInbox(e.childSessionInbox??e.childContinuationToken,a),t=retireProxyInputRequests(t,e.retireRequestIds),o=!0}let s={serializedContext:e.serializedContext??{},sessionState:o?replaceDurableSessionSnapshot({session:t,state:e.sessionState}):e.sessionState};if(a!==void 0)return{...s,...a};let c=[...r].sort(([e],[t])=>e-t),l=c.flatMap(([e],t)=>(n.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:t}))),u=c.length===0?void 0:{...n,deliveryMetadata:l.length===0?void 0:l,payloads:c.map(([,e])=>e)};return{...s,kind:`continue`,remainder:u}}function mergeStrandedResponses(e,t,n){for(let[r,i]of t.payloads.entries()){let a=t.sourcePayloadIndexes[r];if(a===void 0)continue;let o=(i.inputResponses??[]).map(e=>({...e,requestId:createTaskInputRequestId(n,e.requestId)}));if(o.length===0)continue;let s=e.get(a);e.set(a,{...s,inputResponses:[...s?.inputResponses??[],...o]})}}export{routeProxiedDeliverStep};
1
+ import{createInputResolvedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{getPendingCoordinationBatch}from"#harness/coordination.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{findBackgroundWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{createTaskInputRequestId,retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeDeliverPayload}from"#subagents/hitl-proxy.js";import{sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{resumeWorkflowToolRunAnswers,resumeWorkflowToolRunDismissal}from"#execution/tools/workflow/answer.js";async function routeProxiedDeliverStep(e){"use step";let t=readDurableSession(e.sessionState),n=e.delivery,r=new Map,i=new Map,a,o=n.caller===void 0&&n.taskDeliveryId===void 0,s=new Set;for(let[e,c]of n.payloads.entries()){let l=routeDeliverPayload({allowRoute:(e,n)=>!s.has(e)&&(n.taskId===void 0||findBackgroundWorkflowToolRun(t.state,n.taskId)!==void 0),payload:c,resolveMessage:o,state:t.state});a??=l.parentAction,l.forSelf!==void 0&&r.set(e,l.forSelf);for(let[t,r]of l.forChildren.entries()){if(r.answerHook!==void 0)for(let e of r.retireRequestIds)s.add(e);let a=[r.childContinuationToken,r.childSessionInbox?.sessionId??``,r.childResponseUrl??``,r.taskId??``].join(`\0`),o=i.get(a)??{answerHook:r.answerHook,childContinuationToken:r.childContinuationToken,childSessionInbox:r.childSessionInbox,childResponseUrl:r.childResponseUrl,dismissedRequestIds:[],metadata:[],payloads:[],retireRequestIds:[],sourcePayloadIndexes:[],taskId:r.taskId},c=o.payloads.length;if(o.payloads.push(r.payload),o.dismissedRequestIds.push(...r.dismissedRequestIds??[]),o.retireRequestIds.push(...r.retireRequestIds),o.sourcePayloadIndexes.push(e),l.forSelf===void 0&&t===0)for(let t of n.deliveryMetadata??[])t.payloadIndex===e&&o.metadata.push({...t,payloadIndex:c});i.set(a,o)}}let c=!1;for(let a of i.values()){let i=a.taskId;if(i!==void 0){let e=findBackgroundWorkflowToolRun(t.state,i);if(e===void 0){mergeStrandedResponses(r,a,i);continue}if(await sendTaskInboundPayload({taskInboxToken:e.address.hookToken,payload:{auth:n.auth,childContinuationToken:a.childContinuationToken,childSessionInbox:a.childSessionInbox,childResponseUrl:a.childResponseUrl,inputResponses:coalesceDeliverPayloads(a.payloads).inputResponses??[],kind:`input-response`,taskId:i}})===`unreachable`){mergeStrandedResponses(r,a,i);continue}t=retireProxyInputRequests(t,a.retireRequestIds),c=!0;continue}if(a.answerHook!==void 0){let n=coalesceDeliverPayloads(a.payloads).inputResponses??[];await resumeWorkflowToolRunAnswers(a.childContinuationToken,n),a.dismissedRequestIds.length>0&&await resumeWorkflowToolRunDismissal(a.childContinuationToken),a.answerHook.question!==void 0&&await emitQuestionResolutions({dismissedRequestIds:a.dismissedRequestIds,responses:n,sessionState:t.state,sessionWritable:e.sessionWritable}),t=retireProxyInputRequests(t,a.retireRequestIds),c=!0;continue}let o={...n,deliveryMetadata:a.metadata.length===0?void 0:a.metadata,payloads:a.payloads};await resumeSessionInbox(a.childSessionInbox??a.childContinuationToken,o),t=retireProxyInputRequests(t,a.retireRequestIds),c=!0}let l={serializedContext:e.serializedContext??{},sessionState:c?replaceDurableSessionSnapshot({session:t,state:e.sessionState}):e.sessionState};if(a!==void 0)return{...l,...a};let u=[...r].sort(([e],[t])=>e-t),d=u.flatMap(([e],t)=>(n.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:t}))),f=u.length===0?void 0:{...n,deliveryMetadata:d.length===0?void 0:d,payloads:u.map(([,e])=>e)};return{...l,kind:`continue`,remainder:f}}async function emitQuestionResolutions(e){let t=getPendingCoordinationBatch(e.sessionState)?.event;if(t===void 0)return;let n=[...e.responses.map(e=>({kind:`question`,outcome:`answered`,requestId:e.requestId,response:e})),...e.dismissedRequestIds.map(e=>({kind:`question`,outcome:`ignored`,requestId:e}))];if(n.length===0)return;let r=e.sessionWritable.getWriter();try{await r.write(encodeMessageStreamEvent(stampMessageStreamEvent(createInputResolvedEvent({resolutions:n,...t}))))}finally{r.releaseLock()}}function mergeStrandedResponses(e,t,n){for(let[r,i]of t.payloads.entries()){let a=t.sourcePayloadIndexes[r];if(a===void 0)continue;let o=(i.inputResponses??[]).map(e=>({...e,requestId:createTaskInputRequestId(n,e.requestId)}));if(o.length===0)continue;let s=e.get(a);e.set(a,{...s,inputResponses:[...s?.inputResponses??[],...o]})}}export{routeProxiedDeliverStep};
@@ -1,3 +1,3 @@
1
- import{normalizeModelPath}from"#execution/tools/file-state.js";import{MAX_OUTPUT_BYTES}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGlobOnSandbox(e,t){let n=t.path??`/workspace`,r=await resolveAbsoluteFilePath(e,n),i=normalizeModelPath(r),a=Math.min(Math.max(1,t.limit??100),1e3),o=await ripgrepIsAvailable(e)?buildRipgrepCommand({normalizedPath:i,pattern:t.pattern}):buildPosixFindCommand({normalizedPath:i,pattern:t.pattern}),s=await e.run({command:o});if(s.exitCode!==0&&s.exitCode!==1||s.exitCode===1&&s.stderr.trim().length>0)throw buildGlobExecutionError(o,s.exitCode,s.stderr);let c=s.stdout.split(`
1
+ import{MAX_OUTPUT_BYTES}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{normalizeModelPath}from"#execution/tools/file-state.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGlobOnSandbox(e,t){let n=t.path??`/workspace`,r=await resolveAbsoluteFilePath(e,n),i=normalizeModelPath(r),a=Math.min(Math.max(1,t.limit??100),1e3),o=await ripgrepIsAvailable(e)?buildRipgrepCommand({normalizedPath:i,pattern:t.pattern}):buildPosixFindCommand({normalizedPath:i,pattern:t.pattern}),s=await e.run({command:o});if(s.exitCode!==0&&s.exitCode!==1||s.exitCode===1&&s.stderr.trim().length>0)throw buildGlobExecutionError(o,s.exitCode,s.stderr);let c=s.stdout.split(`
2
2
  `).filter(e=>e.length>0),l=c.length>a,u=l?c.slice(0,a):c,d=[],f=0,p=!1;for(let e of u){let t=normalizeModelPath(e),n=Buffer.byteLength(t,`utf8`)+1;if(f+n>MAX_OUTPUT_BYTES&&d.length>0){p=!0;break}d.push(t),f+=n}if(d.length===0)return{content:`No files found`,count:0,path:i,truncated:!1};let m=l||p,h=[...d];return m&&(h.push(``),h.push(`(Results truncated: showing first ${d.length} results out of more. Use a more specific path or pattern to narrow results.)`)),{content:h.join(`
3
3
  `),count:d.length,path:i,truncated:m}}function buildRipgrepCommand(e){return[`rg --files --hidden`,`--glob '!.git/*'`,`--glob ${shellQuote(e.pattern)}`,shellQuote(e.normalizedPath)].join(` `)}function buildPosixFindCommand(e){let t=translateGlobToFindPattern(e.pattern),n=t.includes(`/`)?`-path ${shellQuote(`*/${t}`)}`:`-name ${shellQuote(t)}`;return[`find ${shellQuote(e.normalizedPath)}`,`-type f`,`-not -path '*/.git/*'`,n].join(` `)}function translateGlobToFindPattern(e){let t=e.replaceAll(`**`,`*`);for(;t.startsWith(`*/`);)t=t.slice(2);return t}function buildGlobExecutionError(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`glob failed (exit ${t}): ${i}\nCommand: ${e}`)}export{executeGlobOnSandbox};
@@ -1,3 +1,3 @@
1
- import{normalizeModelPath}from"#execution/tools/file-state.js";import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGrepOnSandbox(e,t){let n=t.path??`/workspace`,r=await resolveAbsoluteFilePath(e,n),i=normalizeModelPath(r),a=Math.min(Math.max(1,t.limit??100),1e3),o=t.context!==void 0&&t.context>0?t.context:0,s=await ripgrepIsAvailable(e)?buildRipgrepCommand({contextLines:o,effectiveLimit:a,glob:t.glob,ignoreCase:t.ignoreCase??!1,literal:t.literal??!1,normalizedPath:i,pattern:t.pattern}):buildPosixGrepCommand({contextLines:o,effectiveLimit:a,glob:t.glob,ignoreCase:t.ignoreCase??!1,literal:t.literal??!1,normalizedPath:i,pattern:t.pattern}),c=await e.run({command:s});if(c.exitCode!==0&&c.exitCode!==1||c.exitCode===1&&c.stderr.trim().length>0)throw buildGrepExecutionError(s,c.exitCode,c.stderr);let l=c.stdout;return l.trim().length===0?{content:`No matches found`,matchCount:0,path:i,truncated:!1}:processOutput({effectiveLimit:a,normalizedPath:i,stdout:l})}function buildRipgrepCommand(e){let t=[`rg`,`--line-number`,`--color=never`,`--hidden`,`--glob '!.git/*'`];return e.ignoreCase&&t.push(`--ignore-case`),e.literal&&t.push(`--fixed-strings`),e.glob!==void 0&&t.push(`--glob ${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`--context ${e.contextLines}`),t.push(`--max-count ${e.effectiveLimit}`),t.push(`--`),t.push(shellQuote(e.pattern)),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function buildPosixGrepCommand(e){let t=[`grep`,`-r`,`-n`,`--exclude-dir=.git`];return e.ignoreCase&&t.push(`-i`),e.literal?t.push(`-F`):t.push(`-E`),e.glob!==void 0&&t.push(`--include=${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`-C ${e.contextLines}`),t.push(`-m ${e.effectiveLimit}`),t.push(`-e ${shellQuote(e.pattern)}`),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function processOutput(e){let t=e.stdout.split(`
1
+ import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{normalizeModelPath}from"#execution/tools/file-state.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";import{ripgrepIsAvailable}from"#execution/sandbox/ripgrep-probe.js";async function executeGrepOnSandbox(e,t){let n=t.path??`/workspace`,r=await resolveAbsoluteFilePath(e,n),i=normalizeModelPath(r),a=Math.min(Math.max(1,t.limit??100),1e3),o=t.context!==void 0&&t.context>0?t.context:0,s=await ripgrepIsAvailable(e)?buildRipgrepCommand({contextLines:o,effectiveLimit:a,glob:t.glob,ignoreCase:t.ignoreCase??!1,literal:t.literal??!1,normalizedPath:i,pattern:t.pattern}):buildPosixGrepCommand({contextLines:o,effectiveLimit:a,glob:t.glob,ignoreCase:t.ignoreCase??!1,literal:t.literal??!1,normalizedPath:i,pattern:t.pattern}),c=await e.run({command:s});if(c.exitCode!==0&&c.exitCode!==1||c.exitCode===1&&c.stderr.trim().length>0)throw buildGrepExecutionError(s,c.exitCode,c.stderr);let l=c.stdout;return l.trim().length===0?{content:`No matches found`,matchCount:0,path:i,truncated:!1}:processOutput({effectiveLimit:a,normalizedPath:i,stdout:l})}function buildRipgrepCommand(e){let t=[`rg`,`--line-number`,`--color=never`,`--hidden`,`--glob '!.git/*'`];return e.ignoreCase&&t.push(`--ignore-case`),e.literal&&t.push(`--fixed-strings`),e.glob!==void 0&&t.push(`--glob ${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`--context ${e.contextLines}`),t.push(`--max-count ${e.effectiveLimit}`),t.push(`--`),t.push(shellQuote(e.pattern)),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function buildPosixGrepCommand(e){let t=[`grep`,`-r`,`-n`,`--exclude-dir=.git`];return e.ignoreCase&&t.push(`-i`),e.literal?t.push(`-F`):t.push(`-E`),e.glob!==void 0&&t.push(`--include=${shellQuote(e.glob)}`),e.contextLines>0&&t.push(`-C ${e.contextLines}`),t.push(`-m ${e.effectiveLimit}`),t.push(`-e ${shellQuote(e.pattern)}`),t.push(shellQuote(e.normalizedPath)),t.join(` `)}function processOutput(e){let t=e.stdout.split(`
2
2
  `),n=[],r=0,i=0,a=!1;for(let e=0;e<t.length;e+=1){let o=t[e]??``;if(o.length===0&&e===t.length-1)continue;o!==`--`&&o.length>0&&/^.+:\d+:/.test(o)&&i++;let s=capLineLength(o),c=Buffer.byteLength(s,`utf8`)+1;if(r+c>MAX_OUTPUT_BYTES&&n.length>0){a=!0;break}n.push(s),r+=c}let o=a||i>=e.effectiveLimit,s=n.join(`
3
3
  `);if(o){let t=[];i>=e.effectiveLimit&&t.push(`Match limit reached (${e.effectiveLimit}). Use a larger limit or more specific pattern.`),a&&t.push(`Output truncated due to size. Use a more specific path or pattern.`),s+=`\n\n[${t.join(` `)}]`}return{content:s,matchCount:i,path:e.normalizedPath,truncated:o}}function buildGrepExecutionError(e,t,n){let r=n.trim(),i=r.length>0?r:`no stderr output`;return Error(`grep failed (exit ${t}): ${i}\nCommand: ${e}`)}export{executeGrepOnSandbox};
@@ -1,3 +1,3 @@
1
- import{loadContext}from"#context/container.js";import{buildReadFileTargetKey,createReadFileStamp,normalizeModelPath,setReadFileStamp}from"#execution/tools/file-state.js";import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";async function executeReadFileOnSandbox(e,t){let{filePath:n,offset:r,limit:i}=t,a=await resolveAbsoluteFilePath(e,n),o=normalizeModelPath(a),s=r??1,c=i??2e3;if(s<1)throw Error(`offset must be >= 1. Received: ${s}.`);let l=await e.readTextFile({path:a});if(l===null)throw Error(`File not found: ${n}. Verify the path exists and is accessible in the sandbox.`);if(l.includes(`\0`))throw Error(`File "${n}" contains NUL bytes and appears to be a binary file. read_file only supports text files.`);let u=l.split(`
1
+ import{loadContext}from"#context/container.js";import{MAX_OUTPUT_BYTES,capLineLength}from"#execution/sandbox/truncate-output.js";import{buildReadFileTargetKey,createReadFileStamp,normalizeModelPath,setReadFileStamp}from"#execution/tools/file-state.js";import{resolveAbsoluteFilePath}from"#execution/sandbox/require-sandbox.js";async function executeReadFileOnSandbox(e,t){let{filePath:n,offset:r,limit:i}=t,a=await resolveAbsoluteFilePath(e,n),o=normalizeModelPath(a),s=r??1,c=i??2e3;if(s<1)throw Error(`offset must be >= 1. Received: ${s}.`);let l=await e.readTextFile({path:a});if(l===null)throw Error(`File not found: ${n}. Verify the path exists and is accessible in the sandbox.`);if(l.includes(`\0`))throw Error(`File "${n}" contains NUL bytes and appears to be a binary file. read_file only supports text files.`);let u=l.split(`
2
2
  `),d=u.length>0&&u[u.length-1]===``?u.length-1:u.length;if(d===0){if(s>1)throw Error(`offset ${s} is past the end of the file (0 lines). Use the default offset to read an empty file.`)}else if(s>d)throw Error(`offset ${s} is past the end of the file (${d} lines).`);let f=createReadFileStamp({content:l,filePath:o}),p=buildReadFileTargetKey(o);if(setReadFileStamp(loadContext(),p,f),d===0)return{content:``,path:o,totalLines:0,truncated:!1};let m=s-1,h=Math.min(m+c,d),g=u.slice(m,h),_=[],v=0,y=!1;for(let e=0;e<g.length;e++){let t=`${s+e}: ${capLineLength(g[e]??``)}`,n=Buffer.byteLength(t,`utf8`)+1;if(v+n>MAX_OUTPUT_BYTES&&_.length>0){y=!0;break}_.push(t),v+=n}let b=_.join(`
3
3
  `),x=s+_.length-1;return x<d||y?{content:b,nextOffset:x+1,path:o,totalLines:d,truncated:!0}:{content:b,path:o,totalLines:d,truncated:!1}}export{executeReadFileOnSandbox};
@@ -1 +1 @@
1
- import{findBlockingWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{cancelAgentInvocationOwnerStep}from"#execution/tools/subagent/task-cancel.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deliverWorkflowAuthorization}from"#execution/tools/workflow/owner.js";import{emitWorkflowToolRunReportStep}from"#execution/tools/workflow/emit-workflow-tool-run-report-step.js";import{releaseAgentInvocationOwnerStep}from"#execution/tools/subagent/invoke-step.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{workflowToolRunOutcomeToToolResult,workflowToolRunRequestToInputRequestPayload}from"#execution/tools/workflow/owner-inbox.js";async function handleWorkflowToolRunMessage(e){let{message:t}=e;switch(t.kind){case`outcome`:return await handleWorkflowToolRunOutcome({...e,message:t});case`request`:await handleWorkflowToolRunRequest({...e,message:t});return;case`report`:await emitWorkflowToolRunReportStep({from:t.from,sessionWritable:e.cursor.sessionWritable,update:t.update});return}}async function handleWorkflowToolRunOutcome(e){let{cursor:t,message:n}=e;if(findBlockingWorkflowToolRun(t.sessionState.snapshot.session.state,n.from.callId,n.from.turnId)?.address.runId!==n.from.runId)return;let r=workflowToolRunOutcomeToToolResult(n);await cancelAgentInvocationOwnerStep({ownerId:n.from.runId,serializedContext:t.serializedContext,sessionState:t.sessionState});let i=await releaseAgentInvocationOwnerStep({cancelled:n.result.status===`cancelled`,ownerId:n.from.runId,sessionState:t.sessionState});return await t.apply({serializedContext:t.serializedContext,sessionState:i.sessionState}),isInboxToolResultFromRecordedWorkflowToolRun(t.sessionState.snapshot.session.state,r)?r:void 0}async function handleWorkflowToolRunRequest(e){let{cursor:t,message:n}=e;if(n.request.kind===`agent-invoke`||n.request.kind===`agent-settled`){if(findBlockingWorkflowToolRun(t.sessionState.snapshot.session.state,n.from.callId,n.from.turnId)?.address.runId!==n.from.runId){n.request.kind===`agent-invoke`&&await resumeHookStep(n.replyTo,{kind:`runtime-action-result`,results:[{callId:n.request.invocationId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:`AGENT_INVOCATION_NOT_ADMITTED`,message:`The workflow tool run no longer owns this agent invocation.`},subagentName:n.request.input.target}]});return}await t.apply(await applyTaskAgentRequest({ownerId:n.from.runId,replyTo:n.replyTo,request:n.request},requestContext(e)));return}if(n.request.kind===`authorization-request`){let e=n.request;await deliverWorkflowAuthorization({...n,request:e},async()=>{await t.apply(await runProxySubagentEventStep({hookPayload:e.event,sessionWritable:t.sessionWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}))});return}await t.apply(await runProxySubagentEventStep({...n.requestCoordinates===void 0?{answerHook:{runId:n.from.runId}}:{},hookPayload:workflowToolRunRequestToInputRequestPayload(n),sessionWritable:t.sessionWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}))}function requestContext(e){return{callbackBaseUrl:resolveWorkflowCallbackBaseUrl(e.callbackMetadataUrl),sessionWritable:e.cursor.sessionWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}}export{handleWorkflowToolRunMessage};
1
+ import{findBlockingWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{cancelAgentInvocationOwnerStep}from"#execution/tools/subagent/task-cancel.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deliverWorkflowAuthorization}from"#execution/tools/workflow/owner.js";import{emitWorkflowToolRunReportStep}from"#execution/tools/workflow/emit-workflow-tool-run-report-step.js";import{releaseAgentInvocationOwnerStep}from"#execution/tools/subagent/invoke-step.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";import{workflowToolRunOutcomeToToolResult,workflowToolRunRequestToInputRequestPayload}from"#execution/tools/workflow/owner-inbox.js";async function handleWorkflowToolRunMessage(e){let{message:t}=e;switch(t.kind){case`outcome`:return await handleWorkflowToolRunOutcome({...e,message:t});case`request`:await handleWorkflowToolRunRequest({...e,message:t});return;case`report`:await emitWorkflowToolRunReportStep({from:t.from,sessionWritable:e.cursor.sessionWritable,update:t.update});return}}async function handleWorkflowToolRunOutcome(e){let{cursor:t,message:n}=e;if(findBlockingWorkflowToolRun(t.sessionState.snapshot.session.state,n.from.callId,n.from.turnId)?.address.runId!==n.from.runId)return;let r=workflowToolRunOutcomeToToolResult(n);await cancelAgentInvocationOwnerStep({ownerId:n.from.runId,serializedContext:t.serializedContext,sessionState:t.sessionState});let i=await releaseAgentInvocationOwnerStep({cancelled:n.result.status===`cancelled`,ownerId:n.from.runId,sessionState:t.sessionState});return await t.apply({serializedContext:t.serializedContext,sessionState:i.sessionState}),isInboxToolResultFromRecordedWorkflowToolRun(t.sessionState.snapshot.session.state,r)?r:void 0}async function handleWorkflowToolRunRequest(e){let{cursor:t,message:n}=e;if(n.request.kind===`agent-invoke`||n.request.kind===`agent-settled`){if(findBlockingWorkflowToolRun(t.sessionState.snapshot.session.state,n.from.callId,n.from.turnId)?.address.runId!==n.from.runId){n.request.kind===`agent-invoke`&&await resumeHookStep(n.replyTo,{kind:`runtime-action-result`,results:[{callId:n.request.invocationId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:`AGENT_INVOCATION_NOT_ADMITTED`,message:`The workflow tool run no longer owns this agent invocation.`},subagentName:n.request.input.target}]});return}await t.apply(await applyTaskAgentRequest({ownerId:n.from.runId,replyTo:n.replyTo,request:n.request},requestContext(e)));return}if(n.request.kind===`authorization-request`){let e=n.request;await deliverWorkflowAuthorization({...n,request:e},async()=>{await t.apply(await runProxySubagentEventStep({hookPayload:e.event,sessionWritable:t.sessionWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}))});return}await t.apply(await runProxySubagentEventStep({...n.requestCoordinates===void 0?{answerHook:createAnswerHookRoute(n)}:{},hookPayload:workflowToolRunRequestToInputRequestPayload(n),sessionWritable:t.sessionWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}))}function createAnswerHookRoute(e){if(e.request.kind!==`ask`)return{runId:e.from.runId};let{allowFreeform:t,dismissible:n,options:r}=e.request.request;return{question:{...t!==void 0&&{allowFreeform:t},...n!==void 0&&{dismissible:n},...r!==void 0&&{options:[...r]}},runId:e.from.runId}}function requestContext(e){return{callbackBaseUrl:resolveWorkflowCallbackBaseUrl(e.callbackMetadataUrl),sessionWritable:e.cursor.sessionWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}}export{handleWorkflowToolRunMessage};
@@ -1 +1 @@
1
- import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{ActivityObserverKey}from"#context/keys.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{parseWorkflowToolInput}from"#execution/tools/workflow/background.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{findBackgroundWorkflowToolRun,getBackgroundWorkflowToolRuns,registerWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{runStep}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveWorkflowAgentMetadata}from"#execution/tools/subagent/metadata.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{startTaskRun,waitForTaskCommandOwner}from"#execution/tasks/parent/run-parent.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{createTaskAgentDispatchContext,prepareBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{deriveBackgroundTaskActivityObserver}from"#execution/activity-work.js";import{projectToolStartLabel}from"#harness/action-presentation.js";import{projectSubagentTask}from"#execution/tasks/parent/subagent-task-projection.js";import{steerBackgroundAgent}from"#execution/tools/subagent/steer.js";function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t)}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{executions=new Map;records=[];agentHandleSession;agentHandlesChanged=!1;retained=!1;initialSession;constructor(e){this.initialSession=e,this.agentHandleSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async readAgentViews(){return(getAgentHandleStore(this.agentHandleSession.state)?.handles??[]).flatMap(e=>e.phase===`reserved`?[]:e.phase===`available`?[{availability:`available`,id:e.identity.id,name:e.identity.name}]:e.phase===`claimed`?[{availability:`busy`,id:e.identity.id,name:e.identity.name,taskId:e.ownerId,taskStatus:`working`}]:[])}hasPendingTasks(){return getBackgroundWorkflowToolRuns(this.initialSession.state).some(e=>e.task.outcome===void 0)||this.records.some(e=>e.settled&&e.task!==void 0)}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await this.compensate(t,Error(`Background tool execution did not delegate or complete its task.`)),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await this.compensate(n,e),t.length===0){this.retained=this.agentHandlesChanged&&isTurnCancellation(e);return}if(isTurnCancellation(e)){this.retained=!0;return}await this.compensate(t,e)}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records)e.settled&&e.task!==void 0&&(t=registerWorkflowToolRun(t,e.task));return this.agentHandlesChanged&&(t=writeHandles(t,getAgentHandleStore(this.agentHandleSession.state)?.handles??[])),t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[{callId:e.callId,taskInboxToken:e.task.address.hookToken,taskId:e.task.task.taskId,taskRunId:e.task.address.runId}]:[]);if(e.length!==0||this.agentHandlesChanged)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e}}async start(e){let t={callId:e.options.toolCallId,settled:!1};this.records.push(t);let n=getHarnessEmissionState(this.initialSession.state),r=loadContext(),i=await this.startTask({ctx:r,emission:n,input:e,record:t});if(i.kind===`steered`)return t.settled=!0,i.receipt;let a=i.task;return t.task=a,t.settled=!0,{...i.receipt,status:`working`,taskId:a.task.taskId}}async startTask(e){let t=e.input.definition,n=parseWorkflowToolInput(e.input.toolInput,e.input.definition.name),r=activeTurnId(e.emission),i=t.nodeId===void 0?void 0:projectSubagentTask({ctx:e.ctx,input:n,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}});if(i!==void 0&&i.identity===void 0&&!hasAgentHandle(this.agentHandleSession,i.metadata.agentId)){let{agentId:a,...o}=n;n=o,i=projectSubagentTask({ctx:e.ctx,input:o,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}})}let a=i?.metadata??{kind:`tool`,name:e.input.definition.name},o=projectToolStartLabel(e.input.definition,e.input.toolInput),s=buildCallbackContext().session,c={activityObserver:deriveBackgroundTaskActivityObserver({activityObserver:e.ctx.get(ActivityObserverKey),callId:e.input.options.toolCallId,label:o,name:a.name,parentSessionId:this.initialSession.sessionId,parentTurnId:r,rootSessionId:this.initialSession.rootSessionId??this.initialSession.sessionId}),callId:e.input.options.toolCallId,dispatchContext:createTaskAgentDispatchContext(e.ctx,s.auth),metadata:a,parentSessionId:this.initialSession.sessionId,parentStepIndex:e.emission.stepIndex,parentTurnId:r,session:this.initialSession},l=prepareBackgroundTask(c),u={...l,task:{...l.task,activityWorkIdentity:c.activityObserver?.workIdentity}};if(t.nodeId!==void 0&&i!==void 0&&i.identity!==void 0){let t=i.identity;if(this.applyAgentHandleCommand({identity:t.identity,callId:c.callId,kind:`reserve`,operationId:t.operation.id,ownerId:u.task.taskId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${t.operation.id}".`);e.record.reservation={agentId:t.identity.id,operationId:t.operation.id}}if(t.nodeId!==void 0&&i!==void 0&&i.identity===void 0){let t=deriveAgentOperationId({callId:c.callId,parentSessionId:c.parentSessionId,parentTurnId:r}),a=this.applyAgentHandleCommand({agentId:i.metadata.agentId,callId:c.callId,expectedTarget:i.metadata.mode,invokedName:i.metadata.name,kind:`claim`,operationId:t,ownerId:u.task.taskId});if(a.kind===`busy`&&a.handle.phase===`claimed`){let t=a.handle,r=findBackgroundWorkflowToolRun(this.agentHandleSession.state,t.ownerId);if(r?.task.metadata.kind===`subagent`&&r.task.metadata.agentId===t.identity.id&&r.task.metadata.name===t.identity.name&&r.task.outcome===void 0)return await steerBackgroundAgent({ctx:e.ctx,handle:t,callId:c.callId,input:n,session:this.agentHandleSession}),{kind:`steered`,receipt:{agentId:t.identity.id,taskId:r.task.taskId,status:`working`}}}readClaimedHandle(a)?e.record.claim={operationId:t,taskId:u.task.taskId}:throwAgentClaimError(i.metadata.agentId,a)}await startTaskRun({activityObserver:c.activityObserver,initialView:{metadata:u.task.metadata,status:`working`,taskId:u.task.taskId},parentContinuationToken:sessionCommandHookToken(this.initialSession.sessionId),taskInboxToken:u.address.hookToken,workflow:{agents:resolveWorkflowAgentMetadata(e.ctx),callId:c.callId,executeInput:t.executeInput?.(n),input:n,session:s,stepIndex:e.emission.stepIndex,toolName:e.input.definition.name,workflowId:t.workflowId}});let d=await waitForTaskCommandOwner({taskInboxToken:u.address.hookToken}),f={...u,address:{...u.address,runId:d.runId}};return e.record.task=f,t.nodeId===void 0||i===void 0?{kind:`started`,task:f}:{kind:`started`,receipt:i.receipt,task:f}}applyAgentHandleCommand(e){let t=applyTaskAgentHandleCommand(this.agentHandleSession,e);return t.session!==this.agentHandleSession&&(this.agentHandleSession=t.session,this.agentHandlesChanged=!0),t.result}async compensate(e,t){let n=[];for(let r of e.toReversed()){if(r.task!==void 0)try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:r.task})}catch(e){n.push(e)}r.claim!==void 0&&this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.claim.taskId}),r.reservation!==void 0&&r.task!==void 0&&this.applyAgentHandleCommand({agentId:r.reservation.agentId,kind:`remove`,ownerId:r.task.task.taskId})}if(n.length>0)throw AggregateError([t,...n],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}};function hasAgentHandle(e,t){return getAgentHandleStore(e.state)?.handles.some(e=>e.identity.id===t)===!0}function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}function readClaimedHandle(e){return e.kind===`ready`&&e.handle?.phase===`claimed`}function throwAgentClaimError(e,t){throw t.kind===`mismatch`?Error(JSON.stringify({code:AGENT_MISMATCH,message:`Agent "${e}" no longer matches this subagent definition. Start a new agent instead.`})):t.kind===`busy`?Error(JSON.stringify({code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:e,agentName:t.handle.identity.name,ownerId:`ownerId`in t.handle?t.handle.ownerId:void 0})})):Error(JSON.stringify({code:AGENT_UNREACHABLE,message:`Agent with id "${e}" is no longer reachable.`}))}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
1
+ import{sessionCommandHookToken}from"#execution/session-inbox/address.js";import{loadContext}from"#context/container.js";import{ActivityObserverKey,CapabilitiesKey}from"#context/keys.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{parseWorkflowToolInput}from"#execution/tools/workflow/background.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deriveAgentOperationId}from"#subagents/handles/operation-id.js";import{findBackgroundWorkflowToolRun,getBackgroundWorkflowToolRuns,registerWorkflowToolRun}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore,writeHandles}from"#subagents/handles/store.js";import{runStep}from"#context/run-step.js";import{activeTurnId}from"#harness/active-turn-id.js";import{resolveWorkflowAgentMetadata}from"#execution/tools/subagent/metadata.js";import{AGENT_BUSY,AGENT_MISMATCH,AGENT_UNREACHABLE,formatAgentBusyMessage}from"#subagents/agent-handle-errors.js";import{startTaskRun,waitForTaskCommandOwner}from"#execution/tasks/parent/run-parent.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{createTaskAgentDispatchContext,prepareBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{applyTaskAgentHandleCommand}from"#subagents/handles/transitions.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{deriveBackgroundTaskActivityObserver}from"#execution/activity-work.js";import{projectToolStartLabel}from"#harness/action-presentation.js";import{projectSubagentTask}from"#execution/tasks/parent/subagent-task-projection.js";import{steerBackgroundAgent}from"#execution/tools/subagent/steer.js";function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t)}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{executions=new Map;records=[];agentHandleSession;agentHandlesChanged=!1;retained=!1;initialSession;constructor(e){this.initialSession=e,this.agentHandleSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async readAgentViews(){return(getAgentHandleStore(this.agentHandleSession.state)?.handles??[]).flatMap(e=>e.phase===`reserved`?[]:e.phase===`available`?[{availability:`available`,id:e.identity.id,name:e.identity.name}]:e.phase===`claimed`?[{availability:`busy`,id:e.identity.id,name:e.identity.name,taskId:e.ownerId,taskStatus:`working`}]:[])}hasPendingTasks(){return getBackgroundWorkflowToolRuns(this.initialSession.state).some(e=>e.task.outcome===void 0)||this.records.some(e=>e.settled&&e.task!==void 0)}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await this.compensate(t,Error(`Background tool execution did not delegate or complete its task.`)),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await this.compensate(n,e),t.length===0){this.retained=this.agentHandlesChanged&&isTurnCancellation(e);return}if(isTurnCancellation(e)){this.retained=!0;return}await this.compensate(t,e)}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records)e.settled&&e.task!==void 0&&(t=registerWorkflowToolRun(t,e.task));return this.agentHandlesChanged&&(t=writeHandles(t,getAgentHandleStore(this.agentHandleSession.state)?.handles??[])),t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[{callId:e.callId,taskInboxToken:e.task.address.hookToken,taskId:e.task.task.taskId,taskRunId:e.task.address.runId}]:[]);if(e.length!==0||this.agentHandlesChanged)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e}}async start(e){let t={callId:e.options.toolCallId,settled:!1};this.records.push(t);let n=getHarnessEmissionState(this.initialSession.state),r=loadContext(),i=await this.startTask({ctx:r,emission:n,input:e,record:t});if(i.kind===`steered`)return t.settled=!0,i.receipt;let a=i.task;return t.task=a,t.settled=!0,{...i.receipt,status:`working`,taskId:a.task.taskId}}async startTask(e){let t=e.input.definition,n=parseWorkflowToolInput(e.input.toolInput,e.input.definition.name),r=activeTurnId(e.emission),i=t.nodeId===void 0?void 0:projectSubagentTask({ctx:e.ctx,input:n,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}});if(i!==void 0&&i.identity===void 0&&!hasAgentHandle(this.agentHandleSession,i.metadata.agentId)){let{agentId:a,...o}=n;n=o,i=projectSubagentTask({ctx:e.ctx,input:o,name:e.input.definition.name,nodeId:t.nodeId??e.input.definition.name,taskInput:{callId:e.input.options.toolCallId,parentSessionId:this.initialSession.sessionId,parentTurnId:r}})}let a=i?.metadata??{kind:`tool`,name:e.input.definition.name},o=projectToolStartLabel(e.input.definition,e.input.toolInput),s=buildCallbackContext().session,c={activityObserver:deriveBackgroundTaskActivityObserver({activityObserver:e.ctx.get(ActivityObserverKey),callId:e.input.options.toolCallId,label:o,name:a.name,parentSessionId:this.initialSession.sessionId,parentTurnId:r,rootSessionId:this.initialSession.rootSessionId??this.initialSession.sessionId}),callId:e.input.options.toolCallId,dispatchContext:createTaskAgentDispatchContext(e.ctx,s.auth),metadata:a,parentSessionId:this.initialSession.sessionId,parentStepIndex:e.emission.stepIndex,parentTurnId:r,session:this.initialSession},l=prepareBackgroundTask(c),u={...l,task:{...l.task,activityWorkIdentity:c.activityObserver?.workIdentity}};if(t.nodeId!==void 0&&i!==void 0&&i.identity!==void 0){let t=i.identity;if(this.applyAgentHandleCommand({identity:t.identity,callId:c.callId,kind:`reserve`,operationId:t.operation.id,ownerId:u.task.taskId}).kind!==`ready`)throw Error(`Agent handle store rejected start operation "${t.operation.id}".`);e.record.reservation={agentId:t.identity.id,operationId:t.operation.id}}if(t.nodeId!==void 0&&i!==void 0&&i.identity===void 0){let t=deriveAgentOperationId({callId:c.callId,parentSessionId:c.parentSessionId,parentTurnId:r}),a=this.applyAgentHandleCommand({agentId:i.metadata.agentId,callId:c.callId,expectedTarget:i.metadata.mode,invokedName:i.metadata.name,kind:`claim`,operationId:t,ownerId:u.task.taskId});if(a.kind===`busy`&&a.handle.phase===`claimed`){let t=a.handle,r=findBackgroundWorkflowToolRun(this.agentHandleSession.state,t.ownerId);if(r?.task.metadata.kind===`subagent`&&r.task.metadata.agentId===t.identity.id&&r.task.metadata.name===t.identity.name&&r.task.outcome===void 0)return await steerBackgroundAgent({ctx:e.ctx,handle:t,callId:c.callId,input:n,session:this.agentHandleSession}),{kind:`steered`,receipt:{agentId:t.identity.id,taskId:r.task.taskId,status:`working`}}}readClaimedHandle(a)?e.record.claim={operationId:t,taskId:u.task.taskId}:throwAgentClaimError(i.metadata.agentId,a)}await startTaskRun({activityObserver:c.activityObserver,initialView:{metadata:u.task.metadata,status:`working`,taskId:u.task.taskId},parentContinuationToken:sessionCommandHookToken(this.initialSession.sessionId),taskInboxToken:u.address.hookToken,workflow:{agents:resolveWorkflowAgentMetadata(e.ctx),callId:c.callId,canRequestInput:e.ctx.get(CapabilitiesKey)?.requestInput===!0,executeInput:t.executeInput?.(n),input:n,session:s,stepIndex:e.emission.stepIndex,toolName:e.input.definition.name,workflowId:t.workflowId}});let d=await waitForTaskCommandOwner({taskInboxToken:u.address.hookToken}),f={...u,address:{...u.address,runId:d.runId}};return e.record.task=f,t.nodeId===void 0||i===void 0?{kind:`started`,task:f}:{kind:`started`,receipt:i.receipt,task:f}}applyAgentHandleCommand(e){let t=applyTaskAgentHandleCommand(this.agentHandleSession,e);return t.session!==this.agentHandleSession&&(this.agentHandleSession=t.session,this.agentHandlesChanged=!0),t.result}async compensate(e,t){let n=[];for(let r of e.toReversed()){if(r.task!==void 0)try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:r.task})}catch(e){n.push(e)}r.claim!==void 0&&this.applyAgentHandleCommand({kind:`release-owner`,ownerId:r.claim.taskId}),r.reservation!==void 0&&r.task!==void 0&&this.applyAgentHandleCommand({agentId:r.reservation.agentId,kind:`remove`,ownerId:r.task.task.taskId})}if(n.length>0)throw AggregateError([t,...n],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}};function hasAgentHandle(e,t){return getAgentHandleStore(e.state)?.handles.some(e=>e.identity.id===t)===!0}function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}function readClaimedHandle(e){return e.kind===`ready`&&e.handle?.phase===`claimed`}function throwAgentClaimError(e,t){throw t.kind===`mismatch`?Error(JSON.stringify({code:AGENT_MISMATCH,message:`Agent "${e}" no longer matches this subagent definition. Start a new agent instead.`})):t.kind===`busy`?Error(JSON.stringify({code:AGENT_BUSY,message:formatAgentBusyMessage({agentId:e,agentName:t.handle.identity.name,ownerId:`ownerId`in t.handle?t.handle.ownerId:void 0})})):Error(JSON.stringify({code:AGENT_UNREACHABLE,message:`Agent with id "${e}" is no longer reachable.`}))}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
@@ -1 +1 @@
1
- import{evaluate}from"#ai/evaluate.js";async function executeAgentRouterTool(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);return t.agent(n,e.outputSchema===void 0?{message:e.message}:{message:e.message,outputSchema:e.outputSchema})}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}executeAgentRouterTool.workflowId=`workflow//eve@0.64.1//executeAgentRouterTool`;export{executeAgentRouterTool};
1
+ import{evaluate}from"#ai/evaluate.js";async function executeAgentRouterTool(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);return t.agent(n,e.outputSchema===void 0?{message:e.message}:{message:e.message,outputSchema:e.outputSchema})}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await evaluate({abortSignal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}executeAgentRouterTool.workflowId=`workflow//eve@0.65.0//executeAgentRouterTool`;export{executeAgentRouterTool};
@@ -0,0 +1,11 @@
1
+ import type { AskQuestionInput, AskQuestionOutput } from "#execution/tools/ask-question.js";
2
+ import type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
3
+ import type { WorkflowToolContext } from "#tools/workflow-definition.js";
4
+ /** Asks the session's user one question in a workflow dedicated to this tool call. */
5
+ export declare function executeAskQuestionTool(input: AskQuestionInput, ctx: WorkflowToolContext): Promise<AskQuestionOutput>;
6
+ /**
7
+ * Free text is always allowed, so the model never needs an "Other" option.
8
+ * Labels double as option ids so a late answer still reads as the label.
9
+ */
10
+ export declare function toAskQuestionRequest(input: AskQuestionInput): ToolInputRequest;
11
+ export declare function toAskQuestionOutput(answer: ToolInputResponse): AskQuestionOutput;
@@ -0,0 +1 @@
1
+ async function executeAskQuestionTool(e,t){"use workflow";return toAskQuestionOutput(await t.ask(toAskQuestionRequest(e)))}function toAskQuestionRequest(e){let t=e.options?.map(e=>({description:e.description,id:e.label,label:e.label}));return{allowFreeform:!0,dismissible:!0,display:t===void 0?`text`:`select`,prompt:e.question,...t!==void 0&&{options:t}}}function toAskQuestionOutput(e){return e.status===`answered`?{answer:e.optionId??e.text??``,status:`answered`}:{status:e.status}}executeAskQuestionTool.workflowId=`workflow//eve@0.65.0//executeAskQuestionTool`;export{executeAskQuestionTool,toAskQuestionOutput,toAskQuestionRequest};
@@ -0,0 +1,20 @@
1
+ import { z } from "#compiled/zod/index.js";
2
+ export { executeAskQuestionTool } from "#execution/tools/ask-question-workflow.js";
3
+ export declare const ASK_QUESTION_TOOL_DESCRIPTION: string;
4
+ export declare const ASK_QUESTION_INPUT_SCHEMA: z.ZodObject<{
5
+ options: z.ZodOptional<z.ZodArray<z.ZodObject<{
6
+ description: z.ZodString;
7
+ label: z.ZodString;
8
+ }, z.core.$strict>>>;
9
+ question: z.ZodString;
10
+ }, z.core.$strict>;
11
+ export declare const ASK_QUESTION_OUTPUT_SCHEMA: z.ZodDiscriminatedUnion<[z.ZodObject<{
12
+ answer: z.ZodString;
13
+ status: z.ZodLiteral<"answered">;
14
+ }, z.core.$strict>, z.ZodObject<{
15
+ status: z.ZodLiteral<"dismissed">;
16
+ }, z.core.$strict>, z.ZodObject<{
17
+ status: z.ZodLiteral<"unavailable">;
18
+ }, z.core.$strict>], "status">;
19
+ export type AskQuestionInput = z.infer<typeof ASK_QUESTION_INPUT_SCHEMA>;
20
+ export type AskQuestionOutput = z.infer<typeof ASK_QUESTION_OUTPUT_SCHEMA>;
@@ -0,0 +1,2 @@
1
+ import{z}from"#compiled/zod/index.js";import{executeAskQuestionTool}from"#execution/tools/ask-question-workflow.js";const ASK_QUESTION_TOOL_DESCRIPTION=[`Ask the user a question and wait for the answer. Use this only when you cannot make good progress without the user's input: to choose between materially different approaches, fill in a missing requirement, or confirm something risky or irreversible. Do not ask for information you can find with your other tools, and do not ask the user to confirm routine steps.`,``,`Usage:`,`- Ask one focused question that includes the context needed to answer it.`,`- For a decision, offer 2-3 mutually exclusive options. Put the option you recommend first and end its label with "(Recommended)".`,`- Do not add an "Other" option; the user can always type their own answer.`,"- The result's `answer` is the chosen option's label or the user's own words.",`- If the status is "dismissed", the user moved on without answering; respond to their next message instead.`,`- If the status is "unavailable", no one can answer in this session; continue with your best judgment and state the assumption you made.`].join(`
2
+ `),ASK_QUESTION_OPTION_SCHEMA=z.strictObject({description:z.string().min(1).max(200).describe(`One short sentence on the impact or tradeoff of choosing this option.`),label:z.string().min(1).max(80).describe(`User-facing label, 1-5 words.`)}),ASK_QUESTION_INPUT_SCHEMA=z.strictObject({options:z.array(ASK_QUESTION_OPTION_SCHEMA).min(2).max(3).refine(e=>new Set(e.map(e=>e.label)).size===e.length,{message:`Option labels must be unique.`}).describe(`Two or three mutually exclusive choices, recommended option first. Omit for an open-ended question. Never include an "Other" option.`).optional(),question:z.string().min(1).max(2e3).describe(`The question to show the user, with the context needed to answer it.`)}),ASK_QUESTION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[z.strictObject({answer:z.string().describe(`The chosen option's label, or the user's own words.`),status:z.literal(`answered`)}),z.strictObject({status:z.literal(`dismissed`)}),z.strictObject({status:z.literal(`unavailable`)})]);export{ASK_QUESTION_INPUT_SCHEMA,ASK_QUESTION_OUTPUT_SCHEMA,ASK_QUESTION_TOOL_DESCRIPTION,executeAskQuestionTool};
@@ -1,4 +1,4 @@
1
- import { type AlsContext } from "#context/container.js";
1
+ import type { AlsContext } from "#context/container.js";
2
2
  import { ContextKey } from "#context/key.js";
3
3
  /**
4
4
  * Per-file fingerprint stored after a successful `read_file` call. Used by
@@ -54,9 +54,3 @@ export declare function createReadFileStamp(input: {
54
54
  * do not duplicate the state mutation pattern.
55
55
  */
56
56
  export declare function setReadFileStamp(ctx: AlsContext, targetKey: string, stamp: ReadFileStamp): void;
57
- /**
58
- * Clears all read-file stamps from the context. The framework calls this on
59
- * context compaction so a write afterward must re-read the file whose read
60
- * evidence was summarized out of history.
61
- */
62
- export declare function clearReadFileState(): void;
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{loadContext}from"#context/container.js";import{posix}from"node:path";import{ContextKey}from"#context/key.js";const ReadFileStateKey=new ContextKey(`eve.readFile`);function normalizeModelPath(e){return posix.normalize(e)}function buildReadFileTargetKey(e){return e}function createReadFileStamp(e){let t=createHash(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function setReadFileStamp(e,t,n){let r=e.ensure(ReadFileStateKey,()=>({byTarget:{}}));e.set(ReadFileStateKey,{byTarget:{...r.byTarget,[t]:n}})}function clearReadFileState(){loadContext().set(ReadFileStateKey,{byTarget:{}})}export{ReadFileStateKey,buildReadFileTargetKey,clearReadFileState,createReadFileStamp,normalizeModelPath,setReadFileStamp};
1
+ import{createHash}from"node:crypto";import{posix}from"node:path";import{ContextKey}from"#context/key.js";const ReadFileStateKey=new ContextKey(`eve.readFile`);function normalizeModelPath(e){return posix.normalize(e)}function buildReadFileTargetKey(e){return e}function createReadFileStamp(e){let t=createHash(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function setReadFileStamp(e,t,n){let r=e.ensure(ReadFileStateKey,()=>({byTarget:{}}));e.set(ReadFileStateKey,{byTarget:{...r.byTarget,[t]:n}})}export{ReadFileStateKey,buildReadFileTargetKey,createReadFileStamp,normalizeModelPath,setReadFileStamp};
@@ -1 +1 @@
1
- import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.64.1//executeSleepTool`;export{executeSleepTool};
1
+ import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.65.0//executeSleepTool`;export{executeSleepTool};
@@ -1,3 +1,5 @@
1
1
  import type { InputResponse } from "#shared/input.js";
2
2
  /** Resumed with the bare response, not a session-inbox delivery, so the body can race the hook. */
3
3
  export declare function resumeWorkflowToolRunAnswers(answerToken: string, responses: readonly InputResponse[] | undefined): Promise<void>;
4
+ /** Resolves a dismissible `ctx.ask()` request the user moved past without answering. */
5
+ export declare function resumeWorkflowToolRunDismissal(answerToken: string): Promise<void>;
@@ -1 +1 @@
1
- import{resumeHook}from"#internal/workflow/runtime.js";async function resumeWorkflowToolRunAnswers(e,t){for(let n of t??[]){let t={optionId:n.optionId,text:n.text};await resumeHook(e,t)}}export{resumeWorkflowToolRunAnswers};
1
+ import{resumeHook}from"#internal/workflow/runtime.js";async function resumeWorkflowToolRunAnswers(e,t){for(let n of t??[]){let t={optionId:n.optionId,status:`answered`,text:n.text};await resumeHook(e,t)}}async function resumeWorkflowToolRunDismissal(e){await resumeHook(e,{status:`dismissed`})}export{resumeWorkflowToolRunAnswers,resumeWorkflowToolRunDismissal};
@@ -2,6 +2,7 @@ import { type Hook } from "#compiled/@workflow/core/index.js";
2
2
  import type { WorkflowToolRunOwner, WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
3
3
  import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
4
4
  export interface WorkflowToolRunContext {
5
+ readonly canRequestInput?: boolean;
5
6
  readonly from: WorkflowToolRunRef;
6
7
  readonly owner: WorkflowToolRunOwner;
7
8
  }
@@ -9,5 +10,5 @@ export declare function attachWorkflowToolRunContext(ctx: ToolContext, context:
9
10
  export declare function findWorkflowToolRunContext(value: unknown): WorkflowToolRunContext | undefined;
10
11
  export declare function readWorkflowToolRunRef(ctx: ToolContext): WorkflowToolRunRef;
11
12
  export declare function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunOwner;
12
- /** Returns an answer hook which may be awaited or raced with another workflow operation. */
13
- export declare function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse>;
13
+ /** Returns an answer which may be awaited or raced with another workflow operation. */
14
+ export declare function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse> | Promise<ToolInputResponse>;
@@ -1 +1 @@
1
- import{workflowToolContextErrorMessage}from"#shared/workflow-tool-context.js";import{createHook}from"#compiled/@workflow/core/index.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";const WORKFLOW_TOOL_RUN_CONTEXT=Symbol.for(`eve.workflow-tool-run.context`);function attachWorkflowToolRunContext(e,t){Object.defineProperty(e,WORKFLOW_TOOL_RUN_CONTEXT,{enumerable:!1,value:t})}function readWorkflowToolRunContext(e,t){let n=e?.[WORKFLOW_TOOL_RUN_CONTEXT];if(n===void 0)throw Error(workflowToolContextErrorMessage(t));return n}function findWorkflowToolRunContext(e){return typeof e==`object`&&e?e[WORKFLOW_TOOL_RUN_CONTEXT]:void 0}function readWorkflowToolRunRef(e){return readWorkflowToolRunContext(e,`agent`).from}function readWorkflowToolRunOwner(e){return readWorkflowToolRunContext(e,`agent`).owner}function ask(e,t){let n=readWorkflowToolRunContext(e,`ask`),r=createHook();return resumeHookStep(n.owner.inbox,{kind:`request`,from:n.from,replyTo:r.token,request:{kind:`ask`,request:t}}),r}export{ask,attachWorkflowToolRunContext,findWorkflowToolRunContext,readWorkflowToolRunOwner,readWorkflowToolRunRef};
1
+ import{workflowToolContextErrorMessage}from"#shared/workflow-tool-context.js";import{createHook}from"#compiled/@workflow/core/index.js";import{resumeHookStep}from"#execution/tools/workflow/resume-hook-step.js";const WORKFLOW_TOOL_RUN_CONTEXT=Symbol.for(`eve.workflow-tool-run.context`);function attachWorkflowToolRunContext(e,t){Object.defineProperty(e,WORKFLOW_TOOL_RUN_CONTEXT,{enumerable:!1,value:t})}function readWorkflowToolRunContext(e,t){let n=e?.[WORKFLOW_TOOL_RUN_CONTEXT];if(n===void 0)throw Error(workflowToolContextErrorMessage(t));return n}function findWorkflowToolRunContext(e){return typeof e==`object`&&e?e[WORKFLOW_TOOL_RUN_CONTEXT]:void 0}function readWorkflowToolRunRef(e){return readWorkflowToolRunContext(e,`agent`).from}function readWorkflowToolRunOwner(e){return readWorkflowToolRunContext(e,`agent`).owner}function ask(e,t){let n=readWorkflowToolRunContext(e,`ask`);if(n.canRequestInput===!1)return Promise.resolve({status:`unavailable`});let r=createHook();return resumeHookStep(n.owner.inbox,{kind:`request`,from:n.from,replyTo:r.token,request:{kind:`ask`,request:t}}),r}export{ask,attachWorkflowToolRunContext,findWorkflowToolRunContext,readWorkflowToolRunOwner,readWorkflowToolRunRef};