@novu/framework 2.13.1-rc.72c80d5b17 → 2.13.1
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/README.md +2 -2
- package/dist/cjs/{agent.types-B5VnP69G.d.cts → agent.types-crcJBtCy.d.cts} +154 -3
- package/dist/cjs/ai-sdk/index.cjs +4 -1
- package/dist/cjs/ai-sdk/index.d.cts +16 -5
- package/dist/cjs/cards.cjs +28 -28
- package/dist/cjs/cards.d.cts +1 -1
- package/dist/cjs/{health-check.types-CtWQ_YSy.d.cts → health-check.types-C2XZ-Tpt.d.cts} +70 -65
- package/dist/cjs/{index-vgb88C84.d.cts → index-DVSB455a.d.cts} +18 -6
- package/dist/cjs/index.cjs +111 -111
- package/dist/cjs/index.d.cts +5 -5
- package/dist/cjs/internal/index.cjs +42 -39
- package/dist/cjs/internal/index.d.cts +324 -27
- package/dist/cjs/langchain/index.cjs +4 -1
- package/dist/cjs/langchain/index.d.cts +24 -6
- package/dist/cjs/servers/express.cjs +109 -109
- package/dist/cjs/servers/express.d.cts +6 -6
- package/dist/cjs/servers/h3.cjs +110 -110
- package/dist/cjs/servers/h3.d.cts +6 -6
- package/dist/cjs/servers/hono.cjs +109 -109
- package/dist/cjs/servers/hono.d.cts +6 -6
- package/dist/cjs/servers/lambda.cjs +109 -109
- package/dist/cjs/servers/lambda.d.cts +6 -6
- package/dist/cjs/servers/nest.cjs +120 -120
- package/dist/cjs/servers/nest.d.cts +8 -8
- package/dist/cjs/servers/next.cjs +109 -109
- package/dist/cjs/servers/next.d.cts +6 -6
- package/dist/cjs/servers/nuxt.cjs +110 -110
- package/dist/cjs/servers/nuxt.d.cts +6 -6
- package/dist/cjs/servers/remix.cjs +109 -109
- package/dist/cjs/servers/remix.d.cts +6 -6
- package/dist/cjs/servers/sveltekit.cjs +109 -109
- package/dist/cjs/servers/sveltekit.d.cts +6 -6
- package/dist/cjs/step-resolver.cjs +4 -4
- package/dist/cjs/step-resolver.d.cts +3 -2
- package/dist/cjs/{subscriber.types-CyNKT0nZ.d.cts → subscriber.types-BanvmGul.d.cts} +680 -27
- package/dist/esm/{agent.types-HUDhyXrV.d.ts → agent.types-DFLG1_vb.d.ts} +154 -3
- package/dist/esm/ai-sdk/index.d.ts +16 -5
- package/dist/esm/ai-sdk/index.js +1 -1
- package/dist/esm/cards.d.ts +1 -1
- package/dist/esm/cards.js +1 -1
- package/dist/esm/chunk-4ETX7FIT.js +1 -0
- package/dist/esm/{chunk-SPS3KBKF.js → chunk-IREH6K2M.js} +4 -4
- package/dist/esm/chunk-PBC7WR2R.js +98 -0
- package/dist/esm/chunk-PU74XQ2P.js +1 -0
- package/dist/esm/chunk-QZ6TSYCK.js +4 -0
- package/dist/esm/chunk-YZ3P3MMZ.js +1 -0
- package/dist/esm/{health-check.types-0Rv-l8yD.d.ts → health-check.types-DORn4djx.d.ts} +70 -65
- package/dist/esm/{index-C0oUWDlb.d.ts → index-BvRGmHFw.d.ts} +18 -6
- package/dist/esm/index.d.ts +5 -5
- package/dist/esm/index.js +1 -1
- package/dist/esm/internal/index.d.ts +317 -20
- package/dist/esm/internal/index.js +1 -1
- package/dist/esm/langchain/index.d.ts +24 -6
- package/dist/esm/langchain/index.js +1 -1
- package/dist/esm/servers/express.d.ts +6 -6
- package/dist/esm/servers/express.js +1 -1
- package/dist/esm/servers/h3.d.ts +6 -6
- package/dist/esm/servers/h3.js +1 -1
- package/dist/esm/servers/hono.d.ts +6 -6
- package/dist/esm/servers/hono.js +1 -1
- package/dist/esm/servers/lambda.d.ts +6 -6
- package/dist/esm/servers/lambda.js +1 -1
- package/dist/esm/servers/nest.d.ts +8 -8
- package/dist/esm/servers/nest.js +1 -1
- package/dist/esm/servers/next.d.ts +6 -6
- package/dist/esm/servers/next.js +1 -1
- package/dist/esm/servers/nuxt.d.ts +6 -6
- package/dist/esm/servers/nuxt.js +1 -1
- package/dist/esm/servers/remix.d.ts +6 -6
- package/dist/esm/servers/remix.js +1 -1
- package/dist/esm/servers/sveltekit.d.ts +6 -6
- package/dist/esm/servers/sveltekit.js +1 -1
- package/dist/esm/step-resolver.d.ts +3 -2
- package/dist/esm/step-resolver.js +1 -1
- package/dist/esm/{subscriber.types-g7VnI_ZQ.d.ts → subscriber.types-Drf26WPA.d.ts} +680 -27
- package/package.json +3 -2
- package/dist/esm/chunk-CGZ5P44A.js +0 -98
- package/dist/esm/chunk-FMKD6TON.js +0 -1
- package/dist/esm/chunk-W6DIBD4Z.js +0 -1
|
@@ -101,6 +101,7 @@ declare enum ChatProviderIdEnum {
|
|
|
101
101
|
Slack = "slack",
|
|
102
102
|
Discord = "discord",
|
|
103
103
|
MsTeams = "msteams",
|
|
104
|
+
WebexMessaging = "webex-messaging",
|
|
104
105
|
Mattermost = "mattermost",
|
|
105
106
|
Ryver = "ryver",
|
|
106
107
|
Zulip = "zulip",
|
|
@@ -108,9 +109,12 @@ declare enum ChatProviderIdEnum {
|
|
|
108
109
|
GetStream = "getstream",
|
|
109
110
|
RocketChat = "rocket-chat",
|
|
110
111
|
WhatsAppBusiness = "whatsapp-business",
|
|
112
|
+
Line = "line",
|
|
111
113
|
ChatWebhook = "chat-webhook",
|
|
114
|
+
Novu = "novu-slack",
|
|
112
115
|
Telegram = "telegram",
|
|
113
|
-
Sendblue = "sendblue"
|
|
116
|
+
Sendblue = "sendblue",
|
|
117
|
+
NovuWebChat = "novu-web-chat"
|
|
114
118
|
}
|
|
115
119
|
declare enum PushProviderIdEnum {
|
|
116
120
|
FCM = "fcm",
|
|
@@ -201,6 +205,51 @@ declare enum AgentEventEnum {
|
|
|
201
205
|
ON_RESOLVE = "onResolve",
|
|
202
206
|
ON_REACTION = "onReaction"
|
|
203
207
|
}
|
|
208
|
+
type HumanInteractionKind = 'ask' | 'approve' | 'choose' | 'tell';
|
|
209
|
+
type HumanAskApproveOptions = {
|
|
210
|
+
/** Attribution label shown to the human (e.g. `"deploy-bot"`). */
|
|
211
|
+
from?: string;
|
|
212
|
+
/** Time until the request expires, in seconds (max 72h; default 24h). */
|
|
213
|
+
ttlSeconds?: number;
|
|
214
|
+
/**
|
|
215
|
+
* Novu `subscriberId`(s) allowed to settle this request. First valid answer
|
|
216
|
+
* wins. When omitted, the conversation's first subscriber participant is used.
|
|
217
|
+
* The maximum number of subscribers is 50.
|
|
218
|
+
*/
|
|
219
|
+
to?: string | string[];
|
|
220
|
+
};
|
|
221
|
+
type HumanChooseOptions = HumanAskApproveOptions;
|
|
222
|
+
type HumanTellOptions = {
|
|
223
|
+
/** Attribution label shown to the human (e.g. `"deploy-bot"`). */
|
|
224
|
+
from?: string;
|
|
225
|
+
/**
|
|
226
|
+
* Novu `subscriberId`(s) this notice is addressed to. In-thread delivery
|
|
227
|
+
* still posts one card on the current conversation.
|
|
228
|
+
*/
|
|
229
|
+
to?: string | string[];
|
|
230
|
+
};
|
|
231
|
+
/**
|
|
232
|
+
* Outcome of a `ctx.ask` / `ctx.approve` / `ctx.choose` request, attached to
|
|
233
|
+
* the later `onMessage` (ask) or `onAction` (approve / choose) turn.
|
|
234
|
+
*/
|
|
235
|
+
type AgentHumanResponse = {
|
|
236
|
+
/** Client-minted id returned by `ctx.ask` / `ctx.approve` / `ctx.choose`. */
|
|
237
|
+
requestId: string;
|
|
238
|
+
/** Public interaction identifier (`hi_...`). */
|
|
239
|
+
interactionId: string;
|
|
240
|
+
kind: HumanInteractionKind;
|
|
241
|
+
/** Terminal status: `answered` | `approved` | `denied` | `expired` | `canceled` | `delivered`. */
|
|
242
|
+
status: string;
|
|
243
|
+
/** True when the TTL elapsed before a valid answer. Do not treat `text` / `optionId` as a verdict. */
|
|
244
|
+
expired: boolean;
|
|
245
|
+
/** Freeform reply text for `ask`. */
|
|
246
|
+
text?: string;
|
|
247
|
+
/** `approve`: `'approve'` | `'deny'`; `choose`: the picked option id. */
|
|
248
|
+
optionId?: string;
|
|
249
|
+
respondedBy?: string;
|
|
250
|
+
/** Stable Novu subscriberId of whoever settled the interaction. */
|
|
251
|
+
respondedBySubscriberId?: string;
|
|
252
|
+
};
|
|
204
253
|
/** Identity of the user or bot that authored a message. */
|
|
205
254
|
interface AgentMessageAuthor {
|
|
206
255
|
userId: string;
|
|
@@ -273,6 +322,17 @@ interface AgentSubscriber {
|
|
|
273
322
|
/** Arbitrary custom data attached to the subscriber in Novu. */
|
|
274
323
|
data?: Record<string, unknown>;
|
|
275
324
|
}
|
|
325
|
+
/** Workflow-origin notification for this turn. */
|
|
326
|
+
interface AgentNotification<TPayload extends Record<string, unknown> = Record<string, unknown>> {
|
|
327
|
+
id: string;
|
|
328
|
+
/** User-facing workflow slug — same string as `ctx.trigger(workflowId)`. */
|
|
329
|
+
workflowId: string;
|
|
330
|
+
messageId: string;
|
|
331
|
+
platformMessageId: string;
|
|
332
|
+
sentAt: string;
|
|
333
|
+
body: string;
|
|
334
|
+
payload: TPayload;
|
|
335
|
+
}
|
|
276
336
|
/**
|
|
277
337
|
* Tool-call details on a tool-related history entry. Which fields are set depends on the
|
|
278
338
|
* entry's `type` (`tool_approval_request`, `tool_approval_decision`, or `tool_result`).
|
|
@@ -533,6 +593,17 @@ interface AgentHandlerContext {
|
|
|
533
593
|
* (e.g. reading the customer's tenant/organization out of it).
|
|
534
594
|
*/
|
|
535
595
|
readonly context: AgentContextPayload | null;
|
|
596
|
+
/**
|
|
597
|
+
* The Novu notification this turn is replying to (workflow origin), or `null` when the
|
|
598
|
+
* conversation was not opened from a workflow send.
|
|
599
|
+
*/
|
|
600
|
+
readonly notification: AgentNotification | null;
|
|
601
|
+
/**
|
|
602
|
+
* Settled `ctx.ask` / `ctx.approve` / `ctx.choose` payload when this
|
|
603
|
+
* `onMessage` or `onAction` turn answered (or expired) a human interaction.
|
|
604
|
+
* `null` on ordinary chat and button clicks.
|
|
605
|
+
*/
|
|
606
|
+
readonly humanResponse: AgentHumanResponse | null;
|
|
536
607
|
/**
|
|
537
608
|
* Full conversation history as an ordered array of entries.
|
|
538
609
|
* Map to your LLM's message format before making a model call:
|
|
@@ -613,6 +684,50 @@ interface AgentHandlerContext {
|
|
|
613
684
|
to?: TriggerRecipientsPayload;
|
|
614
685
|
payload?: Record<string, unknown>;
|
|
615
686
|
}): void;
|
|
687
|
+
/**
|
|
688
|
+
* Ask the conversation subscriber a freeform question. Queued and flushed
|
|
689
|
+
* with the next `ctx.reply()`, or automatically when the handler completes.
|
|
690
|
+
* The answer arrives later on `onMessage` with `ctx.humanResponse` set.
|
|
691
|
+
* Pass `to` to let any listed subscriber settle (first valid answer wins).
|
|
692
|
+
*
|
|
693
|
+
* @returns A `requestId` you can match against `ctx.humanResponse.requestId`.
|
|
694
|
+
*
|
|
695
|
+
* @example
|
|
696
|
+
* ctx.ask('What environment should we deploy to?');
|
|
697
|
+
* ctx.ask('Which environment?', { to: 'alice' });
|
|
698
|
+
*/
|
|
699
|
+
ask(question: string, opts?: HumanAskApproveOptions): string;
|
|
700
|
+
/**
|
|
701
|
+
* Ask the conversation subscriber to approve or deny an action.
|
|
702
|
+
* The verdict arrives later on `onAction` with `ctx.humanResponse` set.
|
|
703
|
+
* Pass `to` to let any listed subscriber settle (first valid answer wins).
|
|
704
|
+
*
|
|
705
|
+
* @returns A `requestId` you can match against `ctx.humanResponse.requestId`.
|
|
706
|
+
*
|
|
707
|
+
* @example
|
|
708
|
+
* ctx.approve('Deploy v2.4.1 to production?');
|
|
709
|
+
* ctx.approve('Deploy v2.4.1?', { to: ['alice', 'bob'] });
|
|
710
|
+
*/
|
|
711
|
+
approve(action: string, opts?: HumanAskApproveOptions): string;
|
|
712
|
+
/**
|
|
713
|
+
* Ask the conversation subscriber to pick one of several options (2–10).
|
|
714
|
+
* The pick arrives later on `onAction` with `ctx.humanResponse` set.
|
|
715
|
+
* Pass `to` to let any listed subscriber settle (first valid answer wins).
|
|
716
|
+
*
|
|
717
|
+
* @returns A `requestId` you can match against `ctx.humanResponse.requestId`.
|
|
718
|
+
*
|
|
719
|
+
* @example
|
|
720
|
+
* ctx.choose('Which region?', ['us-east', 'eu-west', 'ap-south']);
|
|
721
|
+
*/
|
|
722
|
+
choose(question: string, options: string[], opts?: HumanChooseOptions): string;
|
|
723
|
+
/**
|
|
724
|
+
* Send a one-way notification to the conversation subscriber. Nothing to wait
|
|
725
|
+
* on — `tell` never sets `ctx.humanResponse`.
|
|
726
|
+
*
|
|
727
|
+
* @example
|
|
728
|
+
* ctx.tell('Deploy finished. v2.4.1 is live.');
|
|
729
|
+
*/
|
|
730
|
+
tell(message: string, opts?: HumanTellOptions): string;
|
|
616
731
|
/**
|
|
617
732
|
* Add an emoji reaction to any platform message.
|
|
618
733
|
* Reactions are queued and sent with the next `ctx.reply()`, or flushed automatically
|
|
@@ -636,6 +751,13 @@ interface AgentHandlerContext {
|
|
|
636
751
|
* await ctx.reply('Processing…');
|
|
637
752
|
*/
|
|
638
753
|
deleteMessage(messageId: string): void;
|
|
754
|
+
/**
|
|
755
|
+
* Emit a custom AgentEvent (event mode only — no-op when the bridge omits `eventsUrl`).
|
|
756
|
+
*/
|
|
757
|
+
emit(event: {
|
|
758
|
+
name: string;
|
|
759
|
+
data: unknown;
|
|
760
|
+
}): Promise<void>;
|
|
639
761
|
/**
|
|
640
762
|
* Control the typing / "Thinking…" status for the current turn.
|
|
641
763
|
* Posts immediately (like `reply()`), updating the indicator Novu already shows on inbound.
|
|
@@ -754,6 +876,8 @@ interface AgentBridgeRequest {
|
|
|
754
876
|
event: string;
|
|
755
877
|
agentId: string;
|
|
756
878
|
replyUrl: string;
|
|
879
|
+
/** When present, the SDK emits AgentEvents to this URL instead of using replyUrl. */
|
|
880
|
+
eventsUrl?: string;
|
|
757
881
|
conversationId: string;
|
|
758
882
|
integrationIdentifier: string;
|
|
759
883
|
action: AgentAction | null;
|
|
@@ -774,6 +898,18 @@ interface AgentBridgeRequest {
|
|
|
774
898
|
* older API versions that don't send it remain compatible; absent → `ctx.context` is `null`.
|
|
775
899
|
*/
|
|
776
900
|
context?: AgentContextPayload | null;
|
|
901
|
+
/**
|
|
902
|
+
* The Novu notification this turn is replying to, when the conversation was opened (or
|
|
903
|
+
* re-attached) from a workflow send. Optional on the wire for backward compatibility;
|
|
904
|
+
* absent → `ctx.notification` is `null`.
|
|
905
|
+
*/
|
|
906
|
+
notification?: AgentNotification | null;
|
|
907
|
+
/**
|
|
908
|
+
* Settled human-interaction payload when this `onMessage` / `onAction` turn
|
|
909
|
+
* answered or expired a `ctx.ask` / `ctx.approve` / `ctx.choose`. Optional on
|
|
910
|
+
* the wire for backward compatibility; absent → `ctx.humanResponse` is `null`.
|
|
911
|
+
*/
|
|
912
|
+
humanResponse?: AgentHumanResponse | null;
|
|
777
913
|
history: AgentHistoryEntry[];
|
|
778
914
|
platform: string;
|
|
779
915
|
platformContext: AgentPlatformContext;
|
|
@@ -806,7 +942,22 @@ type TriggerSignal = {
|
|
|
806
942
|
to?: TriggerRecipientsPayload;
|
|
807
943
|
payload?: Record<string, unknown>;
|
|
808
944
|
};
|
|
809
|
-
|
|
945
|
+
/**
|
|
946
|
+
* Queued by `ctx.ask` / `ctx.approve` / `ctx.choose` / `ctx.tell` — instructs
|
|
947
|
+
* Novu to create a human interaction in the current conversation thread.
|
|
948
|
+
*/
|
|
949
|
+
type HumanSignal = {
|
|
950
|
+
type: 'human';
|
|
951
|
+
kind: HumanInteractionKind;
|
|
952
|
+
prompt: string;
|
|
953
|
+
requestId: string;
|
|
954
|
+
options?: string[];
|
|
955
|
+
from?: string;
|
|
956
|
+
ttlSeconds?: number;
|
|
957
|
+
/** Novu subscriberId(s) allowed to settle. Omitted = conversation subscriber. */
|
|
958
|
+
to?: string | string[];
|
|
959
|
+
};
|
|
960
|
+
type Signal = MetadataSignal | TriggerSignal | HumanSignal;
|
|
810
961
|
/** The outcome of a tool call, reported back so it's saved in the conversation history. */
|
|
811
962
|
type ToolResult = {
|
|
812
963
|
/** Id of the tool call this result belongs to. */
|
|
@@ -869,4 +1020,4 @@ interface SentMessageInfo {
|
|
|
869
1020
|
platformThreadId: string;
|
|
870
1021
|
}
|
|
871
1022
|
|
|
872
|
-
export { type Agent as A, type
|
|
1023
|
+
export { type AgentReplyPayload as $, type Agent as A, type HumanTellOptions as B, type ToolApprovalConfig as C, type ToolApprovalDecision as D, toAgentError as E, type FileRef as F, type TriggerRecipientsPayload as G, type HumanAskApproveOptions as H, type ITriggerPayload as I, type ISubscriberPayload as J, TriggerEventStatusEnum as K, type ToolResult as L, type MessageContent as M, type ToolApprovalRequestPayload as N, AgentEventEnum as O, type TypingControl as P, type ToolApprovalControl as Q, type ReplyHandle as R, type AgentBridgeRequest as S, type ToolApprovalCard as T, type ReplyContent as U, type Signal as V, type WorkflowPreferencesPartial as W, type AddReactionPayload as X, type DeleteMessagePayload as Y, type SentMessageInfo as Z, type TypingOp as _, type AgentAction as a, type EditPayload as a0, type HumanSignal as a1, type MetadataSignal as a2, type ParsedApprovalAction as a3, type TriggerSignal as a4, buildApprovalActionId as a5, parseApprovalActionId as a6, type AgentActionContext as b, type AgentAttachment as c, type AgentContext as d, type AgentContextPayload as e, type AgentContextValue as f, type AgentConversation as g, AgentDeliveryError as h, AgentError as i, type AgentHandlerContext as j, type AgentHandlers as k, type AgentHistoryEntry as l, type AgentHumanResponse as m, type AgentMessage as n, type AgentMessageAuthor as o, type AgentMessageContext as p, type AgentNotification as q, type AgentPlatformContext as r, type AgentReaction as s, type AgentReactionContext as t, type AgentResolveContext as u, type AgentSubscriber as v, type AgentSubscriberAccess as w, type AgentToolCall as x, type HumanChooseOptions as y, type HumanInteractionKind as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { k as AgentHandlers,
|
|
1
|
+
import { k as AgentHandlers, n as AgentMessage, p as AgentMessageContext, M as MessageContent, D as ToolApprovalDecision, b as AgentActionContext, R as ReplyHandle, A as Agent, l as AgentHistoryEntry, j as AgentHandlerContext } from '../agent.types-DFLG1_vb.js';
|
|
2
2
|
import { streamText, generateText, ModelMessage } from 'ai';
|
|
3
3
|
import { A as Awaitable } from '../util.types-DaFfsxgy.js';
|
|
4
4
|
import 'chat';
|
|
@@ -26,15 +26,26 @@ type AiSdkMessageHandler = AiSdkAgentHandlers['onMessage'];
|
|
|
26
26
|
declare function agent(id: string, handlers: AiSdkMessageHandler | AiSdkAgentHandlers): Agent;
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
|
-
* Convert
|
|
29
|
+
* Convert conversation context into AI SDK `ModelMessage[]` for `streamText` / `generateText`.
|
|
30
30
|
*
|
|
31
|
-
*
|
|
32
|
-
* `
|
|
31
|
+
* Pass `ctx` to prepend `ctx.notification` as an assistant row. Pass `ctx.history` to skip that
|
|
32
|
+
* injection (e.g. after `isFromWorkflow`). History already includes the current inbound message.
|
|
33
|
+
*
|
|
34
|
+
* For http/localhost attachment URLs (e.g. LocalStack), wrap the result in
|
|
35
|
+
* `hydrateUnreachableAttachmentUrls` before passing it to `generateText`.
|
|
33
36
|
*
|
|
34
37
|
* Pass the system prompt via the top-level `instructions` option of `streamText` /
|
|
35
38
|
* `generateText`. AI SDK 7 rejects `system` messages inside the `messages` array by default,
|
|
36
39
|
* so this helper never injects one.
|
|
37
40
|
*/
|
|
38
41
|
declare function toModelMessages(history: AgentHistoryEntry[]): ModelMessage[];
|
|
42
|
+
declare function toModelMessages(ctx: Pick<AgentHandlerContext, 'history' | 'notification'>): ModelMessage[];
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Replace attachment URLs a hosted model cannot fetch with inline bytes.
|
|
46
|
+
* HTTPS public URLs are left as-is so production signed S3 links stay URL-based.
|
|
47
|
+
* Over-budget downloads are omitted so one large file cannot abort the turn.
|
|
48
|
+
*/
|
|
49
|
+
declare function hydrateUnreachableAttachmentUrls(messages: ModelMessage[]): Promise<ModelMessage[]>;
|
|
39
50
|
|
|
40
|
-
export { type AiSdkAgentHandlers, agent, toModelMessages };
|
|
51
|
+
export { type AiSdkAgentHandlers, agent, hydrateUnreachableAttachmentUrls, toModelMessages };
|
package/dist/esm/ai-sdk/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{a as R,c as M,d as I,e as T}from"../chunk-YZ3P3MMZ.js";import{c as v}from"../chunk-QZ6TSYCK.js";import{a as y,d,g as A}from"../chunk-PU74XQ2P.js";import"../chunk-FHYMHX3T.js";function O(t){return t.role==="tool"&&Array.isArray(t.content)}function N(t){return typeof t=="object"&&t!==null&&t.type==="tool-result"}function U(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="execution-denied"}function L(t){if(t&&typeof t=="object"&&"type"in t&&"value"in t){let e=t;if(e.type==="json"||e.type==="text")return e.value}return t}async function D(t){var o;return((o=await Promise.resolve(t.responseMessages))!=null?o:[]).filter(O).flatMap(n=>n.content).filter(N).filter(n=>!U(n.output)).map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,output:L(n.output)}))}function j(t){var o;let e=new Set;for(let n of t.history)n.type==="tool_approval_request"&&((o=n.toolData)!=null&&o.toolCallId)&&e.add(n.toolData.toolCallId);return e}async function C(t,e){var r;let o=await D(t);if(o.length===0)return;let n=j(e);for(let s of o)n.has(s.toolCallId)&&e.emitToolResult({toolCallId:s.toolCallId,toolName:s.toolName,output:s.output,preview:`Tool "${(r=s.toolName)!=null?r:s.toolCallId}" result`})}function g(t){return typeof t=="object"&&t!==null&&typeof t.consumeStream=="function"}function F(t){return typeof t=="object"&&t!==null&&"text"in t&&"steps"in t&&"usage"in t&&!g(t)}function c(t){return typeof t!="object"||t===null||y(t)?!1:g(t)||F(t)}function Y(t){var o;if(typeof t!="object"||t===null||t.type!=="tool-approval-request")return!1;let e=t;return!e.isAutomatic&&typeof((o=e.toolCall)==null?void 0:o.toolCallId)=="string"}async function G(t){let e=await Promise.resolve(t.content);return Array.isArray(e)?e.filter(Y):[]}async function f(t,e,o){g(t)&&await t.consumeStream({onError:r=>{throw r}}),await C(t,e);let n=await G(t);if(n.length>0){let r=n[0],s={id:r.toolCall.toolCallId,name:r.toolCall.toolName,input:r.toolCall.input};await A(e,s,o,r.approvalId);return}await V(t,e)}async function V(t,e){let o=(await Promise.resolve(t.text)).trim();if(!o){await e.typing.stop();return}await e.reply(o)}var $={text:"",platformMessageId:"",author:{userId:"",fullName:"",userName:"",isBot:!1},timestamp:""};function z(t){return typeof t=="object"&&t!==null&&"messageId"in t&&"platformThreadId"in t}function B(t,e){let o=typeof e=="function"?{onMessage:e}:e;if(typeof o.onMessage!="function")throw new Error(`agent('${t}') requires an onMessage handler`);return o}function Q(t,e){if(!t)throw new Error("agent() requires a non-empty agentId");let o=B(t,e),n=o.toolApproval,r=typeof o.onToolApproval=="function",s=async l=>{let i=d(l),p=await o.onMessage($,i.asMessageContext());c(p)&&await f(p,i,n)},a={onMessage:async(l,i)=>{let p=await o.onMessage(l,i);if(c(p)){await f(p,d(i),n);return}return p},onToolApproval:async(l,i)=>{let p=d(i);if(o.onToolApproval){let u=await o.onToolApproval(l,i);if(c(u)){await f(u,p,n);return}u!=null&&!z(u)&&await p.reply(u)}await s(i)},...n&&{toolApproval:n},...o.onAction&&{onAction:o.onAction},...o.onReaction&&{onReaction:o.onReaction},...o.onResolve&&{onResolve:o.onResolve},...o.onError&&{onError:o.onError}};return{id:t,handlers:a,userOnToolApproval:r}}var W="tool_approval_request",J="tool_approval_decision",K="tool_result";function S(t){var o;let e=t.toolData;if(!(!e||typeof e.approvalId!="string"||typeof e.toolCallId!="string"))return{approvalId:e.approvalId,toolCallId:e.toolCallId,name:(o=e.toolName)!=null?o:"tool",input:e.input}}function w(t){let e=t.toolData;if(!(!e||typeof e.approvalId!="string"||typeof e.approved!="boolean"))return{approvalId:e.approvalId,approved:e.approved}}function x(t){let e=t.toolData;if(!(!e||typeof e.toolCallId!="string"))return{toolCallId:e.toolCallId,toolName:e.toolName,output:e.output}}function k(t){let e=new Set,o=new Map,n=new Map,r=new Set;for(let a of t)if(a.type===W){let l=S(a);l&&(n.set(l.approvalId,l.toolCallId),r.add(l.toolCallId))}else if(a.type===J){let l=w(a);l&&!l.approved&&e.add(l.approvalId)}else if(a.type===K){let l=x(a);l&&o.set(l.toolCallId,l)}let s=new Set;for(let a of o.keys())r.has(a)&&s.add(a);return{deniedApprovalIds:e,toolResults:o,approvalIdToToolCallId:n,pairedAtRequest:s}}function X(t,e){return e.deniedApprovalIds.has(t.approvalId)?"denied":e.toolResults.has(t.toolCallId)?"resolved":"in-flight"}function m(t,e){var n;let o=[{type:"tool-call",toolCallId:t.toolCallId,toolName:t.name,input:(n=t.input)!=null?n:{}}];return e&&o.push({type:"tool-approval-request",approvalId:t.approvalId,toolCallId:t.toolCallId}),{role:"assistant",content:o}}function Z(t){return{role:"tool",content:[{type:"tool-result",toolCallId:t,toolName:"tool",output:{type:"execution-denied"}}]}}function E(t){var e;return{role:"tool",content:[{type:"tool-result",toolCallId:t.toolCallId,toolName:(e=t.toolName)!=null?e:"tool",output:{type:"json",value:t.output}}]}}function P(t,e){return[m(t,!1),e]}function h(t,e){let o=S(t);if(!o)return[];let n=X(o,e);switch(n){case"denied":return P(o,Z(o.toolCallId));case"resolved":{let r=e.toolResults.get(o.toolCallId);return r?P(o,E(r)):[m(o,!1)]}case"in-flight":return[m(o,!0)];default:return n}}function H(t,e){let o=w(t);if(!o||!o.approved)return;let n=e.approvalIdToToolCallId.get(o.approvalId);if(!(n&&e.toolResults.has(n)))return{role:"tool",content:[{type:"tool-approval-response",approvalId:o.approvalId,approved:!0}]}}function _(t,e){let o=x(t);if(o&&!e.pairedAtRequest.has(o.toolCallId))return E(o)}function b(t){return M(t).map(e=>({type:"file",data:new URL(e.url),mediaType:e.mediaType,...e.name?{filename:e.name}:{}}))}var tt="message",et="tool_approval_request",ot="tool_approval_decision",nt="tool_result";function q(t){return t==="agent"||t==="assistant"}function rt(t){let e=new Set;for(let o of t)!q(o.role)&&o.role!=="system"&&o.senderName&&e.add(o.senderName);return e.size}function st(t,e){let o=q(t.role),n=!!t.content.trim(),r=o?[]:b(t);if(!n&&r.length===0)return;let s=!o&&e&&t.senderName?`${t.senderName}: ${t.content}`:t.content;return r.length===0?{role:o?"assistant":"user",content:s}:{role:"user",content:n?[...r,{type:"text",text:s}]:r}}function lt(t,e,o){switch(t.type){case tt:{let n=st(t,e);return n?[n]:[]}case et:return h(t,o);case ot:{let n=H(t,o);return n?[n]:[]}case nt:{let n=_(t,o);return n?[n]:[]}default:return[]}}function at(t){let{history:e,notification:o}=R(t),n=rt(e)>1,r=k(e),s=e.flatMap(a=>lt(a,n,r));return o?[{role:"assistant",content:v(o.workflowId,o.body,o.payload)},...s]:s}function it(t){if(t.data instanceof URL)return t.data.toString()}async function pt(t){let e=it(t);if(!e||I(e))return t;let o=await T(e);return o?{...t,data:o}:null}async function ut(t){return Promise.all(t.map(async e=>{if(e.role!=="user"||typeof e.content=="string"||!Array.isArray(e.content))return e;let o=(await Promise.all(e.content.map(n=>n.type==="file"?pt(n):n))).filter(n=>n!=null);return{...e,content:o}}))}export{Q as agent,ut as hydrateUnreachableAttachmentUrls,at as toModelMessages};
|
package/dist/esm/cards.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { Actions, ActionsElement, Button, ButtonElement, Card, CardChild, CardElement, CardLink, CardText, Divider, DividerElement, LinkElement, Select, SelectElement, SelectOption, SelectOptionElement, TextElement, TextInput, TextInputElement } from 'chat';
|
|
1
|
+
export { Actions, ActionsElement, Button, ButtonElement, Card, CardChild, CardElement, CardLink, CardText, Divider, DividerElement, Image, ImageElement, LinkElement, Select, SelectElement, SelectOption, SelectOptionElement, TextElement, TextInput, TextInputElement } from 'chat';
|
|
2
2
|
import 'chat/jsx-runtime';
|
package/dist/esm/cards.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,b as t,c as n,d as l,e as
|
|
1
|
+
import{a as e,b as t,c as n,d as l,e as m,f as i,i as r,p as o,q as E,r as a}from"./chunk-X5AZIKIR.js";import"./chunk-RBTQQ5IZ.js";import"./chunk-FHYMHX3T.js";export{e as Actions,t as Button,n as Card,l as CardLink,m as CardText,i as Divider,r as Image,o as Select,E as SelectOption,a as TextInput};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as L,b as q,c as B,d as j,e as W,f as V,g as G,h as X,i as K,j as z,k as Y,l as J,m as Q,n as Z,o as ee,p as te,q as ne,r as re}from"./chunk-X5AZIKIR.js";import{d as oe,g,i as se,q as ae,r as ie,s as c,t as R,u as C,v as le}from"./chunk-VY27ZAO7.js";import{a as pe,c as ue,g as de}from"./chunk-PU74XQ2P.js";var ce=class extends C{constructor(n){super("Unknown BridgeError",{cause:n});this.statusCode=500;this.code="BridgeError"}};var me=class extends c{constructor(n,r){super(`Workflow with id: \`${n}\` has a corrupt state. Step with id: \`${r}\` does not exist. Please provide the missing state.`);this.code="ExecutionStateCorruptError";this.data={workflowId:n,stepId:r}}},fe=class extends c{constructor(n,r){super(`Workflow with id: \`${n}\` has invalid \`payload\`. Please provide the correct event payload.`);this.code="ExecutionEventPayloadInvalidError";this.data=r}},he=class extends c{constructor(n,r){super(`Workflow with id: \`${n}\` has invalid \`controls\`. Please provide the correct event controls.`);this.code="ExecutionEventControlInvalidError";this.data=r}},ye=class extends c{constructor(n,r,o){super(`Workflow with id: \`${n}\` has an invalid state. Step with id: \`${r}\` has invalid \`controls\`. Please provide the correct step controls.`);this.code="ExecutionStateControlInvalidError";this.data=o}},Re=class extends c{constructor(n,r,o){super(`Workflow with id: \`${n}\` has an invalid state. Step with id: \`${r}\` has invalid output. Please provide the correct step output.`);this.code="ExecutionStateOutputInvalidError";this.data=o}},Ae=class extends c{constructor(n,r,o){super(`Workflow with id: \`${n}\` has an invalid state. Step with id: \`${r}\` has invalid result. Please provide the correct step result.`);this.code="ExecutionStateResultInvalidError";this.data=o}},ve=class extends c{constructor(n,r,o){super(`Workflow with id: \`${n}\` has invalid controls syntax in step with id: \`${r}\`. Please correct step control syntax.`);this.code="StepControlCompilationFailedError";this.data=o}},Se=class extends c{constructor(n,r,o,s){super(`Workflow with id: \`${n}\` has an invalid state. Step with id: \`${r}\` and provider with id: \`${o}\` has invalid output. Please provide the correct provider output.`);this.code="ExecutionProviderOutputInvalidError";this.data=s}},xe=class extends c{constructor(n,r){super(`Workflow with id: \`${n}\` has invalid \`payload\`. Please provide the correct payload.`);this.code="WorkflowPayloadInvalidError";this.data=r}};var Te=t=>Object.values(g).includes(t==null?void 0:t.code),Vt=t=>!Te(t)&&typeof t.statusCode=="number"&&t.statusCode>=400&&t.statusCode<500;var N=t=>Object.values(t).map(e=>`\`${e}\``).join(", "),w=t=>t.replaceAll(/(\w)(\w*)/g,(e,n,r)=>n.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ee=class extends ae{constructor(){super(...arguments);this.code="MethodNotAllowedError";this.statusCode=405;this.message=`Method not allowed. Please use one of ${N(se)}`}},_e=class extends c{constructor(n,r){super(`Invalid query string: \`action\`=\`${n}\`. Please use one of ${N(r)}`);this.code="InvalidActionError"}},Ce=class extends c{constructor(){super("Missing secret key. Set the `NOVU_SECRET_KEY` environment variable or pass `secretKey` to the client options.");this.code="MissingSecretKeyError"}};var we=class extends Error{constructor(e,n,r){super(),this.data={message:r},this.statusCode=e,this.code=n}};var A=class extends le{constructor(e,n){super(`${w(e)} with id: \`${n}\` already exists. Please use a different id.`)}},f=class extends ie{constructor(e,n){super(`${w(e)} with id: \`${n}\` does not exist. Please provide a valid id.`)}},v=class extends C{constructor(n,r,o,s){super(`Failed to ${o} ${w(n)} with id: \`${r}\``,{cause:s});this.statusCode=502}};var Oe=class extends f{constructor(n){super("provider",n);this.code="ProviderNotFoundError"}},Ie=class extends v{constructor(n,r,o){super("provider",n,r,o);this.code="ProviderExecutionFailedError"}};var Pe=class extends R{constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");this.code="SignatureMismatchError"}},ke=class extends R{constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");this.code="SignatureNotFoundError"}},Ne=class extends R{constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");this.code="SignatureInvalidError"}},Ue=class extends R{constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);this.code="SignatureExpiredError"}},Fe=class extends R{constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");this.code="SigningKeyNotFoundError"}},De=class extends R{constructor(){super("Signature version is invalid. Please provide a signature version with version `v1` in the `novu-signature` header");this.code="SignatureVersionInvalidError"}};var Me=class extends f{constructor(n){super("step",n);this.code="StepNotFoundError"}},He=class extends A{constructor(n){super("step",n);this.code="StepAlreadyExistsError"}},$e=class extends v{constructor(n,r,o){super("step",n,r,o);this.code="StepExecutionFailedError"}};var Le=class extends f{constructor(n){super("workflow",n);this.code="WorkflowNotFoundError"}},qe=class extends A{constructor(n){super("workflow",n);this.code="WorkflowAlreadyExistsError"}};function gt(t,e){let n={...t};for(let r of Object.keys(e)){let o=e[r];o&&typeof o=="object"&&!Array.isArray(o)?n[r]=gt(n[r]||{},o):(Array.isArray(o),n[r]=o)}return n}function O(t,e){let n=e.split(".").reduce((r,o)=>{if(r&&typeof r=="object")return r[o]},t);if(n==null)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);if(typeof n=="object"){let r=JSON.stringify(n);return r==="{}"?"":r}return""}function Be(t,e=2,n,r=", "){if(!Array.isArray(t)||t.length===0)return"";let o=n?t.map(a=>typeof a!="object"||!a?"":O(a,n)):t;if(o.length===1)return o[0];if(o.length===2)return`${o[0]} and ${o[1]}`;if(e>=o.length){let a=o.slice(0,-1),p=o[o.length-1];return`${a.join(r)} and ${p}`}let s=o.slice(0,e),u=o.length-e;return`${s.join(r)} and ${u} ${u===1?"other":"others"}`}import mt from"pluralize";function je(t,e="",n="",r="true"){if(t==null)return"";let o=0;if(Array.isArray(t)?o=t.length:typeof t=="object"?o=Object.keys(t).length:typeof t=="string"?o=+t:typeof t=="number"?o=t:o=Number(t),Number.isNaN(o)&&(o=0),o<=0)return"";let s;return n?s=o===1?e:n:s=mt(e,o),r==="true"?`${o} ${s}`:s}import{TokenKind as We}from"liquidjs";import ft from"pluralize";import{z as h}from"zod";var Ge="",Xe=2,Ke="other",ze=", ",Ye=" and ",Je=", and ",Ve={0:"keyPath",1:"limit",2:"overflowSuffix",3:"wordsConnector",4:"twoWordsConnector",5:"lastWordConnector"};function Qe(t,e=Ge,n=Xe,r=Ke,o=ze,s=Ye,u=Je){if(!Array.isArray(t)||t.length===0)return"";let a=e?t.map(i=>typeof i!="object"||!i?"":O(i,e)):t,p=a.length;if(p===1)return a[0];if(p===2)return`${a[0]}${s}${a[1]}`;if(n>=p){let i=a.slice(0,p-1),x=a[p-1];return`${i.join(o)}${u}${x}`}let l=a.slice(0,n),d=p-n,y=n===1?s:u;return`${l.join(o)}${y}${d} ${ft(r,d)}`}function jn(t={},...e){let{requireKeyPath:n=!1}=t,r=[];if(e.length<1)return r.push({message:"Expected at least 1 argument",begin:0,end:0,value:""}),r;let o=h.object({keyPath:n?h.string().min(1,"must be non-empty"):h.string().optional().default(Ge),limit:h.number().optional().default(Xe).refine(a=>a>=0,"must be greater than or equal to 0"),overflowSuffix:h.string().optional().default(Ke),wordsConnector:h.string().optional().default(ze),twoWordsConnector:h.string().optional().default(Ye),lastWordConnector:h.string().optional().default(Je)}),s={};e.forEach((a,p)=>{if(!Array.isArray(a)){let l=a.getText();(a.kind===We.Quoted||a.kind===We.Number)&&(l=a.content);let d=Ve[p];s[d]=l}});let u=o.safeParse(s);if(!u.success)for(let a of u.error.issues){let p="string";"type"in a&&(p=a.type);let l=a.path[0],d=Object.entries(Ve).find(([x,ct])=>ct===l),y=d?parseInt(d[0],10):null,i=typeof y=="number"?e[y]:null;i&&!Array.isArray(i)&&r.push({message:`"toSentence" expects a ${p}${a.message?` that ${a.message}`:""} for argument "${l}"`,begin:i.begin,end:i.end,value:i.getText()})}return r}import{Liquid as ht}from"liquidjs";function yt(t){return Array.isArray(t)||typeof t=="object"&&t!==null?Ze(t):typeof t=="string"?t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"):t==null?"":String(t)}var Ze=(t,e=0)=>Array.isArray(t)||typeof t=="object"&&t!==null?JSON.stringify(t,null,e).replace(/"/g,"'").replace(/\n/g,"\\n"):t==null?"":String(t);function Yn(t){let e=new ht({outputEscape:yt,...t});return e.registerFilter("json",(n,r)=>Ze(n,r)),e.registerFilter("digest",Be),e.registerFilter("toSentence",Qe),e.registerFilter("pluralize",je),e}var Rt={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",408:"Request Timeout",409:"Conflict",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function I(t){return typeof t=="string"&&t.trim()?t:!t||typeof t!="object"?null:I(t.message)}function At(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e,r=I(n.message);if(r)return r;let o=I(n.error);if(o)return o;let s=n.errors;return Array.isArray(s)?I(s[0]):null}function vt(t,e){var o;let n=(o=Rt[t])!=null?o:t,r=At(e);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var S=class extends Error{constructor(e,n){super(e),this.name="AgentError",this.cause=n==null?void 0:n.cause,this.delivery=n==null?void 0:n.delivery}},m=class extends S{constructor(e,n){let r={statusCode:e,responseBody:n};super(vt(e,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=e,this.responseBody=n}};function Qn(t){return t instanceof S?t:t instanceof Error?new S(t.message,{cause:t}):new S("Turn failed",{cause:t})}var St=(o=>(o.ON_MESSAGE="onMessage",o.ON_ACTION="onAction",o.ON_RESOLVE="onResolve",o.ON_REACTION="onReaction",o))(St||{}),b=class{constructor(){this.__novuPendingApproval=!0}};function er(t){return typeof t=="object"&&t!==null&&"suppress"in t&&t.suppress===!0}var et=1;function xt(t){return new Promise(e=>{setTimeout(e,t)})}function Tt(t){return t>=500||t===408||t===429}var P=class{constructor(e){this.sequence=0;this.buffer=[];this.chain=Promise.resolve();var n,r;this.runId=`run_${crypto.randomUUID()}`,this.eventsUrl=e.eventsUrl,this.secretKey=e.secretKey,this.conversationId=e.conversationId,this.agentId=e.agentId,this.turnId=e.turnId,this.fetchFn=(n=e.fetchFn)!=null?n:fetch,this.maxRetries=(r=e.maxRetries)!=null?r:3}enqueue(e){this.sequence+=1,this.buffer.push({version:et,conversationId:this.conversationId,agentId:this.agentId,runId:this.runId,turnId:this.turnId,sequence:this.sequence,timestamp:new Date().toISOString(),event:e})}flush(){if(this.buffer.length===0)return this.chain;let e=this.buffer;return this.buffer=[],this.chain=this.chain.then(()=>this.postBatchWithRetry(e)),this.chain}async emit(e){this.enqueue(e),await this.flush()}async postBatchWithRetry(e){let n;for(let r=1;r<=this.maxRetries;r+=1)try{await this.postBatch(e);return}catch(o){if(n=o,!Et(o))throw o;r<this.maxRetries&&await xt(250*r)}throw n}async postBatch(e){let n;try{n=await this.fetchFn(this.eventsUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify({events:e})})}catch(o){throw _t(o)}let r=await n.text().catch(()=>"");if(!n.ok)throw new m(n.status,r)}};function Et(t){return!(t instanceof m)||t.statusCode===0?!0:Tt(t.statusCode)}function _t(t){if(t instanceof m)return t;let e=t instanceof Error?t.message:"Network request failed";return new m(0,e)}function tt(t){let e=typeof t=="string"?[t]:t,n=[],r=new Set;for(let o of e){if(typeof o!="string")throw new Error("`to` must be a subscriberId string or an array of subscriberIds");let s=o.trim();!s||r.has(s)||(r.add(s),n.push(s))}if(n.length===0)throw new Error("`to` must include at least one subscriberId");if(n.length>50)throw new Error("`to` supports at most 50 subscriberIds");return n}var Ct=Symbol.for("chat.jsx.element"),wt=new Set([L,q,B,j,W,V,Q,G,X,K,z,Z,ee,Y,te,ne,J,re]);function Ot(t){return typeof t=="object"&&t!==null&&t.$$typeof===Ct}async function nt(t){let e=k(t);if(e&&typeof e=="object"&&pe(e))return e;let{isJSX:n,toCardElement:r}=await import("./jsx-runtime-5ZWEWA4A.js");return n(e)?r(e):null}function k(t){var e;if(Array.isArray(t))return t.map(n=>k(n));if(!Ot(t))return t;if(typeof t.type=="function"&&!wt.has(t.type)){let n={...(e=t.props)!=null?e:{}};return t.children!==void 0&&(n.children=t.children),k(t.type(n))}return{...t,children:k(t.children)}}var It=5*1024*1024,bt=5*1024*1024,rt=32768,Pt=/^[A-Za-z0-9+/]*={0,2}$/;function _(t,e){return t.filename?`"${t.filename}"`:`at index ${e}`}function lt(){return globalThis.Buffer}function kt(t){var e,n,r;return(r=(n=(e=lt())==null?void 0:e.isBuffer)==null?void 0:n.call(e,t))!=null?r:!1}function Nt(t){return typeof Blob!="undefined"&&t instanceof Blob}function U(t){let e=lt();if(e)return e.from(t).toString("base64");if(typeof btoa!="function")throw new Error("Unable to encode file data: base64 encoding is not available in this runtime.");let n="";for(let r=0;r<t.length;r+=rt){let o=t.subarray(r,r+rt);n+=String.fromCharCode(...o)}return btoa(n)}function pt(t){let e=t.replace(/\s/g,""),n=e.length%4;if(!e||n===1||!Pt.test(e))return null;let r=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-r}function T(t,e,n){if(t>It)throw new Error(`Invalid file ${_(e,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Ut(t,e,n){if(typeof t=="string"){let r=pt(t);if(r===null)throw new Error(`Invalid file ${_(e,n)}: data must be a base64-encoded string.`);return T(r,e,n),t}if(kt(t))return T(t.byteLength,e,n),t.toString("base64");if(t instanceof Uint8Array)return T(t.byteLength,e,n),U(t);if(t instanceof ArrayBuffer)return T(t.byteLength,e,n),U(new Uint8Array(t));if(Nt(t))return T(t.size,e,n),U(new Uint8Array(await t.arrayBuffer()));throw new Error(`Invalid file ${_(e,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function Ft(t){if(!(t!=null&&t.length))return;let e=[],n=0;for(let[r,o]of t.entries()){let s=o.data,u=o.url,a=s!=null,p=u!=null;if(a===p)throw new Error(`Invalid file ${_(o,r)}: provide exactly one of data or url.`);if(a){let l=await Ut(s,o,r),d=pt(l);if(n+=d!=null?d:0,n>bt)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");e.push({...o,data:l});continue}if(p&&typeof u!="string")throw new Error(`Invalid file ${_(o,r)}: url must be a string.`);e.push(o)}return e}async function ut(t,e){let n=await Ft(e);if(typeof t=="string")return n?{markdown:t,files:n}:{markdown:t};let r=await nt(t);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}function dt(t){return`${t}_${crypto.randomUUID()}`}function ot(t){if(t.markdown!==void 0)return{markdown:t.markdown};if(t.card!==void 0)return{card:t.card};throw new Error("Invalid reply content \u2014 expected markdown or card")}function st(t){if(t!=null&&t.length)return t.map((e,n)=>({fileId:e.filename||`file_${n}`,name:e.filename,mediaType:e.mimeType,...e.data!==void 0?{data:typeof e.data=="string"?e.data:void 0}:{},...e.url!==void 0?{url:e.url}:{}}))}function F(t,e){e.toolApprovalRequest&&(t.toolApprovalRequest=e.toolApprovalRequest),e.signals.length&&(t.signals=e.signals),e.toolResults.length&&(t.toolResults=e.toolResults),e.addReactions.length&&(t.addReactions=e.addReactions),e.deleteMessages.length&&(t.deleteMessages=e.deleteMessages),e.resolve&&(t.resolve=e.resolve)}function D(t,e){var r;let n=[];if(t.toolApprovalRequest){let o=t.toolApprovalRequest;n.push({type:"tool-approval-request",approvalId:o.approvalId,toolUseId:o.toolCallId,toolName:o.name,input:o.input,...e!=null&&e.deliverApprovalCard?{deliverCard:!0}:{}})}for(let o of t.toolResults)n.push({type:"tool-use-result",toolUseId:o.toolCallId,content:[{type:"text",text:String((r=o.preview)!=null?r:"")},{type:"json",value:o.output}]});for(let o of t.signals)n.push({type:"signal",signal:o});for(let o of t.addReactions)n.push({type:"channel.reaction",messageId:o.messageId,emoji:o.emojiName,op:"add"});for(let o of t.deleteMessages)n.push({type:"channel.delete",messageId:o.messageId});return t.resolve&&n.push({type:"resolve",summary:t.resolve.summary}),n}var M=class{constructor(e,n,r,o){this.replyUrl=e;this.secretKey=n;this.conversationId=r;this.integrationIdentifier=o}async sendReply(e,n){let r=this._baseBody();return r.reply=e,F(r,n),this._post(r)}async sendApprovalCard(e,n){let r=this._baseBody();return r.reply={toolApprovalCard:e},F(r,n),this._post(r)}async editMessage(e,n){return this._post({...this._baseBody(),edit:{messageId:e,content:n}})}async deleteMessage(e){await this._post({...this._baseBody(),deleteMessages:[{messageId:e}]})}async setTyping(e){await this._post({...this._baseBody(),typing:e})}async flushSideEffects(e){let n=this._baseBody();F(n,e),await this._post(n)}async emitCustom(){}queueRunStart(){}async emitRunFinish(){}async reportTurnError(){await this._post({...this._baseBody(),error:!0})}_baseBody(){return{conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier}}async _post(e){let n=await fetch(this.replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify(e)});if(!n.ok){let o=await n.text().catch(()=>"");throw new m(n.status,o)}let r=await n.text().catch(()=>"");if(!r)return null;try{let o=JSON.parse(r),s=o&&typeof o=="object"&&"data"in o?o.data:o;if(s&&typeof s.messageId=="string"&&typeof s.platformThreadId=="string")return{messageId:s.messageId,platformThreadId:s.platformThreadId}}catch{}return null}},H=class{constructor(e){this.outbox=e}async sendReply(e,n){let r=dt("msg"),o=D(n);return o.push({type:"message",role:"assistant",messageId:r,content:ot(e),files:st(e.files)}),await this._emitAndFlush(o),{messageId:r,platformThreadId:""}}async sendApprovalCard(e,n){return await this._emitAndFlush(D(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(e,n){return await this.outbox.emit({type:"channel.edit",messageId:e,content:ot(n),files:st(n.files)}),{messageId:e,platformThreadId:""}}async deleteMessage(e){await this.outbox.emit({type:"channel.delete",messageId:e})}async setTyping(e){if(e==="stop"){await this.outbox.emit({type:"channel.typing",state:"off"});return}let n=typeof e=="object"&&"status"in e?e.status:void 0;await this.outbox.emit({type:"channel.typing",state:"on",status:n})}async flushSideEffects(e){await this._emitAndFlush(D(e))}async emitCustom(e,n){await this.outbox.emit({type:"custom",name:e,data:n})}queueRunStart(){this.outbox.enqueue({type:"run-start"})}async emitRunFinish(e){await this.outbox.emit({type:"run-finish",outcome:e})}async reportTurnError(e){await this.outbox.emit({type:"run-error",message:e!=null?e:"agent handler failed"})}async _emitAndFlush(e){if(e.length!==0){for(let n of e)this.outbox.enqueue(n);await this.outbox.flush()}}},E=class{constructor(e,n,r){this.transport=r;this.editedByHandler=!1;this.messageId=e,this.platformThreadId=n}async edit(e,n){this.editedByHandler=!0;let r=await ut(e,n==null?void 0:n.files),o=await this.transport.editMessage(this.messageId,r);if(!o)throw new Error("Agent edit did not return a message handle");return this.messageId=o.messageId,this.platformThreadId=o.platformThreadId,this}async delete(){await this.transport.deleteMessage(this.messageId)}},$=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},it;it=ue;var at=class{constructor(e,n,r){this[it]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;var a,p,l,d,y;this.event=e.event,this.action=(a=e.action)!=null?a:null,this.message=e.message,this.reaction=e.reaction,this.conversation=e.conversation,this.subscriber=e.subscriber,this.context=(p=e.context)!=null?p:null,this.notification=(l=e.notification)!=null?l:null,this.history=e.history,this.platform=e.platform,this.platformContext=e.platformContext,this.humanResponse=(d=e.humanResponse)!=null?d:null,this._toolApprovalConfig=r,this._transport=e.eventsUrl?new H(new P({eventsUrl:e.eventsUrl,secretKey:n,conversationId:e.conversationId,agentId:e.agentId,turnId:e.deliveryId})):new M(e.replyUrl,n,e.conversationId,e.integrationIdentifier),this._metadataState={...(y=e.conversation.metadata)!=null?y:{}};let o=this;this.metadata={get(i){return o._metadataState[i]},set(i,x){o._metadataState[i]=x,o._signals.push({type:"metadata",action:"set",key:i,value:x})},delete(i){delete o._metadataState[i],o._signals.push({type:"metadata",action:"delete",key:i})},clear(){o._metadataState={},o._signals.push({type:"metadata",action:"clear"})},get current(){return{...o._metadataState}}};let s=i=>this._transport.setTyping(i),u=(i=>s(i===void 0?{}:{status:i}));u.stop=()=>s("stop"),this.typing=u,this.toolApproval={request:async i=>(await de(this,i,this._toolApprovalConfig),new b)}}asMessageContext(){return this}async reply(e,n){let r=await ut(e,n==null?void 0:n.files),o=this._drainSideEffectsSnapshot(),s=await this._transport.sendReply(r,o);if(!s)throw new Error("Agent reply did not return a message handle");return new E(s.messageId,s.platformThreadId,this._transport)}async replyApprovalCard(e){let n=this._drainSideEffectsSnapshot(),r=await this._transport.sendApprovalCard(e,n);if(r==="unaddressable")return new $;if(!r)throw new Error("Agent approval card reply did not return a message handle");return new E(r.messageId,r.platformThreadId,this._transport)}createReplyHandle(e){return new E(e,"",this._transport)}async emit(e){await this._transport.emitCustom(e.name,e.data)}resolve(e){this._resolveSignal={summary:e}}trigger(e,n){this._signals.push({...n,type:"trigger",workflowId:e})}ask(e,n){return this.queueHumanSignal("ask",e,n)}approve(e,n){return this.queueHumanSignal("approve",e,n)}choose(e,n,r){if(n.length<2||n.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(n.some(o=>typeof o!="string"||o.trim().length===0))throw new Error("ctx.choose options must be non-empty strings");return this.queueHumanSignal("choose",e,r,n)}tell(e,n){return this.queueHumanSignal("tell",e,n)}queueHumanSignal(e,n,r,o){let s=dt("hr"),u=(r==null?void 0:r.to)!==void 0?tt(r.to):void 0;return this._signals.push({type:"human",kind:e,prompt:n,requestId:s,...o?{options:o}:{},...r!=null&&r.from?{from:r.from}:{},...r&&"ttlSeconds"in r&&r.ttlSeconds!==void 0?{ttlSeconds:r.ttlSeconds}:{},...u!==void 0?{to:u}:{}}),s}emitToolApprovalRequest(e){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=e}emitToolResult(e){this._toolResults.push(e)}addReaction(e,n){this._pendingReactions.push({messageId:e,emojiName:n})}deleteMessage(e){this._pendingDeletes.push({messageId:e})}queueRunStart(){this._transport.queueRunStart()}async emitRunFinish(e){try{await this._transport.emitRunFinish(e.outcome)}catch(n){console.error("[agent] Failed to emit run finish:",n)}}async reportTurnError(e){try{await this._transport.reportTurnError(e)}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(!this._hasPendingSideEffects())return;let e=this._drainSideEffectsSnapshot();await this._transport.flushSideEffects(e)}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffectsSnapshot(){let e={toolApprovalRequest:this._pendingToolApprovalRequest,signals:this._signals,toolResults:this._toolResults,addReactions:this._pendingReactions,deleteMessages:this._pendingDeletes,resolve:this._resolveSignal};return this._pendingToolApprovalRequest=null,this._signals=[],this._toolResults=[],this._pendingReactions=[],this._pendingDeletes=[],this._resolveSignal=null,e}};var Ar={type:"object",properties:{},required:[],additionalProperties:!1};var Dt=(l=>(l.PENDING="pending",l.QUEUED="queued",l.RUNNING="running",l.COMPLETED="completed",l.FAILED="failed",l.DELAYED="delayed",l.CANCELED="canceled",l.MERGED="merged",l.SKIPPED="skipped",l))(Dt||{});var Mt=(o=>(o.NONE="none",o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o))(Mt||{});export{ce as a,me as b,fe as c,he as d,ye as e,Re as f,Ae as g,ve as h,Se as i,xe as j,Te as k,Vt as l,Ee as m,_e as n,Ce as o,we as p,A as q,f as r,v as s,Oe as t,Ie as u,Pe as v,ke as w,Ne as x,Ue as y,Fe as z,De as A,Me as B,He as C,$e as D,Le as E,qe as F,nt as G,gt as H,Be as I,je as J,Qe as K,jn as L,Yn as M,S as N,m as O,Qn as P,St as Q,b as R,er as S,at as T,Ar as U,Dt as V,Mt as W};
|