eve 0.18.1 → 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.
- package/CHANGELOG.md +20 -0
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/@chat-adapter/slack/index.js +29 -32
- package/dist/src/compiled/@chat-adapter/twilio/LICENSE +9 -0
- package/dist/src/compiled/@chat-adapter/twilio/api.d.ts +108 -0
- package/dist/src/compiled/@chat-adapter/twilio/api.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/format.d.ts +12 -0
- package/dist/src/compiled/@chat-adapter/twilio/format.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/index.d.ts +84 -0
- package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/voice.d.ts +44 -0
- package/dist/src/compiled/@chat-adapter/twilio/voice.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/webhook.d.ts +18 -0
- package/dist/src/compiled/@chat-adapter/twilio/webhook.js +1 -0
- package/dist/src/compiled/_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js +1 -0
- package/dist/src/compiled/_chunks/node/chunk-PFJ2G64A-B79fSABi.js +1 -0
- package/dist/src/compiled/_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js +1 -0
- package/dist/src/compiled/_chunks/node/dist-RHRJZ03Q.js +4 -0
- package/dist/src/execution/sandbox/bindings/vercel-create-sdk.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-credentials.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-user-agent.d.ts +6 -0
- package/dist/src/execution/sandbox/bindings/vercel-user-agent.js +1 -0
- package/dist/src/harness/action-result-helpers.d.ts +11 -1
- package/dist/src/harness/action-result-helpers.js +1 -1
- package/dist/src/harness/emission.d.ts +1 -0
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/routes/index.d.ts +7 -2
- package/dist/src/internal/nitro/routes/index.js +78 -48
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +141 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +3 -0
- package/dist/src/public/channels/chat-sdk/index.d.ts +1 -0
- package/dist/src/public/channels/chat-sdk/index.js +1 -0
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/index.d.ts +2 -0
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/twilio/api.d.ts +8 -29
- package/dist/src/public/channels/twilio/api.js +1 -1
- package/dist/src/public/channels/twilio/inbound.d.ts +10 -19
- package/dist/src/public/channels/twilio/inbound.js +2 -2
- package/dist/src/public/channels/twilio/routing.d.ts +13 -0
- package/dist/src/public/channels/twilio/routing.js +1 -0
- package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
- package/dist/src/public/channels/twilio/twiml.d.ts +5 -36
- package/dist/src/public/channels/twilio/twiml.js +1 -1
- package/dist/src/public/channels/twilio/verify.d.ts +12 -33
- package/dist/src/public/channels/twilio/verify.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- 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(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}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 +1 @@
|
|
|
1
|
-
async function createVercelEveImageSandbox(e){let{image:t,runtime:n,source:r,...i}=e.createOptions;return r?.type===`snapshot`?await e.sandboxModule.Sandbox.create({...i,source:r}):await e.sandboxModule.Sandbox.create({...i,source:r,image:VERCEL_EVE_SANDBOX_IMAGE})}const VERCEL_EVE_SANDBOX_IMAGE=`vercel/eve:latest`;export{createVercelEveImageSandbox};
|
|
1
|
+
import{getVercelSandboxFetch}from"#execution/sandbox/bindings/vercel-credentials.js";async function createVercelEveImageSandbox(e){let{image:t,runtime:n,source:r,...i}=e.createOptions,a=getVercelSandboxFetch(e.createOptions);return r?.type===`snapshot`?await e.sandboxModule.Sandbox.create({...i,source:r,fetch:a}):await e.sandboxModule.Sandbox.create({...i,source:r,image:VERCEL_EVE_SANDBOX_IMAGE,fetch:a})}const VERCEL_EVE_SANDBOX_IMAGE=`vercel/eve:latest`;export{createVercelEveImageSandbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getVercelOidcToken}from"#compiled/@vercel/oidc/index.js";function getVercelSandboxFetch(e){
|
|
1
|
+
import{getVercelOidcToken}from"#compiled/@vercel/oidc/index.js";import{withEveSandboxUserAgent}from"#execution/sandbox/bindings/vercel-user-agent.js";function getVercelSandboxFetch(e){let n=e.fetch;return withEveSandboxUserAgent(n??globalThis.fetch)}async function getVercelSandboxCredentials(t){let n=readNonEmptyString(t,`teamId`)??readNonEmptyEnvironmentVariable(`VERCEL_TEAM_ID`)??readNonEmptyEnvironmentVariable(`VERCEL_ORG_ID`),r=readNonEmptyString(t,`projectId`)??readNonEmptyEnvironmentVariable(`VERCEL_PROJECT_ID`),i=readNonEmptyString(t,`token`)??readNonEmptyEnvironmentVariable(`VERCEL_OIDC_TOKEN`)??readNonEmptyEnvironmentVariable(`VERCEL_TOKEN`);return i&&n&&r?{projectId:r,teamId:n,token:i}:getVercelSandboxCredentialsFromOidcToken(await getVercelOidcToken({project:r,team:n}))}function readNonEmptyString(e,t){let n=e[t];return typeof n==`string`&&n.trim().length>0?n.trim():void 0}function readNonEmptyEnvironmentVariable(e){let t=process.env[e];return typeof t==`string`&&t.trim().length>0?t.trim():void 0}function getVercelSandboxCredentialsFromOidcToken(e){let t=e.split(`.`)[1];if(t===void 0)throw Error(`Invalid Vercel OIDC token: missing payload.`);let n=JSON.parse(Buffer.from(base64UrlToBase64(t),`base64`).toString(`utf8`)),r=typeof n.owner_id==`string`?n.owner_id:void 0,i=typeof n.project_id==`string`?n.project_id:void 0;if(r===void 0||i===void 0)throw Error(`Invalid Vercel OIDC token: missing owner_id or project_id.`);return{projectId:i,teamId:r,token:e}}function base64UrlToBase64(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t.padEnd(Math.ceil(t.length/4)*4,`=`)}export{getVercelSandboxCredentials,getVercelSandboxFetch};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function eveSandboxUserAgentToken(): string;
|
|
2
|
+
/**
|
|
3
|
+
* Wraps a `fetch` implementation so every request's `user-agent` ends with the
|
|
4
|
+
* {@link eveSandboxUserAgentToken} (e.g.: eve/0.18.1).
|
|
5
|
+
*/
|
|
6
|
+
export declare function withEveSandboxUserAgent(inner?: typeof globalThis.fetch): typeof globalThis.fetch;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveInstalledPackageInfo}from"#internal/application/package.js";function eveSandboxUserAgentToken(){let{name:t,version:n}=resolveInstalledPackageInfo();return`${t}/${n}`}function withEveSandboxUserAgent(e=globalThis.fetch){let t=eveSandboxUserAgentToken();return(n,r)=>{let i=new Headers(r?.headers??(typeof n==`object`&&n&&`headers`in n?n.headers:void 0)),a=i.get(`user-agent`);return i.set(`user-agent`,a?`${a} ${t}`:t),e(n,{...r,headers:i})}}export{eveSandboxUserAgentToken,withEveSandboxUserAgent};
|
|
@@ -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(
|
|
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,
|
|
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};
|