eve 0.18.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/src/compiled/.vendor-stamp.json +2 -1
  3. package/dist/src/compiled/@chat-adapter/slack/index.js +29 -32
  4. package/dist/src/compiled/@chat-adapter/twilio/LICENSE +9 -0
  5. package/dist/src/compiled/@chat-adapter/twilio/api.d.ts +108 -0
  6. package/dist/src/compiled/@chat-adapter/twilio/api.js +1 -0
  7. package/dist/src/compiled/@chat-adapter/twilio/format.d.ts +12 -0
  8. package/dist/src/compiled/@chat-adapter/twilio/format.js +1 -0
  9. package/dist/src/compiled/@chat-adapter/twilio/index.d.ts +84 -0
  10. package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -0
  11. package/dist/src/compiled/@chat-adapter/twilio/voice.d.ts +44 -0
  12. package/dist/src/compiled/@chat-adapter/twilio/voice.js +1 -0
  13. package/dist/src/compiled/@chat-adapter/twilio/webhook.d.ts +18 -0
  14. package/dist/src/compiled/@chat-adapter/twilio/webhook.js +1 -0
  15. package/dist/src/compiled/_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js +1 -0
  16. package/dist/src/compiled/_chunks/node/chunk-PFJ2G64A-B79fSABi.js +1 -0
  17. package/dist/src/compiled/_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js +1 -0
  18. package/dist/src/compiled/_chunks/node/dist-RHRJZ03Q.js +4 -0
  19. package/dist/src/harness/action-result-helpers.d.ts +11 -1
  20. package/dist/src/harness/action-result-helpers.js +1 -1
  21. package/dist/src/harness/emission.d.ts +1 -0
  22. package/dist/src/harness/emission.js +1 -1
  23. package/dist/src/harness/step-hooks.js +1 -1
  24. package/dist/src/harness/tool-loop.js +1 -1
  25. package/dist/src/internal/application/package.js +1 -1
  26. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  27. package/dist/src/internal/nitro/host/configure-nitro-routes.js +1 -1
  28. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  29. package/dist/src/internal/nitro/routes/index.d.ts +7 -2
  30. package/dist/src/internal/nitro/routes/index.js +78 -48
  31. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +141 -0
  32. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +3 -0
  33. package/dist/src/public/channels/chat-sdk/index.d.ts +1 -0
  34. package/dist/src/public/channels/chat-sdk/index.js +1 -0
  35. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  36. package/dist/src/public/channels/index.d.ts +2 -0
  37. package/dist/src/public/channels/slack/api.js +1 -1
  38. package/dist/src/public/channels/twilio/api.d.ts +8 -29
  39. package/dist/src/public/channels/twilio/api.js +1 -1
  40. package/dist/src/public/channels/twilio/inbound.d.ts +10 -19
  41. package/dist/src/public/channels/twilio/inbound.js +2 -2
  42. package/dist/src/public/channels/twilio/routing.d.ts +13 -0
  43. package/dist/src/public/channels/twilio/routing.js +1 -0
  44. package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
  45. package/dist/src/public/channels/twilio/twiml.d.ts +5 -36
  46. package/dist/src/public/channels/twilio/twiml.js +1 -1
  47. package/dist/src/public/channels/twilio/verify.d.ts +12 -33
  48. package/dist/src/public/channels/twilio/verify.js +1 -1
  49. package/dist/src/setup/scaffold/create/project.js +1 -1
  50. package/package.json +7 -1
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vercel, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,108 @@
1
+ type TwilioCredential = string | (() => Promise<string> | string);
2
+ type TwilioFetch = typeof fetch;
3
+ interface TwilioCredentials {
4
+ accountSid?: TwilioCredential;
5
+ authToken?: TwilioCredential;
6
+ }
7
+ type TwilioFormValue = boolean | number | readonly string[] | string | null | undefined;
8
+ type TwilioFormFields = Readonly<Record<string, TwilioFormValue>>;
9
+ interface TwilioApiOptions {
10
+ apiBaseUrl?: string;
11
+ apiUrl?: string;
12
+ credentials?: TwilioCredentials;
13
+ fetch?: TwilioFetch;
14
+ }
15
+ interface TwilioApiResponse {
16
+ body: unknown;
17
+ ok: boolean;
18
+ status: number;
19
+ }
20
+ interface TwilioMessageResource {
21
+ account_sid?: string;
22
+ body?: string | null;
23
+ date_created?: string | null;
24
+ date_sent?: string | null;
25
+ date_updated?: string | null;
26
+ direction?: string;
27
+ error_code?: number | null;
28
+ error_message?: string | null;
29
+ from?: string | null;
30
+ messaging_service_sid?: string | null;
31
+ num_media?: string;
32
+ sid: string;
33
+ status?: string;
34
+ to?: string | null;
35
+ uri?: string;
36
+ }
37
+ interface TwilioCallResource {
38
+ account_sid?: string;
39
+ answered_by?: string | null;
40
+ caller_name?: string | null;
41
+ date_created?: string | null;
42
+ date_updated?: string | null;
43
+ direction?: string;
44
+ duration?: string | null;
45
+ end_time?: string | null;
46
+ from?: string | null;
47
+ parent_call_sid?: string | null;
48
+ sid: string;
49
+ start_time?: string | null;
50
+ status?: string;
51
+ to?: string | null;
52
+ uri?: string;
53
+ }
54
+ interface SendTwilioMessageOptions extends TwilioApiOptions {
55
+ body?: string;
56
+ from?: string;
57
+ mediaUrl?: readonly string[] | string;
58
+ messagingServiceSid?: string;
59
+ statusCallbackUrl?: string;
60
+ to: string;
61
+ }
62
+ interface FetchTwilioMessageOptions extends TwilioApiOptions {
63
+ messageSid: string;
64
+ }
65
+ interface DeleteTwilioMessageOptions extends TwilioApiOptions {
66
+ messageSid: string;
67
+ }
68
+ interface UpdateTwilioCallOptions extends TwilioApiOptions {
69
+ callSid: string;
70
+ method?: "GET" | "POST";
71
+ status?: "canceled" | "completed";
72
+ twiml?: string;
73
+ url?: string;
74
+ }
75
+ interface FetchTwilioMediaOptions extends TwilioApiOptions {
76
+ url: string;
77
+ }
78
+ interface ListTwilioMessagesOptions extends TwilioApiOptions {
79
+ from?: string;
80
+ limit?: number;
81
+ pageSize?: number;
82
+ to?: string;
83
+ }
84
+ interface CallTwilioApiOptions extends TwilioApiOptions {
85
+ body?: TwilioFormFields | URLSearchParams;
86
+ method?: "DELETE" | "GET" | "POST";
87
+ path: string;
88
+ search?: TwilioFormFields | URLSearchParams;
89
+ }
90
+ declare class TwilioApiError extends Error {
91
+ body: unknown;
92
+ status: number;
93
+ constructor(message: string, options: {
94
+ body: unknown;
95
+ status: number;
96
+ });
97
+ }
98
+ declare function resolveTwilioCredential(value: TwilioCredential | undefined, envName: string): Promise<string>;
99
+ declare function callTwilioApi(pathOrOptions: CallTwilioApiOptions | string, options?: Omit<CallTwilioApiOptions, "path">): Promise<TwilioApiResponse>;
100
+ declare function sendTwilioMessage(options: SendTwilioMessageOptions): Promise<TwilioMessageResource>;
101
+ declare function fetchTwilioMessage(options: FetchTwilioMessageOptions): Promise<TwilioMessageResource>;
102
+ declare function deleteTwilioMessage(options: DeleteTwilioMessageOptions): Promise<void>;
103
+ declare function updateTwilioCall(options: UpdateTwilioCallOptions): Promise<TwilioCallResource>;
104
+ declare function fetchTwilioMedia(options: FetchTwilioMediaOptions): Promise<ArrayBuffer>;
105
+ declare function listTwilioMessages(options?: ListTwilioMessagesOptions): Promise<TwilioMessageResource[]>;
106
+ declare function encodeTwilioForm(fields: TwilioFormFields): URLSearchParams;
107
+
108
+ export { type CallTwilioApiOptions, type DeleteTwilioMessageOptions, type FetchTwilioMediaOptions, type FetchTwilioMessageOptions, type ListTwilioMessagesOptions, type SendTwilioMessageOptions, TwilioApiError, type TwilioApiOptions, type TwilioApiResponse, type TwilioCallResource, type TwilioCredential, type TwilioCredentials, type TwilioFetch, type TwilioFormFields, type TwilioFormValue, type TwilioMessageResource, type UpdateTwilioCallOptions, callTwilioApi, deleteTwilioMessage, encodeTwilioForm, fetchTwilioMedia, fetchTwilioMessage, listTwilioMessages, resolveTwilioCredential, sendTwilioMessage, updateTwilioCall };
@@ -0,0 +1 @@
1
+ import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c,u as l}from"../../_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js";export{c as TwilioApiError,i as callTwilioApi,o as deleteTwilioMessage,n as encodeTwilioForm,e as fetchTwilioMedia,a as fetchTwilioMessage,s as listTwilioMessages,t as resolveTwilioCredential,r as sendTwilioMessage,l as updateTwilioCall};
@@ -0,0 +1,12 @@
1
+ declare const TWILIO_MESSAGE_LIMIT = 1600;
2
+ interface TwilioTextOptions {
3
+ limit?: number;
4
+ }
5
+ interface TwilioTextResult {
6
+ text: string;
7
+ truncated: boolean;
8
+ }
9
+ declare function truncateTwilioText(text: string, options?: TwilioTextOptions): TwilioTextResult;
10
+ declare function twilioTextOrPlaceholder(text: string): string;
11
+
12
+ export { TWILIO_MESSAGE_LIMIT, type TwilioTextOptions, type TwilioTextResult, truncateTwilioText, twilioTextOrPlaceholder };
@@ -0,0 +1 @@
1
+ import{n as e,r as t,t as n}from"../../_chunks/node/chunk-PFJ2G64A-B79fSABi.js";export{n as TWILIO_MESSAGE_LIMIT,e as truncateTwilioText,t as twilioTextOrPlaceholder};
@@ -0,0 +1,84 @@
1
+ import { BaseFormatConverter, Root, AdapterPostableMessage, Logger, CardElement, Adapter, ChatInstance, WebhookOptions, RawMessage, Message, FetchOptions, FetchResult, ThreadInfo, UserInfo, FormattedContent, Attachment } from '#compiled/chat/index.js';
2
+ import { TwilioMessageResource, TwilioCredential, TwilioFetch, TwilioApiOptions } from './api.js';
3
+ import { k as TwilioWebhookPayload, l as TwilioWebhookUrl, n as TwilioWebhookVerifier, b as TwilioMediaPayload } from './types-ConmTsdR.js';
4
+
5
+ declare class TwilioFormatConverter extends BaseFormatConverter {
6
+ toAst(text: string): Root;
7
+ fromAst(ast: Root): string;
8
+ renderPostable(message: AdapterPostableMessage): string;
9
+ }
10
+
11
+ interface TwilioThreadId {
12
+ recipient: string;
13
+ sender: string;
14
+ }
15
+ interface TwilioAdapterConfig {
16
+ accountSid?: TwilioCredential;
17
+ apiUrl?: string;
18
+ authToken?: TwilioCredential;
19
+ fetch?: TwilioFetch;
20
+ logger?: Logger;
21
+ messagingServiceSid?: string;
22
+ phoneNumber?: string;
23
+ statusCallbackUrl?: string;
24
+ userName?: string;
25
+ webhookUrl?: TwilioWebhookUrl;
26
+ webhookVerifier?: TwilioWebhookVerifier;
27
+ }
28
+ type TwilioRawMessage = TwilioMessageResource | TwilioWebhookPayload;
29
+
30
+ declare function cardToTwilioText(card: CardElement): string;
31
+
32
+ declare class TwilioAdapter implements Adapter<TwilioThreadId, TwilioRawMessage> {
33
+ readonly name = "twilio";
34
+ readonly lockScope: "channel";
35
+ readonly persistThreadHistory = true;
36
+ readonly userName: string;
37
+ protected chat: ChatInstance | null;
38
+ protected readonly accountSid?: TwilioAdapterConfig["accountSid"];
39
+ protected readonly apiUrl?: string;
40
+ protected readonly authToken?: TwilioAdapterConfig["authToken"];
41
+ protected readonly fetch?: TwilioAdapterConfig["fetch"];
42
+ protected readonly formatConverter: TwilioFormatConverter;
43
+ protected readonly logger: Logger;
44
+ protected readonly messagingServiceSid?: string;
45
+ protected readonly phoneNumber?: string;
46
+ protected readonly statusCallbackUrl?: string;
47
+ protected readonly webhookUrl?: TwilioAdapterConfig["webhookUrl"];
48
+ protected readonly webhookVerifier?: TwilioAdapterConfig["webhookVerifier"];
49
+ constructor(config?: TwilioAdapterConfig);
50
+ initialize(chat: ChatInstance): Promise<void>;
51
+ handleWebhook(request: Request, options?: WebhookOptions): Promise<Response>;
52
+ postMessage(threadId: string, message: AdapterPostableMessage): Promise<RawMessage<TwilioRawMessage>>;
53
+ editMessage(): Promise<RawMessage<TwilioRawMessage>>;
54
+ deleteMessage(_threadId: string, messageId: string): Promise<void>;
55
+ addReaction(): Promise<void>;
56
+ removeReaction(): Promise<void>;
57
+ startTyping(): Promise<void>;
58
+ parseMessage(raw: TwilioRawMessage): Message<TwilioRawMessage>;
59
+ fetchMessage(threadId: string, messageId: string): Promise<Message<TwilioRawMessage> | null>;
60
+ fetchMessages(threadId: string, options?: FetchOptions): Promise<FetchResult<TwilioRawMessage>>;
61
+ fetchThread(threadId: string): Promise<ThreadInfo>;
62
+ getUser(userId: string): Promise<UserInfo | null>;
63
+ openDM(userId: string): Promise<string>;
64
+ isDM(threadId: string): boolean;
65
+ channelIdFromThreadId(threadId: string): string;
66
+ encodeThreadId(platformData: TwilioThreadId): string;
67
+ decodeThreadId(threadId: string): TwilioThreadId;
68
+ renderFormatted(content: FormattedContent): string;
69
+ rehydrateAttachment(attachment: Attachment): Attachment;
70
+ protected parseTwilioTextPayload(raw: TwilioWebhookPayload & {
71
+ kind: "text";
72
+ }, threadId: string): Message<TwilioRawMessage>;
73
+ protected parseTwilioResource(raw: TwilioMessageResource, fallbackThread: TwilioThreadId | undefined): Message<TwilioRawMessage>;
74
+ protected renderPostableText(message: AdapterPostableMessage): string;
75
+ protected mediaUrls(message: AdapterPostableMessage): string[];
76
+ protected twilioAttachment(media: TwilioMediaPayload): Attachment;
77
+ protected apiOptions(): TwilioApiOptions;
78
+ protected defaultSender(): string;
79
+ protected author(userId: string, isMe: boolean): Message["author"];
80
+ protected threadIdForResource(raw: TwilioMessageResource, fallback: TwilioThreadId): string;
81
+ }
82
+ declare function createTwilioAdapter(config?: TwilioAdapterConfig): TwilioAdapter;
83
+
84
+ export { TwilioAdapter, type TwilioAdapterConfig, TwilioFormatConverter, type TwilioRawMessage, type TwilioThreadId, cardToTwilioText, createTwilioAdapter };
@@ -0,0 +1 @@
1
+ import{At as e,Dt as t,Nt as n,S as r,et as i,l as a,vt as o,wt as s,y as c}from"../../_chunks/node/dist-W8yle6rh.js";import{a as l,d as u,f as d,i as f,u as p}from"../../_chunks/node/dist-RHRJZ03Q.js";import{n as m,r as h,t as g}from"../../_chunks/node/chunk-PFJ2G64A-B79fSABi.js";import{a as _,l as v,o as y,r as b,s as x}from"../../_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js";import{a as S,n as C,r as w}from"../../_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js";function T(e){return l(e).replace(/\*/g,``)}var E=class extends i{toAst(e){return s(e)}fromAst(r){return t(n(structuredClone(r),t=>o(t)?{type:`code`,value:e(t)}:t)).trim()}renderPostable(e){return typeof e==`string`?e:`raw`in e?e.raw:`markdown`in e?this.fromMarkdown(e.markdown):`ast`in e?this.fromAst(e.ast):super.renderPostable(e)}};function D(e){return`twilio:${encodeURIComponent(e.sender)}:${encodeURIComponent(e.recipient)}`}function O(e){let[t,n,r]=e.split(`:`);if(t!==`twilio`||!n||!r)throw new f(`twilio`,`Invalid Twilio thread ID: ${e}`);return{recipient:decodeURIComponent(r),sender:decodeURIComponent(n)}}function k(e){let t=O(e);return`twilio:${encodeURIComponent(t.sender)}`}function A(){return new Response(`<Response></Response>`,{headers:{"content-type":`application/xml`},status:200})}function j(e){return e.startsWith(`MG`)?{messagingServiceSid:e}:{from:e}}function M(e){return e?.startsWith(`image/`)?`image`:e?.startsWith(`video/`)?`video`:e?.startsWith(`audio/`)?`audio`:`file`}var N=class{name=`twilio`;lockScope=`channel`;persistThreadHistory=!0;userName;chat=null;accountSid;apiUrl;authToken;fetch;formatConverter=new E;logger;messagingServiceSid;phoneNumber;statusCallbackUrl;webhookUrl;webhookVerifier;constructor(e={}){this.accountSid=e.accountSid,this.apiUrl=e.apiUrl,this.authToken=e.authToken,this.fetch=e.fetch,this.logger=e.logger??new a(`info`).child(`twilio`),this.messagingServiceSid=e.messagingServiceSid??process.env.TWILIO_MESSAGING_SERVICE_SID,this.phoneNumber=e.phoneNumber??process.env.TWILIO_PHONE_NUMBER,this.statusCallbackUrl=e.statusCallbackUrl,this.userName=e.userName??`bot`,this.webhookUrl=e.webhookUrl,this.webhookVerifier=e.webhookVerifier}async initialize(e){this.chat=e,this.logger.info(`Twilio adapter initialized`,{messagingServiceSid:this.messagingServiceSid,phoneNumber:this.phoneNumber})}async handleWebhook(e,t){let n;try{n=await S(e,{authToken:this.authToken,webhookUrl:this.webhookUrl,webhookVerifier:this.webhookVerifier})}catch(e){if(e instanceof w)return new Response(`Invalid signature`,{status:401});if(e instanceof C)return new Response(`Invalid webhook`,{status:400});throw e}if(n.kind!==`text`||!this.chat)return A();let r=this.encodeThreadId({recipient:n.from,sender:n.to}),i=this.parseTwilioTextPayload(n,r);return this.chat.processMessage(this,r,i,t),A()}async postMessage(e,t){let n=this.decodeThreadId(e),r=this.renderPostableText(t),i=this.mediaUrls(t);if(!r&&i.length===0)throw new f(`twilio`,`Message text cannot be empty`);let a=await v({...this.apiOptions(),body:r||i.length===0?h(r):void 0,mediaUrl:i,statusCallbackUrl:this.statusCallbackUrl,to:n.recipient,...j(n.sender)});return{id:a.sid,raw:a,threadId:this.threadIdForResource(a,n)}}async editMessage(){throw new r(`Twilio does not support editing sent messages`,`editMessage`)}async deleteMessage(e,t){await b({...this.apiOptions(),messageSid:t})}async addReaction(){throw new r(`Twilio does not support message reactions`,`addReaction`)}async removeReaction(){throw new r(`Twilio does not support message reactions`,`removeReaction`)}async startTyping(){}parseMessage(e){if(F(e)){if(e.kind!==`text`)throw new f(`twilio`,`Cannot parse unsupported webhook`);return this.parseTwilioTextPayload(e,this.encodeThreadId({recipient:e.from,sender:e.to}))}return this.parseTwilioResource(e,void 0)}async fetchMessage(e,t){let n=this.decodeThreadId(e);try{let e=await y({...this.apiOptions(),messageSid:t});return this.parseTwilioResource(e,n)}catch{return null}}async fetchMessages(e,t={}){let n=this.decodeThreadId(e),r=t.limit??50,[i,a]=await Promise.all([x({...this.apiOptions(),from:n.sender,limit:r,to:n.recipient}),x({...this.apiOptions(),from:n.recipient,limit:r,to:n.sender})]);return{messages:[...i,...a].map(e=>this.parseTwilioResource(e,n)).sort((e,t)=>e.metadata.dateSent.getTime()-t.metadata.dateSent.getTime()).slice(-r)}}async fetchThread(e){let t=this.decodeThreadId(e);return{channelId:this.channelIdFromThreadId(e),channelName:t.sender,id:e,isDM:!0,metadata:{...t}}}async getUser(e){return{fullName:e,isBot:!1,userId:e,userName:e}}async openDM(e){return this.encodeThreadId({recipient:e,sender:this.defaultSender()})}isDM(e){return e.startsWith(`twilio:`)}channelIdFromThreadId(e){return k(e)}encodeThreadId(e){return D(e)}decodeThreadId(e){return O(e)}renderFormatted(e){return this.formatConverter.fromAst(e)}rehydrateAttachment(e){let t=e.fetchMetadata?.twilioMediaUrl??e.url;return t?this.twilioAttachment({contentType:e.mimeType,url:t}):e}parseTwilioTextPayload(e,t){return new c({attachments:e.media.map(e=>this.twilioAttachment(e)),author:this.author(e.from,!1),formatted:this.formatConverter.toAst(e.body),id:e.messageSid??`twilio:${Date.now()}`,metadata:{dateSent:new Date,edited:!1},raw:e,text:e.body,threadId:t})}parseTwilioResource(e,t){let n=e.direction?.startsWith(`outbound`)??!1,r=e.from??e.messaging_service_sid??(n?t?.sender:t?.recipient),i=e.to??(n?t?.recipient:t?.sender);if(!(r&&i))throw new f(`twilio`,`Twilio message is missing routing`);let a=e.body??``,o=n?{recipient:t?.recipient??i,sender:t?.sender??r}:{recipient:r,sender:i};return new c({attachments:[],author:this.author(n?o.sender:r,n),formatted:this.formatConverter.toAst(a),id:e.sid,metadata:{dateSent:I(e.date_sent??e.date_created),edited:!1},raw:e,text:a,threadId:this.encodeThreadId(o)})}renderPostableText(e){let t=p(e);return m(t?T(t):this.formatConverter.renderPostable(e),{limit:g}).text}mediaUrls(e){if(u(e).length>0)throw new f(`twilio`,`Twilio adapter supports media attachments by public URL only`);let t=d(e),n=[];for(let e of t){if(typeof e.url!=`string`||e.url.length===0)throw new f(`twilio`,`Twilio adapter supports media attachments by public URL only`);n.push(e.url)}return n}twilioAttachment(e){return{fetchData:async()=>Buffer.from(await _({...this.apiOptions(),url:e.url})),fetchMetadata:{twilioMediaUrl:e.url},mimeType:e.contentType,type:M(e.contentType),url:e.url}}apiOptions(){return{apiUrl:this.apiUrl,credentials:{accountSid:this.accountSid,authToken:this.authToken},fetch:this.fetch}}defaultSender(){let e=this.phoneNumber??this.messagingServiceSid;if(!e)throw new f(`twilio`,`phoneNumber or messagingServiceSid is required`);return e}author(e,t){return{fullName:e,isBot:t,isMe:t,userId:e,userName:e}}threadIdForResource(e,t){return this.parseTwilioResource(e,t).threadId}};function P(e={}){return new N(e)}function F(e){return`kind`in e}function I(e){let t=e?new Date(e):new Date;return Number.isNaN(t.getTime())?new Date:t}export{N as TwilioAdapter,E as TwilioFormatConverter,T as cardToTwilioText,P as createTwilioAdapter};
@@ -0,0 +1,44 @@
1
+ interface TwilioVoiceCallPayload {
2
+ accountSid?: string;
3
+ callSid?: string;
4
+ from: string;
5
+ raw: URLSearchParams;
6
+ to?: string;
7
+ }
8
+ interface TwilioVoiceTranscriptionPayload {
9
+ accountSid?: string;
10
+ callSid?: string;
11
+ confidence?: number;
12
+ final?: boolean;
13
+ from?: string;
14
+ raw: URLSearchParams;
15
+ sequenceId?: string;
16
+ text: string;
17
+ timestamp?: string;
18
+ to?: string;
19
+ track?: string;
20
+ transcriptionEvent?: string;
21
+ transcriptionSid?: string;
22
+ }
23
+ interface TwilioGatherSpeechResponseOptions {
24
+ actionOnEmptyResult?: boolean;
25
+ actionUrl: string;
26
+ hints?: readonly string[] | string;
27
+ language?: string;
28
+ method?: "GET" | "POST";
29
+ profanityFilter?: boolean;
30
+ prompt: string;
31
+ speechModel?: string;
32
+ speechTimeout?: "auto" | string;
33
+ timeoutSeconds?: number;
34
+ voice?: string;
35
+ }
36
+ declare function parseTwilioVoiceCall(params: URLSearchParams): TwilioVoiceCallPayload | null;
37
+ declare function parseTwilioVoiceTranscription(params: URLSearchParams): TwilioVoiceTranscriptionPayload | null;
38
+ declare function emptyTwilioResponse(): Response;
39
+ declare function sayTwilioResponse(message: string): Response;
40
+ declare function gatherSpeechTwilioResponse(options: TwilioGatherSpeechResponseOptions): Response;
41
+ declare function twilioResponse(twiml: string): Response;
42
+ declare function escapeXml(value: string): string;
43
+
44
+ export { type TwilioGatherSpeechResponseOptions, type TwilioVoiceCallPayload, type TwilioVoiceTranscriptionPayload, emptyTwilioResponse, escapeXml, gatherSpeechTwilioResponse, parseTwilioVoiceCall, parseTwilioVoiceTranscription, sayTwilioResponse, twilioResponse };
@@ -0,0 +1 @@
1
+ function e(e){let t=u(e,`From`)??u(e,`Caller`);return t?{accountSid:u(e,`AccountSid`),callSid:u(e,`CallSid`),from:t,raw:e,to:u(e,`To`)??u(e,`Called`)}:null}function t(e){let t=s(u(e,`TranscriptionData`)),n=c(u(e,`Final`));if(n===!1)return null;let r=u(e,`SpeechResult`)??u(e,`TranscriptionText`)??t?.transcript??``;return r.trim().length===0?null:{accountSid:u(e,`AccountSid`),callSid:u(e,`CallSid`),confidence:l(u(e,`Confidence`)??t?.confidence),final:n,from:u(e,`From`)??u(e,`Caller`),raw:e,sequenceId:u(e,`SequenceId`),text:r,timestamp:u(e,`Timestamp`),to:u(e,`To`)??u(e,`Called`),track:u(e,`Track`),transcriptionEvent:u(e,`TranscriptionEvent`),transcriptionSid:u(e,`TranscriptionSid`)}}function n(){return a(`<Response></Response>`)}function r(e){return a(`<Response><Say>${o(e)}</Say></Response>`)}function i(e){let t=typeof e.hints==`string`?e.hints:e.hints?.join(`,`),n=[`input="speech"`,`action="${o(e.actionUrl)}"`,`method="${e.method??`POST`}"`,`actionOnEmptyResult="${e.actionOnEmptyResult===!1?`false`:`true`}"`,e.language?`language="${o(e.language)}"`:void 0,e.speechModel?`speechModel="${o(e.speechModel)}"`:void 0,e.timeoutSeconds===void 0?void 0:`timeout="${e.timeoutSeconds}"`,e.speechTimeout?`speechTimeout="${o(e.speechTimeout)}"`:void 0,t?`hints="${o(t)}"`:void 0,e.profanityFilter===void 0?void 0:`profanityFilter="${e.profanityFilter?`true`:`false`}"`].filter(e=>e!==void 0).join(` `),r=[e.voice?`voice="${o(e.voice)}"`:void 0,e.language?`language="${o(e.language)}"`:void 0].filter(e=>e!==void 0).join(` `);return a(`<Response><Gather ${n}>${r?`<Say ${r}>`:`<Say>`}${o(e.prompt)}</Say></Gather></Response>`)}function a(e){return new Response(e,{headers:{"content-type":`text/xml;charset=UTF-8`},status:200})}function o(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&apos;`)}function s(e){if(!e)return null;try{let t=JSON.parse(e);return{confidence:typeof t.confidence==`number`||typeof t.confidence==`string`?String(t.confidence):void 0,transcript:typeof t.transcript==`string`?t.transcript:void 0}}catch{return null}}function c(e){if(e!==void 0){if(e===`true`)return!0;if(e===`false`)return!1}}function l(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function u(e,t){let n=e.get(t);return n===null||n.length===0?void 0:n}export{n as emptyTwilioResponse,o as escapeXml,i as gatherSpeechTwilioResponse,e as parseTwilioVoiceCall,t as parseTwilioVoiceTranscription,r as sayTwilioResponse,a as twilioResponse};
@@ -0,0 +1,18 @@
1
+ import { k as TwilioWebhookPayload, l as TwilioWebhookUrl, h as TwilioVerifyOptions, g as TwilioVerifiedRequest, c as TwilioReadOptions } from './types-ConmTsdR.js';
2
+ export { T as TwilioHeaderValue, a as TwilioHeaders, b as TwilioMediaPayload, d as TwilioStatusPayload, e as TwilioTextPayload, f as TwilioUnsupportedPayload, i as TwilioWebhookError, j as TwilioWebhookParseError, m as TwilioWebhookVerificationError, n as TwilioWebhookVerifier } from './types-ConmTsdR.js';
3
+ import './api.js';
4
+
5
+ declare function parseTwilioWebhookBody(params: URLSearchParams): TwilioWebhookPayload;
6
+
7
+ declare function verifyTwilioRequest(request: Request, options?: TwilioVerifyOptions): Promise<TwilioVerifiedRequest>;
8
+ declare function signTwilioRequest(input: {
9
+ authToken: string;
10
+ params?: URLSearchParams | null;
11
+ url: string;
12
+ }): Promise<string>;
13
+ declare function twilioSignatureBase(url: string, params?: URLSearchParams | null): string;
14
+ declare function resolveTwilioWebhookUrl(request: Request, webhookUrl: TwilioWebhookUrl | undefined): Promise<string>;
15
+
16
+ declare function readTwilioWebhook(request: Request, options?: TwilioReadOptions): Promise<TwilioWebhookPayload>;
17
+
18
+ export { TwilioReadOptions, TwilioVerifiedRequest, TwilioVerifyOptions, TwilioWebhookPayload, TwilioWebhookUrl, parseTwilioWebhookBody, readTwilioWebhook, resolveTwilioWebhookUrl, signTwilioRequest, twilioSignatureBase, verifyTwilioRequest };
@@ -0,0 +1 @@
1
+ import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c}from"../../_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js";export{c as TwilioWebhookError,i as TwilioWebhookParseError,o as TwilioWebhookVerificationError,n as parseTwilioWebhookBody,e as readTwilioWebhook,a as resolveTwilioWebhookUrl,s as signTwilioRequest,t as twilioSignatureBase,r as verifyTwilioRequest};
@@ -0,0 +1 @@
1
+ var e=class extends Error{body;status;constructor(e,t){super(e),this.name=`TwilioApiError`,this.body=t.body,this.status=t.status}},t=`https://api.twilio.com`;async function n(t,n){let r=t??process.env[n];if(!r)throw new e(`${n} is required`,{body:null,status:0});return typeof r==`function`?await r():r}async function r(r,i={}){let a=typeof r==`string`?{...i,path:r}:r,o=await n(a.credentials?.accountSid,`TWILIO_ACCOUNT_SID`),s=await n(a.credentials?.authToken,`TWILIO_AUTH_TOKEN`),c=new URL(a.path,a.apiUrl??a.apiBaseUrl??t);for(let[e,t]of d(a.search)??[])c.searchParams.append(e,t);let l=d(a.body),u=await(a.fetch??fetch)(c,{body:l,headers:{authorization:f(o,s),...l?{"content-type":`application/x-www-form-urlencoded;charset=UTF-8`}:{}},method:a.method??`POST`}),p=await m(u);if(!u.ok)throw new e(`Twilio API returned HTTP ${u.status}`,{body:p,status:u.status});return{body:p,ok:u.ok,status:u.status}}async function i(e){let t=await n(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`),i=p(e.mediaUrl);if(!e.body&&i.length===0)throw TypeError(`body or mediaUrl is required`);if(!(e.from||e.messagingServiceSid))throw TypeError(`from or messagingServiceSid is required`);let a=u({Body:e.body,From:e.from,MediaUrl:i,MessagingServiceSid:e.messagingServiceSid,StatusCallback:e.statusCallbackUrl,To:e.to});return(await r(`/2010-04-01/Accounts/${encodeURIComponent(t)}/Messages.json`,{...e,body:a})).body}async function a(e){let t=await n(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`);return(await r(`/2010-04-01/Accounts/${encodeURIComponent(t)}/Messages/${encodeURIComponent(e.messageSid)}.json`,{...e,method:`GET`})).body}async function o(e){let t=await n(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`);await r(`/2010-04-01/Accounts/${encodeURIComponent(t)}/Messages/${encodeURIComponent(e.messageSid)}.json`,{...e,method:`DELETE`})}async function s(e){let t=await n(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`);if(!(e.twiml||e.url||e.status))throw TypeError(`twiml, url, or status is required`);if(e.twiml&&e.url)throw TypeError(`twiml and url are mutually exclusive`);let i=u({Method:e.method,Status:e.status,Twiml:e.twiml,Url:e.url});return(await r(`/2010-04-01/Accounts/${encodeURIComponent(t)}/Calls/${encodeURIComponent(e.callSid)}.json`,{...e,body:i})).body}async function c(t){let r=await n(t.credentials?.accountSid,`TWILIO_ACCOUNT_SID`),i=await n(t.credentials?.authToken,`TWILIO_AUTH_TOKEN`),a=await(t.fetch??fetch)(t.url,{headers:{authorization:f(r,i)},method:`GET`});if(!a.ok)throw new e(`Twilio API returned HTTP ${a.status}`,{body:await m(a),status:a.status});return a.arrayBuffer()}async function l(e={}){let t=await n(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`),i=u({From:e.from,PageSize:e.pageSize,To:e.to});return((await r(`/2010-04-01/Accounts/${encodeURIComponent(t)}/Messages.json`,{...e,method:`GET`,search:i})).body.messages??[]).slice(0,e.limit)}function u(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null){if(Array.isArray(r)){for(let e of r)t.append(n,e);continue}t.set(n,String(r))}return t}function d(e){if(e!==void 0)return e instanceof URLSearchParams?e:u(e)}function f(e,t){return`Basic ${btoa(`${e}:${t}`)}`}function p(e){return e===void 0?[]:typeof e==`string`?[e]:[...e]}async function m(e){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}export{c as a,n as c,u as i,i as l,r as n,a as o,o as r,l as s,e as t,s as u};
@@ -0,0 +1 @@
1
+ var e=1600;function t(e,t={}){let n=t.limit??1600;if(!Number.isInteger(n)||n<1)throw TypeError(`limit must be a positive integer`);return e.length<=n?{text:e,truncated:!1}:{text:e.slice(0,n),truncated:!0}}function n(e){return e.length>0?e:` `}export{t as n,n as r,e as t};
@@ -0,0 +1 @@
1
+ import{c as e}from"./chunk-5OX2R7AJ-CxVV-owP.js";function t(e){let t=r(e,`MessageStatus`)??r(e,`SmsStatus`),i=r(e,`Body`),a=r(e,`From`),o=r(e,`To`),s=r(e,`MessageSid`)??r(e,`SmsMessageSid`);return t&&!i?{accountSid:r(e,`AccountSid`),from:a,kind:`status`,messageSid:s,messageStatus:t,raw:e,to:o}:a&&o&&(i!==void 0||Number(r(e,`NumMedia`)??0)>0)?{accountSid:r(e,`AccountSid`),body:i??``,from:a,kind:`text`,media:n(e),messageSid:s,raw:e,to:o}:{kind:`unsupported`,raw:e}}function n(e){let t=Number(r(e,`NumMedia`)??0),n=[];for(let i=0;i<t;i++){let t=r(e,`MediaUrl${i}`);t&&n.push({contentType:r(e,`MediaContentType${i}`),url:t})}return n}function r(e,t){let n=e.get(t);return n===null||n.length===0?void 0:n}var i=class extends Error{constructor(e){super(e),this.name=`TwilioWebhookError`}},a=class extends i{constructor(e){super(e),this.name=`TwilioWebhookParseError`}},o=class extends i{constructor(e){super(e),this.name=`TwilioWebhookVerificationError`}};async function s(t,n={}){let r=await t.text();if(n.webhookVerifier){let e=await n.webhookVerifier(t,r);if(!e)throw new o(`Twilio webhook verifier rejected the request`);return{body:typeof e==`string`?e:r,params:d(t,typeof e==`string`?e:r)}}let i=t.headers.get(`x-twilio-signature`);if(!i)throw new o(`Twilio signature header is required`);let a=await e(n.authToken,`TWILIO_AUTH_TOKEN`),s=await u(t,n.webhookUrl),l=d(t,r);if(!p(await c({authToken:a,params:t.method.toUpperCase()===`GET`?null:l,url:s}),i))throw new o(`Twilio signature is invalid`);return{body:r,params:l}}async function c(e){let t=await crypto.subtle.importKey(`raw`,new TextEncoder().encode(e.authToken),{hash:`SHA-1`,name:`HMAC`},!1,[`sign`]);return f(await crypto.subtle.sign(`HMAC`,t,new TextEncoder().encode(l(e.url,e.params))))}function l(e,t){if(!t)return e;let n=e,r=new Map;for(let[e,n]of t){let t=r.get(e)??new Set;t.add(n),r.set(e,t)}for(let e of[...r.keys()].sort())for(let t of[...r.get(e)??[]].sort())n+=`${e}${t}`;return n}async function u(e,t){return typeof t==`function`?t(e):t??e.url}function d(e,t){return e.method.toUpperCase()===`GET`?new URL(e.url).searchParams:new URLSearchParams(t)}function f(e){let t=``,n=new Uint8Array(e);for(let e of n)t+=String.fromCharCode(e);return btoa(t)}function p(e,t){let n=Math.abs(e.length-t.length),r=Math.max(e.length,t.length);for(let i=0;i<r;i++){let r=e.charCodeAt(i)||0,a=t.charCodeAt(i)||0;n+=Number(r!==a)}return n===0}async function m(e,n={}){return t((await s(e,n)).params)}export{m as a,l as c,t as i,s as l,a as n,u as o,o as r,c as s,i as t};
@@ -0,0 +1,4 @@
1
+ import{I as e,K as t,L as n,kt as r}from"./dist-W8yle6rh.js";import i from"crypto";function a(e){return t(e)?e:typeof e==`object`&&e&&`card`in e?e.card:null}function o(e){return typeof e==`object`&&e&&`files`in e?e.files??[]:[]}function s(e){return typeof e==`object`&&e&&`attachments`in e?e.attachments??[]:[]}var c=class extends Error{adapter;code;constructor(e,t,n){super(e),this.name=`AdapterError`,this.adapter=t,this.code=n}},l=class extends c{retryAfter;constructor(e,t){super(`Rate limited by ${e}${t?`, retry after ${t}s`:``}`,e,`RATE_LIMITED`),this.name=`AdapterRateLimitError`,this.retryAfter=t}},u=class extends c{constructor(e,t){super(t||`Authentication failed for ${e}`,e,`AUTH_FAILED`),this.name=`AuthenticationError`}},d=class extends c{constructor(e,t){super(t,e,`VALIDATION_ERROR`),this.name=`ValidationError`}},f=class extends c{originalError;constructor(e,t,n){super(t||`Network error communicating with ${e}`,e,`NETWORK_ERROR`),this.name=`NetworkError`,this.originalError=n}};async function p(e,t){let{platform:n,throwOnUnsupported:r=!0}=t;if(Buffer.isBuffer(e))return e;if(e instanceof ArrayBuffer)return Buffer.from(e);if(e instanceof Blob){let t=await e.arrayBuffer();return Buffer.from(t)}if(r)throw new d(n,`Unsupported file data type`);return null}var m={slack:{primary:`primary`,danger:`danger`},gchat:{primary:`primary`,danger:`danger`},teams:{primary:`positive`,danger:`destructive`},discord:{primary:`primary`,danger:`danger`}};function h(e){return t=>n(t,e)}function g(e,t){if(e)return m[t][e]}function _(e,t={}){let{boldFormat:n=`*`,lineBreak:r=`
2
+ `,platform:i}=t,a=i?h(i):e=>e,o=[];e.title&&o.push(`${n}${a(e.title)}${n}`),e.subtitle&&o.push(a(e.subtitle));for(let t of e.children){let e=v(t,a);e&&o.push(e)}return o.join(r)}function v(t,n){switch(t.type){case`text`:return n(t.content);case`link`:return`${n(t.label)} (${t.url})`;case`fields`:return t.children.map(e=>`${n(e.label)}: ${n(e.value)}`).join(`
3
+ `);case`actions`:return null;case`section`:return t.children.map(e=>v(e,n)).filter(Boolean).join(`
4
+ `);case`table`:return r(t.headers,t.rows);case`divider`:return`---`;default:return e(t)}}var y=`aes-256-gcm`,b=12,x=16,S=/^[0-9a-fA-F]{64}$/;function C(e,t){let n=i.randomBytes(b),r=i.createCipheriv(y,t,n,{authTagLength:x}),a=Buffer.concat([r.update(e,`utf8`),r.final()]),o=r.getAuthTag();return{iv:n.toString(`base64`),data:a.toString(`base64`),tag:o.toString(`base64`)}}function w(e,t){let n=Buffer.from(e.iv,`base64`),r=Buffer.from(e.data,`base64`),a=Buffer.from(e.tag,`base64`),o=i.createDecipheriv(y,t,n,{authTagLength:x});return o.setAuthTag(a),Buffer.concat([o.update(r),o.final()]).toString(`utf8`)}function T(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.iv==`string`&&typeof t.data==`string`&&typeof t.tag==`string`}function E(e){let t=e.trim(),n=S.test(t),r=Buffer.from(t,n?`hex`:`base64`);if(r.length!==32)throw Error(`Encryption key must decode to exactly 32 bytes (received ${r.length}). Use a 64-char hex string or 44-char base64 string.`);return r}export{_ as a,w as c,o as d,s as f,p as h,d as i,C as l,g as m,u as n,h as o,T as p,f as r,E as s,l as t,a as u};
@@ -1,4 +1,4 @@
1
- import type { ModelMessage, ToolSet, TypedToolResult } from "ai";
1
+ import type { ModelMessage, ToolSet, TypedToolError, TypedToolResult } from "ai";
2
2
  import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";
3
3
  type ToolResponsePart = Extract<ModelMessage, {
4
4
  role: "tool";
@@ -28,6 +28,16 @@ export declare function createRuntimeToolResultFromValue(input: {
28
28
  * step result and for `tool-result` parts that arrive on the stream.
29
29
  */
30
30
  export declare function createRuntimeToolResultFromStepResult(toolResult: TypedToolResult<ToolSet>): RuntimeToolResultActionResult;
31
+ /**
32
+ * Builds a failed `RuntimeToolResultActionResult` from one AI SDK
33
+ * `tool-error` part.
34
+ */
35
+ export declare function createRuntimeToolResultFromToolError(toolError: TypedToolError<ToolSet>): RuntimeToolResultActionResult;
36
+ /**
37
+ * Builds the inline tool-result message part that repairs model history after a
38
+ * local tool execution error.
39
+ */
40
+ export declare function createToolResultMessagePartFromToolError(toolError: TypedToolError<ToolSet>): ToolResultPart;
31
41
  /**
32
42
  * Builds a `RuntimeToolResultActionResult` from one tool-result message
33
43
  * part as it appears on `step.response.messages`. Used as a fallback when
@@ -1 +1 @@
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
+ import{toError}from"#shared/errors.js";import{parseJsonValue}from"#shared/json.js";import{authorizationPendingAsJsonObject,isAuthorizationPendingModelOutput,isAuthorizationSignal}from"#harness/authorization.js";import{withToolOutputSerializationError}from"#harness/tool-output-serialization.js";function toJsonValue(e){return isAuthorizationSignal(e)?parseJsonValue(authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})):isAuthorizationPendingModelOutput(e)?parseJsonValue(authorizationPendingAsJsonObject(e)):parseJsonValue(e===void 0?null:e)}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 createRuntimeToolResultFromToolError(t){return createRuntimeToolResultFromValue({callId:t.toolCallId,isError:!0,output:toError(t.error),toolName:t.toolName})}function createToolResultMessagePartFromToolError(t){return{type:`tool-result`,toolCallId:t.toolCallId,toolName:t.toolName,output:{type:`error-text`,value:toError(t.error).message}}}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,createRuntimeToolResultFromToolError,createRuntimeToolResultFromValue,createToolResultMessagePartFromToolError};
@@ -100,6 +100,7 @@ interface EmittedStreamContent {
100
100
  readonly handledInlineToolResultCallIds: ReadonlySet<string>;
101
101
  readonly inlineAuthorizationResults: readonly TypedToolResult<ToolSet>[];
102
102
  readonly inlineToolResultParts: readonly InlineToolResultPart[];
103
+ readonly trailingInlineToolResultParts: readonly InlineToolResultPart[];
103
104
  }
104
105
  interface StreamActionEmissionOptions {
105
106
  readonly excludedActionToolNames: ReadonlySet<string>;
@@ -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{createRuntimeActionRequestFromToolCall,resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromValue}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.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,c){let l=``,u=``,d=`stop`,f,p=new Set,m=new Set,h=new Set,g=new Set,_=createProviderStreamActionBatch({emitFn:a,state:o}),v=new Set,y=[],b=[],flushCurrentMessage=async()=>{u.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``)},emitActionRequest=async e=>{m.has(e.callId)||(u.trim().length>0&&await flushCurrentMessage(),m.add(e.callId),await a(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},collectProviderToolCall=async e=>{g.has(e.toolCallId)||(g.add(e.toolCallId),!m.has(e.toolCallId)&&(m.add(e.toolCallId),u.trim().length>0&&await flushCurrentMessage(),_.observe({callId:e.toolCallId,input:resolveToolCallInputObject(e.input,{callId:e.toolCallId,toolName:e.toolName}),kind:`tool-call`,toolName:e.toolName})))},emitActionResult=async e=>{h.has(e.callId)||(h.add(e.callId),await a(createActionResultEvent({result:e,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitToolCall=async e=>{if(!(c===void 0||e.invalid===!0||c.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:c.tools}))}catch(e){if(e instanceof TypeError)return;throw e}};for await(let t of s)if(f===void 0)switch(t.type){case`reasoning-delta`:await _.flush(),l+=t.text,await a(createReasoningAppendedEvent({reasoningDelta:t.text,reasoningSoFar:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:await _.flush(),l.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l=``),u+=t.text,await a(createMessageAppendedEvent({messageDelta:t.text,messageSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let e=t;p.add(e.toolCallId),e.providerExecuted===!0?await collectProviderToolCall(e):(await _.flush(),await emitToolCall(e));break}case`tool-result`:{let e=t;if(e.preliminary===!0)break;if(e.providerExecuted===!0){await collectProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await _.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(e));break}if(p.has(t.toolCallId)){if(isInlineAuthorizationToolResult(e))break;m.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId));break}if(await _.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){v.add(t.toolCallId),y.push(e);break}await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId);let n=e.output;b.push({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n??null}});break}case`tool-error`:{let n=t;n.providerExecuted===!0?(await collectProviderToolCall(n),await _.flush(),await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName}))):m.has(n.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromValue({callId:n.toolCallId,isError:!0,output:toError(n.error),toolName:n.toolName})),v.add(n.toolCallId));break}case`finish-step`:d=normalizeAssistantStepFinishReason(t.finishReason),await _.flush();break;case`error`:f=toError(t.error);break;default:break}if(await _.flush(),f!==void 0)throw f;return l.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d!==`tool-calls`&&hasEmptyDeliverySentinel(u)?await a(createMessageCompletedEvent({finishReason:d,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):u.trim().length>0&&await a(createMessageCompletedEvent({finishReason:d,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:m,handledInlineToolResultCallIds:v,inlineAuthorizationResults:y,inlineToolResultParts:b}}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{createRuntimeActionRequestFromToolCall,resolveToolCallInputObject}from"#harness/runtime-actions.js";import{isAuthorizationSignal,isPendingAuthorizationToolOutput}from"#harness/authorization.js";import{hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createRuntimeToolResultFromStepResult,createRuntimeToolResultFromToolError,createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{createProviderStreamActionBatch}from"#harness/stream-actions.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,c){let l=``,u=``,d=`stop`,f,p=new Set,m=new Set,h=new Set,g=new Set,_=createProviderStreamActionBatch({emitFn:a,state:o}),v=new Set,y=[],b=[],x=[],flushCurrentMessage=async()=>{u.length!==0&&(await a(createMessageCompletedEvent({finishReason:`tool-calls`,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),u=``)},emitActionRequest=async e=>{m.has(e.callId)||(u.trim().length>0&&await flushCurrentMessage(),m.add(e.callId),await a(createActionsRequestedEvent({actions:[e],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},collectProviderToolCall=async e=>{g.has(e.toolCallId)||(g.add(e.toolCallId),!m.has(e.toolCallId)&&(m.add(e.toolCallId),u.trim().length>0&&await flushCurrentMessage(),_.observe({callId:e.toolCallId,input:resolveToolCallInputObject(e.input,{callId:e.toolCallId,toolName:e.toolName}),kind:`tool-call`,toolName:e.toolName})))},emitActionResult=async e=>{h.has(e.callId)||(h.add(e.callId),await a(createActionResultEvent({result:e,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})))},emitToolCall=async e=>{if(!(c===void 0||e.invalid===!0||c.excludedActionToolNames.has(e.toolName)))try{await emitActionRequest(createRuntimeActionRequestFromToolCall({toolCall:e,tools:c.tools}))}catch(e){if(e instanceof TypeError)return;throw e}};for await(let t of s)if(f===void 0)switch(t.type){case`reasoning-delta`:await _.flush(),l+=t.text,await a(createReasoningAppendedEvent({reasoningDelta:t.text,reasoningSoFar:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`text-delta`:await _.flush(),l.trim().length>0&&(await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),l=``),u+=t.text,await a(createMessageAppendedEvent({messageDelta:t.text,messageSoFar:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));break;case`tool-call`:{let e=t;p.add(e.toolCallId),e.providerExecuted===!0?await collectProviderToolCall(e):(await _.flush(),await emitToolCall(e));break}case`tool-result`:{let e=t;if(e.preliminary===!0)break;if(e.providerExecuted===!0){await collectProviderToolCall({input:`input`in e?e.input:void 0,toolCallId:e.toolCallId,toolName:e.toolName}),await _.flush(),await emitActionResult(createRuntimeToolResultFromStepResult(e));break}if(p.has(t.toolCallId)){if(isInlineAuthorizationToolResult(e))break;m.has(t.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId));break}if(await _.flush(),await flushCurrentMessage(),isInlineAuthorizationToolResult(e)){v.add(t.toolCallId),y.push(e);break}await emitActionResult(createRuntimeToolResultFromStepResult(e)),v.add(t.toolCallId);let n=e.output;b.push({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n??null}});break}case`tool-error`:{let e=t;e.providerExecuted===!0?(await collectProviderToolCall(e),await _.flush(),await emitActionResult(createRuntimeToolResultFromToolError(e))):m.has(e.toolCallId)&&(await emitActionResult(createRuntimeToolResultFromToolError(e)),v.add(e.toolCallId),x.push(createToolResultMessagePartFromToolError(e)));break}case`finish-step`:d=normalizeAssistantStepFinishReason(t.finishReason),await _.flush();break;case`error`:f=toError(t.error);break;default:break}if(await _.flush(),f!==void 0)throw f;return l.trim().length>0&&await a(createReasoningCompletedEvent({reasoning:l,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),d!==`tool-calls`&&hasEmptyDeliverySentinel(u)?await a(createMessageCompletedEvent({finishReason:d,message:null,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})):u.trim().length>0&&await a(createMessageCompletedEvent({finishReason:d,message:u,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{emittedActionCallIds:m,handledInlineToolResultCallIds:v,inlineAuthorizationResults:y,inlineToolResultParts:b,trailingInlineToolResultParts:x}}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
- 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)&&!c.emittedActionCallIds?.has(e.toolCallId)).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
+ 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,createRuntimeToolResultFromToolError}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)&&!c.emittedActionCallIds?.has(e.toolCallId)).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 e.content??[])n.type!==`tool-error`||n.providerExecuted===!0||t.has(n.toolCallId)||t.set(n.toolCallId,createRuntimeToolResultFromToolError(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{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{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt,getPendingWorkflowInterrupt,setPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowRuntimeActionInterrupts,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.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{getWorkflowContinuationSecurity,readWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{buildWorkflowHostTools}from"#harness/workflow-sandbox.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{buildDynamicTools}from"#context/build-dynamic-tools.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{createWorkflowLifecycle}from"#harness/workflow-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{accumulateTurnUsage,getSessionTokenLimitViolation,getSessionTokenUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{normalizeProviderToolHistory}from"#harness/provider-tool-history.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{getAdvertisedTools}from"#harness/advertised-tools.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{buildToolApproval,buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{continueWorkflowSandboxInterrupt,getWorkflowSandboxInterrupt,unwrapWorkflowSandboxResult}from"#shared/workflow-sandbox.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 D=await resolvePendingRuntimeActions({emit:n,session:b,stepInput:S.input});if(D.outcome===`unresolved`)return{next:null,session:D.session};b=D.session;let A=resolvePendingInput({history:D.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:b,stepInput:S.input});if(A.outcome===`unresolved`)return n&&A.deferredMessage===!0&&hasStepInput(v)?(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),x=await emitTurnEpilogue(n,x,t.mode),{next:null,session:setHarnessEmissionState(A.session,x)}):{next:null,session:A.session};if(n&&A.rejectedActions)for(let e of A.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:A.rejectedActions.event.sequence,stepIndex:A.rejectedActions.event.stepIndex,turnId:A.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=A.session;let j=A.messages;if(S.input?.context!==void 0)for(let e of S.input.context)j.push({content:e,role:`user`});if(S.input?.message!==void 0&&!A.deferredMessage&&!A.consumedMessage){let e=await stageAttachmentsToSandbox(S.input.message);j.push({content:e,role:`user`})}let M=await t.resolveModel(b.agent.modelReference),N=detectPromptCachePath(M),P=N.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,F=buildGatewayAttributionHeaders(M,t.runtimeIdentity);({messages:j,session:b}=await maybeCompact({emit:n,emissionState:x,headers:F,messages:j,model:M,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:b,telemetry:enrichTelemetry(c,p)??void 0}));let I=getApprovedTools(b),L=contextStorage.getStore(),R=b.outputSchema===void 0&&L!==void 0&&isScheduleAppAuth(L.get(AuthKey))&&L.get(ParentSessionKey)===void 0,z=await hydrateSandboxAttachments(j),B=[],V=[];for(let e of z)e.role===`system`?B.push(e):V.push(e);if(L!==void 0){B.push(...buildDynamicInstructionMessages(L));let e=L.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&B.push({role:`system`,content:e})}R&&B.push({role:`system`,content:CONDITIONAL_DELIVERY_INSTRUCTION});let H=V,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=b.agent.system?[{role:`system`,content:b.agent.system}]:[],r=B.length>0||t.length>0?[...t,...n,...B]:void 0,i=r!==void 0&&P?applySystemCacheBreakpoint(r,P):r??b.agent.system??void 0;return{instructions:i,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:c,emissionState:x,environment,modelInput:{instructions:i,messages:H},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?[...H,{role:`user`,content:e.trailingUserNote}]:H,s=getAdvertisedTools({session:b,tools:t.tools}),u=await buildToolSetWithProviderTools({approvedTools:I,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:b.agent.modelReference,tools:s});if(L!==void 0){let n=getAdvertisedTools({session:b,tools:buildDynamicTools(L)}),r=buildToolSetFromDefinitions({approvedTools:I,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=n===void 0?void 0:({tools:e})=>createWorkflowLifecycle({emit:n,emissionState:x,tools:e}),f=t.workflow===!0?{lifecycle:d}:void 0,h=await getAdvertisedTools({modelTools:u,session:b,tools:s,workflow:f});b=h.session;let g=h.modelTools,_=P?applyLastToolCacheBreakpoint(g,P):g,v=buildStepHooks({cachePath:N,emit:n,emissionState:x,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:P,session:b}),y=new ToolLoopAgent({headers:F,instructions:i,model:M,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:v.onStepFinish,prepareStep:v.prepareStep,reasoning:b.agent.reasoning,runtimeContext:a,stopWhen:isStepCount(1),telemetry:enrichTelemetry(c,p,a),toolApproval:buildToolApproval(g),tools:_}),executeModelCall=async()=>{if(n){let e=[...t.tools].filter(([e,t])=>t.runtimeAction!==void 0&&s.get(e)===void 0).map(([e])=>e),r=new Set([ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...e]),i=await y.stream({messages:o}),{emittedActionCallIds:a,handledInlineToolResultCallIds:c,inlineAuthorizationResults:u,inlineToolResultParts:d}=await emitStreamContent(n,x,i.fullStream,{excludedActionToolNames:r,tools:t.tools}),f=await v.stepResult;if(isEmptyModelResponse(f)&&d.length===0&&u.length===0)throw new EmptyModelResponseError;if(await emitStepActions(n,x,f,{emittedActionCallIds:a,excludedActionToolNames:r,handledInlineToolResultCallIds:c,tools:s}),d.length>0||u.length>0){let e=f.toolResults,t=new Map(e.map(e=>[e.toolCallId,e]));for(let e of u)t.set(e.toolCallId,e);return{content:f.content,finishReason:f.finishReason,response:{...f.response,...d.length>0?{messages:[{role:`tool`,content:[...d]},...f.response.messages]}:{}},text:f.text,toolCalls:f.toolCalls,toolResults:[...t.values()],usage:f.usage}}return f}await y.generate({messages:o});let e=await v.stepResult;if(isEmptyModelResponse(e))throw new EmptyModelResponseError;return e};return runModelCallWithRetries(()=>executeModelCall().catch(rethrowNoOutputAsEmptyResponse),{sessionId:b.sessionId,turnId:x.turnId})},U=prepareModelCallInput();n&&await emitStepStarted(n,x,j);let W=await continuePendingWorkflowInterrupt({childResults:S.input?.runtimeActionResults,config:t,emit:n,emissionState:x,runStep,session:b});if(W!==null)return W;let G=getSessionTokenLimitViolation(b);if(G!==null)return failSessionTokenLimit({config:t,emit:n,emissionState:x,session:b,violation:G});let K;try{K=await runOneModelCall({preparedInput:U,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:R,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId})]});if(a.outcome===`recovered`)K=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 q=accumulateTurnUsage({previous:getTurnUsageState(b.state),turnId:x.turnId,usage:extractTokenUsageDelta(K.usage)});b=setTurnUsageState(b,q);let J;try{J=formatLanguageModelGatewayId(M)}catch{J=void 0}return await setEveAttributes({"$eve.model":J,"$eve.input_tokens":q.inputTokens,"$eve.output_tokens":q.outputTokens,"$eve.cache_read_tokens":q.cacheReadTokens,"$eve.cache_write_tokens":q.cacheWriteTokens,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:x,promptMessages:j,result:K,runStep,session:b})}return runStep}function extractTokenUsageDelta(e){if(e!==void 0)return{cacheReadTokens:e.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:e.inputTokenDetails?.cacheWriteTokens,inputTokens:e.inputTokens,outputTokens:e.outputTokens}}function formatSessionTokenLimitMessage(e){return`The session reached its configured ${e} token limit.`}async function failSessionTokenLimit(e){let t=getSessionTokenUsage(e.session),n=formatSessionTokenLimitMessage(e.violation.kind),r={inputTokens:t.inputTokens,kind:e.violation.kind,limit:e.violation.limit,outputTokens:t.outputTokens,usedTokens:e.violation.usedTokens};return e.emit&&await emitFailedStep(e.emit,e.emissionState,{code:`SESSION_TOKEN_LIMIT_REACHED`,details:r,message:n,sessionId:e.session.sessionId}),{next:{done:!0,isError:e.config.mode===`task`?!0:void 0,output:e.config.mode===`task`?n:``},session:e.session}}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=new Set;for(let e of[...i.content??[],...i.toolResults??[]])(e.type===`tool-result`||e.type===`tool-error`)&&e.providerExecuted===!0&&f.add(e.toolCallId);let p=normalizeProviderToolHistory({messages:u,providerExecutedOutcomeIds:f}),m=p.messages,h={...s,compaction:createNextCompactionConfig(s.compaction,r,i)},g=t.workflow===!0?readWorkflowContinuationSecurity(h):void 0;if(g!==void 0){let e=await getWorkflowSandboxInterrupt(i,g);if(e!==void 0){if(!isWorkflowRuntimeActionInterrupt(e))throw Error(`Unsupported Workflow interrupt kind "${e.payload.kind}".`);return parkOnWorkflowInterrupt({baseSession:h,emissionState:o,interrupt:e,promptMessages:r,responseMessages:m})}}let _=extractToolApprovalInputRequests({content:i.content??[]}),y=new Set(_.map(e=>e.action.callId)),b=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:y}),S=[..._,...b],C=getAdvertisedTools({session:h,tools:t.tools}),w=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).filter(e=>C.get(e.toolName)?.runtimeAction===void 0?(log.warn(`runtime action tool call blocked because tool is not advertised`,{callId:e.toolCallId,sessionId:h.sessionId,toolName:e.toolName}),!1):!0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:C}));if(w.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:w,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:m,session:{...h,history:[...r]}}),o)};if(S.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:S,responseMessages:m,session:{...h,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:S,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 T=findAuthorizationSignalFromToolResults(i.toolResults);if(T){let{challenges:e}=T;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({...h,history:[...r],state:setPendingAuthorization(h.state,{challenges:e})},o)}}let E=m,O=[...r,...E],k={...h,history:O};return!(k.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(E.at(-1)?.role===`tool`||p.outcomeEndsResponse||hasDeferredStepInput(k))?(n&&(o=advanceStep(o),k=setHarnessEmissionState(k,o)),{next:a,session:k}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:k.outputSchema,session:k,stepOutput:d}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:k.outputSchema,session:k})}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 continuePendingWorkflowInterrupt(e){let t=getPendingWorkflowInterrupt(e.session.state);if(t===void 0)return null;let n=t.interrupt;if(!isWorkflowRuntimeActionInterrupt(n))throw Error(`Unsupported Workflow interrupt kind "${n.payload.kind}".`);let i=e.emit===void 0?void 0:createWorkflowLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools}),a=getWorkflowContinuationSecurity(e.session),o;try{let t=buildWorkflowHostTools({tools:e.config.tools}),r=e.childResults??[],s=n,c=0;for(;;){o=await continueWorkflowSandboxInterrupt({continuationSecurity:a,interrupt:s,lifecycle:i,resolution:r[c]?.output,tools:t});let e=await unwrapWorkflowSandboxResult(o,a);if(e.status!==`interrupted`||!isWorkflowRuntimeActionInterrupt(e.interrupt)||c+1>=r.length)break;let n=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(n===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);c++,s=n}}catch(e){logError(log,`Workflow interrupt continuation failed`,e),o={error:`workflow_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let s=await unwrapWorkflowSandboxResult(o,a),c=s.status===`interrupted`?s.interrupt:s.output,l=replaceWorkflowToolResult([...e.session.history,...t.responseMessages],n.outerToolCallId,c),u=clearPendingWorkflowInterrupt({...e.session,history:l});if(s.status===`interrupted`){if(!isWorkflowRuntimeActionInterrupt(s.interrupt))throw Error(`Unsupported Workflow interrupt kind "${s.interrupt.payload.kind}".`);let t=e.session.history.length,n=l.slice(0,t),r=l.slice(t);return u={...u,history:n},parkOnWorkflowInterrupt({baseSession:u,emissionState:e.emissionState,interrupt:s.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:u}}function replaceWorkflowToolResult(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}})}function parkOnWorkflowInterrupt(e){let t=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(t===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);let n={...e.baseSession,history:[...e.promptMessages]};return{next:null,session:setHarnessEmissionState(setPendingWorkflowInterrupt({interrupt:t,responseMessages:e.responseMessages,session:n}),e.emissionState)}}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{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt,getPendingWorkflowInterrupt,setPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowRuntimeActionInterrupts,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.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{getWorkflowContinuationSecurity,readWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{buildWorkflowHostTools}from"#harness/workflow-sandbox.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{buildDynamicTools}from"#context/build-dynamic-tools.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{createWorkflowLifecycle}from"#harness/workflow-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{accumulateTurnUsage,getSessionTokenLimitViolation,getSessionTokenUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation-runtime-context.js";import{getInstrumentationConfig}from"#harness/instrumentation-config.js";import{normalizeProviderToolHistory}from"#harness/provider-tool-history.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration}from"#harness/otel-integration.js";import{getAdvertisedTools}from"#harness/advertised-tools.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions,isInvalidToolCall}from"#harness/step-hooks.js";import{buildToolApproval,buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{continueWorkflowSandboxInterrupt,getWorkflowSandboxInterrupt,unwrapWorkflowSandboxResult}from"#shared/workflow-sandbox.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 D=await resolvePendingRuntimeActions({emit:n,session:b,stepInput:S.input});if(D.outcome===`unresolved`)return{next:null,session:D.session};b=D.session;let A=resolvePendingInput({history:D.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:b,stepInput:S.input});if(A.outcome===`unresolved`)return n&&A.deferredMessage===!0&&hasStepInput(v)?(x=await emitTurnPreamble(n,v??{},x,t.runtimeIdentity),x=await emitTurnEpilogue(n,x,t.mode),{next:null,session:setHarnessEmissionState(A.session,x)}):{next:null,session:A.session};if(n&&A.rejectedActions)for(let e of A.rejectedActions.results)await n(createActionResultEvent({rejected:!0,result:e,sequence:A.rejectedActions.event.sequence,stepIndex:A.rejectedActions.event.stepIndex,turnId:A.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=A.session;let j=A.messages;if(S.input?.context!==void 0)for(let e of S.input.context)j.push({content:e,role:`user`});if(S.input?.message!==void 0&&!A.deferredMessage&&!A.consumedMessage){let e=await stageAttachmentsToSandbox(S.input.message);j.push({content:e,role:`user`})}let M=await t.resolveModel(b.agent.modelReference),N=detectPromptCachePath(M),P=N.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,F=buildGatewayAttributionHeaders(M,t.runtimeIdentity);({messages:j,session:b}=await maybeCompact({emit:n,emissionState:x,headers:F,messages:j,model:M,onCompaction:t.onCompaction,resolveModel:t.resolveModel,session:b,telemetry:enrichTelemetry(c,p)??void 0}));let I=getApprovedTools(b),L=contextStorage.getStore(),R=b.outputSchema===void 0&&L!==void 0&&isScheduleAppAuth(L.get(AuthKey))&&L.get(ParentSessionKey)===void 0,z=await hydrateSandboxAttachments(j),B=[],V=[];for(let e of z)e.role===`system`?B.push(e):V.push(e);if(L!==void 0){B.push(...buildDynamicInstructionMessages(L));let e=L.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&B.push({role:`system`,content:e})}R&&B.push({role:`system`,content:CONDITIONAL_DELIVERY_INSTRUCTION});let H=V,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=b.agent.system?[{role:`system`,content:b.agent.system}]:[],r=B.length>0||t.length>0?[...t,...n,...B]:void 0,i=r!==void 0&&P?applySystemCacheBreakpoint(r,P):r??b.agent.system??void 0;return{instructions:i,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:c,emissionState:x,environment,modelInput:{instructions:i,messages:H},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?[...H,{role:`user`,content:e.trailingUserNote}]:H,s=getAdvertisedTools({session:b,tools:t.tools}),u=await buildToolSetWithProviderTools({approvedTools:I,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:b.agent.modelReference,tools:s});if(L!==void 0){let n=getAdvertisedTools({session:b,tools:buildDynamicTools(L)}),r=buildToolSetFromDefinitions({approvedTools:I,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=n===void 0?void 0:({tools:e})=>createWorkflowLifecycle({emit:n,emissionState:x,tools:e}),f=t.workflow===!0?{lifecycle:d}:void 0,h=await getAdvertisedTools({modelTools:u,session:b,tools:s,workflow:f});b=h.session;let g=h.modelTools,_=P?applyLastToolCacheBreakpoint(g,P):g,v=buildStepHooks({cachePath:N,emit:n,emissionState:x,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:P,session:b}),y=new ToolLoopAgent({headers:F,instructions:i,model:M,onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownModelCallConfigError(e.error)===null&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:v.onStepFinish,prepareStep:v.prepareStep,reasoning:b.agent.reasoning,runtimeContext:a,stopWhen:isStepCount(1),telemetry:enrichTelemetry(c,p,a),toolApproval:buildToolApproval(g),tools:_}),executeModelCall=async()=>{if(n){let e=[...t.tools].filter(([e,t])=>t.runtimeAction!==void 0&&s.get(e)===void 0).map(([e])=>e),r=new Set([ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...e]),i=await y.stream({messages:o}),{emittedActionCallIds:a,handledInlineToolResultCallIds:c,inlineAuthorizationResults:u,inlineToolResultParts:d,trailingInlineToolResultParts:f}=await emitStreamContent(n,x,i.fullStream,{excludedActionToolNames:r,tools:t.tools}),p=await v.stepResult;if(isEmptyModelResponse(p)&&d.length===0&&u.length===0&&f.length===0)throw new EmptyModelResponseError;if(await emitStepActions(n,x,p,{emittedActionCallIds:a,excludedActionToolNames:r,handledInlineToolResultCallIds:c,tools:s}),d.length>0||u.length>0||f.length>0){let e=p.toolResults,t=new Map(e.map(e=>[e.toolCallId,e]));for(let e of u)t.set(e.toolCallId,e);return{content:p.content,finishReason:p.finishReason,response:{...p.response,...d.length>0||f.length>0?{messages:insertInlineToolResultMessages({append:f,prepend:d,responseMessages:p.response.messages})}:{}},text:p.text,toolCalls:p.toolCalls,toolResults:[...t.values()],usage:p.usage}}return p}await y.generate({messages:o});let e=await v.stepResult;if(isEmptyModelResponse(e))throw new EmptyModelResponseError;return e};return runModelCallWithRetries(()=>executeModelCall().catch(rethrowNoOutputAsEmptyResponse),{sessionId:b.sessionId,turnId:x.turnId})},U=prepareModelCallInput();n&&await emitStepStarted(n,x,j);let W=await continuePendingWorkflowInterrupt({childResults:S.input?.runtimeActionResults,config:t,emit:n,emissionState:x,runStep,session:b});if(W!==null)return W;let G=getSessionTokenLimitViolation(b);if(G!==null)return failSessionTokenLimit({config:t,emit:n,emissionState:x,session:b,violation:G});let K;try{K=await runOneModelCall({preparedInput:U,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:R,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:b.sessionId,turnId:x.turnId})]});if(a.outcome===`recovered`)K=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:t.mode===`task`?{done:!0,isError:!0,output:p}:{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 q=accumulateTurnUsage({previous:getTurnUsageState(b.state),turnId:x.turnId,usage:extractTokenUsageDelta(K.usage)});b=setTurnUsageState(b,q);let J;try{J=formatLanguageModelGatewayId(M)}catch{J=void 0}return await setEveAttributes({"$eve.model":J,"$eve.input_tokens":q.inputTokens,"$eve.output_tokens":q.outputTokens,"$eve.cache_read_tokens":q.cacheReadTokens,"$eve.cache_write_tokens":q.cacheWriteTokens,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:n,emissionState:x,promptMessages:j,result:K,runStep,session:b})}return runStep}function extractTokenUsageDelta(e){if(e!==void 0)return{cacheReadTokens:e.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:e.inputTokenDetails?.cacheWriteTokens,inputTokens:e.inputTokens,outputTokens:e.outputTokens}}function formatSessionTokenLimitMessage(e){return`The session reached its configured ${e} token limit.`}async function failSessionTokenLimit(e){let t=getSessionTokenUsage(e.session),n=formatSessionTokenLimitMessage(e.violation.kind),r={inputTokens:t.inputTokens,kind:e.violation.kind,limit:e.violation.limit,outputTokens:t.outputTokens,usedTokens:e.violation.usedTokens};return e.emit&&await emitFailedStep(e.emit,e.emissionState,{code:`SESSION_TOKEN_LIMIT_REACHED`,details:r,message:n,sessionId:e.session.sessionId}),{next:{done:!0,isError:e.config.mode===`task`?!0:void 0,output:e.config.mode===`task`?n:``},session:e.session}}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}}function insertInlineToolResultMessages(e){let t=extractToolResultCallIds(e.responseMessages),n=e.prepend.filter(e=>!t.has(e.toolCallId)),r=e.append.filter(e=>!t.has(e.toolCallId));return[...n.length>0?[{role:`tool`,content:[...n]}]:[],...e.responseMessages,...r.length>0?[{role:`tool`,content:[...r]}]:[]]}function extractToolResultCallIds(e){let t=new Set;for(let n of e)if(!(n.role!==`tool`||!Array.isArray(n.content)))for(let e of n.content)e.type===`tool-result`&&t.add(e.toolCallId);return 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=new Set;for(let e of[...i.content??[],...i.toolResults??[]])(e.type===`tool-result`||e.type===`tool-error`)&&e.providerExecuted===!0&&f.add(e.toolCallId);let p=normalizeProviderToolHistory({messages:u,providerExecutedOutcomeIds:f}),m=p.messages,h={...s,compaction:createNextCompactionConfig(s.compaction,r,i)},g=t.workflow===!0?readWorkflowContinuationSecurity(h):void 0;if(g!==void 0){let e=await getWorkflowSandboxInterrupt(i,g);if(e!==void 0){if(!isWorkflowRuntimeActionInterrupt(e))throw Error(`Unsupported Workflow interrupt kind "${e.payload.kind}".`);return parkOnWorkflowInterrupt({baseSession:h,emissionState:o,interrupt:e,promptMessages:r,responseMessages:m})}}let _=extractToolApprovalInputRequests({content:i.content??[]}),y=new Set(_.map(e=>e.action.callId)),b=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:y}),S=[..._,...b],C=getAdvertisedTools({session:h,tools:t.tools}),w=(i.toolCalls??[]).filter(e=>!isInvalidToolCall(e)).filter(e=>t.tools.get(e.toolName)?.runtimeAction!==void 0).filter(e=>C.get(e.toolName)?.runtimeAction===void 0?(log.warn(`runtime action tool call blocked because tool is not advertised`,{callId:e.toolCallId,sessionId:h.sessionId,toolName:e.toolName}),!1):!0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:C}));if(w.length>0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:w,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:m,session:{...h,history:[...r]}}),o)};if(S.length>0){let e=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:S,responseMessages:m,session:{...h,history:[...r]}});return n&&(await n(createInputRequestedEvent({requests:S,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 T=findAuthorizationSignalFromToolResults(i.toolResults);if(T){let{challenges:e}=T;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({...h,history:[...r],state:setPendingAuthorization(h.state,{challenges:e})},o)}}let E=m,O=[...r,...E],k={...h,history:O};return!(k.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(E.at(-1)?.role===`tool`||p.outcomeEndsResponse||hasDeferredStepInput(k))?(n&&(o=advanceStep(o),k=setHarnessEmissionState(k,o)),{next:a,session:k}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:k.outputSchema,session:k,stepOutput:d}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:k.outputSchema,session:k})}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 continuePendingWorkflowInterrupt(e){let t=getPendingWorkflowInterrupt(e.session.state);if(t===void 0)return null;let n=t.interrupt;if(!isWorkflowRuntimeActionInterrupt(n))throw Error(`Unsupported Workflow interrupt kind "${n.payload.kind}".`);let i=e.emit===void 0?void 0:createWorkflowLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.config.tools}),a=getWorkflowContinuationSecurity(e.session),o;try{let t=buildWorkflowHostTools({tools:e.config.tools}),r=e.childResults??[],s=n,c=0;for(;;){o=await continueWorkflowSandboxInterrupt({continuationSecurity:a,interrupt:s,lifecycle:i,resolution:r[c]?.output,tools:t});let e=await unwrapWorkflowSandboxResult(o,a);if(e.status!==`interrupted`||!isWorkflowRuntimeActionInterrupt(e.interrupt)||c+1>=r.length)break;let n=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(n===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);c++,s=n}}catch(e){logError(log,`Workflow interrupt continuation failed`,e),o={error:`workflow_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let s=await unwrapWorkflowSandboxResult(o,a),c=s.status===`interrupted`?s.interrupt:s.output,l=replaceWorkflowToolResult([...e.session.history,...t.responseMessages],n.outerToolCallId,c),u=clearPendingWorkflowInterrupt({...e.session,history:l});if(s.status===`interrupted`){if(!isWorkflowRuntimeActionInterrupt(s.interrupt))throw Error(`Unsupported Workflow interrupt kind "${s.interrupt.payload.kind}".`);let t=e.session.history.length,n=l.slice(0,t),r=l.slice(t);return u={...u,history:n},parkOnWorkflowInterrupt({baseSession:u,emissionState:e.emissionState,interrupt:s.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:u}}function replaceWorkflowToolResult(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}})}function parkOnWorkflowInterrupt(e){let t=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(t===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);let n={...e.baseSession,history:[...e.promptMessages]};return{next:null,session:setHarnessEmissionState(setPendingWorkflowInterrupt({interrupt:t,responseMessages:e.responseMessages,session:n}),e.emissionState)}}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};