eve 0.38.0 → 0.38.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 +17 -0
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +5 -5
- package/dist/src/compiled/@workflow/core/events-consumer.d.ts +97 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/private.js +1 -1
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +35 -0
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +127 -93
- package/dist/src/compiled/@workflow/core/runtime/quickjs-entrypoint.d.ts +8 -9
- package/dist/src/compiled/@workflow/core/runtime/replay-budget.d.ts +8 -0
- package/dist/src/compiled/@workflow/core/runtime/resume-latency.d.ts +143 -0
- package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +27 -12
- package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +39 -8
- package/dist/src/compiled/@workflow/core/runtime/world-compatibility.d.ts +6 -5
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +81 -0
- package/dist/src/compiled/@workflow/core/test-support/orchestrator-context.d.ts +25 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.d.ts +18 -2
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/analytics.d.ts +9 -0
- package/dist/src/compiled/@workflow/world/events.d.ts +76 -87
- package/dist/src/compiled/@workflow/world/index.d.ts +3 -3
- package/dist/src/compiled/@workflow/world/interfaces.d.ts +45 -45
- package/dist/src/compiled/@workflow/world/queue.d.ts +86 -0
- package/dist/src/compiled/@workflow/world/slot-identity.d.ts +15 -0
- package/dist/src/compiled/@workflow/world/spec-version.d.ts +30 -18
- package/dist/src/compiled/@workflow/world/test-support/duplicate-event-fixtures.d.ts +41 -0
- package/dist/src/compiled/@workflow/world-local/index.js +5 -5
- package/dist/src/compiled/@workflow/world-vercel/index.js +12 -12
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-DZtQkszH.js → attribute-changes-B8K0pwpH.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-CPlyFOVo.js → dist-BRGbNjhD.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-xQXN70ED.js → dist-CqvWKNQv.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/frames-DoexhtxJ.js +3 -0
- package/dist/src/compiled/_chunks/workflow/private-z_2Kcwee.js +1 -0
- package/dist/src/compiled/_chunks/workflow/resume-hook-DO_MuJlY.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-lq7-eG0l.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-7TgF3i-e.js +1 -0
- package/dist/src/compiled/_chunks/workflow/wait-until-BPSgt1Wg.js +15 -0
- package/dist/src/compiled/_chunks/workflow/ws-transport-TYZ9zwoZ.js +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +5 -0
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/model-catalog.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-extension.d.ts +10 -1
- package/dist/src/compiler/normalize-extension.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/normalize-subagent.d.ts +1 -0
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/discover/discover-agent.js +1 -1
- package/dist/src/discover/discover-subagent.js +1 -1
- package/dist/src/execution/create-session-step.d.ts +1 -0
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +1 -1
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/session-callback-step.d.ts +8 -0
- package/dist/src/execution/session-callback-step.js +1 -1
- package/dist/src/execution/session.d.ts +2 -0
- package/dist/src/execution/session.js +1 -1
- package/dist/src/execution/task-event-callback.d.ts +5 -6
- package/dist/src/execution/task-event-callback.js +1 -1
- package/dist/src/execution/tasks/child/instructions.d.ts +3 -0
- package/dist/src/execution/tasks/child/instructions.js +1 -0
- package/dist/src/execution/tasks/child/steps.d.ts +7 -1
- package/dist/src/execution/tasks/child/steps.js +1 -1
- package/dist/src/execution/tasks/child/update.d.ts +10 -0
- package/dist/src/execution/tasks/child/update.js +1 -0
- package/dist/src/execution/tasks/child/workflow.d.ts +3 -3
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/agent-views.js +1 -1
- package/dist/src/execution/tasks/parent/control-shared.d.ts +1 -1
- package/dist/src/execution/tasks/parent/dispatch-task-step.d.ts +1 -1
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch.d.ts +5 -3
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/advertised-tools.d.ts +3 -0
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-map-loader.js +1 -1
- package/dist/src/internal/nitro/host/extension-capability-requirements.js +1 -1
- package/dist/src/internal/workflow/development-world-client.js +1 -1
- package/dist/src/public/channels/mcp.d.ts +2 -2
- package/dist/src/public/channels/mcp.js +1 -1
- package/dist/src/runtime/framework-tools/index.js +1 -1
- package/dist/src/runtime/framework-tools/tasks.d.ts +6 -7
- package/dist/src/runtime/framework-tools/tasks.js +1 -1
- package/dist/src/runtime/prompt/compose.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/setup/scaffold/create/extension.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/tasks/task-id.d.ts +1 -2
- package/dist/src/tasks/task-id.js +1 -1
- package/dist/src/tasks/task-inbox-token.d.ts +2 -0
- package/dist/src/tasks/task-inbox-token.js +1 -0
- package/dist/src/tasks/types.d.ts +9 -1
- package/dist/src/tasks/wire.d.ts +2 -3
- package/docs/channels/custom.mdx +1 -0
- package/docs/channels/mcp.mdx +185 -0
- package/docs/channels/meta.json +1 -0
- package/docs/channels/overview.mdx +6 -1
- package/docs/extensions.md +14 -6
- package/docs/guides/auth-and-route-protection.md +1 -0
- package/docs/guides/dev-tui.md +1 -0
- package/docs/instructions.mdx +1 -0
- package/docs/subagents/index.mdx +3 -1
- package/package.json +6 -6
- package/dist/src/compiled/_chunks/workflow/frames-BBs-9k1d.js +0 -3
- package/dist/src/compiled/_chunks/workflow/private-UQtz8ZcW.js +0 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-CYtSorp6.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-Cjo0A3NO.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-C1P0OWBm.js +0 -1
- package/dist/src/compiled/_chunks/workflow/wait-until-CT1ve8qB.js +0 -15
- package/dist/src/compiled/_chunks/workflow/ws-transport-beXxD0s_.js +0 -1
- package/dist/src/execution/tasks/parent/send.d.ts +0 -25
- package/dist/src/execution/tasks/parent/send.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join,resolve}from"node:path";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,locateExtensionMount,mountNamespace}from"#discover/extensions.js";import{
|
|
1
|
+
import{join,resolve}from"node:path";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{createAgentSourceManifest,createModuleSourceRef}from"#discover/manifest.js";import{DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,locateExtensionMount,mountNamespace}from"#discover/extensions.js";import{DISCOVER_CHANNELS_DIRECTORY_INVALID,DISCOVER_EXTENSIONS_DIRECTORY_INVALID,DISCOVER_HOOKS_DIRECTORY_INVALID,DISCOVER_TOOLS_DIRECTORY_INVALID,createChannelNameDiagnostic,createExtensionNameDiagnostic,createHookNameDiagnostic,createToolNameDiagnostic,createUnsupportedRootDirectoryDiagnostics,discoverFlatModuleSource,discoverInstructionsSource,discoverNamedSourceDirectory,readSortedDirectoryEntries}from"#discover/grammar.js";import{discoverConnectionSources}from"#discover/connections.js";import{discoverSubagents}from"#discover/discover-subagent.js";import{discoverLibSources}from"#discover/lib.js";import{discoverSandboxSource}from"#discover/sandbox.js";import{discoverScheduleSources}from"#discover/schedules.js";import{discoverSkills}from"#discover/skills.js";import{stripNpmPackageScope}from"#shared/package-name.js";async function discoverAgent(r){let a=r.source??createDiskProjectSource(),c=resolve(r.appRoot),u=resolve(r.agentRoot),d=r.role??`agent`,p=[],h=await tryReadPackageJsonName(a,c),g=await readSortedDirectoryEntries(a,u);p.push(...createUnsupportedRootDirectoryDiagnostics({classifyEntry:classifyAgentRootEntry,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:g,rootPath:u}));let _=await discoverInstructionsSource({rootEntries:g,rootPath:u,source:a,required:d!==`extension`});p.push(..._.diagnostics);let v=discoverFlatModuleSource({rootEntries:g,rootPath:u,slotName:`agent`});p.push(...v.diagnostics);let y=await discoverNamedSourceDirectory({directoryName:`channels`,invalidDirectoryCode:DISCOVER_CHANNELS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(u,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:g,rootPath:u,source:a,validateSegment:createChannelNameDiagnostic});p.push(...y.diagnostics);let b=await discoverLibSources({agentRoot:u,rootEntries:g,source:a});p.push(...b.diagnostics);let x=await discoverScheduleSources({agentRoot:u,rootEntries:g,source:a});p.push(...x.diagnostics);let S=await discoverConnectionSources({rootEntries:g,rootPath:u,source:a});p.push(...S.diagnostics);let C=await discoverSandboxSource({rootEntries:g,rootPath:u,source:a});p.push(...C.diagnostics),d===`extension`&&(v.module!==void 0&&p.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,message:`An extension may not declare agent config (agent.ts) — model, limits, and sandbox are the consuming agent's to own.`,sourcePath:join(u,v.module.logicalPath)})),C.sandbox!==null&&p.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,message:`An extension may not declare a sandbox — it is the consuming agent's to own.`,sourcePath:join(u,C.sandbox.logicalPath)})));let w=await discoverNamedSourceDirectory({directoryName:`tools`,invalidDirectoryCode:DISCOVER_TOOLS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(u,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:g,rootPath:u,source:a,validateSegment:createToolNameDiagnostic});p.push(...w.diagnostics);let T=await discoverNamedSourceDirectory({directoryName:`hooks`,invalidDirectoryCode:DISCOVER_HOOKS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(u,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:g,rootPath:u,source:a,validateSegment:createHookNameDiagnostic});p.push(...T.diagnostics);let E=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(u,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:g,rootPath:u,source:a,validateSegment:createExtensionNameDiagnostic});p.push(...E.diagnostics);let D=await discoverSkills({agentRoot:u,source:a});p.push(...D.diagnostics);let O=await discoverSubagents({agentRoot:u,appRoot:c,source:a});p.push(...O.diagnostics);let k=await collectExtensionMounts({agentRoot:u,fileMounts:E.sources,rootEntries:g,source:a});p.push(...k.diagnostics),p.push(...detectRootNamespaceCollisions({agentRoot:u,namespaces:k.mounts.map(e=>e.namespace),sources:[...w.sources,...S.connections,...D.skills,...x.schedules,...O.subagents]}));let A=[];if(d!==`agent`)for(let t of k.mounts)p.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,message:`"${t.mountRef.logicalPath}" mounts an extension from inside an extension, which is not supported yet. Extensions cannot mount other extensions; remove the "extensions/" slot.`,sourcePath:join(u,t.mountRef.logicalPath)}));else{let e=await resolveExtensionMounts({agentRoot:u,appRoot:c,mounts:k.mounts,source:a});p.push(...e.diagnostics),A=e.mounts}let j={agentRoot:u,appRoot:c,channels:y.sources,connections:S.connections,packageName:h,diagnostics:p,extensions:k.mounts.map(e=>e.mountRef),resolvedExtensions:A,hooks:T.sources,lib:b.lib,instructions:_.instructions,sandbox:C.sandbox,sandboxWorkspaces:C.sandboxWorkspace===null?[]:[C.sandboxWorkspace],schedules:x.schedules,skills:D.skills,tools:w.sources,subagents:O.subagents};return v.module!==void 0&&(j.configModule=v.module),{diagnostics:p,manifest:createAgentSourceManifest(j)}}async function resolveExtensionMounts(e){let t=[],n=[];for(let r of e.mounts){let i=await locateExtensionMount({source:e.source,agentRoot:e.agentRoot,appRoot:e.appRoot,mount:r.mountRef,namespace:r.namespace});if(t.push(...i.diagnostics),i.location===void 0)continue;let a=await discoverAgent({agentRoot:i.location.sourceRoot,appRoot:i.location.packageRoot,source:e.source,role:`extension`});t.push(...a.diagnostics);let o;if(r.overridesRoot!==void 0){let n=await discoverAgent({agentRoot:r.overridesRoot,appRoot:e.appRoot,source:e.source,role:`extension`});t.push(...n.diagnostics),o=n.manifest}n.push({namespace:i.location.namespace,specifier:i.location.specifier,packageName:i.location.packageName,packageRoot:i.location.packageRoot,sourceRoot:i.location.sourceRoot,manifest:a.manifest,overrides:o})}return{diagnostics:t,mounts:n}}async function discoverExtensionMountDeclarations(n){let r=n.source??createDiskProjectSource(),i=resolve(n.agentRoot),a=await readSortedDirectoryEntries(r,i),s=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(i,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:a,rootPath:i,source:r,validateSegment:createExtensionNameDiagnostic}),c=await collectExtensionMounts({agentRoot:i,fileMounts:s.sources,rootEntries:a,source:r});return{diagnostics:[...s.diagnostics,...c.diagnostics],mounts:c.mounts}}async function collectExtensionMounts(t){let r=[],i=join(t.agentRoot,`extensions`),o=t.fileMounts.map(e=>({namespace:mountNamespace(e.logicalPath),mountRef:e})),s=new Set(o.map(e=>e.namespace)),l=t.rootEntries.find(e=>e.name===`extensions`),f=[],p=new Set;if(l?.isDirectory()===!0){let o=await readSortedDirectoryEntries(t.source,i);for(let l of o){if(!l.isDirectory())continue;let o=l.name,u=join(i,o),m=createExtensionNameDiagnostic(o,u);if(m!==null){r.push(m);continue}let h=discoverFlatModuleSource({rootEntries:await readSortedDirectoryEntries(t.source,u),rootPath:u,slotName:`extension`});if(r.push(...h.diagnostics),h.module===void 0){r.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,message:`Extension mount directory "extensions/${o}/" must declare its mount in "extension.ts" (or another supported module extension).`,sourcePath:u}));continue}s.has(o)&&p.add(o),f.push({namespace:o,mountRef:createModuleSourceRef({logicalPath:normalizeLogicalPath(join(`extensions`,o,h.module.logicalPath))}),overridesRoot:u})}}for(let e of p)r.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,message:`Extension namespace "${e}" is claimed by both a file mount ("extensions/${e}.ts") and a directory mount ("extensions/${e}/"). Keep only one.`,sourcePath:i}));return{diagnostics:r,mounts:[...o,...f].filter(e=>!p.has(e.namespace))}}function detectRootNamespaceCollisions(t){if(t.namespaces.length===0)return[];let r=[];for(let i of t.sources){let a=rootContributionName(i.logicalPath),o=t.namespaces.find(e=>a.startsWith(`${e}__`));o!==void 0&&r.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,message:`"${i.logicalPath}" uses the "${o}__" prefix reserved for the mounted extension "${o}". Override an extension's contributions inside its mount directory ("extensions/${o}/…"), not at the agent root.`,sourcePath:join(t.agentRoot,i.logicalPath)}))}return r}function rootContributionName(e){let t=e.slice(e.indexOf(`/`)+1),n=t.split(`/`)[0]??t;for(let e of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(n.toLowerCase().endsWith(e))return n.slice(0,n.length-e.length);return n}async function tryReadPackageJsonName(t,n){try{let r=join(n,`package.json`),i=JSON.parse(await t.readTextFile(r)).name;return typeof i!=`string`||i.length===0?void 0:stripNpmPackageScope(i)}catch{return}}export{detectRootNamespaceCollisions,discoverAgent,discoverExtensionMountDeclarations,resolveExtensionMounts};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join,relative,resolve}from"node:path";import{detectRootNamespaceCollisions,discoverExtensionMountDeclarations,resolveExtensionMounts}from"#discover/discover-agent.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{classifyLocalSubagentEntry,getDirectoryEntryType,getSupportedModuleBaseName,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{createAgentSourceManifest,createLocalSubagentSourceRef,createModuleSourceRef}from"#discover/manifest.js";import{DISCOVER_HOOKS_DIRECTORY_INVALID,DISCOVER_TOOLS_DIRECTORY_INVALID,createHookNameDiagnostic,createToolNameDiagnostic,createUnsupportedRootDirectoryDiagnostics,discoverFlatModuleSource,discoverInstructionsSource,discoverNamedSourceDirectory,readSortedDirectoryEntries}from"#discover/grammar.js";import{discoverConnectionSources}from"#discover/connections.js";import{discoverLibSources}from"#discover/lib.js";import{discoverSandboxSource}from"#discover/sandbox.js";import{discoverSkills}from"#discover/skills.js";const DISCOVER_LOCAL_SUBAGENT_SCHEDULES_INVALID=`discover/local-subagent-schedules-invalid`,DISCOVER_REQUIRED_SUBAGENT_CONFIG_MODULE_MISSING=`discover/required-subagent-config-module-missing`,DISCOVER_SUBAGENTS_DIRECTORY_INVALID=`discover/subagents-directory-invalid`;async function discoverSubagents(r){let i=r.source??createDiskProjectSource(),a=resolve(r.agentRoot),s=resolve(r.subagentsDirectoryPath??join(a,`subagents`)),c=normalizeLogicalPath(r.subagentsLogicalPath??relative(a,s)),f=await i.stat(s);if(f===`missing`)return{diagnostics:[],subagents:[]};if(f!==`directory`)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SUBAGENTS_DIRECTORY_INVALID,message:`Expected "${s}" to be a directory of authored subagents.`,sourcePath:s})],subagents:[]};let p=await readSortedDirectoryEntries(i,s),m=[],h=[];for(let t of p){if(t.isFile()){let n=getSupportedModuleBaseName(t.name);if(n===null)continue;h.push(discoverSingleFileSubagent({agentRoot:a,appRoot:r.appRoot,subagentId:n,subagentLogicalPath:join(c,t.name),subagentPath:join(s,t.name)}));continue}if(!t.isDirectory())continue;let n=await discoverLocalSubagentPackage({appRoot:r.appRoot,source:i,subagentId:t.name,subagentLogicalPath:join(c,t.name),subagentRoot:join(s,t.name)});m.push(...n.diagnostics),h.push(n.subagent)}return{diagnostics:m,subagents:h}}function discoverSingleFileSubagent(e){let t=createModuleSourceRef({logicalPath:e.subagentLogicalPath}),n=createAgentSourceManifest({agentId:e.subagentId,agentRoot:e.agentRoot,appRoot:e.appRoot,configModule:t});return createLocalSubagentSourceRef({entryPath:e.subagentPath,logicalPath:e.subagentLogicalPath,manifest:n,rootPath:e.agentRoot,subagentId:e.subagentId})}async function discoverLocalSubagentPackage(t){let n=[],o=await readSortedDirectoryEntries(t.source,t.subagentRoot);n.push(...createUnsupportedRootDirectoryDiagnostics({classifyEntry:classifyLocalSubagentEntry,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the local subagent root.`},rootEntries:o,rootPath:t.subagentRoot}));let c=await discoverInstructionsSource({required:!1,rootEntries:o,rootPath:t.subagentRoot,source:t.source});n.push(...c.diagnostics);let l=discoverFlatModuleSource({missingDiagnostic:{code:DISCOVER_REQUIRED_SUBAGENT_CONFIG_MODULE_MISSING,message:`Expected one authored subagent config module at "agent.ts", "agent.cts", "agent.mts", "agent.js", "agent.cjs", or "agent.mjs".`},rootEntries:o,rootPath:t.subagentRoot,slotName:`agent`});n.push(...l.diagnostics);let u=await discoverConnectionSources({rootEntries:o,rootPath:t.subagentRoot,source:t.source});n.push(...u.diagnostics);let d=await discoverSandboxSource({rootEntries:o,rootPath:t.subagentRoot,source:t.source});n.push(...d.diagnostics);let m=await discoverNamedSourceDirectory({directoryName:`tools`,invalidDirectoryCode:DISCOVER_TOOLS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(t.subagentRoot,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:o,rootPath:t.subagentRoot,source:t.source,validateSegment:createToolNameDiagnostic});n.push(...m.diagnostics);let g=await discoverNamedSourceDirectory({directoryName:`hooks`,invalidDirectoryCode:DISCOVER_HOOKS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(t.subagentRoot,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:o,rootPath:t.subagentRoot,source:t.source,validateSegment:createHookNameDiagnostic});n.push(...g.diagnostics);let _=await discoverLibSources({agentRoot:t.subagentRoot,rootEntries:o,source:t.source});n.push(..._.diagnostics),n.push(...createLocalSubagentScheduleDiagnostics(t.subagentRoot,o));let v=await discoverSkills({agentRoot:t.subagentRoot,source:t.source});n.push(...v.diagnostics);let y=await discoverSubagents({agentRoot:t.subagentRoot,appRoot:t.appRoot,source:t.source});n.push(...y.diagnostics);let b=await discoverExtensionMountDeclarations({agentRoot:t.subagentRoot,source:t.source});n.push(...b.diagnostics),n.push(...detectRootNamespaceCollisions({agentRoot:t.subagentRoot,namespaces:b.mounts.map(e=>e.namespace),sources:[...m.sources,...u.connections,...v.skills]}));let x=await resolveExtensionMounts({agentRoot:t.subagentRoot,appRoot:t.appRoot,mounts:b.mounts,source:t.source});n.push(...x.diagnostics);let S={agentRoot:t.subagentRoot,appRoot:t.appRoot,connections:u.connections,diagnostics:n,extensions:b.mounts.map(e=>e.mountRef),resolvedExtensions:x.mounts,hooks:g.sources,lib:_.lib,instructions:c.instructions,sandbox:d.sandbox,sandboxWorkspaces:d.sandboxWorkspace===null?[]:[d.sandboxWorkspace],skills:v.skills,tools:m.sources,subagents:y.subagents};l.module!==void 0&&(S.configModule=l.module);let C=createAgentSourceManifest(S);return{diagnostics:n,subagent:createLocalSubagentSourceRef({entryPath:t.subagentRoot,logicalPath:t.subagentLogicalPath,manifest:C,rootPath:t.subagentRoot,subagentId:t.subagentId})}}function createLocalSubagentScheduleDiagnostics(t,n){return n.flatMap(n=>classifyLocalSubagentEntry(n.name,getDirectoryEntryType(n))===`invalid-schedules-directory`?[createDiscoverErrorDiagnostic({code:DISCOVER_LOCAL_SUBAGENT_SCHEDULES_INVALID,message:`Local subagent packages cannot define schedules at "${join(t,n.name)}".`,sourcePath:join(t,n.name)})]:[])}export{DISCOVER_LOCAL_SUBAGENT_SCHEDULES_INVALID,DISCOVER_REQUIRED_SUBAGENT_CONFIG_MODULE_MISSING,DISCOVER_SUBAGENTS_DIRECTORY_INVALID,discoverSubagents};
|
|
1
|
+
import{join,relative,resolve}from"node:path";import{detectRootNamespaceCollisions,discoverExtensionMountDeclarations,resolveExtensionMounts}from"#discover/discover-agent.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{classifyLocalSubagentEntry,getDirectoryEntryType,getSupportedModuleBaseName,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{createAgentSourceManifest,createLocalSubagentSourceRef,createModuleSourceRef}from"#discover/manifest.js";import{DISCOVER_HOOKS_DIRECTORY_INVALID,DISCOVER_TOOLS_DIRECTORY_INVALID,createHookNameDiagnostic,createToolNameDiagnostic,createUnsupportedRootDirectoryDiagnostics,discoverFlatModuleSource,discoverInstructionsSource,discoverNamedSourceDirectory,readSortedDirectoryEntries}from"#discover/grammar.js";import{discoverConnectionSources}from"#discover/connections.js";import{discoverLibSources}from"#discover/lib.js";import{discoverSandboxSource}from"#discover/sandbox.js";import{discoverSkills}from"#discover/skills.js";const DISCOVER_LOCAL_SUBAGENT_SCHEDULES_INVALID=`discover/local-subagent-schedules-invalid`,DISCOVER_REQUIRED_SUBAGENT_CONFIG_MODULE_MISSING=`discover/required-subagent-config-module-missing`,DISCOVER_SUBAGENTS_DIRECTORY_INVALID=`discover/subagents-directory-invalid`;async function discoverSubagents(r){let i=r.source??createDiskProjectSource(),a=resolve(r.agentRoot),s=resolve(r.subagentsDirectoryPath??join(a,`subagents`)),c=normalizeLogicalPath(r.subagentsLogicalPath??relative(a,s)),f=await i.stat(s);if(f===`missing`)return{diagnostics:[],subagents:[]};if(f!==`directory`)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SUBAGENTS_DIRECTORY_INVALID,message:`Expected "${s}" to be a directory of authored subagents.`,sourcePath:s})],subagents:[]};let p=await readSortedDirectoryEntries(i,s),m=[],h=[];for(let t of p){if(t.isFile()){let n=getSupportedModuleBaseName(t.name);if(n===null)continue;h.push(discoverSingleFileSubagent({agentRoot:a,appRoot:r.appRoot,subagentId:n,subagentLogicalPath:join(c,t.name),subagentPath:join(s,t.name)}));continue}if(!t.isDirectory())continue;let n=await discoverLocalSubagentPackage({appRoot:r.appRoot,source:i,subagentId:t.name,subagentLogicalPath:join(c,t.name),subagentRoot:join(s,t.name)});m.push(...n.diagnostics),h.push(n.subagent)}return{diagnostics:m,subagents:h}}function discoverSingleFileSubagent(e){let t=createModuleSourceRef({logicalPath:e.subagentLogicalPath}),n=createAgentSourceManifest({agentId:e.subagentId,agentRoot:e.agentRoot,appRoot:e.appRoot,configModule:t});return createLocalSubagentSourceRef({entryPath:e.subagentPath,logicalPath:e.subagentLogicalPath,manifest:n,rootPath:e.agentRoot,subagentId:e.subagentId})}async function discoverLocalSubagentPackage(t){let n=[],o=await readSortedDirectoryEntries(t.source,t.subagentRoot);n.push(...createUnsupportedRootDirectoryDiagnostics({classifyEntry:classifyLocalSubagentEntry,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the local subagent root.`},rootEntries:o,rootPath:t.subagentRoot}));let c=await discoverInstructionsSource({required:!1,rootEntries:o,rootPath:t.subagentRoot,source:t.source});n.push(...c.diagnostics);let l=discoverFlatModuleSource({missingDiagnostic:{code:DISCOVER_REQUIRED_SUBAGENT_CONFIG_MODULE_MISSING,message:`Expected one authored subagent config module at "agent.ts", "agent.cts", "agent.mts", "agent.js", "agent.cjs", or "agent.mjs".`},rootEntries:o,rootPath:t.subagentRoot,slotName:`agent`});n.push(...l.diagnostics);let u=await discoverConnectionSources({rootEntries:o,rootPath:t.subagentRoot,source:t.source});n.push(...u.diagnostics);let d=await discoverSandboxSource({rootEntries:o,rootPath:t.subagentRoot,source:t.source});n.push(...d.diagnostics);let m=await discoverNamedSourceDirectory({directoryName:`tools`,invalidDirectoryCode:DISCOVER_TOOLS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(t.subagentRoot,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:o,rootPath:t.subagentRoot,source:t.source,validateSegment:createToolNameDiagnostic});n.push(...m.diagnostics);let g=await discoverNamedSourceDirectory({directoryName:`hooks`,invalidDirectoryCode:DISCOVER_HOOKS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(t.subagentRoot,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:o,rootPath:t.subagentRoot,source:t.source,validateSegment:createHookNameDiagnostic});n.push(...g.diagnostics);let _=await discoverLibSources({agentRoot:t.subagentRoot,rootEntries:o,source:t.source});n.push(..._.diagnostics),n.push(...createLocalSubagentScheduleDiagnostics(t.subagentRoot,o));let v=await discoverSkills({agentRoot:t.subagentRoot,source:t.source});n.push(...v.diagnostics);let y=await discoverSubagents({agentRoot:t.subagentRoot,appRoot:t.appRoot,source:t.source});n.push(...y.diagnostics);let b=await discoverExtensionMountDeclarations({agentRoot:t.subagentRoot,source:t.source});n.push(...b.diagnostics),n.push(...detectRootNamespaceCollisions({agentRoot:t.subagentRoot,namespaces:b.mounts.map(e=>e.namespace),sources:[...m.sources,...u.connections,...v.skills,...y.subagents]}));let x=await resolveExtensionMounts({agentRoot:t.subagentRoot,appRoot:t.appRoot,mounts:b.mounts,source:t.source});n.push(...x.diagnostics);let S={agentRoot:t.subagentRoot,appRoot:t.appRoot,connections:u.connections,diagnostics:n,extensions:b.mounts.map(e=>e.mountRef),resolvedExtensions:x.mounts,hooks:g.sources,lib:_.lib,instructions:c.instructions,sandbox:d.sandbox,sandboxWorkspaces:d.sandboxWorkspace===null?[]:[d.sandboxWorkspace],skills:v.skills,tools:m.sources,subagents:y.subagents};l.module!==void 0&&(S.configModule=l.module);let C=createAgentSourceManifest(S);return{diagnostics:n,subagent:createLocalSubagentSourceRef({entryPath:t.subagentRoot,logicalPath:t.subagentLogicalPath,manifest:C,rootPath:t.subagentRoot,subagentId:t.subagentId})}}function createLocalSubagentScheduleDiagnostics(t,n){return n.flatMap(n=>classifyLocalSubagentEntry(n.name,getDirectoryEntryType(n))===`invalid-schedules-directory`?[createDiscoverErrorDiagnostic({code:DISCOVER_LOCAL_SUBAGENT_SCHEDULES_INVALID,message:`Local subagent packages cannot define schedules at "${join(t,n.name)}".`,sourcePath:join(t,n.name)})]:[])}export{DISCOVER_LOCAL_SUBAGENT_SCHEDULES_INVALID,DISCOVER_REQUIRED_SUBAGENT_CONFIG_MODULE_MISSING,DISCOVER_SUBAGENTS_DIRECTORY_INVALID,discoverSubagents};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDurableSessionState}from"#execution/durable-session-store.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{createSession}from"#execution/session.js";import{resolveInheritedTokenLimit}from"#execution/run-session-limits.js";import{resolveEffectiveAgentRuntimeFromConfig}from"#execution/effective-agent-config.js";async function createSessionStep(
|
|
1
|
+
import{createDurableSessionState}from"#execution/durable-session-store.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{createSession}from"#execution/session.js";import{resolveInheritedTokenLimit}from"#execution/run-session-limits.js";import{resolveEffectiveAgentRuntimeFromConfig}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";async function createSessionStep(t){"use step";let n=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(t.compiledArtifactsSource),nodeId:t.nodeId}),r=resolveEffectiveAgentRuntimeFromConfig(n,t.dynamicSubagentAgentConfig),i=t.taskOwned===!0&&isTaskToolAvailable({disabledFrameworkTools:n.resolvedAgent.disabledFrameworkTools??[],hasAuthoredTool:r.turnAgent.tools.some(e=>e.name===TASK_UPDATE_TOOL_NAME),tasksEnabled:n.resolvedAgent.config?.experimental?.tasks===!0,toolName:TASK_UPDATE_TOOL_NAME});return{state:createDurableSessionState({session:createSession({compactionOverrides:{thresholdPercent:r.thresholdPercent},continuationToken:t.continuationToken,limits:{maxInputTokensPerSession:resolveInheritedTokenLimit({configured:r.limits?.maxInputTokensPerSession,inherited:t.inheritedLimits?.maxInputTokensPerSession}),maxOutputTokensPerSession:resolveInheritedTokenLimit({configured:r.limits?.maxOutputTokensPerSession,inherited:t.inheritedLimits?.maxOutputTokensPerSession})},outputSchema:t.outputSchema,rootSessionId:t.rootSessionId,sessionId:t.sessionId,subagentDepth:t.subagentDepth,systemPromptAdditions:i?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:r.turnAgent,workflowMaxSubagents:n.resolvedAgent.workflowTool?.maxSubagents})})}}export{createSessionStep};
|
|
@@ -102,7 +102,7 @@ export declare function prepareRuntimeActionDispatch(input: {
|
|
|
102
102
|
readonly serializedContext: Record<string, unknown>;
|
|
103
103
|
readonly sessionState: DurableSessionState;
|
|
104
104
|
/**
|
|
105
|
-
* Classify
|
|
105
|
+
* Classify task-control calls as
|
|
106
106
|
* task-control plan entries. Only task mode plans them; in plain mode
|
|
107
107
|
* those calls fail as unsupported batch actions.
|
|
108
108
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME,isImplicitAgentToolAvailable}from"#runtime/framework-tools/agent.js";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA}from"#shared/tool-schema.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{createTaskToolHarnessDefinitions,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME,isImplicitAgentToolAvailable}from"#runtime/framework-tools/agent.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel),r=createNodeHarnessTools({node:e.node}),i=getInstrumentationRuntime(),a=createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,clearOnly:e.clearOnly,compactOnly:e.compactOnly,workflow:e.node.agent.workflowTool!==void 0,workflowMaxSubagents:e.workflowMaxSubagents,webSearchProvider:e.node.agent.webSearchProvider,handleEvent:e.handleEvent,instrumentation:i,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,persistentSubagentSessions:e.node.agent.config?.experimental?.tasks===!0||e.node.agent.config?.experimental?.subagentPersistentSessions===!0,dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r});return i===void 0?a:async(e,t)=>{try{return await a(e,t)}finally{await i.forceFlush()}}}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t){return n=>dispatchDynamicModelEvent({ctx:n.ctx,dynamicModel:t,event:n.event,messages:n.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}isImplicitAgentToolAvailable({disabledFrameworkTools:e.node.agent.disabledFrameworkTools,hasAuthoredAgentTool:t.has(AGENT_TOOL_NAME),nodeId:e.node.nodeId})&&t.set(AGENT_TOOL_NAME,{description:AGENT_TOOL_DESCRIPTION,inputSchema:e.node.agent.config?.experimental?.tasks===!0||e.node.agent.config?.experimental?.subagentPersistentSessions===!0?PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA:SUBAGENT_TOOL_INPUT_SCHEMA,name:AGENT_TOOL_NAME,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:AGENT_TOOL_NAME}});let n=e.node.agent.config?.experimental?.tasks===!0;for(let r of createTaskToolHarnessDefinitions())isTaskToolAvailable({disabledFrameworkTools:e.node.agent.disabledFrameworkTools,hasAuthoredTool:t.has(r.name),tasksEnabled:n,toolName:r.name})&&t.set(r.name,r);return t}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`||e.tool.kind===`remote`)return createHarnessDelegationToolDefinition(e.tool);let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(t===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=t.definition,i=r.sourceId.startsWith(`eve:`),o=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({isFrameworkTool:i,rawExecute:o,scope:r.name}),frameworkAction:i&&r.name===LOAD_SKILL_TOOL_NAME?`load-skill`:void 0,inputSchema:r.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:r.name,approval:r.approval,outputSchema:r.outputSchema,toModelOutput:r.toModelOutput}}function resolveAuthoredExecute(e){let{isFrameworkTool:t,rawExecute:n,scope:i}=e;return n===void 0?void 0:t?n:createToolExecuteWithAuth({execute:n,scope:i})}export{buildRuntimeIdentity,createExecutionNodeStep,createNodeHarnessTools};
|
|
@@ -10,6 +10,14 @@ export declare function fireTaskEventCallbackStep(input: {
|
|
|
10
10
|
type: "input.requested";
|
|
11
11
|
}>;
|
|
12
12
|
}): Promise<void>;
|
|
13
|
+
/** Sends one remote task progress update over its existing parent callback. */
|
|
14
|
+
export declare function fireTaskUpdateCallbackStep(input: {
|
|
15
|
+
readonly callback: unknown;
|
|
16
|
+
readonly callId: string;
|
|
17
|
+
readonly childStepIndex: number;
|
|
18
|
+
readonly childTurnId: string;
|
|
19
|
+
readonly message: string;
|
|
20
|
+
}): Promise<string | undefined>;
|
|
13
21
|
/**
|
|
14
22
|
* Sends the configured session terminal callback.
|
|
15
23
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{SESSION_FAILED}from"#harness/agent-handle-errors.js";import{parseSessionCallback}from"#channel/session-callback.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.session-callback`);async function fireTaskEventCallbackStep(e){"use step";let t=parseSerializedSessionCallback(e.callback);if(t.taskId===void 0)return;let n=e.event.type===`input.requested`,r=n?`task.input-requested`:`task.authorization`,i=await postSessionCallbackRequest({body:{callId:t.callId,childContinuationToken:e.childContinuationToken,childSessionId:e.childSessionId,event:n?e.event.data:e.event,kind:r,subagentName:t.subagentName,taskId:t.taskId},url:t.url});if(!i.ok)throw Error(`Task event callback failed with HTTP ${i.status}.`)}async function fireSessionCallbackStep(e){"use step";let i=e.serializedContext[`eve.sessionId`]??``,o=e.serializedContext[SessionCallbackKey.name];if(o!==void 0)try{let t=parseSerializedSessionCallback(o),a=await postSessionCallbackRequest({body:e.status===`completed`?buildCompletedCallbackBody({callback:t,output:e.output,sessionId:i,usage:e.usage}):{callId:t.callId,error:{code:SESSION_FAILED,message:toErrorMessage(e.error)},kind:`session.failed`,sessionId:i,subagentName:t.subagentName,usage:e.usage},url:t.url});if(!a.ok)throw Error(`Session callback failed with HTTP ${a.status}.`)}catch(e){throw log.error(`failed to post session callback`,{error:e,sessionId:i}),e}}function buildCompletedCallbackBody(e){let t={callId:e.callback.callId,kind:`session.completed`,output:e.output??``,sessionId:e.sessionId,subagentName:e.callback.subagentName};return e.usage===void 0?t:{...t,usage:e.usage}}function parseSerializedSessionCallback(e){let t=parseSessionCallback(e);if(!t.ok)throw Error(`Serialized session callback is invalid.`,{cause:t.cause});return t.callback}export{fireSessionCallbackStep,fireTaskEventCallbackStep};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{SESSION_FAILED}from"#harness/agent-handle-errors.js";import{parseSessionCallback}from"#channel/session-callback.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";const log=createLogger(`execution.session-callback`);async function fireTaskEventCallbackStep(e){"use step";let t=parseSerializedSessionCallback(e.callback);if(t.taskId===void 0)return;let n=e.event.type===`input.requested`,r=n?`task.input-requested`:`task.authorization`,i=await postSessionCallbackRequest({body:{callId:t.callId,childContinuationToken:e.childContinuationToken,childSessionId:e.childSessionId,event:n?e.event.data:e.event,kind:r,subagentName:t.subagentName,taskId:t.taskId},url:t.url});if(!i.ok)throw Error(`Task event callback failed with HTTP ${i.status}.`)}async function fireTaskUpdateCallbackStep(e){"use step";let t=parseSerializedSessionCallback(e.callback);if(t.taskId===void 0)return;let n=await postSessionCallbackRequest({body:{callId:e.callId,childStepIndex:e.childStepIndex,childTurnId:e.childTurnId,kind:`task.update`,message:e.message,taskId:t.taskId},url:t.url});if(!n.ok)throw Error(`Task update callback failed with HTTP ${n.status}.`);return t.taskId}async function fireSessionCallbackStep(e){"use step";let i=e.serializedContext[`eve.sessionId`]??``,o=e.serializedContext[SessionCallbackKey.name];if(o!==void 0)try{let t=parseSerializedSessionCallback(o),a=await postSessionCallbackRequest({body:e.status===`completed`?buildCompletedCallbackBody({callback:t,output:e.output,sessionId:i,usage:e.usage}):{callId:t.callId,error:{code:SESSION_FAILED,message:toErrorMessage(e.error)},kind:`session.failed`,sessionId:i,subagentName:t.subagentName,usage:e.usage},url:t.url});if(!a.ok)throw Error(`Session callback failed with HTTP ${a.status}.`)}catch(e){throw log.error(`failed to post session callback`,{error:e,sessionId:i}),e}}function buildCompletedCallbackBody(e){let t={callId:e.callback.callId,kind:`session.completed`,output:e.output??``,sessionId:e.sessionId,subagentName:e.callback.subagentName};return e.usage===void 0?t:{...t,usage:e.usage}}function parseSerializedSessionCallback(e){let t=parseSessionCallback(e);if(!t.ok)throw Error(`Serialized session callback is invalid.`,{cause:t.cause});return t.callback}export{fireSessionCallbackStep,fireTaskEventCallbackStep,fireTaskUpdateCallbackStep};
|
|
@@ -46,6 +46,7 @@ export interface CreateSessionInput {
|
|
|
46
46
|
readonly limits?: AuthoredSessionLimits;
|
|
47
47
|
readonly outputSchema?: HarnessSession["outputSchema"];
|
|
48
48
|
readonly subagentDepth?: number;
|
|
49
|
+
readonly systemPromptAdditions?: readonly string[];
|
|
49
50
|
readonly workflowMaxSubagents?: number;
|
|
50
51
|
}
|
|
51
52
|
/** Creates a fresh {@link HarnessSession} from the current `turnAgent`. */
|
|
@@ -57,6 +58,7 @@ export declare function createSession(input: CreateSessionInput): HarnessSession
|
|
|
57
58
|
*/
|
|
58
59
|
export declare function refreshSessionFromTurnAgent(input: {
|
|
59
60
|
readonly session: HarnessSession;
|
|
61
|
+
readonly systemPromptAdditions?: readonly string[];
|
|
60
62
|
readonly turnAgent: RuntimeTurnAgent;
|
|
61
63
|
readonly compactionOverrides?: {
|
|
62
64
|
readonly thresholdPercent?: number;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{formatAvailableSkillsSection}from"#execution/skills/instructions.js";const DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION=4e7;function createCompactionConfig(e={}){let t=e.thresholdPercent??.9,n={recentWindowSize:10,threshold:e.contextWindowTokens===void 0?1e5:Math.max(1,Math.floor(e.contextWindowTokens*t)),thresholdPercent:t};return e.lastKnownInputTokens===void 0?n:{...n,lastKnownInputTokens:e.lastKnownInputTokens,lastKnownPromptMessageCount:e.lastKnownPromptMessageCount}}function createSession(e){let{turnAgent:t}=e,n=createSessionToolDefinitions(t),r={agent:createSessionAgent(t,createSessionSystemPrompt({turnAgent:t}),n),compaction:createCompactionConfig({contextWindowTokens:t.model?.contextWindowTokens,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:e.continuationToken,history:[...t.initialMessages??[]],sessionId:e.sessionId};return e.rootSessionId!==void 0&&(r.rootSessionId=e.rootSessionId),r.limits=resolveSessionLimits(e),e.outputSchema!==void 0&&(r.outputSchema=e.outputSchema),e.subagentDepth!==void 0&&(r.subagentDepth=e.subagentDepth),e.workflowMaxSubagents!==void 0&&(r.workflowMaxSubagents=e.workflowMaxSubagents),r}function createSessionAgent(e,t,n){let r={compactionModelReference:e.compactionModel,reasoning:e.reasoning,system:t,tools:n};if(e.model!==void 0)return{...r,modelReference:e.model};if(e.dynamicModel!==void 0)return{...r,dynamicModel:!0};throw Error(`Cannot create a session before dynamic subagent config is selected.`)}function refreshSessionFromTurnAgent(e){return{...e.session,agent:createSessionAgent(e.turnAgent,createSessionSystemPrompt({turnAgent:e.turnAgent}),createSessionToolDefinitions(e.turnAgent)),compaction:createCompactionConfig({contextWindowTokens:e.turnAgent.model?.contextWindowTokens,lastKnownInputTokens:e.session.compaction.lastKnownInputTokens,lastKnownPromptMessageCount:e.session.compaction.lastKnownPromptMessageCount,thresholdPercent:e.compactionOverrides?.thresholdPercent})}}function createSessionSystemPrompt(t){let n=formatAvailableSkillsSection(t.turnAgent.availableSkills??[]);return
|
|
1
|
+
import{formatAvailableSkillsSection}from"#execution/skills/instructions.js";const DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION=4e7;function createCompactionConfig(e={}){let t=e.thresholdPercent??.9,n={recentWindowSize:10,threshold:e.contextWindowTokens===void 0?1e5:Math.max(1,Math.floor(e.contextWindowTokens*t)),thresholdPercent:t};return e.lastKnownInputTokens===void 0?n:{...n,lastKnownInputTokens:e.lastKnownInputTokens,lastKnownPromptMessageCount:e.lastKnownPromptMessageCount}}function createSession(e){let{turnAgent:t}=e,n=createSessionToolDefinitions(t),r={agent:createSessionAgent(t,createSessionSystemPrompt({additions:e.systemPromptAdditions,turnAgent:t}),n),compaction:createCompactionConfig({contextWindowTokens:t.model?.contextWindowTokens,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:e.continuationToken,history:[...t.initialMessages??[]],sessionId:e.sessionId};return e.rootSessionId!==void 0&&(r.rootSessionId=e.rootSessionId),r.limits=resolveSessionLimits(e),e.outputSchema!==void 0&&(r.outputSchema=e.outputSchema),e.subagentDepth!==void 0&&(r.subagentDepth=e.subagentDepth),e.workflowMaxSubagents!==void 0&&(r.workflowMaxSubagents=e.workflowMaxSubagents),r}function createSessionAgent(e,t,n){let r={compactionModelReference:e.compactionModel,reasoning:e.reasoning,system:t,tools:n};if(e.model!==void 0)return{...r,modelReference:e.model};if(e.dynamicModel!==void 0)return{...r,dynamicModel:!0};throw Error(`Cannot create a session before dynamic subagent config is selected.`)}function refreshSessionFromTurnAgent(e){return{...e.session,agent:createSessionAgent(e.turnAgent,createSessionSystemPrompt({additions:e.systemPromptAdditions,turnAgent:e.turnAgent}),createSessionToolDefinitions(e.turnAgent)),compaction:createCompactionConfig({contextWindowTokens:e.turnAgent.model?.contextWindowTokens,lastKnownInputTokens:e.session.compaction.lastKnownInputTokens,lastKnownPromptMessageCount:e.session.compaction.lastKnownPromptMessageCount,thresholdPercent:e.compactionOverrides?.thresholdPercent})}}function createSessionSystemPrompt(t){let n=formatAvailableSkillsSection(t.turnAgent.availableSkills??[]);return[...n===null?t.turnAgent.instructions:[...t.turnAgent.instructions,n],...t.additions??[]].join(`
|
|
2
2
|
|
|
3
3
|
`)}function mintSubagentContinuationToken(e){return`subagent:${e??crypto.randomUUID()}`}function projectToDurableSession(e){let t={agent:{system:e.agent.system},continuationToken:e.continuationToken,history:e.history,sessionId:e.sessionId};return(e.compaction.lastKnownInputTokens!==void 0||e.compaction.lastKnownPromptMessageCount!==void 0)&&(t.compaction={lastKnownInputTokens:e.compaction.lastKnownInputTokens,lastKnownPromptMessageCount:e.compaction.lastKnownPromptMessageCount}),e.rootSessionId!==void 0&&(t.rootSessionId=e.rootSessionId),e.limits!==void 0&&(t.limits=e.limits),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.sandboxState!==void 0&&(t.sandboxState=e.sandboxState),e.state!==void 0&&(t.state=e.state),e.subagentDepth!==void 0&&(t.subagentDepth=e.subagentDepth),e.workflowMaxSubagents!==void 0&&(t.workflowMaxSubagents=e.workflowMaxSubagents),t}function hydrateDurableSession(e){let{durable:t,turnAgent:n}=e,r=createSessionToolDefinitions(n),i={agent:createSessionAgent(n,t.agent.system,r),compaction:createCompactionConfig({contextWindowTokens:n.model?.contextWindowTokens,lastKnownInputTokens:t.compaction?.lastKnownInputTokens,lastKnownPromptMessageCount:t.compaction?.lastKnownPromptMessageCount,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:t.continuationToken,history:t.history,sessionId:t.sessionId};return t.rootSessionId!==void 0&&(i.rootSessionId=t.rootSessionId),t.limits!==void 0&&(i.limits=t.limits),t.outputSchema!==void 0&&(i.outputSchema=t.outputSchema),t.sandboxState!==void 0&&(i.sandboxState=t.sandboxState),t.state!==void 0&&(i.state=t.state),t.subagentDepth!==void 0&&(i.subagentDepth=t.subagentDepth),t.workflowMaxSubagents!==void 0&&(i.workflowMaxSubagents=t.workflowMaxSubagents),i}function createSessionToolDefinitions(e){return e.tools.map(e=>({description:e.description??``,inputSchema:e.inputSchema,name:e.name,outputSchema:e.outputSchema}))}function resolveSessionLimits(e){let n=e.subagentDepth!==void 0&&e.subagentDepth>0,r=resolveSessionTokenLimit({authored:e.limits?.maxInputTokensPerSession,fallback:n?void 0:DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION}),i=resolveSessionTokenLimit({authored:e.limits?.maxOutputTokensPerSession,fallback:void 0}),a={};return r!==void 0&&(a.maxInputTokensPerSession=r),i!==void 0&&(a.maxOutputTokensPerSession=i),a}function resolveSessionTokenLimit(e){return e.authored===!1?void 0:e.authored??e.fallback}export{DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION,createCompactionConfig,createSession,hydrateDurableSession,mintSubagentContinuationToken,projectToDurableSession,refreshSessionFromTurnAgent};
|
|
@@ -4,10 +4,9 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
|
4
4
|
* Forwards one task child's blocking transition to its parent's session
|
|
5
5
|
* callback.
|
|
6
6
|
*
|
|
7
|
-
* Task children report HITL and authorization transitions to the
|
|
8
|
-
* task run
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* blocking transitions.
|
|
7
|
+
* Task children report HITL and authorization transitions exclusively to the
|
|
8
|
+
* parent's task run, so the run can block/unblock the task under one durable
|
|
9
|
+
* decision and only the parent channel owns the interaction. Returns whether
|
|
10
|
+
* the event was forwarded and must therefore be suppressed locally.
|
|
12
11
|
*/
|
|
13
|
-
export declare function forwardTaskEventToSessionCallback(ctx: ContextContainer, event: UnstampedMessageStreamEvent): Promise<
|
|
12
|
+
export declare function forwardTaskEventToSessionCallback(ctx: ContextContainer, event: UnstampedMessageStreamEvent): Promise<boolean>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ContinuationTokenKey,SessionCallbackKey,SessionIdKey}from"#context/keys.js";import{fireTaskEventCallbackStep}from"#execution/session-callback-step.js";async function forwardTaskEventToSessionCallback(e,t){let n=e.get(SessionCallbackKey);n
|
|
1
|
+
import{ContinuationTokenKey,SessionCallbackKey,SessionIdKey}from"#context/keys.js";import{fireTaskEventCallbackStep}from"#execution/session-callback-step.js";async function forwardTaskEventToSessionCallback(e,t){let n=e.get(SessionCallbackKey);return n?.taskId===void 0||t.type!==`input.requested`&&t.type!==`authorization.required`&&t.type!==`authorization.completed`?!1:(await fireTaskEventCallbackStep({callback:n,childContinuationToken:e.require(ContinuationTokenKey),childSessionId:e.require(SessionIdKey),event:t}),!0)}export{forwardTaskEventToSessionCallback};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare const TASK_UPDATE_SESSION_INSTRUCTION = "Background task updates\nYou are running as a background task. For multi-step work, use `task_update` at meaningful milestones to briefly state what you are currently doing. Keep updates terse and activity-focused; do not include preliminary findings or results. Do not wait for a response, and return your final result normally.";
|
|
2
|
+
/** True when the serialized caller binding points at a durable task inbox. */
|
|
3
|
+
export declare function isTaskOwnedSerializedContext(serializedContext: Record<string, unknown>): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readTaskIdFromInboxToken}from"#tasks/task-inbox-token.js";const TASK_UPDATE_SESSION_INSTRUCTION="Background task updates\nYou are running as a background task. For multi-step work, use `task_update` at meaningful milestones to briefly state what you are currently doing. Keep updates terse and activity-focused; do not include preliminary findings or results. Do not wait for a response, and return your final result normally.";function isTaskOwnedSerializedContext(e){let t=e[`eve.sessionCallback`];if(typeof t==`object`&&t&&typeof Reflect.get(t,`taskId`)==`string`)return!0;let n=e[`eve.channel`];if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,`state`);if(typeof r!=`object`||!r)return!1;let i=Reflect.get(r,`parentContinuationToken`);return typeof i==`string`&&readTaskIdFromInboxToken(i)!==void 0}export{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type TaskInboundAnswerInput, type TaskInboundAuthorizationEvent, type TaskInboundInputRequest, type TaskView } from "#tasks/types.js";
|
|
1
|
+
import { type TaskInboundAnswerInput, type TaskInboundAuthorizationEvent, type TaskInboundInputRequest, type TaskInboundUpdate, type TaskView } from "#tasks/types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Appends one full task view to the owning task run's `eve.task`
|
|
4
4
|
* stream. Only the task run workflow calls this, which is what makes
|
|
@@ -25,6 +25,12 @@ export declare function wakeTaskParentStep(input: {
|
|
|
25
25
|
readonly token: string;
|
|
26
26
|
readonly view: TaskView;
|
|
27
27
|
}): Promise<void>;
|
|
28
|
+
/** Forwards a running child's intermediate update to its parent session. */
|
|
29
|
+
export declare function wakeTaskUpdateParentStep(input: {
|
|
30
|
+
readonly token: string;
|
|
31
|
+
readonly update: TaskInboundUpdate;
|
|
32
|
+
readonly view: TaskView;
|
|
33
|
+
}): Promise<void>;
|
|
28
34
|
/** Sends an exact local-task HITL batch to the parent's pre-model router. */
|
|
29
35
|
export declare function wakeTaskInputRequestParentStep(input: {
|
|
30
36
|
readonly request: TaskInboundInputRequest;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resumeHook}from"#internal/workflow/runtime.js";import{getWritable}from"#compiled/@workflow/core/index.js";import{isTaskWorkflowTargetGone}from"#execution/tasks/workflow-target.js";import{TASK_VIEW_STREAM_NAMESPACE,isTerminalTaskStatus,taskAuthorizationRequestId}from"#tasks/types.js";const log=createLogger(`execution.tasks.run`);async function appendTaskViewStep(e){"use step";let t=getWritable({namespace:TASK_VIEW_STREAM_NAMESPACE}).getWriter();try{await t.write(e.view)}finally{t.releaseLock()}}async function wakeTaskAuthorizationParentStep(e){"use step";let n={callId:e.request.callId,childSessionId:e.request.childSessionId,event:e.request.event,kind:`subagent-authorization-event`,subagentName:e.request.subagentName},r=e.request.event.data,i={task:{authorizationEvents:[{hookPayload:n,taskId:e.taskId}]}};e.request.event.type===`authorization.required`&&(i.message=`Background task ${e.taskId} needs authorization.`);let a={kind:`send`,payload:i,taskDeliveryId:`${e.taskId}:authorization:${e.request.event.type}:${r.turnId}:${r.stepIndex}:${r.sequence}:${taskAuthorizationRequestId(e.request.event)}`};try{await resumeHook(e.token,a)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function wakeTaskParentStep(e){"use step";let n={message:formatTaskNotification(e.view)};isTerminalTaskStatus(e.view.status)&&(n.task={views:[e.view]});let r={kind:`send`,payload:n,taskDeliveryId:`${e.view.taskId}:ready:${e.view.status}`};try{await resumeHook(e.token,r)}catch(t){if(isTaskWorkflowTargetGone(t)){log.warn(`task wake target is gone; the parent session already ended`,{status:e.view.status,taskId:e.view.taskId});return}throw t}}async function wakeTaskInputRequestParentStep(e){"use step";let n={kind:`send`,payload:{task:{inputRequests:[{hookPayload:e.request,taskId:e.taskId}]}},taskDeliveryId:`${e.taskId}:input:${e.request.event.turnId}:${e.request.event.stepIndex}:${e.request.event.sequence}`};try{await resumeHook(e.token,n)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function deliverTaskInputResponsesStep(e){"use step";let n=new Set(e.requestIds),r={auth:e.answer.auth,kind:`send`,payload:{inputResponses:e.answer.inputResponses.filter(e=>n.has(e.requestId))},taskDeliveryId:`${e.answer.taskId}:${[...e.requestIds].sort().join(`,`)}`};try{if(e.answer.childResponseUrl!==void 0){let t=await fetch(e.answer.childResponseUrl,{body:JSON.stringify({inputResponses:r.payload.inputResponses}),headers:{"content-type":`application/json`},method:`POST`,redirect:`error`});if(t.status===404)return`unreachable`;if(!t.ok)throw Error(`Remote task input delivery failed with HTTP ${t.status}.`)}else await resumeHook(e.answer.childContinuationToken,r);return`delivered`}catch(t){if(isTaskWorkflowTargetGone(t))return log.warn(`task input answer target is gone; the child turn already ended`,{taskId:e.answer.taskId}),`unreachable`;throw t}}function formatTaskNotification(e){let t=`Background task ${e.taskId} (${e.metadata.name})`;return e.status===`input_required`?`${t} needs input. Use task_peek to inspect the outstanding requests.`:`${t} is ${e.status}. Use task_peek to read its output.`}export{appendTaskViewStep,deliverTaskInputResponsesStep,wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resumeHook}from"#internal/workflow/runtime.js";import{getWritable}from"#compiled/@workflow/core/index.js";import{isTaskWorkflowTargetGone}from"#execution/tasks/workflow-target.js";import{TASK_VIEW_STREAM_NAMESPACE,isTerminalTaskStatus,taskAuthorizationRequestId}from"#tasks/types.js";const log=createLogger(`execution.tasks.run`);async function appendTaskViewStep(e){"use step";let t=getWritable({namespace:TASK_VIEW_STREAM_NAMESPACE}).getWriter();try{await t.write(e.view)}finally{t.releaseLock()}}async function wakeTaskAuthorizationParentStep(e){"use step";let n={callId:e.request.callId,childSessionId:e.request.childSessionId,event:e.request.event,kind:`subagent-authorization-event`,subagentName:e.request.subagentName},r=e.request.event.data,i={task:{authorizationEvents:[{hookPayload:n,taskId:e.taskId}]}};e.request.event.type===`authorization.required`&&(i.message=`Background task ${e.taskId} needs authorization.`);let a={kind:`send`,payload:i,taskDeliveryId:`${e.taskId}:authorization:${e.request.event.type}:${r.turnId}:${r.stepIndex}:${r.sequence}:${taskAuthorizationRequestId(e.request.event)}`};try{await resumeHook(e.token,a)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function wakeTaskParentStep(e){"use step";let n={message:formatTaskNotification(e.view)};isTerminalTaskStatus(e.view.status)&&(n.task={views:[e.view]});let r={kind:`send`,payload:n,taskDeliveryId:`${e.view.taskId}:ready:${e.view.status}`};try{await resumeHook(e.token,r)}catch(t){if(isTaskWorkflowTargetGone(t)){log.warn(`task wake target is gone; the parent session already ended`,{status:e.view.status,taskId:e.view.taskId});return}throw t}}async function wakeTaskUpdateParentStep(e){"use step";let n={kind:`send`,payload:{message:`Background task ${e.view.taskId} (${e.view.metadata.name}) update: ${e.update.message}`},taskDeliveryId:`${e.view.taskId}:update:${e.update.childTurnId}:${e.update.childStepIndex}:${e.update.callId}`};try{await resumeHook(e.token,n)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function wakeTaskInputRequestParentStep(e){"use step";let n={kind:`send`,payload:{task:{inputRequests:[{hookPayload:e.request,taskId:e.taskId}]}},taskDeliveryId:`${e.taskId}:input:${e.request.event.turnId}:${e.request.event.stepIndex}:${e.request.event.sequence}`};try{await resumeHook(e.token,n)}catch(e){if(isTaskWorkflowTargetGone(e))return;throw e}}async function deliverTaskInputResponsesStep(e){"use step";let n=new Set(e.requestIds),r={auth:e.answer.auth,kind:`send`,payload:{inputResponses:e.answer.inputResponses.filter(e=>n.has(e.requestId))},taskDeliveryId:`${e.answer.taskId}:${[...e.requestIds].sort().join(`,`)}`};try{if(e.answer.childResponseUrl!==void 0){let t=await fetch(e.answer.childResponseUrl,{body:JSON.stringify({inputResponses:r.payload.inputResponses}),headers:{"content-type":`application/json`},method:`POST`,redirect:`error`});if(t.status===404)return`unreachable`;if(!t.ok)throw Error(`Remote task input delivery failed with HTTP ${t.status}.`)}else await resumeHook(e.answer.childContinuationToken,r);return`delivered`}catch(t){if(isTaskWorkflowTargetGone(t))return log.warn(`task input answer target is gone; the child turn already ended`,{taskId:e.answer.taskId}),`unreachable`;throw t}}function formatTaskNotification(e){let t=`Background task ${e.taskId} (${e.metadata.name})`;return e.status===`input_required`?`${t} needs input. Use task_peek to inspect the outstanding requests.`:`${t} is ${e.status}. Use task_peek to read its output.`}export{appendTaskViewStep,deliverTaskInputResponsesStep,wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep,wakeTaskUpdateParentStep};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ChannelAdapter } from "#channel/adapter.js";
|
|
2
|
+
import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
|
|
3
|
+
/** Sends one child-authored progress update over its existing parent transport. */
|
|
4
|
+
export declare function executeTaskUpdate(input: {
|
|
5
|
+
readonly action: RuntimeToolCallActionRequest;
|
|
6
|
+
readonly adapter: ChannelAdapter | undefined;
|
|
7
|
+
readonly childStepIndex: number;
|
|
8
|
+
readonly childTurnId: string;
|
|
9
|
+
readonly serializedContext: Record<string, unknown> | undefined;
|
|
10
|
+
}): Promise<RuntimeActionResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SessionCallbackKey}from"#context/keys.js";import{readTaskIdFromInboxToken}from"#tasks/task-id.js";import{SUBAGENT_ADAPTER_KIND,isSubagentAdapterState}from"#execution/subagent-adapter-state.js";import{resumeHook}from"#internal/workflow/runtime.js";import{fireTaskUpdateCallbackStep}from"#execution/session-callback-step.js";import{createTaskControlError}from"#execution/tasks/parent/control-shared.js";async function executeTaskUpdate(n){let r=readUpdateMessage(n.action.input);if(r===void 0)return createTaskControlError(n.action,"Provide a non-empty `message`.");let i=n.serializedContext?.[SessionCallbackKey.name];if(i!==void 0){let e=await fireTaskUpdateCallbackStep({callback:i,callId:n.action.callId,childStepIndex:n.childStepIndex,childTurnId:n.childTurnId,message:r});return e===void 0?createTaskControlError(n.action,`This session is not owned by a parent task.`):createTaskUpdateResult(n.action,e)}let a=n.adapter;if(a?.kind!==SUBAGENT_ADAPTER_KIND||!isSubagentAdapterState(a.state))return createTaskControlError(n.action,`This session is not owned by a parent task.`);let o=a.state.parentContinuationToken,s=readTaskIdFromInboxToken(o);return s===void 0?createTaskControlError(n.action,`This session is not owned by a parent task.`):(await resumeHook(o,{callId:n.action.callId,childStepIndex:n.childStepIndex,childTurnId:n.childTurnId,kind:`task-update`,message:r}),createTaskUpdateResult(n.action,s))}function readUpdateMessage(e){return typeof e.message==`string`&&e.message.trim()!==``?e.message:void 0}function createTaskUpdateResult(e,t){return{callId:e.callId,kind:`tool-result`,output:{status:`sent`,taskId:t},toolName:e.toolName}}export{executeTaskUpdate};
|
|
@@ -19,9 +19,9 @@ export interface TaskRunWorkflowInput {
|
|
|
19
19
|
* change nothing.
|
|
20
20
|
*
|
|
21
21
|
* Wake policy: a transition into a ready status — terminal or
|
|
22
|
-
* `input_required` —
|
|
23
|
-
* session. A parked parent starts
|
|
24
|
-
* delivery at its next safe boundary.
|
|
22
|
+
* `input_required` — and an explicit child `task_update` deliver a
|
|
23
|
+
* framework notification to the parent session. A parked parent starts
|
|
24
|
+
* a turn; an active turn observes the delivery at its next safe boundary.
|
|
25
25
|
*
|
|
26
26
|
* The run ends when the task reaches a terminal status. Its view
|
|
27
27
|
* stream stays readable, so terminal tasks remain peekable; the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{isReadyTaskStatus,isTerminalTaskStatus,readTaskInputRequestId,readTaskUsage}from"#tasks/types.js";import{appendTaskViewStep,deliverTaskInputResponsesStep,wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep}from"#execution/tasks/child/steps.js";import{applyTaskTransition}from"#tasks/transitions.js";import{translateTaskInboundPayload}from"#tasks/wire.js";function isTaskRunFinished(e,t){return!isTerminalTaskStatus(e.status)||!t?!1:e.status!==`cancelled`||e.executor?.lifecycle===`terminal`}async function taskRunWorkflow(i){"use workflow";let a=createHook({token:i.taskInboxToken}),o=a[Symbol.asyncIterator](),s=!1;try{try{await claimHookOwnership(a),s=!0}catch(e){if(isHookConflictError(e))return;throw e}let e=i.initialView,n,c=[],l=!1;for(await appendTaskViewStep({view:e});!isTaskRunFinished(e,
|
|
1
|
+
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{isReadyTaskStatus,isTerminalTaskStatus,readTaskInputRequestId,readTaskUsage}from"#tasks/types.js";import{appendTaskViewStep,deliverTaskInputResponsesStep,wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep,wakeTaskUpdateParentStep}from"#execution/tasks/child/steps.js";import{applyTaskTransition}from"#tasks/transitions.js";import{translateTaskInboundPayload}from"#tasks/wire.js";function isTaskRunFinished(e,t){return!isTerminalTaskStatus(e.status)||!t?!1:e.status!==`cancelled`||e.executor?.lifecycle===`terminal`}async function taskRunWorkflow(i){"use workflow";let a=createHook({token:i.taskInboxToken}),o=a[Symbol.asyncIterator](),s=!1;try{try{await claimHookOwnership(a),s=!0}catch(e){if(isHookConflictError(e))return;throw e}let e=i.initialView,n,c=[],l=[],u=!1;for(await appendTaskViewStep({view:e});!isTaskRunFinished(e,u);){let t=await o.next();if(t.done===!0)return;let r=t.value.kind===`subagent-authorization-event`?{...t.value,kind:`authorization-event`}:t.value;if(r.kind===`authorization-event`&&(r.event.type===`approval.candidate`||r.event.type===`approval.settled`))continue;let a=r.kind===`task-command`&&r.command.kind===`ready`,s=r.kind===`task-command`&&r.command.kind===`reject-dispatch`;if((a||s)&&(u=!0),r.kind===`subagent-input-request`&&(n=r),r.kind===`authorization-event`&&c.push(r),r.kind===`task-update`){u&&!isTerminalTaskStatus(e.status)?await wakeTaskUpdateParentStep({token:i.parentContinuationToken,update:r,view:e}):l.push(r);continue}let d=e.status===`cancelled`&&r.kind===`runtime-action-result`,f=r.kind===`input-response`,p;if(d)p={kind:`settle-executor`,usage:readTaskUsage(r.results[0]?.outcome?.usageDelta)};else if(f){if(e.status!==`input_required`)continue;p=await resolveAnsweredCommand(e,r)}else p=translateTaskInboundPayload(r);if(p===void 0)continue;if(a&&isTerminalTaskStatus(e.status)){for(let t of l)await wakeTaskUpdateParentStep({token:i.parentContinuationToken,update:t,view:e});l=[],await wakeTaskParentStep({token:i.parentContinuationToken,view:e});continue}let m=applyTaskTransition(e,p);if(m.outcome!==`accepted`)continue;let h=!isTerminalTaskStatus(e.status)&&isTerminalTaskStatus(m.view.status),g=!isReadyTaskStatus(e.status)&&isReadyTaskStatus(m.view.status);e=m.view,await appendTaskViewStep({view:e});let _=u&&!h?c:[];for(let t of _)await wakeTaskAuthorizationParentStep({request:t,taskId:e.taskId,token:i.parentContinuationToken});if(u&&l.length>0&&!isTerminalTaskStatus(e.status)){for(let t of l)await wakeTaskUpdateParentStep({token:i.parentContinuationToken,update:t,view:e});l=[]}(h||_.length>0)&&(c=[]),n!==void 0&&u&&e.status===`input_required`?(await wakeTaskInputRequestParentStep({request:n,taskId:e.taskId,token:i.parentContinuationToken}),n=void 0):!s&&_.length===0&&u&&(h||g&&n===void 0)&&await wakeTaskParentStep({token:i.parentContinuationToken,view:e}),e.status!==`input_required`&&(n=void 0)}}finally{s&&await disposeHook(a)}}async function resolveAnsweredCommand(e,t){if(t.taskId!==e.taskId)return;let n=new Set(e.inputRequests.flatMap(e=>{let t=readTaskInputRequestId(e);return t===void 0?[]:[t]})),r=t.inputResponses.map(e=>e.requestId).filter(e=>n.has(e));return r.length===0?void 0:await deliverTaskInputResponsesStep({answer:t,requestIds:r})===`delivered`?{kind:`answered`,requestIds:r}:void 0}export{taskRunWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatAgentStatus,getAgentHandleStore}from"#harness/handles/store.js";import{getSessionTaskIndex}from"#tasks/session-index.js";import{
|
|
1
|
+
import{formatAgentStatus,getAgentHandleStore}from"#harness/handles/store.js";import{getSessionTaskIndex}from"#tasks/session-index.js";import{readTaskViews}from"#execution/tasks/parent/control-shared.js";import{resolveAgentsAnnouncement}from"#harness/handles/prompt.js";async function readTaskAgentViews(i){let a=(getAgentHandleStore(i.state)?.handles??[]).filter(e=>e.phase===`addressed`);if(a.length===0)return[];let o=await readTaskViews(getSessionTaskIndex(i.state)),s=new Map;for(let e of o){let t=s.get(e.metadata.agentId)??[];s.set(e.metadata.agentId,[...t,e])}return a.map(t=>{let n=s.get(t.identity.id)??[],r=n.filter(e=>e.status===`working`||e.status===`input_required`);if(r.length>1)throw Error(`Agent "${t.identity.id}" has more than one nonterminal task.`);let i=r[0];if(i!==void 0){let e=i.status===`input_required`?`input_required`:`working`;return{availability:`busy`,id:t.identity.id,name:t.identity.name,taskId:i.taskId,taskStatus:e}}let a=n.at(-1);return{availability:`available`,id:t.identity.id,name:t.identity.name,statusLine:a?.lastOutput===void 0?void 0:formatAgentStatus(a.lastOutput.data)}})}async function appendTaskAgentAnnouncement(e){let n=resolveAgentsAnnouncement({agentViews:await readTaskAgentViews(e),messages:e.history,store:getAgentHandleStore(e.state)});return n===void 0?e:{...e,history:[...e.history,{content:n,role:`user`}]}}export{appendTaskAgentAnnouncement,readTaskAgentViews};
|
|
@@ -6,7 +6,7 @@ import type { TaskView } from "#tasks/types.js";
|
|
|
6
6
|
/**
|
|
7
7
|
* Result and lookup helpers shared by the task-control executors
|
|
8
8
|
* (`task_peek`/`task_cancel` in the dispatch module,
|
|
9
|
-
*
|
|
9
|
+
* task controls in their own).
|
|
10
10
|
*/
|
|
11
11
|
/** Resolves owned index entries, or the ids this session does not own. */
|
|
12
12
|
export declare function lookupTaskEntries(session: RuntimeSession, taskIds: readonly string[]): {
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* parent turn inbox, and every start dispatches a conversation-mode
|
|
12
12
|
* (persistent) child so the background task stays resumable.
|
|
13
13
|
*
|
|
14
|
-
* Task-control calls (`task_peek` / `task_cancel` / `
|
|
14
|
+
* Task-control calls (`task_peek` / `task_cancel` / `task_update`) execute
|
|
15
15
|
* inline in this step, which holds the session ownership index and world
|
|
16
16
|
* access they need.
|
|
17
17
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDurableSessionState}from"#execution/durable-session-store.js";import{dispatchToTaskAgentAddress}from"#execution/agent-handle-dispatch.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{emitSubagentCalled,prepareRuntimeActionDispatch,startSubagent}from"#execution/dispatch-runtime-actions-shared.js";import{beginDelegatedTask,settleDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{checkTaskContinuationAvailability,describeTaskDispatch,persistContinuationTaskInParentSession,settleTaskDispatchError}from"#execution/tasks/parent/continuation-dispatch.js";async function dispatchTaskStep(r){"use step";let i=await prepareRuntimeActionDispatch({serializedContext:r.serializedContext,sessionState:r.sessionState,taskControls:!0});if(i===void 0)return{results:[],sessionState:r.sessionState,pendingTasks:[]};let{batch:a,bundle:o,session:s}=i,c=r.parentWritable.getWriter(),l=s,u=[],d=[];try{for(let e of i.plan){if(e.kind===`reject`){u.push(e.result);continue}if(e.kind===`task-control`){let t=await executeTaskControlAction({action:e.action,bundle:o,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l});l=t.session,t.pendingTask!==void 0&&d.push(t.pendingTask),u.push(t.result);continue}if(e.kind===`resume`){let t=await checkTaskContinuationAvailability({action:e.action,agentId:e.agentId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l});if(t!==void 0){u.push(t);continue}}let n=await beginDelegatedTask({...describeTaskDispatch({action:e.kind===`resume`?e.action:e.target.action,agentId:e.kind===`resume`?e.agentId:void 0,parentSessionId:s.sessionId,parentTurnId:a.event.turnId,session:l}),parentSessionId:s.sessionId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l}),f;e.kind===`resume`&&(f=await persistContinuationTaskInParentSession({action:e.action,agentId:e.agentId,delegated:n,session:l}),l=f?.session??l);let p;switch(e.kind){case`resume`:p=await dispatchToTaskAgentAddress({action:e.action,agentId:e.agentId,bundle:createAgentContinuationBundle({action:e.action,bundle:o,dynamicRemoteAgent:e.dynamicRemoteAgent}),currentSession:l,parentToken:n.taskInboxToken});break;case`start`:p=await startSubagent({auth:i.auth,batchEvent:a.event,bundle:o,callbackBaseUrl:r.callbackBaseUrl,capabilities:i.capabilities,channelMetadata:i.channelMetadata,currentSession:l,fanoutSize:i.fanoutSize,initiatorAuth:i.initiatorAuth,parentContinuationToken:n.taskInboxToken,parentTraceContext:i.parentTraceContext,persistentSessions:!0,serializedContext:i.serializedContext,session:s,taskOwned:!0,target:e.target});break}if(l=p.session,p.kind===`error`){u.push(await settleTaskDispatchError({delegated:n,outcome:p,persisted:f})),f!==void 0&&d.push(n);continue}if(f!==void 0)u.push(f.receipt);else{let e=await settleDelegatedDispatch({callId:p.callId,session:l,subagentName:p.toolName,task:n});l=e.session,u.push(e.receipt)}d.push(n),await emitSubagentCalled({adapter:i.adapter,adapterCtx:i.adapterCtx,batchEvent:a.event,entry:e,outcome:p,sessionId:s.sessionId,writer:c})}}finally{c.releaseLock()}return{results:u,sessionState:l===s?r.sessionState:createDurableSessionState({session:l}),pendingTasks:d}}export{dispatchTaskStep};
|
|
1
|
+
import{createDurableSessionState}from"#execution/durable-session-store.js";import{dispatchToTaskAgentAddress}from"#execution/agent-handle-dispatch.js";import{executeTaskControlAction}from"#execution/tasks/parent/dispatch.js";import{createAgentContinuationBundle}from"#execution/agent-continuation-bundle.js";import{emitSubagentCalled,prepareRuntimeActionDispatch,startSubagent}from"#execution/dispatch-runtime-actions-shared.js";import{beginDelegatedTask,settleDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{checkTaskContinuationAvailability,describeTaskDispatch,persistContinuationTaskInParentSession,settleTaskDispatchError}from"#execution/tasks/parent/continuation-dispatch.js";async function dispatchTaskStep(r){"use step";let i=await prepareRuntimeActionDispatch({serializedContext:r.serializedContext,sessionState:r.sessionState,taskControls:!0});if(i===void 0)return{results:[],sessionState:r.sessionState,pendingTasks:[]};let{batch:a,bundle:o,session:s}=i,c=r.parentWritable.getWriter(),l=s,u=[],d=[];try{for(let e of i.plan){if(e.kind===`reject`){u.push(e.result);continue}if(e.kind===`task-control`){let t=await executeTaskControlAction({action:e.action,adapter:i.adapter,bundle:o,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,serializedContext:i.serializedContext,session:l});l=t.session,t.pendingTask!==void 0&&d.push(t.pendingTask),u.push(t.result);continue}if(e.kind===`resume`){let t=await checkTaskContinuationAvailability({action:e.action,agentId:e.agentId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l});if(t!==void 0){u.push(t);continue}}let n=await beginDelegatedTask({...describeTaskDispatch({action:e.kind===`resume`?e.action:e.target.action,agentId:e.kind===`resume`?e.agentId:void 0,parentSessionId:s.sessionId,parentTurnId:a.event.turnId,session:l}),parentSessionId:s.sessionId,parentStepIndex:a.event.stepIndex,parentTurnId:a.event.turnId,session:l}),f;e.kind===`resume`&&(f=await persistContinuationTaskInParentSession({action:e.action,agentId:e.agentId,delegated:n,session:l}),l=f?.session??l);let p;switch(e.kind){case`resume`:p=await dispatchToTaskAgentAddress({action:e.action,agentId:e.agentId,bundle:createAgentContinuationBundle({action:e.action,bundle:o,dynamicRemoteAgent:e.dynamicRemoteAgent}),currentSession:l,parentToken:n.taskInboxToken});break;case`start`:p=await startSubagent({auth:i.auth,batchEvent:a.event,bundle:o,callbackBaseUrl:r.callbackBaseUrl,capabilities:i.capabilities,channelMetadata:i.channelMetadata,currentSession:l,fanoutSize:i.fanoutSize,initiatorAuth:i.initiatorAuth,parentContinuationToken:n.taskInboxToken,parentTraceContext:i.parentTraceContext,persistentSessions:!0,serializedContext:i.serializedContext,session:s,taskOwned:!0,target:e.target});break}if(l=p.session,p.kind===`error`){u.push(await settleTaskDispatchError({delegated:n,outcome:p,persisted:f})),f!==void 0&&d.push(n);continue}if(f!==void 0)u.push(f.receipt);else{let e=await settleDelegatedDispatch({callId:p.callId,session:l,subagentName:p.toolName,task:n});l=e.session,u.push(e.receipt)}d.push(n),await emitSubagentCalled({adapter:i.adapter,adapterCtx:i.adapterCtx,batchEvent:a.event,entry:e,outcome:p,sessionId:s.sessionId,writer:c})}}finally{c.releaseLock()}return{results:u,sessionState:l===s?r.sessionState:createDurableSessionState({session:l}),pendingTasks:d}}export{dispatchTaskStep};
|
|
@@ -1,24 +1,26 @@
|
|
|
1
1
|
import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
|
|
2
|
+
import type { ChannelAdapter } from "#channel/adapter.js";
|
|
2
3
|
import type { DelegatedTask } from "#execution/tasks/parent/delegate.js";
|
|
3
4
|
import type { RuntimeActionRequest, RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
|
|
4
5
|
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
|
|
5
6
|
import type { SessionTaskIndexEntry } from "#tasks/session-index.js";
|
|
6
7
|
import { type TaskView } from "#tasks/types.js";
|
|
7
|
-
/** True for
|
|
8
|
+
/** True for task-control calls dispatched outside the model loop. */
|
|
8
9
|
export declare function isTaskControlAction(action: RuntimeActionRequest): action is RuntimeToolCallActionRequest;
|
|
9
10
|
/**
|
|
10
11
|
* Executes one task-control call inside the dispatch step, which holds
|
|
11
12
|
* the durable session state (ownership index) and world access the
|
|
12
13
|
* tools need.
|
|
13
14
|
*
|
|
14
|
-
* Returns the
|
|
15
|
-
* new tasks and settle the continued agent handle.
|
|
15
|
+
* Returns the current session alongside the action result.
|
|
16
16
|
*/
|
|
17
17
|
export declare function executeTaskControlAction(input: {
|
|
18
18
|
readonly action: RuntimeToolCallActionRequest;
|
|
19
|
+
readonly adapter?: ChannelAdapter;
|
|
19
20
|
readonly bundle: CompiledBundle;
|
|
20
21
|
readonly parentStepIndex?: number;
|
|
21
22
|
readonly parentTurnId: string;
|
|
23
|
+
readonly serializedContext?: Record<string, unknown>;
|
|
22
24
|
readonly session: RuntimeSession;
|
|
23
25
|
}): Promise<{
|
|
24
26
|
readonly result: RuntimeActionResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{cancelRemoteAgentTurn,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{TASK_CANCEL_TOOL_NAME,TASK_CONTROL_TOOL_NAMES,TASK_PEEK_TOOL_NAME,
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{cancelRemoteAgentTurn,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{TASK_CANCEL_TOOL_NAME,TASK_CONTROL_TOOL_NAMES,TASK_PEEK_TOOL_NAME,TASK_UPDATE_TOOL_NAME}from"#runtime/framework-tools/tasks.js";import{sendTaskCommand}from"#execution/tasks/parent/run-parent.js";import{isTerminalTaskStatus}from"#tasks/types.js";import{createTaskControlError,createTaskViewsResult,createUnknownTasksError,findTaskAgentAddress,lookupTaskEntries,readTaskView,readTaskViews}from"#execution/tasks/parent/control-shared.js";import{executeTaskUpdate}from"#execution/tasks/child/update.js";const log=createLogger(`execution.tasks.dispatch`);function isTaskControlAction(e){return e.kind===`tool-call`&&TASK_CONTROL_TOOL_NAMES.has(e.toolName)}async function executeTaskControlAction(e){let{action:t,session:n}=e;if(t.toolName===TASK_UPDATE_TOOL_NAME)return{result:await executeTaskUpdate({action:t,adapter:e.adapter,childStepIndex:e.parentStepIndex??0,childTurnId:e.parentTurnId,serializedContext:e.serializedContext}),session:n};let r=readTaskIds(t.input);if(r===void 0||r.length===0)return{result:createTaskControlError(t,"Provide a non-empty `taskIds` array."),session:n};let i=lookupTaskEntries(n,r);if(i.kind===`unknown`)return{result:createUnknownTasksError(t,i.unknown),session:n};let o=i.entries;switch(t.toolName){case TASK_PEEK_TOOL_NAME:return{result:createTaskViewsResult(t,await readTaskViews(o)),session:n};case TASK_CANCEL_TOOL_NAME:{let r=[];for(let t of o)r.push(await cancelOwnedTask({bundle:e.bundle,entry:t,session:n}));return{result:createTaskViewsResult(t,r),session:n}}default:return{result:createTaskControlError(t,`Unsupported task control "${t.toolName}".`),session:n}}}async function cancelOwnedTask(e){let{entry:t}=e,n=await sendTaskCommand({command:{kind:`cancel`},taskInboxToken:t.taskInboxToken}),r=await readTaskView(t);for(let e=0;e<10&&!isTerminalTaskStatus(r.status);e+=1)await new Promise(e=>setTimeout(e,250)),r=await readTaskView(t);if(!isTerminalTaskStatus(r.status))throw Error(`Task "${t.taskId}" did not commit cancellation before timeout.`);let i=r;return i.status===`cancelled`&&n===`delivered`&&await propagateTaskCancel({bundle:e.bundle,session:e.session,view:i}),i}async function propagateTaskCancel(e){let a=findTaskAgentAddress(e.session,e.view.metadata.agentId);if(a===void 0)return;let o=a.address.sessionId,s=e.view.executor?.childTurnId;if(!(e.view.executor?.childSessionId!==void 0&&e.view.executor.childSessionId!==o))try{if(a.address.kind===`agent/remote`){let t=resolveRemoteAgentForAction({nodeId:a.identity.nodeId,remoteAgentName:a.identity.name,registry:e.bundle.subagentRegistry.subagentsByNodeId}),i={remote:{...t,url:a.address.url},sessionId:o,taskId:e.view.taskId};s!==void 0&&(i.turnId=s),(await cancelRemoteAgentTurn(i)).status===`no_active_turn`&&await cancelRemoteAgentTurn({remote:{...t,url:a.address.url},sessionId:o,taskId:e.view.taskId});return}let t={sessionId:o,taskId:e.view.taskId};s!==void 0&&(t.turnId=s),(await requestWorkflowTurnCancellation(t)).status===`no_active_turn`&&await requestWorkflowTurnCancellation({sessionId:o,taskId:e.view.taskId})}catch(n){logError(log,`task cancel propagation failed; the child may run to completion`,n,{childSessionId:o,taskId:e.view.taskId})}}function readTaskIds(e){let t=e.taskIds;if(Array.isArray(t))return t.filter(e=>typeof e==`string`&&e.trim()!==``)}export{cancelOwnedTask,executeTaskControlAction,isTaskControlAction};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyDelegatedParentStep,notifyTaskTurnStartedStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";async function workflowEntry(e){"use workflow";let{workflowRunId:o,workflowStartedAt:s}=getWorkflowMetadata(),u=e.serializedContext[`eve.continuationToken`]||``,d=e.serializedContext[`eve.mode`],f=e.serializedContext[`eve.capabilities`],p=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=o;let h=getWritable(),v={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let i=readRootSessionId(e.serializedContext),a=readSerializedSubagentDepth(e.serializedContext),c=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:l}=await createSessionStep({compiledArtifactsSource:p.source,continuationToken:u,dynamicSubagentAgentConfig:c,inheritedLimits:e.limits,nodeId:p.nodeId,outputSchema:e.input.outputSchema,rootSessionId:i,sessionId:o,subagentDepth:a});v.lastSessionState=l,v.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),v.callerResolved=!0;let m=await runDriverLoop({capabilities:f,driverWritable:h,initialInput:{deliveryMetadata:e.serializedContext[`eve.channelDelivery`]===void 0?void 0:[{...e.serializedContext[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:v,mode:d,serializedContext:e.serializedContext,sessionState:l,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(s.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return m.kind===`result`?m.result:await finalizeExpiredSession({caller:v.caller,driverWritable:h,mode:d,serializedContext:m.serializedContext,sessionState:m.sessionState})}catch(t){throw v.lastSessionState!==void 0&&await terminateChildSessionsStep({serializedContext:e.serializedContext,sessionState:v.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:h,serializedContext:e.serializedContext}),d===`task`?(await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:await resolveCallerForCrash(v,e.serializedContext),lifecycle:`terminal`,sessionId:o,settled:{isError:!0,output:t}}),createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runDriverLoop(t){let n=new Map,nextParkedActivity=async e=>{let r=new Set(e.expectedAttemptIds);for(let e of n.keys())r.has(e)||n.delete(e);for(;;){if(r.size>0&&[...r].every(e=>n.has(e))){let e=[...r].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:r.size>0,bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:c,commandInbox:m,deferDeliveries:t.mode===`task`&&r.size>0,driverWritable:t.driverWritable,seenTaskDeliveries:l,stateCursor:v});if(e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&r.has(e.attemptId)&&!n.has(e.attemptId)&&n.set(e.attemptId,t)}if(e.closed){let e=[...n.values()];return n.clear(),{kind:`authorization-resume`,payloads:e}}}},r=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],a=[],c=new Set,l=new Set,m=createSessionCommandInbox(),g=sessionCommandHookToken(t.sessionState.sessionId);await m.claimStable(g),await m.claimAuthorization(`${t.sessionState.sessionId}:auth`);let _=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:g}),v=new SessionStateCursor({serializedContext:t.serializedContext,sessionState:t.sessionState}),y,runTurn=async e=>{let n=t.crashCleanupState.caller;n?.taskId!==void 0&&(l.add(n.taskId),await notifyTaskTurnStartedStep({caller:n,childSessionId:v.sessionState.sessionId,childTurnId:activeTurnId(v.sessionState.emissionState)}));let r=await bindTurnCallerContextStep({caller:n,serializedContext:v.serializedContext}),o=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:c,capabilities:t.capabilities,commandInbox:m,controlToken:nextTurnControlToken(),delivery:e,mode:t.mode,parentWritable:t.driverWritable,serializedContext:r,seenTaskDeliveries:l,sessionState:v.sessionState});return await y?.(),y=o.dispose,v.adoptState(o.action),t.crashCleanupState.lastSessionState=v.sessionState,o.action};try{if(t.sessionState.continuationToken)try{await m.rekeyContinuation(t.sessionState.continuationToken)}catch(e){if(!isHookConflictError(e))throw e;return{kind:`result`,result:{output:``}}}await _?.start();let e=await runTurn(t.initialInput);for(;;){if(e.kind===`done`)return{kind:`result`,result:await finalizeDone({action:e,caller:t.crashCleanupState.caller,mode:t.mode})};if(e.kind!==`park`)throw Error(`Driver received unexpected turn action "${e.kind}".`);if(e.cancelled===!0){let e=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(e);let n={caller:t.crashCleanupState.caller,sessionId:v.sessionState.sessionId};await notifyCancelledTaskCallerStep(e.usage===void 0?n:{...n,usage:e.usage}),t.crashCleanupState.lastSessionState=v.sessionState}v.sessionState.continuationToken&&await m.rekeyContinuation(v.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:v.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[]});if(t.crashCleanupState.lastSessionState=v.sessionState,r.kind===`authorization-resume`){e=await runTurn({kind:`deliver`,payloads:r.payloads});continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:v.serializedContext,sessionState:v.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({serializedContext:v.serializedContext,sessionState:v.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({kind:r.kind});continue}if(r.kind===`closed`)return{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:v.serializedContext,sessionState:v.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(n),e={...e,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=v.sessionState;continue}r.delivery.caller!==void 0&&(t.crashCleanupState.caller=r.delivery.caller),e=await runTurn(r.delivery)}}finally{await y?.(),await _?.dispose(),await m.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),await emitTerminalSessionCompletionStep({parentWritable:e.driverWritable,serializedContext:e.serializedContext}),e.mode===`task`?(await fireSessionCallbackStep({output:``,serializedContext:e.serializedContext,status:`completed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentSuccessResult(e.serializedContext,``),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.sessionState.sessionId,settled:{output:``}}),{output:``}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;if(await terminateChildSessionsStep({serializedContext:n,sessionState:e.action.sessionState}),e.mode===`task`)await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`,usage:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage:e.action.usage});else{let n={output:t,usage:e.action.usageDelta};r&&(n.isError=!0),await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.action.sessionState.sessionId,settled:n})}return{output:t}}export{workflowEntry};
|
|
1
|
+
import{sessionCommandHookToken}from"#execution/session-command-token.js";import{isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{SessionStateCursor}from"#execution/session-state-cursor.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{bindTurnCallerContextStep,notifyCancelledTaskCallerStep,notifyDelegatedParentStep,notifyTaskTurnStartedStep,notifyTurnCallerStep,resolveInitialTurnCallerStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{nextTurnDelivery}from"#execution/parked-delivery-wait.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{createSessionCommandInbox}from"#execution/session-command-inbox.js";import{DEFAULT_SESSION_TIMEOUT_MS}from"#execution/session-timeout.js";import{emitTerminalSessionCompletionStep}from"#execution/terminal-session-completion-step.js";import{createSessionTimeoutControl}from"#execution/session-timeout-control.js";import{terminateChildSessionsStep}from"#execution/terminate-child-sessions-step.js";async function workflowEntry(e){"use workflow";let{workflowRunId:s,workflowStartedAt:c}=getWorkflowMetadata(),d=e.serializedContext[`eve.continuationToken`]||``,f=e.serializedContext[`eve.mode`],p=e.serializedContext[`eve.capabilities`],m=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=s;let g=getWritable(),y={caller:void 0,callerResolved:!1,lastSessionState:void 0};try{let a=readRootSessionId(e.serializedContext),o=readSerializedSubagentDepth(e.serializedContext),l=e.serializedContext[`eve.dynamicSubagentAgentConfig`],{state:u}=await createSessionStep({compiledArtifactsSource:m.source,continuationToken:d,dynamicSubagentAgentConfig:l,inheritedLimits:e.limits,nodeId:m.nodeId,outputSchema:e.input.outputSchema,rootSessionId:a,sessionId:s,subagentDepth:o,taskOwned:isTaskOwnedSerializedContext(e.serializedContext)});y.lastSessionState=u,y.caller=await resolveInitialTurnCallerStep({serializedContext:e.serializedContext}),y.callerResolved=!0;let h=await runDriverLoop({capabilities:p,driverWritable:g,initialInput:{deliveryMetadata:e.serializedContext[`eve.channelDelivery`]===void 0?void 0:[{...e.serializedContext[`eve.channelDelivery`],payloadIndex:0}],kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},crashCleanupState:y,mode:f,serializedContext:e.serializedContext,sessionState:u,sessionTimeoutDeadline:e.sessionTimeoutMs===!1?void 0:new Date(c.getTime()+(e.sessionTimeoutMs??DEFAULT_SESSION_TIMEOUT_MS))});return h.kind===`result`?h.result:await finalizeExpiredSession({caller:y.caller,driverWritable:g,mode:f,serializedContext:h.serializedContext,sessionState:h.sessionState})}catch(t){throw y.lastSessionState!==void 0&&await terminateChildSessionsStep({serializedContext:e.serializedContext,sessionState:y.lastSessionState}),await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:g,serializedContext:e.serializedContext}),f===`task`?(await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:await resolveCallerForCrash(y,e.serializedContext),lifecycle:`terminal`,sessionId:s,settled:{isError:!0,output:t}}),createSafeOuterWorkflowError()}}async function resolveCallerForCrash(e,t){if(e.callerResolved)return e.caller;try{return await resolveInitialTurnCallerStep({serializedContext:t})}catch{return}}function createSafeOuterWorkflowError(){let e=Error(`Agent workflow failed. Inspect the private session trace for details.`);return e.name=`EveWorkflowFailure`,e}async function runDriverLoop(t){let n=new Map,nextParkedActivity=async e=>{let r=new Set(e.expectedAttemptIds);for(let e of n.keys())r.has(e)||n.delete(e);for(;;){if(r.size>0&&[...r].every(e=>n.has(e))){let e=[...r].map(e=>n.get(e));return n.clear(),{kind:`authorization-resume`,payloads:e}}let e=await nextTurnDelivery({awaitAuthorizationCallbacks:r.size>0,bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,commandInbox:u,deferDeliveries:t.mode===`task`&&r.size>0,driverWritable:t.driverWritable,seenTaskDeliveries:l,stateCursor:v});if(e.kind!==`authorization`)return e;for(let t of e.payloads){let e=t.authorizationCallback;typeof e?.attemptId==`string`&&r.has(e.attemptId)&&!n.has(e.attemptId)&&n.set(e.attemptId,t)}if(e.closed){let e=[...n.values()];return n.clear(),{kind:`authorization-resume`,payloads:e}}}},r=0,nextTurnControlToken=()=>`${t.sessionState.sessionId}:turn-control:${String(r++)}`,i=[],a=[],o=new Set,l=new Set,u=createSessionCommandInbox(),h=sessionCommandHookToken(t.sessionState.sessionId);await u.claimStable(h),await u.claimAuthorization(`${t.sessionState.sessionId}:auth`);let _=t.sessionTimeoutDeadline===void 0?void 0:createSessionTimeoutControl({deadline:t.sessionTimeoutDeadline,token:h}),v=new SessionStateCursor({serializedContext:t.serializedContext,sessionState:t.sessionState}),y,runTurn=async e=>{let n=t.crashCleanupState.caller;n?.taskId!==void 0&&(l.add(n.taskId),await notifyTaskTurnStartedStep({caller:n,childSessionId:v.sessionState.sessionId,childTurnId:activeTurnId(v.sessionState.emissionState)}));let r=await bindTurnCallerContextStep({caller:n,serializedContext:v.serializedContext}),s=await dispatchAndAwaitTurn({bufferedDeliveries:i,bufferedSessionControls:a,cancelledTaskIds:o,capabilities:t.capabilities,commandInbox:u,controlToken:nextTurnControlToken(),delivery:e,mode:t.mode,parentWritable:t.driverWritable,serializedContext:r,seenTaskDeliveries:l,sessionState:v.sessionState});return await y?.(),y=s.dispose,v.adoptState(s.action),t.crashCleanupState.lastSessionState=v.sessionState,s.action};try{if(t.sessionState.continuationToken)try{await u.rekeyContinuation(t.sessionState.continuationToken)}catch(e){if(!isHookConflictError(e))throw e;return{kind:`result`,result:{output:``}}}await _?.start();let e=await runTurn(t.initialInput);for(;;){if(e.kind===`done`)return{kind:`result`,result:await finalizeDone({action:e,caller:t.crashCleanupState.caller,mode:t.mode})};if(e.kind!==`park`)throw Error(`Driver received unexpected turn action "${e.kind}".`);if(e.cancelled===!0){let e=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(e);let n={caller:t.crashCleanupState.caller,sessionId:v.sessionState.sessionId};await notifyCancelledTaskCallerStep(e.usage===void 0?n:{...n,usage:e.usage}),t.crashCleanupState.lastSessionState=v.sessionState}v.sessionState.continuationToken&&await u.rekeyContinuation(v.sessionState.continuationToken);let n=e.settled;e.cancelled!==!0&&n!==void 0?(await notifyTurnCallerStep({caller:t.crashCleanupState.caller,lifecycle:`parked`,sessionId:v.sessionState.sessionId,settled:n}),t.crashCleanupState.caller=void 0):e.cancelled===!0&&(t.crashCleanupState.caller=void 0);let r=await nextParkedActivity({expectedAttemptIds:e.authorizationAttemptIds??[]});if(t.crashCleanupState.lastSessionState=v.sessionState,r.kind===`authorization-resume`){e=await runTurn({kind:`deliver`,payloads:r.payloads});continue}if(r.kind===`expired`)return{kind:`expired`,serializedContext:v.serializedContext,sessionState:v.sessionState};if(r.kind===`reset`)return await terminateChildSessionsStep({serializedContext:v.serializedContext,sessionState:v.sessionState}),{kind:`result`,result:{output:``}};if(r.kind===`clear`||r.kind===`compact`){e=await runTurn({kind:r.kind});continue}if(r.kind===`closed`)return{kind:`result`,result:{output:``}};if(r.kind===`cancel-turn`){await cancelDescendantTurnsStep({serializedContext:v.serializedContext,sessionState:v.sessionState});let n=await settleCancelledTurnStep({parentWritable:t.driverWritable,serializedContext:v.serializedContext,sessionState:v.sessionState});v.adoptState(n),e={...e,settled:void 0},t.crashCleanupState.caller=void 0,t.crashCleanupState.lastSessionState=v.sessionState;continue}r.delivery.caller!==void 0&&(t.crashCleanupState.caller=r.delivery.caller),e=await runTurn(r.delivery)}}finally{await y?.(),await _?.dispose(),await u.dispose()}}async function finalizeExpiredSession(e){return await terminateChildSessionsStep({serializedContext:e.serializedContext,sessionState:e.sessionState}),await emitTerminalSessionCompletionStep({parentWritable:e.driverWritable,serializedContext:e.serializedContext}),e.mode===`task`?(await fireSessionCallbackStep({output:``,serializedContext:e.serializedContext,status:`completed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentSuccessResult(e.serializedContext,``),serializedContext:e.serializedContext})):await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.sessionState.sessionId,settled:{output:``}}),{output:``}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;if(await terminateChildSessionsStep({serializedContext:n,sessionState:e.action.sessionState}),e.mode===`task`)await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`,usage:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage:e.action.usage});else{let n={output:t,usage:e.action.usageDelta};r&&(n.isError=!0),await notifyTurnCallerStep({caller:e.caller,lifecycle:`terminal`,sessionId:e.action.sessionState.sessionId,settled:n})}return{output:t}}export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0,f=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let p=getPendingAuthorization(s.state),m;if(p&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(p,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},m=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let h=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),g=getInstrumentationRuntime(),_=getHarnessEmissionState(h.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:g?.hooks,rootSessionId:h.rootSessionId??h.sessionId,sequence:_.sequence,sessionId:h.sessionId,turnId:activeTurnId(_)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:g?.hooks,includeTurn:!1,outcome:`failed`})),await g?.forceFlush()},v=buildAdapterContext(l,c),y;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,v):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}y=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),y={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...v.state}}),o.input?.kind===`deliver`&&y===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:g?.hooks,includeTurn:!1,outcome:`completed`})),await g?.forceFlush();let e=reconcileSessionContinuationToken(c,h),t=serializeContext(c),n=e===h?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let b=u.hookRegistry,x=u.resolvedAgent.dynamicInstructionsResolvers??[],S=u.resolvedAgent.dynamicSkillResolvers??[],C=u.subagentRegistry.dynamicResolvers??[],w=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,T=u.resolvedAgent.dynamicToolResolvers??[],E={...u.graph.root,turnAgent:f.turnAgent},D=buildRuntimeIdentity(E);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!_.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:D});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:C,event:e,messages:h.history,persistentSessions:w,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:T,event:e,messages:h.history,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let O=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,v);setChannelContext(c,{...l,state:{...v.state}});let r=stampMessageStreamEvent(n);return await O.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{await forwardTaskEventToSessionCallback(c,e);let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:b,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:C,event:n,messages:t??[],persistentSessions:w}),await dispatchDynamicToolEvent({ctx:c,resolvers:T,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:x,event:n,messages:t??[]})},k=c.require(ModeKey),A;try{throwIfTurnAborted(o.abortSignal),A=await runStep(c,h,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:y,mode:k,session:e});if(m){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:D,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,D,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of m){let r=p?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:k,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:E,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,y)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;O.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:o.sessionState}}let j=reconcileSessionContinuationToken(c,A.session),M=serializeContext(c);A={...A,session:j};let N=createDurableSessionState({session:A.session}),P=readTurnSleepDurationMs(c),F=P===void 0?{}:{sleepDurationMs:P};if(A.next!==null&&typeof A.next==`object`&&`done`in A.next){if(k===`task`&&hasPendingInputBatch(A.session.state))throw O.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await O.close();let e=getTurnUsageState(A.session.state)?.session;return{action:`done`,output:A.next.output,isError:A.next.isError,...F,serializedContext:M,sessionState:N,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(A.session).delta}}if(A.next===null){O.releaseLock();let e=getPendingWorkflowInterrupt(A.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...F,serializedContext:M,sessionState:N};let t=derivePendingState(A.session);if(A.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(A.session);return{action:`park`,...t,...F,serializedContext:M,sessionState:createDurableSessionState({session:n}),settled:{output:A.settledTurn.output,isError:A.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...t,...F,serializedContext:M,sessionState:N,tasksEnabled:d}}return O.releaseLock(),{action:`continue`,...F,serializedContext:M,sessionState:N}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}export{turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0,f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&isTaskToolAvailable({disabledFrameworkTools:u.resolvedAgent.disabledFrameworkTools??[],hasAuthoredTool:f.turnAgent.tools.some(e=>e.name===TASK_UPDATE_TOOL_NAME),tasksEnabled:d,toolName:TASK_UPDATE_TOOL_NAME});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=getInstrumentationRuntime(),v=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:_?.hooks,rootSessionId:g.rootSessionId??g.sessionId,sequence:v.sequence,sessionId:g.sessionId,turnId:activeTurnId(v)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:_?.hooks,includeTurn:!1,outcome:`failed`})),await _?.forceFlush()},y=buildAdapterContext(l,c),b;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,y):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}b=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),b={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...y.state}}),o.input?.kind===`deliver`&&b===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:_?.hooks,includeTurn:!1,outcome:`completed`})),await _?.forceFlush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),n=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let x=u.hookRegistry,S=u.resolvedAgent.dynamicInstructionsResolvers??[],C=u.resolvedAgent.dynamicSkillResolvers??[],w=u.subagentRegistry.dynamicResolvers??[],T=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,E=u.resolvedAgent.dynamicToolResolvers??[],D={...u.graph.root,turnAgent:f.turnAgent},O=buildRuntimeIdentity(D);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!v.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:O});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:w,event:e,messages:g.history,persistentSessions:T,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:E,event:e,messages:g.history,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let k=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,y);setChannelContext(c,{...l,state:{...y.state}});let r=stampMessageStreamEvent(n);return await k.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e);await dispatchStreamEventHooks({ctx:c,registry:x,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:w,event:n,messages:t??[],persistentSessions:T}),await dispatchDynamicToolEvent({ctx:c,resolvers:E,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:S,event:n,messages:t??[]})},A=c.require(ModeKey),j;try{throwIfTurnAborted(o.abortSignal),j=await runStep(c,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:b,mode:A,session:e});if(h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:O,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,O,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:A,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:D,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,b)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;k.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:o.sessionState}}let M=reconcileSessionContinuationToken(c,j.session),N=serializeContext(c);j={...j,session:M};let P=createDurableSessionState({session:j.session}),F=readTurnSleepDurationMs(c),I=F===void 0?{}:{sleepDurationMs:F};if(j.next!==null&&typeof j.next==`object`&&`done`in j.next){if(A===`task`&&hasPendingInputBatch(j.session.state))throw k.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await k.close();let e=getTurnUsageState(j.session.state)?.session;return{action:`done`,output:j.next.output,isError:j.next.isError,...I,serializedContext:N,sessionState:P,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(j.session).delta}}if(j.next===null){k.releaseLock();let e=getPendingWorkflowInterrupt(j.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...I,serializedContext:N,sessionState:P};let t=derivePendingState(j.session);if(j.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(j.session);return{action:`park`,...t,...I,serializedContext:N,sessionState:createDurableSessionState({session:n}),settled:{output:j.settledTurn.output,isError:j.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...t,...I,serializedContext:N,sessionState:P,tasksEnabled:d}}return k.releaseLock(),{action:`continue`,...I,serializedContext:N,sessionState:P}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}export{turnStep};
|
|
@@ -4,14 +4,17 @@ import type { HarnessSession, HarnessToolMap } from "#harness/types.js";
|
|
|
4
4
|
import type { WorkflowSandboxLifecycle } from "#shared/workflow-sandbox.js";
|
|
5
5
|
type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId" | "subagentDepth">;
|
|
6
6
|
type AdvertisedToolMapInput = {
|
|
7
|
+
readonly delegatedCaller?: boolean;
|
|
7
8
|
readonly session: AdvertisedToolSession;
|
|
8
9
|
readonly tools: HarnessToolMap;
|
|
9
10
|
};
|
|
10
11
|
type AdvertisedToolDefinitionsInput = {
|
|
12
|
+
readonly delegatedCaller?: boolean;
|
|
11
13
|
readonly session: AdvertisedToolSession;
|
|
12
14
|
readonly tools: readonly HarnessToolDefinition[];
|
|
13
15
|
};
|
|
14
16
|
type AdvertisedModelToolsInput = {
|
|
17
|
+
readonly delegatedCaller?: boolean;
|
|
15
18
|
readonly modelTools: ToolSet;
|
|
16
19
|
readonly session: HarnessSession;
|
|
17
20
|
readonly tools: HarnessToolMap;
|