eve 0.66.0 → 0.66.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/dist/src/channel/forwarded-principal.d.ts +26 -6
- package/dist/src/channel/forwarded-principal.js +1 -1
- package/dist/src/chunks/{use-eve-agent-BUeSjwIk.js → use-eve-agent-Di1u2zKu.js} +24 -4
- package/dist/src/chunks/{use-eve-agent-ydPlURM4.js → use-eve-agent-PbSMyJ6e.js} +24 -4
- package/dist/src/cli/commands/deploy.d.ts +3 -1
- package/dist/src/cli/commands/deploy.js +1 -1
- package/dist/src/cli/commands/extension-build.js +1 -1
- package/dist/src/cli/commands/integration-connect.js +1 -1
- package/dist/src/cli/commands/register-project-commands.js +1 -1
- package/dist/src/cli/commands/registry-project.d.ts +2 -1
- package/dist/src/cli/commands/registry-project.js +2 -2
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/commands/trace-detail.d.ts +5 -25
- package/dist/src/cli/commands/trace-detail.js +1 -1
- package/dist/src/cli/commands/trace.js +2 -2
- package/dist/src/cli/commands/vercel-non-interactive.d.ts +7 -0
- package/dist/src/cli/commands/vercel-non-interactive.js +1 -1
- package/dist/src/cli/dev/run-interactive-ui.js +1 -1
- package/dist/src/cli/dev/tui/argument-typeahead.d.ts +1 -1
- package/dist/src/cli/dev/tui/argument-typeahead.js +1 -1
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/registry-result-message.js +1 -1
- package/dist/src/cli/dev/tui/remote-auth.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +2 -2
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +3 -1
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/cli/dev/tui/setup-panel.d.ts +14 -0
- package/dist/src/cli/dev/tui/setup-panel.js +4 -4
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +2 -10
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +2 -2
- package/dist/src/cli/dev/tui/terminal-renderer.js +10 -10
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/client/client-error.js +1 -1
- package/dist/src/client/open-stream.d.ts +3 -2
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +16 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/discover/filesystem.d.ts +2 -0
- package/dist/src/discover/filesystem.js +1 -1
- package/dist/src/discover/grammar.d.ts +4 -2
- package/dist/src/discover/grammar.js +1 -1
- package/dist/src/discover/sandbox.js +1 -1
- package/dist/src/evals/session.d.ts +3 -2
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/types.d.ts +8 -2
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/types.d.ts +12 -4
- package/dist/src/execution/cancel-indexed-session-tasks-step.js +1 -1
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/route-child-delivery.js +2 -2
- package/dist/src/execution/session/admission.js +1 -1
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/input-queue.d.ts +12 -10
- package/dist/src/execution/session/input-queue.js +1 -1
- package/dist/src/execution/session/next-input.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/turn-step-result.d.ts +3 -1
- package/dist/src/execution/session/turn-step-result.js +1 -1
- package/dist/src/execution/session/turn-step-types.d.ts +7 -2
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session/turn.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/parent/control-shared.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +1 -0
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/ask-question-workflow.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-preparation.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
- package/dist/src/execution/tools/subagent/task-cancel.d.ts +1 -1
- package/dist/src/execution/tools/subagent/task-cancel.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-tag-state.d.ts +2 -2
- package/dist/src/harness/workflow-tool-runs.d.ts +33 -5
- package/dist/src/harness/workflow-tool-runs.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/instrumentation-layout.js +1 -1
- package/dist/src/internal/model-auth/vercel-cli.d.ts +2 -0
- package/dist/src/internal/model-auth/vercel-cli.js +1 -1
- package/dist/src/internal/nitro/host/build-extension.js +1 -1
- package/dist/src/internal/nitro/host/extension-build-lock.d.ts +9 -0
- package/dist/src/internal/nitro/host/extension-build-lock.js +1 -0
- package/dist/src/internal/nitro/host/extension-capability-requirements.d.ts +1 -0
- package/dist/src/internal/nitro/host/extension-capability-requirements.js +1 -1
- package/dist/src/internal/nitro/host/extension-declarations.js +1 -1
- package/dist/src/internal/nitro/host/extension-distribution.js +1 -1
- package/dist/src/internal/nitro/host/extension-state-usage.d.ts +2 -2
- package/dist/src/internal/nitro/host/extension-state-usage.js +1 -1
- package/dist/src/internal/nitro/host/prepare-application-host.d.ts +5 -4
- package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
- package/dist/src/internal/nitro/host/types.d.ts +2 -2
- package/dist/src/internal/nitro/host/workspace-extensions.d.ts +31 -0
- package/dist/src/internal/nitro/host/workspace-extensions.js +1 -0
- package/dist/src/public/next/index.d.ts +10 -7
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/server.d.ts +3 -0
- package/dist/src/public/next/server.js +2 -2
- package/dist/src/self-modification/extension/local-only.d.ts +5 -0
- package/dist/src/self-modification/extension/local-only.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/instructions.js +6 -6
- package/dist/src/self-modification/extension/subagents/agent/skills/trace_analysis.d.ts +10 -0
- package/dist/src/self-modification/extension/subagents/agent/skills/trace_analysis.js +19 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace.d.ts +128 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace_spans.d.ts +80 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/inspect_trace_spans.js +1 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/registry_add.js +1 -1
- package/dist/src/self-modification/extension/subagents/agent/tools/search_traces.d.ts +53 -0
- package/dist/src/self-modification/extension/subagents/agent/tools/search_traces.js +1 -0
- package/dist/src/self-modification/extension/trace-inspection.d.ts +15 -0
- package/dist/src/self-modification/extension/trace-inspection.js +1 -0
- package/dist/src/self-modification/sandbox.js +1 -1
- package/dist/src/setup/ask.d.ts +2 -0
- package/dist/src/setup/ask.js +1 -1
- package/dist/src/setup/boxes/link-project.d.ts +2 -0
- package/dist/src/setup/boxes/link-project.js +1 -1
- package/dist/src/setup/cli/option-row.d.ts +3 -1
- package/dist/src/setup/cli/option-row.js +1 -1
- package/dist/src/setup/flows/deploy.d.ts +1 -0
- package/dist/src/setup/flows/deploy.js +1 -1
- package/dist/src/setup/flows/install-vercel-cli.js +1 -1
- package/dist/src/setup/flows/login.js +1 -1
- package/dist/src/setup/flows/model-login-connection.js +1 -1
- package/dist/src/setup/flows/model-login.d.ts +4 -0
- package/dist/src/setup/flows/model-login.js +1 -1
- package/dist/src/setup/flows/vercel-model-login.js +1 -1
- package/dist/src/setup/integrations/runner.js +1 -1
- package/dist/src/setup/integrations/web/setup.d.ts +15 -10
- package/dist/src/setup/integrations/web/setup.js +30 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +7 -3
- package/dist/src/setup/scaffold/create/web-template.js +39 -20
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/slackbot.js +1 -1
- package/dist/src/setup/vercel-project.d.ts +2 -0
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/setup/vercel-trace-sampling.d.ts +3 -0
- package/dist/src/setup/vercel-trace-sampling.js +1 -0
- package/dist/src/subagents/parent-notification.d.ts +1 -1
- package/dist/src/subagents/remote-dispatch.d.ts +1 -0
- package/dist/src/subagents/remote-dispatch.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/delivery-context.js +2 -2
- package/dist/src/tasks/notification.d.ts +6 -0
- package/dist/src/tasks/notification.js +1 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/local-trace-analysis.d.ts +51 -0
- package/dist/src/tracing/local-trace-analysis.js +1 -0
- package/dist/src/tracing/local-trace-discovery-index.d.ts +15 -0
- package/dist/src/tracing/local-trace-discovery-index.js +1 -0
- package/dist/src/tracing/local-trace-operations.d.ts +13 -0
- package/dist/src/tracing/local-trace-operations.js +1 -0
- package/dist/src/tracing/local-trace-query.d.ts +17 -0
- package/dist/src/tracing/local-trace-query.js +1 -0
- package/dist/src/tracing/local-trace-span-processor.js +1 -1
- package/dist/src/tracing/local-trace-summary.d.ts +31 -0
- package/dist/src/tracing/local-trace-summary.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/project-structure.mdx +2 -4
- package/docs/concepts/sessions-runs-and-streaming.md +2 -2
- package/docs/evals/cases.mdx +1 -0
- package/docs/extensions.md +3 -1
- package/docs/guides/auth-and-route-protection.md +33 -1
- package/docs/guides/client/streaming.mdx +26 -0
- package/docs/guides/deployment/vercel.mdx +5 -5
- package/docs/guides/frontend/nextjs.mdx +20 -7
- package/docs/guides/frontend/overview.mdx +1 -1
- package/docs/guides/instrumentation/agent-runs.mdx +4 -4
- package/docs/guides/remote-agents.md +3 -1
- package/docs/install-integrations.mdx +1 -1
- package/docs/reference/agent-files.md +16 -0
- package/docs/reference/cli.md +1 -1
- package/docs/subagents/index.mdx +8 -2
- package/package.json +1 -1
- package/dist/src/internal/nitro/host/dev-workspace-extensions.d.ts +0 -18
- package/dist/src/internal/nitro/host/dev-workspace-extensions.js +0 -1
- package/dist/src/tasks/session-task-cohorts.d.ts +0 -7
- package/dist/src/tasks/session-task-cohorts.js +0 -1
|
@@ -131,9 +131,11 @@ export declare const DISCOVER_UNSUPPORTED_DIRECTORY = "discover/unsupported-dire
|
|
|
131
131
|
*/
|
|
132
132
|
export type StringDirent = Dirent<string>;
|
|
133
133
|
/**
|
|
134
|
-
* Reads
|
|
134
|
+
* Reads sorted agent source entries, excluding colocated tests unless reading resources.
|
|
135
135
|
*/
|
|
136
|
-
export declare function readSortedDirectoryEntries(source: ProjectSource, directoryPath: string
|
|
136
|
+
export declare function readSortedDirectoryEntries(source: ProjectSource, directoryPath: string, options?: {
|
|
137
|
+
readonly includeTests?: boolean;
|
|
138
|
+
}): Promise<ProjectSourceEntry[]>;
|
|
137
139
|
/**
|
|
138
140
|
* Discovers instructions sources from a root directory.
|
|
139
141
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"node:path";import{getDirectoryEntryType}from"#discover/filesystem.js";import{createDiscoverErrorDiagnostic,createDiscoverWarningDiagnostic}from"#discover/diagnostics.js";import{createModuleSourceRef}from"#discover/manifest.js";import{collectFlatSlotCandidates}from"#discover/slots.js";import{lowerInstructionsMarkdown}from"#internal/helpers/markdown.js";import{discoverMarkdownSource}from"#discover/markdown.js";import{discoverNamedSourceDirectory,discoverNamedSourceDirectory as discoverNamedSourceDirectory$1}from"#discover/named-source-directory.js";const DISCOVER_MODULE_SLOT_COLLISION=`discover/module-slot-collision`,DISCOVER_REQUIRED_INSTRUCTIONS_MISSING=`discover/required-instructions-missing`,DISCOVER_DEPRECATED_SYSTEM_SLOT=`discover/deprecated-system-slot`,DISCOVER_SLOT_COLLISION=`discover/slot-collision`,DISCOVER_TOOLS_DIRECTORY_INVALID=`discover/tools-directory-invalid`,DISCOVER_HOOKS_DIRECTORY_INVALID=`discover/hooks-directory-invalid`,DISCOVER_CHANNELS_DIRECTORY_INVALID=`discover/channels-directory-invalid`,DISCOVER_EXTENSIONS_DIRECTORY_INVALID=`discover/extensions-directory-invalid`,DISCOVER_TOOL_NAME_INVALID=`discover/tool-name-invalid`,DISCOVER_CONNECTION_NAME_INVALID=`discover/connection-name-invalid`,DISCOVER_SANDBOX_DIRECTORY_INVALID=`discover/sandbox-directory-invalid`,DISCOVER_INSTRUCTIONS_DIRECTORY_INVALID=`discover/instructions-directory-invalid`,DISCOVER_CHANNEL_NAME_INVALID=`discover/channel-name-invalid`,DISCOVER_HOOK_NAME_INVALID=`discover/hook-name-invalid`,DISCOVER_EXTENSION_NAME_INVALID=`discover/extension-name-invalid`,TOOL_SLUG_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,CONNECTION_SLUG_PATTERN=/^[a-z][a-z0-9-]{0,63}$/,CHANNEL_SLUG_PATTERN=/^(\.?[a-z][a-z0-9-]{0,63}|\[[a-zA-Z][a-zA-Z0-9_]{0,63}\])$/,HOOK_SLUG_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,EXTENSION_SLUG_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,DISCOVER_UNSUPPORTED_DIRECTORY=`discover/unsupported-directory`;async function readSortedDirectoryEntries(e,t){let
|
|
1
|
+
import{join}from"node:path";import{getDirectoryEntryType,isAuthoredTestPath}from"#discover/filesystem.js";import{createDiscoverErrorDiagnostic,createDiscoverWarningDiagnostic}from"#discover/diagnostics.js";import{createModuleSourceRef}from"#discover/manifest.js";import{collectFlatSlotCandidates}from"#discover/slots.js";import{lowerInstructionsMarkdown}from"#internal/helpers/markdown.js";import{discoverMarkdownSource}from"#discover/markdown.js";import{discoverNamedSourceDirectory,discoverNamedSourceDirectory as discoverNamedSourceDirectory$1}from"#discover/named-source-directory.js";const DISCOVER_MODULE_SLOT_COLLISION=`discover/module-slot-collision`,DISCOVER_REQUIRED_INSTRUCTIONS_MISSING=`discover/required-instructions-missing`,DISCOVER_DEPRECATED_SYSTEM_SLOT=`discover/deprecated-system-slot`,DISCOVER_SLOT_COLLISION=`discover/slot-collision`,DISCOVER_TOOLS_DIRECTORY_INVALID=`discover/tools-directory-invalid`,DISCOVER_HOOKS_DIRECTORY_INVALID=`discover/hooks-directory-invalid`,DISCOVER_CHANNELS_DIRECTORY_INVALID=`discover/channels-directory-invalid`,DISCOVER_EXTENSIONS_DIRECTORY_INVALID=`discover/extensions-directory-invalid`,DISCOVER_TOOL_NAME_INVALID=`discover/tool-name-invalid`,DISCOVER_CONNECTION_NAME_INVALID=`discover/connection-name-invalid`,DISCOVER_SANDBOX_DIRECTORY_INVALID=`discover/sandbox-directory-invalid`,DISCOVER_INSTRUCTIONS_DIRECTORY_INVALID=`discover/instructions-directory-invalid`,DISCOVER_CHANNEL_NAME_INVALID=`discover/channel-name-invalid`,DISCOVER_HOOK_NAME_INVALID=`discover/hook-name-invalid`,DISCOVER_EXTENSION_NAME_INVALID=`discover/extension-name-invalid`,TOOL_SLUG_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,CONNECTION_SLUG_PATTERN=/^[a-z][a-z0-9-]{0,63}$/,CHANNEL_SLUG_PATTERN=/^(\.?[a-z][a-z0-9-]{0,63}|\[[a-zA-Z][a-zA-Z0-9_]{0,63}\])$/,HOOK_SLUG_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,EXTENSION_SLUG_PATTERN=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,DISCOVER_UNSUPPORTED_DIRECTORY=`discover/unsupported-directory`;async function readSortedDirectoryEntries(e,t,n={}){let r=(await e.readDirectory(t)).filter(e=>n.includeTests||!isAuthoredTestPath(e.name));return r.sort((e,t)=>e.name.localeCompare(t.name)),r}async function discoverInstructionsSource(e){let t=e.rootEntries.some(e=>e.name===`instructions`&&e.isDirectory()),n=await discoverSlotSource({markdownFileName:`instructions.md`,moduleBaseName:`instructions`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`instructions`,source:e.source});if(t){let t=await discoverNamedSourceDirectory$1({allowMarkdown:!0,directoryName:`instructions`,invalidDirectoryCode:DISCOVER_INSTRUCTIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(e.rootPath,`instructions`)}" to be a directory of authored instructions.`,markdownLowerer:e=>lowerInstructionsMarkdown(e),recursive:!1,rootEntries:e.rootEntries,rootPath:e.rootPath,source:e.source}),r=[...t.sources];return n.source!==void 0&&r.unshift(n.source),{diagnostics:[...n.diagnostics,...t.diagnostics],instructions:r}}if(n.diagnostics.length>0||n.source!==void 0)return{diagnostics:n.diagnostics,instructions:n.source===void 0?[]:[n.source]};let r=await discoverSlotSource({markdownFileName:`system.md`,moduleBaseName:`system`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`system`,source:e.source});if(r.source!==void 0){let t=r.source.sourceKind===`markdown`?`system.md`:r.source.logicalPath;return{diagnostics:[createDiscoverWarningDiagnostic({code:DISCOVER_DEPRECATED_SYSTEM_SLOT,message:`The "${t}" slot is deprecated. Rename it to "${t.replace(/^system/,`instructions`)}" — the runtime still loads the legacy slot for now, but support will be removed in a future release.`,sourcePath:join(e.rootPath,t)}),...r.diagnostics],instructions:[r.source]}}return r.diagnostics.length>0?{diagnostics:r.diagnostics,instructions:[]}:e.required===!1?{diagnostics:[],instructions:[]}:{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_REQUIRED_INSTRUCTIONS_MISSING,message:`Expected authored instructions at "instructions.md", "instructions.ts", "instructions.cts", "instructions.mts", "instructions.js", "instructions.cjs", "instructions.mjs", or "instructions/" directory.`,sourcePath:e.rootPath})],instructions:[]}}async function discoverSlotSource(e){let t=collectFlatSlotCandidates(e.rootEntries,{markdownFileName:e.markdownFileName,moduleBaseName:e.moduleBaseName});if(t.markdownFileName!==void 0&&t.moduleFileNames.length>0)return{diagnostics:[createSlotCollisionDiagnostic(e.rootPath,e.slotLabel,[t.markdownFileName,...t.moduleFileNames])]};if(t.moduleFileNames.length>1)return{diagnostics:[createModuleSlotCollisionDiagnostic(e.rootPath,e.slotLabel,t.moduleFileNames)]};if(t.markdownFileName!==void 0)return{diagnostics:[],source:await discoverMarkdownSource({logicalPath:e.markdownFileName,lower:lowerInstructionsMarkdown,source:e.source,sourcePath:join(e.rootPath,t.markdownFileName)})};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:[]}:{diagnostics:[],source:createModuleSourceRef({logicalPath:n})}}function discoverFlatModuleSource(e){let t=collectFlatSlotCandidates(e.rootEntries,{moduleBaseName:e.slotName});if(t.moduleFileNames.length>1)return{diagnostics:[createModuleSlotCollisionDiagnostic(e.rootPath,e.slotName,t.moduleFileNames)]};let[n]=t.moduleFileNames;return n===void 0?e.missingDiagnostic===void 0?{diagnostics:[]}:{diagnostics:[createDiscoverErrorDiagnostic({code:e.missingDiagnostic.code,message:e.missingDiagnostic.message,sourcePath:e.rootPath})]}:{diagnostics:[],module:createModuleSourceRef({logicalPath:n})}}function createToolNameDiagnostic(e,t){return TOOL_SLUG_PATTERN.test(e)?null:createDiscoverErrorDiagnostic({code:DISCOVER_TOOL_NAME_INVALID,message:`Tool filename "${e}" is not a legal tool name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function createConnectionNameDiagnostic(e,t){return CONNECTION_SLUG_PATTERN.test(e)?null:createDiscoverErrorDiagnostic({code:DISCOVER_CONNECTION_NAME_INVALID,message:`Connection filename "${e}" is not a legal connection name. Expected lowercase ASCII letters, digits, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function createChannelNameDiagnostic(e,t){return CHANNEL_SLUG_PATTERN.test(e)?null:createDiscoverErrorDiagnostic({code:DISCOVER_CHANNEL_NAME_INVALID,message:`Channel path segment "${e}" is not a legal channel name. Expected lowercase kebab-case (\`my-channel\`), optionally with a leading dot (\`.well-known\`), or a path parameter form (\`[sessionId]\`).`,sourcePath:t})}function createHookNameDiagnostic(e,t){return HOOK_SLUG_PATTERN.test(e)?null:createDiscoverErrorDiagnostic({code:DISCOVER_HOOK_NAME_INVALID,message:`Hook path segment "${e}" is not a legal hook name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function createExtensionNameDiagnostic(e,t){return EXTENSION_SLUG_PATTERN.test(e)?null:createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_NAME_INVALID,message:`Extension mount filename "${e}" is not a legal extension namespace. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function createUnsupportedRootDirectoryDiagnostics(e){return e.rootEntries.flatMap(t=>!t.isDirectory()||e.classifyEntry(t.name,getDirectoryEntryType(t))!==`unknown`?[]:[createDiscoverWarningDiagnostic({code:DISCOVER_UNSUPPORTED_DIRECTORY,message:e.createUnsupportedDirectoryMessage(t.name),sourcePath:join(e.rootPath,t.name)})])}function createSlotCollisionDiagnostic(e,t,n){return createDiscoverErrorDiagnostic({code:DISCOVER_SLOT_COLLISION,message:`Found conflicting authored sources for "${t}": ${formatQuotedFileList(n)}.`,sourcePath:e})}function createModuleSlotCollisionDiagnostic(e,t,n){return createDiscoverErrorDiagnostic({code:DISCOVER_MODULE_SLOT_COLLISION,message:`Found multiple authored module sources for "${t}": ${formatQuotedFileList(n)}.`,sourcePath:e})}function formatQuotedFileList(e){return e.map(e=>`"${e}"`).join(`, `)}export{CHANNEL_SLUG_PATTERN,CONNECTION_SLUG_PATTERN,DISCOVER_CHANNELS_DIRECTORY_INVALID,DISCOVER_CHANNEL_NAME_INVALID,DISCOVER_CONNECTION_NAME_INVALID,DISCOVER_DEPRECATED_SYSTEM_SLOT,DISCOVER_EXTENSIONS_DIRECTORY_INVALID,DISCOVER_EXTENSION_NAME_INVALID,DISCOVER_HOOKS_DIRECTORY_INVALID,DISCOVER_HOOK_NAME_INVALID,DISCOVER_INSTRUCTIONS_DIRECTORY_INVALID,DISCOVER_MODULE_SLOT_COLLISION,DISCOVER_REQUIRED_INSTRUCTIONS_MISSING,DISCOVER_SANDBOX_DIRECTORY_INVALID,DISCOVER_SLOT_COLLISION,DISCOVER_TOOLS_DIRECTORY_INVALID,DISCOVER_TOOL_NAME_INVALID,DISCOVER_UNSUPPORTED_DIRECTORY,EXTENSION_SLUG_PATTERN,HOOK_SLUG_PATTERN,TOOL_SLUG_PATTERN,createChannelNameDiagnostic,createConnectionNameDiagnostic,createExtensionNameDiagnostic,createHookNameDiagnostic,createModuleSlotCollisionDiagnostic,createSlotCollisionDiagnostic,createToolNameDiagnostic,createUnsupportedRootDirectoryDiagnostics,discoverFlatModuleSource,discoverInstructionsSource,discoverNamedSourceDirectory,readSortedDirectoryEntries};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"node:path";import{normalizeLogicalPath}from"#discover/filesystem.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{createModuleSourceRef,createPathDerivedSourceId}from"#discover/manifest.js";import{DISCOVER_MODULE_SLOT_COLLISION,DISCOVER_SANDBOX_DIRECTORY_INVALID,readSortedDirectoryEntries}from"#discover/grammar.js";import{collectFlatSlotCandidates,collectNamedSlotCandidates}from"#discover/slots.js";const SANDBOX_DIRECTORY_NAME=`sandbox`,SANDBOX_WORKSPACE_DIRECTORY_NAME=`workspace`,SANDBOX_DEFINITION_BASE_NAME=`sandbox`,DISCOVER_SANDBOX_FOLDER_EMPTY=`discover/sandbox-folder-empty`;async function discoverSandboxSource(e){let t=[],n=e.rootEntries.find(e=>e.name===SANDBOX_DIRECTORY_NAME);if(n===void 0)return discoverRootSandboxModule({diagnostics:t,rootEntries:e.rootEntries,rootPath:e.rootPath});let r=join(e.rootPath,SANDBOX_DIRECTORY_NAME);if(!n.isDirectory())return t.push(createDiscoverErrorDiagnostic({code:DISCOVER_SANDBOX_DIRECTORY_INVALID,message:`Expected "${r}" to be the sandbox folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let i=await readSortedDirectoryEntries(e.source,r),a=collectFolderSandboxModuleCandidates(i),o=i.find(e=>e.name===SANDBOX_WORKSPACE_DIRECTORY_NAME&&e.isDirectory()),s=i.some(e=>e.name===`Dockerfile`&&e.isFile());if(a.length>1)return t.push(createDiscoverErrorDiagnostic({code:DISCOVER_MODULE_SLOT_COLLISION,message:`Found multiple sandbox definition modules inside "${normalizeLogicalPath(SANDBOX_DIRECTORY_NAME)}": `+a.map(e=>`"${e}"`).join(`, `),sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let[c]=a,l=c!==void 0,u=o!==void 0;if(!l&&!u&&!s)return t.push(createDiscoverErrorDiagnostic({code:DISCOVER_SANDBOX_FOLDER_EMPTY,message:`Sandbox folder "sandbox/" contains no "Dockerfile", "sandbox.<ext>" definition, or "workspace/" subdirectory. Add one or remove the folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let d=null;l&&(d=createModuleSourceRef({logicalPath:join(SANDBOX_DIRECTORY_NAME,c)}));let f=null;if(u){let t=join(r,SANDBOX_WORKSPACE_DIRECTORY_NAME),n=normalizeLogicalPath(join(SANDBOX_DIRECTORY_NAME,SANDBOX_WORKSPACE_DIRECTORY_NAME));f={logicalPath:n,rootEntries:await collectWorkspaceRootEntries(e.source,t),sourceId:createPathDerivedSourceId(n),sourcePath:t}}return{diagnostics:t,sandbox:d,sandboxWorkspace:f}}function discoverRootSandboxModule(e){let t=collectFlatSlotCandidates(e.rootEntries,{moduleBaseName:SANDBOX_DEFINITION_BASE_NAME});if(t.moduleFileNames.length>1)return e.diagnostics.push(createDiscoverErrorDiagnostic({code:DISCOVER_MODULE_SLOT_COLLISION,message:`Found multiple top-level sandbox definition modules: `+t.moduleFileNames.map(e=>`"${e}"`).join(`, `),sourcePath:e.rootPath})),{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null}:{diagnostics:e.diagnostics,sandbox:createModuleSourceRef({logicalPath:n}),sandboxWorkspace:null}}function collectFolderSandboxModuleCandidates(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of collectNamedSlotCandidates(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===SANDBOX_DEFINITION_BASE_NAME&&n.push(...e.moduleFileNames);return n}async function collectWorkspaceRootEntries(e,t){let n=await readSortedDirectoryEntries(e,t),r=[];for(let e of n){if(e.isDirectory()){r.push(`${e.name}/`);continue}e.isFile()&&r.push(e.name)}return r}export{DISCOVER_SANDBOX_FOLDER_EMPTY,discoverSandboxSource};
|
|
1
|
+
import{join}from"node:path";import{normalizeLogicalPath}from"#discover/filesystem.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{createModuleSourceRef,createPathDerivedSourceId}from"#discover/manifest.js";import{DISCOVER_MODULE_SLOT_COLLISION,DISCOVER_SANDBOX_DIRECTORY_INVALID,readSortedDirectoryEntries}from"#discover/grammar.js";import{collectFlatSlotCandidates,collectNamedSlotCandidates}from"#discover/slots.js";const SANDBOX_DIRECTORY_NAME=`sandbox`,SANDBOX_WORKSPACE_DIRECTORY_NAME=`workspace`,SANDBOX_DEFINITION_BASE_NAME=`sandbox`,DISCOVER_SANDBOX_FOLDER_EMPTY=`discover/sandbox-folder-empty`;async function discoverSandboxSource(e){let t=[],n=e.rootEntries.find(e=>e.name===SANDBOX_DIRECTORY_NAME);if(n===void 0)return discoverRootSandboxModule({diagnostics:t,rootEntries:e.rootEntries,rootPath:e.rootPath});let r=join(e.rootPath,SANDBOX_DIRECTORY_NAME);if(!n.isDirectory())return t.push(createDiscoverErrorDiagnostic({code:DISCOVER_SANDBOX_DIRECTORY_INVALID,message:`Expected "${r}" to be the sandbox folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let i=await readSortedDirectoryEntries(e.source,r),a=collectFolderSandboxModuleCandidates(i),o=i.find(e=>e.name===SANDBOX_WORKSPACE_DIRECTORY_NAME&&e.isDirectory()),s=i.some(e=>e.name===`Dockerfile`&&e.isFile());if(a.length>1)return t.push(createDiscoverErrorDiagnostic({code:DISCOVER_MODULE_SLOT_COLLISION,message:`Found multiple sandbox definition modules inside "${normalizeLogicalPath(SANDBOX_DIRECTORY_NAME)}": `+a.map(e=>`"${e}"`).join(`, `),sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let[c]=a,l=c!==void 0,u=o!==void 0;if(!l&&!u&&!s)return t.push(createDiscoverErrorDiagnostic({code:DISCOVER_SANDBOX_FOLDER_EMPTY,message:`Sandbox folder "sandbox/" contains no "Dockerfile", "sandbox.<ext>" definition, or "workspace/" subdirectory. Add one or remove the folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let d=null;l&&(d=createModuleSourceRef({logicalPath:join(SANDBOX_DIRECTORY_NAME,c)}));let f=null;if(u){let t=join(r,SANDBOX_WORKSPACE_DIRECTORY_NAME),n=normalizeLogicalPath(join(SANDBOX_DIRECTORY_NAME,SANDBOX_WORKSPACE_DIRECTORY_NAME));f={logicalPath:n,rootEntries:await collectWorkspaceRootEntries(e.source,t),sourceId:createPathDerivedSourceId(n),sourcePath:t}}return{diagnostics:t,sandbox:d,sandboxWorkspace:f}}function discoverRootSandboxModule(e){let t=collectFlatSlotCandidates(e.rootEntries,{moduleBaseName:SANDBOX_DEFINITION_BASE_NAME});if(t.moduleFileNames.length>1)return e.diagnostics.push(createDiscoverErrorDiagnostic({code:DISCOVER_MODULE_SLOT_COLLISION,message:`Found multiple top-level sandbox definition modules: `+t.moduleFileNames.map(e=>`"${e}"`).join(`, `),sourcePath:e.rootPath})),{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null}:{diagnostics:e.diagnostics,sandbox:createModuleSourceRef({logicalPath:n}),sandboxWorkspace:null}}function collectFolderSandboxModuleCandidates(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of collectNamedSlotCandidates(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===SANDBOX_DEFINITION_BASE_NAME&&n.push(...e.moduleFileNames);return n}async function collectWorkspaceRootEntries(e,t){let n=await readSortedDirectoryEntries(e,t,{includeTests:!0}),r=[];for(let e of n){if(e.isDirectory()){r.push(`${e.name}/`);continue}e.isFile()&&r.push(e.name)}return r}export{DISCOVER_SANDBOX_FOLDER_EMPTY,discoverSandboxSource};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ClientSession } from "#client/session.js";
|
|
2
|
-
import type { CancelSessionResult, ClientSessionState, SendTurnInput, SendTurnOptions } from "#client/types.js";
|
|
3
|
-
import type { MessageStreamEvent, RuntimeTraceContext, TurnFailureStreamEvent } from "#protocol/message.js";
|
|
2
|
+
import type { CancelSessionResult, ClientSessionState, SendTurnInput, SendTurnOptions, StreamOptions } from "#client/types.js";
|
|
3
|
+
import type { MessageStreamEvent, RuntimeTraceContext, SubagentCalledStreamEvent, TurnFailureStreamEvent } from "#protocol/message.js";
|
|
4
4
|
import type { InputRequest, InputResponse } from "#shared/input.js";
|
|
5
5
|
import { AssertionCollector } from "#evals/assertions/collector.js";
|
|
6
6
|
import type { EveEvalAssertions, EveEvalLiveTurn, EveEvalOutputAssertions, EveEvalSession, EveEvalSessionResult, EveEvalTurn } from "#evals/types.js";
|
|
@@ -39,6 +39,7 @@ export declare class EvalSessionDriver implements EveEvalSession {
|
|
|
39
39
|
get sessionId(): string;
|
|
40
40
|
get state(): ClientSessionState;
|
|
41
41
|
cancel(): Promise<CancelSessionResult>;
|
|
42
|
+
streamSubagent(called: SubagentCalledStreamEvent, options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
42
43
|
/** @internal */
|
|
43
44
|
cleanup(signal: AbortSignal): Promise<void>;
|
|
44
45
|
requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{basename}from"node:path";import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o;#s;#c=[];#l=new Set;#u;#d=!1;#f=[];constructor(e){this.#i=e.collector,this.#s=e.onSessionStart,this.#o=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#u}get pendingInputRequests(){return this.#f}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#f.length===0&&this.#v(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#f.filter(t=>inputRequestMatches(t,e));return(this.#f.length!==1||t.length!==1)&&this.#v(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#f.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#p({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#p({...t,inputResponses:e})}async respondAll(e){let t=this.#f;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#p({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#p({turnPolicy:`queue`,...t,message:e})}async#p(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.consume(i,n)}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#m(n,e),record:e=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
1
|
+
import{readFile}from"node:fs/promises";import{basename}from"node:path";import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{summarizeTurnEvents}from"#client/session-utils.js";import{createTextWithFileContent}from"#client/file-parts.js";import{extractCompletedResult}from"#client/output-schema.js";import{inputRequestMatches,matchesValue,toolCallMatches}from"#evals/match.js";import"#evals/assertions/collector.js";import{createOutputAssertions,createScopedAssertions}from"#evals/assertions/scoped.js";import{EvalRequirementFailed}from"#evals/control-flow.js";import{deriveRunFacts}from"#evals/runner/derive-run-facts.js";import{formatEvalTranscript,inferMediaType}from"#evals/session-content.js";var EveEvalTurnFailedError=class extends Error{event;turn;constructor(e){let t=e.events.find(isTurnFailureEvent),n=t===void 0?`turn ended with status "${e.status}"`:`${t.type}: ${t.data.code} ${t.data.message}`.trim();super(`Eval turn failed: ${n}`),this.name=`EveEvalTurnFailedError`,this.event=t,this.turn=e}},EvalSessionDriver=class{#e;#t;#n=``;#r;#i;#a=[];#o;#s;#c=[];#l=new Set;#u;#d=!1;#f=[];constructor(e){this.#i=e.collector,this.#s=e.onSessionStart,this.#o=e.primary,this.#e=e.session,this.#t=e.onTurn,this.#r=e.signal,Object.assign(this,createScopedAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}),createOutputAssertions(this.#i,{timing:`snapshot`,select:()=>this.#_()}))}get events(){return this.#a}get transcript(){return formatEvalTranscript(this.#a)}get lastInput(){return this.#n}get lastTurn(){return this.#u}get pendingInputRequests(){return this.#f}get sessionId(){return this.#e.state.sessionId}get state(){return this.#e.state}async cancel(){return await this.#e.cancel()}streamSubagent(e,t={}){return this.#e.streamSubagent(e,{...t,signal:t.signal??this.#r})}async cleanup(e){await this.#e.reset({reason:`Eval timed out`,signal:e})}requireInputRequest(e={}){this.#f.length===0&&this.#v(`requireInputRequest`,`expected one pending input request, but the last turn did not park`);let t=this.#f.filter(t=>inputRequestMatches(t,e));return(this.#f.length!==1||t.length!==1)&&this.#v(`requireInputRequest`,`expected exactly one pending input request matching ${formatInputRequestFilter(e)}, found ${t.length} match(es) across ${this.#f.length} pending request(s)`),this.#i.recordOutcome({name:`requireInputRequest`,outcome:{score:1}}),t[0]}async respond(e,t={}){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await(await this.#p({...t,inputResponses:e})).result()}async startRespond(e,t={}){if(e.length===0)throw Error(`startRespond() requires input responses.`);return await this.#p({...t,inputResponses:e})}async respondAll(e){let t=this.#f;if(t.length===0)throw Error(`respondAll() requires at least one pending input request.`);for(let n of t)assertRequestHasOption(n,e);return await this.respond(t.map(t=>({optionId:e,requestId:t.requestId})))}async send(e,t={}){return await(await this.#p({turnPolicy:`queue`,...t,message:e})).result()}async start(e,t={}){return await this.#p({turnPolicy:`queue`,...t,message:e})}async#p(e){let{inputResponses:t,message:n,...r}=attachSignal(e,this.#r),i=t===void 0?await this.#e.send(n,r):await this.#e.respond(t,r);return this.consume(i,n)}consume(e,t){let n=this.sessionId;return new EvalLiveTurn({events:e,observe:e=>this.#m(n,e),record:e=>(t!==void 0&&(this.#n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
2
|
`)),this.#g(n,e)),session:this,sessionId:n})}async sendFile(e,t,n){let r=await readFile(t),i=createTextWithFileContent({bytes:r,filename:basename(t),mediaType:n??inferMediaType(t),text:e});return await this.send(i)}async readTurn(e){return await this.watchTurn(e).result()}watchTurn(e){return this.consume(this.#e.stream({signal:this.#r,startIndex:e?.startIndex}))}snapshot(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],primary:this.#o,sessionId:e,state:this.#e.state,traceContexts:[...this.#c]}}#m(e,t){if(t.type!==`session.started`&&t.type!==`turn.started`)return;let n=t.data.trace;if(n===void 0)return;let r=`${n.traceId}:${n.spanId}`;this.#l.has(r)||(this.#l.add(r),this.#c.push(n),!this.#d&&(this.#d=!0,this.#s?.({primary:this.#o,sessionId:e,startedAt:t.meta.at,traceContext:n})))}#h(e){this.#a.push(...e.events),this.#f=e.status===`waiting`?e.inputRequests:[];let t=deriveRunFacts(e.events,{sessionId:e.sessionId}),n=new EvalTurn({collector:this.#i,data:e.data,derived:t,events:e.events,inputRequests:e.inputRequests,message:e.message,session:this,sessionId:e.sessionId,status:e.status,toolCalls:t.toolCalls});return this.#u=n,this.#t(this),n}#g(e,t){let n=summarizeTurnEvents(t);return this.#h({data:extractCompletedResult(t),events:t,inputRequests:n.inputRequests,message:n.message,sessionId:e,status:n.status})}#_(){let e=this.sessionId;return{derived:deriveRunFacts(this.#a,{sessionId:e}),events:[...this.#a],output:outputOf(this.#u),status:this.#u?.status??`completed`}}#v(e,t){throw this.#i.recordOutcome({name:e,outcome:{score:0,message:t}}),new EvalRequirementFailed}},EvalLiveTurn=class{session;sessionId;#e;#t=[];#n=new Set;#r;constructor(e){this.session=e.session,this.sessionId=e.sessionId,this.#e=this.#i(e.events,e.observe,e.record),this.#e.catch(()=>{})}get events(){return this.#t}async cancel(){return await this.session.cancel()}async result(){return await this.#e}async waitForEvent(e,t){let matches=n=>n.type===e&&(t?.data===void 0||matchesValue(t.data,`data`in n?n.data:void 0)),n=this.#t.find(matches);if(n!==void 0)return n;if(this.#r!==void 0)throw this.#r;return await new Promise((e,t)=>{let n={matches,reject:t,resolve:t=>e(t)};this.#n.add(n)})}async#i(e,t,n){try{let r=!1;for await(let n of e)if(this.#t.push(n),t(n),this.#a(n),isTurnFailureEvent(n)&&this.#o(Error(`Session ${this.sessionId} failed before the expected event (${n.type}).`)),isCurrentTurnBoundaryEvent(n)){r=!0,this.#o(Error(`Session ${this.sessionId} reached ${n.type} before the expected event.`));break}if(!r)throw Error(`Stream for session "${this.sessionId}" closed before a turn boundary.`);return n(this.#t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw this.#o(t),e}}#a(e){for(let t of this.#n)t.matches(e)&&(this.#n.delete(t),t.resolve(e))}#o(e){if(this.#r===void 0){this.#r=e;for(let t of this.#n)t.reject(e);this.#n.clear()}}},EvalTurn=class{data;events;inputRequests;message;session;sessionId;status;toolCalls;#e;#t;constructor(e){this.data=e.data,this.events=e.events,this.inputRequests=e.inputRequests,this.message=e.message,this.sessionId=e.sessionId,this.session=e.session,this.status=e.status,this.toolCalls=e.toolCalls,this.#e=e.collector,this.#t=e.derived,Object.assign(this,createScopedAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}),createOutputAssertions(e.collector,{timing:`snapshot`,select:()=>this.#n()}))}expectOk(){if(this.status!==`failed`)return this;throw new EveEvalTurnFailedError(this)}requireToolCall(e,t={}){let n=this.toolCalls.filter(n=>n.name===e&&toolCallMatches(n,t));return n.length!==1&&inputRequirementFailed(this.#e,`requireToolCall`,`expected exactly one matching "${e}" tool call in this turn, found ${n.length}; observed [${this.toolCalls.map(e=>e.name).join(`, `)}]`),this.#e.recordOutcome({name:`requireToolCall`,outcome:{score:1}}),n[0]}#n(){return{derived:this.#t,events:this.events,output:outputOf(this),status:this.status}}};function attachSignal(e,t){return t===void 0?e:e.signal===void 0?{...e,signal:t}:e}function formatInputRequestFilter(e){return JSON.stringify(e)}function inputRequirementFailed(e,t,n){throw e.recordOutcome({name:t,outcome:{score:0,message:n}}),new EvalRequirementFailed}function outputOf(e){return e===void 0?null:e.data===void 0?e.message??null:e.data}function assertRequestHasOption(e,t){if(e.options===void 0||e.options.length===0)throw Error(`Input request "${e.requestId}" has no selectable options.`);if(!e.options.some(e=>e.id===t))throw Error(`Input request "${e.requestId}" does not offer option "${t}".`)}export{EvalSessionDriver,EveEvalTurnFailedError};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Experimental_EvaluationModel as EvaluationModel } from "ai";
|
|
2
2
|
import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
|
|
3
|
-
import type { RuntimeIdentity, RuntimeTraceContext, MessageStreamEvent } from "#protocol/message.js";
|
|
4
|
-
import type { CancelSessionResult, ClientSessionState, CreateSessionOptions, SendTurnInput, SendTurnOptions } from "#client/types.js";
|
|
3
|
+
import type { RuntimeIdentity, RuntimeTraceContext, MessageStreamEvent, SubagentCalledStreamEvent } from "#protocol/message.js";
|
|
4
|
+
import type { CancelSessionResult, ClientSessionState, CreateSessionOptions, SendTurnInput, SendTurnOptions, StreamOptions } from "#client/types.js";
|
|
5
5
|
import type { InputRequest, InputResponse } from "#shared/input.js";
|
|
6
6
|
import type { JsonObject, JsonValue } from "#shared/json.js";
|
|
7
7
|
import type { TaskStatus } from "#tasks/types.js";
|
|
@@ -274,6 +274,12 @@ export interface EveEvalSessionDriver {
|
|
|
274
274
|
start(message: string, options?: SendTurnOptions): Promise<EveEvalLiveTurn>;
|
|
275
275
|
/** Send one text turn with a local file attached as a data URL. */
|
|
276
276
|
sendFile(text: string, filePath: string, mediaType?: string): Promise<EveEvalTurn>;
|
|
277
|
+
/**
|
|
278
|
+
* Follow one delegated child's stream through this parent session, with the
|
|
279
|
+
* eval client's credentials. Local children use their own stream route; remote
|
|
280
|
+
* children use the parent-origin proxy.
|
|
281
|
+
*/
|
|
282
|
+
streamSubagent(called: SubagentCalledStreamEvent, options?: StreamOptions): AsyncIterable<MessageStreamEvent>;
|
|
277
283
|
}
|
|
278
284
|
/** One accepted session, exposed by `t.session()`, turns, and target attachment helpers. */
|
|
279
285
|
export interface EveEvalSession extends EveEvalSessionDriver, EveEvalAssertions, EveEvalOutputAssertions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_ACTIVITY_ROUTE_PATTERN,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,EVE_TASK_INPUT_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleActivityRequest}from"#execution/activity-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{handleTaskInputResponseRequest}from"#execution/task-input-response-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteSubagentBinding,healthResponse,normalizeEveCors,resolveOnMessage}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN,handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(EVE_TASK_INPUT_ROUTE_PATTERN,handleTaskInputResponseRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=await parseOptionalJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(i)}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let h=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),g=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof h==`object`?h:h===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,_=f;g!==void 0&&f!==void 0&&(_={...f,forwardedTracePolicy:g}),h===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof h==`object`&&(g===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:h.originAudience,ceiling:formatTraceContentCeiling(h.ceiling),forwarder:i.principalId}));let v=c.message===void 0?{auth:s.auth}:await resolveOnMessage({auth:s.auth,config:e,message:c.message,request:n});if(v instanceof Response)return v;let y=readRouteSessionCreator(r);if(y===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let b;try{b=await y({taskDeliveryPolicy:c.taskDeliveryPolicy,activityObserver:c.activityObserver,audienceAuth:i,auth:v.auth,capabilities:c.capabilities??(c.mode===`task`?void 0:{requestInput:!0}),callback:c.callback,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:v.context,outputSchema:c.outputSchema},c.context),mode:c.mode??`conversation`,conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:u,parentTraceContext:_,title:v.title})}catch(e){let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:b.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:b.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f,p=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.title,p=t.auth}let m;try{let e=r(o),t=attachClientContext({taskDeliveryPolicy:l.taskDeliveryPolicy,activityObserver:l.activityObserver,auth:p,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:f},l.context);m=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,ok:!1},{status:500})}return m.status===`accepted`?Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`,deliveryId:m.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202}):Response.json({code:m.retryable?`session_not_ready`:`session_not_active`,error:m.retryable===!0?`The session is not ready to accept messages yet.`:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({taskId:o.taskId,tasks:o.tasks,turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
|
|
1
|
+
import{EVE_ACTIVITY_ROUTE_PATTERN,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_ROUTE_PREFIX,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,EVE_TASK_INPUT_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{handleExpiredLegacyAuthorization}from"#execution/legacy-session/authorization.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleActivityRequest}from"#execution/activity-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{handleTaskInputResponseRequest}from"#execution/task-input-response-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{routeAuth}from"#public/channels/auth.js";import{defaultEveAudience}from"#eve-channel/audience.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseOptionalJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteSubagentBinding,healthResponse,normalizeEveCors,resolveOnMessage}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,audience:t=>{let n=e.audience??defaultEveAudience;return typeof n==`function`?n(t):n},routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),POST(`${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`,handleExpiredLegacyAuthorization),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN,handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(EVE_TASK_INPUT_ROUTE_PATTERN,handleTaskInputResponseRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=await parseOptionalJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(i,{})}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let h=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),g=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof h==`object`?h:h===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,_=f;g!==void 0&&f!==void 0&&(_={...f,forwardedTracePolicy:g}),h===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof h==`object`&&(g===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:h.originAudience,ceiling:formatTraceContentCeiling(h.ceiling),forwarder:i.principalId}));let v=c.message===void 0?{auth:s.auth}:await resolveOnMessage({auth:s.auth,config:e,message:c.message,request:n});if(v instanceof Response)return v;let y=readRouteSessionCreator(r);if(y===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let b;try{b=await y({taskDeliveryPolicy:c.taskDeliveryPolicy,activityObserver:c.activityObserver,audienceAuth:i,auth:v.auth,capabilities:c.capabilities??(c.mode===`task`?void 0:{requestInput:!0}),callback:c.callback,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:v.context,outputSchema:c.outputSchema},c.context),mode:c.mode??`conversation`,conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:u,parentTraceContext:_,title:v.title})}catch(e){let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:b.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:b.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f,p=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.title,p=t.auth}let m;try{let e=r(o),t=attachClientContext({taskDeliveryPolicy:l.taskDeliveryPolicy,activityObserver:l.activityObserver,auth:p,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy,title:f},l.context);m=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,ok:!1},{status:500})}return m.status===`accepted`?Response.json({ok:!0,sessionId:m.sessionId,status:`accepted`,deliveryId:m.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:m.sessionId},status:202}):Response.json({code:m.retryable?`session_not_ready`:`session_not_active`,error:m.retryable===!0?`The session is not ready to accept messages yet.`:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({taskId:o.taskId,tasks:o.tasks,turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s));let m=new URL(t.url).searchParams.get(EVE_STREAM_CONTROL_VERSION_QUERY);m!==null&&p.searchParams.set(EVE_STREAM_CONTROL_VERSION_QUERY,m),c&&p.searchParams.set(`includeTailIndex`,`1`);let h=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),g=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=h.headers.get(e);t!==null&&g.set(e,t)}return new Response(h.body,{headers:g,status:h.status,statusText:h.statusText})})],events:e.events})}export{eveChannel};
|
|
@@ -5,6 +5,7 @@ import type { AuthFn } from "#public/channels/auth.js";
|
|
|
5
5
|
import type { UploadPolicyInput } from "#public/channels/upload-policy.js";
|
|
6
6
|
import type { AudienceContext, Channel, ChannelContinuationOps, ChannelEvents, ChannelMethod } from "#public/definitions/channel.js";
|
|
7
7
|
import type { ChannelAudience } from "#shared/channel-audience.js";
|
|
8
|
+
export type { ForwardedAssertion, TrustedForwarders } from "#channel/forwarded-principal.js";
|
|
8
9
|
/**
|
|
9
10
|
* Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
|
|
10
11
|
* has no platform-specific state, so handlers receive optional continuation routing here and the
|
|
@@ -93,12 +94,19 @@ export interface EveChannelInput {
|
|
|
93
94
|
* The trusted-forwarders policy: which transport-authenticated callers may
|
|
94
95
|
* assert a forwarded principal, callback-marked public trace audience, or
|
|
95
96
|
* remote parent lineage. The predicate receives the *verified* route-auth
|
|
96
|
-
* principal of the forwarder
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* permissive predicate lets any authenticated forwarder assert any principal,
|
|
97
|
+
* principal of the forwarder and must match it precisely (for example
|
|
98
|
+
* `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).
|
|
99
|
+
* A permissive predicate lets any authenticated forwarder assert any principal,
|
|
100
100
|
* public trace audience, or remote lineage.
|
|
101
101
|
*
|
|
102
|
+
* The second argument carries what the forwarder asserts. `assertion.principal`
|
|
103
|
+
* holds the stamped `current` and `initiator` contexts the forwarder asserts,
|
|
104
|
+
* so a receiver can limit a forwarder to the identities it may speak for, such as
|
|
105
|
+
* one authenticator and issuer. `initiator` takes effect only on session
|
|
106
|
+
* creation; on continuation it is the asserted value, not the session's pinned
|
|
107
|
+
* initiator. `assertion.principal` is absent when the predicate decides remote
|
|
108
|
+
* parent lineage for a request that forwards no principal.
|
|
109
|
+
*
|
|
102
110
|
* When a trusted forwarder's assertion is accepted on session creation, the
|
|
103
111
|
* forwarded principal replaces `session.auth.current` and
|
|
104
112
|
* `session.auth.initiator`. On continuation, only `session.auth.current`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{recordTerminalTaskViewsStep}from"#execution/tasks/parent/hitl-proxy-steps.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{hydrateDurableSession}from"#execution/session.js";import{cancelOwnedTask}from"#execution/tasks/parent/dispatch.js";import{cancelBackgroundAgentTask}from"#execution/tools/subagent/task-cancel.js";const log=createLogger(`execution.cancel-indexed-session-tasks`);async function cancelAllIndexedSessionTasksStep(e){"use step";let t;try{t=readDurableSession(e.sessionState)}catch(t){return logError(log,`failed to read the session for indexed task cancellation`,t,{parentSessionId:e.sessionState.sessionId}),{sessionState:e.sessionState}}let n,r;try{n=getBackgroundTasks(t.state),r=n.query({state:`working`})}catch(n){return logError(log,`failed to read the task index`,n,{parentSessionId:t.sessionId}),{sessionState:e.sessionState}}let i=[];try{i=n.query({state:`cancelled`})}catch(e){logError(log,`failed to read cancelled task outcomes`,e,{parentSessionId:t.sessionId})}let a=[...r,...i].map(e=>e.run);if(a.length===0)return{sessionState:e.sessionState};if(e.serializedContext===void 0)throw Error(`Indexed task cancellation requires serialized runtime context.`);let o=await deserializeContext(e.serializedContext),s=o.require(BundleKey),c=resolveEffectiveAgentRuntime(s,o),l=hydrateDurableSession({durable:t,turnAgent:c.turnAgent}),u=[];for(let n of a)try{let t=await cancelOwnedTask({cancelOwnedWork:cancelBackgroundAgentTask,entry:n,serializedContext:e.serializedContext,session:l});u.push(t)}catch(e){logError(log,`failed to cancel indexed task`,e,{parentSessionId:t.sessionId,taskId:n.task.taskId})}return await recordTerminalTaskViewsStep({serializedContext:e.serializedContext,sessionState:e.sessionState,views:u})}export{cancelAllIndexedSessionTasksStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.66.
|
|
1
|
+
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function executeWorkflowProgram(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}executeWorkflowProgram.workflowId=`workflow//eve@0.66.2//executeWorkflowProgram`;export{executeWorkflowProgram};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputResolvedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{getPendingCoordinationBatch}from"#harness/coordination.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{createInputResolvedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{getPendingCoordinationBatch}from"#harness/coordination.js";import{readDurableSession,replaceDurableSessionSnapshot}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{resumeSessionInbox}from"#execution/session-inbox/resume.js";import{createTaskInputRequestId,retireProxyInputRequests}from"#harness/proxy-input-requests.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{routeDeliverPayload}from"#subagents/hitl-proxy.js";import{sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{resumeWorkflowToolRunAnswers,resumeWorkflowToolRunDismissal}from"#execution/tools/workflow/answer.js";async function routeProxiedDeliverStep(e){"use step";let t=readDurableSession(e.sessionState),n=e.delivery,r=new Map,i=new Map,a,o=n.caller===void 0&&n.taskDeliveryId===void 0,s=new Set;for(let[e,c]of n.payloads.entries()){let l=routeDeliverPayload({allowRoute:(e,n)=>!s.has(e)&&(n.taskId===void 0||getBackgroundTasks(t.state).get(n.taskId)!==void 0),payload:c,resolveMessage:o,state:t.state});a??=l.parentAction,l.forSelf!==void 0&&r.set(e,l.forSelf);for(let[t,r]of l.forChildren.entries()){if(r.answerHook!==void 0)for(let e of r.retireRequestIds)s.add(e);let a=[r.childContinuationToken,r.childSessionInbox?.sessionId??``,r.childResponseUrl??``,r.taskId??``].join(`\0`),o=i.get(a)??{answerHook:r.answerHook,childContinuationToken:r.childContinuationToken,childSessionInbox:r.childSessionInbox,childResponseUrl:r.childResponseUrl,dismissedRequestIds:[],metadata:[],payloads:[],retireRequestIds:[],sourcePayloadIndexes:[],taskId:r.taskId},c=o.payloads.length;if(o.payloads.push(r.payload),o.dismissedRequestIds.push(...r.dismissedRequestIds??[]),o.retireRequestIds.push(...r.retireRequestIds),o.sourcePayloadIndexes.push(e),l.forSelf===void 0&&t===0)for(let t of n.deliveryMetadata??[])t.payloadIndex===e&&o.metadata.push({...t,payloadIndex:c});i.set(a,o)}}let c=!1;for(let a of i.values()){let i=a.taskId;if(i!==void 0){let e=getBackgroundTasks(t.state).get(i)?.run;if(e===void 0){mergeStrandedResponses(r,a,i);continue}if(await sendTaskInboundPayload({taskInboxToken:e.address.hookToken,payload:{auth:n.auth,childContinuationToken:a.childContinuationToken,childSessionInbox:a.childSessionInbox,childResponseUrl:a.childResponseUrl,inputResponses:coalesceDeliverPayloads(a.payloads).inputResponses??[],kind:`input-response`,taskId:i}})===`unreachable`){mergeStrandedResponses(r,a,i);continue}t=retireProxyInputRequests(t,a.retireRequestIds),c=!0;continue}if(a.answerHook!==void 0){let n=coalesceDeliverPayloads(a.payloads).inputResponses??[];await resumeWorkflowToolRunAnswers(a.childContinuationToken,n),a.dismissedRequestIds.length>0&&await resumeWorkflowToolRunDismissal(a.childContinuationToken),a.answerHook.question!==void 0&&await emitQuestionResolutions({dismissedRequestIds:a.dismissedRequestIds,responses:n,sessionState:t.state,sessionWritable:e.sessionWritable}),t=retireProxyInputRequests(t,a.retireRequestIds),c=!0;continue}let o={...n,deliveryMetadata:a.metadata.length===0?void 0:a.metadata,payloads:a.payloads};await resumeSessionInbox(a.childSessionInbox??a.childContinuationToken,o),t=retireProxyInputRequests(t,a.retireRequestIds),c=!0}let l={serializedContext:e.serializedContext??{},sessionState:c?replaceDurableSessionSnapshot({session:t,state:e.sessionState}):e.sessionState};if(a!==void 0)return{...l,...a};let u=[...r].sort(([e],[t])=>e-t),d=u.flatMap(([e],t)=>(n.deliveryMetadata??[]).filter(t=>t.payloadIndex===e).map(e=>({...e,payloadIndex:t}))),f=u.length===0?void 0:{...n,deliveryMetadata:d.length===0?void 0:d,payloads:u.map(([,e])=>e)};return{...l,kind:`continue`,remainder:f}}async function emitQuestionResolutions(e){let t=getPendingCoordinationBatch(e.sessionState)?.event;if(t===void 0)return;let n=[...e.responses.map(e=>({kind:`question`,outcome:`answered`,requestId:e.requestId,response:e})),...e.dismissedRequestIds.map(e=>({kind:`question`,outcome:`ignored`,requestId:e}))];if(n.length===0)return;let r=e.sessionWritable.getWriter();try{await r.write(encodeMessageStreamEvent(stampMessageStreamEvent(createInputResolvedEvent({resolutions:n,...t}))))}finally{r.releaseLock()}}function mergeStrandedResponses(e,t,n){for(let[r,i]of t.payloads.entries()){let a=t.sourcePayloadIndexes[r];if(a===void 0)continue;let o=(i.inputResponses??[]).map(e=>({...e,requestId:createTaskInputRequestId(n,e.requestId)}));if(o.length===0)continue;let s=e.get(a);e.set(a,{...s,inputResponses:[...s?.inputResponses??[],...o]})}}export{routeProxiedDeliverStep};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{recordTaskInputRequestStep,recordTerminalTaskViewsStep}from"#execution/tasks/parent/hitl-proxy-steps.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{emitSubagentEventStep}from"#execution/tools/subagent/emit-event-step.js";import{formatTaskNotification}from"#tasks/notification.js";import{routeProxiedDeliverStep}from"#execution/proxied-deliver-step.js";import{emitRecordedTaskInputRequestStep,runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{acceptTaskAuthorizationEventStep}from"#execution/tools/subagent/accept-event-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";async function routeDeliverToChildren(e){let t=coalesceDeliverPayloads(e.delivery.payloads),n=e.serializedContext,r=e.sessionState,i=new Map,a=new Set((t.task?.views??[]).map(e=>e.taskId));for(let i of t.task?.inputRequests??[]){if(a.has(i.taskId))continue;let t=await recordTaskInputRequestStep({request:i,sessionState:r});if(r=t.sessionState,!t.accepted)continue;let o=await emitRecordedTaskInputRequestStep({sessionWritable:e.sessionWritable,request:t.request,serializedContext:n,sessionState:r});n=o.serializedContext,r=o.sessionState}for(let i of t.task?.agentRequests??[]){if(i.request.kind===`agent-invoke`&&a.has(i.taskId))continue;let t=await applyTaskAgentRequest({...i,ownerId:i.taskId},{sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}for(let i of t.task?.authorizationEvents??[]){if(i.hookPayload.event.type===`authorization.required`&&a.has(i.taskId)||!await acceptTaskAuthorizationEventStep({delivery:i,sessionState:r}))continue;let t=await runProxySubagentEventStep({hookPayload:i.hookPayload,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}if((t.task?.views?.length??0)>0){let a=await recordTerminalTaskViewsStep({serializedContext:n,sessionState:r,views:t.task?.views??[]});n=a.serializedContext,r=a.sessionState;for(let e of a.views)i.set(e.taskId,e);for(let t of a.subagentCompletions){let i=await emitSubagentEventStep({event:t,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=i.serializedContext,r=i.sessionState}}let o=[],
|
|
1
|
+
import{recordTaskInputRequestStep,recordTerminalTaskViewsStep}from"#execution/tasks/parent/hitl-proxy-steps.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{emitSubagentEventStep}from"#execution/tools/subagent/emit-event-step.js";import{formatTaskNotification,hasRecordedTaskOutcome}from"#tasks/notification.js";import{routeProxiedDeliverStep}from"#execution/proxied-deliver-step.js";import{emitRecordedTaskInputRequestStep,runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{acceptTaskAuthorizationEventStep}from"#execution/tools/subagent/accept-event-step.js";import{applyTaskAgentRequest}from"#execution/tools/subagent/task-agent-requests.js";async function routeDeliverToChildren(e){let t=coalesceDeliverPayloads(e.delivery.payloads),n=e.serializedContext,r=e.sessionState,i=new Map,a=new Set((t.task?.views??[]).map(e=>e.taskId));for(let i of t.task?.inputRequests??[]){if(a.has(i.taskId))continue;let t=await recordTaskInputRequestStep({request:i,sessionState:r});if(r=t.sessionState,!t.accepted)continue;let o=await emitRecordedTaskInputRequestStep({sessionWritable:e.sessionWritable,request:t.request,serializedContext:n,sessionState:r});n=o.serializedContext,r=o.sessionState}for(let i of t.task?.agentRequests??[]){if(i.request.kind===`agent-invoke`&&a.has(i.taskId))continue;let t=await applyTaskAgentRequest({...i,ownerId:i.taskId},{sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}for(let i of t.task?.authorizationEvents??[]){if(i.hookPayload.event.type===`authorization.required`&&a.has(i.taskId)||!await acceptTaskAuthorizationEventStep({delivery:i,sessionState:r}))continue;let t=await runProxySubagentEventStep({hookPayload:i.hookPayload,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=t.serializedContext,r=t.sessionState}if((t.task?.views?.length??0)>0){let a=await recordTerminalTaskViewsStep({serializedContext:n,sessionState:r,views:t.task?.views??[]});n=a.serializedContext,r=a.sessionState;for(let e of a.views)i.set(e.taskId,e);for(let t of a.subagentCompletions){let i=await emitSubagentEventStep({event:t,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r});n=i.serializedContext,r=i.sessionState}}let o=e.sessionState.snapshot.session.state;if(t.task!==void 0&&hasRecordedTaskOutcome(e.delivery,o))return{kind:`continue`,remainder:void 0,serializedContext:n,sessionState:r};let s=[],c=[];for(let[t,n]of e.delivery.payloads.entries()){let r={...n};if(delete r.task,r.message!==void 0&&n.task?.views!==void 0){let e=n.task.views.flatMap(({taskId:e})=>{let t=i.get(e);return t===void 0?[]:[formatTaskNotification(t)]});e.length===0?delete r.message:r.message=e.join(`
|
|
2
2
|
|
|
3
|
-
`)}if(Object.keys(r).length===0)continue;let a=
|
|
3
|
+
`)}if(Object.keys(r).length===0)continue;let a=s.length;s.push(r);for(let n of e.delivery.deliveryMetadata??[])n.payloadIndex===t&&c.push({...n,payloadIndex:a})}let l=s.length===0?void 0:{...e.delivery,deliveryMetadata:c.length===0?void 0:c,payloads:s};return l===void 0?{kind:`continue`,remainder:void 0,serializedContext:n,sessionState:r}:r.hasProxyInputRequests?await routeProxiedDeliverStep({delivery:l,sessionWritable:e.sessionWritable,serializedContext:n,sessionState:r}):{kind:`continue`,remainder:l,serializedContext:n,sessionState:r}}export{routeDeliverToChildren};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{isWorkflowMessage}from"#execution/session-inbox/inbox.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{cancelAllIndexedSessionTasksStep}from"#execution/cancel-indexed-session-tasks-step.js";import{SessionInboxPayloadError,decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{reportDroppedWirePayloadStep}from"#execution/report-dropped-wire-payload-step.js";import{findRunningAgentHandle}from"#subagents/handles/query.js";async function admitSessionInboxPayload(e,t){if(e.kind===`runtime-action-result`)return{kind:`runtime-action-result`,payload:e};if(isWorkflowMessage(e))return{kind:`workflow`,message:e};if(e.kind===`authorization-callback`)return t.queue.enqueueAuthorization(e.payloads),{kind:`consumed`};if(e.kind===`subagent-input-request`||e.kind===`subagent-authorization-event`){let n=findRunningAgentHandle(t.cursor.sessionState.snapshot.session.state,{callId:e.callId});return n?.identity.name===e.subagentName&&n.address.sessionId===e.childSessionId&&await t.cursor.apply(await runProxySubagentEventStep({hookPayload:e,sessionWritable:t.cursor.sessionWritable,serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState})),{kind:`consumed`}}let n;try{n=decodeSessionInboxPayload(e)}catch(e){if(!(e instanceof SessionInboxPayloadError))throw e;return await reportDroppedWirePayloadStep({detail:e.message,family:`session-inbox`}),{kind:`consumed`}}switch(n.kind){case`deliver`:{let e=t.queue.enqueueDelivery(n);return e===void 0?{kind:`consumed`}:{admission:e,kind:`delivery`}}case`clear`:case`compact`:return t.queue.enqueueControl(n.kind),{kind:`consumed`};case`session-timeout`:return n.ownerRunId===getWorkflowMetadata().workflowRunId&&t.queue.enqueueControl(`expired`),{kind:`consumed`};case`reset`:return t.queue.enqueueControl(`reset`),{command:{kind:`cancel`},kind:`cancel`};case`cancel`:return{command:n,kind:`cancel`}}}async function applySessionCancellation(e,t){if(e.tasks===!0){let e=await cancelAllIndexedSessionTasksStep({serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState});await t.cursor.apply(e)}e.taskId!==void 0&&t.queue.cancelTask(e.taskId)}export{admitSessionInboxPayload,applySessionCancellation};
|
|
1
|
+
import{getWorkflowMetadata}from"#compiled/@workflow/core/index.js";import{isWorkflowMessage}from"#execution/session-inbox/inbox.js";import{runProxySubagentEventStep}from"#subagents/event-proxy-step.js";import{cancelAllIndexedSessionTasksStep}from"#execution/cancel-indexed-session-tasks-step.js";import{SessionInboxPayloadError,decodeSessionInboxPayload}from"#execution/session-inbox/protocol.js";import{reportDroppedWirePayloadStep}from"#execution/report-dropped-wire-payload-step.js";import{findRunningAgentHandle}from"#subagents/handles/query.js";async function admitSessionInboxPayload(e,t){if(e.kind===`runtime-action-result`)return{kind:`runtime-action-result`,payload:e};if(isWorkflowMessage(e))return{kind:`workflow`,message:e};if(e.kind===`authorization-callback`)return t.queue.enqueueAuthorization(e.payloads),{kind:`consumed`};if(e.kind===`subagent-input-request`||e.kind===`subagent-authorization-event`){let n=findRunningAgentHandle(t.cursor.sessionState.snapshot.session.state,{callId:e.callId});return n?.identity.name===e.subagentName&&n.address.sessionId===e.childSessionId&&await t.cursor.apply(await runProxySubagentEventStep({hookPayload:e,sessionWritable:t.cursor.sessionWritable,serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState})),{kind:`consumed`}}let n;try{n=decodeSessionInboxPayload(e)}catch(e){if(!(e instanceof SessionInboxPayloadError))throw e;return await reportDroppedWirePayloadStep({detail:e.message,family:`session-inbox`}),{kind:`consumed`}}switch(n.kind){case`deliver`:{let e=t.queue.enqueueDelivery(n,t.cursor.sessionState.snapshot.session.state);return e===void 0?{kind:`consumed`}:{admission:e,kind:`delivery`}}case`clear`:case`compact`:return t.queue.enqueueControl(n.kind),{kind:`consumed`};case`session-timeout`:return n.ownerRunId===getWorkflowMetadata().workflowRunId&&t.queue.enqueueControl(`expired`),{kind:`consumed`};case`reset`:return t.queue.enqueueControl(`reset`),{command:{kind:`cancel`},kind:`cancel`};case`cancel`:return{command:n,kind:`cancel`}}}async function applySessionCancellation(e,t){if(e.tasks===!0){let e=await cancelAllIndexedSessionTasksStep({serializedContext:t.cursor.serializedContext,sessionState:t.cursor.sessionState});await t.cursor.apply(e),t.queue.discardStaleNotifications(t.cursor.sessionState.snapshot.session.state)}e.taskId!==void 0&&t.queue.cancelTask(e.taskId)}export{admitSessionInboxPayload,applySessionCancellation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyDelegatedParentStep,notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#subagents/callback-step.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#subagents/parent-result.js";async function finalizeSession(e,t){let{serializedContext:n,sessionState:r}=t.cursor;r!==void 0&&await terminateChildSessionsStep({serializedContext:n,sessionState:r}),e.kind===`expired`?await emitTerminalSessionCompletionStep({sessionWritable:t.sessionWritable,serializedContext:n}):e.kind===`failed`&&await emitTerminalSessionFailureStep({error:normalizeSerializableError(e.error),sessionWritable:t.sessionWritable,serializedContext:n,turnId:e.turnId});let i=settledResult(e);if(t.mode===`task`)await fireSessionCallbackStep({error:i.isError?i.output:void 0,output:i.isError?void 0:i.output,serializedContext:n,status:i.isError?`failed`:`completed`,usage:i.sessionUsage}),await notifyDelegatedParentStep({result:i.isError?createDelegatedSubagentErrorResult(n,i.output):createDelegatedSubagentSuccessResult(n,i.output),serializedContext:n,usage:i.sessionUsage});else if(t.caller!==void 0){let e={output:i.output,usage:i.turnUsage};i.isError&&(e.isError=!0),await notifyTurnCallerStep({caller:t.caller,lifecycle:`terminal`,sessionId:r?.sessionId??n[`eve.sessionId`],settled:e})}return e.kind===`done`?{isError:e.action.isError,output:e.action.output,usage:e.action.usage,usageDelta:e.action.usageDelta}:{isError:i.isError,output:i.output}}function settledResult(e){switch(e.kind){case`done`:return{isError:e.action.isError===!0,output:e.action.output,sessionUsage:e.action.usage,turnUsage:e.action.usageDelta};case`expired`:return{isError:!1,output:``};case`failed`:return{isError:!0,output:normalizeSerializableError(e.error)}}}export{finalizeSession};
|
|
1
|
+
import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";import{notifyDelegatedParentStep,notifyTurnCallerStep}from"#subagents/parent-notification.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{getSessionTokenUsage,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{fireSessionCallbackStep}from"#subagents/callback-step.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#subagents/parent-result.js";async function finalizeSession(e,t){let{serializedContext:n,sessionState:r}=t.cursor;r!==void 0&&await terminateChildSessionsStep({serializedContext:n,sessionState:r}),e.kind===`expired`?await emitTerminalSessionCompletionStep({sessionWritable:t.sessionWritable,serializedContext:n}):e.kind===`failed`&&await emitTerminalSessionFailureStep({error:normalizeSerializableError(e.error),sessionWritable:t.sessionWritable,serializedContext:n,turnId:e.turnId});let i=settledResult(e,t);if(t.mode===`task`)await fireSessionCallbackStep({error:i.isError?i.output:void 0,output:i.isError?void 0:i.output,serializedContext:n,status:i.isError?`failed`:`completed`,usage:i.sessionUsage}),await notifyDelegatedParentStep({result:i.isError?createDelegatedSubagentErrorResult(n,i.output):createDelegatedSubagentSuccessResult(n,i.output),serializedContext:n,usage:i.sessionUsage});else if(t.caller!==void 0){let e={output:i.output,usage:i.turnUsage};i.isError&&(e.isError=!0),await notifyTurnCallerStep({caller:t.caller,lifecycle:`terminal`,sessionId:r?.sessionId??n[`eve.sessionId`],settled:e})}return e.kind===`done`?{isError:e.action.isError,output:e.action.output,usage:e.action.usage,usageDelta:e.action.usageDelta}:{isError:i.isError,output:i.output,usage:i.sessionUsage,usageDelta:i.turnUsage}}function settledResult(e,t){let n=t.cursor.sessionState?.snapshot.session,r=n===void 0||t.caller===void 0?{}:{sessionUsage:toUsage(getSessionTokenUsage(n)),turnUsage:takeSessionUsageDelta(n).delta};switch(e.kind){case`done`:return{isError:e.action.isError===!0,output:e.action.output,sessionUsage:e.action.usage,turnUsage:e.action.usageDelta};case`expired`:return t.caller===void 0?{isError:!1,output:``}:{isError:!0,output:`The session ended before the delegated task completed.`,...r};case`failed`:return{isError:!0,output:normalizeSerializableError(e.error),...r}}}export{finalizeSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{getSandboxEnvironmentRuntime}from"#shared/sandbox-environment.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resumeHook}from"#internal/workflow/runtime.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{getSandboxEnvironmentRuntime}from"#shared/sandbox-environment.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{resumeHook}from"#internal/workflow/runtime.js";import{deserializeContext}from"#context/serialize.js";import{readDurableSession}from"#execution/durable-session-store.js";import{getBackgroundTasks,getBlockingWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{getAgentHandleStore}from"#subagents/handles/store.js";import{getResolvedRuntimeAgentNode}from"#runtime/graph.js";import{SESSION_CHECKPOINT_VERSION}from"#execution/session/handoff.js";function isSessionStateIdleForHandoff(e){let{state:t}=readDurableSession(e),n=getBackgroundTasks(t).query(),r=getAgentHandleStore(t);if([`eve.runtime.pendingAuthorization`,`eve.runtime.pendingInputBatch`,`eve.runtime.pendingCoordinationBatch`,`eve.runtime.deferredStepInput`,`eve.harness.pendingWorkflowInterrupt`].some(e=>t?.[e]!==void 0))return!1;let i=t?.[`eve.runtime.pendingInputBatches`];if(i!==void 0&&(!Array.isArray(i)||i.length>0))return!1;let a=t?.[`eve.runtime.proxyInputRequests`];return a!==void 0&&(!isObject(a)||Object.keys(a).length>0)?!1:(r===void 0||r.handles.every(e=>e.phase===`parked`||e.phase===`available`))&&getBlockingWorkflowToolRuns(t).length===0&&n.every(e=>e.status!==`working`)}async function isSessionIdleForHandoffStep(e){"use step";return isSessionStateIdleForHandoff(e.sessionState)}async function validateSessionCheckpointStep(e){"use step";let{checkpoint:t}=e;if(t.version!==SESSION_CHECKPOINT_VERSION)throw Error(`Unsupported session checkpoint version ${JSON.stringify(t.version)}; this deployment reads version ${SESSION_CHECKPOINT_VERSION}. Start a new session on this deployment.`);let n=t.sessionTimeoutMs;if(n!==!1&&(typeof n!=`number`||!Number.isFinite(n)||n<0))throw Error(`Session checkpoint contains an invalid timeout duration.`);let r=(await deserializeContext(t.serializedContext)).require(BundleKey),i=readDurableSession(t.sessionState).sandboxState?.session;if(i!=null){let e=getResolvedRuntimeAgentNode(r.graph,r.nodeId).sandboxRegistry.sandbox.inheritance?.definition??getResolvedRuntimeAgentNode(r.graph,r.nodeId).sandboxRegistry.sandbox.definition;if(e.kind!==`independent`)throw Error(`Session checkpoint sandbox has no resolved provider.`);let t=getSandboxEnvironmentRuntime(e.environment);if(i.providerName!==t.providerName||i.stateProtocolVersion!==t.stateProtocolVersion)throw Error(`Session checkpoint sandbox provider state is incompatible.`)}if(!isSessionStateIdleForHandoff(t.sessionState))throw Error(`Session checkpoint contains pending work and cannot be handed off.`)}async function signalSessionOwnerActivationStep(e){"use step";await resumeHook(e.token,e.activation)}async function signalSessionAnchorStep(e){"use step";await resumeHook(e.token,e.result)}export{isSessionIdleForHandoffStep,isSessionStateIdleForHandoff,signalSessionAnchorStep,signalSessionOwnerActivationStep,validateSessionCheckpointStep};
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
+
import type { SessionStateMap } from "#harness/types.js";
|
|
1
2
|
import type { TaskDeliveryPolicy, DeliverHookPayload, DeliverPayload } from "#channel/types.js";
|
|
2
|
-
import type { getSessionTaskCohorts } from "#tasks/session-task-cohorts.js";
|
|
3
3
|
export type SessionControl = "clear" | "compact" | "expired" | "reset";
|
|
4
|
-
type TaskCohorts = ReturnType<typeof getSessionTaskCohorts>;
|
|
5
4
|
export interface DeliveryAdmission {
|
|
6
5
|
readonly delivery: DeliverHookPayload;
|
|
7
6
|
readonly sequence: number;
|
|
@@ -29,8 +28,7 @@ export type SessionInputSelection = TurnSelection | {
|
|
|
29
28
|
* Ordered, admitted session input, plus the idempotency and cancellation
|
|
30
29
|
* facts for task deliveries this owner has seen. Entries are private; callers
|
|
31
30
|
* receive typed admission and selection values. Everything here is rebuilt
|
|
32
|
-
* deterministically on replay
|
|
33
|
-
* handoff requires every indexed task to be terminal.
|
|
31
|
+
* deterministically on replay. Indexed task outcomes live in session state.
|
|
34
32
|
*/
|
|
35
33
|
export declare class SessionInputQueue {
|
|
36
34
|
private readonly entries;
|
|
@@ -38,8 +36,8 @@ export declare class SessionInputQueue {
|
|
|
38
36
|
private readonly seenTaskDeliveryIds;
|
|
39
37
|
private nextSequence;
|
|
40
38
|
get pendingCount(): number;
|
|
41
|
-
/**
|
|
42
|
-
enqueueDelivery(delivery: DeliverHookPayload): DeliveryAdmission | undefined;
|
|
39
|
+
/** Drops notifications the model must not see; lifecycle envelopes are always admitted. */
|
|
40
|
+
enqueueDelivery(delivery: DeliverHookPayload, state?: SessionStateMap): DeliveryAdmission | undefined;
|
|
43
41
|
/** A caller's own task id counts as seen so its echo is not admitted twice. */
|
|
44
42
|
rememberTask(taskId: string): void;
|
|
45
43
|
isTaskCancelled(taskId: string): boolean;
|
|
@@ -50,10 +48,12 @@ export declare class SessionInputQueue {
|
|
|
50
48
|
/** Task lifecycle effects must be applied even while their cohort report is held. */
|
|
51
49
|
taskDeliveries(): readonly DeliveryAdmission[];
|
|
52
50
|
replaceDelivery(sequence: number, delivery: DeliverHookPayload | undefined): void;
|
|
53
|
-
/**
|
|
51
|
+
/** Revokes model wakeups for a cancelled task; its lifecycle envelopes still reach routing. */
|
|
54
52
|
cancelTask(taskId: string): void;
|
|
53
|
+
/** After cancellation records outcomes, queued notifications for those tasks are stale. */
|
|
54
|
+
discardStaleNotifications(state: SessionStateMap | undefined): void;
|
|
55
55
|
takeSteering(admitted: ReadonlySet<number>, callerCallId: string | undefined): TurnSelection | undefined;
|
|
56
|
-
takeNext(
|
|
56
|
+
takeNext(state: SessionStateMap | undefined, options?: {
|
|
57
57
|
readonly deferDeliveries?: boolean;
|
|
58
58
|
readonly taskDeliveryPolicy?: TaskDeliveryPolicy;
|
|
59
59
|
/**
|
|
@@ -68,8 +68,10 @@ export declare class SessionInputQueue {
|
|
|
68
68
|
}): SessionInputSelection | undefined;
|
|
69
69
|
private nextActionableIndex;
|
|
70
70
|
private takeSelectionAt;
|
|
71
|
-
private
|
|
71
|
+
private isCancelledDelivery;
|
|
72
|
+
/** A cancelled task's notification never reaches the model. */
|
|
73
|
+
private isCancelledNotification;
|
|
74
|
+
private discardDeliveries;
|
|
72
75
|
private retain;
|
|
73
76
|
}
|
|
74
77
|
export declare function isSteeringDelivery(delivery: DeliverHookPayload, callerCallId: string | undefined): boolean;
|
|
75
|
-
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsonValuesEqual}from"#shared/json.js";import{coalesceDeliveries}from"#harness/messages.js";var SessionInputQueue=class{entries=[];cancelledTaskIds=new Set;seenTaskDeliveryIds=new Set;nextSequence=0;get pendingCount(){return this.entries.length}enqueueDelivery(e){let
|
|
1
|
+
import{jsonValuesEqual}from"#shared/json.js";import{coalesceDeliveries}from"#harness/messages.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{hasRecordedTaskOutcome,taskIdOfDelivery}from"#tasks/notification.js";var SessionInputQueue=class{entries=[];cancelledTaskIds=new Set;seenTaskDeliveryIds=new Set;nextSequence=0;get pendingCount(){return this.entries.length}enqueueDelivery(e,t){if(isStaleNotification(e,t))return;let n=taskDeliveryId(e);if(n!==void 0){let t=terminalTaskId(e),r=t===void 0?n:`${t}:ready`;if(this.seenTaskDeliveryIds.has(r)||this.isCancelledNotification(e))return;this.seenTaskDeliveryIds.add(r)}let r={delivery:e,sequence:this.nextSequence++};return this.entries.push({...r,kind:`delivery`}),r}rememberTask(e){this.seenTaskDeliveryIds.add(e)}isTaskCancelled(e){return this.cancelledTaskIds.has(e)}enqueueControl(e){this.entries.push({control:e,kind:`control`,sequence:this.nextSequence++})}enqueueAuthorization(e){for(let t of e){let e=authorizationAttemptId(t);e!==void 0&&(this.entries.some(t=>t.kind===`authorization`&&t.attemptId===e)||this.entries.push({attemptId:e,kind:`authorization`,payload:t,sequence:this.nextSequence++}))}}delivery(e){return this.entries.find(t=>t.kind===`delivery`&&t.sequence===e)?.delivery}taskDeliveries(){return this.entries.filter(e=>e.kind===`delivery`&&!isNotificationOnly(e.delivery))}replaceDelivery(e,t){let n=this.entries.findIndex(t=>t.kind===`delivery`&&t.sequence===e);if(!(n<0)){if(t===void 0||this.isCancelledNotification(t)){this.entries.splice(n,1);return}this.entries[n]={delivery:t,kind:`delivery`,sequence:e}}}cancelTask(e){this.cancelledTaskIds.add(e),this.discardDeliveries(e=>this.isCancelledNotification(e))}discardStaleNotifications(e){this.discardDeliveries(t=>isStaleNotification(t,e))}takeSteering(e,t){let n=this.entries.filter(n=>n.kind===`delivery`&&e.has(n.sequence)&&isSteeringDelivery(n.delivery,t));if(n.length!==0)return this.retain(e=>e.kind!==`delivery`||!n.includes(e)),{delivery:combine(n),handoffEligible:!1,kind:`turn`,sequences:n.map(({sequence:e})=>e)}}takeNext(e,t){let n=t?.expectedAttemptIds??new Set;if(this.retain(e=>e.kind!==`authorization`||n.has(e.attemptId)),n.size>0){let e=new Map(this.entries.flatMap(e=>e.kind===`authorization`?[[e.attemptId,e.payload]]:[]));if([...n].every(t=>e.has(t)))return this.retain(e=>e.kind!==`authorization`),{kind:`authorization-resume`,payloads:[...n].map(t=>e.get(t))}}let r=getBackgroundTasks(e),i=new Set(r.query({state:`working`}).filter(({taskId:e})=>!this.seenTaskDeliveryIds.has(`${e}:ready`)&&!this.cancelledTaskIds.has(e)).map(e=>e.cohortId)),a=this.nextActionableIndex(r,i,t?.deferDeliveries===!0,t?.taskDeliveryPolicy??`cohort`);if(!(a<0))return this.takeSelectionAt(a,r,t?.freshSequence)}nextActionableIndex(e,t,n,r){return this.entries.findIndex(i=>{if(i.kind===`control`)return!0;if(i.kind===`authorization`||n||this.isCancelledDelivery(i.delivery))return!1;let a=terminalCohort(i.delivery,e);return r===`auto`||a===void 0||!t.has(a)})}takeSelectionAt(e,t,n){let r=this.entries[e];if(r.kind!==`delivery`)return this.entries.splice(e,1),r.kind===`control`?{control:r.control,kind:`control`}:{kind:`authorization-resume`,payloads:[r.payload]};let i=terminalCohort(r.delivery,t);if(i!==void 0){let r=this.entries.findLastIndex(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===i),a=this.entries.findIndex((n,i)=>i>e&&i<r&&(n.kind!==`delivery`||!this.isCancelledDelivery(n.delivery)&&terminalCohort(n.delivery,t)===void 0));if(a>=0)return this.takeSelectionAt(a,t,n)}let a=this.entries.splice(e,1)[0];if(a.kind!==`delivery`)throw Error(`Selected a non-delivery entry as a turn.`);let o=[a],s=terminalCohort(a.delivery,t);if(s!==void 0){let e=this.entries.filter(e=>e.kind===`delivery`&&!this.isCancelledDelivery(e.delivery)&&terminalCohort(e.delivery,t)===s);o.push(...e),this.retain(t=>t.kind!==`delivery`||!e.includes(t))}else{let t=a.delivery.auth!=null&&a.delivery.auth.principalType!==`anonymous`,n=a.delivery.caller;for(;this.entries.length>e;){let r=this.entries[e];if(r?.kind!==`delivery`||a.delivery.taskDeliveryId!==void 0||r.delivery.taskDeliveryId!==void 0||!t||!jsonValuesEqual(a.delivery.auth,r.delivery.auth)||n!==void 0&&r.delivery.caller!==void 0)break;o.push(this.entries.splice(e,1)[0]),n??=r.delivery.caller}}let c=o.map(({sequence:e})=>e),l=combine(o);return{delivery:l,handoffEligible:c.length===1&&c[0]===n&&l.caller===void 0&&taskDeliveryId(l)===void 0&&this.entries.length===0,kind:`turn`,sequences:c}}isCancelledDelivery(e){let t=taskDeliveryId(e);return t!==void 0&&this.cancelledTaskIds.has(taskIdOfDelivery(t))}isCancelledNotification(e){return isNotificationOnly(e)&&this.isCancelledDelivery(e)}discardDeliveries(e){this.retain(t=>t.kind!==`delivery`||!e(t.delivery))}retain(e){let t=this.entries.filter(e);this.entries.splice(0,this.entries.length,...t)}};function isNotificationOnly(e){return e.payloads.every(e=>e.task===void 0)}function isStaleNotification(e,t){return isNotificationOnly(e)&&hasRecordedTaskOutcome(e,t)}function isSteeringDelivery(e,t){return e.taskDeliveryId===void 0&&(e.turnPolicy??`steer`)===`steer`&&(e.caller===void 0||e.caller.callId===t)}function combine(e){if(e.length===1)return e[0].delivery;let t=e.map(({delivery:e})=>e),n=t.flatMap(e=>e.taskDeliveryIds??(e.taskDeliveryId===void 0?[]:[e.taskDeliveryId]));return{...coalesceDeliveries(t),taskDeliveryIds:n.length>0?n:void 0}}function authorizationAttemptId(e){let t=e.authorizationCallback;return typeof t?.attemptId==`string`?t.attemptId:void 0}function taskDeliveryId(e){return e.taskDeliveryId??e.caller?.taskId}function terminalCohort(e,t){let n=terminalTaskId(e);return n===void 0?void 0:t.get(n)?.cohortId}function terminalTaskId(e){if(e.caller===void 0)for(let t of[`completed`,`failed`,`cancelled`]){let n=`:ready:${t}`;if(e.taskDeliveryId?.endsWith(n))return e.taskDeliveryId.slice(0,-n.length)}}export{SessionInputQueue,isSteeringDelivery};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME}from"#context/key-names.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";
|
|
1
|
+
import{TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME}from"#context/key-names.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{routeSelectedDelivery}from"#execution/session/route-selected-delivery.js";import{admitSessionInboxPayload,applySessionCancellation}from"#execution/session/admission.js";async function nextTurnDelivery(e){let{inbox:t,cursor:n,queue:r}=e,i;for(;;){for(let{delivery:e,sequence:t}of r.taskDeliveries()){let i=await routeDeliverToChildren({delivery:e,sessionWritable:n.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});if(await n.apply(i),r.replaceDelivery(t,i.kind===`cancel-turn`?void 0:i.remainder),i.kind===`cancel-turn`)return i}let a=r.takeNext(n.sessionState.snapshot.session.state,{deferDeliveries:e.deferDeliveries,taskDeliveryPolicy:n.serializedContext[TASK_DELIVERY_POLICY_CONTEXT_KEY_NAME]===`auto`?`auto`:`cohort`,expectedAttemptIds:e.expectedAttemptIds,freshSequence:t.hasPending()?void 0:i});if(a?.kind===`control`)return{kind:a.control};if(a?.kind===`authorization-resume`)return a;if(a?.kind===`turn`){let e=await routeSelectedDelivery(a,n);if(e.kind===`cancel-turn`)return e;if(e.kind===`consumed`)continue;return e}let o=r.pendingCount===0,s=await t.next();if(s===void 0)return{kind:`closed`};let c=await admitSessionInboxPayload(s,e);switch(i=o&&c.kind===`delivery`?c.admission.sequence:void 0,c.kind){case`workflow`:return{kind:`workflow`,message:c.message};case`cancel`:await applySessionCancellation(c.command,e)}}}export{nextTurnDelivery};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{finalizeSession}from"#execution/session/finalization.js";import{createSessionTimeoutControl}from"#execution/session/timeout-control.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=new SessionStateCursor({inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),r={caller:e.caller,terminalEmitted:!1},i=new SessionHandoff({checkpoint:{capabilities:e.capabilities,mode:e.mode,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),a={output:``,isError:!0},o;try{try{o=await runSessionLoop(e,{cursor:n,handoff:i,inbox:t,progress:r})}finally{await t.dispose()}return o.kind===`transferred`?e.anchor.kind===`self`?(a=await i.awaitAnchoredResult(),a):{output:``}:(a=await finalizeSession(o.outcome,{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),r.terminalEmitted=!0,a)}catch(t){throw r.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:r.turnId},{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await reportResultToAnchor(e,a,i,o)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue,s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,mode:e.mode,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,sessionId:e.sessionId}),nextParkedActivity=async t=>{for(;;){let r=await nextTurnDelivery({cursor:n,deferDeliveries:e.mode===`task`&&t.size>0,expectedAttemptIds:t,inbox:i,queue:o});if(r.kind!==`workflow`)return r;await s.handleWorkflowMessage(r.message)}},l=0,runTurn=async e=>{let t=a.caller;return t?.taskId!==void 0&&o.rememberTask(t.taskId),t!==void 0&&await n.apply({serializedContext:await bindTurnCallerContextStep({caller:t,serializedContext:n.serializedContext})}),a.turnId=`turn_${String(l++)}`,await s.runTurn(e)},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,{serializedContext:n.serializedContext,sessionState:n.sessionState});return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async()=>{let t=await settleCancelledTurnStep({sessionWritable:e.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});return await n.apply(t),a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity(new Set);switch(e.kind){case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:case`authorization-resume`:continue}}},runInitialAction=async()=>e.awaitFirstMessage?await awaitPrewarmedAction():{action:await runTurn(e.initialInput===void 0?void 0:{delivery:e.initialInput}),kind:`action`};try{let[t,r]=await Promise.allSettled([runInitialAction(),c?.start()]);if(r.status===`rejected`)throw r.reason;if(t.status===`rejected`)throw t.reason;let i=t.value;if(i.kind!==`action`)return i;let o=i.action;for(;;){if(o.kind===`done`)return{kind:`terminal`,outcome:{action:o,kind:`done`}};if(o.cancelled===!0){let t={caller:a.caller,sessionId:e.sessionId},n=await settleCancelledTurn();await notifyCancelledTaskCallerStep(n.usage===void 0?t:{...t,usage:n.usage})}else o.settled
|
|
1
|
+
import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import"#execution/session-inbox/inbox.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#subagents/parent-notification.js";import{signalSessionAnchorStep}from"#execution/session/handoff-steps.js";import{SessionHandoff,sessionAnchorToken}from"#execution/session/handoff.js";import{nextTurnDelivery}from"#execution/session/next-input.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{SessionInputQueue}from"#execution/session/input-queue.js";import{SessionExecution}from"#execution/session/turn.js";import{SessionStateCursor}from"#execution/session/state-cursor.js";import{finalizeSession}from"#execution/session/finalization.js";import{createSessionTimeoutControl}from"#execution/session/timeout-control.js";function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runPreparedSession(e,t){let n=new SessionStateCursor({inbox:t,sessionWritable:e.sessionWritable,serializedContext:e.serializedContext,sessionState:e.sessionState}),r={caller:e.caller,terminalEmitted:!1},i=new SessionHandoff({checkpoint:{capabilities:e.capabilities,mode:e.mode,retention:e.retention,sessionTimeoutMs:e.sessionTimeoutMs},deploymentId:e.deploymentId,inbox:t,isInitialOwner:e.anchor.kind===`self`,sessionId:e.sessionId}),a={output:``,isError:!0},o;try{try{o=await runSessionLoop(e,{cursor:n,handoff:i,inbox:t,progress:r})}finally{await t.dispose()}return o.kind===`transferred`?e.anchor.kind===`self`?(a=await i.awaitAnchoredResult(),a):{output:``}:(a=await finalizeSession(o.outcome,{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),r.terminalEmitted=!0,a)}catch(t){throw r.terminalEmitted||await finalizeSession({error:t,kind:`failed`,turnId:r.turnId},{caller:r.caller,cursor:n,mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}finally{await reportResultToAnchor(e,a,i,o)}}async function failSession(e){let t;try{t=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext})}catch{}throw await finalizeSession({error:e.error,kind:`failed`},{caller:t,cursor:{serializedContext:e.serializedContext,sessionState:e.sessionState},mode:e.mode,sessionWritable:e.sessionWritable}),createSafeOuterWorkflowError()}async function reportResultToAnchor(e,t,n,r){switch(e.anchor.kind){case`self`:await n.disposeAnchor(),await e.anchor.notify?.(t);return;case`successor`:if(r?.kind===`transferred`)return;await signalSessionAnchorStep({result:t,token:sessionAnchorToken(e.sessionId)});return}}async function runSessionLoop(e,t){let{cursor:n,handoff:r,inbox:i,progress:a}=t,o=new SessionInputQueue,s=new SessionExecution({capabilities:e.capabilities,cursor:n,inbox:i,mode:e.mode,queue:o,sessionId:e.sessionId}),c=e.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:e.sessionTimeoutDeadline,sessionId:e.sessionId}),nextParkedActivity=async t=>{for(;;){let r=await nextTurnDelivery({cursor:n,deferDeliveries:e.mode===`task`&&t.size>0,expectedAttemptIds:t,inbox:i,queue:o});if(r.kind!==`workflow`)return r;await s.handleWorkflowMessage(r.message)}},l=0,runTurn=async e=>{let t=a.caller;return t?.taskId!==void 0&&o.rememberTask(t.taskId),t!==void 0&&await n.apply({serializedContext:await bindTurnCallerContextStep({caller:t,serializedContext:n.serializedContext})}),a.turnId=`turn_${String(l++)}`,await s.runTurn(e)},runDeliveredTurn=async e=>{let t=await r.tryTransfer(e,{serializedContext:n.serializedContext,sessionState:n.sessionState});return t.kind===`transferred`?t:(e.delivery.caller!==void 0&&(a.caller=e.delivery.caller),{action:await runTurn({delivery:e.delivery}),kind:`action`})},settleCancelledTurn=async()=>{let t=await settleCancelledTurnStep({sessionWritable:e.sessionWritable,serializedContext:n.serializedContext,sessionState:n.sessionState});return await n.apply(t),a.caller=void 0,t},awaitPrewarmedAction=async()=>{for(;;){let e=await nextParkedActivity(new Set);switch(e.kind){case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:continue;case`turn`:return await runDeliveredTurn(e);case`cancel-turn`:case`authorization-resume`:continue}}},runInitialAction=async()=>e.awaitFirstMessage?await awaitPrewarmedAction():{action:await runTurn(e.initialInput===void 0?void 0:{delivery:e.initialInput}),kind:`action`};try{let[t,r]=await Promise.allSettled([runInitialAction(),c?.start()]);if(r.status===`rejected`)throw r.reason;if(t.status===`rejected`)throw t.reason;let i=t.value;if(i.kind!==`action`)return i;let o=i.action;for(;;){if(o.kind===`done`)return{kind:`terminal`,outcome:{action:o,kind:`done`}};if(o.cancelled===!0){let t={caller:a.caller,sessionId:e.sessionId},n=await settleCancelledTurn();await notifyCancelledTaskCallerStep(n.usage===void 0?t:{...t,usage:n.usage})}else o.settled?.notifyCaller===!0&&(a.caller!==void 0&&await notifyTurnCallerStep({caller:a.caller,lifecycle:`parked`,sessionId:e.sessionId,settled:o.settled}),a.caller=void 0);let t=await nextParkedActivity(new Set(o.authorizationAttemptIds??[]));switch(t.kind){case`authorization-resume`:o=await runTurn({delivery:{kind:`deliver`,payloads:t.payloads}});continue;case`expired`:case`reset`:case`closed`:return{kind:`terminal`,outcome:{kind:`expired`}};case`clear`:case`compact`:o=await runTurn({control:t.kind});continue;case`cancel-turn`:await cancelDescendantTurnsStep({serializedContext:n.serializedContext,sessionState:n.sessionState}),await settleCancelledTurn(),o={...o,settled:void 0};continue;case`turn`:{let e=await runDeliveredTurn(t);if(e.kind!==`action`)return e;o=e.action;continue}}}}finally{await c?.dispose()}}export{failSession,runPreparedSession};
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { DurableStepResult } from "#execution/session/turn-step-types.js";
|
|
2
2
|
import type { StepResult } from "#harness/types.js";
|
|
3
3
|
import type { RunMode } from "#shared/run-mode.js";
|
|
4
|
-
export declare function resolveSessionStepResult(stepResult: StepResult, nextSerializedContext: Record<string, unknown>, mode: RunMode, beforeStepContext: Record<string, unknown
|
|
4
|
+
export declare function resolveSessionStepResult(stepResult: StepResult, nextSerializedContext: Record<string, unknown>, mode: RunMode, beforeStepContext: Record<string, unknown>,
|
|
5
|
+
/** The turn this step belongs to. */
|
|
6
|
+
turnId: string): DurableStepResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDurableSessionState}from"#execution/durable-session-store.js";import{preserveSerializedBackgroundTaskObservabilityState}from"#shared/serialized-observability-state.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{
|
|
1
|
+
import{createDurableSessionState}from"#execution/durable-session-store.js";import{getBackgroundTasks}from"#harness/workflow-tool-runs.js";import{preserveSerializedBackgroundTaskObservabilityState}from"#shared/serialized-observability-state.js";import{derivePendingState}from"#execution/session/pending-turn-state.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{hasPendingInputBatch}from"#harness/input-requests.js";function resolveSessionStepResult(e,t,n,r,i){let a=createDurableSessionState({session:e.session});if(e.steered)return{action:`steered`,serializedContext:t,sessionState:a};let o=e.backgroundTasks===void 0||e.backgroundTaskSession===void 0?{}:{backgroundTaskContext:preserveSerializedBackgroundTaskObservabilityState(r,t,e.backgroundTasks),backgroundTaskState:createDurableSessionState({session:e.backgroundTaskSession}),backgroundTasks:e.backgroundTasks};if(e.next!==null&&typeof e.next==`object`&&`done`in e.next){if(n===`task`&&hasPendingInputBatch(e.session.state))throw Error(`Task mode cannot complete while input requests remain pending.`);let r=getTurnUsageState(e.session.state)?.session;return{action:`done`,...o,output:e.next.output,isError:e.next.isError,serializedContext:t,sessionState:a,usage:r===void 0?void 0:toUsage(r),usageDelta:takeSessionUsageDelta(e.session).delta}}if(e.next===null){let n=derivePendingState(e.session);if(e.settledTurn!==void 0){if(e.settledTurn.isError!==!0&&getBackgroundTasks(e.session.state).query({state:`working`,turnId:i}).length>0)return{action:`park`,...o,...n,settled:{...e.settledTurn,notifyCaller:!1},serializedContext:t,sessionState:a};let{delta:r,session:s}=takeSessionUsageDelta(e.session);return{action:`park`,...o,...n,serializedContext:t,sessionState:createDurableSessionState({session:s}),settled:{notifyCaller:!0,output:e.settledTurn.output,isError:e.settledTurn.isError,usage:r}}}return{action:`park`,...o,...n,serializedContext:t,sessionState:a}}return{action:`continue`,...o,serializedContext:t,sessionState:a}}export{resolveSessionStepResult};
|
|
@@ -3,6 +3,11 @@ import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
|
3
3
|
import type { SettledTurn, StepResult } from "#harness/types.js";
|
|
4
4
|
import type { RuntimeActionResult } from "#shared/action-types.js";
|
|
5
5
|
import type { TokenUsage } from "#shared/token-usage.js";
|
|
6
|
+
/** A settled turn as the session parks it. The session, not the harness, decides caller delivery. */
|
|
7
|
+
export interface ParkedSettledTurn extends SettledTurn {
|
|
8
|
+
/** False while background tasks started by this turn are still working. */
|
|
9
|
+
readonly notifyCaller: boolean;
|
|
10
|
+
}
|
|
6
11
|
/** Trusted runtime-action results collected by the session owner. */
|
|
7
12
|
export interface RuntimeActionResultStepInput {
|
|
8
13
|
readonly acceptedAtMsByCallId?: Readonly<Record<string, number>>;
|
|
@@ -50,7 +55,7 @@ export type DurableStepResult = ({
|
|
|
50
55
|
readonly hasPendingAuthorization: boolean;
|
|
51
56
|
readonly hasPendingInputBatch: boolean;
|
|
52
57
|
readonly pendingCoordinationCallIds?: readonly string[];
|
|
53
|
-
readonly settled?:
|
|
58
|
+
readonly settled?: ParkedSettledTurn;
|
|
54
59
|
}) & DurableStepResultFields;
|
|
55
60
|
/** The only two ways a locally executed conversational turn can settle. */
|
|
56
61
|
export type TurnOutcome = {
|
|
@@ -63,6 +68,6 @@ export type TurnOutcome = {
|
|
|
63
68
|
readonly authorizationAttemptIds?: readonly string[];
|
|
64
69
|
readonly cancelled?: true;
|
|
65
70
|
readonly kind: "park";
|
|
66
|
-
readonly settled?:
|
|
71
|
+
readonly settled?: ParkedSettledTurn;
|
|
67
72
|
};
|
|
68
73
|
export {};
|