eve 0.53.1 → 0.54.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/src/channel/types.d.ts +2 -0
  3. package/dist/src/chunks/{use-eve-agent-BR8EpIOX.js → use-eve-agent-CxPlg0KL.js} +0 -1
  4. package/dist/src/chunks/{use-eve-agent-XnfjQt1Z.js → use-eve-agent-D-KQzzyW.js} +0 -1
  5. package/dist/src/cli/commands/trace-detail.js +1 -1
  6. package/dist/src/cli/commands/trace.d.ts +2 -2
  7. package/dist/src/cli/commands/trace.js +3 -3
  8. package/dist/src/cli/dev/tui/runner.js +1 -1
  9. package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
  10. package/dist/src/cli/dev/tui/traces/trace-content.d.ts +1 -3
  11. package/dist/src/cli/dev/tui/traces/trace-content.js +2 -2
  12. package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +5 -5
  13. package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
  14. package/dist/src/cli/dev/tui/traces/trace-view.js +1 -1
  15. package/dist/src/cli/dev/tui/traces/trace-viewer-session.js +1 -1
  16. package/dist/src/client/agent-info-schema.d.ts +0 -1
  17. package/dist/src/client/agent-info-schema.js +1 -1
  18. package/dist/src/compiled/.vendor-stamp.json +1 -1
  19. package/dist/src/compiled/@opentelemetry/api/index.d.ts +1 -0
  20. package/dist/src/compiler/default-tool-policy.js +1 -1
  21. package/dist/src/compiler/extension-compatibility.d.ts +4 -4
  22. package/dist/src/compiler/extension-compatibility.js +1 -1
  23. package/dist/src/compiler/manifest.js +1 -1
  24. package/dist/src/context/dynamic-instruction-lifecycle.d.ts +2 -1
  25. package/dist/src/context/dynamic-instruction-lifecycle.js +1 -1
  26. package/dist/src/context/keys.d.ts +3 -1
  27. package/dist/src/context/keys.js +1 -1
  28. package/dist/src/context/memory-event-lifecycle.d.ts +2 -0
  29. package/dist/src/context/memory-event-lifecycle.js +1 -1
  30. package/dist/src/context/memory-lifecycle.d.ts +5 -0
  31. package/dist/src/context/memory-lifecycle.js +1 -1
  32. package/dist/src/eve-channel/index.js +1 -1
  33. package/dist/src/execution/cancelled-model-call-batch.js +1 -1
  34. package/dist/src/execution/cancelled-turn-message.js +1 -1
  35. package/dist/src/execution/compaction.d.ts +2 -2
  36. package/dist/src/execution/coordination-dispatch-shared.d.ts +0 -1
  37. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  38. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  39. package/dist/src/execution/create-session-step.js +1 -1
  40. package/dist/src/execution/durable-session-store.d.ts +2 -2
  41. package/dist/src/execution/eve-workflow-attributes.d.ts +3 -3
  42. package/dist/src/execution/next-driver-action.d.ts +2 -0
  43. package/dist/src/execution/parked-delivery-wait.js +1 -1
  44. package/dist/src/execution/route-child-delivery.js +1 -1
  45. package/dist/src/execution/runtime-context.js +1 -1
  46. package/dist/src/execution/session.d.ts +0 -2
  47. package/dist/src/execution/session.js +2 -2
  48. package/dist/src/execution/tasks/parent/dispatch.d.ts +1 -12
  49. package/dist/src/execution/tasks/parent/dispatch.js +1 -1
  50. package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +5 -1
  51. package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
  52. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  53. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  54. package/dist/src/execution/tools/subagent/invoke-agent.d.ts +1 -2
  55. package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
  56. package/dist/src/execution/tools/subagent/invoke-step.d.ts +4 -0
  57. package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
  58. package/dist/src/execution/tools/subagent/start.d.ts +2 -2
  59. package/dist/src/execution/tools/subagent/start.js +1 -1
  60. package/dist/src/execution/tools/subagent/task-agent-requests.js +1 -1
  61. package/dist/src/execution/tools/tasks.d.ts +1 -8
  62. package/dist/src/execution/tools/tasks.js +1 -1
  63. package/dist/src/execution/tools/todo.d.ts +2 -2
  64. package/dist/src/execution/tools/todo.js +2 -2
  65. package/dist/src/execution/turn-workflow.js +1 -1
  66. package/dist/src/execution/workflow-runtime.js +1 -1
  67. package/dist/src/execution/workflow-steps.js +1 -1
  68. package/dist/src/framework/sources/registry.js +1 -1
  69. package/dist/src/harness/compaction.js +1 -1
  70. package/dist/src/harness/coordination.js +1 -1
  71. package/dist/src/harness/current-messages.d.ts +7 -6
  72. package/dist/src/harness/current-messages.js +1 -1
  73. package/dist/src/harness/emission.js +1 -1
  74. package/dist/src/harness/execute-tool.d.ts +2 -4
  75. package/dist/src/harness/messages.d.ts +36 -0
  76. package/dist/src/harness/messages.js +1 -1
  77. package/dist/src/harness/model-call-error.d.ts +5 -0
  78. package/dist/src/harness/model-call-error.js +1 -1
  79. package/dist/src/harness/semantic-errors/rules/model-provider.js +1 -1
  80. package/dist/src/harness/session-limit-enforcement.d.ts +2 -15
  81. package/dist/src/harness/step-hooks.d.ts +2 -1
  82. package/dist/src/harness/step-hooks.js +1 -1
  83. package/dist/src/harness/tool-loop.js +2 -2
  84. package/dist/src/harness/types.d.ts +6 -4
  85. package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -1
  86. package/dist/src/instrumentation/background-task-runtime.d.ts +18 -0
  87. package/dist/src/instrumentation/background-task-runtime.js +1 -0
  88. package/dist/src/instrumentation/channel-delivery.js +1 -1
  89. package/dist/src/instrumentation/content.js +1 -1
  90. package/dist/src/instrumentation/dispatch.js +1 -1
  91. package/dist/src/instrumentation/lifecycle.d.ts +19 -2
  92. package/dist/src/instrumentation/lifecycle.js +1 -1
  93. package/dist/src/instrumentation/memory.d.ts +72 -0
  94. package/dist/src/instrumentation/memory.js +1 -0
  95. package/dist/src/instrumentation/native-events.d.ts +7 -0
  96. package/dist/src/instrumentation/native-events.js +1 -1
  97. package/dist/src/instrumentation/parent-lineage.d.ts +2 -2
  98. package/dist/src/instrumentation/parent-lineage.js +1 -1
  99. package/dist/src/instrumentation/prepare-trace-context.d.ts +3 -11
  100. package/dist/src/instrumentation/prepare-trace-context.js +1 -1
  101. package/dist/src/instrumentation/principal-summary.d.ts +11 -0
  102. package/dist/src/instrumentation/principal-summary.js +1 -0
  103. package/dist/src/instrumentation/provider.d.ts +1 -0
  104. package/dist/src/instrumentation/runtime.d.ts +11 -7
  105. package/dist/src/instrumentation/runtime.js +1 -1
  106. package/dist/src/instrumentation/session-context.d.ts +22 -0
  107. package/dist/src/instrumentation/session-context.js +1 -0
  108. package/dist/src/instrumentation/state.d.ts +7 -2
  109. package/dist/src/instrumentation/state.js +1 -1
  110. package/dist/src/internal/application/package.js +1 -1
  111. package/dist/src/internal/logging.js +1 -1
  112. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  113. package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +4 -5
  114. package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
  115. package/dist/src/protocol/baggage.d.ts +15 -2
  116. package/dist/src/protocol/baggage.js +1 -1
  117. package/dist/src/public/instrumentation/index.d.ts +5 -4
  118. package/dist/src/runtime/agent/bootstrap.d.ts +2 -2
  119. package/dist/src/runtime/agent/bootstrap.js +1 -1
  120. package/dist/src/self-modification/agent.js +1 -1
  121. package/dist/src/self-modification/extension/instructions.js +21 -20
  122. package/dist/src/self-modification/extension/tools/edit_file.js +1 -1
  123. package/dist/src/self-modification/extension/tools/search_registry.d.ts +1 -1
  124. package/dist/src/self-modification/extension/tools/search_registry.js +1 -1
  125. package/dist/src/setup/integrations/self-modification/setup.js +1 -1
  126. package/dist/src/setup/scaffold/create/project.js +1 -1
  127. package/dist/src/shared/action-types.d.ts +4 -0
  128. package/dist/src/shared/action-types.js +1 -1
  129. package/dist/src/shared/dispatch-action.d.ts +1 -1
  130. package/dist/src/shared/memory-state.js +1 -1
  131. package/dist/src/shared/serialized-observability-state.d.ts +12 -0
  132. package/dist/src/shared/serialized-observability-state.js +1 -0
  133. package/dist/src/subagents/callback-route.js +1 -1
  134. package/dist/src/subagents/callback-step.d.ts +0 -8
  135. package/dist/src/subagents/callback-step.js +1 -1
  136. package/dist/src/subagents/invocation.d.ts +9 -0
  137. package/dist/src/subagents/remote-dispatch.d.ts +3 -3
  138. package/dist/src/subagents/remote-dispatch.js +1 -1
  139. package/dist/src/subagents/start-local.d.ts +2 -6
  140. package/dist/src/subagents/start-local.js +1 -1
  141. package/dist/src/subagents/start-remote.d.ts +2 -8
  142. package/dist/src/subagents/start-remote.js +1 -1
  143. package/dist/src/subagents/tool.d.ts +3 -13
  144. package/dist/src/subagents/tool.js +1 -1
  145. package/dist/src/svelte/index.js +1 -1
  146. package/dist/src/svelte/use-eve-agent.js +1 -1
  147. package/dist/src/tasks/delivery-context.d.ts +12 -3
  148. package/dist/src/tasks/delivery-context.js +2 -2
  149. package/dist/src/tasks/session-index.d.ts +6 -3
  150. package/dist/src/tasks/session-index.js +1 -1
  151. package/dist/src/tasks/session-task-cohorts.d.ts +10 -2
  152. package/dist/src/tasks/session-task-cohorts.js +1 -1
  153. package/dist/src/tools/behavior.d.ts +1 -3
  154. package/dist/src/tools/framework/task-contract.d.ts +0 -4
  155. package/dist/src/tools/framework/task-contract.js +1 -1
  156. package/dist/src/tracing/agent-action-instrumentation.d.ts +3 -2
  157. package/dist/src/tracing/agent-action-instrumentation.js +1 -1
  158. package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
  159. package/dist/src/tracing/agent-channel-delivery-instrumentation.d.ts +1 -6
  160. package/dist/src/tracing/agent-channel-delivery-instrumentation.js +1 -1
  161. package/dist/src/tracing/agent-invocation-coordinator.d.ts +28 -0
  162. package/dist/src/tracing/agent-invocation-coordinator.js +1 -0
  163. package/dist/src/tracing/agent-invocation-terminal.d.ts +18 -0
  164. package/dist/src/tracing/agent-invocation-terminal.js +1 -0
  165. package/dist/src/tracing/agent-memory-instrumentation.d.ts +13 -0
  166. package/dist/src/tracing/agent-memory-instrumentation.js +1 -0
  167. package/dist/src/tracing/agent-otel-attributes.d.ts +4 -0
  168. package/dist/src/tracing/agent-otel-attributes.js +1 -0
  169. package/dist/src/tracing/agent-otel-content.d.ts +4 -12
  170. package/dist/src/tracing/agent-otel-content.js +3 -3
  171. package/dist/src/tracing/agent-otel-provider.d.ts +4 -6
  172. package/dist/src/tracing/agent-otel-provider.js +2 -2
  173. package/dist/src/tracing/agent-otel-runtime-context.d.ts +9 -0
  174. package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
  175. package/dist/src/tracing/agent-otel-session-context.d.ts +4 -3
  176. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  177. package/dist/src/tracing/agent-otel-usage.d.ts +4 -10
  178. package/dist/src/tracing/agent-otel-usage.js +1 -1
  179. package/dist/src/tracing/agent-span-contract.d.ts +26 -0
  180. package/dist/src/tracing/agent-span-contract.js +1 -0
  181. package/dist/src/tracing/agent-span-error.d.ts +3 -0
  182. package/dist/src/tracing/agent-span-error.js +1 -0
  183. package/dist/src/tracing/agent-span-id-generator.d.ts +3 -0
  184. package/dist/src/tracing/agent-span-id-generator.js +1 -1
  185. package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
  186. package/dist/src/tracing/agent-trace-context-codec.d.ts +12 -0
  187. package/dist/src/tracing/agent-trace-context-codec.js +1 -0
  188. package/dist/src/tracing/agent-trace-context-store.d.ts +35 -8
  189. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  190. package/dist/src/tracing/agent-trace-span-processor.d.ts +5 -7
  191. package/dist/src/tracing/agent-trace-span-processor.js +1 -1
  192. package/dist/src/tracing/agent-trace-state.d.ts +43 -3
  193. package/dist/src/tracing/agent-trace-state.js +1 -1
  194. package/dist/src/tracing/bounded-error.d.ts +1 -0
  195. package/dist/src/tracing/bounded-error.js +1 -0
  196. package/dist/src/tracing/content-attributes.js +1 -1
  197. package/dist/src/tracing/content-span-processor.js +1 -1
  198. package/dist/src/tracing/conversation-context.d.ts +4 -0
  199. package/dist/src/tracing/conversation-context.js +1 -0
  200. package/dist/src/tracing/error-content-context.d.ts +3 -0
  201. package/dist/src/tracing/error-content-context.js +1 -0
  202. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  203. package/dist/src/tracing/local-trace-reader.d.ts +6 -6
  204. package/dist/src/tracing/local-trace-reader.js +1 -1
  205. package/dist/src/tracing/local-traces.d.ts +6 -8
  206. package/dist/src/tracing/local-traces.js +1 -1
  207. package/dist/src/tracing/otel-declaration.d.ts +5 -3
  208. package/dist/src/tracing/otel-registration.d.ts +2 -1
  209. package/dist/src/tracing/otel-registration.js +1 -1
  210. package/dist/src/tracing/telemetry-budget.d.ts +4 -0
  211. package/dist/src/tracing/telemetry-budget.js +1 -0
  212. package/dist/src/vue/index.js +1 -1
  213. package/dist/src/vue/use-eve-agent.js +1 -1
  214. package/docs/concepts/built-in-tools.md +0 -20
  215. package/docs/concepts/sessions-runs-and-streaming.md +9 -1
  216. package/docs/guides/frontend/overview.mdx +1 -1
  217. package/docs/guides/instrumentation-providers.md +5 -0
  218. package/docs/guides/instrumentation.md +179 -23
  219. package/docs/guides/remote-agents.md +11 -0
  220. package/docs/reference/cli.md +16 -14
  221. package/docs/subagents/index.mdx +15 -10
  222. package/package.json +1 -6
  223. package/dist/src/execution/tasks/child/update-step.d.ts +0 -6
  224. package/dist/src/execution/tasks/child/update-step.js +0 -1
  225. package/dist/src/execution/tasks/child/update.d.ts +0 -8
  226. package/dist/src/execution/tasks/child/update.js +0 -1
  227. package/dist/src/public/tools/task-update.d.ts +0 -1
  228. package/dist/src/public/tools/task-update.js +0 -1
  229. package/dist/src/tools/framework/task-update.d.ts +0 -5
  230. package/dist/src/tools/framework/task-update.js +0 -1
@@ -1,39 +1,40 @@
1
- import{resolveSelfModificationConfig}from"../config.js";import{resolveSelfModificationMode}from"../mode.js";import extension_default from"./extension.js";import{defineDynamic,defineInstructions}from"eve/instructions";const introduction=`You are an expert coding assistant operating inside of an eve agent. You help users by reading files, editing code, and writing new files that shape the behavior of the agent itself.
1
+ import{resolveSelfModificationConfig}from"../config.js";import{resolveSelfModificationMode}from"../mode.js";import extension_default from"./extension.js";import{defineDynamic,defineInstructions}from"eve/instructions";function readSubagentSourceGuidance(e){let t=e.data?.invocation;return t?.kind!==`subagent`||t.name===void 0?``:`Your authored self-modification subagent source is mounted at ${`/source/subagents/${t.name}`}. For changes to this subagent itself, inspect that directory directly instead of searching /source. Its agent.ts owns agent options such as model; config.ts owns policy shared by the self-modification agent, sandbox, and extension.`}function readTrace(e){return e.data?.trace}function localTraceGuidance(e){let t=readTrace(e);return t===void 0?``:`The invoking trace has ID ${t.traceId}. ${(t.traceFlags&1)==1?`If local segments were captured,`:`This trace was not sampled, so local segments may be absent. If any are present,`} inspect them at /traces/${t.traceId}.`}function renderInstructions(e){return e.filter(e=>e.length>0).join(`
2
2
 
3
- The source code of the eve agent is mounted read-write at /source. Use bash only for read-only discovery and available validation commands. Never modify source files with bash, sed, awk, redirection, or scripting. /source is the authored agent directory.
3
+ `)}var instructions_default=defineDynamic({events:{"session.started":e=>{let t=resolveSelfModificationMode(resolveSelfModificationConfig(extension_default.config));return t!==`local`&&t!==`deployed`?null:defineInstructions({markdown:renderInstructions([`## Role
4
4
 
5
- Use selfmod__edit_file for precise changes to existing files; every edits[].oldText must match exactly. When changing multiple separate locations in one file, use one call with multiple entries in edits[]. Each oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits; merge nearby changes into one edit. Keep oldText as small as possible while still being unique. Use write_file only for new files or complete rewrites.
5
+ You are an expert coding assistant operating inside of an eve agent. You help users by reading files, editing code, and writing new files that shape the behavior of the agent itself.`,`## Source workspace
6
6
 
7
- Use selfmod__search_models to get the list of available models.`,workingGuidance=`Batch independent read-only tool calls and edits to different files in one response. Do not edit the same file concurrently.
7
+ The source code of the eve agent is mounted read-write at /source. /source is the authored agent directory. Locate source files with bash. Read source contents with read_file, not shell commands. Before generating an overwrite, ensure read_file has succeeded for that path. Shell reads do not satisfy write_file's read-before-write requirement. selfmod__edit_file instead validates exact matches against current contents. Never modify source files with bash, sed, awk, redirection, or scripting.
8
8
 
9
- Run selfmod__registry_add separately from file edits and other registry installations. Complete all edits and registry installations before publication, and call publish by itself.
9
+ Resolve named tools by filename under /source/tools before searching contents. Tool identifiers derive from filenames and may not occur in the implementation.`,readSubagentSourceGuidance(e),`## Implement changes
10
10
 
