eve 0.42.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/src/channel/forwarded-principal.d.ts +4 -4
- package/dist/src/compiler/extension-compatibility.d.ts +7 -5
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +3 -0
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/normalize-tool.js +1 -1
- package/dist/src/context/build-dynamic-tools.d.ts +5 -5
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-subagent-lifecycle.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.d.ts +8 -27
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +10 -14
- package/dist/src/context/keys.js +1 -1
- package/dist/src/context/provider.d.ts +5 -1
- package/dist/src/context/run-step.d.ts +3 -2
- package/dist/src/context/run-step.js +1 -1
- package/dist/src/execution/agent-handle-dispatch.d.ts +3 -0
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/delegation-tool.d.ts +9 -1
- package/dist/src/execution/delegation-tool.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +14 -1
- package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/history-view.d.ts +9 -0
- package/dist/src/execution/history-view.js +1 -0
- package/dist/src/execution/next-driver-action.d.ts +33 -1
- package/dist/src/execution/node-step.d.ts +5 -2
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +2 -0
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/session-callback-step.d.ts +2 -2
- package/dist/src/execution/session-callback-step.js +1 -1
- package/dist/src/execution/tasks/child/steps.js +1 -1
- package/dist/src/execution/tasks/child/update.d.ts +2 -2
- package/dist/src/execution/tasks/child/update.js +1 -1
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/agent-views.d.ts +2 -1
- package/dist/src/execution/tasks/parent/agent-views.js +1 -1
- package/dist/src/execution/tasks/parent/continuation-dispatch.d.ts +6 -0
- package/dist/src/execution/tasks/parent/continuation-dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/control-shared.d.ts +1 -1
- package/dist/src/execution/tasks/parent/control-shared.js +1 -1
- package/dist/src/execution/tasks/parent/delegate.d.ts +20 -6
- package/dist/src/execution/tasks/parent/delegate.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -1
- package/dist/src/execution/tasks/parent/dispatch.d.ts +13 -1
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.d.ts +46 -0
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -0
- package/dist/src/execution/tool-auth.d.ts +12 -3
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/turn-cancellation-control.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/wire/session-inbox-wire.v1.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +1 -54
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/advertised-tools.js +1 -1
- package/dist/src/harness/background-tools.d.ts +37 -0
- package/dist/src/harness/background-tools.js +1 -0
- package/dist/src/harness/execute-tool.d.ts +10 -1
- package/dist/src/harness/handles/transitions.d.ts +36 -0
- package/dist/src/harness/handles/transitions.js +1 -1
- package/dist/src/harness/messages.d.ts +2 -0
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/tools.d.ts +5 -1
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/harness/types.d.ts +13 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +13 -0
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.d.ts +7 -31
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +4 -4
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/public/channels/eve.d.ts +7 -7
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/definitions/remote-agent.d.ts +7 -5
- package/dist/src/public/definitions/tool.d.ts +23 -0
- package/dist/src/public/definitions/tool.js +1 -1
- package/dist/src/public/tools/approval/approval-helpers.js +1 -1
- package/dist/src/public/tools/index.d.ts +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
- package/dist/src/runtime/framework-tools/subagent/local.d.ts +41 -0
- package/dist/src/runtime/framework-tools/subagent/local.js +1 -0
- package/dist/src/runtime/framework-tools/subagent/remote.d.ts +23 -0
- package/dist/src/runtime/framework-tools/subagent/remote.js +1 -0
- package/dist/src/runtime/framework-tools/tasks.d.ts +11 -2
- package/dist/src/runtime/framework-tools/tasks.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/session-callback-route.js +1 -1
- package/dist/src/setup/integrations/linq/management.d.ts +5 -0
- package/dist/src/setup/integrations/linq/management.js +1 -0
- package/dist/src/setup/integrations/linq/setup.d.ts +5 -1
- package/dist/src/setup/integrations/linq/setup.js +3 -3
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +4 -10
- package/dist/src/setup/scaffold/create/web-template.d.ts +0 -1
- package/dist/src/setup/scaffold/create/web-template.js +1 -1
- package/dist/src/setup/scaffold/update/channels.d.ts +1 -1
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/package-json.d.ts +0 -2
- package/dist/src/setup/scaffold/update/package-json.js +1 -1
- package/dist/src/setup/scaffold/workspace-root.d.ts +0 -1
- package/dist/src/setup/scaffold/workspace-root.js +1 -1
- package/dist/src/shared/durable-dynamic-tool-callbacks.d.ts +34 -0
- package/dist/src/shared/durable-dynamic-tool-callbacks.js +1 -0
- package/dist/src/shared/dynamic-tool-definition.d.ts +2 -4
- package/dist/src/shared/empty-delivery.js +1 -1
- package/dist/src/shared/history-view.d.ts +22 -0
- package/dist/src/shared/history-view.js +1 -0
- package/dist/src/shared/json.d.ts +2 -0
- package/dist/src/shared/json.js +1 -1
- package/dist/src/shared/tool-definition.d.ts +4 -1
- package/dist/src/shared/tool-task.d.ts +107 -0
- package/dist/src/shared/tool-task.js +1 -0
- package/dist/src/tasks/delivery-context.d.ts +12 -0
- package/dist/src/tasks/delivery-context.js +17 -0
- package/dist/src/tasks/json.d.ts +25 -10
- package/dist/src/tasks/json.js +1 -1
- package/dist/src/tasks/session-index.d.ts +5 -3
- package/dist/src/tasks/session-index.js +1 -1
- package/dist/src/tasks/transitions.d.ts +40 -5
- package/dist/src/tasks/transitions.js +1 -1
- package/dist/src/tasks/types.d.ts +46 -4
- package/dist/src/tasks/types.js +1 -1
- package/docs/channels/linq.mdx +1 -1
- package/docs/getting-started.mdx +36 -36
- package/docs/guides/auth-and-route-protection.md +6 -2
- package/docs/guides/dynamic-capabilities.md +12 -10
- package/docs/guides/remote-agents.md +10 -2
- package/docs/tools/overview.mdx +19 -0
- package/package.json +1 -1
|
@@ -4,7 +4,7 @@ import type { DelegatedTask } from "#execution/tasks/parent/delegate.js";
|
|
|
4
4
|
import type { RuntimeActionRequest, RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
|
|
5
5
|
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
|
|
6
6
|
import type { SessionTaskIndexEntry } from "#tasks/session-index.js";
|
|
7
|
-
import { type TaskView } from "#tasks/types.js";
|
|
7
|
+
import { type SubagentExecutorData, type TaskView } from "#tasks/types.js";
|
|
8
8
|
/** True for task-control calls dispatched outside the model loop. */
|
|
9
9
|
export declare function isTaskControlAction(action: RuntimeActionRequest): action is RuntimeToolCallActionRequest;
|
|
10
10
|
/**
|
|
@@ -33,3 +33,15 @@ export declare function cancelOwnedTask(input: {
|
|
|
33
33
|
readonly entry: SessionTaskIndexEntry;
|
|
34
34
|
readonly session: RuntimeSession;
|
|
35
35
|
}): Promise<TaskView>;
|
|
36
|
+
/**
|
|
37
|
+
* Sends the cooperative abort to the child identified by a subagent
|
|
38
|
+
* executor binding. Failures are logged, never thrown: the task is already
|
|
39
|
+
* terminal when this runs, so the worst outcome is a child that runs to
|
|
40
|
+
* completion and has its callback refused.
|
|
41
|
+
*/
|
|
42
|
+
export declare function propagateSubagentExecutorCancel(input: {
|
|
43
|
+
readonly bundle: CompiledBundle | undefined;
|
|
44
|
+
readonly childTurnId?: string;
|
|
45
|
+
readonly executor: SubagentExecutorData;
|
|
46
|
+
readonly taskId: string;
|
|
47
|
+
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{cancelRemoteAgentTurn,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{TASK_CANCEL_TOOL_NAME,TASK_CONTROL_TOOL_NAMES,TASK_UPDATE_TOOL_NAME}from"#runtime/framework-tools/tasks.js";import{sendTaskCommand}from"#execution/tasks/parent/run-parent.js";import{isTerminalTaskStatus}from"#tasks/types.js";import{createTaskControlError,createTaskViewsResult,createUnknownTasksError,findTaskAgentAddress,lookupTaskEntries,readTaskView}from"#execution/tasks/parent/control-shared.js";import{executeTaskUpdate}from"#execution/tasks/child/update.js";const log=createLogger(`execution.tasks.dispatch`);function isTaskControlAction(e){return e.kind===`tool-call`&&TASK_CONTROL_TOOL_NAMES.has(e.toolName)}async function executeTaskControlAction(e){let{action:t,session:n}=e;if(t.toolName===TASK_UPDATE_TOOL_NAME)return{result:await executeTaskUpdate({action:t,adapter:e.adapter,
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{cancelRemoteAgentTurn,resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";import{requestWorkflowTurnCancellation}from"#execution/workflow-runtime.js";import{TASK_CANCEL_TOOL_NAME,TASK_CONTROL_TOOL_NAMES,TASK_UPDATE_TOOL_NAME}from"#runtime/framework-tools/tasks.js";import{sendTaskCommand}from"#execution/tasks/parent/run-parent.js";import{isTerminalTaskStatus,readSubagentExecutor,readSubagentTaskMetadata}from"#tasks/types.js";import{createTaskControlError,createTaskViewsResult,createUnknownTasksError,findTaskAgentAddress,lookupTaskEntries,readTaskView}from"#execution/tasks/parent/control-shared.js";import{executeTaskUpdate}from"#execution/tasks/child/update.js";const log=createLogger(`execution.tasks.dispatch`);function isTaskControlAction(e){return e.kind===`tool-call`&&TASK_CONTROL_TOOL_NAMES.has(e.toolName)}async function executeTaskControlAction(e){let{action:t,session:n}=e;if(t.toolName===TASK_UPDATE_TOOL_NAME)return{result:await executeTaskUpdate({action:t,adapter:e.adapter,updateIndex:e.parentStepIndex??0,updateEpoch:e.parentTurnId,serializedContext:e.serializedContext}),session:n};let r=readTaskIds(t.input);if(r===void 0||r.length===0)return{result:createTaskControlError(t,"Provide a non-empty `taskIds` array."),session:n};let i=lookupTaskEntries(n,r);if(i.kind===`unknown`)return{result:createUnknownTasksError(t,i.unknown),session:n};let o=i.entries;if(t.toolName!==TASK_CANCEL_TOOL_NAME)return{result:createTaskControlError(t,`Unsupported task control "${t.toolName}".`),session:n};let c=[];for(let t of o)c.push(await cancelOwnedTask({bundle:e.bundle,entry:t,session:n}));return{result:createTaskViewsResult(t,c),session:n}}async function cancelOwnedTask(e){let{entry:t}=e,n=await sendTaskCommand({command:{kind:`cancel`},taskInboxToken:t.taskInboxToken}),r=await readTaskView(t);for(let e=0;e<10&&!isTerminalTaskStatus(r.status);e+=1)await new Promise(e=>setTimeout(e,250)),r=await readTaskView(t);if(!isTerminalTaskStatus(r.status))throw Error(`Task "${t.taskId}" did not commit cancellation before timeout.`);let i=r;return i.status===`cancelled`&&n===`delivered`&&await propagateTaskCancel({bundle:e.bundle,session:e.session,view:i}),i}async function propagateTaskCancel(e){let t=readSubagentTaskMetadata(e.view);if(t===void 0)return;let n=readSubagentExecutor(e.view.executor)??findTaskAgentAddress(e.session,t.agentId);n!==void 0&&(e.view.executor?.childSessionId!==void 0&&e.view.executor.childSessionId!==n.address.sessionId||await propagateSubagentExecutorCancel({bundle:e.bundle,childTurnId:e.view.executor?.childTurnId,executor:n,taskId:e.view.taskId}))}async function propagateSubagentExecutorCancel(e){let{address:a,identity:o}=e.executor,s=a.sessionId,c=e.childTurnId;try{if(a.kind===`agent/remote`){if(e.bundle===void 0)throw Error(`No compiled bundle is available to resolve the remote agent.`);let t=resolveRemoteAgentForAction({nodeId:o.nodeId,remoteAgentName:o.name,registry:e.bundle.subagentRegistry.subagentsByNodeId}),i={remote:{...t,url:a.url},sessionId:s,taskId:e.taskId};c!==void 0&&(i.turnId=c),(await cancelRemoteAgentTurn(i)).status===`no_active_turn`&&await cancelRemoteAgentTurn({remote:{...t,url:a.url},sessionId:s,taskId:e.taskId});return}let t={sessionId:s,taskId:e.taskId};c!==void 0&&(t.turnId=c),(await requestWorkflowTurnCancellation(t)).status===`no_active_turn`&&await requestWorkflowTurnCancellation({sessionId:s,taskId:e.taskId})}catch(n){logError(log,`task cancel propagation failed; the child may run to completion`,n,{childSessionId:s,taskId:e.taskId})}}function readTaskIds(e){let t=e.taskIds;if(Array.isArray(t))return t.filter(e=>typeof e==`string`&&e.trim()!==``)}export{cancelOwnedTask,executeTaskControlAction,isTaskControlAction,propagateSubagentExecutorCancel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isInputRequest}from"#runtime/input/types.js";import{createEveTaskInputRoutePath}from"#protocol/routes.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{removeTaskAgentAddressFromState}from"#harness/handles/transitions.js";import{createRemoteTaskInputCallbackUrl}from"#execution/workflow-callback-url.js";import{readDurableSession}from"#execution/durable-session-store.js";import{createTaskInputRequestId,toProxyInputRequestEntries,upsertProxyInputRequestState}from"#harness/proxy-input-requests.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{cacheTerminalTaskView,findSessionTaskEntry}from"#tasks/session-index.js";import{isTerminalTaskStatus}from"#tasks/types.js";import{createTaskInputCapabilityToken}from"#execution/task-input-capability.js";async function recordTaskInputRequestStep(r){"use step";let a=await readDurableSession(r.sessionState),
|
|
1
|
+
import{isInputRequest}from"#runtime/input/types.js";import{createEveTaskInputRoutePath}from"#protocol/routes.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{removeTaskAgentAddressFromState}from"#harness/handles/transitions.js";import{createRemoteTaskInputCallbackUrl}from"#execution/workflow-callback-url.js";import{readDurableSession}from"#execution/durable-session-store.js";import{createTaskInputRequestId,toProxyInputRequestEntries,upsertProxyInputRequestState}from"#harness/proxy-input-requests.js";import{readLatestTaskView}from"#execution/tasks/parent/run-parent.js";import{cacheTerminalTaskView,findSessionTaskEntry}from"#tasks/session-index.js";import{isTerminalTaskStatus,readSubagentTaskMetadata}from"#tasks/types.js";import{createTaskInputCapabilityToken}from"#execution/task-input-capability.js";async function recordTaskInputRequestStep(r){"use step";let a=await readDurableSession(r.sessionState),c=findSessionTaskEntry(a.state,r.taskId),l=c===void 0?void 0:readSubagentTaskMetadata(c),u=(getAgentHandleStore(a.state)?.handles??[]).find(e=>e.phase===`addressed`&&e.identity.id===l?.agentId);if(c===void 0||u?.phase!==`addressed`||u.address.sessionId!==r.hookPayload.childSessionId)return{accepted:!1,sessionState:r.sessionState};let d=await readLatestTaskView({taskRunId:c.taskRunId}),f=d===void 0?void 0:readSubagentTaskMetadata(d),p=r.hookPayload.event.requests.map(e=>e.requestId),m=d?.inputRequests?.map(e=>typeof e==`object`&&e&&!Array.isArray(e)?Reflect.get(e,`requestId`):void 0)??[];if(d?.status!==`input_required`||!r.hookPayload.event.requests.every(isInputRequest)||f?.mode!==(u.address.kind===`agent/remote`?`remote`:`local`)||f.agentId!==l?.agentId||d.executor?.childSessionId!==r.hookPayload.childSessionId||new Set(p).size!==p.length||p.length!==m.length||p.some((e,t)=>e!==m[t]))return{accepted:!1,sessionState:r.sessionState};let h=namespaceTaskInputRequests(r.hookPayload,r.taskId),g=toProxyInputRequestEntries(h,r.taskId).map(([e,t],n)=>{let i=r.hookPayload.event.requests[n].requestId;return[e,{...t,childRequestId:i}]});if(u.address.kind===`agent/remote`){let e=createRemoteTaskInputCallbackUrl(u.address.url,createEveTaskInputRoutePath(createTaskInputCapabilityToken(r.hookPayload.childContinuationToken)));g=g.map(([t,n])=>[t,{...n,childResponseUrl:e}])}let _=upsertProxyInputRequestState({entries:g,forChildContinuationToken:r.hookPayload.childContinuationToken,state:a.state});return{accepted:!0,hookPayload:h,sessionState:{...r.sessionState,hasProxyInputRequests:!0,snapshot:{session:{...a,state:_},version:r.sessionState.version}}}}function namespaceTaskInputRequests(e,t){return{...e,event:{...e.event,requests:e.event.requests.map(e=>({...e,requestId:createTaskInputRequestId(t,e.requestId)}))}}}async function acceptTaskAuthorizationEventStep(e){"use step";let t=await readDurableSession(e.sessionState),r=findSessionTaskEntry(t.state,e.taskId);if(r===void 0)return!1;let i=readSubagentTaskMetadata(r);if(i===void 0)return!1;let a=(getAgentHandleStore(t.state)?.handles??[]).find(e=>e.phase===`addressed`&&e.identity.id===i.agentId);if(a?.phase!==`addressed`||a.address.sessionId!==e.hookPayload.childSessionId)return!1;let o=await readLatestTaskView({taskRunId:r.taskRunId}),s=o===void 0?void 0:readSubagentTaskMetadata(o);return o!==void 0&&!isTerminalTaskStatus(o.status)&&o.executor?.childSessionId===e.hookPayload.childSessionId&&s?.agentId===i.agentId}async function recordTerminalTaskViewsStep(e){"use step";let t=await readDurableSession(e.sessionState),n=t.state;for(let t of e.views)if(n=cacheTerminalTaskView(n,t),t.executor?.lifecycle===`terminal`){let e=readSubagentTaskMetadata(t);e!==void 0&&(n=removeTaskAgentAddressFromState(n,e.agentId))}return n===t.state?e.sessionState:{...e.sessionState,snapshot:{session:{...t,state:n},version:e.sessionState.version}}}export{acceptTaskAuthorizationEventStep,recordTaskInputRequestStep,recordTerminalTaskViewsStep};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ContextContainer } from "#context/container.js";
|
|
2
|
+
import type { FrameworkContextProvider } from "#context/provider.js";
|
|
3
|
+
import type { HarnessSession, StepResult } from "#harness/types.js";
|
|
4
|
+
import { type BackgroundToolExecutor } from "#harness/background-tools.js";
|
|
5
|
+
interface BackgroundToolStepResult {
|
|
6
|
+
readonly backgroundTaskSession: HarnessSession;
|
|
7
|
+
readonly backgroundTasks: NonNullable<StepResult["backgroundTasks"]>;
|
|
8
|
+
}
|
|
9
|
+
export declare function runBackgroundStep(ctx: ContextContainer, session: HarnessSession, callback: (session: HarnessSession) => Promise<StepResult>): Promise<StepResult>;
|
|
10
|
+
/**
|
|
11
|
+
* Makes background tool work transactional with the harness step.
|
|
12
|
+
*
|
|
13
|
+
* Concretely: when the model calls a background tool (e.g. a subagent spawn),
|
|
14
|
+
* the tool does real external work mid-step — it creates a task run and
|
|
15
|
+
* delivers commands to its inbox — while the step itself can still fail. This
|
|
16
|
+
* provider scopes that work to the step so it either lands with the step or
|
|
17
|
+
* is compensated with it.
|
|
18
|
+
*
|
|
19
|
+
* Lifetime: one {@link BackgroundToolExecutionScope} per step. `create` runs
|
|
20
|
+
* before the authored callback; exactly one of `commit` or `rollback` settles
|
|
21
|
+
* the scope afterwards; `decorateStepResult` runs last, only after a
|
|
22
|
+
* successful commit. Nothing survives the step except retained tasks (below).
|
|
23
|
+
*
|
|
24
|
+
* - `commit` — step succeeded. Compensates executions that never settled
|
|
25
|
+
* (the tool neither delegated nor completed its task), then records the
|
|
26
|
+
* task entries and executor-owned session writes onto the session being
|
|
27
|
+
* persisted.
|
|
28
|
+
* - `rollback` — step failed. Compensates incomplete executions, and settled
|
|
29
|
+
* ones too — unless the cause is turn cancellation: those tasks are already
|
|
30
|
+
* running, so they are retained for {@link readRetainedBackgroundToolResult}
|
|
31
|
+
* instead of killed.
|
|
32
|
+
* - `decorateStepResult` — attaches `backgroundTasks` and
|
|
33
|
+
* `backgroundTaskSession` to the {@link StepResult} so the turn loop keeps
|
|
34
|
+
* tracking the spawned tasks after the step returns.
|
|
35
|
+
*/
|
|
36
|
+
export declare const backgroundToolExecutionProvider: FrameworkContextProvider<BackgroundToolExecutor>;
|
|
37
|
+
/**
|
|
38
|
+
* Returns what a successful commit would have produced (session with task
|
|
39
|
+
* entries and executor session writes applied) when turn cancellation raced
|
|
40
|
+
* a successfully delegated task. `rollback` deliberately does not compensate
|
|
41
|
+
* settled records on cancellation — that would kill already-running tasks —
|
|
42
|
+
* so the cancellation epilogue reads this instead to keep those tasks tracked
|
|
43
|
+
* in durable state rather than orphaned. `undefined` when nothing was retained.
|
|
44
|
+
*/
|
|
45
|
+
export declare function readRetainedBackgroundToolResult(ctx: ContextContainer): BackgroundToolStepResult | undefined;
|
|
46
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createEveCallbackRoutePath}from"#protocol/routes.js";import{parseJsonValue}from"#shared/json.js";import{loadContext}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{recordTaskAgentAddress}from"#harness/handles/transitions.js";import{createWorkflowCallbackUrl}from"#execution/workflow-callback-url.js";import{runStep}from"#context/run-step.js";import{propagateSubagentExecutorCancel}from"#execution/tasks/parent/dispatch.js";import{sendTaskCommand,sendTaskInboundPayload}from"#execution/tasks/parent/run-parent.js";import{recordSessionTask}from"#tasks/session-index.js";import{activeTurnId}from"#harness/active-turn-id.js";import{readSubagentExecutor}from"#tasks/types.js";import{beginBackgroundTask,rejectDelegatedDispatch}from"#execution/tasks/parent/delegate.js";import{CallbackBaseUrlKey,isAuthorizationSignal}from"#harness/authorization.js";import{isTurnCancellation}from"#harness/turn-cancellation.js";import{BackgroundToolExecutorKey}from"#harness/background-tools.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{createTaskDelegated,isTaskDelegated}from"#shared/tool-task.js";function runBackgroundStep(e,t,n){return runStep(e,t,n,[backgroundToolExecutionProvider])}const backgroundToolExecutionProvider={key:BackgroundToolExecutorKey,create(e,t){return{value:new BackgroundToolExecutionScope(t,e.get(BundleKey))}},async commit(e,t){return await requireExecutionScope(e).commit(t)},async rollback(e,t){await requireExecutionScope(e).rollback(t)},decorateStepResult(e,t){return requireExecutionScope(e).decorate(t)}};function readRetainedBackgroundToolResult(e){let t=e.get(BackgroundToolExecutorKey);return t instanceof BackgroundToolExecutionScope?t.retainedResult():void 0}var BackgroundToolExecutionScope=class{bundle;executions=new Map;records=[];retained=!1;initialSession;constructor(e,t){this.bundle=t,this.initialSession=e}execute(e){let t=this.executions.get(e.options.toolCallId);if(t!==void 0)return t;if(!e.batch.calls.some(t=>t.callId===e.options.toolCallId))throw Error(`Background tool call "${e.options.toolCallId}" was not registered before execution.`);let n=this.start(e);return this.executions.set(e.options.toolCallId,n),n}async commit(e){let t=this.records.filter(e=>!e.settled);return t.length>0&&await compensateBackgroundToolExecution(t,Error(`Background tool execution did not delegate or complete its task.`),this.bundle),this.apply(e)}decorate(e){let t=this.resultFields();return t===void 0?e:{...e,...t}}async rollback(e){let t=this.records.filter(e=>e.settled),n=this.records.filter(e=>!e.settled);if(n.length>0&&await compensateBackgroundToolExecution(n,e,this.bundle),t.length!==0){if(isTurnCancellation(e)){this.retained=!0;return}await compensateBackgroundToolExecution(t,e,this.bundle)}}retainedResult(){return this.retained?this.resultFields():void 0}apply(e){let t=e;for(let e of this.records){if(!e.settled||e.task===void 0)continue;let n=readSubagentExecutor(e.task.executor);n!==void 0&&(t=recordTaskAgentAddress(t,n)),t=recordSessionTask(t,e.task)}return t}resultFields(){let e=this.records.flatMap(e=>e.settled&&e.task!==void 0?[e.task]:[]);if(e.length!==0)return{backgroundTaskSession:this.apply(this.initialSession),backgroundTasks:e.map(({taskInboxToken:e,taskId:t,taskRunId:n})=>({taskInboxToken:e,taskId:t,taskRunId:n}))}}async start(r){let a={settled:!1};this.records.push(a);let o=getHarnessEmissionState(this.initialSession.state),s=await beginBackgroundTask({callId:r.options.toolCallId,metadata:{kind:`tool`,name:r.definition.name},parentSessionId:this.initialSession.sessionId,parentStepIndex:o.stepIndex,parentTurnId:activeTurnId(o),session:this.initialSession});a.task=s;let c=loadContext().get(CallbackBaseUrlKey),l={taskId:s.taskId,token:s.taskInboxToken,...c===void 0?{}:{url:createWorkflowCallbackUrl(c,createEveCallbackRoutePath(s.taskInboxToken))}},u={batch:r.batch.calls,binding:l,delegated:({executor:e,receipt:t})=>createTaskDelegated({binding:l,executor:e,receipt:t}),send:createTaskSender(s,r.options.toolCallId),session:this.initialSession,task:s},d=r.definition.execute(r.toolInput,r.options,u);if(isAsyncIterable(d))throw Error(`Background tools cannot return AsyncIterable output.`);let f=await d;return isAuthorizationSignal(f)?f:isTaskDelegated(f)?(await deliverTaskCommand(s,{executor:f.executor,kind:`bind`}),a.task={...s,executor:f.executor},a.settled=!0,f.receipt):(await deliverTaskCommand(s,{data:parseJsonValue(f),kind:`complete`}),a.settled=!0,f)}};function requireExecutionScope(e){if(!(e instanceof BackgroundToolExecutionScope))throw Error(`The background tool executor is not owned by the task runtime.`);return e}async function deliverTaskCommand(e,t){if(await sendTaskCommand({command:t,taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${t.kind}".`)}function createTaskSender(e,t){let n=0;return async r=>{if(r.kind!==`update`){await deliverTaskCommand(e,r);return}if(await sendTaskInboundPayload({payload:{callId:t,kind:`task-update`,message:r.message,updateEpoch:e.taskId,updateIndex:n++},taskInboxToken:e.taskInboxToken})!==`delivered`)throw Error(`Task run "${e.taskId}" did not accept "${r.kind}".`)}}async function compensateBackgroundToolExecution(e,t,n){let r=[];for(let i of e.toReversed()){if(i.task===void 0)continue;try{await rejectDelegatedDispatch({error:{code:`PARENT_STEP_FAILED`,message:t instanceof Error?t.message:String(t)},task:i.task})}catch(e){r.push(e)}let e=readSubagentExecutor(i.task.executor);e!==void 0&&await propagateSubagentExecutorCancel({bundle:n,executor:e,taskId:i.task.taskId})}if(r.length>0)throw AggregateError([t,...r],`Background tool execution failed and its tasks could not all be rejected.`,{cause:t})}export{backgroundToolExecutionProvider,readRetainedBackgroundToolResult,runBackgroundStep};
|
|
@@ -14,7 +14,9 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
16
16
|
import type { ApprovalResponseAuth } from "#public/definitions/approval.js";
|
|
17
|
+
import type { ToolContext } from "#public/definitions/tool.js";
|
|
17
18
|
import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
19
|
+
import type { TaskExec } from "#shared/tool-task.js";
|
|
18
20
|
/**
|
|
19
21
|
* Wraps one authored tool's `execute` with a context that supports inline
|
|
20
22
|
* provider auth (`ctx.getToken(connect("..."))`).
|
|
@@ -30,10 +32,16 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
|
30
32
|
* strategies rethrow the original error because they have no consent flow to
|
|
31
33
|
* park on.
|
|
32
34
|
*/
|
|
33
|
-
|
|
35
|
+
type ToolExecuteWithAuthInput<TInput> = {
|
|
34
36
|
readonly scope: string;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
+
} & ({
|
|
38
|
+
readonly execution: "background";
|
|
39
|
+
readonly execute: (toolInput: TInput, ctx: ToolContext, task: TaskExec) => unknown;
|
|
40
|
+
} | {
|
|
41
|
+
readonly execution?: never;
|
|
42
|
+
readonly execute: (toolInput: TInput, ctx: ToolContext, task?: TaskExec) => unknown;
|
|
43
|
+
});
|
|
44
|
+
export declare function createToolExecuteWithAuth<TInput>(input: ToolExecuteWithAuthInput<TInput>): (toolInput: TInput, options: ToolExecuteOptions, task?: TaskExec) => Promise<unknown> | AsyncIterable<unknown>;
|
|
37
45
|
/** Builds the narrow token capability used by approval response authorizers. */
|
|
38
46
|
export declare function buildApprovalResponseAuth(input: {
|
|
39
47
|
readonly responder: SessionAuthContext;
|
|
@@ -41,3 +49,4 @@ export declare function buildApprovalResponseAuth(input: {
|
|
|
41
49
|
}): ApprovalResponseAuth;
|
|
42
50
|
/** Starts authorization requested by an approval response authorizer. */
|
|
43
51
|
export declare function handleApprovalResponsePolicyError(error: unknown): Promise<unknown>;
|
|
52
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{
|
|
1
|
+
import{requestAuthorization}from"#harness/authorization.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{completeScopedAuthorization,evictScopedToken,resolveScopedToken,startScopedAuthorization}from"#runtime/connections/scoped-authorization.js";function createToolExecuteWithAuth(e){let{scope:n}=e;return(r,i,a)=>{let o=buildToolContext({inlineAuthState:{},justAuthorizedScopes:new Set,options:i,scope:n});try{let n;if(e.execution===`background`){if(a===void 0)throw Error(`Background tool execution requires a task runtime.`);n=e.execute(r,o,a)}else n=e.execute(r,o,a);return isAsyncIterable(n)?handleToolIterableErrors(n):Promise.resolve(n).catch(handleToolError)}catch(e){return handleToolError(e)}async function handleToolError(e){if(isToolAuthorizationRequiredError(e))return await handleAuthorizationRequests(e.requests);throw e}async function*handleToolIterableErrors(e){try{for await(let t of e)yield t}catch(e){yield await handleToolError(e)}}}}function buildApprovalResponseAuth(e){let t={},n=new Set;return{async getToken(r,i){if(r===void 0)throw missingProviderError(`ctx.getToken`);return await resolveInlineToken({boundResponder:e.responder,inlineAuthState:t,justAuthorizedScopes:n,options:namespaceApprovalAuthOptions(e.scope,i),provider:r,toolScope:e.scope})},requireAuth(r,i){if(r===void 0)throw missingProviderError(`ctx.requireAuth`);let a=buildInlineScopedAuthorization({boundResponder:e.responder,inlineAuthState:t,options:namespaceApprovalAuthOptions(e.scope,i),provider:r,toolScope:e.scope});throw new ToolAuthorizationRequiredError([{justAuthorized:n.has(a.scope),scoped:a}])}}}function namespaceApprovalAuthOptions(e,t){return t?.authKey===void 0?t:{...t,authKey:`${e}:${t.authKey}`}}async function handleApprovalResponsePolicyError(e){if(!isToolAuthorizationRequiredError(e))throw e;return await handleAuthorizationRequests(e.requests)}function buildToolContext(e){let{scope:t,justAuthorizedScopes:r,inlineAuthState:i}=e;return{...buildBaseToolContext({options:e.options,toolName:t}),async getToken(e,n){if(e===void 0)throw missingProviderError(`ctx.getToken`);return await resolveInlineToken({inlineAuthState:i,justAuthorizedScopes:r,options:n,provider:e,toolScope:t})},requireAuth(e,n){if(e===void 0)throw missingProviderError(`ctx.requireAuth`);let a=buildInlineScopedAuthorization({inlineAuthState:i,options:n,provider:e,toolScope:t});throw new ToolAuthorizationRequiredError([{justAuthorized:r.has(a.scope),scoped:a}])}}}async function resolveInlineToken(e){let{justAuthorizedScopes:t}=e,n=buildInlineScopedAuthorization(e);!t.has(n.scope)&&await completeScopedAuthorization(n)&&t.add(n.scope);try{return await resolveScopedToken(n)}catch(e){throw isConnectionAuthorizationRequiredError(e)?new ToolAuthorizationRequiredError([{cause:e,justAuthorized:t.has(n.scope),scoped:n}]):e}}async function handleAuthorizationRequests(t){let n=[],a;for(let e of t){let{scoped:t}=e;if(e.justAuthorized)throw new ConnectionAuthorizationFailedError(t.scope,{message:`Tool "${t.scope}" rejected the token immediately after authorization.`,reason:`token_rejected_after_authorization`,retryable:!1});await evictScopedToken(t);let s=await startScopedAuthorization(t);if(s!==void 0){n.push(...s.challenges);continue}if(supportsInteractiveAuthorization(t.authorization))throw new ConnectionAuthorizationFailedError(t.scope,{message:`Tool "${t.scope}" requires sign-in, but no authorization callback URL could be minted for this run (missing session context).`,reason:`authorization_callback_unavailable`,retryable:!1});a??=e.cause instanceof Error?e.cause:new ConnectionAuthorizationRequiredError(t.scope)}if(n.length>0)return requestAuthorization(n);throw a??Error(`Tool authorization is required.`)}function buildInlineScopedAuthorization(e){let t=normalizeInlineProvider(e.provider,e.options);return{authorization:t,boundResponder:e.boundResponder,connection:e.options?.connection??{url:``},scope:e.options?.authKey===void 0?deriveInlineScope({authorization:t,inlineAuthState:e.inlineAuthState,provider:e.provider,toolScope:e.toolScope}):validateInlineAuthKey(e.options.authKey)}}function normalizeInlineProvider(e,t){let n=normalizeAuthorizationSpec(e,`ctx.getToken:`,`provider`);if(t?.displayName===void 0)return n;if(t.displayName.length===0)throw Error(`ctx.getToken: The "options.displayName" field must be a non-empty string.`);return{...n,displayName:t.displayName}}function deriveInlineScope(e){let t=e.authorization.vercelConnect?.connector;if(t!==void 0)return`${e.toolScope}__${sanitizeScopeSegment(t)}`;if(e.inlineAuthState.anonymousProvider===void 0)e.inlineAuthState.anonymousProvider=e.provider;else if(e.inlineAuthState.anonymousProvider!==e.provider)throw Error(`ctx.getToken: Multiple inline auth providers without provider metadata need explicit auth keys. Pass options.authKey for each provider, for example ctx.getToken(auth, { authKey: "github" }).`);return`${e.toolScope}__inline_auth`}function validateInlineAuthKey(e){if(!/^[A-Za-z0-9_.:-]+$/u.test(e))throw Error(`ctx.getToken: The "options.authKey" field must contain only letters, digits, "_", "-", ".", or ":".`);return e}function sanitizeScopeSegment(e){let t=e.replace(/[^A-Za-z0-9_.:-]+/gu,`_`).replace(/^_+|_+$/gu,``);return t.length>0?t:`provider`}var ToolAuthorizationRequiredError=class extends Error{requests;constructor(e){super(`Tool authorization required.`),this.name=`ToolAuthorizationRequiredError`,this.requests=e}};function isToolAuthorizationRequiredError(e){return e instanceof Error&&e.name===`ToolAuthorizationRequiredError`}function missingProviderError(e){return Error(`${e}: Pass an auth provider, for example ${e}(connect("github/myagent")).`)}export{buildApprovalResponseAuth,createToolExecuteWithAuth,handleApprovalResponsePolicyError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{
|
|
1
|
+
import{createHook}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{TurnCancelledError}from"#harness/turn-cancellation.js";import{turnCancellationHookToken}from"#execution/turn-cancellation-token.js";async function createTurnCancellationControl(i){let a=createHook({token:turnCancellationHookToken(i.controlToken)}),o=a[Symbol.asyncIterator]();try{await claimHookOwnership(a)}catch(e){if(isHookConflictError(e))return;throw e}let s=new AbortController,c=consumeMatchingCancel(o,i.expectedTurnId,()=>{s.abort(new TurnCancelledError)}).then(()=>`cancel`),l=!1;return{signal:s.signal,requested:c,async dispose(){l||(l=!0,await disposeHook(a))}}}async function consumeMatchingCancel(e,t,n){for(;;){let r=await e.next();if(r.done)return await new Promise(()=>{});if(matchesActiveTurn(r.value,t)){n();return}}}function matchesActiveTurn(e,t){if(typeof e!=`object`||!e)return!0;let n=e.turnId;return n===void 0||n===t}export{createTurnCancellationControl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{dispatchTaskStep}from"#execution/tasks/parent/dispatch-task-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{turnStep}from"#execution/workflow-steps.js";import{getRuntimeActionResultKey}from"#runtime/actions/keys.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let n=migrateTurnWorkflowInput(e);return n.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(n):runLegacyTurnWorkflow(n)}async function runTurnOwnedWorkflow(t){let i=createHook({token:`${t.completionToken}:inbox`}),a=i[Symbol.asyncIterator](),c=new TurnExecutionCursor({controlToken:t.completionToken,parentWritable:t.stepInput.parentWritable,serializedContext:t.stepInput.serializedContext,sessionState:t.stepInput.sessionState}),m=0,nextDeliveryRequestId=()=>`${i.token}:delivery:${String(m++)}`,h=[],g=t.stepInput.input,_=!1,v;try{try{await claimHookOwnership(i),_=!0}catch(e){if(isHookConflictError(e))return;throw e}for(t.driverCapabilities?.cancelledTurnSettle===!0&&(v=await createTurnCancellationControl({controlToken:t.completionToken,expectedTurnId:activeTurnId(t.stepInput.sessionState.emissionState)}));;){let o=await turnStep(c.createStepInput(g,v?.signal)),l
|
|
1
|
+
import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{migrateTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{dispatchTaskStep}from"#execution/tasks/parent/dispatch-task-step.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{runProxySubagentEventStep}from"#execution/subagent-event-proxy-step.js";import{createHook,getWorkflowMetadata,sleep}from"#compiled/@workflow/core/index.js";import{claimHookOwnership,disposeHook,isHookConflictError}from"#execution/hook-ownership.js";import{activeTurnId}from"#harness/active-turn-id.js";import{acknowledgeDelegatedTasksStep}from"#execution/tasks/parent/delegate.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{sendTurnControlStep}from"#execution/turn-control-protocol.js";import{isInboxSubagentResultFromRunningHandle}from"#harness/handles/query.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{cancelDescendantTurnsStep}from"#execution/cancel-descendant-turns-step.js";import{dispatchWorkflowRuntimeActionsStep}from"#execution/dispatch-workflow-runtime-actions-step.js";import{createTurnCancellationControl}from"#execution/turn-cancellation-control.js";import{TurnExecutionCursor}from"#execution/turn-execution-cursor.js";import{turnStep}from"#execution/workflow-steps.js";import{getRuntimeActionResultKey}from"#runtime/actions/keys.js";import{resolveRuntimeActionResultsForKeys}from"#runtime/actions/results.js";const TASK_MODE_WAIT_ERROR_MESSAGE="Task mode cannot wait for follow-up input (`next: null`).";async function turnWorkflow(e){"use workflow";let n=migrateTurnWorkflowInput(e);return n.driverCapabilities?.turnInbox===!0?runTurnOwnedWorkflow(n):runLegacyTurnWorkflow(n)}async function runTurnOwnedWorkflow(t){let i=createHook({token:`${t.completionToken}:inbox`}),a=i[Symbol.asyncIterator](),c=new TurnExecutionCursor({controlToken:t.completionToken,parentWritable:t.stepInput.parentWritable,serializedContext:t.stepInput.serializedContext,sessionState:t.stepInput.sessionState}),m=0,nextDeliveryRequestId=()=>`${i.token}:delivery:${String(m++)}`,h=[],g=t.stepInput.input,_=!1,v;try{try{await claimHookOwnership(i),_=!0}catch(e){if(isHookConflictError(e))return;throw e}for(t.driverCapabilities?.cancelledTurnSettle===!0&&(v=await createTurnCancellationControl({controlToken:t.completionToken,expectedTurnId:activeTurnId(t.stepInput.sessionState.emissionState)}));;){let o={serializedContext:c.serializedContext,sessionState:c.sessionState},l=await turnStep(c.createStepInput(g,v?.signal)),u=l.action===`dispatch-workflow-runtime-actions`||l.action===`park`?l.pendingRuntimeActionKeys:void 0,d=(l.backgroundTasks?.length??0)>0;if(d){if(l.backgroundTaskState===void 0)throw Error(`Background tasks were returned without their committed session state.`);await c.adopt({serializedContext:o.serializedContext,sessionState:l.backgroundTaskState}),await acknowledgeDelegatedTasksStep({tasks:l.backgroundTasks??[]})}if(l.action===`cancelled`){await c.adopt({serializedContext:l.serializedContext,sessionState:c.sessionState}),await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(v?.signal.aborted===!0&&(u===void 0||d)){await c.adopt({serializedContext:preserveSerializedSessionDynamicModelSelection(o.serializedContext,l.serializedContext),sessionState:c.sessionState}),await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(l.sleepDurationMs!==void 0&&await waitForTurnSleep(l.sleepDurationMs,v)===`cancel`){await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}if(l.action===`done`){await v?.dispose(),await c.finish(l,{kind:`done`,output:l.output??``,isError:l.isError,usage:l.usage,usageDelta:l.usageDelta},h);return}if(u!==void 0){await c.adopt(l);let t=l.action===`park`&&l.tasksEnabled,o;o=l.action===`dispatch-workflow-runtime-actions`?dispatchWorkflowRuntimeActionsStep:t?dispatchTaskStep:dispatchRuntimeActionsStep;let d=await o({callbackBaseUrl:resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),parentContinuationToken:i.token,parentWritable:c.parentWritable,serializedContext:c.serializedContext,sessionState:c.sessionState}),f=d.results.length===0?void 0:Date.now();await c.adopt(d),await acknowledgeDelegatedTasksStep({tasks:d.pendingTasks});let p=await waitForRuntimeActionResults({bufferedDeliveries:h,cancellation:v,cursor:c,inboxToken:i.token,initialAcceptedAtMs:f,initialResults:d.results,iterator:a,nextDeliveryRequestId,pendingActionKeys:u});if(p===`cancelled`){g=void 0;continue}if(p===`cancel-turn`){await finishCancelledTurn({bufferedDeliveries:h,cancellation:v,cursor:c});return}g={kind:`runtime-action-result`,...p};continue}if(l.action===`park`){if(!(l.hasPendingAuthorization||l.hasPendingInputBatch&&t.capabilities?.requestInput===!0||t.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);await v?.dispose(),await c.finish(l,{authorizationAttemptIds:l.authorizationAttemptIds,authorizationNames:l.authorizationNames,kind:`park`,settled:l.settled},h);return}await c.adopt(l),g=void 0}}catch(e){throw await c.send({error:normalizeSerializableError(e),kind:`turn-error`}),e}finally{v!==void 0&&await v.dispose(),_&&await disposeHook(i)}}async function finishCancelledTurn(e){await cancelDescendantTurnsStep({serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState}),await e.cancellation?.dispose(),await e.cursor.finish({sessionState:e.cursor.sessionState},{cancelled:!0,kind:`park`},e.bufferedDeliveries)}async function waitForTurnSleep(e,t){if(t?.signal.aborted===!0)return`cancel`;let n=sleep(e).then(()=>`slept`);return t===void 0?n:Promise.race([n,t.requested])}async function waitForRuntimeActionResults(e){let t,n=[...e.initialResults],r=new Map;if(e.initialAcceptedAtMs!==void 0)for(let t of e.initialResults)r.set(getRuntimeActionResultKey(t),e.initialAcceptedAtMs);for(;;){let o=resolveRuntimeActionResultsForKeys({pendingKeys:e.pendingActionKeys,results:n});if(o!==void 0)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),{acceptedAtMsByCallId:Object.fromEntries(o.map(e=>[e.callId,r.get(getRuntimeActionResultKey(e))])),results:o};e.cursor.sessionState.hasProxyInputRequests&&t===void 0&&(t=e.nextDeliveryRequestId(),await e.cursor.send({continuationToken:e.cursor.sessionState.continuationToken,inboxToken:e.inboxToken,kind:`turn-delivery-request`,requestId:t}));let s=e.iterator.next();s.catch(()=>{});let c=await(e.cancellation===void 0?s:Promise.race([s,e.cancellation.requested]));if(c===`cancel`)return t!==void 0&&await e.cursor.send({kind:`turn-delivery-cancelled`,requestId:t}),`cancelled`;if(c.done)throw Error(`Turn inbox closed before runtime actions completed.`);let l=c.value;if(l.kind===`runtime-action-result`){let t=e.cursor.sessionState.snapshot?.session.state,i=l.results.filter(e=>isInboxSubagentResultFromRunningHandle(t,e));if(i.length>0){let e=Date.now();n.push(...i);for(let t of i)r.set(getRuntimeActionResultKey(t),e)}continue}if(l.kind===`subagent-input-request`||l.kind===`subagent-authorization-event`){let t=await runProxySubagentEventStep({hookPayload:l,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});await e.cursor.adopt(t);continue}if(l.kind===`driver-delivery`&&l.requestId===t){await e.cursor.send({kind:`turn-delivery-accepted`,requestId:l.requestId}),t=void 0;let n=await routeDeliverToChildren({delivery:l.delivery,parentWritable:e.cursor.parentWritable,serializedContext:e.cursor.serializedContext,sessionState:e.cursor.sessionState});if(await e.cursor.adopt({serializedContext:n.serializedContext??e.cursor.serializedContext,sessionState:n.sessionState??e.cursor.sessionState}),n.kind===`cancel-turn`)return n.kind;n.remainder!==void 0&&e.bufferedDeliveries.push(n.remainder)}}}async function runLegacyTurnWorkflow(e){let t=e.stepInput;try{for(;;){let n=await turnStep(t);if(n.action!==`cancelled`&&n.sleepDurationMs!==void 0&&await sleep(n.sleepDurationMs),n.action===`done`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`done`,output:n.output??``,isError:n.isError,serializedContext:n.serializedContext,sessionState:n.sessionState,usage:n.usage,usageDelta:n.usageDelta},kind:`turn-result`}});return}if(n.action===`dispatch-workflow-runtime-actions`){await sendTurnControlStep({controlToken:e.completionToken,payload:{action:{kind:`dispatch-workflow-runtime-actions`,pendingActionKeys:n.pendingRuntimeActionKeys,serializedContext:n.serializedContext,sessionState:n.sessionState},kind:`turn-result`}});return}if(n.action===`park`){let t=n.pendingRuntimeActionKeys;if(!(t!==void 0||n.hasPendingAuthorization||n.hasPendingInputBatch&&e.capabilities?.requestInput===!0||e.mode===`conversation`))throw Error(TASK_MODE_WAIT_ERROR_MESSAGE);let r=t===void 0?{kind:`park`,serializedContext:n.serializedContext,sessionState:n.sessionState,authorizationAttemptIds:n.authorizationAttemptIds,authorizationNames:n.authorizationNames,settled:n.settled}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:n.serializedContext,sessionState:n.sessionState};await sendTurnControlStep({controlToken:e.completionToken,payload:{action:r,kind:`turn-result`}});return}t={input:void 0,parentWritable:t.parentWritable,serializedContext:n.serializedContext,sessionState:n.sessionState}}}catch(t){throw await sendTurnControlStep({controlToken:e.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}export{turnWorkflow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inputRequestSchema,inputResponseSchema}from"#runtime/input/types.js";import{z}from"#compiled/zod/index.js";import{formatValidationError}from"#runtime/validation.js";import{jsonObjectSchema,jsonValueSchema}from"#shared/json-schemas.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{SessionInboxWireError}from"#execution/wire/session-inbox-contract.js";import{tokenUsageSchema}from"#shared/token-usage.js";const providerOptionsSchema=z.record(z.string(),jsonObjectSchema),textPartSchema=z.object({providerOptions:providerOptionsSchema.optional(),text:z.string(),type:z.literal(`text`)}).strict(),binaryDataSchema=z.custom(e=>typeof e==`string`||e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof URL,`Expected a string, URL, Uint8Array, or ArrayBuffer.`),imagePartSchema=z.object({image:binaryDataSchema,mediaType:z.string().optional(),providerOptions:providerOptionsSchema.optional(),type:z.literal(`image`)}).strict(),filePartSchema=z.object({data:binaryDataSchema,filename:z.string().optional(),mediaType:z.string(),providerOptions:providerOptionsSchema.optional(),type:z.literal(`file`)}).strict(),userContentSchema=z.union([z.string(),z.array(z.discriminatedUnion(`type`,[textPartSchema,imagePartSchema,filePartSchema]))]),eventCoordinateSchema=z.number().int().nonnegative(),opaqueObjectSchema=z.custom(e=>typeof e==`object`&&!!e&&!Array.isArray(e),`Expected an object.`),subagentInputRequestHookPayloadSchema=z.object({callId:z.string(),childContinuationToken:z.string(),childSessionId:z.string(),event:z.object({requests:z.array(inputRequestSchema),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string()}).strict(),kind:z.literal(`subagent-input-request`),subagentName:z.string()}).strict(),subagentAuthorizationEventHookPayloadSchema=z.object({callId:z.string(),childSessionId:z.string(),event:opaqueObjectSchema,kind:z.literal(`subagent-authorization-event`),subagentName:z.string()}).strict(),taskMetadataSchema=z.object({agentId:z.string(),kind:z.literal(`subagent`),mode:z.enum([`local`,`remote`]),name:z.string()}).strict(),taskViewBase={executor:z.object({childSessionId:z.string().optional(),childTurnId:z.string().optional(),lifecycle:z.enum([`parked`,`terminal`]).optional()}).strict().optional(),metadata:taskMetadataSchema,taskId:z.string(),usage:tokenUsageSchema.optional()},taskViewSchema=z.discriminatedUnion(`status`,[z.object({...taskViewBase,status:z.literal(`working`)}).strict(),z.object({...taskViewBase,inputRequests:z.array(jsonValueSchema),status:z.literal(`input_required`)}).strict(),z.object({...taskViewBase,lastOutput:z.object({data:jsonValueSchema,type:z.literal(`result`)}).strict(),status:z.literal(`completed`)}).strict(),z.object({...taskViewBase,lastOutput:z.object({data:jsonValueSchema,type:z.literal(`error`)}).strict(),status:z.literal(`failed`)}).strict(),z.object({...taskViewBase,status:z.literal(`cancelled`)}).strict()]),taskPayloadSchema=z.object({authorizationEvents:z.array(z.object({hookPayload:subagentAuthorizationEventHookPayloadSchema,taskId:z.string()}).strict()).optional(),inputRequests:z.array(z.object({hookPayload:subagentInputRequestHookPayloadSchema,taskId:z.string()}).strict()).optional(),views:z.array(taskViewSchema).optional()}).strict(),deliverPayloadSchema=z.object({context:z.array(z.string()).optional(),inputResponses:z.array(inputResponseSchema).optional(),message:userContentSchema.optional(),outputSchema:jsonObjectSchema.optional(),task:taskPayloadSchema.optional()}).loose(),authSchema=z.object({attributes:z.record(z.string(),z.union([z.string(),z.array(z.string())])),authenticator:z.string(),issuer:z.string().optional(),principalId:z.string(),principalType:z.string(),subject:z.string().optional()}).strict(),callerSchema=z.object({callId:z.string(),replyTo:z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`hook`),token:z.string()}).strict(),z.object({kind:z.literal(`callback`),token:z.string(),url:z.string()}).strict()]),subagentName:z.string(),taskId:z.string().optional()}).strict(),traceContextSchema=z.object({spanId:z.string(),traceFlags:z.number(),traceId:z.string()}).strict(),deliveryMetadataSchema=z.object({channelKind:z.string(),channelName:z.string(),deliveryId:z.string(),payloadIndex:z.number().int().nonnegative(),requestId:z.string().optional(),requestTraceContext:traceContextSchema.optional()}).strict(),version=z.literal(1),sessionInboxWireV1Schema=z.discriminatedUnion(`kind`,[z.object({auth:authSchema.nullable().optional(),caller:callerSchema.optional(),deliveryMetadata:z.array(deliveryMetadataSchema).optional(),kind:z.literal(`deliver`),payload:deliverPayloadSchema.optional(),payloads:z.array(deliverPayloadSchema),requestId:z.string().optional(),taskDeliveryId:z.string().optional(),turnPolicy:z.enum([`queue`,`steer`]).optional(),version}).strict(),z.object({kind:z.literal(`session-timeout`),version}).strict(),z.object({kind:z.literal(`clear`),version}).strict(),z.object({kind:z.literal(`compact`),version}).strict(),z.object({kind:z.literal(`reset`),reason:z.string().optional(),version}).strict(),z.object({kind:z.literal(`cancel`),taskId:z.string().optional(),turnId:z.string().optional(),version}).strict()]);function encodeSessionCommandV1(e){let t=e.kind===`send`?{auth:e.auth,caller:e.caller,deliveryMetadata:e.delivery===void 0?void 0:[{...e.delivery,payloadIndex:0}],kind:`deliver`,payload:e.payload,payloads:[e.payload],requestId:e.requestId,taskDeliveryId:e.taskDeliveryId,turnPolicy:e.turnPolicy,version:1}:e.kind===`deliver`?{...e,payload:coalesceDeliverPayloads(e.payloads),version:1}:{...e,version:1},n=sessionInboxWireV1Schema.safeParse(t);if(!n.success)throw new SessionInboxWireError(`Produced a session inbox payload that does not match wire version 1: ${formatValidationError(n.error)}`);return n.data}export{encodeSessionCommandV1,sessionInboxWireV1Schema};
|
|
1
|
+
import{inputRequestSchema,inputResponseSchema}from"#runtime/input/types.js";import{z}from"#compiled/zod/index.js";import{formatValidationError}from"#runtime/validation.js";import{jsonObjectSchema,jsonValueSchema}from"#shared/json-schemas.js";import{coalesceDeliverPayloads}from"#execution/deliver-payloads.js";import{SessionInboxWireError}from"#execution/wire/session-inbox-contract.js";import{tokenUsageSchema}from"#shared/token-usage.js";const providerOptionsSchema=z.record(z.string(),jsonObjectSchema),textPartSchema=z.object({providerOptions:providerOptionsSchema.optional(),text:z.string(),type:z.literal(`text`)}).strict(),binaryDataSchema=z.custom(e=>typeof e==`string`||e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof URL,`Expected a string, URL, Uint8Array, or ArrayBuffer.`),imagePartSchema=z.object({image:binaryDataSchema,mediaType:z.string().optional(),providerOptions:providerOptionsSchema.optional(),type:z.literal(`image`)}).strict(),filePartSchema=z.object({data:binaryDataSchema,filename:z.string().optional(),mediaType:z.string(),providerOptions:providerOptionsSchema.optional(),type:z.literal(`file`)}).strict(),userContentSchema=z.union([z.string(),z.array(z.discriminatedUnion(`type`,[textPartSchema,imagePartSchema,filePartSchema]))]),eventCoordinateSchema=z.number().int().nonnegative(),opaqueObjectSchema=z.custom(e=>typeof e==`object`&&!!e&&!Array.isArray(e),`Expected an object.`),subagentInputRequestHookPayloadSchema=z.object({callId:z.string(),childContinuationToken:z.string(),childSessionId:z.string(),event:z.object({requests:z.array(inputRequestSchema),sequence:eventCoordinateSchema,stepIndex:eventCoordinateSchema,turnId:z.string()}).strict(),kind:z.literal(`subagent-input-request`),subagentName:z.string()}).strict(),subagentAuthorizationEventHookPayloadSchema=z.object({callId:z.string(),childSessionId:z.string(),event:opaqueObjectSchema,kind:z.literal(`subagent-authorization-event`),subagentName:z.string()}).strict(),taskMetadataSchema=z.union([z.object({agentId:z.string(),kind:z.literal(`subagent`),mode:z.enum([`local`,`remote`]),name:z.string()}).strict(),z.object({kind:z.string(),name:z.string()}).strict()]),taskViewBase={executor:z.object({binding:z.object({data:z.record(z.string(),jsonValueSchema),kind:z.string()}).strict().optional(),childSessionId:z.string().optional(),childTurnId:z.string().optional(),lifecycle:z.enum([`parked`,`terminal`]).optional()}).strict().optional(),metadata:taskMetadataSchema,taskId:z.string(),usage:tokenUsageSchema.optional()},taskViewSchema=z.discriminatedUnion(`status`,[z.object({...taskViewBase,status:z.literal(`working`)}).strict(),z.object({...taskViewBase,inputRequests:z.array(jsonValueSchema),status:z.literal(`input_required`)}).strict(),z.object({...taskViewBase,lastOutput:z.object({data:jsonValueSchema,type:z.literal(`result`)}).strict(),status:z.literal(`completed`)}).strict(),z.object({...taskViewBase,lastOutput:z.object({data:jsonValueSchema,type:z.literal(`error`)}).strict(),status:z.literal(`failed`)}).strict(),z.object({...taskViewBase,status:z.literal(`cancelled`)}).strict()]),taskPayloadSchema=z.object({authorizationEvents:z.array(z.object({hookPayload:subagentAuthorizationEventHookPayloadSchema,taskId:z.string()}).strict()).optional(),inputRequests:z.array(z.object({hookPayload:subagentInputRequestHookPayloadSchema,taskId:z.string()}).strict()).optional(),views:z.array(taskViewSchema).optional()}).strict(),deliverPayloadSchema=z.object({context:z.array(z.string()).optional(),inputResponses:z.array(inputResponseSchema).optional(),message:userContentSchema.optional(),outputSchema:jsonObjectSchema.optional(),task:taskPayloadSchema.optional()}).loose(),authSchema=z.object({attributes:z.record(z.string(),z.union([z.string(),z.array(z.string())])),authenticator:z.string(),issuer:z.string().optional(),principalId:z.string(),principalType:z.string(),subject:z.string().optional()}).strict(),callerSchema=z.object({callId:z.string(),replyTo:z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`hook`),token:z.string()}).strict(),z.object({kind:z.literal(`callback`),token:z.string(),url:z.string()}).strict()]),subagentName:z.string(),taskId:z.string().optional()}).strict(),traceContextSchema=z.object({spanId:z.string(),traceFlags:z.number(),traceId:z.string()}).strict(),deliveryMetadataSchema=z.object({channelKind:z.string(),channelName:z.string(),deliveryId:z.string(),payloadIndex:z.number().int().nonnegative(),requestId:z.string().optional(),requestTraceContext:traceContextSchema.optional()}).strict(),version=z.literal(1),sessionInboxWireV1Schema=z.discriminatedUnion(`kind`,[z.object({auth:authSchema.nullable().optional(),caller:callerSchema.optional(),deliveryMetadata:z.array(deliveryMetadataSchema).optional(),kind:z.literal(`deliver`),payload:deliverPayloadSchema.optional(),payloads:z.array(deliverPayloadSchema),requestId:z.string().optional(),taskDeliveryId:z.string().optional(),turnPolicy:z.enum([`queue`,`steer`]).optional(),version}).strict(),z.object({kind:z.literal(`session-timeout`),version}).strict(),z.object({kind:z.literal(`clear`),version}).strict(),z.object({kind:z.literal(`compact`),version}).strict(),z.object({kind:z.literal(`reset`),reason:z.string().optional(),version}).strict(),z.object({kind:z.literal(`cancel`),taskId:z.string().optional(),turnId:z.string().optional(),version}).strict()]);function encodeSessionCommandV1(e){let t=e.kind===`send`?{auth:e.auth,caller:e.caller,deliveryMetadata:e.delivery===void 0?void 0:[{...e.delivery,payloadIndex:0}],kind:`deliver`,payload:e.payload,payloads:[e.payload],requestId:e.requestId,taskDeliveryId:e.taskDeliveryId,turnPolicy:e.turnPolicy,version:1}:e.kind===`deliver`?{...e,payload:coalesceDeliverPayloads(e.payloads),version:1}:{...e,version:1},n=sessionInboxWireV1Schema.safeParse(t);if(!n.success)throw new SessionInboxWireError(`Produced a session inbox payload that does not match wire version 1: ${formatValidationError(n.error)}`);return n.data}export{encodeSessionCommandV1,sessionInboxWireV1Schema};
|
|
@@ -1,58 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { TokenUsage } from "#shared/token-usage.js";
|
|
3
|
-
import { type DurableSessionState } from "#execution/durable-session-store.js";
|
|
1
|
+
import type { DurableStepResult } from "#execution/next-driver-action.js";
|
|
4
2
|
import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
|
|
5
|
-
/**
|
|
6
|
-
* Result of one durable harness step. `cancelled` is returned so workflow-core
|
|
7
|
-
* does not retry it; `park` carries the pending state needed by the next action.
|
|
8
|
-
*/
|
|
9
|
-
export type DurableStepResult = {
|
|
10
|
-
readonly action: "continue" | "done";
|
|
11
|
-
readonly output?: unknown;
|
|
12
|
-
readonly isError?: boolean;
|
|
13
|
-
/**
|
|
14
|
-
* Optional durable pause for the turn workflow to fulfill before
|
|
15
|
-
* dispatching this result's next action.
|
|
16
|
-
*/
|
|
17
|
-
readonly sleepDurationMs?: number;
|
|
18
|
-
readonly serializedContext: Record<string, unknown>;
|
|
19
|
-
readonly sessionState: DurableSessionState;
|
|
20
|
-
/** Session-total token usage; set on `done` when the session spent any. */
|
|
21
|
-
readonly usage?: TokenUsage;
|
|
22
|
-
/**
|
|
23
|
-
* Usage the final turn added beyond what earlier settled turns already
|
|
24
|
-
* reported; feeds the terminal `AgentTurnOutcome` for conversation
|
|
25
|
-
* children. Task sessions settle once, so their callers read `usage`.
|
|
26
|
-
*/
|
|
27
|
-
readonly usageDelta?: TokenUsage;
|
|
28
|
-
} | {
|
|
29
|
-
readonly action: "cancelled";
|
|
30
|
-
readonly serializedContext: Record<string, unknown>;
|
|
31
|
-
readonly sessionState: DurableSessionState;
|
|
32
|
-
} | {
|
|
33
|
-
readonly action: "park";
|
|
34
|
-
readonly authorizationAttemptIds?: readonly string[];
|
|
35
|
-
readonly authorizationNames?: readonly string[];
|
|
36
|
-
readonly hasPendingAuthorization: boolean;
|
|
37
|
-
readonly hasPendingInputBatch: boolean;
|
|
38
|
-
readonly pendingRuntimeActionKeys?: readonly string[];
|
|
39
|
-
/**
|
|
40
|
-
* Selects the dispatch step for `pendingRuntimeActionKeys`:
|
|
41
|
-
* `dispatchTaskStep` when the agent runs `experimental.tasks`,
|
|
42
|
-
* `dispatchRuntimeActionsStep` otherwise (including when absent).
|
|
43
|
-
*/
|
|
44
|
-
readonly tasksEnabled?: boolean;
|
|
45
|
-
readonly sleepDurationMs?: number;
|
|
46
|
-
readonly serializedContext: Record<string, unknown>;
|
|
47
|
-
readonly sessionState: DurableSessionState;
|
|
48
|
-
readonly settled?: SettledTurn;
|
|
49
|
-
} | {
|
|
50
|
-
readonly action: "dispatch-workflow-runtime-actions";
|
|
51
|
-
readonly pendingRuntimeActionKeys: readonly string[];
|
|
52
|
-
readonly sleepDurationMs?: number;
|
|
53
|
-
readonly serializedContext: Record<string, unknown>;
|
|
54
|
-
readonly sessionState: DurableSessionState;
|
|
55
|
-
};
|
|
56
3
|
export type { TurnStepInput };
|
|
57
4
|
/**
|
|
58
5
|
* Runs one atomic harness step inside a durable `"use step"` boundary.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{runStep}from"#context/run-step.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,hydrateDynamicSessionTools,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext);a.input?.kind===`deliver`&&c.set(TurnTaskDeliveryKey,a.input.taskDeliveryId!==void 0);let l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0,f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&isTaskToolAvailable({disabledFrameworkTools:u.resolvedAgent.disabledFrameworkTools??[],hasAuthoredTool:f.turnAgent.tools.some(e=>e.name===TASK_UPDATE_TOOL_NAME),tasksEnabled:d,toolName:TASK_UPDATE_TOOL_NAME});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=getInstrumentationRuntime(),v=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:_?.hooks,rootSessionId:g.rootSessionId??g.sessionId,sequence:v.sequence,sessionId:g.sessionId,turnId:activeTurnId(v)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:_?.hooks,includeTurn:!1,outcome:`failed`})),await _?.forceFlush()},y=buildAdapterContext(l,c),b;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,y):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}b=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),b={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...y.state}}),o.input?.kind===`deliver`&&b===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:_?.hooks,includeTurn:!1,outcome:`completed`})),await _?.forceFlush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),n=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let x=u.hookRegistry,S=u.resolvedAgent.dynamicInstructionsResolvers??[],C=u.resolvedAgent.dynamicSkillResolvers??[],w=u.subagentRegistry.dynamicResolvers??[],T=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,E=u.resolvedAgent.dynamicToolResolvers??[],D={...u.graph.root,turnAgent:f.turnAgent},O=buildRuntimeIdentity(D);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!v.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:O});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:w,event:e,messages:g.history,persistentSessions:T,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:E,event:e,messages:g.history,runtimeRevision:t})]),await hydrateDynamicSessionTools({ctx:c,resolvers:E,event:e,messages:g.history})}}catch(e){throw await failChannelDeliveries(e),e}let k=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,y);setChannelContext(c,{...l,state:{...y.state}});let r=stampMessageStreamEvent(n);return await k.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e);await dispatchStreamEventHooks({ctx:c,registry:x,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:w,event:n,messages:t??[],persistentSessions:T}),await dispatchDynamicToolEvent({ctx:c,resolvers:E,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:C,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:S,event:n,messages:t??[]})},A=c.require(ModeKey),j;try{throwIfTurnAborted(o.abortSignal),j=await runStep(c,g,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:b,mode:A,session:e});if(h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,t.history);let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:O,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,O,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:A,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:D,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,b)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;k.releaseLock();let t=serializeContext(c);return{action:`cancelled`,serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:o.sessionState}}let M=reconcileSessionContinuationToken(c,j.session),N=serializeContext(c);j={...j,session:M};let P=createDurableSessionState({session:j.session}),F=readTurnSleepDurationMs(c),I=F===void 0?{}:{sleepDurationMs:F};if(j.next!==null&&typeof j.next==`object`&&`done`in j.next){if(A===`task`&&hasPendingInputBatch(j.session.state))throw k.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await k.close();let e=getTurnUsageState(j.session.state)?.session;return{action:`done`,output:j.next.output,isError:j.next.isError,...I,serializedContext:N,sessionState:P,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(j.session).delta}}if(j.next===null){k.releaseLock();let e=getPendingWorkflowInterrupt(j.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...I,serializedContext:N,sessionState:P};let t=derivePendingState(j.session);if(j.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(j.session);return{action:`park`,...t,...I,serializedContext:N,sessionState:createDurableSessionState({session:n}),settled:{output:j.settledTurn.output,isError:j.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...t,...I,serializedContext:N,sessionState:P,tasksEnabled:d}}return k.releaseLock(),{action:`continue`,...I,serializedContext:N,sessionState:P}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}export{turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,HandleEventKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey,TasksEnabledKey,TurnTaskDeliveryKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,setHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{TASK_UPDATE_SESSION_INSTRUCTION,isTaskOwnedSerializedContext}from"#execution/tasks/child/instructions.js";import{TASK_UPDATE_TOOL_NAME,isTaskToolAvailable}from"#runtime/framework-tools/tasks.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{activeTurnId}from"#harness/active-turn-id.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{preserveSerializedSessionDynamicModelSelection}from"#context/serialized-dynamic-model-selection.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{channelDeliveryErrorCode,instrumentChannelDelivery}from"#harness/channel-delivery-instrumentation.js";import{preserveSerializedInstrumentationState}from"#harness/instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{matchAuthorizationCallbacks}from"#execution/authorization-callback-match.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{forwardTaskEventToSessionCallback}from"#execution/task-event-callback.js";import{resolveEffectiveOutputSchema}from"#execution/effective-output-schema.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{appendTaskAgentAnnouncement}from"#execution/tasks/parent/agent-views.js";import{resolveTaskDeliveryContext}from"#tasks/delivery-context.js";import{readRetainedBackgroundToolResult,runBackgroundStep}from"#execution/tasks/parent/tool-execution.js";import{prepareWorkflowPreambleTrace}from"#execution/workflow-trace-context.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{createExecutionHistoryView}from"#execution/history-view.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext);a.input?.kind===`deliver`&&c.set(TurnTaskDeliveryKey,`none`);let l=c.require(ChannelKey),u=c.require(BundleKey),d=u.resolvedAgent.config?.experimental?.tasks===!0;c.set(TasksEnabledKey,d);let f=resolveEffectiveAgentRuntime(u,c),p=isTaskOwnedSerializedContext(o.serializedContext)&&isTaskToolAvailable({disabledFrameworkTools:u.resolvedAgent.disabledFrameworkTools??[],hasAuthoredTool:f.turnAgent.tools.some(e=>e.name===TASK_UPDATE_TOOL_NAME),tasksEnabled:d,toolName:TASK_UPDATE_TOOL_NAME});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let m=getPendingAuthorization(s.state),h;if(m&&o.input?.kind===`deliver`){let{matches:e,remainingPayloads:t}=matchAuthorizationCallbacks(m,o.input.payloads);if(o={...o,input:{...o.input,payloads:t}},e.length>0){let n=e.map(e=>e.result);c.set(PendingAuthorizationResultKey,n),s={...s,state:clearPendingAuthorization(s.state,n.map(e=>e.attemptId??e.name))},h=e,t.length===0&&(o={...o,input:void 0})}}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let g=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.thresholdPercent},durable:s,turnAgent:f.turnAgent}),_=createExecutionHistoryView(g),v=getInstrumentationRuntime(),y=getHarnessEmissionState(g.state);a.input?.kind===`deliver`&&await contextStorage.run(c,()=>instrumentChannelDelivery({agentName:u.turnAgent.id,ctx:c,delivery:a.input,hooks:v?.hooks,rootSessionId:g.rootSessionId??g.sessionId,sequence:y.sequence,sessionId:g.sessionId,turnId:activeTurnId(y)}));let failChannelDeliveries=async e=>{await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,error:e,errorCode:channelDeliveryErrorCode(e),hooks:v?.hooks,includeTurn:!1,outcome:`failed`})),await v?.forceFlush()},b=buildAdapterContext(l,c),x;if(o.input?.kind===`deliver`){let e=[];try{for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,b):defaultDeliverResult(n);r!=null&&e.push(r)}}catch(e){throw await failChannelDeliveries(e),e}x=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),o.input.acceptedAtMsByCallId!==void 0&&c.set(RuntimeActionSettlementTimesKey,o.input.acceptedAtMsByCallId),x={runtimeActionResults:o.input.results});if(x!==void 0&&a.input?.kind===`deliver`&&a.input.taskDeliveryId!==void 0){let e=resolveTaskDeliveryContext({state:s.state,taskDeliveryId:a.input.taskDeliveryId});e!==void 0&&(c.set(TurnTaskDeliveryKey,e.phase),x={...x,context:[...x.context??[],e.context]})}if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...b.state}}),o.input?.kind===`deliver`&&x===void 0){await contextStorage.run(c,()=>instrumentChannelDelivery({ctx:c,hooks:v?.hooks,includeTurn:!1,outcome:`completed`})),await v?.forceFlush();let e=reconcileSessionContinuationToken(c,g),t=serializeContext(c),n=e===g?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n,tasksEnabled:d}}let S=u.hookRegistry,C=u.resolvedAgent.dynamicInstructionsResolvers??[],w=u.resolvedAgent.dynamicSkillResolvers??[],T=u.subagentRegistry.dynamicResolvers??[],E=d||u.resolvedAgent.config?.experimental?.subagentPersistentSessions===!0,D=u.resolvedAgent.dynamicToolResolvers??[],O={...u.graph.root,turnAgent:f.turnAgent},k=buildRuntimeIdentity(O);try{let e=process.env.VERCEL_DEPLOYMENT_ID?.trim(),t=e?`deployment:${e}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!y.sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,t),c.set(SessionDynamicToolRuntimeRevisionKey,t);else{let e=createSessionStartedEvent({runtime:k});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:T,event:e,messages:_.initial.messages,persistentSessions:E,runtimeRevision:t}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:D,event:e,messages:_.initial.messages,runtimeRevision:t})])}}catch(e){throw await failChannelDeliveries(e),e}let A=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,b);setChannelContext(c,{...l,state:{...b.state}});let r=stampMessageStreamEvent(n);return await A.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await forwardTaskEventToSessionCallback(c,e)?stampMessageStreamEvent(e):await emit(e);await dispatchStreamEventHooks({ctx:c,registry:S,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:f.turnAgent.dynamicModel,event:n,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:T,event:n,messages:t??[],persistentSessions:E}),await dispatchDynamicToolEvent({ctx:c,resolvers:D,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:w,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:C,event:n,messages:t??[]})},j=c.require(ModeKey),M;try{throwIfTurnAborted(o.abortSignal),M=await runBackgroundStep(c,g,async e=>{c.setVirtualContext(HandleEventKey,handleEvent);let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:x,mode:j,session:e});if(h){let e=getHarnessEmissionState(t.state);if(isHarnessBetweenTurns(t)){prepareDynamicInstructionPreamble(c,_.messages(t));let n=[],r=await prepareWorkflowPreambleTrace({ctx:c,emissionState:e,runtimeIdentity:k,session:t});try{e=await emitTurnPreamble(handleEvent,{},e,k,r)}finally{n=drainDynamicInstructionUserMessages(c),t={...t,history:[...t.history,...n]}}t=setHarnessEmissionState(t,e)}for(let{authorization:t,result:n}of h){let r=m?.challenges.find(e=>e.attemptId===n.attemptId)?.candidateId;await handleEvent(createAuthorizationCompletedEvent({attemptId:n.attemptId,authorization:t,candidateId:r,name:n.name,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.thresholdPercent},session:e,systemPromptAdditions:p?[TASK_UPDATE_SESSION_INSTRUCTION]:void 0,turnAgent:f.turnAgent}),i=d?await appendTaskAgentAnnouncement(r,_.messages(r)):r;return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,historyProjector:_.projector,historyView:_.prepare(i),mode:j,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:O,workflowMaxSubagents:r.workflowMaxSubagents})(i,t)})(t,x)})}catch(e){if(!isTurnCancellation(e))throw await failChannelDeliveries(e),e;A.releaseLock();let t=serializeContext(c),n=readRetainedBackgroundToolResult(c);return{action:`cancelled`,...n===void 0?{}:{backgroundTaskState:createDurableSessionState({session:n.backgroundTaskSession}),backgroundTasks:n.backgroundTasks},serializedContext:preserveSerializedInstrumentationState(preserveSerializedAgentTraceState(preserveSerializedSessionDynamicModelSelection(o.serializedContext,t),t),t),sessionState:o.sessionState}}let N=reconcileSessionContinuationToken(c,M.session),P=serializeContext(c);M={...M,session:N};let F=createDurableSessionState({session:M.session}),I=readTurnSleepDurationMs(c),L=I===void 0?{}:{sleepDurationMs:I},R=M.backgroundTasks===void 0||M.backgroundTaskSession===void 0?{}:{backgroundTaskState:createDurableSessionState({session:M.backgroundTaskSession}),backgroundTasks:M.backgroundTasks};if(M.next!==null&&typeof M.next==`object`&&`done`in M.next){if(j===`task`&&hasPendingInputBatch(M.session.state))throw A.releaseLock(),Error(`Task mode cannot complete while input requests remain pending.`);await A.close();let e=getTurnUsageState(M.session.state)?.session;return{action:`done`,...R,output:M.next.output,isError:M.next.isError,...L,serializedContext:P,sessionState:F,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(M.session).delta}}if(M.next===null){A.releaseLock();let e=getPendingWorkflowInterrupt(M.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,...R,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...L,serializedContext:P,sessionState:F};let t=derivePendingState(M.session);if(M.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(M.session);return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:createDurableSessionState({session:n}),settled:{output:M.settledTurn.output,isError:M.settledTurn.isError,usage:e},tasksEnabled:d}}return{action:`park`,...R,...t,...L,serializedContext:P,sessionState:F,tasksEnabled:d}}return A.releaseLock(),{action:`continue`,...R,...L,serializedContext:P,sessionState:F}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationAttemptIds:n?.challenges.flatMap(e=>e.attemptId===void 0?[]:[e.attemptId]),authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}export{turnStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{TASK_TOOL_NAMES,TASK_UPDATE_TOOL_NAME}from"#runtime/framework-tools/tasks.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session,e.delegatedCaller):filterUnavailableDelegationToolMap(e.tools,e.session,e.delegatedCaller)}async function getAdvertisedModelTools(e){let t=filterUnavailableDelegationToolMap(e.tools,e.session,e.delegatedCaller);if(e.workflow===void 0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let n=filterWorkflowHostToolsForRootSession(t,e.session);if(n.size===0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let r=ensureWorkflowContinuationSecurity(e.session),{modelTools:i}=await applyWorkflowTool({continuationSecurity:getWorkflowContinuationSecurity(r),harnessTools:n,lifecycle:e.workflow.lifecycle?.({session:r,tools:n}),maxSubagents:e.workflow.maxSubagents,tools:e.modelTools});return{harnessTools:t,modelTools:i,session:r}}function filterUnavailableDelegationToolDefinitions(e,t,n){let r=[];for(let i of e)shouldHideDelegationTool(i,t,n)||r.push(i);return r}function filterUnavailableDelegationToolMap(e,t,n){let r=new Map;for(let[i,a]of e)shouldHideDelegationTool(a,t,n)||r.set(i,a);return r}function filterWorkflowHostToolsForRootSession(e,t){let r=new Map,i=resolveSubagentDepth(t);if(t.rootSessionId!==void 0||i.currentDepth>0)return r;for(let[t,n]of e)
|
|
1
|
+
import{TASK_TOOL_NAMES,TASK_UPDATE_TOOL_NAME}from"#runtime/framework-tools/tasks.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{ensureWorkflowContinuationSecurity,getWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{applyWorkflowTool}from"#harness/workflow-sandbox.js";function getAdvertisedTools(e){return`modelTools`in e?getAdvertisedModelTools(e):isToolDefinitionList(e.tools)?filterUnavailableDelegationToolDefinitions(e.tools,e.session,e.delegatedCaller):filterUnavailableDelegationToolMap(e.tools,e.session,e.delegatedCaller)}async function getAdvertisedModelTools(e){let t=filterUnavailableDelegationToolMap(e.tools,e.session,e.delegatedCaller);if(e.workflow===void 0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let n=filterWorkflowHostToolsForRootSession(t,e.session);if(n.size===0)return{harnessTools:t,modelTools:e.modelTools,session:e.session};let r=ensureWorkflowContinuationSecurity(e.session),{modelTools:i}=await applyWorkflowTool({continuationSecurity:getWorkflowContinuationSecurity(r),harnessTools:n,lifecycle:e.workflow.lifecycle?.({session:r,tools:n}),maxSubagents:e.workflow.maxSubagents,tools:e.modelTools});return{harnessTools:t,modelTools:i,session:r}}function filterUnavailableDelegationToolDefinitions(e,t,n){let r=[];for(let i of e)shouldHideDelegationTool(i,t,n)||r.push(i);return r}function filterUnavailableDelegationToolMap(e,t,n){let r=new Map;for(let[i,a]of e)shouldHideDelegationTool(a,t,n)||r.set(i,a);return r}function filterWorkflowHostToolsForRootSession(e,t){let r=new Map,i=resolveSubagentDepth(t);if(t.rootSessionId!==void 0||i.currentDepth>0)return r;for(let[t,n]of e)n.workflowCallable===!0&&r.set(t,n);return r}function shouldHideDelegationTool(e,r,i){return e.name===TASK_UPDATE_TOOL_NAME?i!==!0:isRootOnlyFrameworkTool(e)?r.rootSessionId!==void 0||resolveSubagentDepth(r).currentDepth>0:!1}function isRootOnlyFrameworkTool(n){return n.rootOnly===!0||n.name===AGENT_TOOL_NAME&&n.runtimeAction?.kind===`subagent-call`&&n.runtimeAction.nodeId===ROOT_RUNTIME_AGENT_NODE_ID||n.name!==TASK_UPDATE_TOOL_NAME&&TASK_TOOL_NAMES.has(n.name)}function isToolDefinitionList(e){return Array.isArray(e)}export{getAdvertisedTools};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ContextKey } from "#context/key.js";
|
|
2
|
+
import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
3
|
+
import type { TaskExec } from "#shared/tool-task.js";
|
|
4
|
+
export interface BackgroundExecutableTool {
|
|
5
|
+
readonly execute: (input: unknown, options: ToolExecuteOptions, task: TaskExec) => unknown;
|
|
6
|
+
readonly name: string;
|
|
7
|
+
}
|
|
8
|
+
export interface BackgroundToolCall {
|
|
9
|
+
readonly callId: string;
|
|
10
|
+
readonly definition: BackgroundExecutableTool;
|
|
11
|
+
readonly input: unknown;
|
|
12
|
+
}
|
|
13
|
+
export interface BackgroundToolCallBatch {
|
|
14
|
+
readonly calls: readonly BackgroundToolCall[];
|
|
15
|
+
register(call: {
|
|
16
|
+
readonly callId: string;
|
|
17
|
+
readonly input: unknown;
|
|
18
|
+
readonly toolName: string;
|
|
19
|
+
}): void;
|
|
20
|
+
setTool(name: string, definition?: BackgroundExecutableTool): void;
|
|
21
|
+
}
|
|
22
|
+
export interface BackgroundToolExecutor {
|
|
23
|
+
execute(input: {
|
|
24
|
+
readonly batch: BackgroundToolCallBatch;
|
|
25
|
+
readonly definition: BackgroundExecutableTool;
|
|
26
|
+
readonly options: ToolExecuteOptions;
|
|
27
|
+
readonly toolInput: unknown;
|
|
28
|
+
}): Promise<unknown>;
|
|
29
|
+
}
|
|
30
|
+
export declare const BackgroundToolExecutorKey: ContextKey<BackgroundToolExecutor>;
|
|
31
|
+
export declare function createBackgroundToolCallBatch(): BackgroundToolCallBatch;
|
|
32
|
+
export declare function executeBackgroundToolCall(input: {
|
|
33
|
+
readonly batch: BackgroundToolCallBatch;
|
|
34
|
+
readonly definition: BackgroundExecutableTool;
|
|
35
|
+
readonly options: ToolExecuteOptions;
|
|
36
|
+
readonly toolInput: unknown;
|
|
37
|
+
}): Promise<unknown>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";const BackgroundToolExecutorKey=new ContextKey(`eve.internal.backgroundToolExecution`);function createBackgroundToolCallBatch(){let e=[],t=new Map,n=new Map;return{calls:e,register(r){let i=n.get(r.toolName);if(i===void 0)return;let a=t.get(r.callId);if(a?.definition===i)return;if(a!==void 0)throw Error(`Background tool call "${r.callId}" was registered more than once.`);let o={callId:r.callId,definition:i,input:r.input};t.set(r.callId,o),e.push(o)},setTool(e,t){t===void 0?n.delete(e):n.set(e,t)}}}async function executeBackgroundToolCall(t){return await loadContext().require(BackgroundToolExecutorKey).execute(t)}export{BackgroundToolExecutorKey,createBackgroundToolCallBatch,executeBackgroundToolCall};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { FlexibleSchema } from "ai";
|
|
2
2
|
import type { Approval } from "#public/definitions/approval.js";
|
|
3
3
|
import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
4
|
+
import type { TaskExec } from "#shared/tool-task.js";
|
|
4
5
|
/**
|
|
5
6
|
* Runtime-owned action metadata attached to one harness-visible tool.
|
|
6
7
|
*
|
|
@@ -26,12 +27,20 @@ export type HarnessRuntimeActionDefinition = {
|
|
|
26
27
|
export interface HarnessToolDefinition {
|
|
27
28
|
readonly approvalKey?: (toolInput: Readonly<Record<string, unknown>>) => string;
|
|
28
29
|
readonly description: string;
|
|
29
|
-
readonly execute?: (input: any, options: ToolExecuteOptions) => any;
|
|
30
|
+
readonly execute?: (input: any, options: ToolExecuteOptions, task?: TaskExec) => any;
|
|
31
|
+
readonly execution?: "background";
|
|
30
32
|
readonly frameworkAction?: "load-skill";
|
|
31
33
|
readonly inputSchema: FlexibleSchema;
|
|
32
34
|
readonly name: string;
|
|
33
35
|
readonly approval?: Approval;
|
|
34
36
|
readonly outputSchema?: FlexibleSchema;
|
|
37
|
+
/**
|
|
38
|
+
* Advertise this tool only to the root session, hiding it from subagent
|
|
39
|
+
* sessions. Set on the injected `agent` self-delegation tool so children
|
|
40
|
+
* cannot delegate recursively. Absent means visible everywhere.
|
|
41
|
+
*/
|
|
42
|
+
readonly rootOnly?: boolean;
|
|
35
43
|
readonly runtimeAction?: HarnessRuntimeActionDefinition;
|
|
36
44
|
readonly toModelOutput?: (output: unknown) => unknown;
|
|
45
|
+
readonly workflowCallable?: boolean;
|
|
37
46
|
}
|
|
@@ -73,6 +73,19 @@ export declare function confirmTaskAgentAddress(session: HarnessSession, input:
|
|
|
73
73
|
readonly operationId: string;
|
|
74
74
|
readonly address: AgentAddress;
|
|
75
75
|
}): HarnessSession;
|
|
76
|
+
/**
|
|
77
|
+
* Records a task-mode child's persistent address from its durable executor
|
|
78
|
+
* binding, applied when the parent step that delegated the task commits.
|
|
79
|
+
*
|
|
80
|
+
* Replay-idempotent: a record identical to the stored handle is a no-op
|
|
81
|
+
* (a resumed child, or a replayed commit). A different record under the
|
|
82
|
+
* same id throws — ids derive from unique operations, so a collision
|
|
83
|
+
* means corrupted derivation, not a replay.
|
|
84
|
+
*/
|
|
85
|
+
export declare function recordTaskAgentAddress(session: HarnessSession, input: {
|
|
86
|
+
readonly address: AgentAddress;
|
|
87
|
+
readonly identity: AgentIdentity;
|
|
88
|
+
}): HarnessSession;
|
|
76
89
|
/** Removes a task-mode address after permanent delivery failure. */
|
|
77
90
|
export declare function removeTaskAgentAddress(session: HarnessSession, agentId: string): HarnessSession;
|
|
78
91
|
/** State-only variant used while consuming a terminal task wake. */
|
|
@@ -128,4 +141,27 @@ export declare function settleAgentTurn(session: HarnessSession, input: {
|
|
|
128
141
|
readonly operationId: string;
|
|
129
142
|
readonly outcome: AgentTurnOutcome;
|
|
130
143
|
}): SettleAgentTurnResult;
|
|
144
|
+
/**
|
|
145
|
+
* Rebases the handle delta one dispatch produced (`base` → `next`) onto a
|
|
146
|
+
* working session that other concurrently staged effects may have advanced
|
|
147
|
+
* past `base`.
|
|
148
|
+
*
|
|
149
|
+
* Per handle id:
|
|
150
|
+
*
|
|
151
|
+
* - deleted by the dispatch → deleted from the working session.
|
|
152
|
+
* - added by the dispatch → appended. If the working session already holds
|
|
153
|
+
* the id with different content, throws: ids derive from unique
|
|
154
|
+
* operations, so a collision means corrupted derivation.
|
|
155
|
+
* - changed in place by the dispatch → the dispatched copy replaces the
|
|
156
|
+
* working copy while that copy still matches `base`. A working copy that
|
|
157
|
+
* diverged from both throws instead of silently dropping either change.
|
|
158
|
+
* - untouched by the dispatch → the working copy is kept.
|
|
159
|
+
*
|
|
160
|
+
* A delta the working session already contains is a no-op, so replaying an
|
|
161
|
+
* effect is safe.
|
|
162
|
+
*/
|
|
163
|
+
export declare function rebaseAgentHandles(session: HarnessSession, input: {
|
|
164
|
+
readonly base: SessionStateMap | undefined;
|
|
165
|
+
readonly next: SessionStateMap | undefined;
|
|
166
|
+
}): HarnessSession;
|
|
131
167
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AGENT_HANDLES_STATE_KEY,assertPersistableAgentHandleStore,formatAgentStatus,getAgentHandleStore}from"#harness/handles/store.js";function prepareAgentStart(e,t){let n=getAgentHandleStore(e.state)?.handles??[];if(n.some(e=>e.identity.id===t.identity.id))throw Error(`Agent handle "${t.identity.id}" already exists.`);return writeHandles(e,[...n,{identity:t.identity,operation:t.operation,phase:`starting`,target:t.target}])}function prepareAgentContinuation(e,t){let n=getAgentHandleStore(e.state)?.handles??[],
|
|
1
|
+
import{jsonValuesEqual}from"#shared/json.js";import{AGENT_HANDLES_STATE_KEY,assertPersistableAgentHandleStore,formatAgentStatus,getAgentHandleStore}from"#harness/handles/store.js";function prepareAgentStart(e,t){let n=getAgentHandleStore(e.state)?.handles??[];if(n.some(e=>e.identity.id===t.identity.id))throw Error(`Agent handle "${t.identity.id}" already exists.`);return writeHandles(e,[...n,{identity:t.identity,operation:t.operation,phase:`starting`,target:t.target}])}function prepareAgentContinuation(e,t){let n=getAgentHandleStore(e.state)?.handles??[],r=n.find(e=>e.identity.id===t.agentId);if(r===void 0)return{kind:`unknown`};if(r.identity.name!==t.invokedName)return{kind:`mismatch`};if(r.phase===`running`&&r.operation.id===t.operation.id)return{handle:r,kind:`ready`,session:e};if(r.phase!==`parked`)return{kind:`busy`};let a={address:r.address,identity:r.identity,operation:{...t.operation,previousStatus:r.lastStatus},phase:`running`};return{handle:a,kind:`ready`,session:writeHandles(e,n.map(e=>e.identity.id===t.agentId?a:e))}}function findActiveHandle(e,t){return e.find(e=>(e.phase===`starting`||e.phase===`running`)&&e.operation.id===t)}function confirmAgentStarted(e,t){let n=getAgentHandleStore(e.state)?.handles??[],r=findActiveHandle(n,t.operationId);if(r===void 0)throw Error(`No prepared agent handle for operation "${t.operationId}".`);return r.phase===`running`?e:writeHandles(e,n.map(e=>e===r?{address:t.address,identity:r.identity,operation:r.operation,phase:`running`}:e))}function confirmTaskAgentAddress(e,t){let n=getAgentHandleStore(e.state)?.handles??[],r=findActiveHandle(n,t.operationId);if(r===void 0)throw Error(`No prepared agent handle for operation "${t.operationId}".`);if(r.phase===`running`)throw Error(`Task agent operation "${t.operationId}" was confirmed as a running handle.`);return writeHandles(e,n.map(e=>e===r?{address:t.address,identity:r.identity,phase:`addressed`}:e))}function recordTaskAgentAddress(t,n){let r=getAgentHandleStore(t.state)?.handles??[],a={address:n.address,identity:n.identity,phase:`addressed`},o=r.find(e=>e.identity.id===n.identity.id);if(o!==void 0){if(jsonValuesEqual(o,a))return t;throw Error(`Agent handle "${n.identity.id}" already exists with different content.`)}return writeHandles(t,[...r,a])}function removeTaskAgentAddress(e,t){return{...e,state:removeTaskAgentAddressFromState(e.state,t)}}function removeTaskAgentAddressFromState(e,r){let a=getAgentHandleStore(e)?.handles??[];return{...e,[AGENT_HANDLES_STATE_KEY]:assertPersistableAgentHandleStore({handles:a.filter(e=>!(e.phase===`addressed`&&e.identity.id===r))})}}function rejectAgentEffect(e,t){let n=getAgentHandleStore(e.state)?.handles??[],r=findActiveHandle(n,t.operationId);if(r===void 0)return e;if(t.disposition===`retryable`&&r.phase===`running`){let{operation:t}=r;if(t.kind===`continue`)return writeHandles(e,n.map(e=>e===r?{address:r.address,identity:r.identity,lastStatus:t.previousStatus,phase:`parked`}:e))}return writeHandles(e,n.filter(e=>e!==r))}function abandonRunningAgentTurns(e){let t=getAgentHandleStore(e.state)?.handles??[];return t.some(e=>e.phase===`running`)?writeHandles(e,t.map(e=>e.phase===`running`?{address:e.address,identity:e.identity,lastStatus:`(cancelled)`,phase:`parked`}:e)):e}function settleAgentTurn(e,t){let n=getAgentHandleStore(e.state)?.handles??[],a=n.find(e=>e.phase===`running`&&e.operation.id===t.operationId);if(a===void 0||a.phase!==`running`)return{kind:`ignored`,reason:`unknown-operation`};if(t.outcome.kind===`terminal`)return{kind:`settled`,session:writeHandles(e,n.filter(e=>e!==a))};let{result:o}=t.outcome,s=o.kind===`succeeded`?formatAgentStatus(o.output):o.kind===`failed`?formatAgentStatus(o.error):`(cancelled)`;return{kind:`settled`,session:writeHandles(e,n.map(e=>e===a?{address:a.address,identity:a.identity,lastStatus:s,phase:`parked`}:e))}}function rebaseAgentHandles(t,n){let r=handlesById(n.base),a=handlesById(n.next),o=getAgentHandleStore(t.state)?.handles??[],s=new Set(o.map(e=>e.identity.id)),c=!1,l=[];for(let t of o){let n=t.identity.id,i=r.get(n),o=a.get(n);if(i!==void 0&&o===void 0){c=!0;continue}if(i===void 0&&o!==void 0&&!jsonValuesEqual(t,o))throw Error(`Agent handle "${n}" added by a dispatch already exists with different content.`);if(i!==void 0&&o!==void 0&&!jsonValuesEqual(i,o)){if(jsonValuesEqual(t,i)){l.push(o),c=!0;continue}if(!jsonValuesEqual(t,o))throw Error(`Agent handle "${n}" was changed by a dispatch and concurrently by another effect.`)}l.push(t)}let u=[...a.values()].filter(e=>!r.has(e.identity.id)&&!s.has(e.identity.id));return!c&&u.length===0?t:writeHandles(t,[...l,...u])}function handlesById(e){let t=getAgentHandleStore(e)?.handles??[];return new Map(t.map(e=>[e.identity.id,e]))}function writeHandles(e,r){return{...e,state:{...e.state,[AGENT_HANDLES_STATE_KEY]:assertPersistableAgentHandleStore({handles:r})}}}export{abandonRunningAgentTurns,confirmAgentStarted,confirmTaskAgentAddress,prepareAgentContinuation,prepareAgentStart,rebaseAgentHandles,recordTaskAgentAddress,rejectAgentEffect,removeTaskAgentAddress,removeTaskAgentAddressFromState,settleAgentTurn};
|
|
@@ -16,6 +16,8 @@ export declare function coalesceTurnInputs(a: StepInput, b: StepInput): StepInpu
|
|
|
16
16
|
* turn entirely rather than create an empty model prompt block.
|
|
17
17
|
*/
|
|
18
18
|
export declare function normalizeUserContent(content: string | UserContent | undefined): string | UserContent | undefined;
|
|
19
|
+
/** Removes blank text blocks that some providers reject from model-bound history. */
|
|
20
|
+
export declare function normalizeModelMessages(messages: readonly ModelMessage[]): ModelMessage[];
|
|
19
21
|
/**
|
|
20
22
|
* Extracts the final visible assistant text from model response messages.
|
|
21
23
|
*
|