eve 0.13.4 → 0.13.5
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 +9 -0
- package/dist/src/channel/schedule-auth.d.ts +7 -0
- package/dist/src/channel/schedule-auth.js +1 -0
- package/dist/src/channel/schedule.d.ts +2 -6
- package/dist/src/channel/schedule.js +1 -1
- package/dist/src/chunks/{use-eve-agent-BLv-Mj5g.js → use-eve-agent-BjAM8_a3.js} +5 -18
- package/dist/src/chunks/{use-eve-agent-C8UVUMA4.js → use-eve-agent-_dbX0ASK.js} +5 -18
- package/dist/src/client/message-reducer.js +1 -1
- package/dist/src/execution/hook-ownership.d.ts +7 -0
- package/dist/src/execution/hook-ownership.js +1 -0
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/action-result-helpers.d.ts +2 -3
- package/dist/src/harness/action-result-helpers.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/provider-tools.d.ts +4 -27
- package/dist/src/harness/provider-tools.js +1 -1
- package/dist/src/harness/step-hooks.d.ts +0 -13
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/tool-output-serialization.d.ts +17 -0
- package/dist/src/harness/tool-output-serialization.js +1 -0
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +10 -8
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/runtime/framework-tools/web-search.d.ts +2 -2
- package/dist/src/runtime/framework-tools/web-search.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/empty-delivery.d.ts +3 -0
- package/dist/src/shared/empty-delivery.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +1 -1
- package/docs/channels/eve.mdx +1 -1
- package/docs/concepts/execution-model-and-durability.md +2 -0
- package/docs/guides/client/continuations.mdx +4 -0
- package/docs/guides/client/streaming.mdx +6 -0
- package/docs/guides/frontend/overview.mdx +28 -8
- package/docs/schedules.mdx +5 -3
- package/docs/tools/overview.mdx +2 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.13.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c927ecd: Confirm continuation-token ownership before an agent turn starts or a session re-keys. Competing sessions now fail before processing input, and successful delivery reports the hook owner atomically.
|
|
8
|
+
- 5f0f69f: Use Parallel through AI Gateway for the built-in `web_search` tool with every string model. Gateway requests no longer select native provider search tools or pin routing to a model provider.
|
|
9
|
+
- 430ed8c: Teach agents that conditionally delivered work can finish successfully without sending a message. Polling schedules can now intentionally skip delivery without treating an accidental blank model response as success.
|
|
10
|
+
- 25b1b14: fix(eve): catch unserializable tool output values instead of sending them to the model
|
|
11
|
+
|
|
3
12
|
## 0.13.4
|
|
4
13
|
|
|
5
14
|
### Patch Changes
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Framework-owned principal used when a schedule runs on behalf of the agent.
|
|
4
|
+
*/
|
|
5
|
+
export declare const SCHEDULE_APP_AUTH: SessionAuthContext;
|
|
6
|
+
/** Returns whether the current request is authenticated as eve's schedule principal. */
|
|
7
|
+
export declare function isScheduleAppAuth(auth: SessionAuthContext | null | undefined): auth is SessionAuthContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const SCHEDULE_APP_AUTH={attributes:{},authenticator:`app`,principalId:`eve:app`,principalType:`runtime`};function isScheduleAppAuth(e){return e?.authenticator===SCHEDULE_APP_AUTH.authenticator&&e.principalId===SCHEDULE_APP_AUTH.principalId&&e.principalType===SCHEDULE_APP_AUTH.principalType}export{SCHEDULE_APP_AUTH,isScheduleAppAuth};
|
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
import type { ChannelAdapter } from "#channel/adapter.js";
|
|
2
2
|
import { type Session } from "#channel/session.js";
|
|
3
|
-
import type { Runtime
|
|
3
|
+
import type { Runtime } from "#channel/types.js";
|
|
4
4
|
import type { ScheduleRunHandler } from "#public/definitions/schedule.js";
|
|
5
5
|
import type { ResolvedChannelDefinition } from "#runtime/types.js";
|
|
6
|
-
|
|
7
|
-
* Pre-built application auth context handed to schedules. Schedules
|
|
8
|
-
* run on behalf of the agent itself, not a downstream user.
|
|
9
|
-
*/
|
|
10
|
-
export declare const SCHEDULE_APP_AUTH: SessionAuthContext;
|
|
6
|
+
export { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";
|
|
11
7
|
/**
|
|
12
8
|
* Durable adapter kind used when a schedule fires without targeting a
|
|
13
9
|
* channel — the markdown form, and the synthesized run the dispatcher
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSession}from"#channel/session.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{expectFunction}from"#internal/authored-module.js";const
|
|
1
|
+
import{createSession}from"#channel/session.js";import{SCHEDULE_APP_AUTH,SCHEDULE_APP_AUTH as SCHEDULE_APP_AUTH$1}from"#channel/schedule-auth.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{expectFunction}from"#internal/authored-module.js";const SCHEDULE_ADAPTER_KIND=`schedule`,SCHEDULE_ADAPTER={kind:SCHEDULE_ADAPTER_KIND};var ScheduleDispatcher=class{runtime;channels;constructor(e){this.runtime=e.runtime,this.channels=e.channels}async trigger(e){let t=[],i=[],a=createCrossChannelReceiveFn(this.runtime,toCrossChannelTargets(this.channels)),o={appAuth:SCHEDULE_APP_AUTH$1,receive:async(e,n)=>{let r=await a(e,n);return t.push(r),r},waitUntil(e){i.push(e)}};if(e.run)await e.run(o);else if(e.markdown!==void 0){let n=await this.runMarkdown(e.markdown);t.push(n)}else throw Error(`Schedule "${e.scheduleId}" has neither "run" nor "markdown" — at least one must be set.`);return{sessions:t,waitUntilTasks:i}}async runMarkdown(t){let r=await this.runtime.run({adapter:SCHEDULE_ADAPTER,auth:SCHEDULE_APP_AUTH$1,input:{message:t},mode:`task`});return createSession(r.sessionId,r.continuationToken,this.runtime)}};function expectScheduleRun(e,t,n){let r=e;if(typeof r!=`object`||!r)throw Error(`Schedule export "${n??`default`}" from "${t}" must be an object.`);return expectFunction(r.run,`Expected the schedule export "${n??`default`}" from "${t}" to export a \`run\` handler function.`)}export{SCHEDULE_ADAPTER,SCHEDULE_ADAPTER_KIND,SCHEDULE_APP_AUTH,ScheduleDispatcher,expectScheduleRun};
|
|
@@ -1236,7 +1236,7 @@ function reduceMessageData(data, event) {
|
|
|
1236
1236
|
type: "text"
|
|
1237
1237
|
}));
|
|
1238
1238
|
case "message.completed": return updateAssistantMessage(data, event.data.turnId, (message) => {
|
|
1239
|
-
if (event.data.message === null) return
|
|
1239
|
+
if (event.data.message === null) return removeTextPart(message, event.data.stepIndex);
|
|
1240
1240
|
return upsertPart(ensureStepStartPart(message, event.data.stepIndex), {
|
|
1241
1241
|
state: "done",
|
|
1242
1242
|
stepIndex: event.data.stepIndex,
|
|
@@ -1319,25 +1319,16 @@ function upsertPart(message, next) {
|
|
|
1319
1319
|
parts
|
|
1320
1320
|
};
|
|
1321
1321
|
}
|
|
1322
|
-
function
|
|
1323
|
-
const
|
|
1324
|
-
if (
|
|
1325
|
-
const existing = message.parts[index];
|
|
1326
|
-
if (existing?.type !== "text") return message;
|
|
1322
|
+
function removeTextPart(message, stepIndex) {
|
|
1323
|
+
const parts = message.parts.filter((part) => part.type !== "text" || part.stepIndex !== stepIndex);
|
|
1324
|
+
if (parts.length === message.parts.length) return message;
|
|
1327
1325
|
return {
|
|
1328
1326
|
...message,
|
|
1329
1327
|
metadata: {
|
|
1330
1328
|
...message.metadata,
|
|
1331
1329
|
status: "complete"
|
|
1332
1330
|
},
|
|
1333
|
-
parts
|
|
1334
|
-
...message.parts.slice(0, index),
|
|
1335
|
-
{
|
|
1336
|
-
...existing,
|
|
1337
|
-
state: "done"
|
|
1338
|
-
},
|
|
1339
|
-
...message.parts.slice(index + 1)
|
|
1340
|
-
]
|
|
1331
|
+
parts
|
|
1341
1332
|
};
|
|
1342
1333
|
}
|
|
1343
1334
|
function updateToolPart(data, toolCallId, next) {
|
|
@@ -1459,10 +1450,6 @@ function stringifyUnknown(value) {
|
|
|
1459
1450
|
return "Action failed.";
|
|
1460
1451
|
}
|
|
1461
1452
|
}
|
|
1462
|
-
function findLastIndex(items, predicate) {
|
|
1463
|
-
for (let index = items.length - 1; index >= 0; index -= 1) if (predicate(items[index])) return index;
|
|
1464
|
-
return -1;
|
|
1465
|
-
}
|
|
1466
1453
|
|
|
1467
1454
|
//#endregion
|
|
1468
1455
|
//#region src/vue/use-eve-agent.ts
|
|
@@ -1236,7 +1236,7 @@ function reduceMessageData(data, event) {
|
|
|
1236
1236
|
type: "text"
|
|
1237
1237
|
}));
|
|
1238
1238
|
case "message.completed": return updateAssistantMessage(data, event.data.turnId, (message) => {
|
|
1239
|
-
if (event.data.message === null) return
|
|
1239
|
+
if (event.data.message === null) return removeTextPart(message, event.data.stepIndex);
|
|
1240
1240
|
return upsertPart(ensureStepStartPart(message, event.data.stepIndex), {
|
|
1241
1241
|
state: "done",
|
|
1242
1242
|
stepIndex: event.data.stepIndex,
|
|
@@ -1319,25 +1319,16 @@ function upsertPart(message, next) {
|
|
|
1319
1319
|
parts
|
|
1320
1320
|
};
|
|
1321
1321
|
}
|
|
1322
|
-
function
|
|
1323
|
-
const
|
|
1324
|
-
if (
|
|
1325
|
-
const existing = message.parts[index];
|
|
1326
|
-
if (existing?.type !== "text") return message;
|
|
1322
|
+
function removeTextPart(message, stepIndex) {
|
|
1323
|
+
const parts = message.parts.filter((part) => part.type !== "text" || part.stepIndex !== stepIndex);
|
|
1324
|
+
if (parts.length === message.parts.length) return message;
|
|
1327
1325
|
return {
|
|
1328
1326
|
...message,
|
|
1329
1327
|
metadata: {
|
|
1330
1328
|
...message.metadata,
|
|
1331
1329
|
status: "complete"
|
|
1332
1330
|
},
|
|
1333
|
-
parts
|
|
1334
|
-
...message.parts.slice(0, index),
|
|
1335
|
-
{
|
|
1336
|
-
...existing,
|
|
1337
|
-
state: "done"
|
|
1338
|
-
},
|
|
1339
|
-
...message.parts.slice(index + 1)
|
|
1340
|
-
]
|
|
1331
|
+
parts
|
|
1341
1332
|
};
|
|
1342
1333
|
}
|
|
1343
1334
|
function updateToolPart(data, toolCallId, next) {
|
|
@@ -1459,10 +1450,6 @@ function stringifyUnknown(value) {
|
|
|
1459
1450
|
return "Action failed.";
|
|
1460
1451
|
}
|
|
1461
1452
|
}
|
|
1462
|
-
function findLastIndex(items, predicate) {
|
|
1463
|
-
for (let index = items.length - 1; index >= 0; index -= 1) if (predicate(items[index])) return index;
|
|
1464
|
-
return -1;
|
|
1465
|
-
}
|
|
1466
1453
|
|
|
1467
1454
|
//#endregion
|
|
1468
1455
|
//#region src/svelte/use-eve-agent.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,t){switch(t.type){case`client.message.submitted`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`submitted`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.message.failed`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`failed`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.input.responded`:{let n=e;for(let e of t.data.responses)n=respondToInputRequest(n,e);return n}case`message.received`:return upsertMessage(e,{id:`${t.data.turnId}:user`,metadata:{status:`complete`,turnId:t.data.turnId},parts:[{type:`text`,text:t.data.message,state:`done`}],role:`user`});case`step.started`:return updateAssistantMessage(e,t.data.turnId,e=>ensureStepStartPart(e,t.data.stepIndex));case`reasoning.appended`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),{state:`streaming`,stepIndex:t.data.stepIndex,text:t.data.reasoningSoFar,type:`reasoning`}));case`reasoning.completed`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),{state:`done`,stepIndex:t.data.stepIndex,text:t.data.reasoning,type:`reasoning`}));case`actions.requested`:{let n=e;for(let e of t.data.actions){let r=normalizeActionRequest(e);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{input:`input`in e?e.input:void 0,state:`input-available`,stepIndex:t.data.stepIndex,toolCallId:e.callId,toolMetadata:createToolMetadata(r),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`input.requested`:{let n=e;for(let e of t.data.requests){let r=normalizeActionRequest(e.action);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{approval:{id:e.requestId},input:e.action.input,state:`approval-requested`,stepIndex:t.data.stepIndex,toolCallId:e.action.callId,toolMetadata:createToolMetadata(r,{inputRequest:toMessageInputRequest(e)}),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`action.result`:{let n=normalizeActionResult(t.data.result),r=findToolPart(e,t.data.result.callId),i=t.data.error?.code===`TOOL_EXECUTION_DENIED`,a=t.data.status===`failed`&&!i,o=r?.approval?.id??t.data.result.callId,s=mergeToolMetadata(r?.toolMetadata,createToolMetadata(n)),c={input:r?.input,stepIndex:t.data.stepIndex,toolCallId:t.data.result.callId,toolMetadata:s,toolName:r?.toolName??n.toolName,type:`dynamic-tool`},l;return l=i?{...c,approval:{approved:!1,id:o,reason:t.data.error?.message},state:`output-denied`}:a?{...c,approval:approvedApproval(r),errorText:t.data.error?.message??stringifyUnknown(t.data.result.output),state:`output-error`}:{...c,approval:approvedApproval(r),output:t.data.result.output,state:`output-available`},r===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),l)):updateToolPart(e,t.data.result.callId,l)}case`message.appended`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),{state:`streaming`,stepIndex:t.data.stepIndex,text:t.data.messageSoFar,type:`text`}));case`message.completed`:return updateAssistantMessage(e,t.data.turnId,e=>t.data.message===null?
|
|
1
|
+
function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,t){switch(t.type){case`client.message.submitted`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`submitted`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.message.failed`:return upsertMessage(e,{id:optimisticUserMessageId(t.data.submissionId),metadata:{optimistic:!0,status:`failed`},parts:[{type:`text`,text:t.data.message}],role:`user`});case`client.input.responded`:{let n=e;for(let e of t.data.responses)n=respondToInputRequest(n,e);return n}case`message.received`:return upsertMessage(e,{id:`${t.data.turnId}:user`,metadata:{status:`complete`,turnId:t.data.turnId},parts:[{type:`text`,text:t.data.message,state:`done`}],role:`user`});case`step.started`:return updateAssistantMessage(e,t.data.turnId,e=>ensureStepStartPart(e,t.data.stepIndex));case`reasoning.appended`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),{state:`streaming`,stepIndex:t.data.stepIndex,text:t.data.reasoningSoFar,type:`reasoning`}));case`reasoning.completed`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),{state:`done`,stepIndex:t.data.stepIndex,text:t.data.reasoning,type:`reasoning`}));case`actions.requested`:{let n=e;for(let e of t.data.actions){let r=normalizeActionRequest(e);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{input:`input`in e?e.input:void 0,state:`input-available`,stepIndex:t.data.stepIndex,toolCallId:e.callId,toolMetadata:createToolMetadata(r),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`input.requested`:{let n=e;for(let e of t.data.requests){let r=normalizeActionRequest(e.action);n=updateAssistantMessage(n,t.data.turnId,n=>upsertPart(ensureStepStartPart(n,t.data.stepIndex),{approval:{id:e.requestId},input:e.action.input,state:`approval-requested`,stepIndex:t.data.stepIndex,toolCallId:e.action.callId,toolMetadata:createToolMetadata(r,{inputRequest:toMessageInputRequest(e)}),toolName:r.toolName,type:`dynamic-tool`}))}return n}case`action.result`:{let n=normalizeActionResult(t.data.result),r=findToolPart(e,t.data.result.callId),i=t.data.error?.code===`TOOL_EXECUTION_DENIED`,a=t.data.status===`failed`&&!i,o=r?.approval?.id??t.data.result.callId,s=mergeToolMetadata(r?.toolMetadata,createToolMetadata(n)),c={input:r?.input,stepIndex:t.data.stepIndex,toolCallId:t.data.result.callId,toolMetadata:s,toolName:r?.toolName??n.toolName,type:`dynamic-tool`},l;return l=i?{...c,approval:{approved:!1,id:o,reason:t.data.error?.message},state:`output-denied`}:a?{...c,approval:approvedApproval(r),errorText:t.data.error?.message??stringifyUnknown(t.data.result.output),state:`output-error`}:{...c,approval:approvedApproval(r),output:t.data.result.output,state:`output-available`},r===void 0?updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),l)):updateToolPart(e,t.data.result.callId,l)}case`message.appended`:return updateAssistantMessage(e,t.data.turnId,e=>upsertPart(ensureStepStartPart(e,t.data.stepIndex),{state:`streaming`,stepIndex:t.data.stepIndex,text:t.data.messageSoFar,type:`text`}));case`message.completed`:return updateAssistantMessage(e,t.data.turnId,e=>t.data.message===null?removeTextPart(e,t.data.stepIndex):upsertPart(ensureStepStartPart(e,t.data.stepIndex),{state:`done`,stepIndex:t.data.stepIndex,text:t.data.message,type:`text`}));case`result.completed`:return updateAssistantMetadata(e,t.data.turnId,{result:t.data.result});case`turn.completed`:return updateAssistantMetadata(e,t.data.turnId,{status:`complete`});case`turn.failed`:case`session.failed`:return e;default:return e}}function respondToInputRequest(e,t){let n=findToolPartByApprovalId(e,t.requestId);if(!n)return e;let r={id:t.requestId};return t.text!==void 0&&(r.reason=t.text),updateToolPart(e,n.toolCallId,{approval:r,input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:mergeToolMetadata(n.toolMetadata,{eve:{inputResponse:t,kind:n.toolMetadata?.eve?.kind??`unknown`,name:n.toolMetadata?.eve?.name??n.toolName}}),toolName:n.toolName,type:`dynamic-tool`})}function updateAssistantMessage(e,t,n){return upsertMessage(e,n(e.messages.find(e=>e.role===`assistant`&&e.metadata?.turnId===t)??createAssistantMessage(t)))}function updateAssistantMetadata(e,t,n){return updateAssistantMessage(e,t,e=>({...e,metadata:{...e.metadata,...n}}))}function createAssistantMessage(e){return{id:`${e}:assistant`,metadata:{status:`streaming`,turnId:e},parts:[],role:`assistant`}}function ensureStepStartPart(e,t){let n=e.parts.filter(e=>e.type===`step-start`).length;if(n>t)return e;let r=t-n+1;return{...e,parts:[...e.parts,...Array.from({length:r},()=>({type:`step-start`}))]}}function upsertPart(e,t){let n=e.parts.findIndex(e=>partKey(e)===partKey(t)),r=n===-1?[...e.parts,t]:[...e.parts.slice(0,n),t,...e.parts.slice(n+1)];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function removeTextPart(e,t){let n=e.parts.filter(e=>e.type!==`text`||e.stepIndex!==t);return n.length===e.parts.length?e:{...e,metadata:{...e.metadata,status:`complete`},parts:n}}function updateToolPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`dynamic-tool`&&e.toolCallId===t));return r?upsertMessage(e,upsertPart(r,n)):e}function findToolPart(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.toolCallId===t)return e}function findToolPartByApprovalId(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.approval?.id===t)return e}function partKey(e){switch(e.type){case`text`:return`text:${e.stepIndex??0}`;case`reasoning`:return`reasoning:${e.stepIndex??0}`;case`step-start`:return`step-start`;case`dynamic-tool`:return`dynamic-tool:${e.toolCallId}`}}function upsertMessage(e,t){let n=e.messages.findIndex(e=>e.id===t.id);return n===-1?{messages:[...e.messages,t]}:{messages:[...e.messages.slice(0,n),t,...e.messages.slice(n+1)]}}function toMessageInputRequest(e){return{allowFreeform:e.allowFreeform,display:e.display,options:e.options,prompt:e.prompt,requestId:e.requestId}}function createToolMetadata(e,t){return{eve:{inputRequest:t?.inputRequest,kind:e.kind,name:e.name}}}function mergeToolMetadata(e,t){let n=t.eve?.kind??e?.eve?.kind??`unknown`,r=t.eve?.name??e?.eve?.name??`unknown`;return{eve:{...e?.eve,...t.eve,inputRequest:t.eve?.inputRequest??e?.eve?.inputRequest,inputResponse:t.eve?.inputResponse??e?.eve?.inputResponse,kind:n,name:r}}}function approvedApproval(e){if(e?.approval?.id)return{approved:!0,id:e.approval.id,isAutomatic:e.approval.isAutomatic,reason:e.approval.reason}}function normalizeActionRequest(e){switch(e.kind){case`load-skill`:return{kind:`load-skill`,name:`load_skill`,toolName:`eve:load-skill`};case`tool-call`:return{kind:`tool-call`,name:e.toolName,toolName:e.toolName};case`subagent-call`:return{kind:`subagent-call`,name:e.subagentName,toolName:`eve:subagent:${e.subagentName}`};case`remote-agent-call`:return{kind:`subagent-call`,name:e.remoteAgentName,toolName:`eve:subagent:${e.remoteAgentName}`}}}function normalizeActionResult(e){switch(e.kind){case`load-skill-result`:return{kind:`load-skill`,name:e.name??`load_skill`,toolName:`eve:load-skill`};case`tool-result`:return{kind:`tool-call`,name:e.toolName,toolName:e.toolName};case`subagent-result`:return{kind:`subagent-call`,name:e.subagentName,toolName:`eve:subagent:${e.subagentName}`}}}function optimisticUserMessageId(e){return`optimistic:${e}:user`}function stringifyUnknown(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return`Action failed.`}}export{defaultMessageReducer};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Hook } from "#compiled/@workflow/core/index.js";
|
|
2
|
+
export declare function claimHookOwnership<T>(hook: Hook<T>): Promise<void>;
|
|
3
|
+
export declare function closeHookIterator<T>(iterator: AsyncIterator<T>): Promise<void>;
|
|
4
|
+
export declare function disposeHook(hook: {
|
|
5
|
+
dispose?: () => unknown;
|
|
6
|
+
[Symbol.dispose]?: () => unknown;
|
|
7
|
+
}): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function claimHookOwnership(e){let t;try{t=await e.getConflict()}catch(t){return await disposeAndThrow(e,normalizeHookClaimError(t,e.token))}if(t!==null)return await disposeAndThrow(e,createHookConflictError(e.token,t.runId))}async function closeHookIterator(e){typeof e.return==`function`&&await e.return(void 0)}async function disposeHook(e){let t=e.dispose;if(typeof t==`function`){await t.call(e);return}let n=e[Symbol.dispose];typeof n==`function`&&await n.call(e)}async function disposeAndThrow(e,t){try{await disposeHook(e)}catch{}throw t}function normalizeHookClaimError(e,t){return isHookConflictError(e)?createHookConflictError(typeof e.token==`string`?e.token:t,typeof e.conflictingRunId==`string`?e.conflictingRunId:void 0):e}function isHookConflictError(e){return e instanceof Error&&e.name===`HookConflictError`}function createHookConflictError(e,t){let n=t===void 0?``:` (run "${t}")`;return Object.assign(Error(`Hook token "${e}" is already in use${n}`),{conflictingRunId:t,name:`HookConflictError`,token:e})}export{claimHookOwnership,closeHookIterator,disposeHook};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readRootSessionId}from"#execution/eve-workflow-attributes.js";import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{resolveVercelProductionCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchCodeModeRuntimeActionsStep}from"#execution/dispatch-code-mode-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";async function workflowEntry(t){"use workflow";let{workflowRunId:n}=getWorkflowMetadata(),r=t.serializedContext[`eve.continuationToken`]||``,a=t.serializedContext[`eve.mode`],o=t.serializedContext[`eve.capabilities`],c=t.serializedContext[`eve.bundle`];t.serializedContext[`eve.sessionId`]=n;let l=getWritable();try{let i=readRootSessionId(t.serializedContext),{state:s}=await createSessionStep({compiledArtifactsSource:c.source,continuationToken:r,inputMessage:t.input.message,nodeId:c.nodeId,outputSchema:t.input.outputSchema,rootSessionId:i,serializedContext:t.serializedContext,sessionId:n});return await runDriverLoop({capabilities:o,driverWritable:l,initialInput:{kind:`deliver`,payloads:[{message:t.input.message,context:t.input.context,outputSchema:t.input.outputSchema}]},mode:a,serializedContext:t.serializedContext,sessionState:s})}catch(e){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:l,serializedContext:t.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:t.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(t.serializedContext,e),serializedContext:t.serializedContext}),e}}async function runDriverLoop(e){let t=createHook({token:`${e.sessionState.sessionId}:auth`}),i=t[Symbol.asyncIterator](),a=0,nextTurnCompletionToken=()=>`${e.sessionState.sessionId}:turn-completion:${String(a++)}`,o=``,s,c,l=null,u=[],
|
|
1
|
+
import{readRootSessionId}from"#execution/eve-workflow-attributes.js";import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{resolveVercelProductionCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchCodeModeRuntimeActionsStep}from"#execution/dispatch-code-mode-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{claimHookOwnership,closeHookIterator,disposeHook}from"#execution/hook-ownership.js";async function workflowEntry(t){"use workflow";let{workflowRunId:n}=getWorkflowMetadata(),r=t.serializedContext[`eve.continuationToken`]||``,a=t.serializedContext[`eve.mode`],o=t.serializedContext[`eve.capabilities`],c=t.serializedContext[`eve.bundle`];t.serializedContext[`eve.sessionId`]=n;let l=getWritable();try{let i=readRootSessionId(t.serializedContext),{state:s}=await createSessionStep({compiledArtifactsSource:c.source,continuationToken:r,inputMessage:t.input.message,nodeId:c.nodeId,outputSchema:t.input.outputSchema,rootSessionId:i,serializedContext:t.serializedContext,sessionId:n});return await runDriverLoop({capabilities:o,driverWritable:l,initialInput:{kind:`deliver`,payloads:[{message:t.input.message,context:t.input.context,outputSchema:t.input.outputSchema}]},mode:a,serializedContext:t.serializedContext,sessionState:s})}catch(e){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:l,serializedContext:t.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:t.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(t.serializedContext,e),serializedContext:t.serializedContext}),e}}async function runDriverLoop(e){let t=createHook({token:`${e.sessionState.sessionId}:auth`}),i=t[Symbol.asyncIterator](),a=0,nextTurnCompletionToken=()=>`${e.sessionState.sessionId}:turn-completion:${String(a++)}`,o=``,s,c,l=null,u=[],getNextPromise=()=>{if(c===void 0)throw Error(`Cannot wait for deliveries before a continuation token is available.`);return l??=c.next(),l},consumeNext=()=>{l=null},closeParkHook=async()=>{let e=c,t=s;if(s=void 0,c=void 0,l=null,e!==void 0)try{await closeHookIterator(e)}catch(e){if(t!==void 0)try{await disposeHook(t)}catch{}throw e}t!==void 0&&await disposeHook(t)},rekeyHook=async e=>{if(!e||s!==void 0&&e===o)return;let t=createHook({token:e});await claimHookOwnership(t);try{await closeParkHook()}catch(e){try{await disposeHook(t)}catch{}throw e}o=e,s=t,c=t[Symbol.asyncIterator](),l=null};try{e.sessionState.continuationToken&&await rekeyHook(e.sessionState.continuationToken);let t=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:e.initialInput,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});if(t.kind===`done`)return await finalizeDone({action:t,driverWritable:e.driverWritable});if(!t.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");for(await rekeyHook(t.sessionState.continuationToken);;)switch(t.kind){case`done`:return await finalizeDone({action:t,driverWritable:e.driverWritable});case`dispatch-code-mode-runtime-actions`:case`dispatch-runtime-actions`:{let i=await(t.kind===`dispatch-code-mode-runtime-actions`?dispatchCodeModeRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveVercelProductionCallbackBaseUrl()??getWorkflowMetadata().url,parentWritable:e.driverWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),a=await waitForPendingRuntimeActionResults({bufferedDeliveries:u,consumeNext,getNextPromise,initialResults:i.results,parentWritable:e.driverWritable,pendingActionKeys:t.pendingActionKeys,rekeyHook,serializedContext:t.serializedContext,sessionState:i.sessionState});if(a===null)return{output:``};t=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`runtime-action-result`,results:a.results},mode:e.mode,parentWritable:e.driverWritable,serializedContext:a.serializedContext,sessionState:a.sessionState}),await rekeyHook(t.sessionState.continuationToken);break}case`park`:{if(t.authorizationNames&&t.authorizationNames.length>0){let n=t.authorizationNames.length,r=[];for(;r.length<n;){let e=await i.next();if(e.done)break;e.value.kind===`deliver`&&r.push(...e.value.payloads)}t=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`deliver`,payloads:r},mode:e.mode,parentWritable:e.driverWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),await rekeyHook(t.sessionState.continuationToken);break}let n=await waitForNextDeliver({bufferedDeliveries:u,consumeNext,getNextPromise});if(n===null)return{output:``};let r=await routeDeliverForChildren({auth:n.auth,parentWritable:e.driverWritable,payloads:n.payloads,sessionState:t.sessionState});if(r===void 0)continue;t=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{auth:n.auth,kind:`deliver`,payloads:[r]},mode:e.mode,parentWritable:e.driverWritable,serializedContext:t.serializedContext,sessionState:t.sessionState}),await rekeyHook(t.sessionState.continuationToken);break}}}finally{await closeParkHook(),await closeHookIterator(i),await disposeHook(t)}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;return await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n}),{output:t}}async function dispatchAndAwaitTurn(e){let t=createHook({token:e.completionToken}),n=t.token;try{await dispatchTurnStep({capabilities:e.capabilities,completionToken:n,delivery:e.delivery,mode:e.mode,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});let r=await awaitHookPayload(t);if(r.kind===`turn-error`)throw rebuildSerializableError(r.error);return r.action}finally{await disposeHook(t)}}async function awaitHookPayload(e){for await(let t of e)return t;throw Error(`Turn completion hook closed before delivering a result.`)}async function waitForPendingRuntimeActionResults(e){let n=e.sessionState,r=e.serializedContext,i=await accumulateRuntimeActionResults({bufferedDeliveries:e.bufferedDeliveries,async getNext(){for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;let i=t.value;if(i.kind===`deliver`){let t=await routeDeliverForChildren({auth:i.auth,parentWritable:e.parentWritable,payloads:i.payloads,sessionState:n});if(t===void 0)continue;return{kind:`deliver`,value:{...i,payloads:[t]}}}if(i.kind===`runtime-action-result`)return{kind:`runtime-action-result`,results:i.results};let a=await runProxyInputRequestStep({hookPayload:i,parentWritable:e.parentWritable,serializedContext:r,sessionState:n});n=a.sessionState,r=a.serializedContext,await e.rekeyHook(n.continuationToken)}},initialResults:e.initialResults,pendingActionKeys:e.pendingActionKeys});return i===null?null:{results:i,serializedContext:r,sessionState:n}}async function routeDeliverForChildren(e){let t=coalescePayloads(e.payloads);return e.sessionState.hasProxyInputRequests?(await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState})).remainder:t}async function waitForNextDeliver(e){if(e.bufferedDeliveries.length>0)return coalesceDeliveries(e.bufferedDeliveries.splice(0));for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;if(t.value.kind!==`deliver`)continue;let n=t.value;for(;;){let t=await takeReadyPayload(e.getNextPromise());if(t===NO_READY_MESSAGE||(e.consumeNext(),t.done))break;t.value.kind===`deliver`&&(n=coalesceDeliveries([n,t.value]))}return n}}function coalescePayloads(e){if(e.length===0)return{};if(e.length===1)return e[0]??{};let t={},n=[];for(let r of e){for(let[e,n]of Object.entries(r))e!==`inputResponses`&&n!==void 0&&(t[e]=n);r.inputResponses!==void 0&&n.push(...r.inputResponses)}return n.length>0&&(t.inputResponses=n),t}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}export{workflowEntry};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{serializeContext}from"#context/serialize.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeNoActiveSessionError}from"#execution/runtime-errors.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{serializeContext}from"#context/serialize.js";import{getRun,resumeHook,start}from"#compiled/@workflow/core/runtime.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{applyEveWorkflowQueueNamespace}from"#internal/workflow/queue-namespace.js";import{buildRunContext}from"#execution/runtime-context.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async run(n){let r=serializeContext(buildRunContext({bundle:await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),run:n})),o;try{o=await startWorkflowPreferLatest(workflowEntryReference,[{input:n.input,serializedContext:r}])}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:n.continuationToken}),e}let s,getEvents=()=>(s??=parseNdjsonStream(()=>getRun(o.runId).getReadable()),s);return{continuationToken:n.continuationToken??o.runId,get events(){return getEvents()},sessionId:o.runId}},async deliver(e){applyEveWorkflowQueueNamespace();let r={auth:e.auth,kind:`deliver`,payloads:[e.payload]};try{return{sessionId:normalizeWorkflowHook(await resumeHook(e.continuationToken,r)).runId}}catch(r){throw HookNotFoundError.is(r)?new RuntimeNoActiveSessionError(e.continuationToken):(logError(log,`failed to deliver to active session`,r,{continuationToken:e.continuationToken}),r)}},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))}}}async function startWorkflowPreferLatest(e,t){if(applyEveWorkflowQueueNamespace(),!shouldRouteToLatestDeployment())return await start(e,t);try{return await start(e,t,{deploymentId:`latest`})}catch(n){if(!isLatestDeploymentUnsupportedError(n))throw n;return await start(e,t)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}function parseNdjsonStream(e){let t=new TextDecoder,n=``;return new ReadableStream({async start(r){let i=e().getReader();try{for(;;){let{value:e,done:a}=await i.read();if(a)break;n+=t.decode(e,{stream:!0});for(let e=n.indexOf(`
|
|
2
2
|
`);e!==-1;e=n.indexOf(`
|
|
3
3
|
`)){let t=n.slice(0,e).trim();n=n.slice(e+1),t.length>0&&r.enqueue(JSON.parse(t))}}n+=t.decode();let e=n.trim();e.length>0&&r.enqueue(JSON.parse(e)),r.close()}catch(e){r.error(e)}finally{i.releaseLock()}}})}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference,workflowEntryReference};
|
|
@@ -13,9 +13,8 @@ type ToolResultPart = Extract<ToolResponsePart, {
|
|
|
13
13
|
* native tool execution (via {@link createRuntimeToolResultFromStepResult} /
|
|
14
14
|
* {@link createRuntimeToolResultFromMessagePart}) and code-mode nested tool
|
|
15
15
|
* calls funnel through here, so the raw-output-vs-`toModelOutput` decision —
|
|
16
|
-
* always raw — is decided once. The output is
|
|
17
|
-
*
|
|
18
|
-
* code-mode worker bridge).
|
|
16
|
+
* always raw — is decided once. The output is validated as JSON here so bad
|
|
17
|
+
* values never reach protocol events or persisted history.
|
|
19
18
|
*/
|
|
20
19
|
export declare function createRuntimeToolResultFromValue(input: {
|
|
21
20
|
readonly callId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseJsonValue}from"#shared/json.js";import{authorizationPendingAsJsonObject,isAuthorizationPendingModelOutput,isAuthorizationSignal}from"#harness/authorization.js";function toJsonValue(n){return isAuthorizationSignal(n)?parseJsonValue(authorizationPendingAsJsonObject({connections:n.challenges.map(e=>e.name)})):isAuthorizationPendingModelOutput(n)?parseJsonValue(authorizationPendingAsJsonObject(n)):n===
|
|
1
|
+
import{parseJsonValue}from"#shared/json.js";import{authorizationPendingAsJsonObject,isAuthorizationPendingModelOutput,isAuthorizationSignal}from"#harness/authorization.js";import{withToolOutputSerializationError}from"#harness/tool-output-serialization.js";function toJsonValue(n){return isAuthorizationSignal(n)?parseJsonValue(authorizationPendingAsJsonObject({connections:n.challenges.map(e=>e.name)})):isAuthorizationPendingModelOutput(n)?parseJsonValue(authorizationPendingAsJsonObject(n)):parseJsonValue(n===void 0?null:n)}function createRuntimeToolResultFromValue(e){let t={callId:e.callId,kind:`tool-result`,output:toolResultOutputToJsonValue({output:{type:e.isError===!0?`error-json`:`json`,value:e.isError===!0&&e.output instanceof Error?e.output.message:e.output},toolCallId:e.callId,toolName:e.toolName}),toolName:e.toolName};return e.isError===!0?{...t,isError:!0}:t}function createRuntimeToolResultFromStepResult(e){return createRuntimeToolResultFromValue({callId:e.toolCallId,output:e.output,toolName:e.toolName})}function createRuntimeToolResultFromMessagePart(e){return createRuntimeToolResultFromValue({callId:e.toolCallId,output:toolResultOutputToJsonValue({output:e.output,toolCallId:e.toolCallId,toolName:e.toolName}),toolName:e.toolName,isError:isToolResultError(e.output)})}function toolResultOutputToJsonValue(e){return withToolOutputSerializationError({boundary:`action.result`,toolCallId:e.toolCallId,toolName:e.toolName},()=>{switch(e.output.type){case`text`:case`error-text`:return e.output.value;case`json`:case`error-json`:return toJsonValue(e.output.value);case`execution-denied`:return{code:`TOOL_EXECUTION_DENIED`,message:e.output.reason??`Tool execution was denied.`};case`content`:return toJsonValue(e.output.value)}})}function isToolResultError(e){return e.type===`error-json`||e.type===`error-text`||e.type===`execution-denied`}export{createRuntimeToolResultFromMessagePart,createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toError}from"#shared/errors.js";import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let i=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:i})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:i})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:i}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(a,o,s){let c=``,l=``,u=`stop`,d,f=new Set,p=new Set,m=new Set,h=[],g=[],flushCurrentMessage=async()=>{l.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l=``)},emitProviderToolCall=async e=>{p.has(e.toolCallId)||(p.add(e.toolCallId),await a(createActionsRequestedEvent({actions:[{callId:e.toolCallId,input:resolveToolCallInputObject(e.input,{callId:e.toolCallId,toolName:e.toolName}),kind:`tool-call`,toolName:e.toolName}],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))};for await(let n of s)if(d===void 0)switch(n.type){case`reasoning-delta`:c+=n.text,await a(createReasoningAppendedEvent({reasoningDelta:n.text,reasoningSoFar:c,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:c.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:c,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),c=``),l+=n.text,await a(createMessageAppendedEvent({messageDelta:n.text,messageSoFar:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let e=n;f.add(e.toolCallId),e.providerExecuted===!0&&await emitProviderToolCall(e);break}case`tool-result`:{let e=n;if(e.providerExecuted===!0){await emitProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await a(createActionResultEvent({result:createRuntimeToolResultFromStepResult(e),sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break}if(f.has(n.toolCallId))break;if(await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){m.add(n.toolCallId),h.push(e);break}await a(createActionResultEvent({result:createRuntimeToolResultFromStepResult(e),sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),m.add(n.toolCallId);let r=e.output;g.push({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:typeof r==`string`?{type:`text`,value:r}:{type:`json`,value:r??null}});break}case`tool-error`:{let r=n;r.providerExecuted===!0&&(await emitProviderToolCall(r),await a(createActionResultEvent({result:createRuntimeToolResultFromValue({callId:r.toolCallId,isError:!0,output:toError(r.error),toolName:r.toolName}),sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})));break}case`finish-step`:u=normalizeAssistantStepFinishReason(n.finishReason);break;case`error`:d=toError(n.error);break;default:break}if(d!==void 0)throw d;return c.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:c,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l.length>0&&await a(createMessageCompletedEvent({finishReason:u,message:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{handledInlineToolResultCallIds:m,inlineAuthorizationResults:h,inlineToolResultParts:g}}function isInlineAuthorizationToolResult(e){if(isPendingAuthorizationToolOutput(e.output))return!0;let t=contextStorage.getStore();if(t===void 0)return!1;let n=readToolInterrupt(t,e.toolCallId);return n!==void 0&&isAuthorizationSignal(n)}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
|
|
1
|
+
import{toError}from"#shared/errors.js";import{createActionResultEvent,createActionsRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepFailedEvent,createStepStartedEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";const HARNESS_EMISSION_STATE_KEY=`eve.harness.emission`,DEFAULT_EMISSION_STATE={sessionStarted:!1,sequence:0,stepIndex:0,turnId:``};function getHarnessEmissionState(e){return e?.[HARNESS_EMISSION_STATE_KEY]??DEFAULT_EMISSION_STATE}function isHarnessBetweenTurns(e){return getHarnessEmissionState(e.state).turnId===``}function setHarnessEmissionState(e,t){return{...e,state:{...e.state,[HARNESS_EMISSION_STATE_KEY]:t}}}async function emitTurnPreamble(e,t,n,r){let i=`turn_${n.sequence}`;return n.sessionStarted||await e(createSessionStartedEvent({runtime:r})),await e(createTurnStartedEvent({sequence:n.sequence,turnId:i})),t.message!==void 0&&await e(createMessageReceivedEvent({message:t.message,sequence:n.sequence,turnId:i})),{sessionStarted:!0,sequence:n.sequence,stepIndex:0,turnId:i}}async function emitStepStarted(e,t,n){await e(createStepStartedEvent({sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId}),n)}async function emitStepAndTurnFailed(e,t,n){await e(createStepFailedEvent({...n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),await e(createTurnFailedEvent({...n,sequence:t.sequence,turnId:t.turnId}))}async function emitFailedStep(e,t,n){await emitStepAndTurnFailed(e,t,n),await e(createSessionFailedEvent(n))}async function emitRecoverableFailedTurn(e,t,n){return await emitStepAndTurnFailed(e,t,n),await e(createSessionWaitingEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function advanceStep(e){return{...e,stepIndex:e.stepIndex+1}}async function emitTurnEpilogue(e,t,n){return await e(createTurnCompletedEvent({sequence:t.sequence,turnId:t.turnId})),n===`conversation`?await e(createSessionWaitingEvent()):await e(createSessionCompletedEvent()),{sessionStarted:t.sessionStarted,sequence:t.sequence+1,stepIndex:0,turnId:``}}function normalizeAssistantStepFinishReason(e){switch(e){case`content-filter`:case`error`:case`length`:case`stop`:case`tool-calls`:return e;default:return`other`}}async function emitStreamContent(a,o,s){let c=``,l=``,u=`stop`,d,f=new Set,p=new Set,m=new Set,h=[],g=[],flushCurrentMessage=async()=>{l.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l=``)},emitProviderToolCall=async e=>{p.has(e.toolCallId)||(p.add(e.toolCallId),await a(createActionsRequestedEvent({actions:[{callId:e.toolCallId,input:resolveToolCallInputObject(e.input,{callId:e.toolCallId,toolName:e.toolName}),kind:`tool-call`,toolName:e.toolName}],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))};for await(let n of s)if(d===void 0)switch(n.type){case`reasoning-delta`:c+=n.text,await a(createReasoningAppendedEvent({reasoningDelta:n.text,reasoningSoFar:c,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:c.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:c,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),c=``),l+=n.text,await a(createMessageAppendedEvent({messageDelta:n.text,messageSoFar:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let e=n;f.add(e.toolCallId),e.providerExecuted===!0&&await emitProviderToolCall(e);break}case`tool-result`:{let e=n;if(e.providerExecuted===!0){await emitProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await a(createActionResultEvent({result:createRuntimeToolResultFromStepResult(e),sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break}if(f.has(n.toolCallId))break;if(await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){m.add(n.toolCallId),h.push(e);break}await a(createActionResultEvent({result:createRuntimeToolResultFromStepResult(e),sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),m.add(n.toolCallId);let r=e.output;g.push({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:typeof r==`string`?{type:`text`,value:r}:{type:`json`,value:r??null}});break}case`tool-error`:{let r=n;r.providerExecuted===!0&&(await emitProviderToolCall(r),await a(createActionResultEvent({result:createRuntimeToolResultFromValue({callId:r.toolCallId,isError:!0,output:toError(r.error),toolName:r.toolName}),sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})));break}case`finish-step`:u=normalizeAssistantStepFinishReason(n.finishReason);break;case`error`:d=toError(n.error);break;default:break}if(d!==void 0)throw d;return c.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:c,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u!==`tool-calls`&&hasEmptyDeliverySentinel(l)?await a(createMessageCompletedEvent({finishReason:u,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):l.trim().length>0&&await a(createMessageCompletedEvent({finishReason:u,message:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{handledInlineToolResultCallIds:m,inlineAuthorizationResults:h,inlineToolResultParts:g}}function isInlineAuthorizationToolResult(e){if(isPendingAuthorizationToolOutput(e.output))return!0;let t=contextStorage.getStore();if(t===void 0)return!1;let n=readToolInterrupt(t,e.toolCallId);return n!==void 0&&isAuthorizationSignal(n)}export{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,isHarnessBetweenTurns,normalizeAssistantStepFinishReason,setHarnessEmissionState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function coalesceTurnInputs(e,t){let n=coalesceInputResponses({a:e.inputResponses,b:t.inputResponses}),r=coalesceMessage({a:e.message,b:t.message}),i=coalesceContext({a:e.context,b:t.context}),a=t.outputSchema??e.outputSchema,o={};return n!==void 0&&(o.inputResponses=n),r!==void 0&&(o.message=r),i!==void 0&&(o.context=i),a!==void 0&&(o.outputSchema=a),o}function resolveAssistantStepText(e,t){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role!==`assistant`)continue;let r=extractMessageText(n);if(r.length>0)return r}return t!==void 0&&t.length>0?t:null}function extractMessageText(e){return typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.flatMap(e=>typeof e==`string`?[e]:`type`in e&&e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(``):``}function coalesceInputResponses(e){let t=e.a??[],n=e.b??[];if(!(t.length===0&&n.length===0))return[...t,...n]}function coalesceContext(e){let t=e.a??[],n=e.b??[];if(!(t.length===0&&n.length===0))return[...t,...n]}function coalesceMessage(e){return e.a===void 0?e.b:e.b===void 0?e.a:typeof e.a==`string`&&typeof e.b==`string`?`${e.a}\n\n${e.b}`:[...toUserContentArray(e.a),...toUserContentArray(e.b)]}function toUserContentArray(e){return typeof e==`string`?e.length>0?[{type:`text`,text:e}]:[]:Array.isArray(e)?[...e]:[]}function coalesceDeliveries(e){let[t,...n]=e;if(t===void 0)throw Error(`Cannot coalesce an empty delivery batch.`);let r=t.auth,i=[...t.payloads];for(let e of n)e.auth!==void 0&&(r=e.auth),i.push(...e.payloads);return{...t,auth:r,payloads:i}}export{coalesceDeliveries,coalesceTurnInputs,resolveAssistantStepText};
|
|
1
|
+
function coalesceTurnInputs(e,t){let n=coalesceInputResponses({a:e.inputResponses,b:t.inputResponses}),r=coalesceMessage({a:e.message,b:t.message}),i=coalesceContext({a:e.context,b:t.context}),a=t.outputSchema??e.outputSchema,o={};return n!==void 0&&(o.inputResponses=n),r!==void 0&&(o.message=r),i!==void 0&&(o.context=i),a!==void 0&&(o.outputSchema=a),o}function resolveAssistantStepText(e,t){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role!==`assistant`)continue;let r=extractMessageText(n);if(r.trim().length>0)return r}return t!==void 0&&t.trim().length>0?t:null}function extractMessageText(e){return typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.flatMap(e=>typeof e==`string`?[e]:`type`in e&&e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(``):``}function coalesceInputResponses(e){let t=e.a??[],n=e.b??[];if(!(t.length===0&&n.length===0))return[...t,...n]}function coalesceContext(e){let t=e.a??[],n=e.b??[];if(!(t.length===0&&n.length===0))return[...t,...n]}function coalesceMessage(e){return e.a===void 0?e.b:e.b===void 0?e.a:typeof e.a==`string`&&typeof e.b==`string`?`${e.a}\n\n${e.b}`:[...toUserContentArray(e.a),...toUserContentArray(e.b)]}function toUserContentArray(e){return typeof e==`string`?e.length>0?[{type:`text`,text:e}]:[]:Array.isArray(e)?[...e]:[]}function coalesceDeliveries(e){let[t,...n]=e;if(t===void 0)throw Error(`Cannot coalesce an empty delivery batch.`);let r=t.auth,i=[...t.payloads];for(let e of n)e.auth!==void 0&&(r=e.auth),i.push(...e.payloads);return{...t,auth:r,payloads:i}}export{coalesceDeliveries,coalesceTurnInputs,resolveAssistantStepText};
|
|
@@ -4,7 +4,7 @@ import type { JsonObject } from "#shared/json.js";
|
|
|
4
4
|
/**
|
|
5
5
|
* The provider backend resolved for one web search tool invocation.
|
|
6
6
|
*/
|
|
7
|
-
export type WebSearchBackend = "anthropic" | "
|
|
7
|
+
export type WebSearchBackend = "anthropic" | "google" | "openai" | "parallel";
|
|
8
8
|
/**
|
|
9
9
|
* Returns the framework tool name that produced an upstream provider tool
|
|
10
10
|
* `type`, or `null` when the type is not one we know how to remove.
|
|
@@ -14,41 +14,18 @@ export type WebSearchBackend = "anthropic" | "gateway" | "google" | "openai";
|
|
|
14
14
|
* the existing terminal/recoverable handling.
|
|
15
15
|
*/
|
|
16
16
|
export declare function resolveFrameworkToolFromUpstreamType(type: string): string | null;
|
|
17
|
-
/**
|
|
18
|
-
* Maps a {@link WebSearchBackend} to the gateway provider slug used in
|
|
19
|
-
* `providerOptions.gateway.only` to pin routing to that provider.
|
|
20
|
-
*
|
|
21
|
-
* Returns `null` for the `"gateway"` backend (Perplexity via AI Gateway),
|
|
22
|
-
* which is served by the gateway directly and does not need pinning.
|
|
23
|
-
*/
|
|
24
|
-
export declare function resolveGatewayPinForWebSearchBackend(backend: WebSearchBackend): string | null;
|
|
25
17
|
/**
|
|
26
18
|
* Returns the output schema for the provider-managed web search tool that
|
|
27
19
|
* will be injected for `backend`.
|
|
28
20
|
*/
|
|
29
21
|
export declare function resolveWebSearchOutputSchema(backend: WebSearchBackend): JsonObject;
|
|
30
|
-
/**
|
|
31
|
-
* Returns a new `providerOptions` object with
|
|
32
|
-
* `gateway.only = [provider]` merged into the existing `gateway`
|
|
33
|
-
* sub-object so the AI Gateway only attempts the given provider.
|
|
34
|
-
*
|
|
35
|
-
* Used by the harness to pin routing when a provider-specific tool
|
|
36
|
-
* (e.g. Anthropic's `web_search_20250305`) is in the per-step toolset,
|
|
37
|
-
* so a transient primary outage produces a clean retryable 503 instead
|
|
38
|
-
* of a fallback-to-incompatible-provider 400.
|
|
39
|
-
*
|
|
40
|
-
* Author overrides win — if `base.gateway.only` or `base.gateway.order`
|
|
41
|
-
* is already set, the input is returned unchanged so explicit routing
|
|
42
|
-
* preferences are never silently overwritten.
|
|
43
|
-
*/
|
|
44
|
-
export declare function mergeGatewayProviderPin(base: Readonly<Record<string, unknown>> | undefined, provider: string): Record<string, unknown>;
|
|
45
22
|
/**
|
|
46
23
|
* Determines the web search backend for a model reference.
|
|
47
24
|
*
|
|
48
|
-
* -
|
|
49
|
-
* -
|
|
25
|
+
* - All AI Gateway models: Parallel search via gateway
|
|
26
|
+
* - Direct/BYO OpenAI models: native OpenAI search
|
|
27
|
+
* - Direct/BYO Anthropic models: native Anthropic search
|
|
50
28
|
* - Direct/BYO Google models: native Google search grounding
|
|
51
|
-
* - Other models on AI Gateway (including `google/...`): Perplexity search via gateway
|
|
52
29
|
* - Other BYO models: not available (returns `null`)
|
|
53
30
|
*/
|
|
54
31
|
export declare function resolveWebSearchBackend(modelRef: RuntimeModelReference): WebSearchBackend | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{jsonSchema}from"ai";import{WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA,WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA,WEB_SEARCH_OPENAI_OUTPUT_SCHEMA,WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA,WEB_SEARCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-search.js";const UPSTREAM_TOOL_TYPE_TO_FRAMEWORK_NAME={web_search_20250305:WEB_SEARCH_TOOL_DEFINITION.name};function resolveFrameworkToolFromUpstreamType(e){return UPSTREAM_TOOL_TYPE_TO_FRAMEWORK_NAME[e]??null}function resolveWebSearchOutputSchema(e){switch(e){case`anthropic`:return WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA;case`google`:return WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA;case`openai`:return WEB_SEARCH_OPENAI_OUTPUT_SCHEMA;case`parallel`:return WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA}}function resolveWebSearchBackend(e){if(e.source===void 0)return`parallel`;let t=e.id.split(`/`)[0]??``;return t===`openai`||t.startsWith(`openai.`)?`openai`:t===`anthropic`||t.startsWith(`anthropic.`)?`anthropic`:t.startsWith(`google.`)?`google`:null}async function resolveWebSearchProviderTool(e){switch(e){case`openai`:{let{openai:t}=await import(`#compiled/@ai-sdk/openai/index.js`);return attachWebSearchOutputSchema(t.tools.webSearch({}),e)}case`anthropic`:{let{anthropic:t}=await import(`#compiled/@ai-sdk/anthropic/index.js`);return attachWebSearchOutputSchema(t.tools.webSearch_20250305(),e)}case`google`:{let{google:t}=await import(`#compiled/@ai-sdk/google/index.js`);return attachWebSearchOutputSchema(t.tools.googleSearch({}),e)}case`parallel`:{let{gateway:t}=await import(`ai`);return attachWebSearchOutputSchema(t.tools.parallelSearch(),e)}}}function attachWebSearchOutputSchema(t,n){return{...t,outputSchema:jsonSchema(resolveWebSearchOutputSchema(n))}}export{resolveFrameworkToolFromUpstreamType,resolveWebSearchBackend,resolveWebSearchOutputSchema,resolveWebSearchProviderTool};
|
|
@@ -24,19 +24,6 @@ interface StepHooksInput {
|
|
|
24
24
|
* Defaults to `true`.
|
|
25
25
|
*/
|
|
26
26
|
readonly emitStepStarted?: boolean;
|
|
27
|
-
/**
|
|
28
|
-
* When set on the `gateway-auto` cache path, merges
|
|
29
|
-
* `providerOptions.gateway.only = [gatewayPinProvider]` so the AI
|
|
30
|
-
* Gateway only routes to the given provider. Used to keep
|
|
31
|
-
* provider-specific tools (e.g. Anthropic's `web_search_20250305`)
|
|
32
|
-
* on a provider that can serve them, converting a transient outage
|
|
33
|
-
* into a clean retryable 503 rather than a fallback-to-incompatible
|
|
34
|
-
* provider 400.
|
|
35
|
-
*
|
|
36
|
-
* Ignored when the author already set `gateway.only` or
|
|
37
|
-
* `gateway.order` on the model reference's provider options.
|
|
38
|
-
*/
|
|
39
|
-
readonly gatewayPinProvider?: string;
|
|
40
27
|
readonly marker: AnthropicCacheMarker | undefined;
|
|
41
28
|
readonly session: HarnessSession;
|
|
42
29
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createActionResultEvent,createActionsRequestedEvent,createStepCompletedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{emitStepStarted,normalizeAssistantStepFinishReason}from"#harness/emission.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{createRuntimeToolResultFromMessagePart,createRuntimeToolResultFromStepResult}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyConversationCacheControl,mergeGatewayAutoCaching}from"#harness/prompt-cache.js";
|
|
1
|
+
import{createActionResultEvent,createActionsRequestedEvent,createStepCompletedEvent}from"#protocol/message.js";import{contextStorage}from"#context/container.js";import{emitStepStarted,normalizeAssistantStepFinishReason}from"#harness/emission.js";import{createRuntimeActionRequestFromToolCall}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{createRuntimeToolResultFromMessagePart,createRuntimeToolResultFromStepResult}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyConversationCacheControl,mergeGatewayAutoCaching}from"#harness/prompt-cache.js";function buildStepHooks(e){let t=e.session,n=e.emit,r;return{onStepFinish:async e=>{r(e)},prepareStep:async({messages:r})=>{let a=r;n&&e.emitStepStarted!==!1&&await emitStepStarted(n,e.emissionState,r),e.cachePath.kind===`anthropic-direct`&&e.marker&&(a=applyConversationCacheControl([...r],e.marker));let o={messages:a};return e.cachePath.kind===`gateway-auto`&&(o.providerOptions=mergeGatewayAutoCaching(t.agent.modelReference.providerOptions)),o},stepResult:new Promise(e=>{r=e})}}async function emitStepActions(r,i,s,c){let l=new Set(s.toolCalls.filter(isProviderExecutedToolCall).map(e=>e.toolCallId)),u=new Set([...l,...extractToolApprovalInputRequests({content:s.content??[]}).map(e=>e.action.callId),...s.toolCalls.filter(isInvalidToolCall).map(e=>e.toolCallId)]),isExcluded=(e,t)=>u.has(e)||c.excludedActionToolNames.has(t),d=s.toolCalls.filter(e=>!isExcluded(e.toolCallId,e.toolName)).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:c.tools}));d.length>0&&await r(createActionsRequestedEvent({actions:d,sequence:i.sequence,stepIndex:i.stepIndex,turnId:i.turnId}));let f=c.handledInlineToolResultCallIds,p=new Map(s.toolResults.map(e=>[e.toolCallId,e.output]));for(let t of reconcileToolResults(s)){if(isExcluded(t.callId,t.toolName)||f?.has(t.callId))continue;let n=p.get(t.callId);shouldSkipAuthorizationActionResult(t.callId,n)||await r(createActionResultEvent({result:t,sequence:i.sequence,stepIndex:i.stepIndex,turnId:i.turnId}))}await r(createStepCompletedEvent({finishReason:normalizeAssistantStepFinishReason(s.finishReason),sequence:i.sequence,stepIndex:i.stepIndex,turnId:i.turnId,usage:extractStepUsage(s.usage)}))}function isInvalidToolCall(e){return e.invalid===!0}function isProviderExecutedToolCall(e){return e.providerExecuted===!0}function reconcileToolResults(e){let t=new Map;for(let n of e.toolResults)n.providerExecuted!==!0&&t.set(n.toolCallId,createRuntimeToolResultFromStepResult(n));for(let n of extractToolResultParts(e.response.messages))n.providerExecuted!==!0&&(t.has(n.toolCallId)||t.set(n.toolCallId,createRuntimeToolResultFromMessagePart(n)));return[...t.values()]}function shouldSkipAuthorizationActionResult(e,t){if(t!==void 0&&isPendingAuthorizationToolOutput(t))return!0;let n=contextStorage.getStore();if(n===void 0)return!1;let i=readToolInterrupt(n,e);return i!==void 0&&isAuthorizationSignal(i)}function extractToolResultParts(e){let t=[];for(let n of e)if(!(n.role!==`tool`||!Array.isArray(n.content)))for(let e of n.content)e.type===`tool-result`&&t.push(e);return t}function extractStepUsage(e){if(e===void 0)return;let t={};return e.inputTokens!==void 0&&(t.inputTokens=e.inputTokens),e.outputTokens!==void 0&&(t.outputTokens=e.outputTokens),e.inputTokenDetails?.cacheReadTokens!==void 0&&(t.cacheReadTokens=e.inputTokenDetails.cacheReadTokens),e.inputTokenDetails?.cacheWriteTokens!==void 0&&(t.cacheWriteTokens=e.inputTokenDetails.cacheWriteTokens),Object.keys(t).length>0?t:void 0}export{buildStepHooks,emitStepActions,isInvalidToolCall};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,isNoOutputGeneratedError,summarizeKnownModelCallConfigError,summarizeKnownModelCallRequestError}from"#harness/model-call-error.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createResultCompletedEvent}from"#protocol/message.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ToolLoopAgent,isStepCount}from"ai";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{clearPendingCodeModeInterrupt,getPendingCodeModeInterrupt,setPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{CODE_MODE_TOOL_NAME,loadCodeModeModule}from"#shared/code-mode.js";import{isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{resolveAssistantStepText}from"#harness/messages.js";import{buildDynamicInstructionMessages}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{consumeDeferredStepInput,getApprovedTools,hasDeferredStepInput,hasStepInput,resolvePendingInput,setPendingInputBatch}from"#harness/input-requests.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{isCodeModeConnectionAuthInterrupt}from"#runtime/framework-tools/code-mode-connection-auth.js";import{isSandboxEnabled,selectSandboxSurfaces}from"#harness/sandbox-surface.js";import{buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{WEB_SEARCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-search.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{resolveFrameworkToolFromUpstreamType,resolveGatewayPinForWebSearchBackend,resolveWebSearchBackend}from"#harness/provider-tools.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{applySandboxToolSet,buildSandboxHostTools,createEveCodeModeOptions}from"#harness/code-mode.js";import{createCodeModeLifecycle}from"#harness/code-mode-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#runtime/framework-tools/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n){if(e===void 0)return;let r={};for(let e of Object.keys(n??{}))r[e]=!0;return{functionId:e.functionId??t,includeRuntimeContext:r,isEnabled:!0,recordInputs:e.recordInputs??!0,recordOutputs:e.recordOutputs??!0}}function resolveGatewayPinForStep(e){if(e.cachePath.kind!==`gateway-auto`||e.tools[WEB_SEARCH_TOOL_DEFINITION.name]===void 0)return;let t=resolveWebSearchBackend(e.modelReference);return t===null?void 0:resolveGatewayPinForWebSearchBackend(t)??void 0}function buildGatewayAttributionHeaders(e,t){if(typeof e!=`string`)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0;if(!n&&!i)return;let a={};return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function createToolLoopHarness(t){let n=t.handleEvent,a=getInstrumentationConfig();a!==void 0&&ensureOtelIntegration();let l=a===void 0?void 0:trace.getTracer(`eve`),u=t.runtimeIdentity?.agentName;async function runStep(e,t){let n;if(l&&hasStepInput(t)){let t=a?.functionId??u,r={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(r[`ai.telemetry.functionId`]=t),n=l.startSpan(`ai.eve.turn`,{attributes:r})}let r=resolveStepOtelContext(l,n,e),executeStep=()=>executeStepBody(e,t,n);try{return r?await context.with(r,executeStep):await executeStep()}finally{n?.end()}}async function executeStepBody(l,h,g){let _=l;g&&(_=setTurnTraceState(_,g.spanContext()));let v=getHarnessEmissionState(_.state),y=consumeDeferredStepInput({input:h,session:_});_=y.session;let C=await resolvePendingRuntimeActions({emit:n,session:_,stepInput:y.input});if(C.outcome===`unresolved`)return{next:null,session:C.session};_=C.session;let w=resolvePendingInput({history:C.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:_,stepInput:y.input});if(w.outcome===`unresolved`)return{next:null,session:w.session};if(n&&w.rejectedActions)for(let e of w.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:w.rejectedActions.event.sequence,stepIndex:w.rejectedActions.event.stepIndex,turnId:w.rejectedActions.event.turnId}));n&&hasStepInput(h)&&(v=await emitTurnPreamble(n,h??{},v,t.runtimeIdentity),_=setHarnessEmissionState(_,v),g&&g.setAttribute(`eve.turn.id`,v.turnId)),_=w.session;let T=w.messages;if(y.input?.context!==void 0)for(let e of y.input.context)T.push({content:e,role:`user`});if(y.input?.message!==void 0&&!w.deferredMessage){let e=await stageAttachmentsToSandbox(y.input.message);T.push({content:e,role:`user`})}let E=await t.resolveModel(_.agent.modelReference),D=detectPromptCachePath(E),O=D.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,k=buildGatewayAttributionHeaders(E,t.runtimeIdentity);({messages:T,session:_}=await maybeCompact({emit:n,emissionState:v,headers:k,messages:T,model:E,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:_,telemetry:enrichTelemetry(a,u)??void 0}));let A=getApprovedTools(_),j=contextStorage.getStore(),M=await hydrateSandboxAttachments(T),N=[],P=[];for(let e of M)e.role===`system`?N.push(e):P.push(e);if(j!==void 0){N.push(...buildDynamicInstructionMessages(j));let e=j.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&N.push({role:`system`,content:e})}let F=P,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=_.agent.system?[{role:`system`,content:_.agent.system}]:[],r=N.length>0||t.length>0?[...t,...n,...N]:void 0,i=r!==void 0&&O?applySystemCacheBreakpoint(r,O):r??_.agent.system??void 0;return{instructions:i,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:a,emissionState:v,environment,modelInput:{instructions:i,messages:F},session:_})}},runOneModelCall=async e=>{let{instructions:i,telemetryRuntimeContext:s={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(s[`eve.retry.reason`]=e.retryReason);let c=e.trailingUserNote?[...F,{role:`user`,content:e.trailingUserNote}]:F,l=selectSandboxSurfaces(t),f=await buildToolSetWithProviderTools({approvedTools:A,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:_.agent.modelReference,tools:t.tools});if(j!==void 0){let n=buildDynamicTools(j),r=buildToolSetFromDefinitions({approvedTools:A,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r))f[e]=t}_.outputSchema!==void 0&&(f[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(_.outputSchema));let p=l.length>0?(await applySandboxToolSet({harnessTools:t.tools,lifecycle:n===void 0?void 0:createCodeModeLifecycle({emit:n,emissionState:v,tools:t.tools}),tools:f,surfaces:l})).modelTools:f,m=O?applyLastToolCacheBreakpoint(p,O):p,h=resolveGatewayPinForStep({cachePath:D,modelReference:_.agent.modelReference,tools:m}),g=buildStepHooks({cachePath:D,emit:n,emissionState:v,emitStepStarted:e.suppressStepStartedEmission!==!0,gatewayPinProvider:h,marker:O,session:_}),y=new ToolLoopAgent({headers:k,instructions:i,model:E,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:g.onStepFinish,prepareStep:g.prepareStep,runtimeContext:s,stopWhen:isStepCount(1),telemetry:enrichTelemetry(a,u,s),tools:m}),executeModelCall=async()=>{if(n){let e=await y.stream({messages:c}),{handledInlineToolResultCallIds:r,inlineAuthorizationResults:i,inlineToolResultParts:a}=await emitStreamContent(n,v,e.fullStream),s=await g.stepResult;if(isEmptyModelResponse(s))throw new EmptyModelResponseError;if(await emitStepActions(n,v,s,{excludedActionToolNames:new Set([ASK_QUESTION_TOOL_NAME,CODE_MODE_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME]),handledInlineToolResultCallIds:r,tools:t.tools}),a.length>0||i.length>0){let e=s.toolResults,t=new Map(e.map(e=>[e.toolCallId,e]));for(let e of i)t.set(e.toolCallId,e);return{content:s.content,finishReason:s.finishReason,response:{...s.response,...a.length>0?{messages:[{role:`tool`,content:[...a]},...s.response.messages]}:{}},text:s.text,toolCalls:s.toolCalls,toolResults:[...t.values()],usage:s.usage}}return s}await y.generate({messages:c});let e=await g.stepResult;if(isEmptyModelResponse(e))throw new EmptyModelResponseError;return e};return runModelCallWithRetries(()=>executeModelCall().catch(rethrowNoOutputAsEmptyResponse),{sessionId:_.sessionId,turnId:v.turnId})},I=prepareModelCallInput();n&&await emitStepStarted(n,v,T);let L=await continuePendingCodeModeInterrupt({capabilities:t.capabilities,childResults:y.input?.runtimeActionResults,config:t,emit:n,emissionState:v,messages:T,runStep,session:_});if(L!==null)return L;let R;try{R=await runOneModelCall({preparedInput:I,suppressStepStartedEmission:!0})}catch(r){let a=await runModelCallRecoveryPipeline({error:r,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:_.sessionId,turnId:v.turnId}),e=>attemptEmptyResponseRecovery({error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:_.sessionId,turnId:v.turnId})]});if(a.outcome===`recovered`)R=a.result;else{let r=a.error;if(g&&recordErrorOnSpan(g,r),!n)throw r;let o=extractWorkflowStreamWriteErrorDetails(r);if(o!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...o,errorId:t,error:r,sessionId:_.sessionId,turnId:v.turnId}),v=await emitRecoverableFailedTurn(n,v,{code:`WORKFLOW_STREAM_WRITE_FAILED`,details:{...o,errorId:t},message:toErrorMessage(r)}),{next:null,session:setHarnessEmissionState(_,v)}}let l=classifyModelCallError(r),u=createErrorId(),m=l===`terminal`?summarizeKnownModelCallConfigError(r):null,h=m===null?summarizeKnownModelCallRequestError(r):null,y=m?.message??h?.message??toErrorMessage(r),b=extractModelCallErrorDetails(r),x=buildModelCallFailureDetails({configSummary:m,error:r,errorId:u,modelCallDetails:b,requestSummary:h}),S=buildModelCallFailureLogFields({error:r,errorId:u,modelCallDetails:b,requestSummary:h,sessionId:_.sessionId,turnId:v.turnId});return l===`terminal`?(m===null?log.error(h?.message??`model call failed terminally`,S):log.error(`${m.name}: ${m.message}`,{errorId:u,sessionId:_.sessionId,turnId:v.turnId}),await emitFailedStep(n,v,{code:`MODEL_CALL_FAILED`,details:x,message:y,sessionId:_.sessionId}),{next:{done:!0,output:``},session:_}):t.mode===`task`?(log.error(h?.message??`model call failed; failing the task run`,S),await emitFailedStep(n,v,{code:`MODEL_CALL_FAILED`,details:x,message:y,sessionId:_.sessionId}),{next:{done:!0,isError:!0,output:y},session:_}):(log.error(h?.message??`model call failed — parking session for retry by the user`,S),v=await emitRecoverableFailedTurn(n,v,{code:`MODEL_CALL_FAILED`,details:x,message:y}),{next:null,session:setHarnessEmissionState(_,v)})}}let z=accumulateTurnUsage({previous:getTurnUsageState(_.state),turnId:v.turnId,usage:R.usage??{}});_=setTurnUsageState(_,z);let B;try{B=formatLanguageModelGatewayId(E)}catch{B=void 0}return await setEveAttributes({"$eve.model":B,"$eve.input_tokens":z.inputTokens,"$eve.output_tokens":z.outputTokens,"$eve.cache_read_tokens":z.cacheReadTokens,"$eve.cache_write_tokens":z.cacheWriteTokens,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:v,promptMessages:T,result:R,runStep,session:_})}return runStep}function buildModelCallFailureDetails(e){let{configSummary:t,error:r,errorId:i,modelCallDetails:a,requestSummary:o}=e;return t===null?o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}:{errorId:i,message:t.message,name:t.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.requestSummary===null?{...t,error:e.error}:{...t,details:e.modelCallDetails}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.finishReason===`other`&&e.toolCalls.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:`Your previous reply was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=i.response.messages,l=resolveAssistantStepText(c,i.text),u={...s,compaction:createNextCompactionConfig(s.compaction,r,i)};if(isSandboxEnabled(t)){let{getCodeModeInterrupt:e}=await loadCodeModeModule(),a=e(i);if(a!==void 0)return parkOnCodeModeInterrupt({baseSession:u,config:t,emit:n,emissionState:o,interrupt:a,promptMessages:r,responseMessages:c})}let d=extractToolApprovalInputRequests({content:i.content??[]}),f=new Set(d.map(e=>e.action.callId)),p=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:f}),m=[...d,...p],g=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:t.tools}));if(g.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:g,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:c,session:{...u,history:[...r]}}),o)};if(m.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:m,responseMessages:c,session:{...u,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:m,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode),e=setHarnessEmissionState(e,o))),{next:null,session:e}}let _=findAuthorizationSignalFromToolResults(i.toolResults);if(_){let{challenges:e}=_;if(n)for(let t of e)await n(createAuthorizationRequiredEvent({authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));return{next:null,session:setHarnessEmissionState({...u,history:[...r],state:setPendingAuthorization(u.state,{challenges:e})},o)}}let y=[...r,...c],b={...u,history:y};return!(b.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(c.at(-1)?.role===`tool`||hasDeferredStepInput(b))?(n&&(o=advanceStep(o),b=setHarnessEmissionState(b,o)),{next:a,session:b}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:b.outputSchema,session:b,stepOutput:l}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:b.outputSchema,session:b})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME)?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i}=e,{emissionState:a,session:o}=e;if(i===void 0)return t&&(a=await emitTurnEpilogue(t,a,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o};let s=extractFinalOutput(r);return s===void 0?(t&&(a=await emitRecoverableFailedTurn(t,a,OUTPUT_SCHEMA_NOT_FULFILLED),o=setHarnessEmissionState(o,a)),{next:null,session:o}):(o=persistStructuredAssistantTurn(o,n,s),t&&(a=await emitStructuredResult(t,a,s,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o})}async function continuePendingCodeModeInterrupt(e){let t=getPendingCodeModeInterrupt(e.session.state);if(t===void 0)return null;let{continueCodeModeApproval:n,continueCodeModeInterrupt:i,getCodeModeApprovalResponse:a,isCodeModeApprovalInterrupt:o,replaceCodeModeInterruptResult:s,unwrapCodeModeResult:c}=await loadCodeModeModule(),l=t.interrupt,u=o(l)?a([...e.messages],l):void 0;if(o(l)&&u===void 0)return{next:null,session:e.session};let d=createEveCodeModeOptions({lifecycle:e.emit===void 0?void 0:createCodeModeLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools})}),f;try{let t=await buildSandboxHostTools({approvedTools:getApprovedTools(e.session),capabilities:e.capabilities,tools:e.config.tools});if(o(l)&&u!==void 0)f=await n({approvalResponse:u,interrupt:l,options:d,tools:t});else if(isCodeModeConnectionAuthInterrupt(l))f=await i({interrupt:l,resolution:{status:`authorized`},tools:t,options:d});else if(isCodeModeRuntimeActionInterrupt(l)){let n=e.childResults??[],r=l,a=0;for(;;){f=await i({interrupt:r,resolution:n[a]?.output,tools:t,options:d});let e=c(f);if(e.status!==`interrupted`||!isCodeModeRuntimeActionInterrupt(e.interrupt)||a+1>=n.length)break;a++,r=e.interrupt}}else throw Error(`Unsupported code-mode interrupt kind "${l.payload.kind}".`)}catch(e){logError(log,`code-mode interrupt continuation failed`,e),f={error:`code_mode_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let m=c(f),h=m.status===`interrupted`?m.interrupt:m.output,g=[...e.session.history,...t.responseMessages],_=isCodeModeRuntimeActionInterrupt(l)?replaceCodeModeToolResult(g,l.outerToolCallId,h):s(g,l,h),v=clearPendingCodeModeInterrupt({...e.session,history:_});if(m.status===`interrupted`){let t=e.session.history.length,n=_.slice(0,t),r=_.slice(t);return v={...v,history:n},parkOnCodeModeInterrupt({baseSession:v,config:e.config,emit:e.emit,emissionState:e.emissionState,interrupt:m.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:v}}function replaceCodeModeToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}async function parkOnCodeModeInterrupt(e){let{isCodeModeApprovalInterrupt:t,toCodeModeApprovalMessages:n}=await loadCodeModeModule(),r=e.interrupt,i={...e.baseSession,history:[...e.promptMessages]};if(isCodeModeConnectionAuthInterrupt(r)){let t=[...r.payload.challenges??[]];if(e.emit)for(let n of t)await e.emit(createAuthorizationRequiredEvent({authorization:n.challenge,name:n.name,description:n.challenge.instructions??`Authorization required for ${n.name}`,webhookUrl:n.hookUrl,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId}));return{next:null,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:{...i,state:setPendingAuthorization(i.state,{challenges:t})}})}}if(t(r)){let t=n(r),a=extractToolApprovalInputRequests({content:extractAssistantContent(t)}),o=setPendingInputBatch({event:{sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId},requests:a,responseMessages:t,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i})});if(e.emit&&(await e.emit(createInputRequestedEvent({requests:a,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId})),e.config.mode===`conversation`)){let t=await emitTurnEpilogue(e.emit,e.emissionState,e.config.mode);o=setHarnessEmissionState(o,t)}return{next:null,session:o}}return{next:null,session:setHarnessEmissionState(setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i}),e.emissionState)}}function extractAssistantContent(e){let t=[];for(let n of e)n.role===`assistant`&&Array.isArray(n.content)&&t.push(...n.content);return t}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t.length),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session;if(!shouldCompact(r,i.compaction))return{messages:r,session:i};let a=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:i.agent.modelReference,resolveModel:e.resolveModel});if(t&&await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(r,i.compaction)})),r=await compactMessages(r,a.model,i.compaction,a.providerOptions,e.telemetry,e.headers),e.onCompaction)for(let t of e.onCompaction())r.push(t);return t&&await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId})),{messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t){for(let n=1;;n++)try{return await e()}catch(e){if(n===3||classifyModelCallError(e)!==`retry`)throw e;let r=500*2**(n-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:n,delayMs:r,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,r))}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{createToolLoopHarness};
|
|
1
|
+
import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{isScheduleAppAuth}from"#channel/schedule-auth.js";import{AuthKey,ParentSessionKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,isNoOutputGeneratedError,summarizeKnownModelCallConfigError,summarizeKnownModelCallRequestError}from"#harness/model-call-error.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createResultCompletedEvent}from"#protocol/message.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ToolLoopAgent,isStepCount}from"ai";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{clearPendingCodeModeInterrupt,getPendingCodeModeInterrupt,setPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{CODE_MODE_TOOL_NAME,loadCodeModeModule}from"#shared/code-mode.js";import{isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{resolveAssistantStepText}from"#harness/messages.js";import{buildDynamicInstructionMessages}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{consumeDeferredStepInput,getApprovedTools,hasDeferredStepInput,hasStepInput,resolvePendingInput,setPendingInputBatch}from"#harness/input-requests.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{isCodeModeConnectionAuthInterrupt}from"#runtime/framework-tools/code-mode-connection-auth.js";import{isSandboxEnabled,selectSandboxSurfaces}from"#harness/sandbox-surface.js";import{buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{applySandboxToolSet,buildSandboxHostTools,createEveCodeModeOptions}from"#harness/code-mode.js";import{createCodeModeLifecycle}from"#harness/code-mode-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#runtime/framework-tools/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n){if(e===void 0)return;let r={};for(let e of Object.keys(n??{}))r[e]=!0;return{functionId:e.functionId??t,includeRuntimeContext:r,isEnabled:!0,recordInputs:e.recordInputs??!0,recordOutputs:e.recordOutputs??!0}}function buildGatewayAttributionHeaders(e,t){if(typeof e!=`string`)return;let n=t?.agentName??t?.agentId,r=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,i=r?`https://${r}`:void 0;if(!n&&!i)return;let a={};return n&&(a[`x-title`]=n),i&&(a[`http-referer`]=i),a}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function createToolLoopHarness(t){let n=t.handleEvent,c=getInstrumentationConfig();c!==void 0&&ensureOtelIntegration();let f=c===void 0?void 0:trace.getTracer(`eve`),p=t.runtimeIdentity?.agentName;async function runStep(e,t){let n;if(f&&hasStepInput(t)){let t=c?.functionId??p,r={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(r[`ai.telemetry.functionId`]=t),n=f.startSpan(`ai.eve.turn`,{attributes:r})}let r=resolveStepOtelContext(f,n,e),executeStep=()=>executeStepBody(e,t,n);try{return r?await context.with(r,executeStep):await executeStep()}finally{n?.end()}}async function executeStepBody(f,v,y){let b=f;y&&(b=setTurnTraceState(b,y.spanContext()));let x=getHarnessEmissionState(b.state),S=consumeDeferredStepInput({input:v,session:b});b=S.session;let E=await resolvePendingRuntimeActions({emit:n,session:b,stepInput:S.input});if(E.outcome===`unresolved`)return{next:null,session:E.session};b=E.session;let D=resolvePendingInput({history:E.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:b,stepInput:S.input});if(D.outcome===`unresolved`)return{next:null,session:D.session};if(n&&D.rejectedActions)for(let e of D.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:D.rejectedActions.event.sequence,stepIndex:D.rejectedActions.event.stepIndex,turnId:D.rejectedActions.event.turnId}));n&&hasStepInput(v)&&(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),b=setHarnessEmissionState(b,x),y&&y.setAttribute(`eve.turn.id`,x.turnId)),b=D.session;let O=D.messages;if(S.input?.context!==void 0)for(let e of S.input.context)O.push({content:e,role:`user`});if(S.input?.message!==void 0&&!D.deferredMessage){let e=await stageAttachmentsToSandbox(S.input.message);O.push({content:e,role:`user`})}let k=await t.resolveModel(b.agent.modelReference),A=detectPromptCachePath(k),j=A.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,M=buildGatewayAttributionHeaders(k,t.runtimeIdentity);({messages:O,session:b}=await maybeCompact({emit:n,emissionState:x,headers:M,messages:O,model:k,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:b,telemetry:enrichTelemetry(c,p)??void 0}));let N=getApprovedTools(b),P=contextStorage.getStore(),F=b.outputSchema===void 0&&P!==void 0&&isScheduleAppAuth(P.get(AuthKey))&&P.get(ParentSessionKey)===void 0,I=await hydrateSandboxAttachments(O),L=[],R=[];for(let e of I)e.role===`system`?L.push(e):R.push(e);if(P!==void 0){L.push(...buildDynamicInstructionMessages(P));let e=P.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&L.push({role:`system`,content:e})}F&&L.push({role:`system`,content:CONDITIONAL_DELIVERY_INSTRUCTION});let z=R,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=b.agent.system?[{role:`system`,content:b.agent.system}]:[],r=L.length>0||t.length>0?[...t,...n,...L]:void 0,i=r!==void 0&&j?applySystemCacheBreakpoint(r,j):r??b.agent.system??void 0;return{instructions:i,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:c,emissionState:x,environment,modelInput:{instructions:i,messages:z},session:b})}},runOneModelCall=async e=>{let{instructions:i,telemetryRuntimeContext:a={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(a[`eve.retry.reason`]=e.retryReason);let o=e.trailingUserNote?[...z,{role:`user`,content:e.trailingUserNote}]:z,s=selectSandboxSurfaces(t),u=await buildToolSetWithProviderTools({approvedTools:N,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:b.agent.modelReference,tools:t.tools});if(P!==void 0){let n=buildDynamicTools(P),r=buildToolSetFromDefinitions({approvedTools:N,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r))u[e]=t}b.outputSchema!==void 0&&(u[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(b.outputSchema));let d=s.length>0?(await applySandboxToolSet({harnessTools:t.tools,lifecycle:n===void 0?void 0:createCodeModeLifecycle({emit:n,emissionState:x,tools:t.tools}),tools:u,surfaces:s})).modelTools:u,f=j?applyLastToolCacheBreakpoint(d,j):d,h=buildStepHooks({cachePath:A,emit:n,emissionState:x,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:j,session:b}),g=new ToolLoopAgent({headers:M,instructions:i,model:k,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:h.onStepFinish,prepareStep:h.prepareStep,runtimeContext:a,stopWhen:isStepCount(1),telemetry:enrichTelemetry(c,p,a),tools:f}),executeModelCall=async()=>{if(n){let e=await g.stream({messages:o}),{handledInlineToolResultCallIds:r,inlineAuthorizationResults:i,inlineToolResultParts:a}=await emitStreamContent(n,x,e.fullStream),s=await h.stepResult;if(isEmptyModelResponse(s)&&a.length===0&&i.length===0)throw new EmptyModelResponseError;if(await emitStepActions(n,x,s,{excludedActionToolNames:new Set([ASK_QUESTION_TOOL_NAME,CODE_MODE_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME]),handledInlineToolResultCallIds:r,tools:t.tools}),a.length>0||i.length>0){let e=s.toolResults,t=new Map(e.map(e=>[e.toolCallId,e]));for(let e of i)t.set(e.toolCallId,e);return{content:s.content,finishReason:s.finishReason,response:{...s.response,...a.length>0?{messages:[{role:`tool`,content:[...a]},...s.response.messages]}:{}},text:s.text,toolCalls:s.toolCalls,toolResults:[...t.values()],usage:s.usage}}return s}await g.generate({messages:o});let e=await h.stepResult;if(isEmptyModelResponse(e))throw new EmptyModelResponseError;return e};return runModelCallWithRetries(()=>executeModelCall().catch(rethrowNoOutputAsEmptyResponse),{sessionId:b.sessionId,turnId:x.turnId})},B=prepareModelCallInput();n&&await emitStepStarted(n,x,O);let V=await continuePendingCodeModeInterrupt({capabilities:t.capabilities,childResults:S.input?.runtimeActionResults,config:t,emit:n,emissionState:x,messages:O,runStep,session:b});if(V!==null)return V;let H;try{H=await runOneModelCall({preparedInput:B,suppressStepStartedEmission:!0})}catch(r){let a=await runModelCallRecoveryPipeline({error:r,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId}),e=>attemptEmptyResponseRecovery({emptyDeliveryEnabled:F,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId})]});if(a.outcome===`recovered`)H=a.result;else{let r=a.error;if(y&&recordErrorOnSpan(y,r),!n)throw r;let o=extractWorkflowStreamWriteErrorDetails(r);if(o!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...o,errorId:t,error:r,sessionId:b.sessionId,turnId:x.turnId}),x=await emitRecoverableFailedTurn(n,x,{code:`WORKFLOW_STREAM_WRITE_FAILED`,details:{...o,errorId:t},message:toErrorMessage(r)}),{next:null,session:setHarnessEmissionState(b,x)}}let s=classifyModelCallError(r),c=createErrorId(),l=s===`terminal`?summarizeKnownModelCallConfigError(r):null,f=l===null?summarizeKnownModelCallRequestError(r):null,p=l?.message??f?.message??toErrorMessage(r),_=extractModelCallErrorDetails(r),v=buildModelCallFailureDetails({configSummary:l,error:r,errorId:c,modelCallDetails:_,requestSummary:f}),S=buildModelCallFailureLogFields({error:r,errorId:c,modelCallDetails:_,requestSummary:f,sessionId:b.sessionId,turnId:x.turnId});return s===`terminal`?(l===null?log.error(f?.message??`model call failed terminally`,S):log.error(`${l.name}: ${l.message}`,{errorId:c,sessionId:b.sessionId,turnId:x.turnId}),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p,sessionId:b.sessionId}),{next:{done:!0,output:``},session:b}):t.mode===`task`?(log.error(f?.message??`model call failed; failing the task run`,S),await emitFailedStep(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p,sessionId:b.sessionId}),{next:{done:!0,isError:!0,output:p},session:b}):(log.error(f?.message??`model call failed — parking session for retry by the user`,S),x=await emitRecoverableFailedTurn(n,x,{code:`MODEL_CALL_FAILED`,details:v,message:p}),{next:null,session:setHarnessEmissionState(b,x)})}}let U=accumulateTurnUsage({previous:getTurnUsageState(b.state),turnId:x.turnId,usage:H.usage??{}});b=setTurnUsageState(b,U);let W;try{W=formatLanguageModelGatewayId(k)}catch{W=void 0}return await setEveAttributes({"$eve.model":W,"$eve.input_tokens":U.inputTokens,"$eve.output_tokens":U.outputTokens,"$eve.cache_read_tokens":U.cacheReadTokens,"$eve.cache_write_tokens":U.cacheWriteTokens,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:x,promptMessages:O,result:H,runStep,session:b})}return runStep}function buildModelCallFailureDetails(e){let{configSummary:t,error:r,errorId:i,modelCallDetails:a,requestSummary:o}=e;return t===null?o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}:{errorId:i,message:t.message,name:t.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.requestSummary===null?{...t,error:e.error}:{...t,details:e.modelCallDetails}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.toolCalls.length===0&&e.toolResults.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}const EMPTY_RESPONSE_NUDGE=`Your previous reply was empty and was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`;function buildEmptyResponseNudge(e){return e?`${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`:EMPTY_RESPONSE_NUDGE}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:buildEmptyResponseNudge(e.emptyDeliveryEnabled)})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=resolveAssistantStepText(i.response.messages,i.text),l=i.finishReason!==`tool-calls`&&i.toolCalls.length===0&&hasEmptyDeliverySentinel(c),u=l?[]:i.response.messages,d=l?null:c,f={...s,compaction:createNextCompactionConfig(s.compaction,r,i)};if(isSandboxEnabled(t)){let{getCodeModeInterrupt:e}=await loadCodeModeModule(),a=e(i);if(a!==void 0)return parkOnCodeModeInterrupt({baseSession:f,config:t,emit:n,emissionState:o,interrupt:a,promptMessages:r,responseMessages:u})}let p=extractToolApprovalInputRequests({content:i.content??[]}),m=new Set(p.map(e=>e.action.callId)),h=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:m}),g=[...p,...h],_=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:t.tools}));if(_.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:_,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:u,session:{...f,history:[...r]}}),o)};if(g.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:g,responseMessages:u,session:{...f,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:g,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode),e=setHarnessEmissionState(e,o))),{next:null,session:e}}let y=findAuthorizationSignalFromToolResults(i.toolResults);if(y){let{challenges:e}=y;if(n)for(let t of e)await n(createAuthorizationRequiredEvent({authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));return{next:null,session:setHarnessEmissionState({...f,history:[...r],state:setPendingAuthorization(f.state,{challenges:e})},o)}}let b=new Set((d===null?i.toolResults??[]:[]).filter(e=>e.providerExecuted===!0).map(e=>e.toolCallId)),S=[],C=u.map(e=>e.role===`assistant`&&Array.isArray(e.content)?{...e,content:e.content.flatMap(e=>e.type===`tool-result`&&b.has(e.toolCallId)?(S.push(e),[]):[e.type===`tool-call`&&b.has(e.toolCallId)?{...e,providerExecuted:!1}:e])}:e);S.length>0&&C.push({role:`tool`,content:S});let w=[...r,...C],T={...f,history:w};return!(T.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(C.at(-1)?.role===`tool`||hasDeferredStepInput(T))?(n&&(o=advanceStep(o),T=setHarnessEmissionState(T,o)),{next:a,session:T}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T,stepOutput:d}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME)?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i}=e,{emissionState:a,session:o}=e;if(i===void 0)return t&&(a=await emitTurnEpilogue(t,a,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o};let s=extractFinalOutput(r);return s===void 0?(t&&(a=await emitRecoverableFailedTurn(t,a,OUTPUT_SCHEMA_NOT_FULFILLED),o=setHarnessEmissionState(o,a)),{next:null,session:o}):(o=persistStructuredAssistantTurn(o,n,s),t&&(a=await emitStructuredResult(t,a,s,`conversation`),o=setHarnessEmissionState(o,a)),{next:null,session:o})}async function continuePendingCodeModeInterrupt(e){let t=getPendingCodeModeInterrupt(e.session.state);if(t===void 0)return null;let{continueCodeModeApproval:n,continueCodeModeInterrupt:i,getCodeModeApprovalResponse:a,isCodeModeApprovalInterrupt:o,replaceCodeModeInterruptResult:s,unwrapCodeModeResult:c}=await loadCodeModeModule(),l=t.interrupt,u=o(l)?a([...e.messages],l):void 0;if(o(l)&&u===void 0)return{next:null,session:e.session};let d=createEveCodeModeOptions({lifecycle:e.emit===void 0?void 0:createCodeModeLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools})}),f;try{let t=await buildSandboxHostTools({approvedTools:getApprovedTools(e.session),capabilities:e.capabilities,tools:e.config.tools});if(o(l)&&u!==void 0)f=await n({approvalResponse:u,interrupt:l,options:d,tools:t});else if(isCodeModeConnectionAuthInterrupt(l))f=await i({interrupt:l,resolution:{status:`authorized`},tools:t,options:d});else if(isCodeModeRuntimeActionInterrupt(l)){let n=e.childResults??[],r=l,a=0;for(;;){f=await i({interrupt:r,resolution:n[a]?.output,tools:t,options:d});let e=c(f);if(e.status!==`interrupted`||!isCodeModeRuntimeActionInterrupt(e.interrupt)||a+1>=n.length)break;a++,r=e.interrupt}}else throw Error(`Unsupported code-mode interrupt kind "${l.payload.kind}".`)}catch(e){logError(log,`code-mode interrupt continuation failed`,e),f={error:`code_mode_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let p=c(f),m=p.status===`interrupted`?p.interrupt:p.output,h=[...e.session.history,...t.responseMessages],_=isCodeModeRuntimeActionInterrupt(l)?replaceCodeModeToolResult(h,l.outerToolCallId,m):s(h,l,m),v=clearPendingCodeModeInterrupt({...e.session,history:_});if(p.status===`interrupted`){let t=e.session.history.length,n=_.slice(0,t),r=_.slice(t);return v={...v,history:n},parkOnCodeModeInterrupt({baseSession:v,config:e.config,emit:e.emit,emissionState:e.emissionState,interrupt:p.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:v}}function replaceCodeModeToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}async function parkOnCodeModeInterrupt(e){let{isCodeModeApprovalInterrupt:t,toCodeModeApprovalMessages:n}=await loadCodeModeModule(),r=e.interrupt,i={...e.baseSession,history:[...e.promptMessages]};if(isCodeModeConnectionAuthInterrupt(r)){let t=[...r.payload.challenges??[]];if(e.emit)for(let n of t)await e.emit(createAuthorizationRequiredEvent({authorization:n.challenge,name:n.name,description:n.challenge.instructions??`Authorization required for ${n.name}`,webhookUrl:n.hookUrl,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId}));return{next:null,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:{...i,state:setPendingAuthorization(i.state,{challenges:t})}})}}if(t(r)){let t=n(r),a=extractToolApprovalInputRequests({content:extractAssistantContent(t)}),o=setPendingInputBatch({event:{sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId},requests:a,responseMessages:t,session:setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i})});if(e.emit&&(await e.emit(createInputRequestedEvent({requests:a,sequence:e.emissionState.sequence,stepIndex:e.emissionState.stepIndex,turnId:e.emissionState.turnId})),e.config.mode===`conversation`)){let t=await emitTurnEpilogue(e.emit,e.emissionState,e.config.mode);o=setHarnessEmissionState(o,t)}return{next:null,session:o}}return{next:null,session:setHarnessEmissionState(setPendingCodeModeInterrupt({interrupt:r,responseMessages:e.responseMessages,session:i}),e.emissionState)}}function extractAssistantContent(e){let t=[];for(let n of e)n.role===`assistant`&&Array.isArray(n.content)&&t.push(...n.content);return t}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t.length),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session;if(!shouldCompact(r,i.compaction))return{messages:r,session:i};let a=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:i.agent.modelReference,resolveModel:e.resolveModel});if(t&&await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(r,i.compaction)})),r=await compactMessages(r,a.model,i.compaction,a.providerOptions,e.telemetry,e.headers),e.onCompaction)for(let t of e.onCompaction())r.push(t);return t&&await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(a.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId})),{messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t){for(let n=1;;n++)try{return await e()}catch(e){if(n===3||classifyModelCallError(e)!==`retry`)throw e;let r=500*2**(n-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:n,delayMs:r,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,r))}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{createToolLoopHarness};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
type ToolOutputSerializationBoundary = "action.result" | "execute" | "toModelOutput";
|
|
2
|
+
export declare class ToolOutputSerializationError extends TypeError {
|
|
3
|
+
readonly toolCallId: string | undefined;
|
|
4
|
+
readonly toolName: string;
|
|
5
|
+
constructor(input: {
|
|
6
|
+
readonly boundary: ToolOutputSerializationBoundary;
|
|
7
|
+
readonly cause?: unknown;
|
|
8
|
+
readonly toolCallId?: string;
|
|
9
|
+
readonly toolName: string;
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
export declare function withToolOutputSerializationError<T>(input: {
|
|
13
|
+
readonly boundary: ToolOutputSerializationBoundary;
|
|
14
|
+
readonly toolCallId?: string;
|
|
15
|
+
readonly toolName: string;
|
|
16
|
+
}, fn: () => T): T;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var ToolOutputSerializationError=class extends TypeError{toolCallId;toolName;constructor(e){super(formatToolOutputSerializationMessage(e)),this.name=`ToolOutputSerializationError`,this.toolCallId=e.toolCallId,this.toolName=e.toolName,e.cause!==void 0&&(this.cause=e.cause)}};function formatToolOutputSerializationMessage(e){return`${e.toolCallId===void 0?`Tool "${e.toolName}"`:`Tool "${e.toolName}" call "${e.toolCallId}"`} ${e.boundary===`execute`?`returned a non-JSON-serializable result`:e.boundary===`toModelOutput`?`returned a non-JSON-serializable model output`:`produced a non-JSON-serializable action result`}.${e.cause instanceof Error&&e.cause.message.length>0?` ${e.cause.message}`:``}`}function withToolOutputSerializationError(e,t){try{return t()}catch(t){throw t instanceof ToolOutputSerializationError?t:new ToolOutputSerializationError({boundary:e.boundary,cause:t,toolCallId:e.toolCallId,toolName:e.toolName})}}export{ToolOutputSerializationError,withToolOutputSerializationError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{loadContext}from"#context/container.js";import{tool}from"ai";import{authorizationPendingModelText,isAuthorizationPendingModelOutput,isAuthorizationSignal,modelFacingAuthorizationOutput}from"#harness/authorization.js";import{isCodeModeToolExecutionOptions}from"#runtime/framework-tools/code-mode-connection-auth.js";import{stashToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{WEB_SEARCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-search.js";import{resolveWebSearchBackend,resolveWebSearchProviderTool}from"#harness/provider-tools.js";function buildToolSet(e){let t={},
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{parseJsonValue}from"#shared/json.js";import{loadContext}from"#context/container.js";import{tool}from"ai";import{authorizationPendingModelText,isAuthorizationPendingModelOutput,isAuthorizationSignal,modelFacingAuthorizationOutput}from"#harness/authorization.js";import{withToolOutputSerializationError}from"#harness/tool-output-serialization.js";import{isCodeModeToolExecutionOptions}from"#runtime/framework-tools/code-mode-connection-auth.js";import{stashToolInterrupt}from"#harness/tool-interrupts.js";import{ASK_QUESTION_TOOL_NAME}from"#runtime/framework-tools/ask-question.js";import{WEB_SEARCH_TOOL_DEFINITION}from"#runtime/framework-tools/web-search.js";import{resolveWebSearchBackend,resolveWebSearchProviderTool}from"#harness/provider-tools.js";function buildToolSet(e){let t={},n=e.capabilities?.requestInput===!0,o=e.disabledProviderTools;for(let s of e.tools.values()){if(s.name===ASK_QUESTION_TOOL_NAME&&!n||o?.has(s.name))continue;let c=s.toModelOutput;t[s.name]=tool({description:s.description,execute:wrapToolExecute(s),inputSchema:s.inputSchema,needsApproval:buildNeedsApprovalFn(s,e),outputSchema:s.outputSchema,...s.execute===void 0?c===void 0?{}:{toModelOutput:async({output:e,toolCallId:t})=>normalizeToolModelOutput({output:await c(e),toolCallId:t,toolName:s.name})}:{toModelOutput:async({output:e,toolCallId:t})=>isAuthorizationPendingModelOutput(e)?{type:`text`,value:authorizationPendingModelText(e.connections)}:c===void 0?typeof e==`string`?{type:`text`,value:e}:normalizeToolModelOutput({output:{type:`json`,value:e??null},toolCallId:t,toolName:s.name}):normalizeToolModelOutput({output:await c(e),toolCallId:t,toolName:s.name})}})}return t}function buildToolSetFromDefinitions(e){let t=new Map;for(let n of e.tools)t.has(n.name)||t.set(n.name,n);return buildToolSet({approvedTools:e.approvedTools,capabilities:e.capabilities,disabledProviderTools:e.disabledProviderTools,tools:t})}function wrapToolExecute(e){let t=e.execute;if(t!==void 0)return async(r,i)=>{let a=await t(r);return isAuthorizationSignal(a)?isCodeModeToolExecutionOptions(i)?a:(stashToolInterrupt(loadContext(),i.toolCallId,a),modelFacingAuthorizationOutput(a)):normalizeToolJsonOutput({boundary:`execute`,output:a,toolCallId:i.toolCallId,toolName:e.name})}}function normalizeToolJsonOutput(e){let n=e.output===void 0?null:e.output;return withToolOutputSerializationError(e,()=>(parseJsonValue(n),n))}function normalizeToolModelOutput(e){return withToolOutputSerializationError({boundary:`toModelOutput`,toolCallId:e.toolCallId,toolName:e.toolName},()=>{if(e.output===null||typeof e.output!=`object`)throw TypeError(`Expected a tool model output object.`);let t=e.output;if(t.type===`text`){if(typeof t.value!=`string`)throw TypeError(`Expected text model output to include a string "value".`);return{type:`text`,value:t.value}}if(t.type===`json`)return{type:`json`,value:normalizeToolJsonOutput({boundary:`toModelOutput`,output:t.value,toolCallId:e.toolCallId,toolName:e.toolName})};throw TypeError(`Expected tool model output type to be "text" or "json".`)})}async function buildToolSetWithProviderTools(e){let t=e.disabledProviderTools,n={...buildToolSet({approvedTools:e.approvedTools,capabilities:e.capabilities,disabledProviderTools:t,tools:e.tools})};if(!t?.has(WEB_SEARCH_TOOL_DEFINITION.name)){let t=e.tools.get(WEB_SEARCH_TOOL_DEFINITION.name);if(t!==void 0&&t.execute===void 0){let t=resolveWebSearchBackend(e.modelReference);t===null?delete n[WEB_SEARCH_TOOL_DEFINITION.name]:n[WEB_SEARCH_TOOL_DEFINITION.name]=await resolveWebSearchProviderTool(t)}}return n}function buildNeedsApprovalFn(t,n){return async r=>{if(t.needsApproval===void 0)return!1;let i=isObject(r)?r:void 0;return t.needsApproval({approvedTools:n.approvedTools??new Set,toolInput:i,toolName:t.name})}}export{buildToolSet,buildToolSetFromDefinitions,buildToolSetWithProviderTools,wrapToolExecute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.13.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.13.5`,WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -2,12 +2,16 @@ export declare class RetryableError extends Error {
|
|
|
2
2
|
}
|
|
3
3
|
export declare class FatalError extends Error {
|
|
4
4
|
}
|
|
5
|
+
interface WorkflowHook<T> extends AsyncIterable<T> {
|
|
6
|
+
readonly token: string;
|
|
7
|
+
getConflict(): Promise<{
|
|
8
|
+
readonly runId: string;
|
|
9
|
+
} | null>;
|
|
10
|
+
}
|
|
5
11
|
/**
|
|
6
12
|
* Creates a Workflow hook from inside a durable workflow body.
|
|
7
13
|
*/
|
|
8
|
-
export declare function createHook<T = unknown>(options?: unknown):
|
|
9
|
-
readonly token: string;
|
|
10
|
-
};
|
|
14
|
+
export declare function createHook<T = unknown>(options?: unknown): WorkflowHook<T>;
|
|
11
15
|
/**
|
|
12
16
|
* Returns metadata for the current durable workflow body.
|
|
13
17
|
*/
|
|
@@ -21,17 +25,14 @@ export declare function getWritable<T = unknown>(options?: {
|
|
|
21
25
|
/**
|
|
22
26
|
* Creates a Workflow webhook from inside a durable workflow body.
|
|
23
27
|
*/
|
|
24
|
-
export declare function createWebhook<T = unknown>(options?: unknown):
|
|
25
|
-
readonly token: string;
|
|
28
|
+
export declare function createWebhook<T = unknown>(options?: unknown): WorkflowHook<T> & {
|
|
26
29
|
url?: string;
|
|
27
30
|
};
|
|
28
31
|
/**
|
|
29
32
|
* Defines a Workflow hook factory for workflow-body code.
|
|
30
33
|
*/
|
|
31
34
|
export declare function defineHook<T = unknown>(): {
|
|
32
|
-
readonly create: (options?: unknown) =>
|
|
33
|
-
readonly token: string;
|
|
34
|
-
};
|
|
35
|
+
readonly create: (options?: unknown) => WorkflowHook<T>;
|
|
35
36
|
readonly resume: () => never;
|
|
36
37
|
};
|
|
37
38
|
/**
|
|
@@ -80,3 +81,4 @@ export interface ExperimentalSetAttributesOptions {
|
|
|
80
81
|
* bundle.
|
|
81
82
|
*/
|
|
82
83
|
export declare function experimental_setAttributes(attrs: Record<string, string | undefined>, options?: ExperimentalSetAttributesOptions): Promise<void>;
|
|
84
|
+
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{buildSlackAuthContext}from"#public/channels/slack/auth.js";import{buildAuthCompletedText,buildAuthEphemeralBlocks,buildAuthRequiredPublicText,formatConnectionDisplayName}from"#public/channels/slack/connections.js";import{renderInputRequestBlocks}from"#public/channels/slack/hitl.js";import{truncateMessageText,truncateTypingStatus}from"#public/channels/slack/limits.js";const log=createLogger(`slack.defaults`);function defaultSlackAuth(e,t){let n=e.author;return n?buildSlackAuthContext({channelId:t.slack.channelId,fullName:n.fullName,isBot:n.isBot,teamId:e.teamId,threadTs:t.slack.threadTs,userId:n.userId,userName:n.userName}):null}async function defaultOnAppMention(e,t){return await e.thread.startTyping(`Thinking...`),{auth:defaultSlackAuth(t,e)}}async function defaultOnDirectMessage(e,t){return await e.thread.startTyping(`Thinking...`),{auth:defaultSlackAuth(t,e)}}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}function defaultInputRequestedHandler(){return async(e,t,n)=>{if(e.requests.length===0)return;let r=truncateMessageText(e.requests.map(e=>e.prompt).join(`
|
|
2
|
-
`));await t.thread.post({blocks:e.requests.flatMap(renderInputRequestBlocks),text:r})}}const defaultEvents={async"turn.started"(e,t,n){t.state.pendingToolCallMessage=null,t.state.lastReasoningTypingAtMs=null,t.state.lastReasoningTypingStatus=null,await t.thread.startTyping(`Working...`)},async"reasoning.appended"(e,t,n){let r=firstNonEmptyLine(e.reasoningSoFar);if(r===void 0)return;let i=truncateTypingStatus(r),a=t.state.lastReasoningTypingStatus,o=a!=null&&i.startsWith(a)&&i.length>=a.length+4,s=Date.now(),c=t.state.lastReasoningTypingAtMs;if(!o&&c!=null){let e=s-c;if(e>=0&&e<5e3)return}await t.thread.startTyping(i),t.state.lastReasoningTypingAtMs=s,t.state.lastReasoningTypingStatus=i},async"actions.requested"(e,t,n){let r=t.state.pendingToolCallMessage;if(t.state.pendingToolCallMessage=null,r){await t.thread.startTyping(truncateTypingStatus(r));return}let i=e.actions.map(e=>e.kind===`tool-call`?e.toolName:e.kind);await t.thread.startTyping(truncateTypingStatus(`Running ${i.join(`, `)}...`))},async"message.completed"(e,t,n){if(e.finishReason===`tool-calls`){t.state.pendingToolCallMessage=e.message?firstNonEmptyLine(e.message)??null:null;return}t.state.pendingToolCallMessage=null
|
|
2
|
+
`));await t.thread.post({blocks:e.requests.flatMap(renderInputRequestBlocks),text:r})}}const defaultEvents={async"turn.started"(e,t,n){t.state.pendingToolCallMessage=null,t.state.lastReasoningTypingAtMs=null,t.state.lastReasoningTypingStatus=null,await t.thread.startTyping(`Working...`)},async"reasoning.appended"(e,t,n){let r=firstNonEmptyLine(e.reasoningSoFar);if(r===void 0)return;let i=truncateTypingStatus(r),a=t.state.lastReasoningTypingStatus,o=a!=null&&i.startsWith(a)&&i.length>=a.length+4,s=Date.now(),c=t.state.lastReasoningTypingAtMs;if(!o&&c!=null){let e=s-c;if(e>=0&&e<5e3)return}await t.thread.startTyping(i),t.state.lastReasoningTypingAtMs=s,t.state.lastReasoningTypingStatus=i},async"actions.requested"(e,t,n){let r=t.state.pendingToolCallMessage;if(t.state.pendingToolCallMessage=null,r){await t.thread.startTyping(truncateTypingStatus(r));return}let i=e.actions.map(e=>e.kind===`tool-call`?e.toolName:e.kind);await t.thread.startTyping(truncateTypingStatus(`Running ${i.join(`, `)}...`))},async"message.completed"(e,t,n){if(e.finishReason===`tool-calls`){t.state.pendingToolCallMessage=e.message?firstNonEmptyLine(e.message)??null:null;return}if(t.state.pendingToolCallMessage=null,!e.message){await t.thread.startTyping();return}await t.thread.post(e.message)},async"turn.failed"(e,r,i){let a=formatErrorHint(e),o=extractErrorId(e.details);await r.thread.post([`I hit an error while handling your request${a}.`,``,`Please try again, rephrase, or reach out if it keeps failing.`,...o?[``,`_Error id: \`${o}\`_`]:[]].join(`
|
|
3
3
|
`))},async"session.failed"(e,r){let i=formatErrorHint(e),a=extractErrorId(e.details);await r.thread.post([`This session couldn't recover from an error${i}.`,``,`Start a new thread to continue — I can't pick this one back up.`,...a?[``,`_Error id: \`${a}\`_`]:[]].join(`
|
|
4
4
|
`))},async"authorization.required"(e,t,n){let r=e.authorization?.displayName??formatConnectionDisplayName(e.name),i=t.state.triggeringUserId??null,c=e.authorization?.url,l=t.state.pendingAuthMessageTs??{};if(l[e.name]===void 0){let n=buildAuthRequiredPublicText({displayName:r,hasUser:i!==null});try{let r=await t.thread.post(n);r.id&&(t.state.pendingAuthMessageTs={...l,[e.name]:r.id})}catch(t){log.error(`Slack auth public message delivery failed`,{name:e.name,error:t})}}if(i&&c){let n=e.authorization?.userCode;try{await t.thread.postEphemeral(i,{blocks:buildAuthEphemeralBlocks({displayName:r,url:c,userCode:n}),text:n?`Sign in with ${r}: ${c} (code: ${n})`:`Sign in with ${r}: ${c}`})}catch(t){log.error(`Slack auth ephemeral delivery failed`,{name:e.name,error:t})}}},async"authorization.completed"(e,t,n){let r=t.state.pendingAuthMessageTs??{},a=r[e.name];if(a===void 0)return;let o=buildAuthCompletedText({displayName:e.authorization?.displayName??formatConnectionDisplayName(e.name),outcome:e.outcome,reason:e.reason});try{await t.slack.request(`chat.update`,{channel:t.slack.channelId,ts:a,text:o})}catch(t){log.error(`Slack auth status edit failed`,{name:e.name,error:t})}let c={...r};delete c[e.name],t.state.pendingAuthMessageTs=c}};export{defaultEvents,defaultInputRequestedHandler,defaultOnAppMention,defaultOnDirectMessage,defaultSlackAuth};
|
|
@@ -13,9 +13,9 @@ export declare const WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA: JsonObject;
|
|
|
13
13
|
*/
|
|
14
14
|
export declare const WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA: JsonObject;
|
|
15
15
|
/**
|
|
16
|
-
* Output schema for AI Gateway's provider-managed `
|
|
16
|
+
* Output schema for AI Gateway's provider-managed `parallelSearch` tool.
|
|
17
17
|
*/
|
|
18
|
-
export declare const
|
|
18
|
+
export declare const WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA: JsonObject;
|
|
19
19
|
/**
|
|
20
20
|
* Framework-provided web search tool definition.
|
|
21
21
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const WEB_SEARCH_OPENAI_OUTPUT_SCHEMA={$schema:`http://json-schema.org/draft-07/schema#`,additionalProperties:!1,properties:{action:{oneOf:[{additionalProperties:!1,properties:{queries:{items:{type:`string`},type:`array`},query:{type:`string`},type:{const:`search`,type:`string`}},required:[`type`],type:`object`},{additionalProperties:!1,properties:{type:{const:`openPage`,type:`string`},url:{anyOf:[{type:`string`},{type:`null`}]}},required:[`type`],type:`object`},{additionalProperties:!1,properties:{pattern:{anyOf:[{type:`string`},{type:`null`}]},type:{const:`findInPage`,type:`string`},url:{anyOf:[{type:`string`},{type:`null`}]}},required:[`type`],type:`object`}]},sources:{items:{oneOf:[{additionalProperties:!1,properties:{type:{const:`url`,type:`string`},url:{type:`string`}},required:[`type`,`url`],type:`object`},{additionalProperties:!1,properties:{name:{type:`string`},type:{const:`api`,type:`string`}},required:[`type`,`name`],type:`object`}]},type:`array`}},type:`object`},WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA={$schema:`http://json-schema.org/draft-07/schema#`,items:{additionalProperties:!1,properties:{encryptedContent:{type:`string`},pageAge:{anyOf:[{type:`string`},{type:`null`}]},title:{anyOf:[{type:`string`},{type:`null`}]},type:{const:`web_search_result`,type:`string`},url:{type:`string`}},required:[`url`,`title`,`pageAge`,`encryptedContent`,`type`],type:`object`},type:`array`},WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA={$schema:`http://json-schema.org/draft-07/schema#`,additionalProperties:!1,properties:{},type:`object`},
|
|
1
|
+
const WEB_SEARCH_OPENAI_OUTPUT_SCHEMA={$schema:`http://json-schema.org/draft-07/schema#`,additionalProperties:!1,properties:{action:{oneOf:[{additionalProperties:!1,properties:{queries:{items:{type:`string`},type:`array`},query:{type:`string`},type:{const:`search`,type:`string`}},required:[`type`],type:`object`},{additionalProperties:!1,properties:{type:{const:`openPage`,type:`string`},url:{anyOf:[{type:`string`},{type:`null`}]}},required:[`type`],type:`object`},{additionalProperties:!1,properties:{pattern:{anyOf:[{type:`string`},{type:`null`}]},type:{const:`findInPage`,type:`string`},url:{anyOf:[{type:`string`},{type:`null`}]}},required:[`type`],type:`object`}]},sources:{items:{oneOf:[{additionalProperties:!1,properties:{type:{const:`url`,type:`string`},url:{type:`string`}},required:[`type`,`url`],type:`object`},{additionalProperties:!1,properties:{name:{type:`string`},type:{const:`api`,type:`string`}},required:[`type`,`name`],type:`object`}]},type:`array`}},type:`object`},WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA={$schema:`http://json-schema.org/draft-07/schema#`,items:{additionalProperties:!1,properties:{encryptedContent:{type:`string`},pageAge:{anyOf:[{type:`string`},{type:`null`}]},title:{anyOf:[{type:`string`},{type:`null`}]},type:{const:`web_search_result`,type:`string`},url:{type:`string`}},required:[`url`,`title`,`pageAge`,`encryptedContent`,`type`],type:`object`},type:`array`},WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA={$schema:`http://json-schema.org/draft-07/schema#`,additionalProperties:!1,properties:{},type:`object`},WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA={$schema:`http://json-schema.org/draft-07/schema#`,anyOf:[{additionalProperties:!1,properties:{results:{items:{additionalProperties:!1,properties:{excerpt:{type:`string`},publishDate:{anyOf:[{type:`string`},{type:`null`}]},relevanceScore:{type:`number`},title:{type:`string`},url:{type:`string`}},required:[`url`,`title`,`excerpt`],type:`object`},type:`array`},searchId:{type:`string`}},required:[`searchId`,`results`],type:`object`},{additionalProperties:!1,properties:{error:{enum:[`api_error`,`rate_limit`,`timeout`,`invalid_input`,`configuration_error`,`unknown`],type:`string`},message:{type:`string`},statusCode:{type:`number`}},required:[`error`,`message`],type:`object`}]},WEB_SEARCH_TOOL_DEFINITION={description:`Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.`,inputSchema:null,logicalPath:`eve:framework/web-search`,name:`web_search`,sourceId:`eve:web-search-tool`,sourceKind:`module`};export{WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA,WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA,WEB_SEARCH_OPENAI_OUTPUT_SCHEMA,WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA,WEB_SEARCH_TOOL_DEFINITION};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`7.0.0-beta.178`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.13.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{pathExists,writeTextFile}from"../files.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{basename,join,resolve}from"node:path";import{mkdir,readdir,stat}from"node:fs/promises";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),DEFAULT_AI_PACKAGE_VERSION=`7.0.0-beta.178`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.2.2`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.13.5`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
|
|
2
2
|
|
|
3
3
|
export default defineAgent({
|
|
4
4
|
model: "__EVE_INIT_MODEL__",
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare const EMPTY_DELIVERY_SENTINEL = "<eve-empty-delivery/>";
|
|
2
|
+
export declare const CONDITIONAL_DELIVERY_INSTRUCTION = "Conditional delivery\nOnly when the current task explicitly makes delivery conditional and there is nothing to report, reply with exactly <eve-empty-delivery/> and no other text. Do not use this marker for ordinary conversations, after input or approval responses, or merely because you have no additional commentary. Never return an empty response; use the marker to intentionally deliver nothing.";
|
|
3
|
+
export declare function hasEmptyDeliverySentinel(text: string | null | undefined): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const EMPTY_DELIVERY_SENTINEL=`<eve-empty-delivery/>`,CONDITIONAL_DELIVERY_INSTRUCTION=`Conditional delivery\nOnly when the current task explicitly makes delivery conditional and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL} and no other text. Do not use this marker for ordinary conversations, after input or approval responses, or merely because you have no additional commentary. Never return an empty response; use the marker to intentionally deliver nothing.`;function hasEmptyDeliverySentinel(e){return e?.includes(`<eve-empty-delivery/>`)??!1}export{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel};
|
package/dist/src/svelte/index.js
CHANGED
package/dist/src/vue/index.js
CHANGED
package/docs/channels/custom.mdx
CHANGED
|
@@ -225,7 +225,7 @@ defineChannel<{ ref: string | null }>({
|
|
|
225
225
|
});
|
|
226
226
|
```
|
|
227
227
|
|
|
228
|
-
|
|
228
|
+
At the next workflow boundary, the runtime claims the new park hook before releasing the old token. If another active session already owns the new token, the re-keying session fails instead of taking it over. After a successful re-key, inbound deliveries still addressed to the old token are dropped, so coordinate with your senders to use the new token.
|
|
229
229
|
|
|
230
230
|
## File uploads
|
|
231
231
|
|
package/docs/channels/eve.mdx
CHANGED
|
@@ -39,7 +39,7 @@ Stream that session's events as newline-delimited JSON (`application/x-ndjson; c
|
|
|
39
39
|
```bash
|
|
40
40
|
curl -N https://<deployment>/eve/v1/session/ses_01h.../stream
|
|
41
41
|
# {"type":"turn.started",...}
|
|
42
|
-
# {"type":"
|
|
42
|
+
# {"type":"message.appended","data":{"messageDelta":"It is ",...}}
|
|
43
43
|
# {"type":"message.completed",...}
|
|
44
44
|
```
|
|
45
45
|
|
|
@@ -54,6 +54,8 @@ Some work has to wait, including a human approving a [tool](../tools), an intera
|
|
|
54
54
|
|
|
55
55
|
eve does not maintain a durable FIFO queue of user messages for a session. The `continuationToken` is a resume handle for the session's current workflow hook, not a general message-queue address.
|
|
56
56
|
|
|
57
|
+
Only one active session can own a continuation token. When a session starts with a token, eve commits the park hook before processing its first turn and fails a competing session if another run already owns that token. A tokenless session claims its token after the first turn establishes one. Competing input is not forwarded to the owner.
|
|
58
|
+
|
|
57
59
|
When a session is waiting, a delivery to the current continuation token wakes the session and starts the next turn. When a turn is already active, the hook may accept additional deliveries, but the runtime only drains them at specific workflow boundaries. If more than one delivery is ready when the driver checks, eve may fold them into the next turn; that drain is best-effort and depends on workflow and transport timing.
|
|
58
60
|
|
|
59
61
|
So don't rely on concurrent sends to the same session behaving like a typical ordered chat queue. For deterministic behavior, send one user turn at a time and wait for `session.waiting` before sending the next message to the same session. If your channel can receive bursts while the agent is working, keep your own per-session queue in the channel or app layer, then deliver the next message after the session parks again. Separate sessions still run independently.
|
|
@@ -35,6 +35,8 @@ interface SessionState {
|
|
|
35
35
|
|
|
36
36
|
The continuation token resumes the conversation. The session ID and stream index let the client reconnect to the right stream position without replaying events it already consumed.
|
|
37
37
|
|
|
38
|
+
`SessionState` is a cursor, not a chat transcript. If your app shows historical messages, persist the stream events separately and store them under your own chat or thread ID. On reload, pass the saved `SessionState` back to `client.session(savedState)` or `useEveAgent({ initialSession })`, and pass the saved events to your renderer or `useEveAgent({ initialEvents })`.
|
|
39
|
+
|
|
38
40
|
## Resume a saved session
|
|
39
41
|
|
|
40
42
|
Pass the saved state back into `client.session()`:
|
|
@@ -97,6 +99,8 @@ await save("support", support.state);
|
|
|
97
99
|
|
|
98
100
|
The shared `Client` only owns host, auth, headers, and reconnect settings. Conversation state lives on each `ClientSession`.
|
|
99
101
|
|
|
102
|
+
For a multi-chat UI, this usually means one application row per chat with two eve fields: the latest `SessionState` and the ordered event log for rendering. Do not reuse one `ClientSession` across sidebar conversations, and do not treat `streamIndex` as your database row index; it is only the remote stream cursor for that eve session.
|
|
103
|
+
|
|
100
104
|
## Reconnect an existing stream
|
|
101
105
|
|
|
102
106
|
When a session already has a `sessionId`, `session.stream()` reattaches to its stream from the saved cursor. Resuming a saved `SessionState` after a restart is the common reason to do this:
|
|
@@ -76,6 +76,12 @@ The most common UI events are:
|
|
|
76
76
|
|
|
77
77
|
For the complete event table, see [Sessions, runs & streaming](../../concepts/sessions-runs-and-streaming).
|
|
78
78
|
|
|
79
|
+
## Authorization pauses
|
|
80
|
+
|
|
81
|
+
`authorization.required` is different from the normal `session.waiting` boundary. It means a connection needs OAuth or another authorization challenge before the parked turn can continue. Chat UIs should render the authorization prompt, disable ordinary text input for that session, and persist the event with the rest of the chat history.
|
|
82
|
+
|
|
83
|
+
If you support refresh while an authorization prompt is pending, keep the session cursor from the started session and rehydrate the saved events on load. Do not treat a missing `session.waiting` after `authorization.required` as a finished conversation; the callback or a structured decline should resume the same eve session.
|
|
84
|
+
|
|
79
85
|
## Reconnection
|
|
80
86
|
|
|
81
87
|
The client reconnects after transient stream disconnects. It resumes from the number of events already consumed in the current session:
|
|
@@ -186,23 +186,43 @@ const agent = useEveAgent({ reducer: toolCounter });
|
|
|
186
186
|
|
|
187
187
|
## Resumable sessions
|
|
188
188
|
|
|
189
|
-
The browser conversation lives durably on the server. Persist the `session` cursor to pick it back up after a reload:
|
|
189
|
+
The browser conversation lives durably on the server. Persist both the rendered event log and the `session` cursor to pick it back up after a reload:
|
|
190
190
|
|
|
191
191
|
```tsx
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
192
|
+
import type { HandleMessageStreamEvent, SessionState } from "eve/client";
|
|
193
|
+
|
|
194
|
+
type SavedEveChat = {
|
|
195
|
+
events?: readonly HandleMessageStreamEvent[];
|
|
196
|
+
session?: SessionState;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const [saved] = useState<SavedEveChat>(() => {
|
|
200
|
+
const raw = localStorage.getItem("eve-chat");
|
|
201
|
+
return raw ? JSON.parse(raw) : {};
|
|
195
202
|
});
|
|
196
203
|
|
|
197
204
|
const agent = useEveAgent({
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
205
|
+
initialEvents: saved.events ?? [],
|
|
206
|
+
initialSession: saved.session,
|
|
207
|
+
onFinish(snapshot) {
|
|
208
|
+
localStorage.setItem(
|
|
209
|
+
"eve-chat",
|
|
210
|
+
JSON.stringify({
|
|
211
|
+
events: snapshot.events,
|
|
212
|
+
session: snapshot.session,
|
|
213
|
+
}),
|
|
214
|
+
);
|
|
201
215
|
},
|
|
202
216
|
});
|
|
203
217
|
```
|
|
204
218
|
|
|
205
|
-
Store the full `session` object (`sessionId`, `continuationToken`, `streamIndex`), not a single field.
|
|
219
|
+
Store the full `session` object (`sessionId`, `continuationToken`, `streamIndex`), not a single field. The session cursor lets eve continue the durable conversation; the event log lets your UI render historical messages without replaying the whole stream. A database-backed chat app should usually persist stream events as they arrive with `onEvent` and then save a final snapshot in `onFinish`.
|
|
220
|
+
|
|
221
|
+
For multiple chat threads, keep one saved event log and session cursor per thread. `host`, `reducer`, `session`, `initialEvents`, `initialSession`, `auth`, `headers`, `maxReconnectAttempts`, and `optimistic` are read when the hook creates its store, so remount the chat component when switching threads, for example with `key={chat.id}`.
|
|
222
|
+
|
|
223
|
+
If the user can refresh or navigate immediately after pressing send, create your app-level chat row and store the pending user message before calling `send()`. After the request starts, persist the session state as soon as it contains a `sessionId`, then reconnect an interrupted in-flight turn with `session.stream({ startIndex: savedEvents.length })` from the lower-level client.
|
|
224
|
+
|
|
225
|
+
Connection authorization prompts need one extra bit of UI state. eve emits `authorization.required` when a tool needs OAuth or another connection grant. Treat that as a parked chat turn for rendering and persistence: show the authorization prompt, disable ordinary text input for that thread, and keep the session cursor so the callback or a structured decline can continue the same session.
|
|
206
226
|
|
|
207
227
|
## Custom hosts and headers
|
|
208
228
|
|
package/docs/schedules.mdx
CHANGED
|
@@ -58,17 +58,17 @@ Sweep stale workflow state.
|
|
|
58
58
|
|
|
59
59
|
Use a handler when the schedule needs to deliver to a channel, branch on conditions, or compute its arguments at fire time. The handler is in full control. It has no channel of its own, so it passes the work to one with `receive`.
|
|
60
60
|
|
|
61
|
-
```ts title="agent/schedules/
|
|
61
|
+
```ts title="agent/schedules/critical-alerts.ts"
|
|
62
62
|
import { defineSchedule } from "eve/schedules";
|
|
63
63
|
|
|
64
64
|
import slack from "../channels/slack.js";
|
|
65
65
|
|
|
66
66
|
export default defineSchedule({
|
|
67
|
-
cron: "
|
|
67
|
+
cron: "* * * * *",
|
|
68
68
|
async run({ receive, waitUntil, appAuth }) {
|
|
69
69
|
waitUntil(
|
|
70
70
|
receive(slack, {
|
|
71
|
-
message: "
|
|
71
|
+
message: "Check for new critical alerts. Report only when there are any.",
|
|
72
72
|
target: { channelId: "C0123ABC" },
|
|
73
73
|
auth: appAuth,
|
|
74
74
|
}),
|
|
@@ -77,6 +77,8 @@ export default defineSchedule({
|
|
|
77
77
|
});
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
+
The agent does not have to deliver a message on every run. When a prompt makes delivery conditional, as in the alert check above, eve tells the agent how to finish successfully without sending anything to the channel. Frequent polling schedules do not need a separate filter or delivery setting.
|
|
81
|
+
|
|
80
82
|
- `receive(channel, { message, target, auth })`: starts a session on another channel. Same contract as a route handler's `args.receive`.
|
|
81
83
|
- `waitUntil(promise)`: extends the cron task's lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `receive` call in it.
|
|
82
84
|
- `appAuth`: the app principal (`{ authenticator: "app", principalId: "eve:app", principalType: "runtime" }`). Pass it as `receive(..., { auth: appAuth })` for work the agent does on its own behalf.
|
package/docs/tools/overview.mdx
CHANGED
|
@@ -77,6 +77,8 @@ toModelOutput(output) {
|
|
|
77
77
|
|
|
78
78
|
`toModelOutput` receives the full, typed `execute` return and only affects the model. Channel event handlers and hooks still get the full output on `action.result`, so a channel can render rich platform output (Slack Block Kit, say) the model never sees. Return `{ type: "text", value }` for a summary, or `{ type: "json", value }` for a smaller object.
|
|
79
79
|
|
|
80
|
+
Tool outputs must be JSON-serializable. Return plain objects, arrays, strings, numbers, booleans, or `null`; convert values like `Date`, `Map`, `Set`, `NaN`, and cyclic objects before returning them from `execute` or from a `{ type: "json" }` `toModelOutput`.
|
|
81
|
+
|
|
80
82
|
Do not return secrets, credentials, unnecessary personal data, or unbounded sensitive content from tools. Filter, minimize, and redact tool outputs before returning them.
|
|
81
83
|
|
|
82
84
|
## What to read next
|