11
- Skip task lists for simple work - only use them for complex actions. Never spend a turn only reporting status or updating the task list - batch them with other calls.
11
+ Use selfmod__edit_file for localized changes; include only the unique matching text. For a complete rewrite, use read_file then write_file; do not encode the whole old file as one replacement. If tool arguments fail argument parsing, retry the same tool with corrected encoding.
12
12
 
13
- Registry installation is outside the source sandbox.
13
+ Once paths are known, batch independent file reads and edits to different files. Never edit the same file concurrently.`,`## Add integrations
14
14
 
15
- The eve framework documentation is mounted read-only at /eve-docs. Read the eve guide directly relevant to an unfamiliar public API. Prefer an existing local implementation pattern over broad documentation research.`,developmentMarkdown=`${introduction}
15
+ Before adding a new eve-managed channel, connection, extension, instrumentation, or memory integration, call selfmod__search_registry alongside source discovery. If an item fulfills the requirement, install it with selfmod__registry_add using its exact address. If no matching item fulfills the requirement, or if the developer asks for a custom implementation, write the integration yourself.
16
16
 
17
- Before writing an integration by hand, check whether the eve registry already ships it with selfmod__search_registry. If it has an item that fulfills the requirement, install it with selfmod__registry_add using its address. If the registry does not have any matches that will fulfill the requirement, or if the developer asks for a custom implementation, write the integration yourself.
17
+ Modifying the behavior of an existing skill or tool does not require a registry search. Registry search blocks implementation, not source inspection. Serialize registry installation and dependent edits. Run selfmod__registry_add separately from file edits and other registry installations.
18
18
 
