eve 0.13.7 → 0.13.8
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 +6 -0
- package/dist/src/execution/create-session-step.d.ts +0 -17
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/eve-workflow-attributes.d.ts +1 -1
- package/dist/src/execution/sandbox/prewarm.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +10 -2
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/runtime/attributes/emit.d.ts +2 -43
- package/dist/src/runtime/attributes/emit.js +1 -1
- package/dist/src/runtime/attributes/normalize.d.ts +17 -0
- package/dist/src/runtime/attributes/normalize.js +1 -0
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -15,29 +15,12 @@ export interface CreateSessionStepResult {
|
|
|
15
15
|
* state before the workflow enters its turn loop.
|
|
16
16
|
* `nodeId` targets a subagent node in the compiled graph; omitted for
|
|
17
17
|
* the root agent.
|
|
18
|
-
*
|
|
19
|
-
* Emits the session/subagent-root `$eve.*` tags from inside this step
|
|
20
|
-
* (so the attribute write folds into a step the session already runs)
|
|
21
|
-
* and returns the durable state value the driver consumes.
|
|
22
18
|
*/
|
|
23
19
|
export declare function createSessionStep(input: {
|
|
24
20
|
readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
|
|
25
21
|
readonly continuationToken: string;
|
|
26
|
-
/**
|
|
27
|
-
* First user message of the run, used to derive `$eve.title` for
|
|
28
|
-
* top-level sessions. Threaded in so the session/subagent-root tags
|
|
29
|
-
* can be emitted from inside this step (see the tag write below)
|
|
30
|
-
* instead of the workflow body, where each `setEveAttributes` call
|
|
31
|
-
* spends a standalone `__builtin_set_attributes` step.
|
|
32
|
-
*/
|
|
33
|
-
readonly inputMessage: unknown;
|
|
34
22
|
readonly outputSchema?: JsonObject;
|
|
35
23
|
readonly nodeId?: string;
|
|
36
24
|
readonly rootSessionId?: string;
|
|
37
|
-
/**
|
|
38
|
-
* Shared serialized context, read for `$eve.trigger` (channel kind)
|
|
39
|
-
* and to detect whether this run is a delegated subagent root.
|
|
40
|
-
*/
|
|
41
|
-
readonly serializedContext: Record<string, unknown>;
|
|
42
25
|
readonly sessionId: string;
|
|
43
26
|
}): Promise<CreateSessionStepResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{createDurableSessionState}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId});return{state:createDurableSessionState({session:createSession({compactionOverrides:{thresholdPercent:t.resolvedAgent.config.compaction?.thresholdPercent},continuationToken:e.continuationToken,outputSchema:e.outputSchema,rootSessionId:e.rootSessionId,sessionId:e.sessionId,turnAgent:t.turnAgent})})}}export{createSessionStep};
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
* - `$eve.title` — truncated session title from the first user message
|
|
25
25
|
* - `$eve.channel_request_id` — inbound channel request id
|
|
26
26
|
*/
|
|
27
|
-
import type { EveAttributeValue } from "#runtime/attributes/
|
|
27
|
+
import type { EveAttributeValue } from "#runtime/attributes/normalize.js";
|
|
28
28
|
/**
|
|
29
29
|
* Active compiled graph node id for the session's agent. Returned by
|
|
30
30
|
* `createSessionStep` so workflow bodies don't have to load the bundle
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{withSandboxTemplatePrewarmLock}from"./template-prewarm-lock.js";import{toErrorMessage}from"#shared/errors.js";import{
|
|
1
|
+
import{withSandboxTemplatePrewarmLock}from"./template-prewarm-lock.js";import{toErrorMessage}from"#shared/errors.js";import{createBundledRuntimeCompiledArtifactsSource,getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{loadCompiledModuleMapFromAuthoredSource}from"#internal/authored-module-map-loader.js";import{createAuthoredSourceRuntimeCompiledArtifactsSource}from"#internal/application/runtime-compiled-artifacts-source.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{loadCompileMetadata}from"#runtime/loaders/compile-metadata.js";import{withBundledCompiledArtifacts}from"#runtime/loaders/bundled-artifacts.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{resolveRuntimeCompilerArtifactPaths}from"#runtime/loaders/artifact-paths.js";import{resolveRuntimeAgentGraph}from"#runtime/resolve-agent-graph.js";import{createRuntimeSandboxTemplateKey}from"#runtime/sandbox/keys.js";import{createRuntimeSandboxTemplatePlan}from"#runtime/sandbox/template-plan.js";import{materializeWorkspaceDirectory}from"#runtime/workspace/seed-files.js";async function prewarmSandboxes(n){let r=await collectPrewarmTargets(n);if(r.length===0)return;let i=createPrewarmSignature(r);if(n.shouldPrewarmSignature?.(i)===!1)return;let a=n.dispatch??(async({backend:e,input:t})=>await e.prewarm(t));n.log?.(`eve: initializing ${formatSandboxTemplateCount(r.length)}...`);let o=(await Promise.all(r.map(async({backend:r,label:i,input:o})=>{let logBackendProgress=e=>{shouldLogSandboxPrewarmProgress(e)&&n.log?.(`eve: sandbox template "${i}" (${r.name}): ${e}`)},s;try{s=await withSandboxTemplatePrewarmLock({appRoot:o.runtimeContext.appRoot,backendName:r.name,templateKey:o.templateKey},async()=>await a({backend:r,input:{...o,log:n.log===void 0?void 0:logBackendProgress}}))}catch(e){throw n.log?.(`eve: failed to initialize sandbox template "${i}" on backend "${r.name}": ${toErrorMessage(e)}`),e}return s}))).filter(e=>e.reused).length;n.log?.(`eve: initialized ${formatSandboxTemplateCount(r.length)} (${o} reused, ${r.length-o} built).`),n.onPrewarmSignature?.(i)}async function prewarmAppSandboxes(e){let t=e.compiledArtifactsSource??createAuthoredSourceRuntimeCompiledArtifactsSource(e.appRoot);if(t.kind!==`disk`)throw Error(`prewarmAppSandboxes requires disk-backed compiled artifacts.`);let n=await(e.loadAgentGraph??loadGraphFromArtifacts)({compiledArtifactsSource:t});await prewarmSandboxes({appRoot:getRuntimeCompiledArtifactsSandboxAppRoot(t)??e.appRoot,compiledArtifactsSource:t,dispatch:e.dispatch,graph:n,log:e.log,onPrewarmSignature:e.onPrewarmSignature,shouldPrewarmSignature:e.shouldPrewarmSignature})}async function prewarmBuiltAppSandboxes(e){let t=createAuthoredSourceRuntimeCompiledArtifactsSource(e.appRoot),[r,o,l]=await Promise.all([loadCompileMetadata({compiledArtifactsSource:t}),loadCompiledManifest({compiledArtifactsSource:t}),loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:t})]);await withBundledCompiledArtifacts({manifest:o,metadata:r??void 0,moduleMap:l,sessionId:`built-app-prewarm`},async()=>{let t=createBundledRuntimeCompiledArtifactsSource(),r=await resolveRuntimeAgentGraph({manifest:o,moduleMap:l});await prewarmSandboxes({appRoot:e.appRoot,compiledArtifactsSource:t,dispatch:e.dispatch,graph:r,log:e.log})})}async function collectPrewarmTargets(e){let t=resolveRuntimeCompilerArtifactPaths(e.appRoot).compileDirectoryPath,n={appRoot:e.appRoot},r=[];return await Promise.all(collectNodeSandboxes(e.graph).map(async({definition:i,nodeId:a,workspaceResourceRoot:o})=>{let s=createRuntimeSandboxTemplatePlan({definition:i,workspaceResourceRoot:o}),c=await createRuntimeSandboxTemplateKey({backendName:i.backend.name,compiledArtifactsSource:e.compiledArtifactsSource,nodeId:a,sourceId:i.sourceId,templatePlan:s});c!==null&&r.push({backend:i.backend,label:formatLabel(a),input:{bootstrap:i.bootstrap,seedFiles:await loadResourceRootSeedFiles({compileDirectoryPath:t,workspaceResourceRoot:o}),runtimeContext:n,templateKey:c},signature:`${i.backend.name}:${a}:${c}`})})),r.sort((e,t)=>e.label.localeCompare(t.label))}async function loadResourceRootSeedFiles(e){return e.workspaceResourceRoot.rootEntries.length===0?[]:(await materializeWorkspaceDirectory(`${e.compileDirectoryPath}/${e.workspaceResourceRoot.logicalPath}`)).map(e=>({content:e.content,path:e.path}))}async function loadGraphFromArtifacts(e){let[t,n]=await Promise.all([loadCompiledManifest({compiledArtifactsSource:e.compiledArtifactsSource}),loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e.compiledArtifactsSource})]);return await resolveRuntimeAgentGraph({manifest:t,moduleMap:n})}function collectNodeSandboxes(e){return[...e.nodesByNodeId.entries()].flatMap(([e,t])=>{let n=t.sandboxRegistry.sandbox;return n===null?[]:[{...n,nodeId:e}]})}function formatLabel(e){return e===ROOT_RUNTIME_AGENT_NODE_ID?`root`:e}function createPrewarmSignature(e){return e.map(e=>e.signature).sort().join(`
|
|
2
2
|
`)}function formatSandboxTemplateCount(e){return`${e} sandbox ${e===1?`template`:`templates`}`}function shouldLogSandboxPrewarmProgress(e){return!e.startsWith(`checking `)&&!e.startsWith(`reusing `)&&e!==`loading microsandbox runtime`&&e!==`microsandbox runtime ready`}export{prewarmAppSandboxes,prewarmBuiltAppSandboxes,prewarmSandboxes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{resolveVercelProductionCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchCodeModeRuntimeActionsStep}from"#execution/dispatch-code-mode-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{claimHookOwnership,closeHookIterator,disposeHook}from"#execution/hook-ownership.js";async function workflowEntry(e){"use workflow";let{workflowRunId:t}=getWorkflowMetadata(),n=e.serializedContext[`eve.continuationToken`]||``,i=e.serializedContext[`eve.mode`],a=e.serializedContext[`eve.capabilities`],s=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=t;let c=getWritable();try{let r=readRootSessionId(e.serializedContext),{state:o}=await createSessionStep({compiledArtifactsSource:s.source,continuationToken:n,nodeId:s.nodeId,outputSchema:e.input.outputSchema,rootSessionId:r,sessionId:t});return await runDriverLoop({capabilities:a,driverWritable:c,initialInput:{kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},mode:i,serializedContext:e.serializedContext,sessionState:o})}catch(t){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:c,serializedContext:e.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext}),t}}async function runDriverLoop(e){let r=createHook({token:`${e.sessionState.sessionId}:auth`}),i=r[Symbol.asyncIterator](),a=0,nextTurnCompletionToken=()=>`${e.sessionState.sessionId}:turn-completion:${String(a++)}`,o=``,s,c,l=null,u=[],getNextPromise=()=>{if(c===void 0)throw Error(`Cannot wait for deliveries before a continuation token is available.`);return l??=c.next(),l},consumeNext=()=>{l=null},closeParkHook=async()=>{let e=c,t=s;if(s=void 0,c=void 0,l=null,e!==void 0)try{await closeHookIterator(e)}catch(e){if(t!==void 0)try{await disposeHook(t)}catch{}throw e}t!==void 0&&await disposeHook(t)},rekeyHook=async e=>{if(!e||s!==void 0&&e===o)return;let t=createHook({token:e});await claimHookOwnership(t);try{await closeParkHook()}catch(e){try{await disposeHook(t)}catch{}throw e}o=e,s=t,c=t[Symbol.asyncIterator](),l=null};try{e.sessionState.continuationToken&&await rekeyHook(e.sessionState.continuationToken);let r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:e.initialInput,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});if(r.kind===`done`)return await finalizeDone({action:r,driverWritable:e.driverWritable});if(!r.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");for(await rekeyHook(r.sessionState.continuationToken);;)switch(r.kind){case`done`:return await finalizeDone({action:r,driverWritable:e.driverWritable});case`dispatch-code-mode-runtime-actions`:case`dispatch-runtime-actions`:{let i=await(r.kind===`dispatch-code-mode-runtime-actions`?dispatchCodeModeRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveVercelProductionCallbackBaseUrl()??getWorkflowMetadata().url,parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState}),a=await waitForPendingRuntimeActionResults({bufferedDeliveries:u,consumeNext,getNextPromise,initialResults:i.results,parentWritable:e.driverWritable,pendingActionKeys:r.pendingActionKeys,rekeyHook,serializedContext:r.serializedContext,sessionState:i.sessionState});if(a===null)return{output:``};r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`runtime-action-result`,results:a.results},mode:e.mode,parentWritable:e.driverWritable,serializedContext:a.serializedContext,sessionState:a.sessionState}),await rekeyHook(r.sessionState.continuationToken);break}case`park`:{if(r.authorizationNames&&r.authorizationNames.length>0){let t=r.authorizationNames.length,n=[];for(;n.length<t;){let e=await i.next();if(e.done)break;e.value.kind===`deliver`&&n.push(...e.value.payloads)}r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`deliver`,payloads:n},mode:e.mode,parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState}),await rekeyHook(r.sessionState.continuationToken);break}let t=await waitForNextDeliver({bufferedDeliveries:u,consumeNext,getNextPromise});if(t===null)return{output:``};let n=await routeDeliverForChildren({auth:t.auth,parentWritable:e.driverWritable,payloads:t.payloads,sessionState:r.sessionState});if(n===void 0)continue;r=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{auth:t.auth,kind:`deliver`,payloads:[n],requestId:t.requestId},mode:e.mode,parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState}),await rekeyHook(r.sessionState.continuationToken);break}}}finally{await closeParkHook(),await closeHookIterator(i),await disposeHook(r)}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;return await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n}),{output:t}}async function dispatchAndAwaitTurn(e){let t=createHook({token:e.completionToken}),n=t.token;try{await dispatchTurnStep({capabilities:e.capabilities,completionToken:n,delivery:e.delivery,mode:e.mode,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});let r=await awaitHookPayload(t);if(r.kind===`turn-error`)throw rebuildSerializableError(r.error);return r.action}finally{await disposeHook(t)}}async function awaitHookPayload(e){for await(let t of e)return t;throw Error(`Turn completion hook closed before delivering a result.`)}async function waitForPendingRuntimeActionResults(t){let n=t.sessionState,r=t.serializedContext,i=await accumulateRuntimeActionResults({bufferedDeliveries:t.bufferedDeliveries,async getNext(){for(;;){let e=await t.getNextPromise();if(t.consumeNext(),e.done)return null;let i=e.value;if(i.kind===`deliver`){let e=await routeDeliverForChildren({auth:i.auth,parentWritable:t.parentWritable,payloads:i.payloads,sessionState:n});if(e===void 0)continue;return{kind:`deliver`,value:{...i,payloads:[e]}}}if(i.kind===`runtime-action-result`)return{kind:`runtime-action-result`,results:i.results};let a=await runProxyInputRequestStep({hookPayload:i,parentWritable:t.parentWritable,serializedContext:r,sessionState:n});n=a.sessionState,r=a.serializedContext,await t.rekeyHook(n.continuationToken)}},initialResults:t.initialResults,pendingActionKeys:t.pendingActionKeys});return i===null?null:{results:i,serializedContext:r,sessionState:n}}async function routeDeliverForChildren(e){let t=coalescePayloads(e.payloads);return e.sessionState.hasProxyInputRequests?(await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState})).remainder:t}async function waitForNextDeliver(e){if(e.bufferedDeliveries.length>0)return coalesceDeliveries(e.bufferedDeliveries.splice(0));for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;if(t.value.kind!==`deliver`)continue;let n=t.value;for(;;){let t=await takeReadyPayload(e.getNextPromise());if(t===NO_READY_MESSAGE||(e.consumeNext(),t.done))break;t.value.kind===`deliver`&&(n=coalesceDeliveries([n,t.value]))}return n}}function coalescePayloads(e){if(e.length===0)return{};if(e.length===1)return e[0]??{};let t={},n=[];for(let r of e){for(let[e,n]of Object.entries(r))e!==`inputResponses`&&n!==void 0&&(t[e]=n);r.inputResponses!==void 0&&n.push(...r.inputResponses)}return n.length>0&&(t.inputResponses=n),t}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}export{workflowEntry};
|
|
@@ -1,7 +1,14 @@
|
|
|
1
|
-
import type { WorkflowFunction, WorkflowMetadata } from "#compiled/@workflow/core/runtime/start.js";
|
|
2
1
|
import type { Runtime } from "#channel/types.js";
|
|
3
2
|
import { type Run } from "#internal/workflow/runtime.js";
|
|
4
3
|
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
|
|
4
|
+
type WorkflowFunction<TArgs extends unknown[], TResult> = (...args: TArgs) => Promise<TResult>;
|
|
5
|
+
interface WorkflowMetadata {
|
|
6
|
+
readonly workflowId: string;
|
|
7
|
+
}
|
|
8
|
+
interface WorkflowStartOptions {
|
|
9
|
+
readonly allowReservedAttributes?: boolean;
|
|
10
|
+
readonly attributes?: Record<string, string>;
|
|
11
|
+
}
|
|
5
12
|
export declare const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE = "deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()";
|
|
6
13
|
/**
|
|
7
14
|
* Workflow function names whose bundled id is stable across deployments
|
|
@@ -45,4 +52,5 @@ export declare function createWorkflowRuntime(config: {
|
|
|
45
52
|
* Starts a workflow on the latest deployment when latest routing applies,
|
|
46
53
|
* while preserving local/dev worlds that do not implement latest routing.
|
|
47
54
|
*/
|
|
48
|
-
export declare function startWorkflowPreferLatest<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata, args: TArgs): Promise<Run<unknown> | Run<TResult>>;
|
|
55
|
+
export declare function startWorkflowPreferLatest<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata, args: TArgs, options?: WorkflowStartOptions): Promise<Run<unknown> | Run<TResult>>;
|
|
56
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{serializeContext}from"#context/serialize.js";import{getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async run(n){let r=
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{serializeContext}from"#context/serialize.js";import{getRun,resumeHook,start}from"#internal/workflow/runtime.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async run(n){let r=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),i=serializeContext(buildRunContext({bundle:r,run:n})),a=readParentLineage(i),o=a.sessionId===void 0?buildSessionAttributes({inputMessage:n.input.message,serializedContext:i}):buildSubagentRootAttributes({identity:{nodeId:r.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:a.callId,parentSessionId:a.sessionId,parentTurnId:a.turnId,rootSessionId:a.rootSessionId??a.sessionId,serializedContext:i}),s;try{s=await startWorkflowPreferLatest(workflowEntryReference,[{input:n.input,serializedContext:i}],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(o)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:n.continuationToken}),e}let c,getEvents=()=>(c??=parseNdjsonStream(()=>getRun(s.runId).getReadable()),c);return{continuationToken:n.continuationToken??s.runId,get events(){return getEvents()},sessionId:s.runId}},async deliver(e){let r={auth:e.auth,kind:`deliver`,payloads:[e.payload],requestId:e.requestId};try{return{sessionId:normalizeWorkflowHook(await resumeHook(e.continuationToken,r)).runId}}catch(r){throw HookNotFoundError.is(r)?new RuntimeNoActiveSessionError(e.continuationToken):(logError(log,`failed to deliver to active session`,r,{continuationToken:e.continuationToken}),r)}},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))}}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference,workflowEntryReference};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeHook}from"#internal/workflow/runtime.js";import{getRuntimeActionKeyFromInterrupt,isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{getPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=e;await setEveAttributes(buildTurnAttributes({parentSessionId:t.sessionState.sessionId,requestId:t.input?.kind===`deliver`?t.input.requestId:void 0,rootSessionId:readRootSessionId(t.serializedContext)??t.sessionState.sessionId}));let o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let m=getPendingAuthorization(o.state),h;if(m&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=m.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),o={...o,state:clearPendingAuthorization(o.state,e.map(e=>e.name))},h=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent}),_=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,g),n=serializeContext(l),r=e===g?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of h)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingCodeModeInterrupt(T.session.state);return e!==void 0&&isCodeModeRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-code-mode-runtime-actions`,pendingRuntimeActionKeys:[getRuntimeActionKeyFromInterrupt(e.interrupt)],serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={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))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[createTurnWorkflowInput(e)])).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{resumeHook}from"#internal/workflow/runtime.js";import{getRuntimeActionKeyFromInterrupt,isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{getPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";let t=e,o=await readDurableSession(t.sessionState),l=await deserializeContext(t.serializedContext),f=l.require(ChannelKey),p=l.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&l.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let m=getPendingAuthorization(o.state),h;if(m&&t.input?.kind===`deliver`){let e=[],n=[],r=[];for(let i of t.input.payloads){let t=i.authorizationCallback;if(t){let r=m.challenges.find(e=>e.name===t.connectionName);r&&(e.push({name:r.name,resume:r.resume,callback:t.callback,hookUrl:r.hookUrl}),n.push({name:r.name,authorization:r.challenge}))}else r.push(i)}e.length>0&&(l.set(PendingAuthorizationResultKey,e),o={...o,state:clearPendingAuthorization(o.state,e.map(e=>e.name))},h=n,t=r.length>0?{...t,input:{...t.input,payloads:r}}:{...t,input:void 0})}t.input?.kind===`deliver`&&t.input.auth!==void 0&&l.set(AuthKey,t.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},durable:o,turnAgent:p.turnAgent}),_=buildAdapterContext(f,l),v;if(t.input?.kind===`deliver`){let e=[];for(let n of t.input.payloads){let t=f.deliver?await f.deliver(n,_):defaultDeliverResult(n);t!=null&&e.push(t)}v=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else t.input?.kind===`runtime-action-result`&&(v={runtimeActionResults:t.input.results});if(t.input?.kind===`deliver`&&setChannelContext(l,{...f,state:{..._.state}}),t.input?.kind===`deliver`&&v===void 0){let e=reconcileSessionContinuationToken(l,g),n=serializeContext(l),r=e===g?t.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:n,sessionState:r}}let y=t.parentWritable.getWriter(),b=p.hookRegistry,x=p.resolvedAgent.dynamicInstructionsResolvers??[],S=p.resolvedAgent.dynamicSkillResolvers??[],C=p.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(f,e,_);return setChannelContext(l,{...f,state:{..._.state}}),await y.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:l,registry:b,event:n}),await dispatchDynamicToolEvent({ctx:l,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:l,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:l,resolvers:x,event:n,messages:t??[]})},w=l.require(ModeKey),T=await runStep(l,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:p.turnAgent.outputSchema,input:v,mode:w,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of h)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=l.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:p.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:p.turnAgent});return createExecutionNodeStep({capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:w,modelResolutionScope:{moduleMap:p.moduleMap,nodeId:p.nodeId},node:p.graph.root})(r,t)})(t,v)}),E=reconcileSessionContinuationToken(l,T.session),D=serializeContext(l);T={...T,session:E};let O=createDurableSessionState({session:T.session});if(T.next!==null&&typeof T.next==`object`&&`done`in T.next)return await y.close(),{action:`done`,output:T.next.output,isError:T.next.isError,serializedContext:D,sessionState:O};if(T.next===null){y.releaseLock();let e=getPendingCodeModeInterrupt(T.session.state);return e!==void 0&&isCodeModeRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-code-mode-runtime-actions`,pendingRuntimeActionKeys:[getRuntimeActionKeyFromInterrupt(e.interrupt)],serializedContext:D,sessionState:O}:{action:`park`,...derivePendingState(T.session),serializedContext:D,sessionState:O}}return y.releaseLock(),{action:`continue`,serializedContext:D,sessionState:O}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={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))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`eve.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{isScheduleAppAuth}from"#channel/schedule-auth.js";import{AuthKey,ParentSessionKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,isNoOutputGeneratedError,summarizeKnownModelCallConfigError,summarizeKnownModelCallRequestError}from"#harness/model-call-error.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createResultCompletedEvent}from"#protocol/message.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ToolLoopAgent,isStepCount}from"ai";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{clearPendingCodeModeInterrupt,getPendingCodeModeInterrupt,setPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{CODE_MODE_TOOL_NAME,loadCodeModeModule}from"#shared/code-mode.js";import{isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{resolveAssistantStepText}from"#harness/messages.js";import{buildDynamicInstructionMessages}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{consumeDeferredStepInput,getApprovedTools,hasDeferredStepInput,hasStepInput,resolvePendingInput,setPendingInputBatch}from"#harness/input-requests.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{isCodeModeConnectionAuthInterrupt}from"#runtime/framework-tools/code-mode-connection-auth.js";import{isSandboxEnabled,selectSandboxSurfaces}from"#harness/sandbox-surface.js";import{buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{applySandboxToolSet,buildSandboxHostTools,createEveCodeModeOptions}from"#harness/code-mode.js";import{createCodeModeLifecycle}from"#harness/code-mode-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#runtime/framework-tools/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n){if(e===void 0)return;let r={};for(let e of Object.keys(n??{}))r[e]=!0;return{functionId:e.functionId??t,includeRuntimeContext:r,isEnabled:!0,recordInputs:e.recordInputs??!0,recordOutputs:e.recordOutputs??!0}}function buildGatewayAttributionHeaders(e,t){if(typeof e!=`string`)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0;if(!n&&!i)return;let a={};return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function createToolLoopHarness(t){let n=t.handleEvent,c=getInstrumentationConfig();c!==void 0&&ensureOtelIntegration();let f=c===void 0?void 0:trace.getTracer(`eve`),p=t.runtimeIdentity?.agentName;async function runStep(e,t){let n;if(f&&hasStepInput(t)){let t=c?.functionId??p,r={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(r[`ai.telemetry.functionId`]=t),n=f.startSpan(`ai.eve.turn`,{attributes:r})}let r=resolveStepOtelContext(f,n,e),executeStep=()=>executeStepBody(e,t,n);try{return r?await context.with(r,executeStep):await executeStep()}finally{n?.end()}}async function executeStepBody(f,v,y){let b=f;y&&(b=setTurnTraceState(b,y.spanContext()));let x=getHarnessEmissionState(b.state),S=consumeDeferredStepInput({input:v,session:b});b=S.session;let E=await resolvePendingRuntimeActions({emit:n,session:b,stepInput:S.input});if(E.outcome===`unresolved`)return{next:null,session:E.session};b=E.session;let D=resolvePendingInput({history:E.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:b,stepInput:S.input});if(D.outcome===`unresolved`)return{next:null,session:D.session};if(n&&D.rejectedActions)for(let e of D.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:D.rejectedActions.event.sequence,stepIndex:D.rejectedActions.event.stepIndex,turnId:D.rejectedActions.event.turnId}));n&&hasStepInput(v)&&(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),b=setHarnessEmissionState(b,x),y&&y.setAttribute(`eve.turn.id`,x.turnId)),b=D.session;let O=D.messages;if(S.input?.context!==void 0)for(let e of S.input.context)O.push({content:e,role:`user`});if(S.input?.message!==void 0&&!D.deferredMessage){let e=await stageAttachmentsToSandbox(S.input.message);O.push({content:e,role:`user`})}let k=await t.resolveModel(b.agent.modelReference),A=detectPromptCachePath(k),j=A.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,M=buildGatewayAttributionHeaders(k,t.runtimeIdentity);({messages:O,session:b}=await maybeCompact({emit:n,emissionState:x,headers:M,messages:O,model:k,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:b,telemetry:enrichTelemetry(c,p)??void 0}));let N=getApprovedTools(b),P=contextStorage.getStore(),F=b.outputSchema===void 0&&P!==void 0&&isScheduleAppAuth(P.get(AuthKey))&&P.get(ParentSessionKey)===void 0,I=await hydrateSandboxAttachments(O),L=[],R=[];for(let e of I)e.role===`system`?L.push(e):R.push(e);if(P!==void 0){L.push(...buildDynamicInstructionMessages(P));let e=P.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&L.push({role:`system`,content:e})}F&&L.push({role:`system`,content:CONDITIONAL_DELIVERY_INSTRUCTION});let z=R,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=b.agent.system?[{role:`system`,content:b.agent.system}]:[],r=L.length>0||t.length>0?[...t,...n,...L]:void 0,i=r!==void 0&&j?applySystemCacheBreakpoint(r,j):r??b.agent.system??void 0;return{instructions:i,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:c,emissionState:x,environment,modelInput:{instructions:i,messages:z},session:b})}},runOneModelCall=async e=>{let{instructions:i,telemetryRuntimeContext:a={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(a[`eve.retry.reason`]=e.retryReason);let o=e.trailingUserNote?[...z,{role:`user`,content:e.trailingUserNote}]:z,s=selectSandboxSurfaces(t),u=await buildToolSetWithProviderTools({approvedTools:N,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:b.agent.modelReference,tools:t.tools});if(P!==void 0){let n=buildDynamicTools(P),r=buildToolSetFromDefinitions({approvedTools:N,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r))u[e]=t}b.outputSchema!==void 0&&(u[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(b.outputSchema));let d=s.length>0?(await applySandboxToolSet({harnessTools:t.tools,lifecycle:n===void 0?void 0:createCodeModeLifecycle({emit:n,emissionState:x,tools:t.tools}),tools:u,surfaces:s})).modelTools:u,f=j?applyLastToolCacheBreakpoint(d,j):d,h=buildStepHooks({cachePath:A,emit:n,emissionState:x,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:j,session:b}),g=new ToolLoopAgent({headers:M,instructions:i,model:k,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:h.onStepFinish,prepareStep:h.prepareStep,runtimeContext:a,stopWhen:isStepCount(1),telemetry:enrichTelemetry(c,p,a),tools:f}),executeModelCall=async()=>{if(n){let e=await g.stream({messages:o}),{handledInlineToolResultCallIds:r,inlineAuthorizationResults:i,inlineToolResultParts:a}=await emitStreamContent(n,x,e.fullStream),s=await h.stepResult;if(isEmptyModelResponse(s)&&a.length===0&&i.length===0)throw new EmptyModelResponseError;if(await emitStepActions(n,x,s,{excludedActionToolNames:new Set([ASK_QUESTION_TOOL_NAME,CODE_MODE_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME]),handledInlineToolResultCallIds:r,tools:t.tools}),a.length>0||i.length>0){let e=s.toolResults,t=new Map(e.map(e=>[e.toolCallId,e]));for(let e of i)t.set(e.toolCallId,e);return{content:s.content,finishReason:s.finishReason,response:{...s.response,...a.length>0?{messages:[{role:`tool`,content:[...a]},...s.response.messages]}:{}},text:s.text,toolCalls:s.toolCalls,toolResults:[...t.values()],usage:s.usage}}return s}await g.generate({messages:o});let e=await h.stepResult;if(isEmptyModelResponse(e))throw new EmptyModelResponseError;return e};return runModelCallWithRetries(()=>executeModelCall().catch(rethrowNoOutputAsEmptyResponse),{sessionId:b.sessionId,turnId:x.turnId})},B=prepareModelCallInput();n&&await emitStepStarted(n,x,O);let V=await continuePendingCodeModeInterrupt({capabilities:t.capabilities,childResults:S.input?.runtimeActionResults,config:t,emit:n,emissionState:x,messages:O,runStep,session:b});if(V!==null)return V;let H;try{H=await runOneModelCall({preparedInput:B,suppressStepStartedEmission:!0})}catch(r){let a=await runModelCallRecoveryPipeline({error:r,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId}),e=>attemptEmptyResponseRecovery({emptyDeliveryEnabled:F,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId})]});if(a.outcome===`recovered`)H=a.result;else{let r=a.error;if(y&&recordErrorOnSpan(y,r),!n)throw r;let o=extractWorkflowStreamWriteErrorDetails(r);if(o!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...o,errorId:t,error:r,sessionId:b.sessionId,turnId:x.turnId}),x=await emitRecoverableFailedTurn(n,x,{code:`WORKFLOW_STREAM_WRITE_FAILED`,details:{...o,errorId:t},message:toErrorMessage(r)}),{next:null,session:setHarnessEmissionState(b,x)}}let s=classifyModelCallError(r),c=createErrorId(),l=s===`terminal`?summarizeKnownModelCallConfigError(r):null,f=l===null?summarizeKnownModelCallRequestError(r):null,p=l?.message??f?.message??toErrorMessage(r),_=extractModelCallErrorDetails(r),v=buildModelCallFailureDetails({configSummary:l,error:r,errorId:c,modelCallDetails:_,requestSummary:f}),S=buildModelCallFailureLogFields({error:r,errorId:c,modelCallDetails:_,requestSummary:f,sessionId:b.sessionId,turnId:x.turnId});return s===`terminal`?(l===null?log.error(f?.message??`model call failed terminally`,S):log.error(`${l.name}: ${l.message}`,{errorId:c,sessionId:b.sessionId,turnId:x.turnId}),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p,sessionId:b.sessionId}),{next:{done:!0,output:``},session:b}):t.mode===`task`?(log.error(f?.message??`model call failed; failing the task run`,S),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p,sessionId:b.sessionId}),{next:{done:!0,isError:!0,output:p},session:b}):(log.error(f?.message??`model call failed — parking session for retry by the user`,S),x=await emitRecoverableFailedTurn(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p}),{next:null,session:setHarnessEmissionState(b,x)})}}let U=accumulateTurnUsage({previous:getTurnUsageState(b.state),turnId:x.turnId,usage:H.usage??{}});b=setTurnUsageState(b,U);let W;try{W=formatLanguageModelGatewayId(k)}catch{W=void 0}return await setEveAttributes({"$eve.model":W,"$eve.input_tokens":U.inputTokens,"$eve.output_tokens":U.outputTokens,"$eve.cache_read_tokens":U.cacheReadTokens,"$eve.cache_write_tokens":U.cacheWriteTokens,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:x,promptMessages:O,result:H,runStep,session:b})}return runStep}function buildModelCallFailureDetails(e){let{configSummary:t,error:r,errorId:i,modelCallDetails:a,requestSummary:o}=e;return t===null?o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}:{errorId:i,message:t.message,name:t.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.requestSummary===null?{...t,error:e.error}:{...t,details:e.modelCallDetails}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.toolCalls.length===0&&e.toolResults.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}const EMPTY_RESPONSE_NUDGE=`Your previous reply was empty and was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`;function buildEmptyResponseNudge(e){return e?`${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`:EMPTY_RESPONSE_NUDGE}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:buildEmptyResponseNudge(e.emptyDeliveryEnabled)})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=resolveAssistantStepText(i.response.messages,i.text),l=i.finishReason!==`tool-calls`&&i.toolCalls.length===0&&hasEmptyDeliverySentinel(c),u=l?[]:i.response.messages,d=l?null:c,f={...s,compaction:createNextCompactionConfig(s.compaction,r,i)};if(isSandboxEnabled(t)){let{getCodeModeInterrupt:e}=await loadCodeModeModule(),a=e(i);if(a!==void 0)return parkOnCodeModeInterrupt({baseSession:f,config:t,emit:n,emissionState:o,interrupt:a,promptMessages:r,responseMessages:u})}let p=extractToolApprovalInputRequests({content:i.content??[]}),m=new Set(p.map(e=>e.action.callId)),h=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:m}),g=[...p,...h],_=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:t.tools}));if(_.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:_,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:u,session:{...f,history:[...r]}}),o)};if(g.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:g,responseMessages:u,session:{...f,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:g,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode),e=setHarnessEmissionState(e,o))),{next:null,session:e}}let y=findAuthorizationSignalFromToolResults(i.toolResults);if(y){let{challenges:e}=y;if(n)for(let t of e)await n(createAuthorizationRequiredEvent({authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));return{next:null,session:setHarnessEmissionState({...f,history:[...r],state:setPendingAuthorization(f.state,{challenges:e})},o)}}let b=new Set((d===null?i.toolResults??[]:[]).filter(e=>e.providerExecuted===!0).map(e=>e.toolCallId)),S=[],C=u.map(e=>e.role===`assistant`&&Array.isArray(e.content)?{...e,content:e.content.flatMap(e=>e.type===`tool-result`&&b.has(e.toolCallId)?(S.push(e),[]):[e.type===`tool-call`&&b.has(e.toolCallId)?{...e,providerExecuted:!1}:e])}:e);S.length>0&&C.push({role:`tool`,content:S});let w=[...r,...C],T={...f,history:w};return!(T.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(C.at(-1)?.role===`tool`||hasDeferredStepInput(T))?(n&&(o=advanceStep(o),T=setHarnessEmissionState(T,o)),{next:a,session:T}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T,stepOutput:d}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME)?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i}=e,{emissionState:a,session:o}=e;if(i===void 0)return t&&(a=await emitTurnEpilogue(t,a,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o};let s=extractFinalOutput(r);return s===void 0?(t&&(a=await emitRecoverableFailedTurn(t,a,OUTPUT_SCHEMA_NOT_FULFILLED),o=setHarnessEmissionState(o,a)),{next:null,session:o}):(o=persistStructuredAssistantTurn(o,n,s),t&&(a=await emitStructuredResult(t,a,s,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o})}async function continuePendingCodeModeInterrupt(e){let t=getPendingCodeModeInterrupt(e.session.state);if(t===void 0)return null;let{continueCodeModeApproval:n,continueCodeModeInterrupt:i,getCodeModeApprovalResponse:a,isCodeModeApprovalInterrupt:o,replaceCodeModeInterruptResult:s,unwrapCodeModeResult:c}=await loadCodeModeModule(),l=t.interrupt,u=o(l)?a([...e.messages],l):void 0;if(o(l)&&u===void 0)return{next:null,session:e.session};let d=createEveCodeModeOptions({lifecycle:e.emit===void 0?void 0:createCodeModeLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools})}),f;try{let t=await buildSandboxHostTools({approvedTools:getApprovedTools(e.session),capabilities:e.capabilities,tools:e.config.tools});if(o(l)&&u!==void 0)f=await n({approvalResponse:u,interrupt:l,options:d,tools:t});else if(isCodeModeConnectionAuthInterrupt(l))f=await i({interrupt:l,resolution:{status:`authorized`},tools:t,options:d});else if(isCodeModeRuntimeActionInterrupt(l)){let n=e.childResults??[],r=l,a=0;for(;;){f=await i({interrupt:r,resolution:n[a]?.output,tools:t,options:d});let e=c(f);if(e.status!==`interrupted`||!isCodeModeRuntimeActionInterrupt(e.interrupt)||a+1>=n.length)break;a++,r=e.interrupt}}else throw Error(`Unsupported code-mode interrupt kind "${l.payload.kind}".`)}catch(e){logError(log,`code-mode interrupt continuation failed`,e),f={error:`code_mode_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let p=c(f),m=p.status===`interrupted`?p.interrupt:p.output,h=[...e.session.history,...t.responseMessages],_=isCodeModeRuntimeActionInterrupt(l)?replaceCodeModeToolResult(h,l.outerToolCallId,m):s(h,l,m),v=clearPendingCodeModeInterrupt({...e.session,history:_});if(p.status===`interrupted`){let t=e.session.history.length,n=_.slice(0,t),r=_.slice(t);return v={...v,history:n},parkOnCodeModeInterrupt({baseSession:v,config:e.config,emit:e.emit,emissionState:e.emissionState,interrupt:p.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:v}}function replaceCodeModeToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}async function parkOnCodeModeInterrupt(e){let{isCodeModeApprovalInterrupt:t,toCodeModeApprovalMessages:n}=await loadCodeModeModule(),r=e.interrupt,i={...e.baseSession,history:[...e.promptMessages]};if(isCodeModeConnectionAuthInterrupt(r)){let t=[...r.payload.challenges??[]];if(e.emit)for(let n of t)await e.emit(createAuthorizationRequiredEvent({authorization:n.challenge,name:n.name,description:n.challenge.instructions??`Authorization required for ${n.name}`,webhookUrl:n.hookUrl,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId}));return{next:null,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:{...i,state:setPendingAuthorization(i.state,{challenges:t})}})}}if(t(r)){let t=n(r),a=extractToolApprovalInputRequests({content:extractAssistantContent(t)}),o=setPendingInputBatch({event:{sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId},requests:a,responseMessages:t,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i})});if(e.emit&&(await e.emit(createInputRequestedEvent({requests:a,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId})),e.config.mode===`conversation`)){let t=await emitTurnEpilogue(e.emit,e.emissionState,e.config.mode);o=setHarnessEmissionState(o,t)}return{next:null,session:o}}return{next:null,session:setHarnessEmissionState(setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i}),e.emissionState)}}function extractAssistantContent(e){let t=[];for(let n of e)n.role===`assistant`&&Array.isArray(n.content)&&t.push(...n.content);return t}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t.length),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session;if(!shouldCompact(r,i.compaction))return{messages:r,session:i};let a=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:i.agent.modelReference,resolveModel:e.resolveModel});if(t&&await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(r,i.compaction)})),r=await compactMessages(r,a.model,i.compaction,a.providerOptions,e.telemetry,e.headers),e.onCompaction)for(let t of e.onCompaction())r.push(t);return t&&await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId})),{messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t){for(let n=1;;n++)try{return await e()}catch(e){if(n===3||classifyModelCallError(e)!==`retry`)throw e;let r=500*2**(n-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:n,delayMs:r,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,r))}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{createToolLoopHarness};
|
|
1
|
+
import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{isScheduleAppAuth}from"#channel/schedule-auth.js";import{AuthKey,ParentSessionKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,isNoOutputGeneratedError,summarizeKnownModelCallConfigError,summarizeKnownModelCallRequestError}from"#harness/model-call-error.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createResultCompletedEvent}from"#protocol/message.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ToolLoopAgent,isStepCount}from"ai";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{clearPendingCodeModeInterrupt,getPendingCodeModeInterrupt,setPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{CODE_MODE_TOOL_NAME,loadCodeModeModule}from"#shared/code-mode.js";import{isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{resolveAssistantStepText}from"#harness/messages.js";import{buildDynamicInstructionMessages}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{consumeDeferredStepInput,getApprovedTools,hasDeferredStepInput,hasStepInput,resolvePendingInput,setPendingInputBatch}from"#harness/input-requests.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{isCodeModeConnectionAuthInterrupt}from"#runtime/framework-tools/code-mode-connection-auth.js";import{isSandboxEnabled,selectSandboxSurfaces}from"#harness/sandbox-surface.js";import{buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{applySandboxToolSet,buildSandboxHostTools,createEveCodeModeOptions}from"#harness/code-mode.js";import{createCodeModeLifecycle}from"#harness/code-mode-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#runtime/framework-tools/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n){if(e===void 0)return;let r={};for(let e of Object.keys(n??{}))r[e]=!0;return{functionId:e.functionId??t,includeRuntimeContext:r,isEnabled:!0,recordInputs:e.recordInputs??!0,recordOutputs:e.recordOutputs??!0}}function buildGatewayAttributionHeaders(e,t){if(typeof e!=`string`)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0;if(!n&&!i)return;let a={};return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function createToolLoopHarness(t){let n=t.handleEvent,c=getInstrumentationConfig();c!==void 0&&ensureOtelIntegration();let f=c===void 0?void 0:trace.getTracer(`eve`),p=t.runtimeIdentity?.agentName;async function runStep(e,t){let n;if(f&&hasStepInput(t)){let t=c?.functionId??p,r={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(r[`ai.telemetry.functionId`]=t),n=f.startSpan(`ai.eve.turn`,{attributes:r})}let r=resolveStepOtelContext(f,n,e),executeStep=()=>executeStepBody(e,t,n);try{return r?await context.with(r,executeStep):await executeStep()}finally{n?.end()}}async function executeStepBody(f,v,y){let b=f;y&&(b=setTurnTraceState(b,y.spanContext()));let x=getHarnessEmissionState(b.state),S=consumeDeferredStepInput({input:v,session:b});b=S.session;let E=await resolvePendingRuntimeActions({emit:n,session:b,stepInput:S.input});if(E.outcome===`unresolved`)return{next:null,session:E.session};b=E.session;let D=resolvePendingInput({history:E.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:b,stepInput:S.input});if(D.outcome===`unresolved`)return{next:null,session:D.session};if(n&&D.rejectedActions)for(let e of D.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:D.rejectedActions.event.sequence,stepIndex:D.rejectedActions.event.stepIndex,turnId:D.rejectedActions.event.turnId}));n&&hasStepInput(v)&&(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),b=setHarnessEmissionState(b,x),y&&y.setAttribute(`eve.turn.id`,x.turnId)),b=D.session;let O=D.messages;if(S.input?.context!==void 0)for(let e of S.input.context)O.push({content:e,role:`user`});if(S.input?.message!==void 0&&!D.deferredMessage){let e=await stageAttachmentsToSandbox(S.input.message);O.push({content:e,role:`user`})}let k=await t.resolveModel(b.agent.modelReference),A=detectPromptCachePath(k),j=A.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,M=buildGatewayAttributionHeaders(k,t.runtimeIdentity);({messages:O,session:b}=await maybeCompact({emit:n,emissionState:x,headers:M,messages:O,model:k,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:b,telemetry:enrichTelemetry(c,p)??void 0}));let N=getApprovedTools(b),P=contextStorage.getStore(),F=b.outputSchema===void 0&&P!==void 0&&isScheduleAppAuth(P.get(AuthKey))&&P.get(ParentSessionKey)===void 0,I=await hydrateSandboxAttachments(O),L=[],R=[];for(let e of I)e.role===`system`?L.push(e):R.push(e);if(P!==void 0){L.push(...buildDynamicInstructionMessages(P));let e=P.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&L.push({role:`system`,content:e})}F&&L.push({role:`system`,content:CONDITIONAL_DELIVERY_INSTRUCTION});let z=R,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=b.agent.system?[{role:`system`,content:b.agent.system}]:[],r=L.length>0||t.length>0?[...t,...n,...L]:void 0,i=r!==void 0&&j?applySystemCacheBreakpoint(r,j):r??b.agent.system??void 0;return{instructions:i,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:c,emissionState:x,environment,modelInput:{instructions:i,messages:z},session:b})}},runOneModelCall=async e=>{let{instructions:i,telemetryRuntimeContext:a={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(a[`eve.retry.reason`]=e.retryReason);let o=e.trailingUserNote?[...z,{role:`user`,content:e.trailingUserNote}]:z,s=selectSandboxSurfaces(t),u=await buildToolSetWithProviderTools({approvedTools:N,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:b.agent.modelReference,tools:t.tools});if(P!==void 0){let n=buildDynamicTools(P),r=buildToolSetFromDefinitions({approvedTools:N,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r))u[e]=t}b.outputSchema!==void 0&&(u[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(b.outputSchema));let d=s.length>0?(await applySandboxToolSet({harnessTools:t.tools,lifecycle:n===void 0?void 0:createCodeModeLifecycle({emit:n,emissionState:x,tools:t.tools}),tools:u,surfaces:s})).modelTools:u,f=j?applyLastToolCacheBreakpoint(d,j):d,h=buildStepHooks({cachePath:A,emit:n,emissionState:x,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:j,session:b}),g=new ToolLoopAgent({headers:M,instructions:i,model:k,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:h.onStepFinish,prepareStep:h.prepareStep,runtimeContext:a,stopWhen:isStepCount(1),telemetry:enrichTelemetry(c,p,a),tools:f}),executeModelCall=async()=>{if(n){let e=await g.stream({messages:o}),{handledInlineToolResultCallIds:r,inlineAuthorizationResults:i,inlineToolResultParts:a}=await emitStreamContent(n,x,e.fullStream),s=await h.stepResult;if(isEmptyModelResponse(s)&&a.length===0&&i.length===0)throw new EmptyModelResponseError;if(await emitStepActions(n,x,s,{excludedActionToolNames:new Set([ASK_QUESTION_TOOL_NAME,CODE_MODE_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME]),handledInlineToolResultCallIds:r,tools:t.tools}),a.length>0||i.length>0){let e=s.toolResults,t=new Map(e.map(e=>[e.toolCallId,e]));for(let e of i)t.set(e.toolCallId,e);return{content:s.content,finishReason:s.finishReason,response:{...s.response,...a.length>0?{messages:[{role:`tool`,content:[...a]},...s.response.messages]}:{}},text:s.text,toolCalls:s.toolCalls,toolResults:[...t.values()],usage:s.usage}}return s}await g.generate({messages:o});let e=await h.stepResult;if(isEmptyModelResponse(e))throw new EmptyModelResponseError;return e};return runModelCallWithRetries(()=>executeModelCall().catch(rethrowNoOutputAsEmptyResponse),{sessionId:b.sessionId,turnId:x.turnId})},B=prepareModelCallInput();n&&await emitStepStarted(n,x,O);let V=await continuePendingCodeModeInterrupt({capabilities:t.capabilities,childResults:S.input?.runtimeActionResults,config:t,emit:n,emissionState:x,messages:O,runStep,session:b});if(V!==null)return V;let H;try{H=await runOneModelCall({preparedInput:B,suppressStepStartedEmission:!0})}catch(r){let a=await runModelCallRecoveryPipeline({error:r,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId}),e=>attemptEmptyResponseRecovery({emptyDeliveryEnabled:F,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId})]});if(a.outcome===`recovered`)H=a.result;else{let r=a.error;if(y&&recordErrorOnSpan(y,r),!n)throw r;let o=extractWorkflowStreamWriteErrorDetails(r);if(o!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...o,errorId:t,error:r,sessionId:b.sessionId,turnId:x.turnId}),x=await emitRecoverableFailedTurn(n,x,{code:`WORKFLOW_STREAM_WRITE_FAILED`,details:{...o,errorId:t},message:toErrorMessage(r)}),{next:null,session:setHarnessEmissionState(b,x)}}let s=classifyModelCallError(r),c=createErrorId(),l=s===`terminal`?summarizeKnownModelCallConfigError(r):null,f=l===null?summarizeKnownModelCallRequestError(r):null,p=l?.message??f?.message??toErrorMessage(r),_=extractModelCallErrorDetails(r),v=buildModelCallFailureDetails({configSummary:l,error:r,errorId:c,modelCallDetails:_,requestSummary:f}),S=buildModelCallFailureLogFields({error:r,errorId:c,modelCallDetails:_,requestSummary:f,sessionId:b.sessionId,turnId:x.turnId});return s===`terminal`?(l===null?log.error(f?.message??`model call failed terminally`,S):log.error(`${l.name}: ${l.message}`,{errorId:c,sessionId:b.sessionId,turnId:x.turnId}),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p,sessionId:b.sessionId}),{next:{done:!0,output:``},session:b}):t.mode===`task`?(log.error(f?.message??`model call failed; failing the task run`,S),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p,sessionId:b.sessionId}),{next:{done:!0,isError:!0,output:p},session:b}):(log.error(f?.message??`model call failed — parking session for retry by the user`,S),x=await emitRecoverableFailedTurn(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p}),{next:null,session:setHarnessEmissionState(b,x)})}}let U=accumulateTurnUsage({previous:getTurnUsageState(b.state),turnId:x.turnId,usage:H.usage??{}});b=setTurnUsageState(b,U);let W;try{W=formatLanguageModelGatewayId(k)}catch{W=void 0}return await setEveAttributes({"$eve.model":W,"$eve.input_tokens":U.inputTokens,"$eve.output_tokens":U.outputTokens,"$eve.cache_read_tokens":U.cacheReadTokens,"$eve.cache_write_tokens":U.cacheWriteTokens,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:x,promptMessages:O,result:H,runStep,session:b})}return runStep}function buildModelCallFailureDetails(e){let{configSummary:t,error:r,errorId:i,modelCallDetails:a,requestSummary:o}=e;return t===null?o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}:{errorId:i,message:t.message,name:t.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.requestSummary===null?{...t,error:e.error}:{...t,details:e.modelCallDetails}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.toolCalls.length===0&&e.toolResults.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}const EMPTY_RESPONSE_NUDGE=`Your previous reply was empty and was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`;function buildEmptyResponseNudge(e){return e?`${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`:EMPTY_RESPONSE_NUDGE}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:buildEmptyResponseNudge(e.emptyDeliveryEnabled)})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=resolveAssistantStepText(i.response.messages,i.text),l=i.finishReason!==`tool-calls`&&i.toolCalls.length===0&&hasEmptyDeliverySentinel(c),u=l?[]:i.response.messages,d=l?null:c,f={...s,compaction:createNextCompactionConfig(s.compaction,r,i)};if(isSandboxEnabled(t)){let{getCodeModeInterrupt:e}=await loadCodeModeModule(),a=e(i);if(a!==void 0)return parkOnCodeModeInterrupt({baseSession:f,config:t,emit:n,emissionState:o,interrupt:a,promptMessages:r,responseMessages:u})}let p=extractToolApprovalInputRequests({content:i.content??[]}),m=new Set(p.map(e=>e.action.callId)),h=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:m}),g=[...p,...h],_=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:t.tools}));if(_.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:_,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:u,session:{...f,history:[...r]}}),o)};if(g.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:g,responseMessages:u,session:{...f,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:g,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode),e=setHarnessEmissionState(e,o))),{next:null,session:e}}let y=findAuthorizationSignalFromToolResults(i.toolResults);if(y){let{challenges:e}=y;if(n)for(let t of e)await n(createAuthorizationRequiredEvent({authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));return{next:null,session:setHarnessEmissionState({...f,history:[...r],state:setPendingAuthorization(f.state,{challenges:e})},o)}}let b=new Set((d===null?i.toolResults??[]:[]).filter(e=>e.providerExecuted===!0).map(e=>e.toolCallId)),S=[],C=u.map(e=>e.role===`assistant`&&Array.isArray(e.content)?{...e,content:e.content.flatMap(e=>e.type===`tool-result`&&b.has(e.toolCallId)?(S.push(e),[]):[e.type===`tool-call`&&b.has(e.toolCallId)?{...e,providerExecuted:!1}:e])}:e);S.length>0&&C.push({role:`tool`,content:S});let w=[...r,...C],T={...f,history:w};return!(T.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(C.at(-1)?.role===`tool`||hasDeferredStepInput(T))?(n&&(o=advanceStep(o),T=setHarnessEmissionState(T,o)),{next:a,session:T}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T,stepOutput:d}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME)?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i}=e,{emissionState:a,session:o}=e;if(i===void 0)return t&&(a=await emitTurnEpilogue(t,a,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o};let s=extractFinalOutput(r);return s===void 0?(t&&(a=await emitRecoverableFailedTurn(t,a,OUTPUT_SCHEMA_NOT_FULFILLED),o=setHarnessEmissionState(o,a)),{next:null,session:o}):(o=persistStructuredAssistantTurn(o,n,s),t&&(a=await emitStructuredResult(t,a,s,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o})}async function continuePendingCodeModeInterrupt(e){let t=getPendingCodeModeInterrupt(e.session.state);if(t===void 0)return null;let{continueCodeModeApproval:n,continueCodeModeInterrupt:i,getCodeModeApprovalResponse:a,isCodeModeApprovalInterrupt:o,replaceCodeModeInterruptResult:s,unwrapCodeModeResult:c}=await loadCodeModeModule(),l=t.interrupt,u=o(l)?a([...e.messages],l):void 0;if(o(l)&&u===void 0)return{next:null,session:e.session};let d=createEveCodeModeOptions({lifecycle:e.emit===void 0?void 0:createCodeModeLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools})}),f;try{let t=await buildSandboxHostTools({approvedTools:getApprovedTools(e.session),capabilities:e.capabilities,tools:e.config.tools});if(o(l)&&u!==void 0)f=await n({approvalResponse:u,interrupt:l,options:d,tools:t});else if(isCodeModeConnectionAuthInterrupt(l))f=await i({interrupt:l,resolution:{status:`authorized`},tools:t,options:d});else if(isCodeModeRuntimeActionInterrupt(l)){let n=e.childResults??[],r=l,a=0;for(;;){f=await i({interrupt:r,resolution:n[a]?.output,tools:t,options:d});let e=c(f);if(e.status!==`interrupted`||!isCodeModeRuntimeActionInterrupt(e.interrupt)||a+1>=n.length)break;a++,r=e.interrupt}}else throw Error(`Unsupported code-mode interrupt kind "${l.payload.kind}".`)}catch(e){logError(log,`code-mode interrupt continuation failed`,e),f={error:`code_mode_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let p=c(f),m=p.status===`interrupted`?p.interrupt:p.output,h=[...e.session.history,...t.responseMessages],_=isCodeModeRuntimeActionInterrupt(l)?replaceCodeModeToolResult(h,l.outerToolCallId,m):s(h,l,m),v=clearPendingCodeModeInterrupt({...e.session,history:_});if(p.status===`interrupted`){let t=e.session.history.length,n=_.slice(0,t),r=_.slice(t);return v={...v,history:n},parkOnCodeModeInterrupt({baseSession:v,config:e.config,emit:e.emit,emissionState:e.emissionState,interrupt:p.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:v}}function replaceCodeModeToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}async function parkOnCodeModeInterrupt(e){let{isCodeModeApprovalInterrupt:t,toCodeModeApprovalMessages:n}=await loadCodeModeModule(),r=e.interrupt,i={...e.baseSession,history:[...e.promptMessages]};if(isCodeModeConnectionAuthInterrupt(r)){let t=[...r.payload.challenges??[]];if(e.emit)for(let n of t)await e.emit(createAuthorizationRequiredEvent({authorization:n.challenge,name:n.name,description:n.challenge.instructions??`Authorization required for ${n.name}`,webhookUrl:n.hookUrl,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId}));return{next:null,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:{...i,state:setPendingAuthorization(i.state,{challenges:t})}})}}if(t(r)){let t=n(r),a=extractToolApprovalInputRequests({content:extractAssistantContent(t)}),o=setPendingInputBatch({event:{sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId},requests:a,responseMessages:t,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i})});if(e.emit&&(await e.emit(createInputRequestedEvent({requests:a,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId})),e.config.mode===`conversation`)){let t=await emitTurnEpilogue(e.emit,e.emissionState,e.config.mode);o=setHarnessEmissionState(o,t)}return{next:null,session:o}}return{next:null,session:setHarnessEmissionState(setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i}),e.emissionState)}}function extractAssistantContent(e){let t=[];for(let n of e)n.role===`assistant`&&Array.isArray(n.content)&&t.push(...n.content);return t}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t.length),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session;if(!shouldCompact(r,i.compaction))return{messages:r,session:i};let a=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:i.agent.modelReference,resolveModel:e.resolveModel});if(t&&await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(r,i.compaction)})),r=await compactMessages(r,a.model,i.compaction,a.providerOptions,e.telemetry,e.headers),e.onCompaction)for(let t of e.onCompaction())r.push(t);return t&&await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId})),{messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t){for(let n=1;;n++)try{return await e()}catch(e){if(n===3||classifyModelCallError(e)!==`retry`)throw e;let r=500*2**(n-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:n,delayMs:r,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,r))}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{createToolLoopHarness};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.13.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.13.8`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1,47 +1,6 @@
|
|
|
1
1
|
import "#internal/workflow/builtins.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
*
|
|
5
|
-
* Local mirror of `ATTRIBUTE_VALUE_MAX_BYTES` from `@workflow/world`
|
|
6
|
-
* (source of truth: `packages/world/src/attributes.ts` in the workflow
|
|
7
|
-
* repo). The value is duplicated rather than imported because
|
|
8
|
-
* `@workflow/core` — the only workflow surface bundled into the
|
|
9
|
-
* workflow body — does not re-export it, and pulling `@workflow/world`
|
|
10
|
-
* into the body bundle would drag in the full zod attribute validator
|
|
11
|
-
* (the same reason `workflow-core-shim.ts` skips runtime validation in
|
|
12
|
-
* its `experimental_setAttributes`).
|
|
13
|
-
*
|
|
14
|
-
* Strings emitted through {@link setEveAttributes} are truncated to this
|
|
15
|
-
* byte count before they reach the runtime so the validator never
|
|
16
|
-
* rejects a tag for length alone.
|
|
17
|
-
*
|
|
18
|
-
* Drift is conservative-by-construction: if workflow LOWERS the limit,
|
|
19
|
-
* over-long values are rejected and `setEveAttributes` swallows the
|
|
20
|
-
* failure (warn-once-per-process) — dashboards see a missing tag, never
|
|
21
|
-
* a broken agent; if workflow RAISES it, titles are merely shorter than
|
|
22
|
-
* necessary. `emit.drift.test.ts` asserts equality against the real
|
|
23
|
-
* `@workflow/world` export (a devDependency) so CI fails loudly the day
|
|
24
|
-
* the constants diverge.
|
|
25
|
-
*/
|
|
26
|
-
export declare const EVE_ATTRIBUTE_VALUE_MAX_BYTES = 256;
|
|
27
|
-
/**
|
|
28
|
-
* Attribute value the caller wants to write. `undefined` values are
|
|
29
|
-
* stripped before the runtime call; numbers are stringified; strings
|
|
30
|
-
* are truncated to {@link EVE_ATTRIBUTE_VALUE_MAX_BYTES}.
|
|
31
|
-
*/
|
|
32
|
-
export type EveAttributeValue = string | number | undefined;
|
|
33
|
-
/**
|
|
34
|
-
* Truncates a string so its UTF-8 byte length is at most `maxBytes`
|
|
35
|
-
* without splitting a multi-byte character.
|
|
36
|
-
*
|
|
37
|
-
* The workflow runtime measures attribute values in UTF-8 bytes, not
|
|
38
|
-
* code units, so `value.slice(0, maxBytes)` is not safe — a JS string
|
|
39
|
-
* with two-byte characters (e.g. emoji surrogate pairs) can serialize
|
|
40
|
-
* to twice as many bytes as code units. We re-encode the truncated
|
|
41
|
-
* candidate after each drop and shrink one code unit at a time when
|
|
42
|
-
* the candidate's last character straddles the byte budget.
|
|
43
|
-
*/
|
|
44
|
-
export declare function truncateForTag(value: string, maxBytes?: number): string;
|
|
2
|
+
import { type EveAttributeValue } from "#runtime/attributes/normalize.js";
|
|
3
|
+
export { EVE_ATTRIBUTE_VALUE_MAX_BYTES, type EveAttributeValue, truncateForTag, } from "#runtime/attributes/normalize.js";
|
|
45
4
|
/**
|
|
46
5
|
* Writes a batch of eve-owned attributes to the active workflow run.
|
|
47
6
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"#internal/workflow/builtins.js";
|
|
1
|
+
import{EVE_ATTRIBUTE_VALUE_MAX_BYTES,normalizeEveAttributes,truncateForTag}from"#runtime/attributes/normalize.js";import"#internal/workflow/builtins.js";let WARNED_ABOUT_TAG_FAILURE=!1;async function setEveAttributes(e){let t=normalizeEveAttributes(e);if(Object.keys(t).length!==0)try{let{experimental_setAttributes:e}=await import(`#compiled/@workflow/core/index.js`);await e(t,{allowReservedAttributes:!0})}catch(e){WARNED_ABOUT_TAG_FAILURE||(WARNED_ABOUT_TAG_FAILURE=!0,console.warn(`[eve] setEveAttributes failed; suppressing further warnings this process.`,{keys:Object.keys(t),error:e.message}))}}export{EVE_ATTRIBUTE_VALUE_MAX_BYTES,setEveAttributes,truncateForTag};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maximum UTF-8 byte size for one Workflow run attribute value.
|
|
3
|
+
*
|
|
4
|
+
* Mirrored from `ATTRIBUTE_VALUE_MAX_BYTES` in `@workflow/world` so the
|
|
5
|
+
* normalization helper stays independent of the full world package.
|
|
6
|
+
* `emit.drift.test.ts` guards the mirror against upstream changes.
|
|
7
|
+
*/
|
|
8
|
+
export declare const EVE_ATTRIBUTE_VALUE_MAX_BYTES = 256;
|
|
9
|
+
/** Attribute value accepted by eve's internal attribute builders. */
|
|
10
|
+
export type EveAttributeValue = string | number | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Truncates a string to Workflow's UTF-8 byte budget without splitting
|
|
13
|
+
* a surrogate pair.
|
|
14
|
+
*/
|
|
15
|
+
export declare function truncateForTag(value: string, maxBytes?: number): string;
|
|
16
|
+
/** Normalizes sparse eve attributes into Workflow's string-only shape. */
|
|
17
|
+
export declare function normalizeEveAttributes(attrs: Record<string, EveAttributeValue>): Record<string, string>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const EVE_ATTRIBUTE_VALUE_MAX_BYTES=256;function truncateForTag(e,t=256){if(t<=0)return``;let n=new TextEncoder;if(n.encode(e).length<=t)return e;let r=e.length;for(;r>0;){let i=e.charCodeAt(r-1);if(i>=55296&&i<=56319){--r;continue}let a=e.slice(0,r);if(n.encode(a).length<=t)return a;--r}return``}function normalizeEveAttributes(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=truncateForTag(typeof r==`number`?String(r):r));return t}export{EVE_ATTRIBUTE_VALUE_MAX_BYTES,normalizeEveAttributes,truncateForTag};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectObjectRecord}from"#internal/authored-module.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{
|
|
1
|
+
import{expectObjectRecord}from"#internal/authored-module.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{CODE_MODE_TOOL_NAME,WORKFLOW_TOOL_NAME}from"#shared/code-mode.js";import{createRuntimeToolRegistry}from"#runtime/tools/registry.js";import{createRuntimeSubagentRegistry}from"#runtime/subagents/registry.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolNames,getFrameworkToolDefinitions}from"#runtime/framework-tools/index.js";import{createConnectionSearchResolver}from"#runtime/framework-tools/connection-search-dynamic.js";import{resolveAgent}from"#runtime/resolve-agent.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createResolvedRuntimeTurnAgent}from"#runtime/agent/bootstrap.js";import{createRuntimeHookRegistry}from"#runtime/hooks/registry.js";import{createRuntimeSandboxRegistry}from"#runtime/sandbox/registry.js";var ResolveRuntimeAgentGraphError=class extends Error{logicalPath;nodeId;sourceId;constructor(e,t={}){super(e),this.name=`ResolveRuntimeAgentGraphError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.nodeId!==void 0&&(this.nodeId=t.nodeId),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};async function resolveRuntimeAgentGraph(e){let n=new Map,r=createChildNodeIdsByParentNodeId(e.manifest),i=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:n,root:await resolveRuntimeAgentNode({childNodeIdsByParentNodeId:r,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:ROOT_COMPILED_AGENT_NODE_ID,nodesByNodeId:n,subagentNodesById:i})}}async function resolveRuntimeAgentNode(e){let t=toRuntimeNodeId(e.nodeId);if(e.nodesByNodeId.has(t))throw new ResolveRuntimeAgentGraphError(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let a=await resolveAgent({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),o=a.connections.length>0,s=getFrameworkToolDefinitions({hasConnections:o}),c=new Set(s.map(e=>e.name)),l=getAllFrameworkToolNames(),u=new Set(a.tools.map(e=>e.name));for(let n of a.disabledFrameworkTools)if(!l.has(n))throw new ResolveRuntimeAgentGraphError(`agent/tools/${n}.ts exports disableTool() but "${n}" is not a framework tool. Rename the file to one of: ${[...l].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let d=new Set(a.disabledFrameworkTools),f=await createRuntimeToolRegistry({tools:[...s.filter(e=>!u.has(e.name)&&!d.has(e.name)),...a.tools]},{reservedToolNames:[CODE_MODE_TOOL_NAME,WORKFLOW_TOOL_NAME,...c.has(LOAD_SKILL_TOOL_NAME)||u.has(LOAD_SKILL_TOOL_NAME)?[]:[LOAD_SKILL_TOOL_NAME]]}),p=new Set(a.channels.map(e=>e.name)),m=getAllFrameworkChannelNames();for(let n of a.disabledFrameworkChannels)if(!m.has(n))throw new ResolveRuntimeAgentGraphError(`agent/channels/${n}.ts exports disableRoute() but "${n}" is not a framework channel. Rename the file to one of: ${[...m].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let h=new Set(a.disabledFrameworkChannels),g=[...getFrameworkChannelDefinitions().filter(e=>!p.has(e.name)&&!h.has(e.name)),...a.channels],_=createRuntimeSandboxRegistry({authoredSandbox:a.sandbox,workspaceResourceRoot:a.workspaceResourceRoot}),v=createRuntimeSubagentRegistry({reservedToolNames:[LOAD_SKILL_TOOL_NAME,...f.preparedTools.map(e=>e.name)],subagents:await resolveRuntimeSubagents({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.manifest,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),y=o?{...a,dynamicToolResolvers:[...a.dynamicToolResolvers,createConnectionSearchResolver()]}:a,b={agent:y,channels:g,hookRegistry:createRuntimeHookRegistry(y.hooks),nodeId:t,sandboxRegistry:_,sourceId:e.sourceId,subagentRegistry:v,toolRegistry:f,turnAgent:createResolvedRuntimeTurnAgent({agent:y,nodeId:t,tools:[...f.preparedTools,...v.preparedTools]})};return e.nodesByNodeId.set(t,b),b}async function resolveRuntimeSubagents(e){let t=[],n=e.childNodeIdsByParentNodeId.get(e.parentNodeId)??[];for(let r of n){let n=e.subagentNodesById.get(r);if(n===void 0)throw new ResolveRuntimeAgentGraphError(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:toRuntimeNodeId(e.parentNodeId),sourceId:r});t.push(await resolveRuntimeSubagent({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}for(let n of e.manifest.remoteAgents)t.push(await resolveRuntimeRemoteAgent({moduleMap:e.moduleMap,nodeScopeId:e.parentNodeId,sourceRef:n}));return t}async function resolveRuntimeSubagent(e){let t={description:e.sourceRef.description,kind:`subagent`,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:toRuntimeNodeId(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await resolveRuntimeAgentNode({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.sourceRef.agent,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId,nodesByNodeId:e.nodesByNodeId,sourceId:e.sourceRef.sourceId,subagentNodesById:e.subagentNodesById}),t}async function resolveRuntimeRemoteAgent(t){let n=expectObjectRecord(await loadResolvedModuleExport({definition:t.sourceRef,kindLabel:`remote agent`,moduleMap:t.moduleMap,nodeId:t.nodeScopeId}),`Expected remote agent source "${t.sourceRef.logicalPath}" to export an object.`),r={description:t.sourceRef.description,kind:`remote`,logicalPath:t.sourceRef.logicalPath,name:t.sourceRef.name,nodeId:toRuntimeNodeId(t.sourceRef.nodeId),outputSchema:t.sourceRef.outputSchema,path:t.sourceRef.path,sourceId:t.sourceRef.sourceId,sourceKind:`module`,url:t.sourceRef.url};typeof n.auth==`function`&&(r.auth=n.auth);let i=resolveRemoteAgentHeaders(n.headers);return i!==void 0&&(r.headers=i),r}function resolveRemoteAgentHeaders(e){if(e===void 0)return;if(typeof e==`function`)return e;if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function createChildNodeIdsByParentNodeId(e){let t=new Map;for(let n of e.subagentEdges){let e=t.get(n.parentNodeId);if(e===void 0){t.set(n.parentNodeId,[n.childNodeId]);continue}e.push(n.childNodeId)}return t}function toRuntimeNodeId(e){return e===ROOT_COMPILED_AGENT_NODE_ID?ROOT_RUNTIME_AGENT_NODE_ID:e}export{resolveRuntimeAgentGraph};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{
|
|
1
|
+
import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{getRuntimeCompiledArtifactsCacheKey}from"#runtime/compiled-artifacts-source.js";import{getResolvedRuntimeAgentNode}from"#runtime/graph.js";import{loadCompiledManifest}from"#runtime/loaders/manifest.js";import{resolveRuntimeAgentGraph}from"#runtime/resolve-agent-graph.js";import{pathToFileURL}from"node:url";import{loadCompiledModuleMap}from"#runtime/loaders/module-map.js";import{getActiveRuntimeSession}from"#runtime/sessions/runtime-session.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";import{createRuntimeAdapterRegistry}from"#runtime/channels/registry.js";const isCacheDisabled=process.env.EVE_DISABLE_AGENT_CACHE===`1`;function isDevelopmentRuntimeSnapshotRoot(e){return e.replaceAll(`\\`,`/`).includes(`/.eve/dev-runtime/snapshots/`)}function normalizeCompiledArtifactsSource(t){return t.kind!==`disk`||t.moduleMapLoaderPath!==void 0||!isDevelopmentRuntimeSnapshotRoot(t.appRoot)?t:{...t,moduleMapLoaderPath:resolvePackageSourceFilePath(`src/internal/authored-module-map-loader.ts`)}}async function loadFullBundle(e){let t=normalizeCompiledArtifactsSource(e),[n,a]=await Promise.all([loadCompiledManifest({compiledArtifactsSource:t}),loadRuntimeCompiledModuleMap(t)]),o=await resolveRuntimeAgentGraph({manifest:n,moduleMap:a}),s=o.root;return{adapterRegistry:createRuntimeAdapterRegistry({channels:collectResolvedChannels(o)}),compiledArtifactsSource:t,graph:o,hookRegistry:s.hookRegistry,moduleMap:a,resolvedAgent:s.agent,subagentRegistry:s.subagentRegistry,toolRegistry:s.toolRegistry,turnAgent:s.turnAgent}}async function loadRuntimeCompiledModuleMap(e){return e.kind===`disk`&&e.moduleMapLoaderPath!==void 0?await loadAuthoredSourceCompiledModuleMap(e):await loadCompiledModuleMap({compiledArtifactsSource:e})}async function loadAuthoredSourceCompiledModuleMap(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(pathToFileURL(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function getOrLoadFullBundle(e){let n=normalizeCompiledArtifactsSource(e);if(isCacheDisabled)return loadFullBundle(n);let r=getActiveRuntimeSession(),i=getRuntimeCompiledArtifactsCacheKey(n),a=await resolveRuntimeCompiledArtifactsVersionedCacheKey(n),o=r.bundleCacheKeyBySourceKey.get(i);o!==void 0&&o!==a&&r.bundleCache.delete(o),r.bundleCacheKeyBySourceKey.set(i,a);let c=r.bundleCache.get(a);if(c!==void 0)return c;let l=loadFullBundle(n).catch(e=>{throw r.bundleCache.delete(a),r.bundleCacheKeyBySourceKey.get(i)===a&&r.bundleCacheKeyBySourceKey.delete(i),e});return r.bundleCache.set(a,l),l}async function getCompiledRuntimeAgentBundle(e){let t=await getOrLoadFullBundle(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let r=getResolvedRuntimeAgentNode(t.graph,e.nodeId);return{adapterRegistry:t.adapterRegistry,compiledArtifactsSource:t.compiledArtifactsSource,graph:{nodesByNodeId:t.graph.nodesByNodeId,root:r},hookRegistry:r.hookRegistry,moduleMap:t.moduleMap,nodeId:e.nodeId,resolvedAgent:r.agent,subagentRegistry:r.subagentRegistry,toolRegistry:r.toolRegistry,turnAgent:r.turnAgent}}function clearCompiledRuntimeAgentBundleCache(){let e=getActiveRuntimeSession();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function collectResolvedChannels(e){let t=new Map;for(let n of e.nodesByNodeId.values())for(let e of n.channels)t.set(`${e.sourceId}:${e.name}`,e);return[...t.values()]}export{clearCompiledRuntimeAgentBundleCache,getCompiledRuntimeAgentBundle};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`7.0.0-beta.178`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.13.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`7.0.0-beta.178`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.13.8`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
|
|
2
2
|
|
|
3
3
|
export default defineAgent({
|
|
4
4
|
model: "__EVE_INIT_MODEL__",
|