eve 0.81.1 → 0.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/src/channel/channel-address.d.ts +21 -2
- package/dist/src/channel/channel-address.js +1 -1
- package/dist/src/channel/channel-operations.d.ts +32 -1
- package/dist/src/channel/channel-operations.js +1 -1
- package/dist/src/channel/delivery-idempotency.d.ts +4 -0
- package/dist/src/channel/delivery-idempotency.js +1 -0
- package/dist/src/channel/routes.d.ts +6 -0
- package/dist/src/channel/session.d.ts +5 -0
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +14 -11
- package/dist/src/chunks/{use-eve-agent-Bp6nbhfV.js → use-eve-agent-DTu78IAF.js} +36 -0
- package/dist/src/chunks/{use-eve-agent-DLkjJIm3.js → use-eve-agent-DlznYwQk.js} +36 -0
- package/dist/src/cli/dev/command-options.d.ts +1 -0
- package/dist/src/cli/dev/diagnostic-dump.js +1 -1
- package/dist/src/cli/run.d.ts +1 -0
- package/dist/src/cli/run.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/message-reducer-types.d.ts +7 -3
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/client/transcript-reducer.d.ts +6 -3
- package/dist/src/client/transcript-reducer.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +19 -18
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/load-binding-namespace.d.ts +2 -0
- package/dist/src/compiler/load-binding-namespace.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/module-lifecycle.d.ts +1 -1
- package/dist/src/compiler/module-lifecycle.js +1 -1
- package/dist/src/compiler/module-map.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/project-sources.d.ts +6 -0
- package/dist/src/compiler/project-sources.js +1 -1
- package/dist/src/context/keys.d.ts +2 -0
- package/dist/src/context/keys.js +1 -1
- package/dist/src/evals/cli/eval-state-directory.d.ts +7 -0
- package/dist/src/evals/cli/eval-state-directory.js +1 -0
- package/dist/src/evals/cli/eval.js +2 -2
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/support.d.ts +2 -0
- package/dist/src/eve-channel/support.js +1 -1
- package/dist/src/eve-channel/types.d.ts +7 -0
- package/dist/src/execution/agent-sessions/context.d.ts +2 -13
- package/dist/src/execution/agent-sessions/context.js +1 -1
- package/dist/src/execution/agent-sessions/runtime-overrides.d.ts +5 -0
- package/dist/src/execution/agent-sessions/runtime-overrides.js +1 -0
- package/dist/src/execution/agent-sessions/session.d.ts +2 -2
- package/dist/src/execution/agent-sessions/session.js +1 -1
- package/dist/src/execution/agent-sessions/steps.d.ts +2 -0
- package/dist/src/execution/agent-sessions/steps.js +1 -1
- package/dist/src/execution/coordination-dispatch-shared.d.ts +5 -5
- package/dist/src/execution/coordination-dispatch-step.d.ts +17 -2
- package/dist/src/execution/coordination-dispatch-step.js +1 -1
- package/dist/src/execution/create-session-step.d.ts +5 -2
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/deliver-payloads.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +0 -1
- package/dist/src/execution/dynamic-connection-recovery.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/effective-agent-config.d.ts +8 -2
- package/dist/src/execution/effective-agent-config.js +1 -1
- package/dist/src/execution/install-workflow-deployment-id.d.ts +3 -0
- package/dist/src/execution/install-workflow-deployment-id.js +1 -0
- package/dist/src/execution/legacy-session/turn-workflow.js +1 -1
- package/dist/src/execution/node-step.d.ts +1 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/runtime-context.d.ts +2 -0
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/admission.js +1 -1
- package/dist/src/execution/session/checkpoint-migrations.js +1 -1
- package/dist/src/execution/session/entry-input.d.ts +1 -3
- package/dist/src/execution/session/entry.js +1 -1
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +6 -9
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +5 -1
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/pending-history.d.ts +5 -0
- package/dist/src/execution/session/pending-history.js +1 -0
- package/dist/src/execution/session/pending-turn-state.js +1 -1
- package/dist/src/execution/session/program.d.ts +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/timeout-control.d.ts +18 -4
- package/dist/src/execution/session/timeout-control.js +1 -1
- package/dist/src/execution/session/timeout.d.ts +1 -2
- package/dist/src/execution/session/timeout.js +1 -1
- package/dist/src/execution/session/turn-event-handler.js +1 -1
- package/dist/src/execution/session/turn-step-result.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn-waiting-step.js +1 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/session-inbox/protocol.js +1 -1
- package/dist/src/execution/session.d.ts +0 -12
- package/dist/src/execution/session.js +2 -2
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/model-step.js +1 -1
- package/dist/src/execution/tasks/start.d.ts +4 -4
- package/dist/src/execution/tasks/start.js +1 -1
- package/dist/src/execution/tasks/steps.js +1 -1
- package/dist/src/execution/terminate-child-sessions-step.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/workflow/body.d.ts +2 -2
- package/dist/src/execution/workflow-runtime.d.ts +5 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/hitl/approvals.js +1 -1
- package/dist/src/harness/hitl/budget-request.d.ts +12 -6
- package/dist/src/harness/hitl/budget-request.js +1 -1
- package/dist/src/harness/hitl/budget.d.ts +7 -1
- package/dist/src/harness/hitl/budget.js +1 -1
- package/dist/src/harness/hitl/coordinator.js +1 -1
- package/dist/src/harness/hitl/delivery.d.ts +1 -1
- package/dist/src/harness/hitl/delivery.js +1 -1
- package/dist/src/harness/hitl/index.js +1 -1
- package/dist/src/harness/hitl/intake.d.ts +2 -2
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/messages.d.ts +5 -0
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/model-call/call.d.ts +2 -2
- package/dist/src/harness/model-call/request.d.ts +2 -2
- package/dist/src/harness/session-machine/transitions.d.ts +3 -1
- package/dist/src/harness/session-machine/transitions.js +1 -1
- package/dist/src/harness/step/context.d.ts +3 -0
- package/dist/src/harness/step/context.js +1 -1
- package/dist/src/harness/step/intake.d.ts +5 -2
- package/dist/src/harness/step/intake.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/turn-tag-state.d.ts +7 -26
- package/dist/src/harness/turn-tag-state.js +1 -1
- package/dist/src/harness/types.d.ts +10 -25
- package/dist/src/internal/application/build-profile.d.ts +3 -0
- package/dist/src/internal/application/build-profile.js +1 -1
- package/dist/src/internal/application/compiled-artifacts.js +2 -2
- package/dist/src/internal/application/dev-environment.d.ts +13 -0
- package/dist/src/internal/application/dev-environment.js +1 -1
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/authored-module-build-options.d.ts +7 -0
- package/dist/src/internal/authored-module-build-options.js +1 -0
- package/dist/src/internal/authored-module-graph.d.ts +13 -0
- package/dist/src/internal/authored-module-graph.js +1 -0
- package/dist/src/internal/authored-module-loader.d.ts +22 -1
- package/dist/src/internal/authored-module-loader.js +1 -3
- package/dist/src/internal/authored-module.d.ts +7 -0
- package/dist/src/internal/authored-module.js +1 -1
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/bundler/nitro-rolldown.d.ts +5 -1
- package/dist/src/internal/bundler/nitro-rolldown.js +1 -1
- package/dist/src/internal/development-programmatic-source-loader.d.ts +1 -0
- package/dist/src/internal/development-programmatic-source-loader.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-generation-metadata.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/build-deployment-id.d.ts +8 -0
- package/dist/src/internal/nitro/host/build-deployment-id.js +1 -0
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/dev-server-state.js +1 -1
- package/dist/src/internal/nitro/host/skill-server-assets.js +1 -1
- package/dist/src/internal/nitro/host/stage-build-deployment-id.d.ts +2 -0
- package/dist/src/internal/nitro/host/stage-build-deployment-id.js +1 -0
- package/dist/src/internal/nitro/host/start-production-server.d.ts +1 -0
- package/dist/src/internal/nitro/host/start-production-server.js +3 -3
- package/dist/src/internal/nitro/routes/schedule-task.d.ts +3 -0
- package/dist/src/internal/nitro/routes/schedule-task.js +1 -1
- package/dist/src/internal/programmatic-source-loader.d.ts +1 -0
- package/dist/src/internal/programmatic-source-loader.js +1 -1
- package/dist/src/internal/schedules/disabled.d.ts +2 -0
- package/dist/src/internal/schedules/disabled.js +1 -0
- package/dist/src/internal/workflow/development-world-server.js +1 -1
- package/dist/src/internal/workflow/local-world-data-directory.d.ts +2 -1
- package/dist/src/internal/workflow/local-world-data-directory.js +1 -1
- package/dist/src/internal/workflow-bundle/builder.js +1 -1
- package/dist/src/protocol/message.d.ts +27 -1
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +13 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
- package/dist/src/public/channels/chat-sdk/fetch-message.d.ts +10 -0
- package/dist/src/public/channels/chat-sdk/fetch-message.js +1 -0
- package/dist/src/public/channels/chat-sdk/index.d.ts +1 -1
- package/dist/src/public/channels/chat-sdk/reply-context.d.ts +15 -0
- package/dist/src/public/channels/chat-sdk/reply-context.js +2 -0
- package/dist/src/public/channels/discord/discordChannel.d.ts +3 -0
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +3 -0
- package/dist/src/public/channels/imessage-tapbacks.d.ts +74 -0
- package/dist/src/public/channels/imessage-tapbacks.js +1 -0
- package/dist/src/public/channels/index.d.ts +2 -1
- package/dist/src/public/channels/index.js +1 -1
- package/dist/src/public/channels/linear/linearChannel.d.ts +3 -0
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/linq/inboundContent.d.ts +7 -0
- package/dist/src/public/channels/linq/inboundContent.js +1 -1
- package/dist/src/public/channels/linq/index.d.ts +1 -0
- package/dist/src/public/channels/linq/index.js +1 -1
- package/dist/src/public/channels/linq/linqChannel.d.ts +17 -1
- package/dist/src/public/channels/linq/linqChannel.js +1 -1
- package/dist/src/public/channels/photon/inboundContent.d.ts +7 -0
- package/dist/src/public/channels/photon/inboundContent.js +2 -1
- package/dist/src/public/channels/photon/index.d.ts +1 -0
- package/dist/src/public/channels/photon/index.js +1 -1
- package/dist/src/public/channels/photon/photonIMessageChannel.d.ts +17 -1
- package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -1
- package/dist/src/public/channels/slack/api.d.ts +6 -0
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/slack/model-context.d.ts +7 -0
- package/dist/src/public/channels/slack/model-context.js +1 -1
- package/dist/src/public/channels/slack/reply-delivery.d.ts +5 -0
- package/dist/src/public/channels/slack/reply-delivery.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +17 -3
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +3 -0
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +3 -0
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/definitions/agent.d.ts +1 -1
- package/dist/src/public/definitions/channel.d.ts +2 -2
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +1 -0
- package/dist/src/public/index.d.ts +1 -1
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/runtime/agent/resolve-model.d.ts +4 -0
- package/dist/src/runtime/agent/resolve-model.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
- package/dist/src/runtime/subagents/dynamic-agent-config.d.ts +2 -1
- package/dist/src/runtime/subagents/dynamic-agent-config.js +1 -1
- package/dist/src/runtime/types.d.ts +3 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +31 -42
- package/dist/src/shared/session-history.d.ts +22 -0
- package/dist/src/shared/session-history.js +1 -0
- package/dist/src/subagents/tool.d.ts +1 -3
- package/dist/src/subagents/tool.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/tools/workflow-definition.d.ts +14 -1
- package/dist/src/tracing/eve/conversation-context.d.ts +4 -1
- package/dist/src/tracing/eve/conversation-context.js +1 -1
- package/dist/src/tracing/eve/invoke-tool-span.js +1 -1
- package/dist/src/tracing/eve/operation-input.d.ts +0 -5
- package/dist/src/tracing/eve/operation-input.js +1 -1
- package/dist/src/tracing/eve/otel-registration.js +1 -1
- package/dist/src/tracing/eve/session.d.ts +3 -2
- package/dist/src/tracing/eve/session.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +86 -65
- package/docs/channels/chat-sdk.mdx +6 -1
- package/docs/channels/custom.mdx +38 -6
- package/docs/channels/eve.mdx +46 -0
- package/docs/channels/linq.mdx +51 -0
- package/docs/channels/photon.mdx +64 -0
- package/docs/channels/slack.mdx +4 -2
- package/docs/concepts/built-in-tools.md +1 -1
- package/docs/concepts/execution-model-and-durability.mdx +12 -5
- package/docs/concepts/sessions-runs-and-streaming.md +9 -8
- package/docs/connections/overview.mdx +1 -1
- package/docs/experimental/dynamic-schedules.mdx +186 -0
- package/docs/experimental/meta.json +4 -0
- package/docs/guides/client/streaming.mdx +1 -0
- package/docs/guides/deployment/self-hosting.md +3 -0
- package/docs/guides/hooks.md +21 -1
- package/docs/memory/overview.mdx +2 -1
- package/docs/patterns/dynamic-scheduling.md +3 -1
- package/docs/reference/cli.md +14 -7
- package/docs/schedules.mdx +2 -0
- package/docs/subagents/index.mdx +2 -0
- package/docs/tools/overview.mdx +2 -1
- package/docs/tools/tasks-upgrade.md +12 -7
- package/docs/tools/tasks.md +10 -6
- package/docs/tools/workflows.mdx +36 -5
- package/docs/tutorial/connect-a-warehouse.mdx +1 -1
- package/docs/tutorial/run-analysis.mdx +1 -1
- package/package.json +1 -1
- package/dist/src/execution/run-session-limits.d.ts +0 -12
- package/dist/src/execution/run-session-limits.js +0 -1
- package/dist/src/harness/session-usage-limits.d.ts +0 -49
- package/dist/src/harness/session-usage-limits.js +0 -1
- package/dist/src/subagents/token-budget.d.ts +0 -15
- package/dist/src/subagents/token-budget.js +0 -1
|
@@ -36,7 +36,7 @@ export declare function resolveTypedApproval(view: Pick<SessionView, "projection
|
|
|
36
36
|
export declare function canonicalize(responses: readonly InputResponse[]): readonly InputResponse[];
|
|
37
37
|
export declare function isEmptyInput(input: StepInput): boolean;
|
|
38
38
|
export declare function withoutResponses(input: ResolvedStepInput | undefined): StepInput | undefined;
|
|
39
|
-
/** The turn's own input: the message a plain-text answer didn't consume, and
|
|
39
|
+
/** The turn's own input: the message a plain-text answer didn't consume, its history and context. */
|
|
40
40
|
export declare function turnInputOnly(input: ResolvedStepInput | undefined): StepInput | undefined;
|
|
41
41
|
/** What of the input isn't the turn's: answers, and the output the session asks for. */
|
|
42
42
|
export declare function withoutTurnInput(input: ResolvedStepInput | undefined): ResolvedStepInput;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{openInputs}from"#protocol/session-projection.js";import{attachClientContext,readClientContext}from"#internal/client-context.js";import{readAnswerText}from"#internal/input-text.js";import{firstOpenInput}from"#harness/open-input-request.js";import{resolveTextToResponse,resolveTextToResponses}from"#channel/resolve-text.js";import{coalesceTurnInputs}from"#harness/messages.js";import{ownOpenRequestIds}from"#harness/session-machine/transitions.js";import{isApprovalRequest}from"#harness/input-request-class.js";import{convertStaleResponsesToUserMessage,dropStaleSessionLimitContinuationResponses}from"#harness/hitl/stale-responses.js";function deliver(e,t,n){let r=n.takeQueued?e.turn.queued:void 0,i=openInputs(e.projection).find(e=>e.request.kind===`session-limit`),a=r!==void 0&&i!==void 0?resolveTextInput({requests:[i.request]},t):t,o=r===void 0?a:a===void 0?r:coalesceTurnInputs(r,a),s=new Set([...ownOpenRequestIds(e),...e.turn.suspended.flatMap(e=>e.requests.map(e=>e.requestId))]),c=new Map(Object.values(e.projection.inputs).map(e=>[e.request.requestId,e.request])),l=convertStaleResponsesToUserMessage({pendingRequestIds:s,requests:c,stepInput:dropStaleSessionLimitContinuationResponses({pendingRequestIds:s,stepInput:o})});return l.kind===`converted`?{displayMessage:l.displayMessage,input:l.stepInput,takeQueued:n.takeQueued}:{input:l.stepInput,takeQueued:n.takeQueued}}function resolveTextInput(e,t){let n=readAnswerText(t);if(t===void 0||n===void 0)return t;let r=new Set(e.requests.map(e=>e.requestId));if(t.inputResponses?.some(e=>r.has(e.requestId)))return t;let i=resolveTextToResponses(n,e.requests);return i.length===0?t:compactInput({...t,context:void 0,inputResponses:[...t.inputResponses??[],...i],message:void 0,messageConsumed:!0})}function resolveTypedApproval(e,t){let n=readAnswerText(t);if(t===void 0||n===void 0)return t;let r=new Set([...t.inputResponses??[],...(t.attributedInputResponses??[]).map(({response:e})=>e)].map(({requestId:e})=>e)),i=firstOpenInput(e.projection,e=>r.has(e))?.request,a=e.turn.suspended.some(e=>e.requests.some(e=>e.requestId===i?.requestId));if(i===void 0||!a||!isApprovalRequest(i))return t;let o=resolveTextToResponse(n,i);return o===void 0?t:{...t,context:void 0,inputResponses:[...t.inputResponses??[],o],message:void 0,messageConsumed:!0}}function canonicalize(e){let t=new Map;for(let n of e)t.set(n.requestId,n);return[...t.values()]}function isEmptyInput(e){return Object.keys(compactInput(e)).length===0}function withoutResponses(e){if(e===void 0)return;let{attributedInputResponses:t,inputResponses:n,messageConsumed:r,...i}=e;return i}function turnInputOnly(e){if(e===void 0)return;let t={};(e.context?.length??0)>0&&(t.context=e.context),e.message!==void 0&&e.messageConsumed!==!0&&(t.message=e.message);let n=attachClientContext(t,readClientContext(e));return isEmptyInput(n)?void 0:n}function withoutTurnInput(e){let t={};return(e?.inputResponses?.length??0)>0&&(t.inputResponses=e.inputResponses),e?.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),t}function compactInput(e){if(e===void 0)return{};let t={};return(e.context?.length??0)>0&&(t.context=e.context),(e.inputResponses?.length??0)>0&&(t.inputResponses=e.inputResponses),e.message!==void 0&&(t.message=e.message),e.messageConsumed===!0&&(t.messageConsumed=!0),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),attachClientContext(t,readClientContext(e))}export{canonicalize,compactInput,deliver,isEmptyInput,resolveTextInput,resolveTypedApproval,turnInputOnly,withoutResponses,withoutTurnInput};
|
|
1
|
+
import{openInputs}from"#protocol/session-projection.js";import{attachClientContext,readClientContext}from"#internal/client-context.js";import{readAnswerText}from"#internal/input-text.js";import{firstOpenInput}from"#harness/open-input-request.js";import{resolveTextToResponse,resolveTextToResponses}from"#channel/resolve-text.js";import{coalesceTurnInputs}from"#harness/messages.js";import{ownOpenRequestIds}from"#harness/session-machine/transitions.js";import{isApprovalRequest}from"#harness/input-request-class.js";import{convertStaleResponsesToUserMessage,dropStaleSessionLimitContinuationResponses}from"#harness/hitl/stale-responses.js";function deliver(e,t,n){let r=n.takeQueued?e.turn.queued:void 0,i=openInputs(e.projection).find(e=>e.request.kind===`session-limit`),a=r!==void 0&&i!==void 0?resolveTextInput({requests:[i.request]},t):t,o=r===void 0?a:a===void 0?r:coalesceTurnInputs(r,a),s=new Set([...ownOpenRequestIds(e),...e.turn.suspended.flatMap(e=>e.requests.map(e=>e.requestId))]),c=new Map(Object.values(e.projection.inputs).map(e=>[e.request.requestId,e.request])),l=convertStaleResponsesToUserMessage({pendingRequestIds:s,requests:c,stepInput:dropStaleSessionLimitContinuationResponses({pendingRequestIds:s,stepInput:o})});return l.kind===`converted`?{displayMessage:l.displayMessage,input:l.stepInput,takeQueued:n.takeQueued}:{input:l.stepInput,takeQueued:n.takeQueued}}function resolveTextInput(e,t){let n=readAnswerText(t);if(t===void 0||n===void 0)return t;let r=new Set(e.requests.map(e=>e.requestId));if(t.inputResponses?.some(e=>r.has(e.requestId)))return t;let i=resolveTextToResponses(n,e.requests);return i.length===0?t:compactInput({...t,context:void 0,history:void 0,inputResponses:[...t.inputResponses??[],...i],message:void 0,messageConsumed:!0})}function resolveTypedApproval(e,t){let n=readAnswerText(t);if(t===void 0||n===void 0)return t;let r=new Set([...t.inputResponses??[],...(t.attributedInputResponses??[]).map(({response:e})=>e)].map(({requestId:e})=>e)),i=firstOpenInput(e.projection,e=>r.has(e))?.request,a=e.turn.suspended.some(e=>e.requests.some(e=>e.requestId===i?.requestId));if(i===void 0||!a||!isApprovalRequest(i))return t;let o=resolveTextToResponse(n,i);return o===void 0?t:{...t,context:void 0,history:void 0,inputResponses:[...t.inputResponses??[],o],message:void 0,messageConsumed:!0}}function canonicalize(e){let t=new Map;for(let n of e)t.set(n.requestId,n);return[...t.values()]}function isEmptyInput(e){return Object.keys(compactInput(e)).length===0}function withoutResponses(e){if(e===void 0)return;let{attributedInputResponses:t,inputResponses:n,messageConsumed:r,...i}=e;return i}function turnInputOnly(e){if(e===void 0)return;let t={};(e.context?.length??0)>0&&(t.context=e.context),(e.history?.length??0)>0&&(t.history=e.history),e.message!==void 0&&e.messageConsumed!==!0&&(t.message=e.message);let n=attachClientContext(t,readClientContext(e));return isEmptyInput(n)?void 0:n}function withoutTurnInput(e){let t={};return(e?.inputResponses?.length??0)>0&&(t.inputResponses=e.inputResponses),e?.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),t}function compactInput(e){if(e===void 0)return{};let t={};return(e.context?.length??0)>0&&(t.context=e.context),(e.history?.length??0)>0&&(t.history=e.history),(e.inputResponses?.length??0)>0&&(t.inputResponses=e.inputResponses),e.message!==void 0&&(t.message=e.message),e.messageConsumed===!0&&(t.messageConsumed=!0),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),attachClientContext(t,readClientContext(e))}export{canonicalize,compactInput,deliver,isEmptyInput,resolveTextInput,resolveTypedApproval,turnInputOnly,withoutResponses,withoutTurnInput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{renderPendingApprovalsInstruction}from"./approval-prompt.js";import{isEmptyInput}from"./delivery.js";import{grantedApprovalKeys,hasRunnableQueue,parkOnApprovals as parkOnApprovals$1,requestLimit,requireSignIn}from"./approvals.js";import{checkSessionUsageLimit}from"./budget.js";import{discardClearedHitlState,holdsHitlRequests,readHitlState}from"./requests.js";import{retireActiveCandidates}from"./candidates.js";import{acceptHumanInput,admitApprovedWork,dispatchApprovedWorkflows,hasApprovedWork,holdForInput,runApprovedLocalCalls}from"./intake.js";import{AuthKey,SessionKey}from"#context/keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{fail,hold}from"#harness/session-machine/transitions.js";import{readTurnState,writeTurnState}from"#harness/session-machine/state.js";import{extractToolApprovalInputRequests}from"#harness/input-extraction.js";async function parkOnApprovals(e,t){let n=parkOnApprovals$1(e.view(),{event:t.event,messages:t.messages,requests:t.requests,tasks:t.tasks,requester:currentRequester(e),responseAuthRequiredRequestIds:responsePolicyRequestIds(t.tools,t.requests)});return await e.apply(n,[...e.session.history,...n.commit??[]]),t.waitsOn===void 0?hasRunnableQueue(e.view())?{next:e.runStep,session:e.session}:holdForInput(e):(t.waitsOn===`runtime`&&t.tasks.some(e=>e.entry.entryPoint===`execute`)&&await e.apply(hold(e.view(),{on:`tasks`})),{next:null,session:e.session})}async function stopForToolSignIn(e,t){return await e.apply(requireSignIn(e.view(),{calls:t.calls,challenges:t.challenges}),e.session.history),{held:{kind:`request`},next:null,session:e.session}}async function enforceBudget(e,t){let n=checkSessionUsageLimit({canAsk:e.emit!==void 0&&e.config.capabilities?.requestInput===!0,session:e.session,turnSequence:e.position().sequence});if(n.kind!==`within`)return n.kind===`ask`?(e.session={...e.session,history:validateHarnessModelMessages([...t])},await e.apply(requestLimit(e.view(),{request:n.request}),e.session.history),{next:null,session:e.session}):(await e.apply(fail(e.view(),{code:n.code,details:n.details,message:n.message,terminal:{sessionId:e.session.sessionId}})),{next:{done:!0,output:``},session:e.session})}function humanInputContext(e,t){let n=e.view();return{approvedTools:grantedApprovalKeys(n,e=>t.get(e.action.toolName)?.approvalKey?.(e.action.input)),pendingApprovalsNote:renderPendingApprovalsInstruction(n.turn.suspended.flatMap(e=>e.requests))}}function responsePolicyRequestIds(e,t){return t.filter(t=>{let n=e.get(t.action.toolName)?.approval;return n!==void 0&&typeof n!=`function`&&n.response!==void 0}).map(e=>e.requestId)}function currentRequester(e){return e.ctx?.get(AuthKey)??e.ctx?.get(SessionKey)?.auth.current??null}function retireCancelledCandidates(e){return{...e,state:retireActiveCandidates(e.state,{completedAt:Date.now(),reason:`Cancelled.`})}}function takeDeferredMessage(e){let{queued:t,...n}=readTurnState(e.state);if(t?.message===void 0)return{session:e};let{message:r,...i}=t;return{message:r,session:writeTurnState(e,isEmptyInput(i)?n:{...n,queued:i})}}export{acceptHumanInput,admitApprovedWork,discardClearedHitlState as discardClearedHumanInput,dispatchApprovedWorkflows,enforceBudget,extractToolApprovalInputRequests,hasApprovedWork,hasRunnableQueue,holdsHitlRequests,humanInputContext,parkOnApprovals,readHitlState,retireCancelledCandidates,runApprovedLocalCalls,stopForToolSignIn,takeDeferredMessage};
|
|
1
|
+
import{renderPendingApprovalsInstruction}from"./approval-prompt.js";import{isEmptyInput}from"./delivery.js";import{grantedApprovalKeys,hasRunnableQueue,parkOnApprovals as parkOnApprovals$1,requestLimit,requireSignIn}from"./approvals.js";import{DEFAULT_SESSION_USAGE_LIMIT,checkSessionUsageLimit}from"./budget.js";import{discardClearedHitlState,holdsHitlRequests,readHitlState}from"./requests.js";import{retireActiveCandidates}from"./candidates.js";import{acceptHumanInput,admitApprovedWork,dispatchApprovedWorkflows,hasApprovedWork,holdForInput,runApprovedLocalCalls}from"./intake.js";import{AuthKey,SessionKey}from"#context/keys.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{fail,hold}from"#harness/session-machine/transitions.js";import{readTurnState,writeTurnState}from"#harness/session-machine/state.js";import{extractToolApprovalInputRequests}from"#harness/input-extraction.js";async function parkOnApprovals(e,t){let n=parkOnApprovals$1(e.view(),{event:t.event,messages:t.messages,requests:t.requests,tasks:t.tasks,requester:currentRequester(e),responseAuthRequiredRequestIds:responsePolicyRequestIds(t.tools,t.requests)});return await e.apply(n,[...e.session.history,...n.commit??[]]),t.waitsOn===void 0?hasRunnableQueue(e.view())?{next:e.runStep,session:e.session}:holdForInput(e):(t.waitsOn===`runtime`&&t.tasks.some(e=>e.entry.entryPoint===`execute`)&&await e.apply(hold(e.view(),{on:`tasks`})),{next:null,session:e.session})}async function stopForToolSignIn(e,t){return await e.apply(requireSignIn(e.view(),{calls:t.calls,challenges:t.challenges}),e.session.history),{held:{kind:`request`},next:null,session:e.session}}async function enforceBudget(e,t){let n=checkSessionUsageLimit({canAsk:e.emit!==void 0&&e.config.capabilities?.requestInput===!0,limit:e.config.sessionUsageLimit??DEFAULT_SESSION_USAGE_LIMIT,session:e.session,turnSequence:e.position().sequence});if(n.kind!==`within`)return n.kind===`ask`?(e.session={...e.session,history:validateHarnessModelMessages([...t])},await e.apply(requestLimit(e.view(),{request:n.request}),e.session.history),{next:null,session:e.session}):(await e.apply(fail(e.view(),{code:n.code,details:n.details,message:n.message,terminal:{sessionId:e.session.sessionId}})),{next:{done:!0,output:``},session:e.session})}function humanInputContext(e,t){let n=e.view();return{approvedTools:grantedApprovalKeys(n,e=>t.get(e.action.toolName)?.approvalKey?.(e.action.input)),pendingApprovalsNote:renderPendingApprovalsInstruction(n.turn.suspended.flatMap(e=>e.requests))}}function responsePolicyRequestIds(e,t){return t.filter(t=>{let n=e.get(t.action.toolName)?.approval;return n!==void 0&&typeof n!=`function`&&n.response!==void 0}).map(e=>e.requestId)}function currentRequester(e){return e.ctx?.get(AuthKey)??e.ctx?.get(SessionKey)?.auth.current??null}function retireCancelledCandidates(e){return{...e,state:retireActiveCandidates(e.state,{completedAt:Date.now(),reason:`Cancelled.`})}}function takeDeferredMessage(e){let{queued:t,...n}=readTurnState(e.state);if(t?.message===void 0)return{session:e};let{message:r,...i}=t;return{message:r,session:writeTurnState(e,isEmptyInput(i)?n:{...n,queued:i})}}export{acceptHumanInput,admitApprovedWork,discardClearedHitlState as discardClearedHumanInput,dispatchApprovedWorkflows,enforceBudget,extractToolApprovalInputRequests,hasApprovedWork,hasRunnableQueue,holdsHitlRequests,humanInputContext,parkOnApprovals,readHitlState,retireCancelledCandidates,runApprovedLocalCalls,stopForToolSignIn,takeDeferredMessage};
|
|
@@ -41,8 +41,8 @@ export declare function acceptHumanInput(step: Step, input: StepInput | undefine
|
|
|
41
41
|
readonly takeQueued: boolean;
|
|
42
42
|
}): Promise<HumanInputIntake>;
|
|
43
43
|
/**
|
|
44
|
-
* Admits what a delivery decided before its turn calls the model: a session-limit answer
|
|
45
|
-
*
|
|
44
|
+
* Admits what a delivery decided before its turn calls the model: a session-limit answer starts a
|
|
45
|
+
* new usage window or ends the turn tree, and a step its answers completed, as denials do, commits.
|
|
46
46
|
*/
|
|
47
47
|
export declare function admitApprovedWork(step: Step, work: ApprovedWork): Promise<void>;
|
|
48
48
|
/** Whether a suspended step holds approved calls that haven't run. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{deliver,resolveTypedApproval,turnInputOnly,withoutTurnInput}from"./delivery.js";import{answer,approvingSteps,deferInput,dispatch,grantedApprovalKeys,requireSignIn,stepForRequest,withdrawSignIns}from"./approvals.js";import{rejectApprovedCall,runApprovedCalls}from"./approved-calls.js";import{getApprovalAuditState,responderOfRequest,retireActiveCandidates}from"./candidates.js";import{coordinateApprovalDelivery}from"./coordinator.js";import{SEARCH_TOOL_NAME}from"#protocol/catalog-tools.js";import{activeTurnId}from"#harness/session-machine/view.js";import{
|
|
1
|
+
import{deliver,resolveTypedApproval,turnInputOnly,withoutTurnInput}from"./delivery.js";import{answer,approvingSteps,deferInput,dispatch,grantedApprovalKeys,requireSignIn,stepForRequest,withdrawSignIns}from"./approvals.js";import{rejectApprovedCall,runApprovedCalls}from"./approved-calls.js";import{getApprovalAuditState,responderOfRequest,retireActiveCandidates}from"./candidates.js";import{coordinateApprovalDelivery}from"./coordinator.js";import{SEARCH_TOOL_NAME}from"#protocol/catalog-tools.js";import{activeTurnId}from"#harness/session-machine/view.js";import{resetSessionUsageWindow}from"#harness/turn-tag-state.js";import{collectWorkflowCalls}from"#harness/coordination.js";import{approvedCalls,completeSignIn,hold,runnableCalls,settle}from"#harness/session-machine/transitions.js";import{stepStartedForResolvers}from"#harness/session-machine/resolver-events.js";import{SessionLimitDeclinedError,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{resolveInlineAuthorizationInterrupt}from"#harness/inline-tool-authorization.js";import{recheckApprovedCall}from"#harness/tools.js";import{buildStepCatalog}from"#execution/catalog/step-catalog.js";import{signInAttemptKey}from"#harness/hitl/sign-ins.js";async function acceptHumanInput(e,t,n){let{config:r,ctx:i}=e,a=r.signInCompletions??[];a.length>0&&await e.apply(completeSignIn(e.view(),{completions:a}));let o=deliver(e.view(),t,n),s=resolveTypedApproval(e.view(),o.input),c=t?.message!==void 0&&s?.message!==void 0||o.displayMessage!==void 0?await withdrawSteeredSignIns(e,s):s,l=new Map,u,restoreTools=async t=>{let n=t?.event??e.position(),a=`${n.turnId}:${n.stepIndex}`,o=l.get(a);if(o!==void 0&&u===a)return o;t!==void 0&&await r.prepareApprovalTurn?.(t.event),i!==void 0&&await r.resolveStepDynamicTools?.({ctx:i,event:stepStartedForResolvers({modelId:e.session.agent.modelReference?.id??`dynamic`,sequence:n.sequence,stepIndex:n.stepIndex,turnId:n.turnId}),messages:e.projectHistory(e.session.history)});let s=buildStepCatalog({agentTools:r.tools,ctx:i,endsTurn:!1,session:e.session});return l.set(a,s),u=a,s},toolsOf=e=>(e&&l.get(`${e.event.turnId}:${e.event.stepIndex}`))??r.tools,d=e.view().signIns,f=await coordinateApprovalDelivery({session:e.session,stepInput:c,tools:r.tools,prepareTools:t=>restoreTools(stepForRequest(e.view(),t.requestId))});e.session=f.session;for(let t of approvingSteps(e.view(),f.stepInput))await restoreTools(t);let p=answer(e.view(),{approvalKey:t=>toolsOf(stepForRequest(e.view(),t.requestId)).get(t.action.toolName)?.approvalKey?.(t.action.input),delivery:f.stepInput,searchable:t=>toolsOf(stepForRequest(e.view(),t.requestId)).get(SEARCH_TOOL_NAME)!==void 0,policy:{...f,audit:getApprovalAuditState(e.session.state),challengesAtStart:d},takeQueued:o.takeQueued});for(let t of p.resolved)await e.instrumentation?.publishInputResolutions({batch:t,sessionId:e.session.sessionId});await e.apply(p);let stop=e=>({kind:`stop`,result:e});switch(p.next){case`park`:return e.view().projection.activeTurnId===void 0?stop({next:null,session:e.session}):stop(await holdForInput(e));case`repeat`:return stop({next:e.runStep,session:e.session});case`sign-in`:return await e.apply(requireSignIn(e.view(),{challenges:f.challenges,queued:f.stepInput})),stop(held(e))}let m=e.view();for(let e of m.turn.suspended)runnableCalls(m,e).length>0&&await restoreTools(e);let h=p.resolved.some(e=>e.inputs.some(e=>e.request.kind===`tool-approval`)&&e.inputs.every(e=>e.response!==void 0))||approvedCalls(e.view()).length>0?turnInputOnly(p.input):void 0;return h!==void 0&&await e.apply(deferInput(e.view(),h)),{approved:{limit:p.limit,toolsOf},consumedMessage:p.consumedMessage===!0,input:h===void 0?p.input:withoutTurnInput(p.input),message:p.consumedMessage===!0||h!==void 0?void 0:o.displayMessage??o.input?.message,kind:`run`,opensTurn:hasTurnInput(o.input)||hasTurnInput(f.stepInput)}}async function admitApprovedWork(e,t){if(t.limit!==void 0){if(!t.limit.granted)throw new SessionLimitDeclinedError;e.session=resetSessionUsageWindow(e.session)}await e.apply(settle(e.view(),{results:[]}))}function hasApprovedWork(e){return approvedCalls(e.view()).length>0}async function dispatchApprovedWorkflows(e,t){let n=[],r=[],i=e.view();for(let a of i.turn.suspended){let o=t.toolsOf(a),s=[];for(let t of runnableCalls(i,a)){let n=o.get(t.action.toolName);if(n?.workflowId===void 0)continue;let i=await recheckApprovedCall(n,{abortSignal:e.config.abortSignal,callId:t.action.callId,input:t.action.input,approvedTools:grantedApprovalKeys(e.view(),e=>o.get(e.action.toolName)?.approvalKey?.(e.action.input))});i.denied?r.push(await rejectApprovedCall({request:t,reason:i.reason,position:e.position(),publish:e.publish})):s.push(t)}if(s.length===0)continue;let c=collectWorkflowCalls({session:e.session,toolCalls:s.map(({action:e})=>({input:e.input,toolCallId:e.callId,toolName:e.toolName})),tools:o,turnId:a.event.turnId});e.session=c.session,n.push(...c.workflowRequests)}return r.length>0&&await e.apply(settle(e.view(),{results:r})),n.length!==0&&(await e.apply(dispatch(e.view(),{tasks:n})),n.some(e=>e.entry.entryPoint===`execute`)&&await e.apply(hold(e.view(),{on:`tasks`})),!0)}function reportingOnce(e,t,n){let r=(t.signIns??[]).filter(t=>{let r=signInAttemptKey(t),i=e.projection.authorizations[t.attemptId??t.name]?.status;return n.has(r)||i!==`required`?!1:(n.add(r),!0)});return{...t,signIns:r}}async function runApprovedLocalCalls(e,t,n){let r=e.view(),i=new Set,a=r.turn.suspended.map(e=>{let n=t.toolsOf(e);return{requests:runnableCalls(r,e).filter(e=>n.get(e.action.toolName)?.workflowId===void 0).map(e=>reportingOnce(r,e,i)),tools:n}}),o=a.flatMap(({requests:e})=>e);e.frameworkToolNames=new Set(a.flatMap(({requests:e,tools:t})=>e.map(e=>e.action.toolName).filter(e=>t.get(e)?.frameworkTool===!0)));let s=e.position(),c=o.length===0?void 0:e.instrumentation?.prepareAttempt({isFrameworkTool:t=>e.frameworkToolNames.has(t),attemptIndex:0,stepIndex:s.stepIndex,turnId:activeTurnId(s)});c!==void 0&&n(c.scope);let l=await Promise.all(a.map(async({requests:t,tools:n})=>t.length===0?{settled:[],toolResults:[]}:await runApprovedCalls({abortSignal:e.config.abortSignal,approvedTools:grantedApprovalKeys(e.view(),e=>n.get(e.action.toolName)?.approvalKey?.(e.action.input)),messages:e.projectHistory(e.session.history),position:e.position(),publish:e.publish,requests:t,responderOf:t=>responderOfRequest(e.session.state,t.requestId),telemetry:c?.telemetry,tools:n})));await e.apply(settle(e.view(),{results:l.flatMap(e=>e.settled)})),throwIfTurnAborted(e.config.abortSignal);let u=resolveInlineAuthorizationInterrupt({toolResults:l.flatMap(e=>e.toolResults)});if(u!==void 0)return await e.apply(requireSignIn(e.view(),{calls:u.calls,challenges:u.challenges}),e.session.history),held(e)}const STEERED_SIGN_IN_REASON=`Cancelled because a new message arrived.`;async function holdForInput(e){return await e.apply(hold(e.view(),{on:`input`})),held(e)}function held(e){return{held:{kind:`request`},next:null,session:e.session}}async function withdrawSteeredSignIns(e,t){let n=[...new Set(e.view().signIns.map(e=>e.name))];return e.session={...e.session,state:retireActiveCandidates(e.session.state,{completedAt:Date.now(),reason:STEERED_SIGN_IN_REASON})},n.length===0?t:(await e.apply(withdrawSignIns(e.view(),STEERED_SIGN_IN_REASON)),{...t,context:[...t?.context??[],`Sign-in to ${n.join(`, `)} was cancelled because the user sent a new message instead. Ask to sign in again only if the new message still needs it.`]})}function hasTurnInput(e){return e===void 0?!1:e.message!==void 0||(e.inputResponses?.length??0)>0}export{acceptHumanInput,admitApprovedWork,dispatchApprovedWorkflows,hasApprovedWork,holdForInput,runApprovedLocalCalls};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ModelMessage, UserContent } from "ai";
|
|
2
2
|
import type { ChannelDeliveryMetadataEntry, DeliverPayload, SessionAuthContext, TurnCaller } from "#channel/types.js";
|
|
3
3
|
import type { StepInput } from "#harness/types.js";
|
|
4
|
+
import type { SessionHistoryMessage } from "#shared/session-history.js";
|
|
4
5
|
/** Reason a framework-authored user-role message was added to model history. */
|
|
5
6
|
export type FrameworkMessageKind = "context.instruction" | "context.state" | "context.compaction" | "memory.load" | "execution.continuation" | "execution.retry" | "task.result";
|
|
6
7
|
/** Semantic classification for every user-role message in model history. */
|
|
@@ -22,6 +23,10 @@ type FrameworkUserMessage = UserModelMessage & {
|
|
|
22
23
|
/** Builds a classified user-role message for model history. */
|
|
23
24
|
export declare function createUserMessage(kind: FrameworkMessageKind, content: UserContent, metadata?: Record<string, unknown>): FrameworkUserMessage;
|
|
24
25
|
export declare function createUserMessage(kind: "user", content: UserContent, metadata?: Record<string, unknown>): UserModelMessage;
|
|
26
|
+
/** Metadata key marking a user message seeded from `history` rather than typed in a turn. */
|
|
27
|
+
export declare const IMPORTED_MESSAGE_METADATA_KEY = "eve.imported";
|
|
28
|
+
/** Maps seeded history to model messages: plain user and assistant text, nothing else. */
|
|
29
|
+
export declare function createImportedHistoryMessages(history: readonly SessionHistoryMessage[]): HarnessModelMessage[];
|
|
25
30
|
/** Builds a framework-authored user-role message for model history. */
|
|
26
31
|
export declare function createFrameworkUserMessage(kind: FrameworkMessageKind, content: UserContent, metadata?: Record<string, unknown>): FrameworkUserMessage;
|
|
27
32
|
/** True when a value is a recognized classification for a user-role message. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";function createUserMessage(e,t,n){let r={content:t,kind:e,role:`user`};return n===void 0?r:{...r,metadata:n}}function createFrameworkUserMessage(e,t,n){return createUserMessage(e,t,n)}function isUserMessageKind(e){return e===`user`||isFrameworkMessageKind(e)}function isUserModelMessage(e){if(e.role!==`user`)return!1;let{kind:t}=e;return isUserMessageKind(t)}function isFrameworkUserMessage(e){return isUserModelMessage(e)&&e.kind!==`user`}function validateHarnessModelMessages(e){let t=[];for(let n of e){if(n.role!==`user`){t.push(n);continue}if(!isUserModelMessage(n))throw TypeError(`Expected every user-role model message to have a kind.`);t.push(n)}return t}function isFrameworkMessageKind(e){return e===`context.instruction`||e===`context.state`||e===`context.compaction`||e===`memory.load`||e===`execution.continuation`||e===`execution.retry`||e===`task.result`}function markFrameworkStepInput(e,t){return{...e,frameworkMessageKind:t}}function frameworkMessageKindForStepInput(e){if(e===void 0)return;let{frameworkMessageKind:t}=e;return isFrameworkMessageKind(t)?t:void 0}function coalesceTurnInputs(e,t){let n=coalesceInputResponses({a:e.inputResponses,b:t.inputResponses}),r=coalesceMessage({a:e.message,b:t.message}),i=coalesceContext({a:e.context,b:t.context}),a=coalesceFrameworkMessageKind({a:e,b:t}),
|
|
1
|
+
import{attachClientContext,readClientContext}from"#internal/client-context.js";import{attachInputText,readInputText}from"#internal/input-text.js";function createUserMessage(e,t,n){let r={content:t,kind:e,role:`user`};return n===void 0?r:{...r,metadata:n}}const IMPORTED_MESSAGE_METADATA_KEY=`eve.imported`;function createImportedHistoryMessages(e){return e.map(e=>e.role===`user`?createUserMessage(`user`,e.text,{[IMPORTED_MESSAGE_METADATA_KEY]:!0}):{content:e.text,role:`assistant`})}function createFrameworkUserMessage(e,t,n){return createUserMessage(e,t,n)}function isUserMessageKind(e){return e===`user`||isFrameworkMessageKind(e)}function isUserModelMessage(e){if(e.role!==`user`)return!1;let{kind:t}=e;return isUserMessageKind(t)}function isFrameworkUserMessage(e){return isUserModelMessage(e)&&e.kind!==`user`}function validateHarnessModelMessages(e){let t=[];for(let n of e){if(n.role!==`user`){t.push(n);continue}if(!isUserModelMessage(n))throw TypeError(`Expected every user-role model message to have a kind.`);t.push(n)}return t}function isFrameworkMessageKind(e){return e===`context.instruction`||e===`context.state`||e===`context.compaction`||e===`memory.load`||e===`execution.continuation`||e===`execution.retry`||e===`task.result`}function markFrameworkStepInput(e,t){return{...e,frameworkMessageKind:t}}function frameworkMessageKindForStepInput(e){if(e===void 0)return;let{frameworkMessageKind:t}=e;return isFrameworkMessageKind(t)?t:void 0}function coalesceTurnInputs(e,t){let n=coalesceInputResponses({a:e.inputResponses,b:t.inputResponses}),r=coalesceMessage({a:e.message,b:t.message}),i=coalesceContext({a:e.context,b:t.context}),a=[...e.history??[],...t.history??[]],o=coalesceFrameworkMessageKind({a:e,b:t}),s=coalesceContext({a:readClientContext(e),b:readClientContext(t)}),c=t.outputSchema??e.outputSchema,l=[...e.attributedInputResponses??[],...t.attributedInputResponses??[]],u={};n!==void 0&&(u.inputResponses=n),l.length>0&&(u.attributedInputResponses=l),r!==void 0&&(u.message=r),i!==void 0&&(u.context=i),a.length>0&&(u.history=a),c!==void 0&&(u.outputSchema=c);let d=normalizeUserContent(e.message)===void 0?readInputText(t):normalizeUserContent(t.message)===void 0?readInputText(e):void 0;return attachClientContext(attachInputText(o===void 0?u:markFrameworkStepInput(u,o),d),s)}function normalizeUserContent(e){if(e===void 0)return;if(typeof e==`string`)return e.trim().length>0?e:void 0;let t=e.filter(e=>e.type!==`text`||e.text.trim().length>0);if(t.length!==0)return t.length===e.length?e:t}const TOOL_RESULT_BOUNDARY=`…`;function followsToolResults(e){return e.findLast(e=>e.role!==`user`)?.role===`tool`}function createTurnInputMessages(e){let t=[...readClientContext(e)??[],...e?.context??[]].map(e=>createFrameworkUserMessage(`context.instruction`,e)),n=normalizeUserContent(e?.message);if(n===void 0)return t;let r=frameworkMessageKindForStepInput(e);return[...t,r===void 0?createUserMessage(`user`,n):createFrameworkUserMessage(r,n)]}function normalizeModelMessages(e){return e.flatMap(e=>{if(typeof e.content==`string`)return e.content.trim().length>0?[e]:[];let t=e.content.filter(e=>e.type!==`text`||e.text.trim().length>0);return t.length===0?[]:t.length===e.content.length?[e]:[{...e,content:t}]})}function resolveAssistantStepText(e,t){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role!==`assistant`)continue;let r=extractMessageText(n);if(r.trim().length>0)return r}return t!==void 0&&t.trim().length>0?t:null}function extractMessageText(e){return typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.flatMap(e=>typeof e==`string`?[e]:`type`in e&&e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(``):``}function coalesceInputResponses(e){let t=e.a??[],n=e.b??[];if(t.length!==0||n.length!==0)return[...t,...n]}function coalesceContext(e){let t=e.a??[],n=e.b??[];if(t.length!==0||n.length!==0)return[...t,...n]}function coalesceFrameworkMessageKind(e){let t=frameworkMessageKindForStepInput(e.a),n=frameworkMessageKindForStepInput(e.b);return e.a.message===void 0?n:e.b.message===void 0||t===n?t:void 0}function coalesceMessage(e){let t=normalizeUserContent(e.a),n=normalizeUserContent(e.b);return t===void 0?n:n===void 0?t:appendUserContent({appended:n,existing:t})}function appendUserContent(e){return typeof e.existing==`string`&&typeof e.appended==`string`?`${e.existing}\n\n${e.appended}`:[...toUserContentArray(e.existing),...toUserContentArray(e.appended)]}function toUserContentArray(e){return typeof e==`string`?e.length>0?[{type:`text`,text:e}]:[]:Array.isArray(e)?[...e]:[]}function coalesceDeliveries(e){let[t,...n]=e;if(t===void 0)throw Error(`Cannot coalesce an empty delivery batch.`);let r=t.auth,i=t.caller,a=[...t.payloads],o=[...t.deliveryMetadata??[]];for(let e of n){let t=a.length;if(e.auth!==void 0&&(r=e.auth),e.caller!==void 0){if(i!==void 0&&i.callId!==e.caller.callId)throw Error(`Cannot coalesce deliveries from different turns.`);i=e.caller}a.push(...e.payloads),o.push(...(e.deliveryMetadata??[]).map(e=>({...e,payloadIndex:e.payloadIndex+t})))}return{...t,auth:r,caller:i,deliveryMetadata:o.length===0?void 0:o,payloads:a}}export{IMPORTED_MESSAGE_METADATA_KEY,TOOL_RESULT_BOUNDARY,appendUserContent,coalesceDeliveries,coalesceTurnInputs,createFrameworkUserMessage,createImportedHistoryMessages,createTurnInputMessages,createUserMessage,followsToolResults,frameworkMessageKindForStepInput,isFrameworkMessageKind,isFrameworkUserMessage,isUserMessageKind,isUserModelMessage,markFrameworkStepInput,normalizeModelMessages,normalizeUserContent,resolveAssistantStepText,validateHarnessModelMessages};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type LanguageModel, type ModelMessage } from "ai";
|
|
2
2
|
import type { StepCatalog } from "#execution/catalog/step-catalog.js";
|
|
3
3
|
import type { GenerationSteering } from "#harness/generation-steering.js";
|
|
4
|
-
import type { HarnessModelMessage
|
|
4
|
+
import type { HarnessModelMessage } from "#harness/messages.js";
|
|
5
5
|
import { type ModelProfile } from "#harness/model-profile.js";
|
|
6
6
|
import type { Step } from "#harness/step/context.js";
|
|
7
7
|
import { type Prompt } from "#harness/step/prompt.js";
|
|
@@ -24,7 +24,7 @@ interface ModelCallerInput {
|
|
|
24
24
|
readonly model: LanguageModel;
|
|
25
25
|
readonly generation: GenerationSteering;
|
|
26
26
|
readonly hidesHeldText: boolean;
|
|
27
|
-
readonly turnMessages: readonly
|
|
27
|
+
readonly turnMessages: readonly HarnessModelMessage[];
|
|
28
28
|
readonly approvedTools: ReadonlySet<string>;
|
|
29
29
|
readonly pendingApprovalsNote: string | undefined;
|
|
30
30
|
/** The prompt as the step started it, projected for the model. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ModelMessage, SystemModelMessage } from "ai";
|
|
2
2
|
import type { StepCatalog } from "#execution/catalog/step-catalog.js";
|
|
3
3
|
import { createCurrentMessages } from "#harness/current-messages.js";
|
|
4
|
-
import { type HarnessModelMessage
|
|
4
|
+
import { type HarnessModelMessage } from "#harness/messages.js";
|
|
5
5
|
import type { ModelProfile } from "#harness/model-profile.js";
|
|
6
6
|
import type { Step } from "#harness/step/context.js";
|
|
7
7
|
import type { HarnessSession } from "#harness/types.js";
|
|
@@ -14,7 +14,7 @@ export type RequestMessages = ReturnType<typeof createCurrentMessages>;
|
|
|
14
14
|
export declare function requestMessages(step: Step, input: {
|
|
15
15
|
readonly messages: readonly HarnessModelMessage[];
|
|
16
16
|
readonly projectedMessages: readonly HarnessModelMessage[];
|
|
17
|
-
readonly turnMessages: readonly
|
|
17
|
+
readonly turnMessages: readonly HarnessModelMessage[];
|
|
18
18
|
readonly catalog: StepCatalog;
|
|
19
19
|
readonly hidesHeldText: boolean;
|
|
20
20
|
readonly pendingApprovalsNote: string | undefined;
|
|
@@ -4,6 +4,7 @@ import type { AuthorizationChallenge } from "#harness/authorization.js";
|
|
|
4
4
|
import { type TurnWaitingOn, createSessionCompletedEvent, createSessionFailedEvent, type InputResolution, type RuntimeIdentity, type RuntimeTraceContext, type SessionPredecessor, type TaskCancelReason, type TaskStartedStreamEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
5
5
|
import type { RuntimeActionResult } from "#shared/action-types.js";
|
|
6
6
|
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
7
|
+
import type { SessionHistoryMessage } from "#shared/session-history.js";
|
|
7
8
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
8
9
|
import type { Transition } from "./commit.js";
|
|
9
10
|
import { type WorkflowAskRoute } from "#harness/hitl/relays.js";
|
|
@@ -17,9 +18,10 @@ export type ToolResultPart = Extract<ToolResponsePart, {
|
|
|
17
18
|
}>;
|
|
18
19
|
/**
|
|
19
20
|
* Input arrives: the session starts once, a turn opens unless one is open (steering joins it),
|
|
20
|
-
* and a message is received.
|
|
21
|
+
* any history the delivery added is published, and a message is received.
|
|
21
22
|
*/
|
|
22
23
|
export declare function receive(view: SessionView, input: {
|
|
24
|
+
readonly imported?: readonly SessionHistoryMessage[];
|
|
23
25
|
readonly message?: string | UserContent;
|
|
24
26
|
/** The session this one replaced, when eve started it in place of a stranded one. */
|
|
25
27
|
readonly predecessor?: SessionPredecessor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{activeTurnId,answeredCallIds,nextStepIndex,runningTasks,turnPosition}from"./view.js";import{inputWithdrawn,signInWithdrawn}from"./events.js";import{openInputs,openSignIns,turnCoordinates}from"#protocol/session-projection.js";import{createActionResultEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createContextClearedEvent,createInputRequestedEvent,createInputResolvedEvent,createMessageReceivedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTaskSettledEvent,createTaskStartedEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,createTurnWaitingEvent}from"#protocol/message.js";import{toProxyInputRequestEntries}from"#harness/hitl/relays.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";import{signInAttemptKey}from"#harness/hitl/sign-ins.js";const unchanged=(e,t)=>({events:t,turn:e.turn});function at(e){let t=turnPosition(e);return{sequence:t.sequence,stepIndex:t.stepIndex,turnId:activeTurnId(t)}}function receive(e,t){let n=turnPosition(e.projection),r=activeTurnId(n),i=[];return n.sessionStarted||i.push(createSessionStartedEvent({predecessor:t.predecessor,runtime:t.runtime,trace:t.trace})),n.turnId===``&&i.push(createTurnStartedEvent({sequence:n.sequence,trace:t.trace,turnId:r})),t.message!==void 0&&i.push(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:r})),unchanged(e,i)}function startStep(e,t){let{sequence:n,turnId:r}=at(e.projection);return unchanged(e,[createStepStartedEvent({modelId:t.modelId,sequence:n,stepIndex:nextStepIndex(e.projection),turnId:r})])}function hold(e,t){let{sequence:n,turnId:r}=turnPosition(e.projection);return r===``?unchanged(e,[]):unchanged(e,[createTurnWaitingEvent({on:t.on,sequence:n,turnId:r,usage:e.usage})])}function finishTurn(e,t={}){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=[];return t.result!==void 0&&a.push(createResultCompletedEvent({result:t.result,sequence:n,stepIndex:r,turnId:i})),e.projection.activeTurnId!==void 0&&a.push(createTurnCompletedEvent({sequence:n,turnId:i})),a.push(createSessionWaitingEvent(e.usage)),unchanged(e,a)}function fail(e,t){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=e.turn.suspended.filter(e=>(e.approved?.length??0)>0);return{commit:a.flatMap(cancelledTranscript),events:failedEvents(e,t,{sequence:n,stepIndex:r,turnId:i}),turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!a.includes(e))}}}function failedEvents(e,t,n){let{sequence:r,stepIndex:i,turnId:a}=n,{code:o,details:s,message:c}=t,l=t.terminal!==void 0;return[createStepFailedEvent({code:o,details:s,message:c,sequence:r,stepIndex:i,turnId:a}),createTurnFailedEvent({code:o,details:s,message:c,sequence:r,terminal:l,turnId:a}),t.terminal===void 0?createSessionWaitingEvent(e.usage):createSessionFailedEvent({code:o,details:s,message:c,sessionId:t.terminal.sessionId,usage:e.usage})]}function idle(e){return unchanged(e,[createSessionWaitingEvent(e.usage)])}function sessionCompleted(e){return createSessionCompletedEvent(e)}function sessionFailed(e){return createSessionFailedEvent(e)}function settle(e,t){let n=[],r=[...e.turn.suspended];for(let{part:e,result:i}of t.results){let t=r.findIndex(t=>stepCallIds(t).has(e.toolCallId)),a=r[t];a!==void 0&&(r[t]=withoutApproved({...a,messages:withResult(a.messages,e)},new Set([e.toolCallId])),i!==void 0&&n.push(createActionResultEvent({result:i,...a.event})))}for(let t of r)t.tasks.length!==0&&t.requests.length!==0&&(runningTasks(t).length>0||t.requests.some(t=>t.requestId in e.projection.inputs)||n.push(createInputRequestedEvent({requests:t.requests,...t.event})));let i=r.filter(isComplete);return{commit:i.flatMap(e=>e.messages),events:n,turn:{...e.turn,suspended:r.filter(e=>!i.includes(e))}}}const RETRIED_CALL_RESULT={code:`MODEL_CALL_ATTEMPT_RETRIED`,message:`The model call attempt was retried before this tool could run.`};function discardAttempt(e,t){let n=at(e.projection);return unchanged(e,t.calls.map(({callId:e,toolName:t})=>createActionResultEvent({...n,result:{callId:e,isError:!0,kind:`tool-result`,output:{...RETRIED_CALL_RESULT},toolName:t}})))}function suspendStep(e,t){return{events:[],turn:suspend(e.turn,{...t,requests:[]})}}function withoutApproved(e,t){if(e.approved===void 0)return e;let n=e.approved.filter(e=>!t.has(e.action.callId));if(n.length===e.approved.length)return e;let{approved:r,...i}=e;return n.length===0?i:{...i,approved:n}}function runnableCalls(e,t){let n=new Set(e.signIns.map(signInAttemptKey));return(t.approved??[]).filter(e=>(e.signIns??[]).every(e=>!n.has(signInAttemptKey(e))))}function approvedCalls(e){return e.turn.suspended.flatMap(t=>runnableCalls(e,t))}function suspend(e,t){return{...e,suspended:[...e.suspended,t]}}function stepCallIds(e){let t=new Set;for(let n of e.messages)if(n.role===`assistant`&&typeof n.content!=`string`)for(let e of n.content)e.type===`tool-call`&&e.providerExecuted!==!0&&t.add(e.toolCallId);return t}function isComplete(e){if(e.requests.length>0)return!1;let t=answeredCallIds(e.messages);return[...stepCallIds(e)].every(e=>t.has(e))}function withResult(e,t){let n=[...e],r=findCall(n,t.toolCallId);if(r===void 0)return n.push({content:[t],role:`tool`}),n;let i={...t,toolName:r.call.toolName},a=n[r.index+1];return a?.role===`tool`?n[r.index+1]={...a,content:[...a.content,i]}:n.splice(r.index+1,0,{content:[i],role:`tool`}),n}function withoutResults(e,t){return e.flatMap(e=>{if(e.role!==`tool`)return[e];let n=e.content.filter(e=>e.type!==`tool-result`||!t.has(e.toolCallId));return n.length===0?[]:[{...e,content:n}]})}function findCall(e,t){for(let[n,r]of e.entries()){if(r.role!==`assistant`||typeof r.content==`string`)continue;let e=r.content.find(e=>e.type===`tool-call`&&e.toolCallId===t);if(e!==void 0)return{call:e,index:n}}}function startTask(e,t){return unchanged(e,[createTaskStartedEvent(t)])}function settleTask(e,t){let{outcome:n,task:r}=t;return unchanged(e,t.calls.map(e=>{let t={callId:e.callId,kind:r.kind,name:r.name,taskId:r.id,turnId:e.turnId};switch(n.status){case`completed`:return createTaskSettledEvent({...t,output:n.output,status:`completed`});case`failed`:return createTaskSettledEvent({...t,error:{message:n.error},status:`failed`});case`cancelled`:return createTaskSettledEvent(n.reason===void 0?{...t,status:`cancelled`}:{...t,cancel:{reason:n.reason},status:`cancelled`})}}))}function finishRun(e,t){let n=new Set(t.requestIds);return unchanged(e,openInputs(e.projection).filter(e=>n.has(e.request.requestId)||t.taskId!==void 0&&e.taskId===t.taskId).map(inputWithdrawn))}function relay(e,t){let{payload:n}=t,r=[...finishRun(e,{requestIds:t.replacedRequestIds}).events];if(n.kind===`subagent-input-request`){let{event:e}=n;r.push(createInputRequestedEvent({callId:n.callId,requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId}))}else{let{event:t}=n;if(r.push(t),t.type!==`authorization.required`)return unchanged(e,r)}if(r.push(...hold(e,{on:`input`}).events),n.kind!==`subagent-input-request`)return unchanged(e,r);let i=toProxyInputRequestEntries(n).map(([e,n])=>[e,{...n,...t.workflowAsk!==void 0&&{workflowAsk:t.workflowAsk},...t.runId!==void 0&&{runId:t.runId}}]);return{...unchanged(e,r),relays:{upsert:{entries:i,forChildContinuationToken:n.childContinuationToken,inputSource:n.inputSource}}}}function receiveRelayedAnswer(e){return createMessageReceivedEvent(e)}function routeAnswer(e,t){let n=t.children.filter(e=>e.resolutions.length>0).map(e=>createInputResolvedEvent({resolutions:e.resolutions,...e.event}));t.holds===!0&&n.push(...hold(e,{on:`input`}).events);let r=t.children.flatMap(e=>e.resolutions.map(e=>e.requestId));return{...unchanged(e,n),...r.length>0&&{relays:{retire:r}}}}function runSignIn(e,t,n){let r={...authorizationEventFields(t),sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId};return n===void 0?createAuthorizationRequiredEvent({...r,description:`Sign in to ${t.name} to continue.`,webhookUrl:t.hookUrl}):createAuthorizationCompletedEvent({...r,outcome:n})}function matchSignIns(e,t){let n=new Set(t.attemptIds);return{...unchanged(e,[]),signIns:e.signIns.filter(e=>!n.has(signInAttemptKey(e)))}}function callSignIns(e){return e.suspended.flatMap(e=>(e.approved??[]).flatMap(e=>e.signIns??[]))}function awaitSignIns(e,t){let n=stepCallIds(e),r=t.stopped.filter(({action:e})=>n.has(e.callId));if(r.length===0)return e;let i=r.map(({action:n,connections:r})=>{let i=e.approved?.find(e=>e.action.callId===n.callId);return{action:n,requestId:i?.requestId??n.callId,signIns:[...i?.signIns??[],...t.challenges.filter(e=>r.includes(e.name))]}}),a=new Set(i.map(e=>e.action.callId));return{...e,messages:withoutResults(e.messages,a),approved:[...(e.approved??[]).filter(e=>!a.has(e.action.callId)),...i]}}function completeSignIn(e,t){let n=at(e.projection),r=new Set(callSignIns(e.turn).map(signInAttemptKey));return unchanged(e,t.completions.filter(e=>!r.has(signInAttemptKey(e))).map(t=>{let r=t.attemptId===void 0?void 0:e.projection.authorizations[t.attemptId];return createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:r?.sequence??n.sequence,stepIndex:r?.stepIndex??n.stepIndex,turnId:r?.turnId??n.turnId})}))}function ownOpenRequestIds(e){return new Set(openInputs(e.projection).filter(t=>t.callId===void 0&&t.taskId===void 0&&!e.relayedRequestIds.has(t.request.requestId)).map(e=>e.request.requestId))}const CANCELLED_CALL_RESULT=`The turn was cancelled before this call finished.`;function cancel(e){let{projection:t}=e,n=t.activeTurnId,r=e.turn.suspended.filter(e=>n!==void 0&&e.event.turnId===n||e.tasks.some(t=>!answeredCallIds(e.messages).has(t.callId))||(e.approved?.length??0)>0),i=new Set(r.flatMap(e=>e.requests.map(e=>e.requestId))),a=[...openInputs(t).filter(t=>t.turnId===n||i.has(t.request.requestId)||e.relayedRequestIds.has(t.request.requestId)||t.request.kind===`session-limit`).map(inputWithdrawn),...openSignIns(t).filter(e=>e.turnId===n).map(e=>signInWithdrawn(e,`Cancelled.`))];if(n!==void 0){let{sequence:e}=turnCoordinates(t);a.push(createTurnCancelledEvent({sequence:e,turnId:n}))}return a.push(createSessionWaitingEvent(e.usage)),{commit:r.flatMap(cancelledTranscript),events:a,signIns:[],turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!r.includes(e))}}}function cancelledTranscript(e){let t=answeredCallIds(e.messages),n=[...e.messages];for(let r of e.messages)if(r.role===`assistant`&&typeof r.content!=`string`)for(let e of r.content)e.type===`tool-call`&&e.providerExecuted!==!0&&(t.has(e.toolCallId)||(n=withResult(n,{output:{type:`text`,value:CANCELLED_CALL_RESULT},toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-result`})));return n}function clear(e,t){let{projection:n}=e,{sequence:r,turnId:i}=turnCoordinates(n);return{clearsHistory:!0,events:[...openInputs(n).filter(t=>!e.relayedRequestIds.has(t.request.requestId)).map(inputWithdrawn),...openSignIns(n).map(e=>signInWithdrawn(e,`The context was cleared.`)),createContextClearedEvent({sequence:r,sessionId:t.sessionId,turnId:i}),createSessionWaitingEvent(e.usage)],turn:{grants:e.turn.grants,suspended:[]}}}export{CANCELLED_CALL_RESULT,approvedCalls,awaitSignIns,callSignIns,cancel,clear,completeSignIn,discardAttempt,fail,finishRun,finishTurn,hold,idle,matchSignIns,ownOpenRequestIds,receive,receiveRelayedAnswer,relay,routeAnswer,runSignIn,runnableCalls,sessionCompleted,sessionFailed,settle,settleTask,startStep,startTask,stepCallIds,suspend,suspendStep,withResult,withoutApproved};
|
|
1
|
+
import{activeTurnId,answeredCallIds,nextStepIndex,runningTasks,turnPosition}from"./view.js";import{inputWithdrawn,signInWithdrawn}from"./events.js";import{openInputs,openSignIns,turnCoordinates}from"#protocol/session-projection.js";import{createActionResultEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createContextClearedEvent,createHistoryImportedEvent,createInputRequestedEvent,createInputResolvedEvent,createMessageReceivedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTaskSettledEvent,createTaskStartedEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,createTurnWaitingEvent}from"#protocol/message.js";import{toProxyInputRequestEntries}from"#harness/hitl/relays.js";import{authorizationEventFields}from"#harness/authorization-event-fields.js";import{signInAttemptKey}from"#harness/hitl/sign-ins.js";const unchanged=(e,t)=>({events:t,turn:e.turn});function at(e){let t=turnPosition(e);return{sequence:t.sequence,stepIndex:t.stepIndex,turnId:activeTurnId(t)}}function receive(e,t){let n=turnPosition(e.projection),r=activeTurnId(n),i=[];return n.sessionStarted||i.push(createSessionStartedEvent({predecessor:t.predecessor,runtime:t.runtime,trace:t.trace})),n.turnId===``&&i.push(createTurnStartedEvent({sequence:n.sequence,trace:t.trace,turnId:r})),t.imported!==void 0&&t.imported.length>0&&i.push(createHistoryImportedEvent({messages:t.imported,sequence:n.sequence,turnId:r})),t.message!==void 0&&i.push(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:r})),unchanged(e,i)}function startStep(e,t){let{sequence:n,turnId:r}=at(e.projection);return unchanged(e,[createStepStartedEvent({modelId:t.modelId,sequence:n,stepIndex:nextStepIndex(e.projection),turnId:r})])}function hold(e,t){let{sequence:n,turnId:r}=turnPosition(e.projection);return r===``?unchanged(e,[]):unchanged(e,[createTurnWaitingEvent({on:t.on,sequence:n,turnId:r,usage:e.usage})])}function finishTurn(e,t={}){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=[];return t.result!==void 0&&a.push(createResultCompletedEvent({result:t.result,sequence:n,stepIndex:r,turnId:i})),e.projection.activeTurnId!==void 0&&a.push(createTurnCompletedEvent({sequence:n,turnId:i})),a.push(createSessionWaitingEvent(e.usage)),unchanged(e,a)}function fail(e,t){let{sequence:n,stepIndex:r,turnId:i}=at(e.projection),a=e.turn.suspended.filter(e=>(e.approved?.length??0)>0);return{commit:a.flatMap(cancelledTranscript),events:failedEvents(e,t,{sequence:n,stepIndex:r,turnId:i}),turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!a.includes(e))}}}function failedEvents(e,t,n){let{sequence:r,stepIndex:i,turnId:a}=n,{code:o,details:s,message:c}=t,l=t.terminal!==void 0;return[createStepFailedEvent({code:o,details:s,message:c,sequence:r,stepIndex:i,turnId:a}),createTurnFailedEvent({code:o,details:s,message:c,sequence:r,terminal:l,turnId:a}),t.terminal===void 0?createSessionWaitingEvent(e.usage):createSessionFailedEvent({code:o,details:s,message:c,sessionId:t.terminal.sessionId,usage:e.usage})]}function idle(e){return unchanged(e,[createSessionWaitingEvent(e.usage)])}function sessionCompleted(e){return createSessionCompletedEvent(e)}function sessionFailed(e){return createSessionFailedEvent(e)}function settle(e,t){let n=[],r=[...e.turn.suspended];for(let{part:e,result:i}of t.results){let t=r.findIndex(t=>stepCallIds(t).has(e.toolCallId)),a=r[t];a!==void 0&&(r[t]=withoutApproved({...a,messages:withResult(a.messages,e)},new Set([e.toolCallId])),i!==void 0&&n.push(createActionResultEvent({result:i,...a.event})))}for(let t of r)t.tasks.length!==0&&t.requests.length!==0&&(runningTasks(t).length>0||t.requests.some(t=>t.requestId in e.projection.inputs)||n.push(createInputRequestedEvent({requests:t.requests,...t.event})));let i=r.filter(isComplete);return{commit:i.flatMap(e=>e.messages),events:n,turn:{...e.turn,suspended:r.filter(e=>!i.includes(e))}}}const RETRIED_CALL_RESULT={code:`MODEL_CALL_ATTEMPT_RETRIED`,message:`The model call attempt was retried before this tool could run.`};function discardAttempt(e,t){let n=at(e.projection);return unchanged(e,t.calls.map(({callId:e,toolName:t})=>createActionResultEvent({...n,result:{callId:e,isError:!0,kind:`tool-result`,output:{...RETRIED_CALL_RESULT},toolName:t}})))}function suspendStep(e,t){return{events:[],turn:suspend(e.turn,{...t,requests:[]})}}function withoutApproved(e,t){if(e.approved===void 0)return e;let n=e.approved.filter(e=>!t.has(e.action.callId));if(n.length===e.approved.length)return e;let{approved:r,...i}=e;return n.length===0?i:{...i,approved:n}}function runnableCalls(e,t){let n=new Set(e.signIns.map(signInAttemptKey));return(t.approved??[]).filter(e=>(e.signIns??[]).every(e=>!n.has(signInAttemptKey(e))))}function approvedCalls(e){return e.turn.suspended.flatMap(t=>runnableCalls(e,t))}function suspend(e,t){return{...e,suspended:[...e.suspended,t]}}function stepCallIds(e){let t=new Set;for(let n of e.messages)if(n.role===`assistant`&&typeof n.content!=`string`)for(let e of n.content)e.type===`tool-call`&&e.providerExecuted!==!0&&t.add(e.toolCallId);return t}function isComplete(e){if(e.requests.length>0)return!1;let t=answeredCallIds(e.messages);return[...stepCallIds(e)].every(e=>t.has(e))}function withResult(e,t){let n=[...e],r=findCall(n,t.toolCallId);if(r===void 0)return n.push({content:[t],role:`tool`}),n;let i={...t,toolName:r.call.toolName},a=n[r.index+1];return a?.role===`tool`?n[r.index+1]={...a,content:[...a.content,i]}:n.splice(r.index+1,0,{content:[i],role:`tool`}),n}function withoutResults(e,t){return e.flatMap(e=>{if(e.role!==`tool`)return[e];let n=e.content.filter(e=>e.type!==`tool-result`||!t.has(e.toolCallId));return n.length===0?[]:[{...e,content:n}]})}function findCall(e,t){for(let[n,r]of e.entries()){if(r.role!==`assistant`||typeof r.content==`string`)continue;let e=r.content.find(e=>e.type===`tool-call`&&e.toolCallId===t);if(e!==void 0)return{call:e,index:n}}}function startTask(e,t){return unchanged(e,[createTaskStartedEvent(t)])}function settleTask(e,t){let{outcome:n,task:r}=t;return unchanged(e,t.calls.map(e=>{let t={callId:e.callId,kind:r.kind,name:r.name,taskId:r.id,turnId:e.turnId};switch(n.status){case`completed`:return createTaskSettledEvent({...t,output:n.output,status:`completed`});case`failed`:return createTaskSettledEvent({...t,error:{message:n.error},status:`failed`});case`cancelled`:return createTaskSettledEvent(n.reason===void 0?{...t,status:`cancelled`}:{...t,cancel:{reason:n.reason},status:`cancelled`})}}))}function finishRun(e,t){let n=new Set(t.requestIds);return unchanged(e,openInputs(e.projection).filter(e=>n.has(e.request.requestId)||t.taskId!==void 0&&e.taskId===t.taskId).map(inputWithdrawn))}function relay(e,t){let{payload:n}=t,r=[...finishRun(e,{requestIds:t.replacedRequestIds}).events];if(n.kind===`subagent-input-request`){let{event:e}=n;r.push(createInputRequestedEvent({callId:n.callId,requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId}))}else{let{event:t}=n;if(r.push(t),t.type!==`authorization.required`)return unchanged(e,r)}if(r.push(...hold(e,{on:`input`}).events),n.kind!==`subagent-input-request`)return unchanged(e,r);let i=toProxyInputRequestEntries(n).map(([e,n])=>[e,{...n,...t.workflowAsk!==void 0&&{workflowAsk:t.workflowAsk},...t.runId!==void 0&&{runId:t.runId}}]);return{...unchanged(e,r),relays:{upsert:{entries:i,forChildContinuationToken:n.childContinuationToken,inputSource:n.inputSource}}}}function receiveRelayedAnswer(e){return createMessageReceivedEvent(e)}function routeAnswer(e,t){let n=t.children.filter(e=>e.resolutions.length>0).map(e=>createInputResolvedEvent({resolutions:e.resolutions,...e.event}));t.holds===!0&&n.push(...hold(e,{on:`input`}).events);let r=t.children.flatMap(e=>e.resolutions.map(e=>e.requestId));return{...unchanged(e,n),...r.length>0&&{relays:{retire:r}}}}function runSignIn(e,t,n){let r={...authorizationEventFields(t),sequence:e.sequence,stepIndex:e.stepIndex,taskId:e.taskId,turnId:e.turnId};return n===void 0?createAuthorizationRequiredEvent({...r,description:`Sign in to ${t.name} to continue.`,webhookUrl:t.hookUrl}):createAuthorizationCompletedEvent({...r,outcome:n})}function matchSignIns(e,t){let n=new Set(t.attemptIds);return{...unchanged(e,[]),signIns:e.signIns.filter(e=>!n.has(signInAttemptKey(e)))}}function callSignIns(e){return e.suspended.flatMap(e=>(e.approved??[]).flatMap(e=>e.signIns??[]))}function awaitSignIns(e,t){let n=stepCallIds(e),r=t.stopped.filter(({action:e})=>n.has(e.callId));if(r.length===0)return e;let i=r.map(({action:n,connections:r})=>{let i=e.approved?.find(e=>e.action.callId===n.callId);return{action:n,requestId:i?.requestId??n.callId,signIns:[...i?.signIns??[],...t.challenges.filter(e=>r.includes(e.name))]}}),a=new Set(i.map(e=>e.action.callId));return{...e,messages:withoutResults(e.messages,a),approved:[...(e.approved??[]).filter(e=>!a.has(e.action.callId)),...i]}}function completeSignIn(e,t){let n=at(e.projection),r=new Set(callSignIns(e.turn).map(signInAttemptKey));return unchanged(e,t.completions.filter(e=>!r.has(signInAttemptKey(e))).map(t=>{let r=t.attemptId===void 0?void 0:e.projection.authorizations[t.attemptId];return createAuthorizationCompletedEvent({...authorizationEventFields(t),outcome:`authorized`,sequence:r?.sequence??n.sequence,stepIndex:r?.stepIndex??n.stepIndex,turnId:r?.turnId??n.turnId})}))}function ownOpenRequestIds(e){return new Set(openInputs(e.projection).filter(t=>t.callId===void 0&&t.taskId===void 0&&!e.relayedRequestIds.has(t.request.requestId)).map(e=>e.request.requestId))}const CANCELLED_CALL_RESULT=`The turn was cancelled before this call finished.`;function cancel(e){let{projection:t}=e,n=t.activeTurnId,r=e.turn.suspended.filter(e=>n!==void 0&&e.event.turnId===n||e.tasks.some(t=>!answeredCallIds(e.messages).has(t.callId))||(e.approved?.length??0)>0),i=new Set(r.flatMap(e=>e.requests.map(e=>e.requestId))),a=[...openInputs(t).filter(t=>t.turnId===n||i.has(t.request.requestId)||e.relayedRequestIds.has(t.request.requestId)||t.request.kind===`session-limit`).map(inputWithdrawn),...openSignIns(t).filter(e=>e.turnId===n).map(e=>signInWithdrawn(e,`Cancelled.`))];if(n!==void 0){let{sequence:e}=turnCoordinates(t);a.push(createTurnCancelledEvent({sequence:e,turnId:n}))}return a.push(createSessionWaitingEvent(e.usage)),{commit:r.flatMap(cancelledTranscript),events:a,signIns:[],turn:{...e.turn,suspended:e.turn.suspended.filter(e=>!r.includes(e))}}}function cancelledTranscript(e){let t=answeredCallIds(e.messages),n=[...e.messages];for(let r of e.messages)if(r.role===`assistant`&&typeof r.content!=`string`)for(let e of r.content)e.type===`tool-call`&&e.providerExecuted!==!0&&(t.has(e.toolCallId)||(n=withResult(n,{output:{type:`text`,value:CANCELLED_CALL_RESULT},toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-result`})));return n}function clear(e,t){let{projection:n}=e,{sequence:r,turnId:i}=turnCoordinates(n);return{clearsHistory:!0,events:[...openInputs(n).filter(t=>!e.relayedRequestIds.has(t.request.requestId)).map(inputWithdrawn),...openSignIns(n).map(e=>signInWithdrawn(e,`The context was cleared.`)),createContextClearedEvent({sequence:r,sessionId:t.sessionId,turnId:i}),createSessionWaitingEvent(e.usage)],turn:{grants:e.turn.grants,suspended:[]}}}export{CANCELLED_CALL_RESULT,approvedCalls,awaitSignIns,callSignIns,cancel,clear,completeSignIn,discardAttempt,fail,finishRun,finishTurn,hold,idle,matchSignIns,ownOpenRequestIds,receive,receiveRelayedAnswer,relay,routeAnswer,runSignIn,runnableCalls,sessionCompleted,sessionFailed,settle,settleTask,startStep,startTask,stepCallIds,suspend,suspendStep,withResult,withoutApproved};
|
|
@@ -6,6 +6,7 @@ import { type StepProjection } from "#harness/session-machine/current.js";
|
|
|
6
6
|
import { type SessionView, type TurnPosition } from "#harness/session-machine/view.js";
|
|
7
7
|
import type { HarnessEmitFn, HarnessSession, StepFn, StepInput, StepResult, ToolLoopHarnessConfig } from "#harness/types.js";
|
|
8
8
|
import type { InstrumentationStepScope } from "#instrumentation/runtime.js";
|
|
9
|
+
import type { SessionHistoryMessage } from "#shared/session-history.js";
|
|
9
10
|
import type { createHistoryViewPreparer } from "#shared/history-view.js";
|
|
10
11
|
type HistoryViewPreparer = ReturnType<typeof createHistoryViewPreparer>;
|
|
11
12
|
/**
|
|
@@ -49,6 +50,8 @@ export declare function createStep(input: {
|
|
|
49
50
|
* preamble failed the session.
|
|
50
51
|
*/
|
|
51
52
|
export declare function openTurn(step: Step, opened: {
|
|
53
|
+
/** Prior conversation the delivery added, published before the message. */
|
|
54
|
+
readonly imported?: readonly SessionHistoryMessage[];
|
|
52
55
|
readonly input: readonly HarnessModelMessage[];
|
|
53
56
|
readonly message?: StepInput["message"];
|
|
54
57
|
}): Promise<StepResult | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createErrorId,createLogger}from"#internal/logging.js";import{recordAppliedSession}from"#harness/session-machine/current.js";import{ParentSessionKey,SessionCallbackKey,SessionPredecessorKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";import{
|
|
1
|
+
import{createErrorId,createLogger}from"#internal/logging.js";import{recordAppliedSession}from"#harness/session-machine/current.js";import{ParentSessionKey,SessionCallbackKey,SessionPredecessorKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{drainMemoryCommit,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";import{fail,receive}from"#harness/session-machine/transitions.js";import{isDynamicConnectionResolutionError}from"#context/dynamic-connection-lifecycle.js";import{applyTransition,sessionView}from"#harness/session-machine/commit.js";import{isDynamicModelSelectionError}from"#context/dynamic-model-lifecycle.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";const log=createLogger(`harness.step`);function createStep(e){let{ctx:t,live:n}=e,r={session:e.session,frameworkToolNames:new Set,config:e.config,ctx:t,runStep:e.runStep,publish:e.publish,emit:e.emit,instrumentation:e.instrumentation,hasDelegatedCaller:t?.get(ParentSessionKey)!==void 0||t?.get(SessionCallbackKey)!==void 0,view:()=>sessionView(n.read(),r.session.state),position:()=>turnPosition(n.read()),async apply(n,i){r.session=await applyTransition(r.session,n,e.publish,i),t!==void 0&&recordAppliedSession(t,r.session)},projectHistory:(t,n=r.session.state)=>e.prepareHistory(t,n).messages};return r}async function openTurn(e,t){let{config:n,ctx:r}=e;r!==void 0&&(prepareDynamicInstructionPreamble(r,e.projectHistory(e.session.history)),prepareMemoryPreamble(r,{history:e.session.history,input:[...t.input],projector:n.historyProjector,state:e.session.state}));let i;try{let i=e.position(),a=await e.instrumentation?.preparePreamble({sequence:i.sequence,sessionStarted:i.sessionStarted,traceContext:e.instrumentation?.traceContext,turnId:activeTurnId(i)});await e.apply(receive(e.view(),{imported:t.imported,message:t.message,predecessor:r?.get(SessionPredecessorKey),runtime:n.runtimeIdentity,trace:a}),e.projectHistory([...e.session.history,...t.input]))}catch(e){i={error:e}}let a=r===void 0?[]:drainDynamicInstructionUserMessages(r),o=r===void 0?void 0:drainMemoryCommit(r);if(e.session={...e.session,history:validateHarnessModelMessages([...e.session.history,...o?.recalledMessages??[],...a]),state:o?.state??e.session.state},i!==void 0)return failBoundaryEvent(e,i.error);e.instrumentation?.setTurnId(e.position().turnId)}async function failBoundaryEvent(e,t){if(throwIfTurnAborted(e.config.abortSignal),isTurnCancellation(t))throw t;if(isDynamicModelSelectionError(t))return failModelSelection(e,t);if(isDynamicConnectionResolutionError(t))return failConnectionResolution(e,t);throw t}async function failConnectionResolution(e,t){if(e.emit===void 0)throw t;e.instrumentation?.recordError(t);let n=createErrorId(),r=toErrorMessage(t);return log.error(`dynamic connection resolver failed — parking session`,{error:t,errorId:n,sessionId:e.session.sessionId,turnId:activeTurnId(e.position())}),await e.apply(fail(e.view(),{code:`EVENT_HANDLER_FAILED`,details:{errorId:n},message:r})),e.session={...e.session,outputSchema:void 0},{next:null,session:e.session,settledTurn:{isError:!0,output:r}}}async function failModelSelection(e,t){if(throwIfTurnAborted(e.config.abortSignal),e.instrumentation?.recordError(t),e.emit===void 0)throw t;let n=createErrorId(),r=toErrorMessage(t),{session:i}=e;return log.error(`model selection failed terminally`,{error:t,errorId:n,sessionId:i.sessionId,turnId:activeTurnId(e.position())}),await e.apply(fail(e.view(),{code:`MODEL_SELECTION_FAILED`,details:{errorId:n},message:r,terminal:{sessionId:i.sessionId}})),{next:e.hasDelegatedCaller?{done:!0,isError:!0,output:r}:{done:!0,output:``},session:e.session}}export{createStep,failBoundaryEvent,failConnectionResolution,failModelSelection,openTurn};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type HarnessModelMessage, type UserModelMessage } from "#harness/messages.js";
|
|
2
2
|
import { getTurnClientContextState } from "#harness/turn-client-context.js";
|
|
3
3
|
import type { StepInput } from "#harness/types.js";
|
|
4
|
+
import type { SessionHistoryMessage } from "#shared/session-history.js";
|
|
4
5
|
import type { Step } from "./context.js";
|
|
5
6
|
/**
|
|
6
7
|
* Settles the calls the runtime ran for parked steps. Returns `undefined` while some are still
|
|
@@ -18,8 +19,10 @@ export interface TurnInput {
|
|
|
18
19
|
readonly clientContext: readonly string[] | undefined;
|
|
19
20
|
readonly storedClientContext: ReturnType<typeof getTurnClientContextState>;
|
|
20
21
|
readonly ephemeral: readonly UserModelMessage[];
|
|
21
|
-
/**
|
|
22
|
-
readonly
|
|
22
|
+
/** Prior conversation the delivery added, as published in `history.imported`. */
|
|
23
|
+
readonly imported: readonly SessionHistoryMessage[];
|
|
24
|
+
/** The added history, the context entries, and the message, in history order. */
|
|
25
|
+
readonly messages: readonly HarnessModelMessage[];
|
|
23
26
|
/** The input carries a user's message, which follows tool results across a boundary. */
|
|
24
27
|
readonly hasUserMessage: boolean;
|
|
25
28
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readClientContext}from"#internal/client-context.js";import{TOOL_RESULT_BOUNDARY,createFrameworkUserMessage,createUserMessage,frameworkMessageKindForStepInput,normalizeUserContent}from"#harness/messages.js";import{activeTurnId,runtimeWait}from"#harness/session-machine/view.js";import{stageAttachmentsToSandbox,stageToolResultMedia}from"#harness/attachment-staging.js";import{forgetFinishedRuns,runtimeResultCalls}from"#harness/coordination.js";import{finishRun,settle}from"#harness/session-machine/transitions.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";import{getTurnClientContextState}from"#harness/turn-client-context.js";async function settleRuntimeWork(e,t){let n=runtimeWait(e.session.state);if(n===void 0)return{input:t,waited:!1};let r=resolveRuntimeActionResultsForCallIds({pendingCallIds:n.callIds,results:t?.runtimeActionResults??[]});if(r===void 0)return;let i=forgetFinishedRuns(e.session,r,n.event.turnId);e.session=i.session,await e.apply(finishRun(e.view(),{requestIds:i.requestIds}));let a=await runtimeResultCalls(r,e.config.tools),o=(await stageToolResultMedia([{role:`tool`,content:a.map(({part:e})=>e)}])).flatMap(e=>e.role===`tool`?e.content.filter(e=>e.type===`tool-result`):[]);if(await e.apply(settle(e.view(),{results:a.map((e,t)=>({...e,part:o[t]}))})),t===void 0)return{input:t,waited:!0};let{runtimeActionResults:s,...c}=t;return{input:c,waited:!0}}async function prepareTurnInput(e,t,n){let r=activeTurnId(e.position()),i=getTurnClientContextState(e.session.state,r),a=readClientContext(t),o=(a??i?.messages)?.map(e=>createFrameworkUserMessage(`context.instruction`,e))??[],s=(t?.context??[]).map(e=>createFrameworkUserMessage(`context.instruction`,e)),
|
|
1
|
+
import{readClientContext}from"#internal/client-context.js";import{TOOL_RESULT_BOUNDARY,createFrameworkUserMessage,createImportedHistoryMessages,createUserMessage,frameworkMessageKindForStepInput,normalizeUserContent}from"#harness/messages.js";import{activeTurnId,runtimeWait}from"#harness/session-machine/view.js";import{stageAttachmentsToSandbox,stageToolResultMedia}from"#harness/attachment-staging.js";import{forgetFinishedRuns,runtimeResultCalls}from"#harness/coordination.js";import{finishRun,settle}from"#harness/session-machine/transitions.js";import{resolveRuntimeActionResultsForCallIds}from"#runtime/actions/results.js";import{getTurnClientContextState}from"#harness/turn-client-context.js";async function settleRuntimeWork(e,t){let n=runtimeWait(e.session.state);if(n===void 0)return{input:t,waited:!1};let r=resolveRuntimeActionResultsForCallIds({pendingCallIds:n.callIds,results:t?.runtimeActionResults??[]});if(r===void 0)return;let i=forgetFinishedRuns(e.session,r,n.event.turnId);e.session=i.session,await e.apply(finishRun(e.view(),{requestIds:i.requestIds}));let a=await runtimeResultCalls(r,e.config.tools),o=(await stageToolResultMedia([{role:`tool`,content:a.map(({part:e})=>e)}])).flatMap(e=>e.role===`tool`?e.content.filter(e=>e.type===`tool-result`):[]);if(await e.apply(settle(e.view(),{results:a.map((e,t)=>({...e,part:o[t]}))})),t===void 0)return{input:t,waited:!0};let{runtimeActionResults:s,...c}=t;return{input:c,waited:!0}}async function prepareTurnInput(e,t,n){let r=activeTurnId(e.position()),i=getTurnClientContextState(e.session.state,r),a=readClientContext(t),o=(a??i?.messages)?.map(e=>createFrameworkUserMessage(`context.instruction`,e))??[],s=t?.history??[],c=[...createImportedHistoryMessages(s),...(t?.context??[]).map(e=>createFrameworkUserMessage(`context.instruction`,e))],l=frameworkMessageKindForStepInput(t),u=normalizeUserContent(t?.message),d=u!==void 0&&!n.consumedMessage?await stageAttachmentsToSandbox(u):void 0;return d!==void 0&&c.push(l===void 0?createUserMessage(`user`,d):createFrameworkUserMessage(l,d)),{clientContext:a,ephemeral:o,hasUserMessage:d!==void 0&&l===void 0,imported:s,messages:c,storedClientContext:i,turnId:r}}function followingToolResults(e){return[...e.hasUserMessage?[{content:TOOL_RESULT_BOUNDARY,role:`assistant`}]:[],...e.messages]}export{followingToolResults,prepareTurnInput,settleRuntimeWork};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage}from"#context/container.js";import{saveProjection,stepProjection}from"#harness/session-machine/current.js";import{ScheduleIdKey,StaticModelReferenceKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{clearMemorySessionState}from"#shared/memory-state.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";import{acceptHumanInput,admitApprovedWork,discardClearedHumanInput}from"#harness/hitl/index.js";import{clear}from"#harness/session-machine/transitions.js";import{createHistoryViewPreparer}from"#shared/history-view.js";import{compactHistory,replaceSessionHistory}from"#harness/compaction/step.js";import{createStep,openTurn}from"#harness/step/context.js";import{GenerationSteering}from"#harness/generation-steering.js";import{runModelStep}from"#harness/model-call/run.js";import{handleStepResult}from"#harness/step/after-model.js";import{prepareTurnInput,settleRuntimeWork}from"#harness/step/intake.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version;function createToolLoopHarness(e){e.instrumentation?.installAiSdkWarningLogger();async function runStep(t,n){let executeStep=async r=>{let i=r?.session??t,a=stepProjection(contextStorage.getStore(),i.state),o=new GenerationSteering({abortSignal:e.abortSignal,steeringSignal:e.steeringSignal,outputStarted:turnPosition(a.read()).assistantOutputStarted});try{let e=await executeStepBody(i,o,a,n,r);return{...e,session:saveProjection(e.session,a.read())}}finally{o.dispose()}};return e.instrumentation?.runStep({environment,eveVersion,hasInput:hasStepInput(n),session:t},executeStep)??executeStep()}async function executeStepBody(t,n,r,i,a){let o=createHistoryViewPreparer({previous:e.historyView,projector:e.historyProjector});o(t.history,t.state);let s=contextStorage.getStore();s!==void 0&&!s.has(StaticModelReferenceKey)&&s.setVirtualContext(StaticModelReferenceKey,t.agent.dynamicModel===!0?null:t.agent.modelReference??null);let c,l=a?.createHandleEvent({getAttemptScope:()=>c,isFrameworkTool:e=>u.frameworkToolNames.has(e),handleEvent:e.handleEvent,turnId:activeTurnId(turnPosition(r.read()))})??e.handleEvent,u=createStep({config:e,ctx:s,emit:l,instrumentation:a,live:r,prepareHistory:o,publish:async(e,t)=>{n.beforeEvent(e),l!==void 0&&await l(e,t),(l===void 0||s===void 0)&&r.record(e)},runStep,session:t});if(e.clearOnly===!0)return clearContext(u);if(e.compactOnly===!0)return compactHistory(u);let d=await settleRuntimeWork(u,i);if(d===void 0)return{next:null,session:u.session};let f=await acceptHumanInput(u,d.input,{takeQueued:!d.waited});if(f.kind===`stop`)return f.result;let p=await prepareTurnInput(u,f.input,{consumedMessage:f.consumedMessage});if(f.opensTurn){let e=await openTurn(u,{input:[...p.ephemeral,...p.messages],message:f.message});if(e!==void 0)return e}return await admitApprovedWork(u,f.approved),runModelStep(u,{approved:f.approved,onResponse:e=>handleStepResult(u,e),generation:n,hidesHeldText:u.hasDelegatedCaller||s?.get(ScheduleIdKey)!==void 0,setAttemptScope:e=>{c=e},turn:p})}return runStep}async function clearContext(e){await e.apply(clear(e.view(),{sessionId:e.session.sessionId}));let t=discardClearedHumanInput({...e.session,state:clearMemorySessionState(e.session.state)});return{next:null,session:replaceSessionHistory(t,[])}}function hasStepInput(e){return e===void 0?!1:e.message!==void 0||(e.inputResponses?.length??0)>0}export{createToolLoopHarness};
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{saveProjection,stepProjection}from"#harness/session-machine/current.js";import{ScheduleIdKey,StaticModelReferenceKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{clearMemorySessionState}from"#shared/memory-state.js";import{activeTurnId,turnPosition}from"#harness/session-machine/view.js";import{acceptHumanInput,admitApprovedWork,discardClearedHumanInput}from"#harness/hitl/index.js";import{clear}from"#harness/session-machine/transitions.js";import{createHistoryViewPreparer}from"#shared/history-view.js";import{compactHistory,replaceSessionHistory}from"#harness/compaction/step.js";import{createStep,openTurn}from"#harness/step/context.js";import{GenerationSteering}from"#harness/generation-steering.js";import{runModelStep}from"#harness/model-call/run.js";import{handleStepResult}from"#harness/step/after-model.js";import{prepareTurnInput,settleRuntimeWork}from"#harness/step/intake.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version;function createToolLoopHarness(e){e.instrumentation?.installAiSdkWarningLogger();async function runStep(t,n){let executeStep=async r=>{let i=r?.session??t,a=stepProjection(contextStorage.getStore(),i.state),o=new GenerationSteering({abortSignal:e.abortSignal,steeringSignal:e.steeringSignal,outputStarted:turnPosition(a.read()).assistantOutputStarted});try{let e=await executeStepBody(i,o,a,n,r);return{...e,session:saveProjection(e.session,a.read())}}finally{o.dispose()}};return e.instrumentation?.runStep({environment,eveVersion,hasInput:hasStepInput(n),session:t},executeStep)??executeStep()}async function executeStepBody(t,n,r,i,a){let o=createHistoryViewPreparer({previous:e.historyView,projector:e.historyProjector});o(t.history,t.state);let s=contextStorage.getStore();s!==void 0&&!s.has(StaticModelReferenceKey)&&s.setVirtualContext(StaticModelReferenceKey,t.agent.dynamicModel===!0?null:t.agent.modelReference??null);let c,l=a?.createHandleEvent({getAttemptScope:()=>c,isFrameworkTool:e=>u.frameworkToolNames.has(e),handleEvent:e.handleEvent,turnId:activeTurnId(turnPosition(r.read()))})??e.handleEvent,u=createStep({config:e,ctx:s,emit:l,instrumentation:a,live:r,prepareHistory:o,publish:async(e,t)=>{n.beforeEvent(e),l!==void 0&&await l(e,t),(l===void 0||s===void 0)&&r.record(e)},runStep,session:t});if(e.clearOnly===!0)return clearContext(u);if(e.compactOnly===!0)return compactHistory(u);let d=await settleRuntimeWork(u,i);if(d===void 0)return{next:null,session:u.session};let f=await acceptHumanInput(u,d.input,{takeQueued:!d.waited});if(f.kind===`stop`)return f.result;let p=await prepareTurnInput(u,f.input,{consumedMessage:f.consumedMessage});if(f.opensTurn){let e=await openTurn(u,{imported:p.imported,input:[...p.ephemeral,...p.messages],message:f.message});if(e!==void 0)return e}return await admitApprovedWork(u,f.approved),runModelStep(u,{approved:f.approved,onResponse:e=>handleStepResult(u,e),generation:n,hidesHeldText:u.hasDelegatedCaller||s?.get(ScheduleIdKey)!==void 0,setAttemptScope:e=>{c=e},turn:p})}return runStep}async function clearContext(e){await e.apply(clear(e.view(),{sessionId:e.session.sessionId}));let t=discardClearedHumanInput({...e.session,state:clearMemorySessionState(e.session.state)});return{next:null,session:replaceSessionHistory(t,[])}}function hasStepInput(e){return e===void 0?!1:e.message!==void 0||(e.inputResponses?.length??0)>0}export{createToolLoopHarness};
|
|
@@ -21,9 +21,7 @@
|
|
|
21
21
|
* the shared {@link TokenUsage} contract.
|
|
22
22
|
*/
|
|
23
23
|
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
|
|
24
|
-
import { type SessionRuntimeUsageLimits, type SessionUsageLimitViolation } from "#harness/session-usage-limits.js";
|
|
25
24
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
26
|
-
export type { SessionRuntimeUsageLimits, SessionUsageLimitViolation };
|
|
27
25
|
export interface TokenUsageTotals {
|
|
28
26
|
readonly cacheReadTokens: number;
|
|
29
27
|
readonly cacheWriteTokens: number;
|
|
@@ -52,31 +50,14 @@ export declare function getSessionUsage(session: Pick<HarnessSession, "state">):
|
|
|
52
50
|
/** Projects a {@link TokenUsageTotals} down to the cross-cutting {@link TokenUsage} shape. */
|
|
53
51
|
export declare function toUsage(totals: TokenUsageTotals): TokenUsage;
|
|
54
52
|
/**
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
* continuation the runtime limit equals the configured limit; each grant
|
|
58
|
-
* re-anchors it to `usage + configured limit` via
|
|
59
|
-
* {@link bumpSessionRuntimeUsageLimits}.
|
|
53
|
+
* What the session spent since the last approved continuation, or since it
|
|
54
|
+
* started. This is the `window` the session usage limit sees.
|
|
60
55
|
*/
|
|
61
|
-
export declare function
|
|
62
|
-
/**
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
* bump together to avoid back-to-back prompts. Configured limits never change.
|
|
67
|
-
*/
|
|
68
|
-
export declare function bumpSessionRuntimeUsageLimits(session: HarnessSession): HarnessSession;
|
|
69
|
-
/**
|
|
70
|
-
* Remaining lifetime usage quota under the runtime limits, per axis.
|
|
71
|
-
* `false` marks an uncapped axis. This is the pool a delegated child's
|
|
72
|
-
* budget is granted from.
|
|
73
|
-
*/
|
|
74
|
-
export declare function getSessionRemainingUsageQuota(session: Pick<HarnessSession, "limits" | "state">): {
|
|
75
|
-
costUsd: number | false;
|
|
76
|
-
inputTokens: number | false;
|
|
77
|
-
outputTokens: number | false;
|
|
78
|
-
};
|
|
79
|
-
export declare function getSessionUsageLimitViolation(session: Pick<HarnessSession, "limits" | "state">): SessionUsageLimitViolation | null;
|
|
56
|
+
export declare function getSessionUsageWindow(session: Pick<HarnessSession, "state">): TokenUsage;
|
|
57
|
+
/** Starts a new usage window at the session's current totals, after an approved continuation. */
|
|
58
|
+
export declare function resetSessionUsageWindow<T extends Pick<HarnessSession, "state">>(session: T): T;
|
|
59
|
+
/** How many usage windows the session has started before its current one. */
|
|
60
|
+
export declare function getSessionUsageWindowIndex(session: Pick<HarnessSession, "state">): number;
|
|
80
61
|
/**
|
|
81
62
|
* Takes the session-usage delta accumulated since the previous take and
|
|
82
63
|
* marks it reported.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
const HARNESS_TURN_USAGE_STATE_KEY=`eve.harness.turnUsage`,REPORTED_SESSION_USAGE_STATE_KEY=`eve.harness.reportedSessionUsage`,SESSION_USAGE_WINDOW_START_KEY=`eve.harness.sessionUsageWindowStart`,SESSION_USAGE_WINDOW_INDEX_KEY=`eve.harness.sessionUsageWindowIndex`,ZERO_TOKEN_USAGE={cacheReadTokens:0,cacheWriteTokens:0,costUsd:0,inputTokens:0,outputTokens:0,sawCost:!1};function getTurnUsageState(e){return e?.[HARNESS_TURN_USAGE_STATE_KEY]}function getSessionTokenUsage(e){return getTurnUsageState(e.state)?.session??ZERO_TOKEN_USAGE}function getSessionUsage(e){return toUsage(getSessionTokenUsage(e))}function toUsage(e){return{cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,costUsd:e.sawCost?e.costUsd:void 0,inputTokens:e.inputTokens,outputTokens:e.outputTokens}}function getSessionUsageWindow(e){return toUsage(subtractTokenUsage(getSessionTokenUsage(e),getWindowStart(e)))}function resetSessionUsageWindow(e){return{...e,state:{...e.state,[SESSION_USAGE_WINDOW_INDEX_KEY]:getSessionUsageWindowIndex(e)+1,[SESSION_USAGE_WINDOW_START_KEY]:getSessionTokenUsage(e)}}}function getSessionUsageWindowIndex(e){return e.state?.[SESSION_USAGE_WINDOW_INDEX_KEY]??0}function getWindowStart(e){return e.state?.[SESSION_USAGE_WINDOW_START_KEY]??ZERO_TOKEN_USAGE}function takeSessionUsageDelta(e){let t=getSessionTokenUsage(e);return{delta:toUsage(subtractTokenUsage(t,e.state?.[REPORTED_SESSION_USAGE_STATE_KEY]??ZERO_TOKEN_USAGE)),session:{...e,state:{...e.state,[REPORTED_SESSION_USAGE_STATE_KEY]:t}}}}function setTurnUsageState(e,t){return{...e,state:{...e.state,[HARNESS_TURN_USAGE_STATE_KEY]:t}}}function accumulateTurnUsage(e){let t=toTokenUsageDelta(e.usage),n=e.previous?.session??ZERO_TOKEN_USAGE;return{...addTokenUsage(e.previous!==void 0&&e.previous.turnId===e.turnId?e.previous:ZERO_TOKEN_USAGE,t),turnId:e.turnId,session:addTokenUsage(n,t)}}function addTurnUsage(e,t,n){return setTurnUsageState(e,accumulateTurnUsage({previous:getTurnUsageState(e.state),turnId:t,usage:n}))}function addUsageOutsideTurns(e,t){if(t===void 0)return e;let n=setTurnUsageState(e,accumulateSessionUsage({previous:getTurnUsageState(e.state),usage:t})),r=e.state?.[REPORTED_SESSION_USAGE_STATE_KEY]??ZERO_TOKEN_USAGE;return{...n,state:{...n.state,[REPORTED_SESSION_USAGE_STATE_KEY]:addTokenUsage(r,toTokenUsageDelta(t))}}}function accumulateSessionUsage(e){let t=toTokenUsageDelta(e.usage),n=e.previous??{...ZERO_TOKEN_USAGE,session:ZERO_TOKEN_USAGE,turnId:``};return{...n,session:addTokenUsage(n.session,t)}}function addTokenUsage(e,t){return{cacheReadTokens:e.cacheReadTokens+t.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens+t.cacheWriteTokens,costUsd:e.costUsd+t.costUsd,inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,sawCost:e.sawCost||t.sawCost}}function subtractTokenUsage(e,t){return{cacheReadTokens:e.cacheReadTokens-t.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens-t.cacheWriteTokens,costUsd:e.costUsd-t.costUsd,inputTokens:e.inputTokens-t.inputTokens,outputTokens:e.outputTokens-t.outputTokens,sawCost:e.sawCost||t.sawCost}}function toTokenUsageDelta(e){if(e===void 0)return ZERO_TOKEN_USAGE;let t=e.inputTokens??0,n=e.outputTokens??0;return{cacheReadTokens:e.cacheReadTokens??0,cacheWriteTokens:e.cacheWriteTokens??0,costUsd:e.costUsd??0,inputTokens:t,outputTokens:n,sawCost:e.costUsd!==void 0}}export{accumulateSessionUsage,accumulateTurnUsage,addTurnUsage,addUsageOutsideTurns,getSessionTokenUsage,getSessionUsage,getSessionUsageWindow,getSessionUsageWindowIndex,getTurnUsageState,resetSessionUsageWindow,setTurnUsageState,takeSessionUsageDelta,toUsage};
|
|
@@ -10,11 +10,12 @@ import type { SandboxState } from "#sandbox/state.js";
|
|
|
10
10
|
import type { JsonObject } from "#shared/json.js";
|
|
11
11
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
12
12
|
import type { InternalToolDefinition } from "#tools/definition.js";
|
|
13
|
-
import type { AgentReasoningDefinition } from "#shared/agent-definition.js";
|
|
13
|
+
import type { AgentReasoningDefinition, SessionUsageLimit } from "#shared/agent-definition.js";
|
|
14
14
|
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
|
|
15
15
|
import type { HarnessModelMessage } from "#harness/messages.js";
|
|
16
16
|
import type { SessionInstrumentation } from "#instrumentation/runtime.js";
|
|
17
17
|
import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";
|
|
18
|
+
import type { SessionHistoryMessage } from "#shared/session-history.js";
|
|
18
19
|
/**
|
|
19
20
|
* Serializable tool definition stored on the session.
|
|
20
21
|
*
|
|
@@ -64,7 +65,6 @@ export interface HarnessSessionBase {
|
|
|
64
65
|
readonly agent: SessionAgent;
|
|
65
66
|
readonly compaction: CompactionConfig;
|
|
66
67
|
readonly continuationToken: string;
|
|
67
|
-
readonly limits?: SessionLimits;
|
|
68
68
|
readonly outputSchema?: JsonObject;
|
|
69
69
|
/**
|
|
70
70
|
* Stable identifier of the top user-facing session in the dispatch
|
|
@@ -89,29 +89,6 @@ export interface HarnessSession extends HarnessSessionBase {
|
|
|
89
89
|
readonly history: HarnessModelMessage[];
|
|
90
90
|
}
|
|
91
91
|
export declare function requireSessionModelReference(session: HarnessSession): RuntimeModelReference;
|
|
92
|
-
/**
|
|
93
|
-
* Token limits stored on one durable session.
|
|
94
|
-
*/
|
|
95
|
-
export interface SessionLimits {
|
|
96
|
-
/**
|
|
97
|
-
* Maximum provider-reported input tokens this durable session may spend
|
|
98
|
-
* before eve refuses to start another model call. Absent when the session
|
|
99
|
-
* is uncapped. Root sessions default to 40M unless authored otherwise;
|
|
100
|
-
* delegated subagent sessions receive the parent's remaining quota at
|
|
101
|
-
* dispatch time.
|
|
102
|
-
*/
|
|
103
|
-
readonly maxInputTokensPerSession?: number;
|
|
104
|
-
/**
|
|
105
|
-
* Maximum provider-reported output tokens this durable session may spend before
|
|
106
|
-
* eve refuses to start another model call.
|
|
107
|
-
*/
|
|
108
|
-
readonly maxOutputTokensPerSession?: number;
|
|
109
|
-
/**
|
|
110
|
-
* Maximum provider-reported model token cost this durable session may spend,
|
|
111
|
-
* in US dollars, before eve refuses to start another model call.
|
|
112
|
-
*/
|
|
113
|
-
readonly maxTokenCostUsdPerSession?: number;
|
|
114
|
-
}
|
|
115
92
|
/**
|
|
116
93
|
* Input payload for a harness turn.
|
|
117
94
|
*
|
|
@@ -139,6 +116,12 @@ export interface StepInput {
|
|
|
139
116
|
* delivery message. Populated by channels via `SendPayload.context`.
|
|
140
117
|
*/
|
|
141
118
|
readonly context?: readonly string[];
|
|
119
|
+
/**
|
|
120
|
+
* Prior conversation from the channel delivery, added as user and assistant
|
|
121
|
+
* turns before this turn's context and message. Populated by channels via
|
|
122
|
+
* `SendPayload.history`.
|
|
123
|
+
*/
|
|
124
|
+
readonly history?: readonly SessionHistoryMessage[];
|
|
142
125
|
/**
|
|
143
126
|
* Run-scoped schema that replaces the session's current output schema when
|
|
144
127
|
* present. Omitted continuations keep the existing schema.
|
|
@@ -311,6 +294,8 @@ export interface ToolLoopHarnessConfig {
|
|
|
311
294
|
* authoritative server-side metadata.
|
|
312
295
|
*/
|
|
313
296
|
readonly runtimeIdentity?: RuntimeIdentity;
|
|
297
|
+
/** The agent's `limits.sessionUsage`; the default limit applies when absent. */
|
|
298
|
+
readonly sessionUsageLimit?: SessionUsageLimit;
|
|
314
299
|
/**
|
|
315
300
|
* Unified tool definitions for this harness step.
|
|
316
301
|
*
|
|
@@ -28,6 +28,8 @@ interface ApplicationBuildProfileTiming {
|
|
|
28
28
|
}
|
|
29
29
|
/** Stable JSON document written by `eve build --profile <path>`. */
|
|
30
30
|
export interface ApplicationBuildProfile {
|
|
31
|
+
/** Build identity exposed to the Workflow World; self-hosted output only. */
|
|
32
|
+
readonly deploymentId?: string | undefined;
|
|
31
33
|
readonly durationMs: number;
|
|
32
34
|
readonly kind: "eve-build-profile";
|
|
33
35
|
readonly output: ApplicationBuildProfileOutput;
|
|
@@ -50,6 +52,7 @@ export declare class ApplicationBuildProfiler {
|
|
|
50
52
|
}
|
|
51
53
|
/** Creates the versioned report shape from completed timings and output measurements. */
|
|
52
54
|
export declare function createApplicationBuildProfile(input: {
|
|
55
|
+
readonly deploymentId?: string | undefined;
|
|
53
56
|
readonly output: ApplicationBuildProfileOutput;
|
|
54
57
|
readonly target: ApplicationBuildProfileTarget;
|
|
55
58
|
readonly timing: ApplicationBuildProfileTiming;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{dirname,join,relative,sep}from"node:path";import{performance}from"node:perf_hooks";import{gzipSync}from"node:zlib";const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION=1;function roundDuration(e){return Math.round(Math.max(0,e)*10)/10}function createMutableOutputSize(){return{files:0,gzipBytes:0,rawBytes:0}}function toOutputSize(e){return{files:e.files,gzipBytes:e.gzipBytes,rawBytes:e.rawBytes}}function toProfilePath(e,t){return relative(e,t).split(sep).join(`/`)}function measureFileSize(e){return{gzipBytes:gzipSync(e).byteLength,rawBytes:e.byteLength}}function addFileSize(e,t){e.files+=1,e.rawBytes+=t.rawBytes,e.gzipBytes+=t.gzipBytes}var ApplicationBuildProfiler=class{#e;#t=[];#n;#r=!1;constructor(e={}){this.#e=e.now??performance.now.bind(performance),this.#n=this.#e()}async measure(e,t){if(this.#r)throw Error(`Cannot record a phase after the build profile has finished.`);let n=this.#e();try{return await t()}finally{this.#t.push({durationMs:roundDuration(this.#e()-n),name:e})}}finish(){if(this.#r)throw Error(`The build profile has already finished.`);return this.#r=!0,{durationMs:roundDuration(this.#e()-this.#n),phases:[...this.#t]}}};function createApplicationBuildProfile(e){return{durationMs:e.timing.durationMs,kind:`eve-build-profile`,output:e.output,phases:e.timing.phases,schemaVersion:1,target:e.target}}async function measureApplicationBuildOutput(e){let t=createMutableOutputSize(),n=new Map,visit=async(r,i)=>{let a=await readdir(r,{withFileTypes:!0});for(let o of a){let a=join(r,o.name);if(o.isDirectory()){let t=o.name.endsWith(`.func`)?toProfilePath(e,a):i;await visit(a,t);continue}if(!o.isFile())continue;let s=measureFileSize(await readFile(a));if(addFileSize(t,s),i!==void 0){let e=n.get(i)??createMutableOutputSize();addFileSize(e,s),n.set(i,e)}}};return await visit(e,void 0),{...toOutputSize(t),functionBundles:[...n.entries()].map(([e,t])=>({path:e,...toOutputSize(t)})).sort((e,t)=>e.path.localeCompare(t.path))}}async function writeApplicationBuildProfile(e,t){await mkdir(dirname(e),{recursive:!0}),await writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}export{APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile};
|
|
1
|
+
import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{dirname,join,relative,sep}from"node:path";import{performance}from"node:perf_hooks";import{gzipSync}from"node:zlib";const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION=1;function roundDuration(e){return Math.round(Math.max(0,e)*10)/10}function createMutableOutputSize(){return{files:0,gzipBytes:0,rawBytes:0}}function toOutputSize(e){return{files:e.files,gzipBytes:e.gzipBytes,rawBytes:e.rawBytes}}function toProfilePath(e,t){return relative(e,t).split(sep).join(`/`)}function measureFileSize(e){return{gzipBytes:gzipSync(e).byteLength,rawBytes:e.byteLength}}function addFileSize(e,t){e.files+=1,e.rawBytes+=t.rawBytes,e.gzipBytes+=t.gzipBytes}var ApplicationBuildProfiler=class{#e;#t=[];#n;#r=!1;constructor(e={}){this.#e=e.now??performance.now.bind(performance),this.#n=this.#e()}async measure(e,t){if(this.#r)throw Error(`Cannot record a phase after the build profile has finished.`);let n=this.#e();try{return await t()}finally{this.#t.push({durationMs:roundDuration(this.#e()-n),name:e})}}finish(){if(this.#r)throw Error(`The build profile has already finished.`);return this.#r=!0,{durationMs:roundDuration(this.#e()-this.#n),phases:[...this.#t]}}};function createApplicationBuildProfile(e){return{deploymentId:e.deploymentId,durationMs:e.timing.durationMs,kind:`eve-build-profile`,output:e.output,phases:e.timing.phases,schemaVersion:1,target:e.target}}async function measureApplicationBuildOutput(e){let t=createMutableOutputSize(),n=new Map,visit=async(r,i)=>{let a=await readdir(r,{withFileTypes:!0});for(let o of a){let a=join(r,o.name);if(o.isDirectory()){let t=o.name.endsWith(`.func`)?toProfilePath(e,a):i;await visit(a,t);continue}if(!o.isFile())continue;let s=measureFileSize(await readFile(a));if(addFileSize(t,s),i!==void 0){let e=n.get(i)??createMutableOutputSize();addFileSize(e,s),n.set(i,e)}}};return await visit(e,void 0),{...toOutputSize(t),functionBundles:[...n.entries()].map(([e,t])=>({path:e,...toOutputSize(t)})).sort((e,t)=>e.path.localeCompare(t.path))}}async function writeApplicationBuildProfile(e,t){await mkdir(dirname(e),{recursive:!0}),await writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}export{APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{copyFile,mkdir,readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{buildPackageUserAgent}from"#internal/user-agent.js";import{sandboxPreparedArtifactsManifestSchema}from"#shared/sandbox-prepared-artifacts.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import"#internal/instrumentation-layout.js";import{resolveWorkflowWorldImport}from"#internal/workflow/world-target.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-module-map.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),i=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),a=sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(e.compileResult.paths.sandboxPreparedArtifactsPath,`utf8`))),o=await prepareAuthoredRuntimeModules({appRoot:e.compileResult.project.appRoot,manifest:e.compileResult.manifest,moduleMapPath:e.compileResult.paths.moduleMapPath});await mkdir(e.outDir,{recursive:!0}),await writeFile(n,o.moduleMapCode),await writeFile(t,createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),metadata:e.compileResult.metadata,moduleMapImportPath:n,sandboxPreparedArtifacts:a})),await writeFile(i,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld}));let s={authoredWorkflowModules:o.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:i},c=await writePreparedInstrumentation({instrumentation:o.instrumentation,outDir:e.outDir});return await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:c})),s.instrumentationPluginPath=r,s.instrumentationLayout=generatedInstrumentationLayout(c),s.instrumentationSourcePaths=instrumentationSourcePathsOf(c),s}async function writePreparedInstrumentation(e){let writeOne=async(t,n)=>{let r=join(e.outDir,`compiled-artifacts-instrumentation-${t}.mjs`);return await writeFile(r,n),r},t={};for(let[n,r]of Object.entries(e.instrumentation.moduleCodeBySlot))t[n]=await writeOne(n,r);return{kind:`directory`,modulePathsBySlot:t}}function instrumentationSourcePathsOf(e){return Object.values(e.modulePathsBySlot)}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),i=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(i===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(r,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let a={authoredWorkflowModules:e.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:r};if(i.instrumentation!==void 0){let t=await copyMaterializedInstrumentation({instrumentation:i.instrumentation,outDir:e.outDir,runtimeAppRoot:e.runtimeAppRoot});await writeFile(n,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:t})),a.instrumentationPluginPath=n,a.instrumentationLayout=generatedInstrumentationLayout(t),a.instrumentationSourcePaths=instrumentationSourcePathsOf(t)}return a}function generatedInstrumentationLayout(e){return{kind:`directory`,slots:Object.keys(e.modulePathsBySlot)}}async function copyMaterializedInstrumentation(e){let t=join(e.runtimeAppRoot,`.eve`,`compile`),copyOne=async(n,r)=>{let i=join(e.outDir,`compiled-artifacts-instrumentation-${n}.mjs`);return await copyFile(join(t,r),i),i},n={};for(let[t,r]of Object.entries(e.instrumentation.modulePathsBySlot))n[t]=await copyOne(t,r);return{kind:`directory`,modulePathsBySlot:n}}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
|
|
1
|
+
import{copyFile,mkdir,readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{buildPackageUserAgent}from"#internal/user-agent.js";import{sandboxPreparedArtifactsManifestSchema}from"#shared/sandbox-prepared-artifacts.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{prepareAuthoredRuntimeModules}from"#internal/authored-runtime-modules.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import"#internal/instrumentation-layout.js";import{resolveWorkflowWorldImport}from"#internal/workflow/world-target.js";import{BUILD_DEPLOYMENT_ID_PLACEHOLDER}from"#internal/nitro/host/build-deployment-id.js";async function writeCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-module-map.mjs`),r=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),i=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),a=sandboxPreparedArtifactsManifestSchema.parse(JSON.parse(await readFile(e.compileResult.paths.sandboxPreparedArtifactsPath,`utf8`))),o=await prepareAuthoredRuntimeModules({appRoot:e.compileResult.project.appRoot,manifest:e.compileResult.manifest,moduleMapPath:e.compileResult.paths.moduleMapPath});await mkdir(e.outDir,{recursive:!0}),await writeFile(n,o.moduleMapCode),await writeFile(t,createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),metadata:e.compileResult.metadata,moduleMapImportPath:n,sandboxPreparedArtifacts:a})),await writeFile(i,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld}));let s={authoredWorkflowModules:o.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:i},c=await writePreparedInstrumentation({instrumentation:o.instrumentation,outDir:e.outDir});return await writeFile(r,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:c})),s.instrumentationPluginPath=r,s.instrumentationLayout=generatedInstrumentationLayout(c),s.instrumentationSourcePaths=instrumentationSourcePathsOf(c),s}async function writePreparedInstrumentation(e){let writeOne=async(t,n)=>{let r=join(e.outDir,`compiled-artifacts-instrumentation-${t}.mjs`);return await writeFile(r,n),r},t={};for(let[n,r]of Object.entries(e.instrumentation.moduleCodeBySlot))t[n]=await writeOne(n,r);return{kind:`directory`,modulePathsBySlot:t}}function instrumentationSourcePathsOf(e){return Object.values(e.modulePathsBySlot)}async function writeDevelopmentCompiledArtifactsFiles(e){let t=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),i=await readMaterializedAuthoredModuleIndex(e.runtimeAppRoot);if(i===void 0)throw Error(`Development generation at "${e.runtimeAppRoot}" is not materialized.`);await mkdir(e.outDir,{recursive:!0}),await writeFile(t,createDevelopmentCompiledArtifactsBootstrapSource(e.compileResult.manifest.config.name)),await writeFile(r,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:t,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));let a={authoredWorkflowModules:e.authoredWorkflowModules,bootstrapPath:t,workflowWorldPluginPath:r};if(i.instrumentation!==void 0){let t=await copyMaterializedInstrumentation({instrumentation:i.instrumentation,outDir:e.outDir,runtimeAppRoot:e.runtimeAppRoot});await writeFile(n,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:t})),a.instrumentationPluginPath=n,a.instrumentationLayout=generatedInstrumentationLayout(t),a.instrumentationSourcePaths=instrumentationSourcePathsOf(t)}return a}function generatedInstrumentationLayout(e){return{kind:`directory`,slots:Object.keys(e.modulePathsBySlot)}}async function copyMaterializedInstrumentation(e){let t=join(e.runtimeAppRoot,`.eve`,`compile`),copyOne=async(n,r)=>{let i=join(e.outDir,`compiled-artifacts-instrumentation-${n}.mjs`);return await copyFile(join(t,r),i),i},n={};for(let[t,r]of Object.entries(e.instrumentation.modulePathsBySlot))n[t]=await copyOne(t,r);return{kind:`directory`,modulePathsBySlot:n}}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
|
|
2
2
|
`)}function createCompiledArtifactsBootstrapSource(e){let t=e.compileResult.manifest.config.name;return[`// Generated by eve. Do not edit by hand.`,`import moduleMap from ${stringifyEsmImportSpecifier(e.moduleMapImportPath)};`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(e.installModulePath)};`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(t)});`,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`const sandboxPreparedArtifacts = ${JSON.stringify(e.sandboxPreparedArtifacts,null,2)};`,``,`export { moduleMap };`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` sandboxPreparedArtifacts,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``].join(`
|
|
3
3
|
`)}function resolveInstallWorldImportSpecifier(){return resolvePackageSourceFilePath(`src/execution/install-workflow-world.ts`)}function resolveWorkflowWorldWiring(e){if(e===`@workflow/world-local`){let t=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/local-world-data-directory.ts`)),n=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/local-world-delivery-timeouts.ts`));return{moduleImportSpecifier:resolvePackageCompiledFilePath(`src/compiled/${e}/index.js`),extraImportLines:`
|
|
4
4
|
import { applyLocalWorkflowWorldDeliveryTimeoutDefaults } from ${n};
|
|
@@ -10,7 +10,7 @@ const workflowWorld = await workflowWorldModule.createWorld({
|
|
|
10
10
|
const workflowWorld = await workflowWorldModule.createWorld({
|
|
11
11
|
headers: { "User-Agent": ${JSON.stringify(buildPackageUserAgent())} },
|
|
12
12
|
});
|
|
13
|
-
applyVercelWorkflowWorldDefaults(workflowWorld);`.trimStart();return{moduleImportSpecifier:n,extraImportLines:[`import { applyVercelWorkflowWorldDefaults } from ${t};`],createWorldSource:r}}return{moduleImportSpecifier:e,extraImportLines:[`import { createWorldFromModule } from ${stringifyEsmImportSpecifier(resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`))};`],createWorldSource:`const workflowWorld = await createWorldFromModule(workflowWorldModule);`}}function createWorkflowWorldPluginSource(e){let t=e.configuredWorld??e.defaultWorld,n=resolveWorkflowWorldWiring(resolveWorkflowWorldImport(t));return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(e.compiledArtifactsBootstrapPath)};`,`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(n.moduleImportSpecifier)};`,...n.extraImportLines,`import { installWorkflowWorld } from ${stringifyEsmImportSpecifier(resolveInstallWorldImportSpecifier())}
|
|
13
|
+
applyVercelWorkflowWorldDefaults(workflowWorld);`.trimStart();return{moduleImportSpecifier:n,extraImportLines:[`import { applyVercelWorkflowWorldDefaults } from ${t};`],createWorldSource:r}}return{moduleImportSpecifier:e,extraImportLines:[`import { createWorldFromModule } from ${stringifyEsmImportSpecifier(resolvePackageCompiledFilePath(`src/compiled/@workflow/core/runtime.js`))};`],createWorldSource:`const workflowWorld = await createWorldFromModule(workflowWorldModule);`}}function createWorkflowWorldPluginSource(e){let t=e.configuredWorld??e.defaultWorld,n=resolveWorkflowWorldWiring(resolveWorkflowWorldImport(t));return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(e.compiledArtifactsBootstrapPath)};`,`import * as workflowWorldModule from ${stringifyEsmImportSpecifier(n.moduleImportSpecifier)};`,...n.extraImportLines,`import { installWorkflowWorld } from ${stringifyEsmImportSpecifier(resolveInstallWorldImportSpecifier())};`,`import { installWorkflowDeploymentId } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/execution/install-workflow-deployment-id.ts`))};`,``,`installWorkflowDeploymentId(${JSON.stringify(BUILD_DEPLOYMENT_ID_PLACEHOLDER)});`,n.createWorldSource,`await installWorkflowWorld({ packageName: ${JSON.stringify(e.configuredWorld)}, world: workflowWorld });`,``,`export default function installWorkflowWorldPlugin() {}`,``].join(`
|
|
14
14
|
`)}function createDevelopmentWorkflowWorldPluginSource(e){if(!usesParentDevelopmentWorkflowWorld(e.configuredWorld))return createWorkflowWorldPluginSource({...e,defaultWorld:`local`});let t=resolvePackageSourceFilePath(`src/internal/workflow/development-world-client.ts`);return[`// Generated by eve. Do not edit by hand.`,`import ${stringifyEsmImportSpecifier(e.compiledArtifactsBootstrapPath)};`,`import { createDevelopmentWorkflowWorld } from ${stringifyEsmImportSpecifier(t)};`,`import { installWorkflowWorld } from ${stringifyEsmImportSpecifier(resolveInstallWorldImportSpecifier())};`,``,`await installWorkflowWorld({ world: createDevelopmentWorkflowWorld() });`,``,`export default function installDevelopmentWorkflowWorldPlugin() {}`,``].join(`
|
|
15
15
|
`)}function createInstrumentationPluginSource(e){let t=JSON.stringify(e.agentName),n=resolvePackageSourceFilePath(`src/instrumentation/providers.ts`),r=Object.entries(e.layout.modulePathsBySlot);return[`// Generated by eve. Do not edit by hand.`,...r.map(([e,t],n)=>`import * as provider${n} from ${stringifyEsmImportSpecifier(t)}; // ${e}`),`import { finalizeInstrumentationProviders, registerInstrumentationProvider, seedInstrumentationProviders, shutdownInstrumentationProviders } from ${stringifyEsmImportSpecifier(n)};`,``,`seedInstrumentationProviders();`,``,...r.flatMap(([e],n)=>[`await registerInstrumentationProvider({`,` agentName: ${t},`,` slot: ${JSON.stringify(e)},`,` value: provider${n}.default,`,`});`]),``,`finalizeInstrumentationProviders({ serviceName: ${t} });`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin(nitroApp) {`,` // The last point a buffered exporter can still reach the network.`,` nitroApp?.hooks?.hook('close', async () => {`,` await shutdownInstrumentationProviders();`,` });`,`}`,``].join(`
|
|
16
16
|
`)}export{createCompiledArtifactsBootstrapSource,createDevelopmentWorkflowWorldPluginSource,createWorkflowWorldPluginSource,writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles};
|