19
- The selfmod__registry_add tool will complete installation for items that need no setup. In the local dev TUI, a \`needs-terminal\` result from the tool call automatically opens the existing setup panel for the user to complete setup there. In headless development, relay the terminal command the tool names.
19
+ Registry installation is outside the source sandbox.`,`## Consult documentation
20
20
 
21
- ${workingGuidance}
21
+ The eve framework documentation is mounted read-only at /eve-docs. Prefer source and existing local patterns. Before reading docs, identify the specific unresolved API question. Search the relevant file for its heading or term, then read only the bounded surrounding section. Do not concatenate wildcard files or read a full page when a section answers the question. Stop when the question is resolved.`,t===`local`?`## Local environment
22
22
 
23
- Local eve dev logs are available read-only at /logs.
23
+ The selfmod__registry_add tool will complete installation for items that need no setup. In the local dev TUI, a \`needs-terminal\` result from the tool call automatically opens the existing setup panel for the user to complete setup there. In headless development, relay the terminal command the tool names.
24
24
 
25
- You cannot access application files outside the authored agent directory or run host binaries such as git, node, pnpm, or tsc.
25
+ Local eve dev logs are available read-only at /logs.
26
+ Local trace segments are mounted read-only at /traces when available. Inspect other traces only when the user asks about another session or broader behavior.
26
27
 
27
- Treat a successful file-edit tool result as confirmation; do not reread a file solely to verify that the edit succeeded. Do not approximate unavailable build or test commands with broad source searches.
28
+ The application package.json is not mounted. Do not search outside /source for application files. You cannot run host binaries such as git, node, pnpm, or tsc. Use existing imports and selfmod__registry_add for supported registry installations.`:"## Deployed environment\n\nThe selfmod__registry_add tool may return `completed`, `input-required`, `external-action-required`, `cancelled`, or `failed`. Supply only non-secret structured answers when continuing an `input-required` setup; set `installed: true` so the continuation does not reinstall source. Never request, accept, or repeat secret values. External authorization and secret binding are incomplete follow-up boundaries, not evidence that an integration is active.\n\nThe configured target branch is checked out as a disposable workspace under /workspace/repository. Make ordinary changes through /source, which is the writable view of the configured application's agent/ directory. Publication validates the final repository snapshot, including registry, manifest, and lockfile changes. Never modify Git refs, access GitHub directly, or use shell commands to write files. The sandbox has no reusable GitHub credential after checkout.\n\nComplete all edits and registry installations before publication, and call publish by itself. Before publication, review and summarize the complete intended scope. Call publish once with a concise title and summary. A successful result is only a draft pull request. Return its URL and changed paths, and state that merge and deployment have not occurred.",t===`local`?localTraceGuidance(e):``,`## Work efficiently
28
29
 
29
- Local trace segments are mounted read-only at /traces when available. Inspect other traces only when the user asks about another session or broader behavior.`,developmentInstructions=defineInstructions({markdown:developmentMarkdown}),deployedInstructions=defineInstructions({markdown:`${introduction}
30
+ Skip task lists for simple work - only use them for complex actions. Never spend a turn only reporting status or updating the task list - batch them with other calls.
30
31
 
31
- Before writing an integration by hand, check whether the official eve registry already ships it with selfmod__search_registry. If it has a suitable item, call selfmod__registry_add with the exact address. The tool may return \`completed\`, \`input-required\`, \`external-action-required\`, \`cancelled\`, or \`failed\`. Supply only non-secret structured answers when continuing an \`input-required\` setup; set \`installed: true\` so the continuation does not reinstall source. Never request, accept, or repeat secret values. External authorization and secret binding are incomplete follow-up boundaries, not evidence that an integration is active.
32
+ Treat a successful file-edit tool result as confirmation; do not reread a file solely to verify that the edit succeeded. Do not approximate unavailable build or test commands with broad source searches.`,t===`local`?`## Report results
32
33
 
33
- ${workingGuidance}
34
+ For source-modification tasks, return a concise handoff to the caller. Use at most four short bullets covering changed paths and behavior, and any required setup or unresolved issues.
34
35
 
35
- The configured target branch is checked out as a disposable workspace under /workspace/repository. Make ordinary changes through /source, which is the writable view of the configured application's agent/ directory. Publication validates the final repository snapshot, including registry, manifest, and lockfile changes. Never modify Git refs, access GitHub directly, or use shell commands to write files. The sandbox has no reusable GitHub credential after checkout.
36
+ For investigation tasks, report the findings and supporting evidence requested by the caller.`:`## Report results
36
37
 
37
- Before publication, review and summarize the complete intended scope. Call publish once with a concise title and summary. A successful result is only a draft pull request. Return its URL and changed paths, and state that merge and deployment have not occurred.
38
+ For source-modification tasks, return a concise handoff to the caller. Use at most four short bullets covering changed paths and behavior, and any required setup or unresolved issues. Include the draft pull request URL if one was published.
38
39
 
39
- Treat a successful file-edit tool result as confirmation; do not reread a file solely to verify that the edit succeeded. Do not approximate unavailable build or test commands with broad source searches.`});function readTrace(e){return e.data?.trace}var instructions_default=defineDynamic({events:{"session.started":e=>{let t=resolveSelfModificationMode(resolveSelfModificationConfig(extension_default.config));if(t===`deployed`)return deployedInstructions;if(t!==`local`)return null;let n=readTrace(e);if(n===void 0)return developmentInstructions;let r=(n.traceFlags&1)==1?`If local segments were captured,`:`This trace was not sampled, so local segments may be absent. If any are present,`;return defineInstructions({markdown:`${developmentMarkdown}\n\nThe invoking trace has ID ${n.traceId}. ${r} inspect them at /traces/${n.traceId}.`})}}});export{instructions_default as default};
40
+ For investigation tasks, report the findings and supporting evidence requested by the caller.`])})}}});export{instructions_default as default};
@@ -1 +1 @@
1
- import{defineTool}from"eve/tools";const inputSchema={type:`object`,additionalProperties:!1,properties:{path:{type:`string`,minLength:1,description:`Absolute path below /source to edit.`},edits:{type:`array`,minItems:1,items:{type:`object`,additionalProperties:!1,properties:{oldText:{type:`string`,minLength:1,description:`Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.`},newText:{type:`string`,description:`Replacement text for this targeted edit.`}},required:[`oldText`,`newText`]},description:`One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.`}},required:[`path`,`edits`]},outputSchema={type:`object`,additionalProperties:!1,properties:{path:{type:`string`},replacements:{type:`integer`,minimum:1}},required:[`path`,`replacements`]};function applyExactEdits(e,t){if(t.length===0)throw Error(`edits must contain at least one replacement.`);let n=[...t.map((t,n)=>{if(t.oldText.length===0)throw Error(`edits[${n}].oldText must not be empty.`);let r=e.indexOf(t.oldText);if(r===-1)throw Error(`edits[${n}].oldText was not found in the current file. Read the file and try again.`);if(e.indexOf(t.oldText,r+1)!==-1)throw Error(`edits[${n}].oldText occurs more than once. Include more surrounding text to make it unique.`);return{...t,end:r+t.oldText.length,index:n,start:r}})].sort((e,t)=>e.start-t.start);for(let e=1;e<n.length;e+=1){let t=n[e-1],r=n[e];if(t!==void 0&&r!==void 0&&r.start<t.end)throw Error(`edits[${t.index}] and edits[${r.index}] overlap. Merge them into one edit.`)}return n.toReversed().reduce((e,t)=>e.slice(0,t.start)+t.newText+e.slice(t.end),e)}var edit_file_default=defineTool({description:`Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.`,inputSchema,outputSchema,async execute(e,t){let{edits:n,path:r}=e;if(typeof r!=`string`||!Array.isArray(n)||n.some(e=>typeof e!=`object`||!e||typeof e.oldText!=`string`||typeof e.newText!=`string`))throw Error(`path must be a string and edits must contain oldText and newText strings.`);let i=await t.getSandbox(),a=i.resolvePath(r);if(!a.startsWith(`/source/`)||a.split(`/`).some(e=>e===`..`))throw Error(`Self-modification file edits must stay below /source.`);let o=await i.readTextFile({path:a});if(o===null)throw Error(`File not found: ${r}.`);if(o.includes(`\0`))throw Error(`File "${r}" contains NUL bytes and appears to be binary.`);return await i.writeTextFile({content:applyExactEdits(o,n),path:a}),{path:a,replacements:n.length}}});export{applyExactEdits,edit_file_default as default};
1
+ import{defineTool}from"eve/tools";const inputSchema={type:`object`,additionalProperties:!1,properties:{path:{type:`string`,minLength:1,description:`Absolute path below /source to edit.`},edits:{type:`array`,minItems:1,items:{type:`object`,additionalProperties:!1,properties:{oldText:{type:`string`,minLength:1,description:`Unique exact text from the current file. Encode control characters, quotes, and backslashes as JSON escapes.`},newText:{type:`string`,description:`Exact replacement text. Encode control characters, quotes, and backslashes as JSON escapes.`}},required:[`oldText`,`newText`]},description:`One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.`}},required:[`path`,`edits`]},outputSchema={type:`object`,additionalProperties:!1,properties:{path:{type:`string`},replacements:{type:`integer`,minimum:1}},required:[`path`,`replacements`]};function applyExactEdits(e,t){if(t.length===0)throw Error(`edits must contain at least one replacement.`);let n=[...t.map((t,n)=>{if(t.oldText.length===0)throw Error(`edits[${n}].oldText must not be empty.`);let r=e.indexOf(t.oldText);if(r===-1)throw Error(`edits[${n}].oldText was not found in the current file. Read the file and try again.`);if(e.indexOf(t.oldText,r+1)!==-1)throw Error(`edits[${n}].oldText occurs more than once. Include more surrounding text to make it unique.`);return{...t,end:r+t.oldText.length,index:n,start:r}})].sort((e,t)=>e.start-t.start);for(let e=1;e<n.length;e+=1){let t=n[e-1],r=n[e];if(t!==void 0&&r!==void 0&&r.start<t.end)throw Error(`edits[${t.index}] and edits[${r.index}] overlap. Merge them into one edit.`)}return n.toReversed().reduce((e,t)=>e.slice(0,t.start)+t.newText+e.slice(t.end),e)}var edit_file_default=defineTool({description:`Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.`,inputSchema,outputSchema,async execute(e,t){let{edits:n,path:r}=e;if(typeof r!=`string`||!Array.isArray(n)||n.some(e=>typeof e!=`object`||!e||typeof e.oldText!=`string`||typeof e.newText!=`string`))throw Error(`path must be a string and edits must contain oldText and newText strings.`);let i=await t.getSandbox(),a=i.resolvePath(r);if(!a.startsWith(`/source/`)||a.split(`/`).some(e=>e===`..`))throw Error(`Self-modification file edits must stay below /source.`);let o=await i.readTextFile({path:a});if(o===null)throw Error(`File not found: ${r}.`);if(o.includes(`\0`))throw Error(`File "${r}" contains NUL bytes and appears to be binary.`);return await i.writeTextFile({content:applyExactEdits(o,n),path:a}),{path:a,replacements:n.length}}});export{applyExactEdits,edit_file_default as default};
@@ -1,6 +1,6 @@
1
1
  import { type ToolContext } from "eve/tools";
2
2
  /** Registry categories an integration search can be narrowed to. */
3
- declare const CATEGORIES: readonly ["channel", "connection", "extension", "instrumentation"];
3
+ declare const CATEGORIES: readonly ["channel", "connection", "extension", "instrumentation", "memory"];
4
4
  type Category = (typeof CATEGORIES)[number];
5
5
  /** One catalog entry, narrowed from the published registry index. */
6
6
  export interface CatalogEntry {
@@ -1 +1 @@
1
- import{defineTool}from"eve/tools";const CATEGORIES=[`channel`,`connection`,`extension`,`instrumentation`],INDEX_PATH=`/registry.json`,FETCH_TIMEOUT_MS=1e4,inputSchema={type:`object`,additionalProperties:!1,properties:{query:{type:`string`,maxLength:200,description:`Free-text match against integration names, titles, and descriptions.`},category:{type:`string`,enum:[...CATEGORIES],description:`Restrict results to one registry category.`},limit:{type:`integer`,minimum:1,maximum:25,description:`Maximum number of items to return (default 10, maximum 25).`},offset:{type:`integer`,minimum:0,description:`Number of matching items to skip. Use nextOffset from a prior result to retrieve the next page.`}}},outputSchema={type:`object`,additionalProperties:!1,properties:{items:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{address:{type:`string`},title:{type:`string`},description:{type:`string`},category:{type:`string`},components:{type:`array`,items:{type:`string`}},requires:{type:`string`},installed:{type:`boolean`}},required:[`address`,`title`]}},errors:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{registry:{type:`string`},message:{type:`string`}},required:[`registry`,`message`]}},total:{type:`integer`},hasMore:{type:`boolean`},nextOffset:{type:`integer`}},required:[`items`,`errors`,`total`,`hasMore`]};function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function optionalString(e){return typeof e==`string`&&e.length>0?e:void 0}function isCategory(e){return CATEGORIES.includes(e)}function categoryOf(e){let t=e.split(`/`)[0];return t!==void 0&&e.includes(`/`)&&isCategory(t)?t:void 0}function titleFromAddress(e){return(e.split(`/`).at(-1)??e).split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function eveMetadata(e){let t=e.meta;if(!isRecord(t))return{};let n=t.eve;return isRecord(n)?n:{}}function componentMetadata(e){let t=e.components;if(!Array.isArray(t))return;let n=[],r=[];for(let e of t){if(!isRecord(e))continue;let t=optionalString(e.item);if(t===void 0)continue;n.push(t),r.push(t);let i=optionalString(e.label);i!==void 0&&r.push(i);let a=optionalString(e.description);a!==void 0&&r.push(a)}return n.length>0?{addresses:n,searchTerms:r}:void 0}function authoredTargetOf(e){let t=e.files;if(Array.isArray(t))for(let e of t){if(!isRecord(e))continue;let t=optionalString(e.target);if(t?.startsWith(`agent/`)===!0)return t}}function declaredEnvVars(e){let t=e.envVars;return isRecord(t)?Object.keys(t):[]}function parseRegistryIndex(e){if(!isRecord(e)||!Array.isArray(e.items))return[];let t=[];for(let n of e.items){if(!isRecord(n))continue;let e=optionalString(n.name);if(e===void 0)continue;let r=eveMetadata(n);if(r.hidden===!0)continue;let i={address:e,title:optionalString(n.title)??titleFromAddress(e)},a=categoryOf(e);a!==void 0&&(i.category=a);let o=optionalString(n.description);o!==void 0&&(i.description=o);let s=componentMetadata(r);s!==void 0&&(i.components=s.addresses,i.componentSearchTerms=s.searchTerms);let c=optionalString(r.requires);c!==void 0&&(i.requires=c);let l=authoredTargetOf(n);l!==void 0&&(i.authoredTarget=l),r.setup!==void 0&&r.setup!==null&&(i.declaresSetup=!0);let u=declaredEnvVars(n);u.length>0&&(i.envVars=u),t.push(i)}return t}function selectIntegrations(e){return selectIntegrationPage(e).items}function selectIntegrationPage(e){let t=Math.min(Math.max(e.limit??10,1),25),n=Math.max(e.offset??0,0),r=(e.query??``).toLowerCase().split(/\s+/u).filter(e=>e.length>0),i=e.entries.map((e,t)=>{let n=`${e.address} ${e.title}`.toLowerCase();return{entry:e,haystack:[n,e.description??``,...e.componentSearchTerms??e.components??[]].join(` `).toLowerCase(),index:t,primaryTerms:n}}),a=new Map(r.map(e=>{let t=i.filter(({haystack:t})=>t.includes(e)).length;return[e,Math.log((i.length+1)/(t+1))+1]})),o=i.map(({entry:t,haystack:n,index:i,primaryTerms:o})=>{if(e.category!==void 0&&!matchesCategory(t,e.category))return;if(r.length===0)return{entry:t,index:i,score:0};let s=r.reduce((e,t)=>{let r=a.get(t)??0;return o.includes(t)?e+2*r:n.includes(t)?e+r:e},0);return s>0?{entry:t,index:i,score:s}:void 0}).filter(e=>e!==void 0).sort((e,t)=>t.score-e.score||e.index-t.index),s=(o[0]?.score??0)*.4,c=o.filter(({score:e})=>e>=s),l=c.slice(n,n+t).map(({entry:e})=>{let t={address:e.address,title:e.title};return e.category!==void 0&&(t.category=e.category),e.components!==void 0&&(t.components=e.components),e.description!==void 0&&(t.description=e.description),e.requires!==void 0&&(t.requires=e.requires),t}),u=n+l.length,d={hasMore:u<c.length,items:l,total:c.length};return u<c.length&&(d.nextOffset=u),d}function matchesCategory(e,t){return e.category===t||e.components?.some(e=>categoryOf(e)===t)===!0}function officialRegistryIndexUrl(){return`https://eve.dev/r${INDEX_PATH}`}function resolveRegistryIndexUrl(e=process.env.EVE_DEV_OFFICIAL_REGISTRY_URL){if(e===void 0)return officialRegistryIndexUrl();let t;try{t=new URL(e)}catch{throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`);if(t.username!==``||t.password!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include credentials.`);if(t.search!==``||t.hash!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include a query or fragment.`);return t.pathname=`${t.pathname.replace(/\/+$/u,``)}${INDEX_PATH}`,t.toString()}let cache;function clearRegistryIndexCache(){cache=void 0}async function loadRegistryIndex(e){if(cache!==void 0&&cache.url===e.url&&e.nowMs-cache.fetchedAtMs<3e5)return cache.entries;let t=await fetch(e.url,{headers:{accept:`application/json`},signal:AbortSignal.any(e.signal===void 0?[AbortSignal.timeout(FETCH_TIMEOUT_MS)]:[e.signal,AbortSignal.timeout(FETCH_TIMEOUT_MS)])});if(!t.ok)throw Error(`Could not read the eve registry (${t.status}).`);let n=parseRegistryIndex(await t.json());return cache={entries:n,fetchedAtMs:e.nowMs,url:e.url},n}async function annotateInstalled(e){let t=new Map(e.entries.flatMap(e=>e.authoredTarget===void 0?[]:[[e.address,e.authoredTarget]]));if(e.rows.every(e=>t.get(e.address)===void 0))return e.rows;let n;try{n=await e.ctx.getSandbox()}catch{return e.rows}return await Promise.all(e.rows.map(async e=>{let r=t.get(e.address);if(r===void 0)return e;let i=`/source/${r.slice(6)}`;try{let t=await n.readTextFile({path:i});return{...e,installed:t!==null}}catch{return e}}))}var search_registry_default=defineTool({description:"Search the eve registry for integrations this project can add: channels, MCP connections, extensions, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact item address (for example `channel/slack`) to selfmod__registry_add.",inputSchema,outputSchema,async execute(e,t){let n=[],r;try{r=resolveRegistryIndexUrl()}catch(e){return{errors:[{message:errorMessage(e),registry:`eve`}],hasMore:!1,items:[],total:0}}let i=[];try{i=await loadRegistryIndex({nowMs:Date.now(),signal:t.abortSignal,url:r})}catch(e){n.push({message:errorMessage(e),registry:r})}let a={entries:i},o=typeof e.category==`string`?e.category:void 0;o!==void 0&&isCategory(o)&&(a.category=o),typeof e.limit==`number`&&(a.limit=e.limit),typeof e.offset==`number`&&(a.offset=e.offset),typeof e.query==`string`&&(a.query=e.query);let s=selectIntegrationPage(a),c={errors:n,hasMore:s.hasMore,items:await annotateInstalled({ctx:t,entries:i,rows:s.items}),total:s.total};return s.nextOffset!==void 0&&(c.nextOffset=s.nextOffset),c}});function errorMessage(e){return e instanceof Error?e.message:String(e)}export{clearRegistryIndexCache,search_registry_default as default,loadRegistryIndex,officialRegistryIndexUrl,parseRegistryIndex,resolveRegistryIndexUrl,selectIntegrationPage,selectIntegrations};
1
+ import{defineTool}from"eve/tools";const CATEGORIES=[`channel`,`connection`,`extension`,`instrumentation`,`memory`],INDEX_PATH=`/registry.json`,FETCH_TIMEOUT_MS=1e4,inputSchema={type:`object`,additionalProperties:!1,properties:{query:{type:`string`,maxLength:200,description:`Free-text match against integration names, titles, and descriptions.`},category:{type:`string`,enum:[...CATEGORIES],description:`Restrict results to one registry category.`},limit:{type:`integer`,minimum:1,maximum:25,description:`Maximum number of items to return (default 10, maximum 25).`},offset:{type:`integer`,minimum:0,description:`Number of matching items to skip. Use nextOffset from a prior result to retrieve the next page.`}}},outputSchema={type:`object`,additionalProperties:!1,properties:{items:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{address:{type:`string`},title:{type:`string`},description:{type:`string`},category:{type:`string`},components:{type:`array`,items:{type:`string`}},requires:{type:`string`},installed:{type:`boolean`}},required:[`address`,`title`]}},errors:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{registry:{type:`string`},message:{type:`string`}},required:[`registry`,`message`]}},total:{type:`integer`},hasMore:{type:`boolean`},nextOffset:{type:`integer`}},required:[`items`,`errors`,`total`,`hasMore`]};function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function optionalString(e){return typeof e==`string`&&e.length>0?e:void 0}function isCategory(e){return CATEGORIES.includes(e)}function categoryOf(e){let t=e.split(`/`)[0];return t!==void 0&&e.includes(`/`)&&isCategory(t)?t:void 0}function titleFromAddress(e){return(e.split(`/`).at(-1)??e).split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function eveMetadata(e){let t=e.meta;if(!isRecord(t))return{};let n=t.eve;return isRecord(n)?n:{}}function componentMetadata(e){let t=e.components;if(!Array.isArray(t))return;let n=[],r=[];for(let e of t){if(!isRecord(e))continue;let t=optionalString(e.item);if(t===void 0)continue;n.push(t),r.push(t);let i=optionalString(e.label);i!==void 0&&r.push(i);let a=optionalString(e.description);a!==void 0&&r.push(a)}return n.length>0?{addresses:n,searchTerms:r}:void 0}function authoredTargetOf(e){let t=e.files;if(Array.isArray(t))for(let e of t){if(!isRecord(e))continue;let t=optionalString(e.target);if(t?.startsWith(`agent/`)===!0)return t}}function declaredEnvVars(e){let t=e.envVars;return isRecord(t)?Object.keys(t):[]}function parseRegistryIndex(e){if(!isRecord(e)||!Array.isArray(e.items))return[];let t=[];for(let n of e.items){if(!isRecord(n))continue;let e=optionalString(n.name);if(e===void 0)continue;let r=eveMetadata(n);if(r.hidden===!0)continue;let i={address:e,title:optionalString(n.title)??titleFromAddress(e)},a=categoryOf(e);a!==void 0&&(i.category=a);let o=optionalString(n.description);o!==void 0&&(i.description=o);let s=componentMetadata(r);s!==void 0&&(i.components=s.addresses,i.componentSearchTerms=s.searchTerms);let c=optionalString(r.requires);c!==void 0&&(i.requires=c);let l=authoredTargetOf(n);l!==void 0&&(i.authoredTarget=l),r.setup!==void 0&&r.setup!==null&&(i.declaresSetup=!0);let u=declaredEnvVars(n);u.length>0&&(i.envVars=u),t.push(i)}return t}function selectIntegrations(e){return selectIntegrationPage(e).items}function selectIntegrationPage(e){let t=Math.min(Math.max(e.limit??10,1),25),n=Math.max(e.offset??0,0),r=(e.query??``).toLowerCase().split(/\s+/u).filter(e=>e.length>0),i=e.entries.map((e,t)=>{let n=`${e.address} ${e.title}`.toLowerCase();return{entry:e,haystack:[n,e.description??``,...e.componentSearchTerms??e.components??[]].join(` `).toLowerCase(),index:t,primaryTerms:n}}),a=new Map(r.map(e=>{let t=i.filter(({haystack:t})=>t.includes(e)).length;return[e,Math.log((i.length+1)/(t+1))+1]})),o=i.map(({entry:t,haystack:n,index:i,primaryTerms:o})=>{if(e.category!==void 0&&!matchesCategory(t,e.category))return;if(r.length===0)return{entry:t,index:i,score:0};let s=r.reduce((e,t)=>{let r=a.get(t)??0;return o.includes(t)?e+2*r:n.includes(t)?e+r:e},0);return s>0?{entry:t,index:i,score:s}:void 0}).filter(e=>e!==void 0).sort((e,t)=>t.score-e.score||e.index-t.index),s=(o[0]?.score??0)*.4,c=o.filter(({score:e})=>e>=s),l=c.slice(n,n+t).map(({entry:e})=>{let t={address:e.address,title:e.title};return e.category!==void 0&&(t.category=e.category),e.components!==void 0&&(t.components=e.components),e.description!==void 0&&(t.description=e.description),e.requires!==void 0&&(t.requires=e.requires),t}),u=n+l.length,d={hasMore:u<c.length,items:l,total:c.length};return u<c.length&&(d.nextOffset=u),d}function matchesCategory(e,t){return e.category===t||e.components?.some(e=>categoryOf(e)===t)===!0}function officialRegistryIndexUrl(){return`https://eve.dev/r${INDEX_PATH}`}function resolveRegistryIndexUrl(e=process.env.EVE_DEV_OFFICIAL_REGISTRY_URL){if(e===void 0)return officialRegistryIndexUrl();let t;try{t=new URL(e)}catch{throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`);if(t.username!==``||t.password!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include credentials.`);if(t.search!==``||t.hash!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include a query or fragment.`);return t.pathname=`${t.pathname.replace(/\/+$/u,``)}${INDEX_PATH}`,t.toString()}let cache;function clearRegistryIndexCache(){cache=void 0}async function loadRegistryIndex(e){if(cache!==void 0&&cache.url===e.url&&e.nowMs-cache.fetchedAtMs<3e5)return cache.entries;let t=await fetch(e.url,{headers:{accept:`application/json`},signal:AbortSignal.any(e.signal===void 0?[AbortSignal.timeout(FETCH_TIMEOUT_MS)]:[e.signal,AbortSignal.timeout(FETCH_TIMEOUT_MS)])});if(!t.ok)throw Error(`Could not read the eve registry (${t.status}).`);let n=parseRegistryIndex(await t.json());return cache={entries:n,fetchedAtMs:e.nowMs,url:e.url},n}async function annotateInstalled(e){let t=new Map(e.entries.flatMap(e=>e.authoredTarget===void 0?[]:[[e.address,e.authoredTarget]]));if(e.rows.every(e=>t.get(e.address)===void 0))return e.rows;let n;try{n=await e.ctx.getSandbox()}catch{return e.rows}return await Promise.all(e.rows.map(async e=>{let r=t.get(e.address);if(r===void 0)return e;let i=`/source/${r.slice(6)}`;try{let t=await n.readTextFile({path:i});return{...e,installed:t!==null}}catch{return e}}))}var search_registry_default=defineTool({description:"Search the eve registry for integrations this project can add: channels, MCP connections, extensions, memory providers, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact item address (for example `channel/slack`) to selfmod__registry_add.",inputSchema,outputSchema,async execute(e,t){let n=[],r;try{r=resolveRegistryIndexUrl()}catch(e){return{errors:[{message:errorMessage(e),registry:`eve`}],hasMore:!1,items:[],total:0}}let i=[];try{i=await loadRegistryIndex({nowMs:Date.now(),signal:t.abortSignal,url:r})}catch(e){n.push({message:errorMessage(e),registry:r})}let a={entries:i},o=typeof e.category==`string`?e.category:void 0;o!==void 0&&isCategory(o)&&(a.category=o),typeof e.limit==`number`&&(a.limit=e.limit),typeof e.offset==`number`&&(a.offset=e.offset),typeof e.query==`string`&&(a.query=e.query);let s=selectIntegrationPage(a),c={errors:n,hasMore:s.hasMore,items:await annotateInstalled({ctx:t,entries:i,rows:s.items}),total:s.total};return s.nextOffset!==void 0&&(c.nextOffset=s.nextOffset),c}});function errorMessage(e){return e instanceof Error?e.message:String(e)}export{clearRegistryIndexCache,search_registry_default as default,loadRegistryIndex,officialRegistryIndexUrl,parseRegistryIndex,resolveRegistryIndexUrl,selectIntegrationPage,selectIntegrations};
@@ -1 +1 @@
1
- import{defineSetupIntegration}from"../types.js";import{describeIntegrationSetupEnvironment}from"../shared/environment.js";import{confirm,text}from"#setup/ask.js";import{classifySelfModificationConfig,connectorName,defaultSelfModificationSetupOperations,directoryError,gitRefError,renderSelfModificationConfig,repositoryPartError}from"#self-modification/setup.js";import{SELF_MODIFICATION_CONFIG_PATH}from"#self-modification/git-workspace.js";function validationResult(e){return e??null}async function prepareSelfModificationSetup(e,t=defaultSelfModificationSetupOperations(e.appRoot)){let n=await t.readConfig();if(classifySelfModificationConfig(n)===`authored`)return e.presenter.note(`The existing ${SELF_MODIFICATION_CONFIG_PATH} contains authored configuration and was not overwritten.`,`Manual update required`,{tone:`warning`}),{kind:`authored`};let[r,i]=await Promise.all([t.detectGitRepository(),t.detectChannelNames()]),a=await e.asker.ask(text({key:`self-modification-repository-owner`,message:`GitHub repository owner`,detected:r.owner,required:!0,validate:e=>validationResult(repositoryPartError(e))})),o=await e.asker.ask(text({key:`self-modification-repository-name`,message:`GitHub repository name`,detected:r.repo,required:!0,validate:e=>validationResult(repositoryPartError(e))})),s=await e.asker.ask(text({key:`self-modification-repository-directory`,message:`Application directory relative to the repository root`,detected:r.directory??`.`,required:!0,validate:e=>validationResult(directoryError(e))})),c=await e.asker.ask(text({key:`self-modification-target-branch`,message:`Target branch`,detected:r.branch??`main`,required:!0,validate:e=>validationResult(gitRefError(e))})),l=connectorName(a,o),u={branch:c,channelNames:i,connector:`github/${l}`,directory:s,repository:`github.com/${a}/${o}`,vercelBackend:e.environment.vercel.kind===`available`&&e.environment.vercel.project.kind!==`unresolved`};return e.presenter.note(renderSelfModificationConfig(u),`Generated ${SELF_MODIFICATION_CONFIG_PATH}`),e.presenter.note(`Vercel Connect will issue short-lived GitHub App credentials restricted to this repository. Install the managed GitHub App and select only this repository. Review, merge, and deployment remain separate operator boundaries.`,`Security summary`),await e.asker.ask(confirm({key:`self-modification-confirm`,message:`Create or attach this GitHub connector and write this configuration?`,recommended:!1,required:!0}))?{kind:`deployed`,connectorName:l,values:u}:{kind:`local`}}async function applySelfModificationSetup(e,t,n=defaultSelfModificationSetupOperations(t.appRoot)){if(e.kind===`authored`)return{facts:[{label:`Self-modification`,value:`manual configuration update required`}]};if(e.kind===`local`)return{facts:[{label:`Self-modification`,value:`local editing`}]};let r=await n.findOrCreateConnector(e.connectorName);return await n.attachConnector(r),await n.writeConfig(renderSelfModificationConfig({...e.values,connector:r})),t.presenter.log.success(`Updated ${SELF_MODIFICATION_CONFIG_PATH}.`),t.presenter.nextSteps([`Install the managed GitHub App for the configured repository, then deploy or redeploy.`,e.values.vercelBackend?"After deployment, try self-modification by running `eve dev <deployment-url>` from this linked project. The generated policy admits its Vercel OIDC identity over HTTP; configured channels remain denied until you update `agent/subagents/self-modification/config.ts`.":"Before deployment, configure `deployed.authorize` in `agent/subagents/self-modification/config.ts` to admit a trusted principal for your deployment's channel. After deployment, use that channel to try self-modification."]),{deploymentRequired:!0,facts:[{label:`Repository`,value:e.values.repository},{label:`Application directory`,value:e.values.directory},{label:`Target branch`,value:e.values.branch},{label:`Credential`,value:r}]}}async function prepareLocalSelfModificationSetup(e,t=defaultSelfModificationSetupOperations(e.appRoot)){let n=await t.readConfig();return classifySelfModificationConfig(n)===`authored`?(e.presenter.note(`The existing ${SELF_MODIFICATION_CONFIG_PATH} contains authored configuration and was not overwritten.`,`Manual update required`,{tone:`warning`}),{kind:`authored`}):{kind:`local`}}function describeEnvironment(e){if(e.vercel.kind===`available`)return describeIntegrationSetupEnvironment(e);switch(e.vercel.reason){case`logged-out`:return`No authenticated Vercel account found. Local editing remains available; deployed proposals require Vercel Connect.`;case`cli-missing`:return`Vercel CLI not found. Local editing remains available; deployed proposals require Vercel Connect.`;case`unavailable`:return`Could not verify the Vercel account. Local editing remains available; deployed proposals require Vercel Connect.`}}const SELF_MODIFICATION_SETUP=defineSetupIntegration({kind:`self-modification`,label:`Self-modification`,hint:`Local source editing is enabled`,describeEnvironment,prepare:prepareLocalSelfModificationSetup,apply:applySelfModificationSetup}),SELF_MODIFICATION_PRODUCTION_SETUP=defineSetupIntegration({kind:`self-modification-production`,label:`Self-modification production`,hint:`Configure deployed draft pull requests`,describeEnvironment,prepare:prepareSelfModificationSetup,apply:applySelfModificationSetup});export{SELF_MODIFICATION_PRODUCTION_SETUP,SELF_MODIFICATION_SETUP,applySelfModificationSetup,prepareLocalSelfModificationSetup,prepareSelfModificationSetup};
1
+ import{defineSetupIntegration}from"../types.js";import{describeIntegrationSetupEnvironment}from"../shared/environment.js";import{confirm,text}from"#setup/ask.js";import{classifySelfModificationConfig,connectorName,defaultSelfModificationSetupOperations,directoryError,gitRefError,renderSelfModificationConfig,repositoryPartError}from"#self-modification/setup.js";import{SELF_MODIFICATION_CONFIG_PATH}from"#self-modification/git-workspace.js";function validationResult(e){return e??null}async function prepareSelfModificationSetup(e,t=defaultSelfModificationSetupOperations(e.appRoot)){let n=await t.readConfig();if(classifySelfModificationConfig(n)===`authored`)return e.presenter.note(`The existing ${SELF_MODIFICATION_CONFIG_PATH} contains authored configuration and was not overwritten.`,`Manual update required`,{tone:`warning`}),{kind:`authored`};let[r,i]=await Promise.all([t.detectGitRepository(),t.detectChannelNames()]),a=await e.asker.ask(text({key:`self-modification-repository-owner`,message:`GitHub repository owner`,detected:r.owner,required:!0,validate:e=>validationResult(repositoryPartError(e))})),o=await e.asker.ask(text({key:`self-modification-repository-name`,message:`GitHub repository name`,detected:r.repo,required:!0,validate:e=>validationResult(repositoryPartError(e))})),s=await e.asker.ask(text({key:`self-modification-repository-directory`,message:`Application directory relative to the repository root`,detected:r.directory??`.`,required:!0,validate:e=>validationResult(directoryError(e))})),c=await e.asker.ask(text({key:`self-modification-target-branch`,message:`Target branch`,detected:r.branch??`main`,required:!0,validate:e=>validationResult(gitRefError(e))})),l=connectorName(a,o),u={branch:c,channelNames:i,connector:`github/${l}`,directory:s,repository:`github.com/${a}/${o}`,vercelBackend:e.environment.vercel.kind===`available`&&e.environment.vercel.project.kind!==`unresolved`};return e.presenter.note(renderSelfModificationConfig(u),`Generated ${SELF_MODIFICATION_CONFIG_PATH}`),e.presenter.note(`Vercel Connect will issue short-lived GitHub App credentials restricted to this repository. Install the managed GitHub App and select only this repository. Review, merge, and deployment remain separate operator boundaries.`,`Security summary`),await e.asker.ask(confirm({key:`self-modification-confirm`,message:`Create or attach this GitHub connector and write this configuration?`,recommended:!1,required:!0}))?{kind:`deployed`,connectorName:l,values:u}:{kind:`local`}}async function applySelfModificationSetup(e,t,n=defaultSelfModificationSetupOperations(t.appRoot)){if(e.kind===`authored`)return{facts:[{label:`Self-modification`,value:`manual configuration update required`}]};if(e.kind===`local`)return{facts:[]};let r=await n.findOrCreateConnector(e.connectorName);return await n.attachConnector(r),await n.writeConfig(renderSelfModificationConfig({...e.values,connector:r})),t.presenter.log.success(`Updated ${SELF_MODIFICATION_CONFIG_PATH}.`),t.presenter.nextSteps([`Install the managed GitHub App for the configured repository, then deploy or redeploy.`,e.values.vercelBackend?"After deployment, try self-modification by running `eve dev <deployment-url>` from this linked project. The generated policy admits its Vercel OIDC identity over HTTP; configured channels remain denied until you update `agent/subagents/self-modification/config.ts`.":"Before deployment, configure `deployed.authorize` in `agent/subagents/self-modification/config.ts` to admit a trusted principal for your deployment's channel. After deployment, use that channel to try self-modification."]),{deploymentRequired:!0,facts:[{label:`Repository`,value:e.values.repository},{label:`Application directory`,value:e.values.directory},{label:`Target branch`,value:e.values.branch},{label:`Credential`,value:r}]}}async function prepareLocalSelfModificationSetup(e,t=defaultSelfModificationSetupOperations(e.appRoot)){let n=await t.readConfig();return classifySelfModificationConfig(n)===`authored`?(e.presenter.note(`The existing ${SELF_MODIFICATION_CONFIG_PATH} contains authored configuration and was not overwritten.`,`Manual update required`,{tone:`warning`}),{kind:`authored`}):{kind:`local`}}function describeEnvironment(e){if(e.vercel.kind===`available`)return describeIntegrationSetupEnvironment(e);switch(e.vercel.reason){case`logged-out`:return`No authenticated Vercel account found. Local editing remains available; deployed proposals require Vercel Connect.`;case`cli-missing`:return`Vercel CLI not found. Local editing remains available; deployed proposals require Vercel Connect.`;case`unavailable`:return`Could not verify the Vercel account. Local editing remains available; deployed proposals require Vercel Connect.`}}const SELF_MODIFICATION_SETUP=defineSetupIntegration({kind:`self-modification`,label:`Self-modification`,hint:`Local source editing is enabled`,describeEnvironment,prepare:prepareLocalSelfModificationSetup,apply:applySelfModificationSetup}),SELF_MODIFICATION_PRODUCTION_SETUP=defineSetupIntegration({kind:`self-modification-production`,label:`Self-modification production`,hint:`Configure deployed draft pull requests`,describeEnvironment,prepare:prepareSelfModificationSetup,apply:applySelfModificationSetup});export{SELF_MODIFICATION_PRODUCTION_SETUP,SELF_MODIFICATION_SETUP,applySelfModificationSetup,prepareLocalSelfModificationSetup,prepareSelfModificationSetup};
@@ -1,4 +1,4 @@
1
- import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.93`,DEFAULT_CONNECT_PACKAGE_VERSION=`1.0.0`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.53.1`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{"agent/agent.ts":renderAgentTemplate(e,t),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
1
+ import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.93`,DEFAULT_CONNECT_PACKAGE_VERSION=`1.0.0`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.54.2`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{"agent/agent.ts":renderAgentTemplate(e,t),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
2
2
 
3
3
  export default defineAgent({
4
4
  model: "__EVE_INIT_MODEL__",
@@ -120,6 +120,10 @@ declare const runtimeLoadSkillActionRequestSchema: z.ZodObject<{
120
120
  * {@link RuntimeWorkflowTaskRequest} instead.
121
121
  */
122
122
  export type RuntimeActionRequest = RuntimeLoadSkillActionRequest | RuntimeRemoteAgentCallActionRequest | RuntimeSubagentCallActionRequest | RuntimeToolCallActionRequest | RuntimeWorkflowToolCallActionRequest;
123
+ /** Marks an in-process tool action without changing its serialized protocol shape. */
124
+ export declare function markRuntimeWorkflowToolAction(action: RuntimeToolCallActionRequest): RuntimeToolCallActionRequest;
125
+ /** Reads the in-process marker or the older explicit protocol action kind. */
126
+ export declare function isRuntimeWorkflowToolAction(action: RuntimeActionRequest): boolean;
123
127
  /** Internal agent dispatch request owned by a workflow task. */
124
128
  export type RuntimeAgentDispatchRequest = RuntimeRemoteAgentDispatchRequest | RuntimeSubagentDispatchRequest;
125
129
  /**
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{jsonObjectSchema,jsonValueSchema}from"#shared/json-schemas.js";import{tokenUsageSchema,tokenUsageWithCostSchema}from"#shared/token-usage.js";import{agentTurnOutcomeSchema,agentTurnOutcomeWithCostSchema}from"#shared/agent-turn-outcome.js";const runtimeToolCallActionRequestSchema=z.object({callId:z.string(),input:jsonObjectSchema,kind:z.literal(`tool-call`),toolName:z.string()}).strict(),runtimeSubagentCallActionRequestSchema=z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`subagent-call`),name:z.string(),nodeId:z.string(),subagentName:z.string()}).strict(),runtimeRemoteAgentCallActionRequestSchema=z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`remote-agent-call`),name:z.string(),nodeId:z.string(),remoteAgentName:z.string()}).strict(),runtimeWorkflowToolCallActionRequestSchema=z.object({callId:z.string(),input:jsonObjectSchema,kind:z.literal(`workflow-tool-call`),toolName:z.string(),workflowId:z.string()}).strict();z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`subagent-call`),name:z.string(),nodeId:z.string(),subagentName:z.string()}).strict();const runtimeRemoteAgentDispatchRequestSchema=z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`remote-agent-call`),name:z.string(),nodeId:z.string(),remoteAgentName:z.string()}).strict(),runtimeWorkflowTaskRequestSchema=z.object({callId:z.string(),executeInput:jsonValueSchema.optional(),input:jsonObjectSchema,kind:z.literal(`workflow-task`),nodeId:z.string().optional(),resultKind:z.enum([`subagent`,`tool`]).optional(),toolName:z.string(),workflowId:z.string()}).strict(),runtimeLoadSkillActionRequestSchema=z.object({callId:z.string(),input:jsonObjectSchema,kind:z.literal(`load-skill`)}).strict(),runtimeActionRequestSchema=z.discriminatedUnion(`kind`,[runtimeLoadSkillActionRequestSchema,runtimeRemoteAgentCallActionRequestSchema,runtimeSubagentCallActionRequestSchema,runtimeToolCallActionRequestSchema,runtimeWorkflowToolCallActionRequestSchema]);z.object({callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`tool-result`),output:jsonValueSchema,toolName:z.string()}).strict();const runtimeSubagentChildResultFields={backgroundTask:z.strictObject({status:z.literal(`working`),taskId:z.string()}).optional(),callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`subagent-result`),origin:z.literal(`child`),output:jsonValueSchema,subagentName:z.string()},runtimeSubagentChildResultSchema=z.object({backgroundTask:z.strictObject({status:z.literal(`working`),taskId:z.string()}).optional(),callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`subagent-result`),origin:z.literal(`child`),outcome:agentTurnOutcomeSchema,output:jsonValueSchema,subagentName:z.string(),usage:tokenUsageSchema.optional()}).strict(),runtimeSubagentChildResultWithCostSchema=z.object({...runtimeSubagentChildResultFields,outcome:agentTurnOutcomeWithCostSchema,usage:tokenUsageWithCostSchema.optional()}).strict();z.object({callId:z.string(),isError:z.literal(!0),kind:z.literal(`subagent-result`),origin:z.literal(`dispatch`),output:jsonValueSchema,subagentName:z.string()}).strict(),z.object({callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`load-skill-result`),output:jsonValueSchema,name:z.string().optional()}).strict();export{runtimeActionRequestSchema,runtimeRemoteAgentCallActionRequestSchema,runtimeRemoteAgentDispatchRequestSchema,runtimeSubagentChildResultSchema,runtimeSubagentChildResultWithCostSchema,runtimeToolCallActionRequestSchema,runtimeWorkflowTaskRequestSchema};
1
+ import{z}from"#compiled/zod/index.js";import{jsonObjectSchema,jsonValueSchema}from"#shared/json-schemas.js";import{tokenUsageSchema,tokenUsageWithCostSchema}from"#shared/token-usage.js";import{agentTurnOutcomeSchema,agentTurnOutcomeWithCostSchema}from"#shared/agent-turn-outcome.js";const runtimeToolCallActionRequestSchema=z.object({callId:z.string(),input:jsonObjectSchema,kind:z.literal(`tool-call`),toolName:z.string()}).strict(),runtimeSubagentCallActionRequestSchema=z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`subagent-call`),name:z.string(),nodeId:z.string(),subagentName:z.string()}).strict(),runtimeRemoteAgentCallActionRequestSchema=z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`remote-agent-call`),name:z.string(),nodeId:z.string(),remoteAgentName:z.string()}).strict(),runtimeWorkflowToolCallActionRequestSchema=z.object({callId:z.string(),input:jsonObjectSchema,kind:z.literal(`workflow-tool-call`),toolName:z.string(),workflowId:z.string()}).strict();z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`subagent-call`),name:z.string(),nodeId:z.string(),subagentName:z.string()}).strict();const runtimeRemoteAgentDispatchRequestSchema=z.object({callId:z.string(),description:z.string(),input:jsonObjectSchema,kind:z.literal(`remote-agent-call`),name:z.string(),nodeId:z.string(),remoteAgentName:z.string()}).strict(),runtimeWorkflowTaskRequestSchema=z.object({callId:z.string(),executeInput:jsonValueSchema.optional(),input:jsonObjectSchema,kind:z.literal(`workflow-task`),nodeId:z.string().optional(),resultKind:z.enum([`subagent`,`tool`]).optional(),toolName:z.string(),workflowId:z.string()}).strict(),runtimeLoadSkillActionRequestSchema=z.object({callId:z.string(),input:jsonObjectSchema,kind:z.literal(`load-skill`)}).strict(),RUNTIME_WORKFLOW_TOOL_ACTION=Symbol.for(`eve:runtime-workflow-tool-action`);function markRuntimeWorkflowToolAction(e){return Object.defineProperty(e,RUNTIME_WORKFLOW_TOOL_ACTION,{value:!0}),e}function isRuntimeWorkflowToolAction(e){return e.kind===`workflow-tool-call`||e.kind===`tool-call`&&Reflect.get(e,RUNTIME_WORKFLOW_TOOL_ACTION)===!0}const runtimeActionRequestSchema=z.discriminatedUnion(`kind`,[runtimeLoadSkillActionRequestSchema,runtimeRemoteAgentCallActionRequestSchema,runtimeSubagentCallActionRequestSchema,runtimeToolCallActionRequestSchema,runtimeWorkflowToolCallActionRequestSchema]);z.object({callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`tool-result`),output:jsonValueSchema,toolName:z.string()}).strict();const runtimeSubagentChildResultFields={backgroundTask:z.strictObject({status:z.literal(`working`),taskId:z.string()}).optional(),callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`subagent-result`),origin:z.literal(`child`),output:jsonValueSchema,subagentName:z.string()},runtimeSubagentChildResultSchema=z.object({backgroundTask:z.strictObject({status:z.literal(`working`),taskId:z.string()}).optional(),callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`subagent-result`),origin:z.literal(`child`),outcome:agentTurnOutcomeSchema,output:jsonValueSchema,subagentName:z.string(),usage:tokenUsageSchema.optional()}).strict(),runtimeSubagentChildResultWithCostSchema=z.object({...runtimeSubagentChildResultFields,outcome:agentTurnOutcomeWithCostSchema,usage:tokenUsageWithCostSchema.optional()}).strict();z.object({callId:z.string(),isError:z.literal(!0),kind:z.literal(`subagent-result`),origin:z.literal(`dispatch`),output:jsonValueSchema,subagentName:z.string()}).strict(),z.object({callId:z.string(),isError:z.boolean().optional(),kind:z.literal(`load-skill-result`),output:jsonValueSchema,name:z.string().optional()}).strict();export{isRuntimeWorkflowToolAction,markRuntimeWorkflowToolAction,runtimeActionRequestSchema,runtimeRemoteAgentCallActionRequestSchema,runtimeRemoteAgentDispatchRequestSchema,runtimeSubagentChildResultSchema,runtimeSubagentChildResultWithCostSchema,runtimeToolCallActionRequestSchema,runtimeWorkflowTaskRequestSchema};
@@ -17,7 +17,7 @@ export type PendingAgentDispatchAction = PendingDispatchAction & {
17
17
  /** Pending action that mutates the durable task lifecycle. */
18
18
  export type PendingTaskControlAction = PendingDispatchAction & {
19
19
  readonly target: Extract<PreparedDispatchTarget, {
20
- readonly kind: "task-cancel" | "task-update";
20
+ readonly kind: "task-cancel";
21
21
  }>;
22
22
  };
23
23
  /** Pending action that runs a tool's execute body as a durable workflow. */
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{identityHistoryViewProjector}from"#shared/history-view.js";const MEMORY_NAMESPACE_MAX_BYTES=1024,MEMORY_SCOPE_COMPONENT_MAX_BYTES=1024,MEMORY_SCOPE_TUPLE_MAX_COMPONENTS=16,MEMORY_CANONICAL_KEY_INPUT_MAX_BYTES=4096,MEMORY_ITEM_ID_MAX_BYTES=1024,MEMORY_RAW_RECORD_MAX_COUNT=512,MEMORY_RAW_RECORD_MAX_BYTES=262144,MEMORY_MESSAGE_METADATA_KEY=`eve.memory`,MEMORY_SESSION_STATE_KEY=`eve.memory`;function createMemoryLock(e){validateMemoryNamespace(e.namespace),validateMemoryScopeValue(e.scope);let t=encodeScalar(`namespace`,e.namespace),n=encodeScope(e.scope);if(t.byteLength+n.byteLength>4096)throw Error(`Memory slot "${e.slot}" namespace and scope encoding exceeds ${MEMORY_CANONICAL_KEY_INPUT_MAX_BYTES} UTF-8 bytes.`);let r=digest(`memns1_`,t),i=digest(`memscope1_`,n),a=Buffer.concat([Buffer.from(`eve-memory-composite-v1\0`),lengthPrefix(Buffer.from(r)),lengthPrefix(Buffer.from(i))]),o=Object.freeze({key:digest(`memscope1_`,a),namespace:e.namespace,value:Array.isArray(e.scope)?Object.freeze([...e.scope]):e.scope});return Object.freeze({namespaceKey:r,scope:o,scopeKey:i,slot:e.slot,turn:e.turn,visibility:e.visibility})}function validateMemoryRecallResult(e,t){if(e==null)return[];if(typeof e!=`object`||Array.isArray(e))throw Error(`Memory slot "${t}" recall() must return { messages }, null, or undefined.`);let n=Object.keys(e).filter(e=>e!==`messages`);if(n.length>0)throw Error(`Memory slot "${t}" recall() returned unknown key(s): ${n.join(`, `)}.`);if(!Array.isArray(e.messages))throw Error(`Memory slot "${t}" recall().messages must be an array.`);let r=new Set;return e.messages.map((e,n)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Memory slot "${t}" recall message ${n} must be an object.`);let i=Object.keys(e).filter(e=>e!==`content`&&e!==`id`);if(i.length>0)throw Error(`Memory slot "${t}" recall message ${n} has unknown key(s): ${i.join(`, `)}.`);if(typeof e.content!=`string`||e.content.trim().length===0)throw Error(`Memory slot "${t}" recall message ${n} content must be non-blank.`);if(e.id===void 0)return Object.freeze({content:e.content});if(typeof e.id!=`string`||e.id.length===0)throw Error(`Memory slot "${t}" recall message ${n} id must be non-empty.`);if(utf8Bytes(e.id)>1024)throw Error(`Memory slot "${t}" recall message ${n} id exceeds ${MEMORY_ITEM_ID_MAX_BYTES} UTF-8 bytes.`);if(r.has(e.id))throw Error(`Memory slot "${t}" recall() returned duplicate id "${e.id}".`);return r.add(e.id),Object.freeze({content:e.content,itemKey:digest(`memitem1_`,encodeScalar(`item`,e.id))})})}function applyMemoryRecallBatches(e){let t={...readMemorySessionState(e.state).operationDigests},n=latestKeyedRecords(e.history),r=[];for(let i of e.batches){let e=recallBatchDigest(i.messages),a=t[i.operationId];if(a!==void 0){if(a!==e)throw Error(`Memory recall operation "${i.operationId}" replayed with a different result.`);continue}t[i.operationId]=e;for(let[e,t]of i.messages.entries()){let a={batchIndex:e,itemKey:t.itemKey,namespaceKey:i.lock.namespaceKey,operationId:i.operationId,scopeKey:i.lock.scopeKey,slot:i.lock.slot,version:1};if(t.itemKey!==void 0){let e=memoryItemIdentity(a);if(n.get(e)?.content===t.content)continue;n.set(e,{attribution:a,content:t.content})}r.push(attributeMemoryRecord(t.content,a))}}let i=Object.fromEntries(Object.entries(t).slice(-1024));return{history:[...e.history,...r],state:writeMemorySessionState(e.state,{locks:Object.fromEntries(e.batches.map(e=>[e.lock.slot,e.lock])),operationDigests:i})}}function projectMemoryHistory(e){let t=latestKeyedRecordIndexes(e.messages);return e.messages.flatMap((n,r)=>{let i=readMemoryRecordAttribution(n);if(i===null)return[n];let a=e.locks[i.slot];return a===void 0||a.namespaceKey!==i.namespaceKey||a.visibility===`scope`&&a.scopeKey!==i.scopeKey||i.itemKey!==void 0&&t.get(memoryItemIdentity(i))!==r?[]:[stripMemoryRecordAttribution(n)]})}function projectMemoryHistoryFromSessionState(e){let t=identityHistoryViewProjector(e);return projectMemoryHistory({locks:readMemorySessionState(e.state).locks,messages:t})}function canonicalizeMemoryRecords(e){let t=latestKeyedRecordIndexes(e),n=[],r=[];for(let[i,a]of e.entries()){let e=readMemoryRecordAttribution(a);if(e===null){r.push(a);continue}(e.itemKey===void 0||t.get(memoryItemIdentity(e))===i)&&n.push(a)}return{memory:n,ordinary:r}}function shouldCanonicalizeMemory(e){let t=0,n=0;for(let r of e)readMemoryRecordAttribution(r)!==null&&(t+=1,n+=serializedBytes(r));return t>512||n>262144}function clearMemorySessionState(e){if(e===void 0||!Object.hasOwn(e,MEMORY_SESSION_STATE_KEY))return e??{};let{[MEMORY_SESSION_STATE_KEY]:t,...n}=e;return n}function readMemoryLocks(e){return readMemorySessionState(e).locks}function validateMemoryNamespace(e){if(e.trim().length===0)throw Error(`Memory namespace must be non-empty.`);if(utf8Bytes(e)>1024)throw Error(`Memory namespace exceeds ${MEMORY_NAMESPACE_MAX_BYTES} UTF-8 bytes.`)}function validateMemoryScopeValue(e){let t=Array.isArray(e)?e:[e];if(Array.isArray(e)&&t.length>16)throw Error(`Memory scope tuple exceeds 16 components.`);if(t.length===0)throw Error(`Memory scope tuple must not be empty.`);for(let[e,n]of t.entries()){if(typeof n!=`string`||n.trim().length===0)throw Error(`Memory scope component ${e} must be a non-empty string.`);if(utf8Bytes(n)>1024)throw Error(`Memory scope component ${e} exceeds ${MEMORY_SCOPE_COMPONENT_MAX_BYTES} UTF-8 bytes.`)}}function encodeScope(e){return typeof e==`string`?encodeScalar(`scope-scalar`,e):Buffer.concat([Buffer.from(`scope-tuple-v1\0`),uint32(e.length),...e.map(e=>lengthPrefix(Buffer.from(e,`utf8`)))])}function encodeScalar(e,t){return Buffer.concat([Buffer.from(`${e}-v1\0`),lengthPrefix(Buffer.from(t,`utf8`))])}function lengthPrefix(e){return Buffer.concat([uint32(e.byteLength),e])}function uint32(e){let t=Buffer.allocUnsafe(4);return t.writeUInt32BE(e),t}function digest(e,t){return`${e}${createHash(`sha256`).update(t).digest(`base64url`)}`}function recallBatchDigest(e){return createHash(`sha256`).update(JSON.stringify(e)).digest(`base64url`)}function attributeMemoryRecord(e,t){return{content:e,metadata:{[MEMORY_MESSAGE_METADATA_KEY]:t},role:`user`}}function readMemoryRecordAttribution(e){if(typeof e!=`object`||!e)return null;let t=Reflect.get(e,`metadata`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,MEMORY_MESSAGE_METADATA_KEY);if(typeof n!=`object`||!n)return null;let r=n;if(r.version!==1||typeof r.batchIndex!=`number`||typeof r.namespaceKey!=`string`||typeof r.operationId!=`string`||typeof r.scopeKey!=`string`||typeof r.slot!=`string`||r.itemKey!==void 0&&typeof r.itemKey!=`string`)throw Error(`Durable history contains invalid eve memory attribution.`);return r}function stripMemoryRecordAttribution(e){let t=Reflect.get(e,`metadata`);if(typeof t!=`object`||!t)return e;let{[MEMORY_MESSAGE_METADATA_KEY]:n,...r}=t,{metadata:i,...a}=e;return Object.keys(r).length===0?a:Object.assign(a,{metadata:r})}function latestKeyedRecordIndexes(e){let t=new Map;for(let[n,r]of e.entries()){let e=readMemoryRecordAttribution(r);e?.itemKey!==void 0&&t.set(memoryItemIdentity(e),n)}return t}function latestKeyedRecords(e){let t=new Map;for(let n of e){let e=readMemoryRecordAttribution(n);if(e?.itemKey===void 0)continue;let r=Reflect.get(n,`content`),i=typeof r==`string`?r:``;t.set(memoryItemIdentity(e),{attribution:e,content:i})}return t}function memoryItemIdentity(e){return JSON.stringify([e.slot,e.namespaceKey,e.scopeKey,e.itemKey])}function readMemorySessionState(e){let t=e?.[MEMORY_SESSION_STATE_KEY];if(typeof t!=`object`||!t||Array.isArray(t))return{locks:{},operationDigests:{}};let n=Reflect.get(t,`locks`),r=Reflect.get(t,`operationDigests`);return{locks:typeof n==`object`&&n&&!Array.isArray(n)?n:{},operationDigests:typeof r==`object`&&r&&!Array.isArray(r)?r:{}}}function writeMemorySessionState(e,t){return{...e,[MEMORY_SESSION_STATE_KEY]:t}}function serializedBytes(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function utf8Bytes(e){return Buffer.byteLength(e,`utf8`)}export{MEMORY_CANONICAL_KEY_INPUT_MAX_BYTES,MEMORY_ITEM_ID_MAX_BYTES,MEMORY_NAMESPACE_MAX_BYTES,MEMORY_RAW_RECORD_MAX_BYTES,MEMORY_RAW_RECORD_MAX_COUNT,MEMORY_SCOPE_COMPONENT_MAX_BYTES,MEMORY_SCOPE_TUPLE_MAX_COMPONENTS,applyMemoryRecallBatches,canonicalizeMemoryRecords,clearMemorySessionState,createMemoryLock,projectMemoryHistory,projectMemoryHistoryFromSessionState,readMemoryLocks,shouldCanonicalizeMemory,validateMemoryRecallResult};
1
+ import{createHash}from"node:crypto";import{createFrameworkUserMessage}from"#harness/messages.js";import{identityHistoryViewProjector}from"#shared/history-view.js";const MEMORY_NAMESPACE_MAX_BYTES=1024,MEMORY_SCOPE_COMPONENT_MAX_BYTES=1024,MEMORY_SCOPE_TUPLE_MAX_COMPONENTS=16,MEMORY_CANONICAL_KEY_INPUT_MAX_BYTES=4096,MEMORY_ITEM_ID_MAX_BYTES=1024,MEMORY_RAW_RECORD_MAX_COUNT=512,MEMORY_RAW_RECORD_MAX_BYTES=262144,MEMORY_MESSAGE_METADATA_KEY=`eve.memory`,MEMORY_SESSION_STATE_KEY=`eve.memory`;function createMemoryLock(e){validateMemoryNamespace(e.namespace),validateMemoryScopeValue(e.scope);let t=encodeScalar(`namespace`,e.namespace),n=encodeScope(e.scope);if(t.byteLength+n.byteLength>4096)throw Error(`Memory slot "${e.slot}" namespace and scope encoding exceeds ${MEMORY_CANONICAL_KEY_INPUT_MAX_BYTES} UTF-8 bytes.`);let r=digest(`memns1_`,t),i=digest(`memscope1_`,n),a=Buffer.concat([Buffer.from(`eve-memory-composite-v1\0`),lengthPrefix(Buffer.from(r)),lengthPrefix(Buffer.from(i))]),o=Object.freeze({key:digest(`memscope1_`,a),namespace:e.namespace,value:Array.isArray(e.scope)?Object.freeze([...e.scope]):e.scope});return Object.freeze({namespaceKey:r,scope:o,scopeKey:i,slot:e.slot,turn:e.turn,visibility:e.visibility})}function validateMemoryRecallResult(e,t){if(e==null)return[];if(typeof e!=`object`||Array.isArray(e))throw Error(`Memory slot "${t}" recall() must return { messages }, null, or undefined.`);let n=Object.keys(e).filter(e=>e!==`messages`);if(n.length>0)throw Error(`Memory slot "${t}" recall() returned unknown key(s): ${n.join(`, `)}.`);if(!Array.isArray(e.messages))throw Error(`Memory slot "${t}" recall().messages must be an array.`);let r=new Set;return e.messages.map((e,n)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Memory slot "${t}" recall message ${n} must be an object.`);let i=Object.keys(e).filter(e=>e!==`content`&&e!==`id`);if(i.length>0)throw Error(`Memory slot "${t}" recall message ${n} has unknown key(s): ${i.join(`, `)}.`);if(typeof e.content!=`string`||e.content.trim().length===0)throw Error(`Memory slot "${t}" recall message ${n} content must be non-blank.`);if(e.id===void 0)return Object.freeze({content:e.content});if(typeof e.id!=`string`||e.id.length===0)throw Error(`Memory slot "${t}" recall message ${n} id must be non-empty.`);if(utf8Bytes(e.id)>1024)throw Error(`Memory slot "${t}" recall message ${n} id exceeds ${MEMORY_ITEM_ID_MAX_BYTES} UTF-8 bytes.`);if(r.has(e.id))throw Error(`Memory slot "${t}" recall() returned duplicate id "${e.id}".`);return r.add(e.id),Object.freeze({content:e.content,itemKey:digest(`memitem1_`,encodeScalar(`item`,e.id))})})}function applyMemoryRecallBatches(e){let t={...readMemorySessionState(e.state).operationDigests},n=latestKeyedRecords(e.history),r=[];for(let i of e.batches){let e=recallBatchDigest(i.messages),a=t[i.operationId];if(a!==void 0){if(a!==e)throw Error(`Memory recall operation "${i.operationId}" replayed with a different result.`);continue}t[i.operationId]=e;for(let[e,t]of i.messages.entries()){let a={batchIndex:e,itemKey:t.itemKey,namespaceKey:i.lock.namespaceKey,operationId:i.operationId,scopeKey:i.lock.scopeKey,slot:i.lock.slot,version:1};if(t.itemKey!==void 0){let e=memoryItemIdentity(a);if(n.get(e)?.content===t.content)continue;n.set(e,{attribution:a,content:t.content})}r.push(attributeMemoryRecord(t.content,a))}}let i=Object.fromEntries(Object.entries(t).slice(-1024));return{history:[...e.history,...r],state:writeMemorySessionState(e.state,{locks:Object.fromEntries(e.batches.map(e=>[e.lock.slot,e.lock])),operationDigests:i})}}function projectMemoryHistory(e){let t=latestKeyedRecordIndexes(e.messages);return e.messages.flatMap((n,r)=>{let i=readMemoryRecordAttribution(n);if(i===null)return[n];let a=e.locks[i.slot];return a===void 0||a.namespaceKey!==i.namespaceKey||a.visibility===`scope`&&a.scopeKey!==i.scopeKey||i.itemKey!==void 0&&t.get(memoryItemIdentity(i))!==r?[]:[stripMemoryRecordAttribution(n)]})}function projectMemoryHistoryFromSessionState(e){let t=identityHistoryViewProjector(e);return projectMemoryHistory({locks:readMemorySessionState(e.state).locks,messages:t})}function canonicalizeMemoryRecords(e){let t=latestKeyedRecordIndexes(e),n=[],r=[];for(let[i,a]of e.entries()){let e=readMemoryRecordAttribution(a);if(e===null){r.push(a);continue}(e.itemKey===void 0||t.get(memoryItemIdentity(e))===i)&&n.push(a)}return{memory:n,ordinary:r}}function shouldCanonicalizeMemory(e){let t=0,n=0;for(let r of e)readMemoryRecordAttribution(r)!==null&&(t+=1,n+=serializedBytes(r));return t>512||n>262144}function clearMemorySessionState(e){if(e===void 0||!Object.hasOwn(e,MEMORY_SESSION_STATE_KEY))return e??{};let{[MEMORY_SESSION_STATE_KEY]:t,...n}=e;return n}function readMemoryLocks(e){return readMemorySessionState(e).locks}function validateMemoryNamespace(e){if(e.trim().length===0)throw Error(`Memory namespace must be non-empty.`);if(utf8Bytes(e)>1024)throw Error(`Memory namespace exceeds ${MEMORY_NAMESPACE_MAX_BYTES} UTF-8 bytes.`)}function validateMemoryScopeValue(e){let t=Array.isArray(e)?e:[e];if(Array.isArray(e)&&t.length>16)throw Error(`Memory scope tuple exceeds 16 components.`);if(t.length===0)throw Error(`Memory scope tuple must not be empty.`);for(let[e,n]of t.entries()){if(typeof n!=`string`||n.trim().length===0)throw Error(`Memory scope component ${e} must be a non-empty string.`);if(utf8Bytes(n)>1024)throw Error(`Memory scope component ${e} exceeds ${MEMORY_SCOPE_COMPONENT_MAX_BYTES} UTF-8 bytes.`)}}function encodeScope(e){return typeof e==`string`?encodeScalar(`scope-scalar`,e):Buffer.concat([Buffer.from(`scope-tuple-v1\0`),uint32(e.length),...e.map(e=>lengthPrefix(Buffer.from(e,`utf8`)))])}function encodeScalar(e,t){return Buffer.concat([Buffer.from(`${e}-v1\0`),lengthPrefix(Buffer.from(t,`utf8`))])}function lengthPrefix(e){return Buffer.concat([uint32(e.byteLength),e])}function uint32(e){let t=Buffer.allocUnsafe(4);return t.writeUInt32BE(e),t}function digest(e,t){return`${e}${createHash(`sha256`).update(t).digest(`base64url`)}`}function recallBatchDigest(e){return createHash(`sha256`).update(JSON.stringify(e)).digest(`base64url`)}function attributeMemoryRecord(e,t){return createFrameworkUserMessage(`memory.load`,e,{[MEMORY_MESSAGE_METADATA_KEY]:t})}function readMemoryRecordAttribution(e){if(typeof e!=`object`||!e)return null;let t=Reflect.get(e,`metadata`);if(typeof t!=`object`||!t)return null;let n=Reflect.get(t,MEMORY_MESSAGE_METADATA_KEY);if(typeof n!=`object`||!n)return null;let r=n;if(r.version!==1||typeof r.batchIndex!=`number`||typeof r.namespaceKey!=`string`||typeof r.operationId!=`string`||typeof r.scopeKey!=`string`||typeof r.slot!=`string`||r.itemKey!==void 0&&typeof r.itemKey!=`string`)throw Error(`Durable history contains invalid eve memory attribution.`);return r}function stripMemoryRecordAttribution(e){let t=Reflect.get(e,`metadata`);if(typeof t!=`object`||!t)return e;let{[MEMORY_MESSAGE_METADATA_KEY]:n,...r}=t,{metadata:i,...a}=e;return Object.keys(r).length===0?a:Object.assign(a,{metadata:r})}function latestKeyedRecordIndexes(e){let t=new Map;for(let[n,r]of e.entries()){let e=readMemoryRecordAttribution(r);e?.itemKey!==void 0&&t.set(memoryItemIdentity(e),n)}return t}function latestKeyedRecords(e){let t=new Map;for(let n of e){let e=readMemoryRecordAttribution(n);if(e?.itemKey===void 0)continue;let r=Reflect.get(n,`content`),i=typeof r==`string`?r:``;t.set(memoryItemIdentity(e),{attribution:e,content:i})}return t}function memoryItemIdentity(e){return JSON.stringify([e.slot,e.namespaceKey,e.scopeKey,e.itemKey])}function readMemorySessionState(e){let t=e?.[MEMORY_SESSION_STATE_KEY];if(typeof t!=`object`||!t||Array.isArray(t))return{locks:{},operationDigests:{}};let n=Reflect.get(t,`locks`),r=Reflect.get(t,`operationDigests`);return{locks:typeof n==`object`&&n&&!Array.isArray(n)?n:{},operationDigests:typeof r==`object`&&r&&!Array.isArray(r)?r:{}}}function writeMemorySessionState(e,t){return{...e,[MEMORY_SESSION_STATE_KEY]:t}}function serializedBytes(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function utf8Bytes(e){return Buffer.byteLength(e,`utf8`)}export{MEMORY_CANONICAL_KEY_INPUT_MAX_BYTES,MEMORY_ITEM_ID_MAX_BYTES,MEMORY_NAMESPACE_MAX_BYTES,MEMORY_RAW_RECORD_MAX_BYTES,MEMORY_RAW_RECORD_MAX_COUNT,MEMORY_SCOPE_COMPONENT_MAX_BYTES,MEMORY_SCOPE_TUPLE_MAX_COMPONENTS,applyMemoryRecallBatches,canonicalizeMemoryRecords,clearMemorySessionState,createMemoryLock,projectMemoryHistory,projectMemoryHistoryFromSessionState,readMemoryLocks,shouldCanonicalizeMemory,validateMemoryRecallResult};
@@ -0,0 +1,12 @@
1
+ export declare const SERIALIZED_INSTRUMENTATION_STATE_KEYS: {
2
+ readonly activeChannelDeliveries: "eve.activeChannelDeliveries";
3
+ readonly actionScopes: "eve.harness.instrumentationActionScopes";
4
+ readonly inputScopes: "eve.harness.instrumentationInputScopes";
5
+ readonly providerState: "eve.harness.instrumentationState";
6
+ };
7
+ /** Keeps instrumentation state needed to settle operations opened by a discarded step. */
8
+ export declare function preserveSerializedInstrumentationState(original: Record<string, unknown>, interrupted: Record<string, unknown>): Record<string, unknown>;
9
+ /** Keeps only the observability state a retained background task needs before readiness. */
10
+ export declare function preserveSerializedBackgroundTaskObservabilityState(original: Record<string, unknown>, completed: Record<string, unknown>, tasks: readonly {
11
+ readonly taskId: string;
12
+ }[]): Record<string, unknown>;
@@ -0,0 +1 @@
1
+ const SERIALIZED_INSTRUMENTATION_STATE_KEYS={activeChannelDeliveries:`eve.activeChannelDeliveries`,actionScopes:`eve.harness.instrumentationActionScopes`,inputScopes:`eve.harness.instrumentationInputScopes`,providerState:`eve.harness.instrumentationState`},SERIALIZED_AGENT_TRACE_STATE_KEY=`eve.harness.agentTrace`;function preserveSerializedInstrumentationState(e,t){let n=e;for(let e of Object.values(SERIALIZED_INSTRUMENTATION_STATE_KEYS)){let r=t[e];r!==void 0&&(n={...n,[e]:r})}return n}function preserveSerializedBackgroundTaskObservabilityState(e,t,n){let r=new Set(n.map(e=>e.taskId)),i=asRecord(t[SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes]),a=Object.fromEntries(Object.entries(i).filter(([,e])=>{let t=asRecord(e);return typeof t.taskId==`string`&&r.has(t.taskId)})),o=new Set(Object.keys(a));if(o.size===0)return e;let s=mergeSerializedRecord(e,SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes,a),c=Object.fromEntries(Object.entries(asRecord(t[SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState])).filter(([e])=>{let t=e.indexOf(`\0`);return t>=0&&o.has(e.slice(t+1))}));s=mergeSerializedRecord(s,SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState,c);let l=asRecord(t[SERIALIZED_AGENT_TRACE_STATE_KEY]),u=selectEntries(l.actionAnchors,o),d=Object.fromEntries(Object.entries(asRecord(l.actions)).filter(([e])=>o.has(e))),f=new Set;for(let e of[...Object.values(u),...Object.values(d)]){let t=asRecord(e).callId;typeof t==`string`&&f.add(t)}let p=selectOwnedInvocations(l.invocations,o,f);if(Object.keys(u).length===0&&Object.keys(d).length===0&&Object.keys(p).length===0)return s;let m=asRecord(e[SERIALIZED_AGENT_TRACE_STATE_KEY]);return{...s,[SERIALIZED_AGENT_TRACE_STATE_KEY]:{actionAnchors:{...asRecord(m.actionAnchors),...u},actions:{...asRecord(m.actions),...d},invocations:{...asRecord(m.invocations),...p},sessions:asRecord(m.sessions),turns:asRecord(m.turns)}}}function selectEntries(e,t){return Object.fromEntries(Object.entries(asRecord(e)).filter(([e])=>t.has(e)))}function selectOwnedInvocations(e,t,n){let r=Object.entries(asRecord(e)),i={},a=!0;for(;a;){a=!1;for(let e=r.length-1;e>=0;e--){let[o,s]=r[e],c=asRecord(s),l=c.parentActionCallId;if(!t.has(o)&&!(typeof l==`string`&&n.has(l)))continue;i[o]=s;let u=c.callId;typeof u==`string`&&n.add(u),r.splice(e,1),a=!0}}return i}function mergeSerializedRecord(e,t,n){return Object.keys(n).length===0?e:{...e,[t]:{...asRecord(e[t]),...n}}}function asRecord(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}export{SERIALIZED_INSTRUMENTATION_STATE_KEYS,preserveSerializedBackgroundTaskObservabilityState,preserveSerializedInstrumentationState};
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{isInputRequest}from"#shared/input.js";import{jsonValueSchema}from"#shared/json-schemas.js";import{resumeHook}from"#internal/workflow/runtime.js";import{REMOTE_AGENT_FAILED}from"#subagents/agent-handle-errors.js";import{tokenUsageWithCostSchema}from"#shared/token-usage.js";import{agentTurnOutcomeWithCostSchema}from"#shared/agent-turn-outcome.js";import{readTaskIdFromInboxToken}from"#tasks/task-inbox-token.js";const ZERO_TOKEN_USAGE={cacheReadTokens:0,cacheWriteTokens:0,inputTokens:0,outputTokens:0},eventCoordinateSchema=z.number().int().nonnegative(),authorizationChallengeSchema=z.looseObject({displayName:z.string().optional(),expiresAt:z.string().optional(),instructions:z.string().optional(),url:z.string().optional(),userCode:z.string().optional()}),taskInputEventSchema=z.looseObject({requests:z.array(jsonValueSchema.refine(isInputRequest)).min(1),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string()}),taskAuthorizationEventSchema=z.discriminatedUnion(`type`,[z.looseObject({data:z.looseObject({attemptId:z.string().optional(),authorization:authorizationChallengeSchema.optional(),description:z.string(),name:z.string(),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string(),webhookUrl:z.string().optional()}),type:z.literal(`authorization.required`)}),z.looseObject({data:z.looseObject({attemptId:z.string().optional(),authorization:authorizationChallengeSchema.optional(),name:z.string(),outcome:z.enum([`authorized`,`declined`,`failed`,`timed-out`]),reason:z.string().optional(),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string()}),type:z.literal(`authorization.completed`)})]),taskEventCallbackSchema=z.discriminatedUnion(`kind`,[z.object({callId:z.string(),childContinuationToken:z.string(),childSessionId:z.string(),event:taskInputEventSchema,kind:z.literal(`task.input-requested`),subagentName:z.string(),taskId:z.string()}),z.object({callId:z.string(),childContinuationToken:z.string(),childSessionId:z.string(),event:taskAuthorizationEventSchema,kind:z.literal(`task.authorization`),subagentName:z.string(),taskId:z.string()})]),taskTurnStartedCallbackSchema=z.object({kind:z.literal(`turn.started`),sessionId:z.string().min(1),taskId:z.string().min(1),turnId:z.string().min(1)}),taskUpdateCallbackSchema=z.object({callId:z.string().min(1),kind:z.literal(`task.update`),message:z.string().min(1),taskId:z.string().min(1),updateEpoch:z.string().min(1),updateIndex:eventCoordinateSchema}),sessionResultCallbackSchema=z.discriminatedUnion(`kind`,[z.object({callId:z.string().min(1),kind:z.literal(`session.completed`),output:jsonValueSchema.optional(),subagentName:z.string().min(1),usage:z.unknown().optional()}),z.object({callId:z.string().min(1),error:jsonValueSchema.optional(),kind:z.literal(`session.failed`),subagentName:z.string().min(1),usage:z.unknown().optional()}),z.object({callId:z.string().min(1),kind:z.literal(`turn.completed`),outcome:agentTurnOutcomeWithCostSchema,output:jsonValueSchema.optional(),subagentName:z.string().min(1)}),z.object({callId:z.string().min(1),error:jsonValueSchema,kind:z.literal(`turn.failed`),outcome:agentTurnOutcomeWithCostSchema,subagentName:z.string().min(1)})]);async function handleSessionCallbackRequest(e,t){let n=t.params.token;if(typeof n!=`string`||n.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});let r;try{r=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}let i=projectTaskEvent(r,n);if(i instanceof Response)return i;if(i!==void 0){try{await resumeHook(n,i)}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}let a=projectTaskUpdate(r,n);if(a instanceof Response)return a;if(a!==void 0){try{await resumeHook(n,a)}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}let o=rejectDirectTaskTurnStarted(r,n);if(o instanceof Response)return o;if(o!==void 0){try{await resumeHook(n,o)}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}let s=projectSessionCallbackResult(r);if(s instanceof Response)return s;try{await resumeHook(n,{kind:`runtime-action-result`,results:[s]})}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}function callbackKind(e){if(typeof e==`object`&&e)return Reflect.get(e,`kind`)}function projectTaskEvent(e,t){let n=callbackKind(e);if(n!==`task.input-requested`&&n!==`task.authorization`)return;let r=taskEventCallbackSchema.safeParse(e);if(!r.success)return Response.json({error:`Invalid task event callback.`,ok:!1},{status:400});let i=r.data;if(readTaskIdFromInboxToken(t)!==void 0){let e=rejectMismatchedTaskToken(t,i.taskId);return e===void 0?Response.json({error:`Direct subagent task events are no longer accepted.`,ok:!1},{status:410}):e}return i.kind===`task.input-requested`?{callId:i.callId,childContinuationToken:i.childContinuationToken,childSessionId:i.childSessionId,event:i.event,kind:`subagent-input-request`,subagentName:i.subagentName}:{callId:i.callId,childSessionId:i.childSessionId,event:i.event,kind:`subagent-authorization-event`,subagentName:i.subagentName}}function rejectDirectTaskTurnStarted(e,t){if(callbackKind(e)!==`turn.started`)return;let n=taskTurnStartedCallbackSchema.safeParse(e);if(!n.success)return Response.json({error:`Invalid task turn-start callback.`,ok:!1},{status:400});let r=rejectMismatchedTaskToken(t,n.data.taskId);return r===void 0?Response.json({error:`Direct subagent task turn callbacks are no longer accepted.`,ok:!1},{status:410}):r}function projectTaskUpdate(e,t){if(callbackKind(e)!==`task.update`)return;let n=taskUpdateCallbackSchema.safeParse(e);if(!n.success)return Response.json({error:`Invalid task update callback.`,ok:!1},{status:400});if(readTaskIdFromInboxToken(t)!==void 0){let e=rejectMismatchedTaskToken(t,n.data.taskId);if(e!==void 0)return e}return{callId:n.data.callId,kind:`task-update`,message:n.data.message,updateEpoch:n.data.updateEpoch,updateIndex:n.data.updateIndex}}function rejectMismatchedTaskToken(e,t){return readTaskIdFromInboxToken(e)===t?void 0:Response.json({error:`Task callback token mismatch.`,ok:!1},{status:403})}function projectSessionCallbackResult(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let t=callbackKind(e);if(t!==`session.completed`&&t!==`session.failed`&&t!==`turn.completed`&&t!==`turn.failed`)return Response.json({error:`Unsupported callback kind.`,ok:!1},{status:400});let n=sessionResultCallbackSchema.safeParse(e);if(!n.success)return Response.json({error:`Invalid session result callback.`,ok:!1},{status:400});let r=n.data;if(r.kind===`session.completed`){let e=r.output??``,t=parseCallbackUsage(r.usage),n={callId:r.callId,kind:`subagent-result`,origin:`child`,outcome:{kind:`terminal`,result:{kind:`succeeded`,output:e},usageDelta:t??ZERO_TOKEN_USAGE},output:e,subagentName:r.subagentName};return t===void 0?n:{...n,usage:t}}if(r.kind===`session.failed`){let e=r.error===void 0?{code:REMOTE_AGENT_FAILED,message:`Remote agent failed.`}:r.error,t=parseCallbackUsage(r.usage);return{callId:r.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:{kind:`terminal`,result:{error:e,kind:`failed`},usageDelta:t??ZERO_TOKEN_USAGE},output:e,subagentName:r.subagentName}}return r.kind===`turn.completed`?{callId:r.callId,kind:`subagent-result`,origin:`child`,outcome:r.outcome,output:r.output??``,subagentName:r.subagentName,usage:r.outcome.usageDelta}:{callId:r.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:r.outcome,output:r.error,subagentName:r.subagentName}}function parseCallbackUsage(e){if(e===void 0)return;let t=tokenUsageWithCostSchema.safeParse(e);return t.success?t.data:void 0}export{handleSessionCallbackRequest};
1
+ import{z}from"#compiled/zod/index.js";import{isInputRequest}from"#shared/input.js";import{jsonValueSchema}from"#shared/json-schemas.js";import{resumeHook}from"#internal/workflow/runtime.js";import{REMOTE_AGENT_FAILED}from"#subagents/agent-handle-errors.js";import{tokenUsageWithCostSchema}from"#shared/token-usage.js";import{agentTurnOutcomeWithCostSchema}from"#shared/agent-turn-outcome.js";import{readTaskIdFromInboxToken}from"#tasks/task-inbox-token.js";const ZERO_TOKEN_USAGE={cacheReadTokens:0,cacheWriteTokens:0,inputTokens:0,outputTokens:0},eventCoordinateSchema=z.number().int().nonnegative(),authorizationChallengeSchema=z.looseObject({displayName:z.string().optional(),expiresAt:z.string().optional(),instructions:z.string().optional(),url:z.string().optional(),userCode:z.string().optional()}),taskInputEventSchema=z.looseObject({requests:z.array(jsonValueSchema.refine(isInputRequest)).min(1),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string()}),taskAuthorizationEventSchema=z.discriminatedUnion(`type`,[z.looseObject({data:z.looseObject({attemptId:z.string().optional(),authorization:authorizationChallengeSchema.optional(),description:z.string(),name:z.string(),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string(),webhookUrl:z.string().optional()}),type:z.literal(`authorization.required`)}),z.looseObject({data:z.looseObject({attemptId:z.string().optional(),authorization:authorizationChallengeSchema.optional(),name:z.string(),outcome:z.enum([`authorized`,`declined`,`failed`,`timed-out`]),reason:z.string().optional(),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string()}),type:z.literal(`authorization.completed`)})]),taskEventCallbackSchema=z.discriminatedUnion(`kind`,[z.object({callId:z.string(),childContinuationToken:z.string(),childSessionId:z.string(),event:taskInputEventSchema,kind:z.literal(`task.input-requested`),subagentName:z.string(),taskId:z.string()}),z.object({callId:z.string(),childContinuationToken:z.string(),childSessionId:z.string(),event:taskAuthorizationEventSchema,kind:z.literal(`task.authorization`),subagentName:z.string(),taskId:z.string()})]),taskTurnStartedCallbackSchema=z.object({kind:z.literal(`turn.started`),sessionId:z.string().min(1),taskId:z.string().min(1),turnId:z.string().min(1)}),sessionResultCallbackSchema=z.discriminatedUnion(`kind`,[z.object({callId:z.string().min(1),kind:z.literal(`session.completed`),output:jsonValueSchema.optional(),subagentName:z.string().min(1),usage:z.unknown().optional()}),z.object({callId:z.string().min(1),error:jsonValueSchema.optional(),kind:z.literal(`session.failed`),subagentName:z.string().min(1),usage:z.unknown().optional()}),z.object({callId:z.string().min(1),kind:z.literal(`turn.completed`),outcome:agentTurnOutcomeWithCostSchema,output:jsonValueSchema.optional(),subagentName:z.string().min(1)}),z.object({callId:z.string().min(1),error:jsonValueSchema,kind:z.literal(`turn.failed`),outcome:agentTurnOutcomeWithCostSchema,subagentName:z.string().min(1)})]);async function handleSessionCallbackRequest(e,t){let n=t.params.token;if(typeof n!=`string`||n.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});let r;try{r=await e.json()}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}let i=projectTaskEvent(r,n);if(i instanceof Response)return i;if(i!==void 0){try{await resumeHook(n,i)}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}let a=rejectDirectTaskTurnStarted(r,n);if(a instanceof Response)return a;if(a!==void 0){try{await resumeHook(n,a)}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}let o=projectSessionCallbackResult(r);if(o instanceof Response)return o;try{await resumeHook(n,{kind:`runtime-action-result`,results:[o]})}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}function callbackKind(e){if(typeof e==`object`&&e)return Reflect.get(e,`kind`)}function projectTaskEvent(e,t){let n=callbackKind(e);if(n!==`task.input-requested`&&n!==`task.authorization`)return;let r=taskEventCallbackSchema.safeParse(e);if(!r.success)return Response.json({error:`Invalid task event callback.`,ok:!1},{status:400});let i=r.data;if(readTaskIdFromInboxToken(t)!==void 0){let e=rejectMismatchedTaskToken(t,i.taskId);return e===void 0?Response.json({error:`Direct subagent task events are no longer accepted.`,ok:!1},{status:410}):e}return i.kind===`task.input-requested`?{callId:i.callId,childContinuationToken:i.childContinuationToken,childSessionId:i.childSessionId,event:i.event,kind:`subagent-input-request`,subagentName:i.subagentName}:{callId:i.callId,childSessionId:i.childSessionId,event:i.event,kind:`subagent-authorization-event`,subagentName:i.subagentName}}function rejectDirectTaskTurnStarted(e,t){if(callbackKind(e)!==`turn.started`)return;let n=taskTurnStartedCallbackSchema.safeParse(e);if(!n.success)return Response.json({error:`Invalid task turn-start callback.`,ok:!1},{status:400});let r=rejectMismatchedTaskToken(t,n.data.taskId);return r===void 0?Response.json({error:`Direct subagent task turn callbacks are no longer accepted.`,ok:!1},{status:410}):r}function rejectMismatchedTaskToken(e,t){return readTaskIdFromInboxToken(e)===t?void 0:Response.json({error:`Task callback token mismatch.`,ok:!1},{status:403})}function projectSessionCallbackResult(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let t=callbackKind(e);if(t!==`session.completed`&&t!==`session.failed`&&t!==`turn.completed`&&t!==`turn.failed`)return Response.json({error:`Unsupported callback kind.`,ok:!1},{status:400});let n=sessionResultCallbackSchema.safeParse(e);if(!n.success)return Response.json({error:`Invalid session result callback.`,ok:!1},{status:400});let r=n.data;if(r.kind===`session.completed`){let e=r.output??``,t=parseCallbackUsage(r.usage),n={callId:r.callId,kind:`subagent-result`,origin:`child`,outcome:{kind:`terminal`,result:{kind:`succeeded`,output:e},usageDelta:t??ZERO_TOKEN_USAGE},output:e,subagentName:r.subagentName};return t===void 0?n:{...n,usage:t}}if(r.kind===`session.failed`){let e=r.error===void 0?{code:REMOTE_AGENT_FAILED,message:`Remote agent failed.`}:r.error,t=parseCallbackUsage(r.usage);return{callId:r.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:{kind:`terminal`,result:{error:e,kind:`failed`},usageDelta:t??ZERO_TOKEN_USAGE},output:e,subagentName:r.subagentName}}return r.kind===`turn.completed`?{callId:r.callId,kind:`subagent-result`,origin:`child`,outcome:r.outcome,output:r.output??``,subagentName:r.subagentName,usage:r.outcome.usageDelta}:{callId:r.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:r.outcome,output:r.error,subagentName:r.subagentName}}function parseCallbackUsage(e){if(e===void 0)return;let t=tokenUsageWithCostSchema.safeParse(e);return t.success?t.data:void 0}export{handleSessionCallbackRequest};
@@ -10,14 +10,6 @@ export declare function fireTaskEventCallbackStep(input: {
10
10
  type: "input.requested";
11
11
  }>;
12
12
  }): Promise<void>;
13
- /** Sends one remote task progress update over its existing parent callback. */
14
- export declare function fireTaskUpdateCallbackStep(input: {
15
- readonly callback: unknown;
16
- readonly callId: string;
17
- readonly updateIndex: number;
18
- readonly updateEpoch: string;
19
- readonly message: string;
20
- }): Promise<string | undefined>;
21
13
  /**
22
14
  * Sends the configured session terminal callback.
23
15
  *
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseSessionCallback}from"#channel/session-callback.js";import{SESSION_FAILED}from"#subagents/agent-handle-errors.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.session-callback`);async function fireTaskEventCallbackStep(e){"use step";let t=parseSerializedSessionCallback(e.callback);if(t.taskId===void 0)return;let n=e.event.type===`input.requested`,r=n?`task.input-requested`:`task.authorization`,i=await postSessionCallbackRequest({body:{callId:t.callId,childContinuationToken:e.childContinuationToken,childSessionId:e.childSessionId,event:n?e.event.data:e.event,kind:r,subagentName:t.subagentName,taskId:t.taskId},url:t.url});if(!i.ok)throw Error(`Task event callback failed with HTTP ${i.status}.`)}async function fireTaskUpdateCallbackStep(e){"use step";let t=parseSerializedSessionCallback(e.callback);if(t.taskId===void 0)return;let n=await postSessionCallbackRequest({body:{callId:e.callId,updateIndex:e.updateIndex,updateEpoch:e.updateEpoch,kind:`task.update`,message:e.message,taskId:t.taskId},url:t.url});if(!n.ok)throw Error(`Task update callback failed with HTTP ${n.status}.`);return t.taskId}async function fireSessionCallbackStep(e){"use step";let t=e.serializedContext[`eve.sessionId`]??``,n=e.serializedContext[SessionCallbackKey.name];if(n===void 0)return;let r;try{r=parseSerializedSessionCallback(n)}catch(e){throw log.error(`invalid session callback metadata`,{error:e,sessionId:t}),e}let i=e.status===`completed`?buildCompletedCallbackBody({callback:r,output:e.output,sessionId:t,usage:e.usage}):{callId:r.callId,error:{code:SESSION_FAILED,message:toErrorMessage(e.error)},kind:`session.failed`,sessionId:t,subagentName:r.subagentName,usage:e.usage},a=await postSessionCallbackRequest({body:i,url:r.url});if(!a.ok)throw Error(`Session callback failed with HTTP ${a.status}.`)}function buildCompletedCallbackBody(e){let t={callId:e.callback.callId,kind:`session.completed`,output:e.output??``,sessionId:e.sessionId,subagentName:e.callback.subagentName};return e.usage===void 0?t:{...t,usage:e.usage}}function parseSerializedSessionCallback(e){let t=parseSessionCallback(e);if(!t.ok)throw Error(`Serialized session callback is invalid.`,{cause:t.cause});return t.callback}export{fireSessionCallbackStep,fireTaskEventCallbackStep,fireTaskUpdateCallbackStep};
1
+ import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseSessionCallback}from"#channel/session-callback.js";import{SESSION_FAILED}from"#subagents/agent-handle-errors.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.session-callback`);async function fireTaskEventCallbackStep(e){"use step";let t=parseSerializedSessionCallback(e.callback);if(t.taskId===void 0)return;let n=e.event.type===`input.requested`,r=n?`task.input-requested`:`task.authorization`,i=await postSessionCallbackRequest({body:{callId:t.callId,childContinuationToken:e.childContinuationToken,childSessionId:e.childSessionId,event:n?e.event.data:e.event,kind:r,subagentName:t.subagentName,taskId:t.taskId},url:t.url});if(!i.ok)throw Error(`Task event callback failed with HTTP ${i.status}.`)}async function fireSessionCallbackStep(e){"use step";let t=e.serializedContext[`eve.sessionId`]??``,n=e.serializedContext[SessionCallbackKey.name];if(n===void 0)return;let r;try{r=parseSerializedSessionCallback(n)}catch(e){throw log.error(`invalid session callback metadata`,{error:e,sessionId:t}),e}let i=e.status===`completed`?buildCompletedCallbackBody({callback:r,output:e.output,sessionId:t,usage:e.usage}):{callId:r.callId,error:{code:SESSION_FAILED,message:toErrorMessage(e.error)},kind:`session.failed`,sessionId:t,subagentName:r.subagentName,usage:e.usage},a=await postSessionCallbackRequest({body:i,url:r.url});if(!a.ok)throw Error(`Session callback failed with HTTP ${a.status}.`)}function buildCompletedCallbackBody(e){let t={callId:e.callback.callId,kind:`session.completed`,output:e.output??``,sessionId:e.sessionId,subagentName:e.callback.subagentName};return e.usage===void 0?t:{...t,usage:e.usage}}function parseSerializedSessionCallback(e){let t=parseSessionCallback(e);if(!t.ok)throw Error(`Serialized session callback is invalid.`,{cause:t.cause});return t.callback}export{fireSessionCallbackStep,fireTaskEventCallbackStep};
@@ -1,5 +1,14 @@
1
1
  import type { StepInput } from "#harness/types.js";
2
+ import type { SessionParent, SessionTraceContext } from "#channel/types.js";
3
+ import type { ChannelAudience } from "#shared/channel-audience.js";
2
4
  import { type JsonObject, type JsonValue } from "#shared/json.js";
5
+ export interface SubagentParentContext {
6
+ readonly conversationId?: string;
7
+ readonly lineage: SessionParent;
8
+ readonly continuationToken?: string;
9
+ readonly traceContext?: SessionTraceContext;
10
+ readonly originAudience?: ChannelAudience;
11
+ }
3
12
  /**
4
13
  * Narrowed form of {@link StepInput} whose `message` is always a plain string.
5
14
  * Delegated child runs receive a synthesized text-only prompt.
@@ -1,6 +1,7 @@
1
1
  import { type ResetResponse } from "#protocol/reset-session.js";
2
- import type { ActivityObserverConfig, CancelTurnResult, SessionAuthContext, SessionTraceContext } from "#channel/types.js";
2
+ import type { ActivityObserverConfig, CancelTurnResult, SessionAuthContext } from "#channel/types.js";
3
3
  import type { ChannelAudience } from "#shared/channel-audience.js";
4
+ import { type SubagentParentContext } from "#subagents/invocation.js";
4
5
  import type { HarnessSession } from "#harness/types.js";
5
6
  import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";
6
7
  import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
@@ -16,7 +17,6 @@ export declare function startRemoteAgentSession(input: {
16
17
  /** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */
17
18
  readonly auth?: SessionAuthContext | null;
18
19
  readonly callbackBaseUrl: string | undefined;
19
- readonly callbackToken?: string;
20
20
  readonly originAudience?: ChannelAudience;
21
21
  readonly activityObserver?: ActivityObserverConfig;
22
22
  /** The root initiator's principal, forwarded alongside {@link auth}. */
@@ -27,7 +27,7 @@ export declare function startRemoteAgentSession(input: {
27
27
  * created instead of starting a second one.
28
28
  */
29
29
  readonly operationId?: string;
30
- readonly parentTraceContext?: SessionTraceContext;
30
+ readonly parent?: Omit<SubagentParentContext, "lineage">;
31
31
  readonly remote: ResolvedRuntimeRemoteAgentNode;
32
32
  readonly session: HarnessSession;
33
33
  readonly taskId?: string;
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{createEveCallbackRoutePath,createEveSessionCancelRoutePath,createEveSessionResetRoutePath,createEveSessionRoutePath}from"#protocol/routes.js";import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{ResetResponseSchema}from"#protocol/reset-session.js";import{formatTraceparent}from"#protocol/traceparent.js";import{writeForwardedAudienceBaggage}from"#protocol/baggage.js";import{decisionToTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{readTaskIdFromInboxToken}from"#tasks/task-inbox-token.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#subagents/invocation.js";import{AgentHandleError}from"#protocol/agent-handle-error.js";import{createRemoteAgentRouteUrl}from"#subagents/remote-route-url.js";const CreateSessionResponseSchema=z.object({ok:z.literal(!0),sessionId:z.string().min(1),status:z.literal(`accepted`)});var RemoteAgentCancelRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentCancelRequestError`,this.retryable=t.retryable}};async function startRemoteAgentSession(e){let t=e.callbackToken??e.session.continuationToken;if(!t)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!e.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let n=buildForwardedPrincipalField(e),r={capabilities:{},callback:{callId:e.action.callId,subagentName:e.action.remoteAgentName,taskId:e.taskId??readTaskIdFromInboxToken(t),token:t,url:createWorkflowCallbackUrl(e.callbackBaseUrl,createEveCallbackRoutePath(t))},message:formatRemoteAgentCallInputMessage({action:e.action,remote:e.remote}),mode:`conversation`,outputSchema:normalizeRequestedOutputSchema(e.action.input.outputSchema)??e.remote.outputSchema};e.activityObserver!==void 0&&(r.activityObserver=e.activityObserver),n!==void 0&&(r.forwardedPrincipal=n),e.operationId!==void 0&&(r.operationId=e.operationId);let i=await resolveRemoteAgentRequestHeaders(e.remote),a=formatTraceparent(e.parentTraceContext);a!==void 0&&setHeader(i,`traceparent`,a),setHeader(i,`baggage`,writeForwardedAudienceBaggage(readHeader(i,`baggage`),buildForwardedTraceAssertion({forwardedPrincipal:n,originAudience:e.originAudience,parentTraceContext:e.parentTraceContext,traceparent:a})));let o=await fetch(createRemoteAgentSessionUrl(e.remote),{body:JSON.stringify(r),headers:{"content-type":`application/json`,...i},method:`POST`});if(!o.ok)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session request failed with HTTP ${o.status}.`);let s;try{s=await o.json()}catch{throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was not valid JSON.`)}let c=CreateSessionResponseSchema.safeParse(s);if(!c.success)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was invalid.`);return{sessionId:c.data.sessionId}}function buildForwardedTraceAssertion(e){let t=decisionToTraceContentCeiling(e.parentTraceContext?.decision);if(e.forwardedPrincipal!==void 0&&e.parentTraceContext!==void 0&&(e.parentTraceContext.traceFlags&1)==1&&e.traceparent!==void 0&&t!==void 0)return{ceiling:t,originAudience:e.originAudience??`unknown`}}async function continueRemoteAgentSession(e){let t=buildForwardedPrincipalField(e),n={activityObserver:e.activityObserver,callback:e.callback,message:e.message,outputSchema:e.outputSchema};t!==void 0&&(n.forwardedPrincipal=t);let r=await fetch(createRemoteAgentContinueUrl(e.remote,e.sessionId),{body:JSON.stringify(n),headers:{"content-type":`application/json`,...await resolveRemoteAgentRequestHeaders(e.remote)},method:`POST`});if(!r.ok){let n=await readRemoteAgentErrorCode(r),i=r.status===404||n===AgentHandleError.SessionNotResumable.code,a=r.status===400&&t!==void 0?` The receiver may support forwarded principals only on session creation; upgrade it before retrying.`:``;throw new RemoteAgentContinueRequestError(`Remote agent "${e.remote.name}" continue-session request failed${i?` permanently`:``} with HTTP ${r.status}.${a}`,{deliveryAmbiguous:isAmbiguousRemoteContinueStatus(r.status),retryable:!i})}}var RemoteAgentContinueRequestError=class extends Error{deliveryAmbiguous;retryable;constructor(e,t){super(e),this.name=`RemoteAgentContinueRequestError`,this.deliveryAmbiguous=t.deliveryAmbiguous,this.retryable=t.retryable}};function isRetryableRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.retryable}function isAmbiguousRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.deliveryAmbiguous}function isAmbiguousRemoteContinueStatus(e){return e===408||e===425||e>=500}async function readRemoteAgentErrorCode(e){let t;try{t=await e.json()}catch{return}if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`code`);return typeof n==`string`?n:void 0}function buildForwardedPrincipalField(e){if(e.remote.forwardPrincipal!==!0||e.auth===null||e.auth===void 0)return;let t={current:e.auth};return e.initiatorAuth!==null&&e.initiatorAuth!==void 0&&(t.initiator=e.initiatorAuth),t}async function cancelRemoteAgentTurn(e){let t=e.headers??await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentCancelTurnUrl(e.remote,e.sessionId),{body:e.turnId===void 0&&e.taskId===void 0?void 0:JSON.stringify({taskId:e.taskId,turnId:e.turnId}),headers:t,method:`POST`});if(!n.ok)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn request failed with HTTP ${n.status}.`,{retryable:isRetryableRemoteCancelStatus(n.status)});let r;try{r=await n.json()}catch{throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was not valid JSON.`,{retryable:!1})}let i=CancelTurnResponseSchema.safeParse(r);if(!i.success||i.data.status===`accepted`&&i.data.sessionId!==e.sessionId)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was invalid.`,{retryable:!1});return i.data.status===`accepted`?{sessionId:i.data.sessionId,status:`accepted`}:{status:`no_active_turn`}}function readHeader(e,t){let n=Object.keys(e).find(e=>e.toLowerCase()===t);return n===void 0?void 0:e[n]}function setHeader(e,t,n){for(let n of Object.keys(e))n.toLowerCase()===t&&delete e[n];n!==void 0&&(e[t]=n)}async function resetRemoteAgentSession(e){let t=e.headers??await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentRouteUrl(e.remote.url,createEveSessionResetRoutePath(e.sessionId)),{body:JSON.stringify({reason:`Parent session ended`}),headers:{"content-type":`application/json`,...t},method:`POST`});if(!n.ok)throw Error(`Remote agent "${e.remote.name}" reset-session request failed with HTTP ${n.status}.`);let r=ResetResponseSchema.safeParse(await n.json());if(!r.success||r.data.status===`reset`&&r.data.previousSessionId!==e.sessionId)throw Error(`Remote agent "${e.remote.name}" reset-session response was invalid.`);return r.data}function isRetryableRemoteAgentCancelError(e){return!(e instanceof RemoteAgentCancelRequestError)||e.retryable}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(e.dynamicRemoteAgent!==void 0){if(t===void 0)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);let n=resolveDynamicRemoteAgentCredentials(e.dynamicRemoteAgent),r=e.dynamicRemoteAgent,i={description:r.description,kind:`remote`,logicalPath:t.logicalPath,name:e.remoteAgentName,nodeId:e.nodeId,outputSchema:r.outputSchema,path:r.path,sourceId:t.sourceId,sourceKind:`module`,url:r.url};return r.forwardPrincipal!==void 0&&(i.forwardPrincipal=r.forwardPrincipal),n.auth!==void 0&&(i.auth=n.auth),n.headers!==void 0&&(i.headers=n.headers),i}if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}async function resolveRemoteAgentStreamHeaders(e){if(e.resolverId===void 0)return{};let t=new Set([e.bundle.graph.root,...e.bundle.graph.nodesByNodeId.values()]);for(let n of t){let t=n.subagentRegistry.subagentsByNodeId.get(e.resolverId)?.definition;if(t!==void 0){if(t.kind!==`remote`||t.name!==e.name||t.url!==e.url)throw Error(`Remote child stream resolver does not match the authored remote agent.`);return await resolveRemoteAgentRequestHeaders(t)}}return await resolveRemoteAgentRequestHeaders(resolveDynamicRemoteAgentCredentials({credentialsStepId:e.resolverId,description:``,path:``,url:e.url}))}function resolveDynamicRemoteAgentCredentials(e){if(e.credentialsStepId===void 0)return{};let t=getStepRegistry().get(e.credentialsStepId);if(t===void 0)throw Error(`Dynamic remote subagent credentials function "${e.credentialsStepId}" is not registered.`);let n=expectObjectRecord(t(),`Dynamic remote subagent credentials are invalid.`),r={};return n.auth!==void 0&&(r.auth=expectFunction(n.auth,`Dynamic remote subagent auth is invalid.`)),n.headers!==void 0&&(r.headers=resolveDynamicRemoteAgentHeaders(n.headers)),r}function resolveDynamicRemoteAgentHeaders(e){if(typeof e==`function`)return e;let t=expectObjectRecord(e,`Dynamic remote subagent headers are invalid.`);for(let e of Object.values(t))if(typeof e!=`string`)throw Error(`Dynamic remote subagent headers are invalid.`);return t}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function createRemoteAgentSessionUrl(e){return createRemoteAgentRouteUrl(e.url,e.path)}function createRemoteAgentCancelTurnUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionCancelRoutePath(t))}function createRemoteAgentContinueUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionRoutePath(t))}function isRetryableRemoteCancelStatus(e){return e===408||e===425||e===429||e>=500}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.action.input.message==`string`?e.action.input.message:``;return formatSubagentInput({description:e.remote.description,message:t,name:e.action.remoteAgentName,type:`remote`}).message}export{RemoteAgentContinueRequestError,cancelRemoteAgentTurn,continueRemoteAgentSession,isAmbiguousRemoteAgentContinueError,isRetryableRemoteAgentCancelError,isRetryableRemoteAgentContinueError,resetRemoteAgentSession,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders,startRemoteAgentSession};
1
+ import{z}from"#compiled/zod/index.js";import{createEveCallbackRoutePath,createEveSessionCancelRoutePath,createEveSessionResetRoutePath,createEveSessionRoutePath}from"#protocol/routes.js";import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{ResetResponseSchema}from"#protocol/reset-session.js";import{formatTraceparent}from"#protocol/traceparent.js";import{writeForwardedAudienceBaggage}from"#protocol/baggage.js";import{writeConversationBaggage}from"#tracing/conversation-context.js";import{decisionToTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{readTaskIdFromInboxToken}from"#tasks/task-inbox-token.js";import{formatSubagentInput,normalizeRequestedOutputSchema}from"#subagents/invocation.js";import{AgentHandleError}from"#protocol/agent-handle-error.js";import{createRemoteAgentRouteUrl}from"#subagents/remote-route-url.js";const CreateSessionResponseSchema=z.object({ok:z.literal(!0),sessionId:z.string().min(1),status:z.literal(`accepted`)});var RemoteAgentCancelRequestError=class extends Error{retryable;constructor(e,t){super(e),this.name=`RemoteAgentCancelRequestError`,this.retryable=t.retryable}};async function startRemoteAgentSession(e){let t=e.parent?.continuationToken??e.session.continuationToken;if(!t)throw Error(`Cannot dispatch remote agent without a parent continuation token.`);if(!e.callbackBaseUrl)throw Error(`Cannot dispatch remote agent without a callback base URL.`);let n=buildForwardedPrincipalField(e),r={capabilities:{},callback:{callId:e.action.callId,subagentName:e.action.remoteAgentName,taskId:e.taskId??readTaskIdFromInboxToken(t),token:t,url:createWorkflowCallbackUrl(e.callbackBaseUrl,createEveCallbackRoutePath(t))},message:formatRemoteAgentCallInputMessage({action:e.action,remote:e.remote}),mode:`conversation`,outputSchema:normalizeRequestedOutputSchema(e.action.input.outputSchema)??e.remote.outputSchema};e.activityObserver!==void 0&&(r.activityObserver=e.activityObserver),n!==void 0&&(r.forwardedPrincipal=n),e.operationId!==void 0&&(r.operationId=e.operationId);let i=await resolveRemoteAgentRequestHeaders(e.remote),a=formatTraceparent(e.parent?.traceContext);a!==void 0&&setHeader(i,`traceparent`,a);let o=writeForwardedAudienceBaggage(readHeader(i,`baggage`),buildForwardedTraceAssertion({forwardedPrincipal:n,originAudience:e.originAudience,parentTraceContext:e.parent?.traceContext,traceparent:a}));setHeader(i,`baggage`,writeConversationBaggage(o,e.parent?.conversationId));let s=await fetch(createRemoteAgentSessionUrl(e.remote),{body:JSON.stringify(r),headers:{"content-type":`application/json`,...i},method:`POST`});if(!s.ok)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session request failed with HTTP ${s.status}.`);let c;try{c=await s.json()}catch{throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was not valid JSON.`)}let l=CreateSessionResponseSchema.safeParse(c);if(!l.success)throw Error(`Remote agent "${e.action.remoteAgentName}" create-session response was invalid.`);return{sessionId:l.data.sessionId}}function buildForwardedTraceAssertion(e){let t=decisionToTraceContentCeiling(e.parentTraceContext?.decision);if(e.forwardedPrincipal!==void 0&&e.parentTraceContext!==void 0&&(e.parentTraceContext.traceFlags&1)==1&&e.traceparent!==void 0&&t!==void 0)return{ceiling:t,originAudience:e.originAudience??`unknown`}}async function continueRemoteAgentSession(e){let t=buildForwardedPrincipalField(e),n={activityObserver:e.activityObserver,callback:e.callback,message:e.message,outputSchema:e.outputSchema};t!==void 0&&(n.forwardedPrincipal=t);let r=await fetch(createRemoteAgentContinueUrl(e.remote,e.sessionId),{body:JSON.stringify(n),headers:{"content-type":`application/json`,...await resolveRemoteAgentRequestHeaders(e.remote)},method:`POST`});if(!r.ok){let n=await readRemoteAgentErrorCode(r),i=r.status===404||n===AgentHandleError.SessionNotResumable.code,a=r.status===400&&t!==void 0?` The receiver may support forwarded principals only on session creation; upgrade it before retrying.`:``;throw new RemoteAgentContinueRequestError(`Remote agent "${e.remote.name}" continue-session request failed${i?` permanently`:``} with HTTP ${r.status}.${a}`,{deliveryAmbiguous:isAmbiguousRemoteContinueStatus(r.status),retryable:!i})}}var RemoteAgentContinueRequestError=class extends Error{deliveryAmbiguous;retryable;constructor(e,t){super(e),this.name=`RemoteAgentContinueRequestError`,this.deliveryAmbiguous=t.deliveryAmbiguous,this.retryable=t.retryable}};function isRetryableRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.retryable}function isAmbiguousRemoteAgentContinueError(e){return!(e instanceof RemoteAgentContinueRequestError)||e.deliveryAmbiguous}function isAmbiguousRemoteContinueStatus(e){return e===408||e===425||e>=500}async function readRemoteAgentErrorCode(e){let t;try{t=await e.json()}catch{return}if(typeof t!=`object`||!t)return;let n=Reflect.get(t,`code`);return typeof n==`string`?n:void 0}function buildForwardedPrincipalField(e){if(e.remote.forwardPrincipal!==!0||e.auth===null||e.auth===void 0)return;let t={current:e.auth};return e.initiatorAuth!==null&&e.initiatorAuth!==void 0&&(t.initiator=e.initiatorAuth),t}async function cancelRemoteAgentTurn(e){let t=e.headers??await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentCancelTurnUrl(e.remote,e.sessionId),{body:e.turnId===void 0&&e.taskId===void 0?void 0:JSON.stringify({taskId:e.taskId,turnId:e.turnId}),headers:t,method:`POST`});if(!n.ok)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn request failed with HTTP ${n.status}.`,{retryable:isRetryableRemoteCancelStatus(n.status)});let r;try{r=await n.json()}catch{throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was not valid JSON.`,{retryable:!1})}let i=CancelTurnResponseSchema.safeParse(r);if(!i.success||i.data.status===`accepted`&&i.data.sessionId!==e.sessionId)throw new RemoteAgentCancelRequestError(`Remote agent "${e.remote.name}" cancel-turn response was invalid.`,{retryable:!1});return i.data.status===`accepted`?{sessionId:i.data.sessionId,status:`accepted`}:{status:`no_active_turn`}}function readHeader(e,t){let n=Object.keys(e).find(e=>e.toLowerCase()===t);return n===void 0?void 0:e[n]}function setHeader(e,t,n){for(let n of Object.keys(e))n.toLowerCase()===t&&delete e[n];n!==void 0&&(e[t]=n)}async function resetRemoteAgentSession(e){let t=e.headers??await resolveRemoteAgentRequestHeaders(e.remote),n=await fetch(createRemoteAgentRouteUrl(e.remote.url,createEveSessionResetRoutePath(e.sessionId)),{body:JSON.stringify({reason:`Parent session ended`}),headers:{"content-type":`application/json`,...t},method:`POST`});if(!n.ok)throw Error(`Remote agent "${e.remote.name}" reset-session request failed with HTTP ${n.status}.`);let r=ResetResponseSchema.safeParse(await n.json());if(!r.success||r.data.status===`reset`&&r.data.previousSessionId!==e.sessionId)throw Error(`Remote agent "${e.remote.name}" reset-session response was invalid.`);return r.data}function isRetryableRemoteAgentCancelError(e){return!(e instanceof RemoteAgentCancelRequestError)||e.retryable}function resolveRemoteAgentForAction(e){let t=e.registry.get(e.nodeId)?.definition;if(e.dynamicRemoteAgent!==void 0){if(t===void 0)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);let n=resolveDynamicRemoteAgentCredentials(e.dynamicRemoteAgent),r=e.dynamicRemoteAgent,i={description:r.description,kind:`remote`,logicalPath:t.logicalPath,name:e.remoteAgentName,nodeId:e.nodeId,outputSchema:r.outputSchema,path:r.path,sourceId:t.sourceId,sourceKind:`module`,url:r.url};return r.forwardPrincipal!==void 0&&(i.forwardPrincipal=r.forwardPrincipal),n.auth!==void 0&&(i.auth=n.auth),n.headers!==void 0&&(i.headers=n.headers),i}if(t?.kind!==`remote`)throw Error(`Missing remote agent "${e.remoteAgentName}" in runtime registry.`);return t}async function resolveRemoteAgentStreamHeaders(e){if(e.resolverId===void 0)return{};let t=new Set([e.bundle.graph.root,...e.bundle.graph.nodesByNodeId.values()]);for(let n of t){let t=n.subagentRegistry.subagentsByNodeId.get(e.resolverId)?.definition;if(t!==void 0){if(t.kind!==`remote`||t.name!==e.name||t.url!==e.url)throw Error(`Remote child stream resolver does not match the authored remote agent.`);return await resolveRemoteAgentRequestHeaders(t)}}return await resolveRemoteAgentRequestHeaders(resolveDynamicRemoteAgentCredentials({credentialsStepId:e.resolverId,description:``,path:``,url:e.url}))}function resolveDynamicRemoteAgentCredentials(e){if(e.credentialsStepId===void 0)return{};let t=getStepRegistry().get(e.credentialsStepId);if(t===void 0)throw Error(`Dynamic remote subagent credentials function "${e.credentialsStepId}" is not registered.`);let n=expectObjectRecord(t(),`Dynamic remote subagent credentials are invalid.`),r={};return n.auth!==void 0&&(r.auth=expectFunction(n.auth,`Dynamic remote subagent auth is invalid.`)),n.headers!==void 0&&(r.headers=resolveDynamicRemoteAgentHeaders(n.headers)),r}function resolveDynamicRemoteAgentHeaders(e){if(typeof e==`function`)return e;let t=expectObjectRecord(e,`Dynamic remote subagent headers are invalid.`);for(let e of Object.values(t))if(typeof e!=`string`)throw Error(`Dynamic remote subagent headers are invalid.`);return t}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function createRemoteAgentSessionUrl(e){return createRemoteAgentRouteUrl(e.url,e.path)}function createRemoteAgentCancelTurnUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionCancelRoutePath(t))}function createRemoteAgentContinueUrl(e,t){return createRemoteAgentRouteUrl(e.url,createEveSessionRoutePath(t))}function isRetryableRemoteCancelStatus(e){return e===408||e===425||e===429||e>=500}async function resolveRemoteAgentRequestHeaders(e){let t={};return e.headers!==void 0&&Object.assign(t,typeof e.headers==`function`?await e.headers():e.headers),e.auth!==void 0&&Object.assign(t,(await e.auth()).headers),t}function formatRemoteAgentCallInputMessage(e){let t=typeof e.action.input.message==`string`?e.action.input.message:``;return formatSubagentInput({description:e.remote.description,message:t,name:e.action.remoteAgentName,type:`remote`}).message}export{RemoteAgentContinueRequestError,cancelRemoteAgentTurn,continueRemoteAgentSession,isAmbiguousRemoteAgentContinueError,isRetryableRemoteAgentCancelError,isRetryableRemoteAgentContinueError,resetRemoteAgentSession,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders,startRemoteAgentSession};
@@ -4,15 +4,12 @@ import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool
4
4
  import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
5
5
  import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
6
6
  import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
7
+ import type { SubagentParentContext } from "#subagents/invocation.js";
7
8
  type DynamicSubagentAgentConfig = Parameters<typeof createWorkflowRuntime>[0]["dynamicSubagentAgentConfig"];
8
9
  /** Starts one local subagent after dispatch planning has selected its target. */
9
10
  export declare function startLocalSubagent(input: {
10
11
  readonly action: RuntimeSubagentDispatchRequest;
11
12
  readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
12
- readonly batchEvent: {
13
- readonly sequence: number;
14
- readonly turnId: string;
15
- };
16
13
  readonly bundle: CompiledBundle;
17
14
  readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
18
15
  readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
@@ -21,8 +18,7 @@ export declare function startLocalSubagent(input: {
21
18
  readonly fanoutSize: number;
22
19
  readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
23
20
  readonly localDevRequest?: LocalDevRequestProvenance;
24
- readonly parentContinuationToken: string | undefined;
25
- readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
21
+ readonly parent: SubagentParentContext;
26
22
  readonly activityObserver?: Parameters<typeof buildSubagentRunInput>[0]["activityObserver"];
27
23
  readonly sandboxSessionId: string;
28
24
  readonly session: RuntimeSession;
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{ContextContainer,contextStorage}from"#context/container.js";import{toErrorMessage}from"#shared/errors.js";import{createWorkflowRuntime,waitForCommandHookOwner}from"#execution/workflow-runtime.js";import{buildSubagentRunInput}from"#subagents/tool.js";import{SUBAGENT_START_FAILED}from"#subagents/agent-handle-errors.js";const log=createLogger(`execution.subagent-start-local`);async function startLocalSubagent(e){let{action:t,source:n}=e,r=createWorkflowRuntime({compiledArtifactsSource:e.bundle.compiledArtifactsSource,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,nodeId:t.nodeId}),{childContinuationToken:i,runInput:a}=buildSubagentRunInput({action:t,auth:e.auth,batchEvent:e.batchEvent,capabilities:e.capabilities,channelMetadata:e.channelMetadata,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,graph:e.bundle.graph,parentContinuationToken:e.parentContinuationToken,parentTraceContext:e.parentTraceContext,activityObserver:e.activityObserver,sandboxSessionId:e.sandboxSessionId,session:e.session,selfAgent:n.type===`runtime`,source:n,taskId:e.taskId}),o=n.type===`runtime`?`agent/self`:`agent/local`,s;try{await contextStorage.run(new ContextContainer({localDevRequest:e.localDevRequest}),()=>r.createSession(a)),s=(await waitForCommandHookOwner(i)).runId}catch(n){return logError(log,`local subagent start failed`,n,{callId:t.callId,nodeId:t.nodeId,subagentName:t.subagentName}),{kind:`error`,result:{callId:t.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:SUBAGENT_START_FAILED,message:toErrorMessage(n)},subagentName:t.subagentName},session:e.currentSession}}return{address:{continuationToken:i,kind:o,sessionId:s},callId:t.callId,kind:`called`,name:t.name,session:e.currentSession,toolName:t.subagentName}}export{startLocalSubagent};
1
+ import{createLogger,logError}from"#internal/logging.js";import{ContextContainer,contextStorage}from"#context/container.js";import{toErrorMessage}from"#shared/errors.js";import{createWorkflowRuntime,waitForCommandHookOwner}from"#execution/workflow-runtime.js";import{buildSubagentRunInput}from"#subagents/tool.js";import{SUBAGENT_START_FAILED}from"#subagents/agent-handle-errors.js";const log=createLogger(`execution.subagent-start-local`);async function startLocalSubagent(e){let{action:t,source:n}=e,r=createWorkflowRuntime({compiledArtifactsSource:e.bundle.compiledArtifactsSource,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,nodeId:t.nodeId}),{childContinuationToken:i,runInput:a}=buildSubagentRunInput({action:t,auth:e.auth,capabilities:e.capabilities,channelMetadata:e.channelMetadata,fanoutSize:e.fanoutSize,initiatorAuth:e.initiatorAuth,graph:e.bundle.graph,parent:e.parent,activityObserver:e.activityObserver,sandboxSessionId:e.sandboxSessionId,session:e.session,selfAgent:n.type===`runtime`,source:n,taskId:e.taskId}),o=n.type===`runtime`?`agent/self`:`agent/local`,s;try{await contextStorage.run(new ContextContainer({localDevRequest:e.localDevRequest}),()=>r.createSession(a)),s=(await waitForCommandHookOwner(i)).runId}catch(n){return logError(log,`local subagent start failed`,n,{callId:t.callId,nodeId:t.nodeId,subagentName:t.subagentName}),{kind:`error`,result:{callId:t.callId,isError:!0,kind:`subagent-result`,origin:`dispatch`,output:{code:SUBAGENT_START_FAILED,message:toErrorMessage(n)},subagentName:t.subagentName},session:e.currentSession}}return{address:{continuationToken:i,kind:o,sessionId:s},callId:t.callId,kind:`called`,name:t.name,session:e.currentSession,toolName:t.subagentName}}export{startLocalSubagent};
@@ -2,23 +2,17 @@ import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch
2
2
  import { resolveRemoteAgentForAction, startRemoteAgentSession } from "#subagents/remote-dispatch.js";
3
3
  import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";
4
4
  import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
5
- import type { ChannelAudience } from "#shared/channel-audience.js";
5
+ import type { SubagentParentContext } from "#subagents/invocation.js";
6
6
  /** Starts one remote subagent after dispatch planning has selected its target. */
7
7
  export declare function startRemoteSubagent(input: {
8
8
  readonly action: RuntimeRemoteAgentDispatchRequest;
9
9
  readonly auth: Parameters<typeof startRemoteAgentSession>[0]["auth"];
10
- readonly batchEvent: {
11
- readonly sequence: number;
12
- readonly turnId: string;
13
- };
14
10
  readonly bundle: CompiledBundle;
15
11
  readonly callbackBaseUrl: string | undefined;
16
- readonly originAudience: ChannelAudience;
17
12
  readonly currentSession: RuntimeSession;
18
13
  readonly dynamicRemoteAgent?: NonNullable<Parameters<typeof resolveRemoteAgentForAction>[0]["dynamicRemoteAgent"]>;
19
14
  readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
20
- readonly parentContinuationToken: string | undefined;
21
- readonly parentTraceContext: Parameters<typeof startRemoteAgentSession>[0]["parentTraceContext"];
15
+ readonly parent: SubagentParentContext;
22
16
  readonly activityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];
23
17
  readonly session: RuntimeSession;
24
18
  readonly taskId?: string;
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#subagents/remote-dispatch.js";import{deriveChildActivityObserverConfig}from"#execution/activity-work.js";import{createRemoteAgentStartFailureResult}from"#execution/dispatch-action-failures.js";import{mintStartOperation}from"#execution/dispatch-start-operation.js";const log=createLogger(`execution.subagent-start-remote`);async function startRemoteSubagent(e){let{action:t}=e,n=deriveChildActivityObserverConfig({activityObserver:e.activityObserver,callId:t.callId,kind:`remote-agent`,name:t.remoteAgentName,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),r,i;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);r=e.callbackBaseUrl,i=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:t.nodeId,remoteAgentName:t.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(n){return logError(log,`remote agent start failed`,n,{remoteAgentName:t.remoteAgentName,nodeId:t.nodeId,callId:t.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:t,error:n}),session:e.currentSession}}let{operation:a}=mintStartOperation({callId:t.callId,name:t.remoteAgentName,nodeId:t.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.batchEvent.turnId}),o={resolverId:e.dynamicRemoteAgent===void 0?t.nodeId:e.dynamicRemoteAgent.credentialsStepId};try{let s=await startRemoteAgentSession({action:t,auth:e.auth,callbackBaseUrl:r,callbackToken:e.parentContinuationToken,originAudience:e.originAudience,initiatorAuth:e.initiatorAuth,operationId:a.id,parentTraceContext:e.parentTraceContext,activityObserver:n,remote:i,session:e.session,taskId:e.taskId});return{address:{callbackBaseUrl:r,credentialResolver:o,kind:`agent/remote`,sessionId:s.sessionId,url:i.url},callId:t.callId,kind:`called`,name:t.name,session:e.currentSession,toolName:t.remoteAgentName}}catch(n){return logError(log,`remote agent start failed`,n,{remoteAgentName:t.remoteAgentName,nodeId:t.nodeId,callId:t.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:t,error:n}),session:e.currentSession}}}export{startRemoteSubagent};
1
+ import{createLogger,logError}from"#internal/logging.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#subagents/remote-dispatch.js";import{deriveChildActivityObserverConfig}from"#execution/activity-work.js";import{createRemoteAgentStartFailureResult}from"#execution/dispatch-action-failures.js";import{mintStartOperation}from"#execution/dispatch-start-operation.js";const log=createLogger(`execution.subagent-start-remote`);async function startRemoteSubagent(e){let{action:t}=e,n=deriveChildActivityObserverConfig({activityObserver:e.activityObserver,callId:t.callId,kind:`remote-agent`,name:t.remoteAgentName,parentSessionId:e.session.sessionId,parentTurnId:e.parent.lineage.turn.id}),r,i;try{if(e.callbackBaseUrl===void 0)throw Error(`Cannot dispatch remote agent without a callback base URL.`);r=e.callbackBaseUrl,i=resolveRemoteAgentForAction({dynamicRemoteAgent:e.dynamicRemoteAgent,nodeId:t.nodeId,remoteAgentName:t.remoteAgentName,registry:e.bundle.subagentRegistry.subagentsByNodeId})}catch(n){return logError(log,`remote agent start failed`,n,{remoteAgentName:t.remoteAgentName,nodeId:t.nodeId,callId:t.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:t,error:n}),session:e.currentSession}}let{operation:a}=mintStartOperation({callId:t.callId,name:t.remoteAgentName,nodeId:t.nodeId,parentSessionId:e.session.sessionId,parentTurnId:e.parent.lineage.turn.id}),o={resolverId:e.dynamicRemoteAgent===void 0?t.nodeId:e.dynamicRemoteAgent.credentialsStepId};try{let s=await startRemoteAgentSession({action:t,auth:e.auth,callbackBaseUrl:r,originAudience:e.parent.originAudience,initiatorAuth:e.initiatorAuth,operationId:a.id,parent:e.parent,activityObserver:n,remote:i,session:e.session,taskId:e.taskId});return{address:{callbackBaseUrl:r,credentialResolver:o,kind:`agent/remote`,sessionId:s.sessionId,url:i.url},callId:t.callId,kind:`called`,name:t.name,session:e.currentSession,toolName:t.remoteAgentName}}catch(n){return logError(log,`remote agent start failed`,n,{remoteAgentName:t.remoteAgentName,nodeId:t.nodeId,callId:t.callId}),{kind:`error`,result:createRemoteAgentStartFailureResult({action:t,error:n}),session:e.currentSession}}}export{startRemoteSubagent};