@segmentstream/agent 0.48.0 → 0.50.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.
Files changed (91) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/_chunks/{build-metadata-DjhDPTy-.mjs → build-metadata-CLYC7FWE.mjs} +1 -1
  3. package/dist/_chunks/principal-D5Tualrk.mjs +1836 -0
  4. package/dist/extension/channels/slack.mjs +2 -1
  5. package/dist/extension/channels/whatsapp.mjs +1 -0
  6. package/dist/extension/connections/ontology.mjs +1 -1
  7. package/dist/extension/hooks/authorization.mjs +1 -1
  8. package/dist/extension/instructions/persona.mjs +1 -1
  9. package/dist/extension/lib/actor.mjs +1 -46
  10. package/dist/extension/lib/attachment-tools.mjs +1 -3
  11. package/dist/extension/lib/attachments.d.ts +1 -1
  12. package/dist/extension/lib/attachments.mjs +1 -230
  13. package/dist/extension/lib/build-metadata.mjs +1 -1
  14. package/dist/extension/lib/chat-address.mjs +1 -50
  15. package/dist/extension/lib/chat-context.mjs +1 -1
  16. package/dist/extension/lib/chat-recorder.mjs +1 -2
  17. package/dist/extension/lib/confirmations.mjs +1 -179
  18. package/dist/extension/lib/inbound-media/files.d.ts +91 -0
  19. package/dist/extension/lib/inbound-media/files.mjs +7 -0
  20. package/dist/extension/lib/{telegram → inbound-media}/images.d.ts +2 -0
  21. package/dist/extension/lib/{telegram → inbound-media}/images.mjs +1 -2
  22. package/dist/extension/lib/inbound-media/index.d.ts +55 -0
  23. package/dist/extension/lib/inbound-media/index.mjs +7 -0
  24. package/dist/extension/lib/inbound-media/plan.d.ts +59 -0
  25. package/dist/extension/lib/{telegram/media-policy.mjs → inbound-media/plan.mjs} +56 -4
  26. package/dist/extension/lib/inbound-media/report.d.ts +5 -0
  27. package/dist/extension/lib/inbound-media/report.mjs +7 -0
  28. package/dist/extension/lib/inbound-media/speech.d.ts +52 -0
  29. package/dist/extension/lib/inbound-media/speech.mjs +73 -0
  30. package/dist/extension/lib/ontology-connection.mjs +1 -101
  31. package/dist/extension/lib/ontology-file-call.mjs +1 -4
  32. package/dist/extension/lib/ontology-tools.mjs +1 -377
  33. package/dist/extension/lib/review/hold.mjs +1 -2
  34. package/dist/extension/lib/review/reply.mjs +1 -2
  35. package/dist/extension/lib/role-skill.mjs +1 -1
  36. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  37. package/dist/extension/lib/sent-files.mjs +1 -2
  38. package/dist/extension/lib/slack/adapter.d.ts +49 -7
  39. package/dist/extension/lib/slack/adapter.mjs +79 -21
  40. package/dist/extension/lib/slack/attachments-send.mjs +1 -3
  41. package/dist/extension/lib/slack/files.d.ts +12 -19
  42. package/dist/extension/lib/slack/files.mjs +26 -58
  43. package/dist/extension/lib/stored-files.mjs +1 -3
  44. package/dist/extension/lib/telegram/adapter.d.ts +3 -3
  45. package/dist/extension/lib/telegram/adapter.mjs +13 -17
  46. package/dist/extension/lib/telegram/attachment-description.d.ts +1 -1
  47. package/dist/extension/lib/telegram/attachment-description.mjs +2 -2
  48. package/dist/extension/lib/telegram/attachments-send.mjs +1 -3
  49. package/dist/extension/lib/telegram/callbacks.mjs +1 -2
  50. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  51. package/dist/extension/lib/telegram/confirmations.mjs +1 -3
  52. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  53. package/dist/extension/lib/telegram/files.d.ts +8 -15
  54. package/dist/extension/lib/telegram/files.mjs +32 -107
  55. package/dist/extension/lib/telegram/health.mjs +1 -1
  56. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  57. package/dist/extension/lib/telegram/inbound-request.d.ts +6 -12
  58. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  59. package/dist/extension/lib/telegram/inbound.d.ts +3 -3
  60. package/dist/extension/lib/telegram/inbound.mjs +11 -11
  61. package/dist/extension/lib/telegram/lifecycle.mjs +2 -6
  62. package/dist/extension/lib/telegram/principal.mjs +1 -1
  63. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  64. package/dist/extension/lib/telegram/silent.mjs +1 -1
  65. package/dist/extension/lib/telegram/structured.mjs +1 -1
  66. package/dist/extension/lib/telegram/turn-errors.mjs +1 -2
  67. package/dist/extension/lib/telegram/voice.d.ts +7 -38
  68. package/dist/extension/lib/telegram/voice.mjs +1 -64
  69. package/dist/extension/lib/telegram/workspace-action.mjs +1 -3
  70. package/dist/extension/lib/web/auth.mjs +1 -168
  71. package/dist/extension/lib/web/channel.d.ts +13 -4
  72. package/dist/extension/lib/web/channel.mjs +15 -8
  73. package/dist/extension/lib/whatsapp/adapter.d.ts +37 -1
  74. package/dist/extension/lib/whatsapp/adapter.mjs +118 -21
  75. package/dist/extension/lib/whatsapp/files.d.ts +40 -0
  76. package/dist/extension/lib/whatsapp/files.mjs +70 -0
  77. package/dist/extension/lib/workspace-source.mjs +1 -3
  78. package/dist/extension/model.mjs +1 -1
  79. package/dist/extension/tools/attachments_discard.mjs +1 -1
  80. package/dist/extension/tools/attachments_list.mjs +1 -1
  81. package/dist/extension/tools/attachments_promote.mjs +1 -5
  82. package/dist/extension/tools/attachments_read.mjs +1 -1
  83. package/dist/extension/tools/attachments_send.mjs +1 -2
  84. package/dist/extension/tools/attachments_stage.mjs +1 -1
  85. package/dist/extension/tools/attachments_table.mjs +1 -1
  86. package/dist/extension/tools/questions_ask.mjs +1 -2
  87. package/dist/extension/tools/workspace_source.mjs +1 -1
  88. package/package.json +2 -2
  89. package/dist/_chunks/inbound-request-B3RhCuOw.mjs +0 -413
  90. package/dist/_chunks/principal-Dzs8hUDB.mjs +0 -128
  91. package/dist/extension/lib/telegram/media-policy.d.ts +0 -15
@@ -4,171 +4,4 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { withButtonDecision } from "../confirmation-buttons.mjs";
8
- import { withChatAddress } from "../chat-address.mjs";
9
- import { appOrigin } from "../environment.mjs";
10
- import { runtimeToken } from "../runtime-token.mjs";
11
- import { createHash } from "node:crypto";
12
- import { ForbiddenError, UnauthenticatedError } from "eve/channels/auth";
13
- const WEB_AUTHENTICATOR = "segmentstream-web";
14
- const WEB_PROVIDER = "web";
15
- const AGENT_GRANT_HEADER = "X-SegmentStream-Agent-Grant";
16
- const WEB_GRANT_ATTRIBUTE = "webGrant";
17
- const ACCESS_TOKEN_PREFIX = "sso_";
18
- const INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
19
- const INTROSPECTION_TIMEOUT_MS = 5e3;
20
- const ANSWER_TTL_MS = 6e4;
21
- const ANSWER_LIMIT = 1e3;
22
- const TURN_LIMITED_CODE = "rate_limited";
23
- var TurnLimitedError = class extends ForbiddenError {
24
- retryAfterSeconds;
25
- response;
26
- constructor(retryAfterSeconds) {
27
- super({
28
- code: TURN_LIMITED_CODE,
29
- message: TURN_LIMITED_CODE
30
- });
31
- this.retryAfterSeconds = retryAfterSeconds;
32
- this.name = "TurnLimitedError";
33
- this.response = Response.json({
34
- code: TURN_LIMITED_CODE,
35
- ok: false,
36
- retry_after_seconds: retryAfterSeconds
37
- }, {
38
- status: 429,
39
- headers: {
40
- "cache-control": "no-store",
41
- "retry-after": String(retryAfterSeconds)
42
- }
43
- });
44
- }
45
- };
46
- function strings(value) {
47
- return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
48
- }
49
- function webMemberOf(body) {
50
- if (typeof body !== "object" || body === null) return;
51
- const answer = body;
52
- const roles = strings(answer.roles);
53
- if (answer.active !== true || typeof answer.member_id !== "string" || typeof answer.grant_id !== "string" || answer.chat !== `member:${answer.member_id}` || roles === void 0) return;
54
- const limited = answer.limited;
55
- return {
56
- memberId: answer.member_id,
57
- grant: answer.grant_id,
58
- chat: answer.chat,
59
- roles,
60
- ...typeof answer.name === "string" && answer.name !== "" ? { name: answer.name } : {},
61
- ...typeof limited === "object" && limited !== null && typeof limited.retry_after_seconds === "number" ? { limited: {
62
- scope: typeof limited.scope === "string" ? limited.scope : "",
63
- retryAfterSeconds: limited.retry_after_seconds
64
- } } : {}
65
- };
66
- }
67
- function ontologyIntrospection(options = {}) {
68
- return async (token, origin, turn) => {
69
- const ask = async (body) => (options.fetch ?? fetch)(`${appOrigin(options.environment ?? process.env)}${INTROSPECTION_PATH}`, {
70
- method: "POST",
71
- headers: {
72
- authorization: `Bearer ${await (options.token ?? runtimeToken)()}`,
73
- "content-type": "application/json"
74
- },
75
- body: JSON.stringify(body),
76
- signal: AbortSignal.timeout(INTROSPECTION_TIMEOUT_MS)
77
- });
78
- let response = await ask({
79
- token,
80
- origin,
81
- ...turn === true ? { turn: true } : {}
82
- });
83
- if (turn === true && response.status === 400) response = await ask({
84
- token,
85
- origin
86
- });
87
- if (!response.ok) throw new Error(`The ontology could not say whom an agent token stands for (${response.status}).`);
88
- return webMemberOf(await response.json());
89
- };
90
- }
91
- function webPrincipal(member) {
92
- const chat = {
93
- provider: "web",
94
- chatId: member.chat,
95
- threadId: "",
96
- kind: "private",
97
- peer: member.memberId
98
- };
99
- const attributes = {
100
- memberId: member.memberId,
101
- identityProvider: "web",
102
- roles: member.roles,
103
- [WEB_GRANT_ATTRIBUTE]: member.grant
104
- };
105
- if (member.name !== void 0) attributes.memberName = member.name;
106
- return withChatAddress({
107
- authenticator: WEB_AUTHENTICATOR,
108
- principalId: `web:${member.memberId}`,
109
- principalType: "user",
110
- subject: member.memberId,
111
- attributes
112
- }, chat);
113
- }
114
- function webGrantOf(principal) {
115
- const grant = principal?.attributes[WEB_GRANT_ATTRIBUTE];
116
- return principal?.authenticator === "segmentstream-web" && typeof grant === "string" && grant !== "" ? grant : void 0;
117
- }
118
- function bearerOf(request) {
119
- const header = request.headers.get("authorization") ?? "";
120
- return /^Bearer\s+(.+)$/iu.exec(header.trim())?.[1];
121
- }
122
- async function bodyOf(request) {
123
- if (request.method !== "POST") return;
124
- try {
125
- const body = await request.clone().json();
126
- return typeof body === "object" && body !== null ? body : void 0;
127
- } catch {
128
- return;
129
- }
130
- }
131
- function answersOf(body) {
132
- const answers = body?.answers;
133
- return Array.isArray(answers) ? answers.filter((answer) => typeof answer === "object" && answer !== null && typeof answer.interactionId === "string") : [];
134
- }
135
- function startsTurn(body) {
136
- return body?.message !== void 0 && body.message !== null;
137
- }
138
- function answerCache(introspect) {
139
- const answers = new Map();
140
- return async (token, origin, turn) => {
141
- if (turn === true) return introspect(token, origin, true);
142
- const key = createHash("sha256").update(`${origin} ${token}`).digest("hex");
143
- const now = Date.now();
144
- const kept = answers.get(key);
145
- if (kept !== void 0 && kept.until > now) return kept.member;
146
- answers.delete(key);
147
- const member = await introspect(token, origin, false);
148
- if (member !== void 0) {
149
- if (answers.size >= ANSWER_LIMIT) answers.delete(answers.keys().next().value);
150
- answers.set(key, {
151
- member,
152
- until: now + ANSWER_TTL_MS
153
- });
154
- }
155
- return member;
156
- };
157
- }
158
- function webAuth(options = {}) {
159
- let introspect;
160
- return async (request) => {
161
- const token = bearerOf(request);
162
- if (token === void 0 || !token.startsWith("sso_")) return null;
163
- introspect ??= answerCache(options.introspect ?? ontologyIntrospection());
164
- const body = await bodyOf(request);
165
- const member = await introspect(token, new URL(request.url).origin, startsTurn(body));
166
- if (member === void 0) throw new UnauthenticatedError({
167
- code: "agent_token_invalid",
168
- message: "The agent token is invalid or expired."
169
- });
170
- if (member.limited !== void 0) throw new TurnLimitedError(member.limited.retryAfterSeconds);
171
- return withButtonDecision(webPrincipal(member), answersOf(body));
172
- };
173
- }
174
- export { ACCESS_TOKEN_PREFIX, AGENT_GRANT_HEADER, INTROSPECTION_PATH, TURN_LIMITED_CODE, TurnLimitedError, WEB_AUTHENTICATOR, WEB_GRANT_ATTRIBUTE, WEB_PROVIDER, ontologyIntrospection, webAuth, webGrantOf, webMemberOf, webPrincipal };
7
+ export { K as ACCESS_TOKEN_PREFIX, q as AGENT_GRANT_HEADER, J as INTROSPECTION_PATH, Y as TURN_LIMITED_CODE, X as TurnLimitedError, Z as WEB_AUTHENTICATOR, Q as WEB_GRANT_ATTRIBUTE, $ as WEB_PROVIDER, et as ontologyIntrospection, tt as webAuth, nt as webGrantOf, rt as webMemberOf, it as webPrincipal } from "../../../_chunks/principal-D5Tualrk.mjs";
@@ -1,9 +1,18 @@
1
1
  import { type WebAuthOptions } from "./auth.js";
2
2
  /**
3
- * The agent's own HTTP channel, which browsers talk to: a member who shows an agent token from the
4
- * ontology talks to the agent as themselves, in their own chat; every other request keeps the
5
- * runtime's defaults (this deployment's own functions, local development). The runtime reads this
6
- * channel only from the agent's `agent/channels/eve.ts`, whose name it fixes:
3
+ * Browsers on any origin may call the agent's routes: every request a browser makes carries an
4
+ * agent token as its bearer, never a cookie, and a website's visitors get theirs only from the
5
+ * ontology, on the origins `signUp.origins` names. A refusal's `Retry-After` stays readable.
6
+ */
7
+ export declare const WEB_CORS: {
8
+ readonly origin: "*";
9
+ readonly exposeHeaders: readonly ["retry-after"];
10
+ };
11
+ /**
12
+ * The agent's own HTTP channel, which browsers talk to: a member, or a website's visitor, who shows
13
+ * an agent token from the ontology talks to the agent as themselves, in their own chat; every other
14
+ * request keeps the runtime's defaults (this deployment's own functions, local development). The
15
+ * runtime reads this channel only from the agent's `agent/channels/eve.ts`, whose name it fixes:
7
16
  *
8
17
  * ```ts
9
18
  * import { webChannel } from "@segmentstream/agent/web";
@@ -4,15 +4,22 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { WEB_PROVIDER, webAuth } from "./auth.mjs";
7
+ import { $ as WEB_PROVIDER, tt as webAuth } from "../../../_chunks/principal-D5Tualrk.mjs";
8
8
  import { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";
9
9
  import { eveChannel } from "eve/channels/eve";
10
+ const WEB_CORS = {
11
+ origin: "*",
12
+ exposeHeaders: ["retry-after"]
13
+ };
10
14
  function webChannel(options = {}) {
11
- return eveChannel({ auth: [
12
- webAuth(options),
13
- vercelOidc(),
14
- localDev(),
15
- placeholderAuth()
16
- ] });
15
+ return eveChannel({
16
+ auth: [
17
+ webAuth(options),
18
+ vercelOidc(),
19
+ localDev(),
20
+ placeholderAuth()
21
+ ],
22
+ cors: WEB_CORS
23
+ });
17
24
  }
18
- export { WEB_PROVIDER, webAuth, webChannel };
25
+ export { WEB_CORS, WEB_PROVIDER, webAuth, webChannel };
@@ -1,7 +1,11 @@
1
1
  import { WhatsAppAdapter } from "@chat-adapter/whatsapp";
2
2
  import { type Message, type PostableCard, type WebhookOptions } from "chat";
3
3
  import type { SessionAuthContext } from "eve/context";
4
- import type { AdmissionSettings, WhatsAppSettings } from "../../config.js";
4
+ import type { AdmissionSettings, ChatModelChoice, WhatsAppSettings } from "../../config.js";
5
+ import { type AgentAttachments } from "../attachments.js";
6
+ import { type ImageDescriber } from "../inbound-media/images.js";
7
+ import { type CapabilityLookup } from "../inbound-media/plan.js";
8
+ import { type Transcriber } from "../inbound-media/speech.js";
5
9
  import { type ChannelReviewOptions } from "../review/reply.js";
6
10
  import { type ConnectionProxy } from "../connection-proxy.js";
7
11
  import { type Environment } from "../environment.js";
@@ -15,6 +19,10 @@ import { type RuntimeToken } from "../runtime-token.js";
15
19
  * through the workspace's `WhatsAppConnection` by the connection proxy, which addresses the number
16
20
  * as `/phone`: no Meta token or number ID enters this process.
17
21
  *
22
+ * A message's media goes through the inbound media pipeline, as in every channel: a voice note is
23
+ * transcribed and every file is stored as the member's attachment before the turn. eve keeps the
24
+ * file parts of the other files and downloads them through this adapter when the turn starts.
25
+ *
18
26
  * Only paired members are answered. A sender nobody paired gets the workspace's
19
27
  * `replies.pairingRequired` text with a button labelled `replies.pairingButton` that opens the
20
28
  * app's `/agent/connect`, or the text followed by the link where the workspace sets no label.
@@ -39,6 +47,20 @@ export interface WhatsAppChannelOptions {
39
47
  readonly identities?: AgentIdentities;
40
48
  /** Who sends the agent's replies, from `review`; without it every reply is sent. */
41
49
  readonly review?: ChannelReviewOptions;
50
+ /**
51
+ * `models` of `agent/segmentstream.json`: `stt` transcribes voice notes, and `chat` with
52
+ * `imageDescription` decides how images reach the model. Without it voice is not transcribed.
53
+ */
54
+ readonly models?: () => {
55
+ readonly stt: string | false;
56
+ readonly chat?: ChatModelChoice | null;
57
+ readonly imageDescription?: string | false | null;
58
+ };
59
+ /** Where members' files are stored as attachments; tests pass their own. */
60
+ readonly attachments?: AgentAttachments;
61
+ readonly transcribe?: Transcriber;
62
+ readonly describeImage?: ImageDescriber;
63
+ readonly modelCapabilities?: CapabilityLookup;
42
64
  }
43
65
  /** What the adapter reads per request: eve binds the mount after it loads the channel. */
44
66
  interface WhatsAppRuntime {
@@ -62,6 +84,20 @@ export declare class ProxiedWhatsAppAdapter extends WhatsAppAdapter {
62
84
  protected graphApiUpload<T = unknown>(): Promise<T>;
63
85
  /** The media's URL by `GET /media/{id}`, then its bytes through the connection's `media` API. */
64
86
  downloadMedia(mediaId: string): Promise<Buffer>;
87
+ /** {@link downloadMedia}, failing once the bytes exceed `maxBytes`. */
88
+ fetchMedia(mediaId: string, maxBytes: number, abortSignal?: AbortSignal): Promise<Uint8Array>;
89
+ /**
90
+ * The Chat SDK adapter's typing indicator, on the inbound message the turn's durable state names.
91
+ * The adapter looks the message up in its in-memory history, which is empty in the invocation
92
+ * that runs the turn. eve's channel state keeps the latest inbound message's id, which
93
+ * {@link withDurableTyping} supplies, and its thread passes its current message's. Meta shows
94
+ * the indicator for up to 25 seconds or until the reply; eve repeats it as the turn starts and on
95
+ * each tool call. A failure is logged and never fails the turn.
96
+ */
97
+ startTyping(threadId: string, _status?: string, options?: {
98
+ readonly initiatorUserId?: string;
99
+ readonly messageId?: string;
100
+ }): Promise<void>;
65
101
  }
66
102
  /** The adapter addresses the number by its ID, which here is the proxy's `/phone` alias. */
67
103
  export declare function proxyPath(path: string): string;
@@ -5,8 +5,13 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { admitMessage, localizedText } from "../admission.mjs";
8
+ import { providerChat } from "../attachment-tools.mjs";
9
+ import { S as agentAttachments, ct as withChatAddress, d as prepareInboundMedia, i as memberIdOf } from "../../../_chunks/principal-D5Tualrk.mjs";
10
+ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
11
+ import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.mjs";
12
+ import { gatewayTranscriber } from "../inbound-media/speech.mjs";
13
+ import { whatsappMedia, whatsappTurnContent } from "./files.mjs";
8
14
  import { chatSdkButtonAnswer, withButtonDecision } from "../confirmation-buttons.mjs";
9
- import { withChatAddress } from "../chat-address.mjs";
10
15
  import { channelReview, withReviewedReplies } from "../review/reply.mjs";
11
16
  import { redactDiagnostic } from "../diagnostics.mjs";
12
17
  import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs";
@@ -14,7 +19,8 @@ import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../
14
19
  import { agentIdentities } from "../identities.mjs";
15
20
  import { runtimeToken } from "../runtime-token.mjs";
16
21
  import { withPlainLinks } from "./links.mjs";
17
- import { createHash, createHmac, timingSafeEqual } from "node:crypto";
22
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
23
+ import { AsyncLocalStorage } from "node:async_hooks";
18
24
  import { createMemoryState } from "@chat-adapter/state-memory";
19
25
  import { WhatsAppAdapter, WhatsAppApiError } from "@chat-adapter/whatsapp";
20
26
  import { Actions, Card, CardText, ConsoleLogger, LinkButton } from "chat";
@@ -28,6 +34,26 @@ const MEDIA_ORIGIN = "https://lookaside.fbsbx.com";
28
34
  var WhatsAppProxyRouteError = class extends Error {
29
35
  name = "WhatsAppProxyRouteError";
30
36
  };
37
+ const typingTarget = new AsyncLocalStorage();
38
+ const TYPING_EVENTS = ["turn.started", "call.requested"];
39
+ function withDurableTyping(channel) {
40
+ const adapter = channel.adapter;
41
+ if (adapter === void 0) return channel;
42
+ const handlers = TYPING_EVENTS.flatMap((type) => {
43
+ const handler = adapter[type];
44
+ return typeof handler !== "function" ? [] : [[type, (event, context) => {
45
+ const latest = context.state?.latestMessageId;
46
+ return typingTarget.run(typeof latest === "string" ? latest : void 0, () => handler(event, context));
47
+ }]];
48
+ });
49
+ return {
50
+ ...channel,
51
+ adapter: {
52
+ ...adapter,
53
+ ...Object.fromEntries(handlers)
54
+ }
55
+ };
56
+ }
31
57
  var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
32
58
  #runtime;
33
59
  constructor(runtime) {
@@ -43,6 +69,9 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
43
69
  });
44
70
  this.#runtime = runtime;
45
71
  this.formatConverter = withPlainLinks(this.formatConverter);
72
+ const typing = this;
73
+ const fromHistory = typing.resolveTypingTargetMessageId?.bind(this);
74
+ if (fromHistory !== void 0) typing.resolveTypingTargetMessageId = async (threadId) => typingTarget.getStore() ?? await fromHistory(threadId);
46
75
  }
47
76
  async handleWebhook(request, options) {
48
77
  if (!this.#runtime.enabled()) return new Response(null, { status: 404 });
@@ -68,6 +97,9 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
68
97
  throw new WhatsAppProxyRouteError("The WhatsApp connection does not admit media uploads; send media by link.");
69
98
  }
70
99
  async downloadMedia(mediaId) {
100
+ return Buffer.from(await this.fetchMedia(mediaId, MAXIMUM_DOWNLOAD_BYTES));
101
+ }
102
+ async fetchMedia(mediaId, maxBytes, abortSignal) {
71
103
  if (!/^[0-9]{1,32}$/.test(mediaId)) throw new WhatsAppProxyRouteError("A WhatsApp media ID is numeric.");
72
104
  const described = await this.#graph({
73
105
  api: "graph",
@@ -75,7 +107,7 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
75
107
  path: `/media/${mediaId}`,
76
108
  headers: [],
77
109
  body: new Uint8Array()
78
- }, "Failed to get media URL");
110
+ }, "Failed to get media URL", abortSignal);
79
111
  const url = typeof described.url === "string" ? new URL(described.url) : void 0;
80
112
  if (url === void 0 || url.origin !== MEDIA_ORIGIN) throw new WhatsAppProxyRouteError("WhatsApp media is downloaded only from its own host.");
81
113
  const reply = await this.#runtime.proxy().download({
@@ -84,12 +116,19 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
84
116
  path: `${url.pathname}${url.search}`,
85
117
  headers: [],
86
118
  body: new Uint8Array()
87
- }, MAXIMUM_DOWNLOAD_BYTES);
119
+ }, Math.min(maxBytes, MAXIMUM_DOWNLOAD_BYTES), abortSignal);
88
120
  if (reply.status < 200 || reply.status >= 300) throw new WhatsAppApiError(`Failed to download media ${mediaId}`, reply.status, new TextDecoder().decode(reply.body));
89
- return Buffer.from(reply.body);
121
+ return reply.body;
90
122
  }
91
- async #graph(call, label) {
92
- const reply = await this.#runtime.proxy().request(call);
123
+ async startTyping(threadId, _status, options) {
124
+ try {
125
+ await typingTarget.run(typingTarget.getStore() ?? options?.messageId, () => super.startTyping(threadId));
126
+ } catch (error) {
127
+ report("typing_failed", error);
128
+ }
129
+ }
130
+ async #graph(call, label, abortSignal) {
131
+ const reply = await this.#runtime.proxy().request(call, abortSignal);
93
132
  const text = new TextDecoder().decode(reply.body);
94
133
  if (reply.status < 200 || reply.status >= 300) throw new WhatsAppApiError(label, reply.status, text);
95
134
  return JSON.parse(text);
@@ -105,6 +144,16 @@ function report(operation, error) {
105
144
  error: redactDiagnostic(error, new Set())
106
145
  });
107
146
  }
147
+ function reportWithReference(operation, error, metadata = {}) {
148
+ const reference = randomUUID();
149
+ console.error("[segmentstream] WhatsApp delivery diagnostic", {
150
+ ...metadata,
151
+ operation,
152
+ reference,
153
+ error: redactDiagnostic(error, new Set())
154
+ });
155
+ return reference;
156
+ }
108
157
  function digest(value) {
109
158
  return createHash("sha256").update(value, "utf8").digest();
110
159
  }
@@ -160,9 +209,17 @@ function segmentstreamWhatsApp(options) {
160
209
  });
161
210
  return lookup.status === "paired" ? whatsappPrincipal(lookup.member, sender) : null;
162
211
  }
212
+ let store = options.attachments;
213
+ const attachments = () => store ??= agentAttachments({
214
+ origin: appOrigin(environment),
215
+ token,
216
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
217
+ });
218
+ const capabilities = options.modelCapabilities ?? gatewayMediaCapabilities(options.fetch, reportWithReference);
219
+ const adapter = new ProxiedWhatsAppAdapter(runtime);
163
220
  const bridge = chatSdkChannel({
164
221
  userName: "agent",
165
- adapters: { whatsapp: new ProxiedWhatsAppAdapter(runtime) },
222
+ adapters: { whatsapp: adapter },
166
223
  state: createMemoryState(),
167
224
  streaming: false,
168
225
  resolveInputAuth: async (event) => {
@@ -171,24 +228,64 @@ function segmentstreamWhatsApp(options) {
171
228
  return principal === null || answer === void 0 ? principal : withButtonDecision(principal, [answer]);
172
229
  }
173
230
  });
174
- bridge.bot.onDirectMessage((thread, message) => receive({
175
- thread,
176
- message,
177
- admission: options.admission(),
178
- identities: pairing(),
179
- environment
180
- }).then((admitted) => admitted === void 0 ? void 0 : bridge.send(messageContentOf(message), {
181
- thread,
182
- idempotencyKey: message.id,
183
- auth: admitted
184
- })).then(() => void 0));
185
- if (options.review === void 0) return bridge.channel;
231
+ bridge.bot.onDirectMessage(async (thread, message) => {
232
+ const auth = await receive({
233
+ thread,
234
+ message,
235
+ admission: options.admission(),
236
+ identities: pairing(),
237
+ environment
238
+ });
239
+ const memberId = memberIdOf(auth);
240
+ if (auth === void 0 || memberId === void 0) return;
241
+ const { caption, files } = whatsappMedia({
242
+ message,
243
+ download: (mediaId, maxBytes, abortSignal) => adapter.fetchMedia(mediaId, maxBytes, abortSignal)
244
+ });
245
+ const models = options.models?.();
246
+ const plan = files.length === 0 || models === void 0 ? void 0 : await turnMediaPlan({
247
+ models,
248
+ principal: auth,
249
+ capabilities,
250
+ environment,
251
+ report: reportWithReference
252
+ });
253
+ const media = await prepareInboundMedia({
254
+ caption,
255
+ files,
256
+ group: false,
257
+ sttModel: models?.stt ?? false,
258
+ transcribe: options.transcribe ?? gatewayTranscriber,
259
+ report: reportWithReference,
260
+ ...plan === void 0 ? {} : { plan },
261
+ describeImage: options.describeImage ?? gatewayImageDescriber,
262
+ store: {
263
+ attachments: attachments(),
264
+ memberId,
265
+ chat: providerChat("whatsapp", thread.id),
266
+ source: "whatsapp",
267
+ sourceRef: (index) => `${thread.id}:${message.id}:${index}`
268
+ }
269
+ });
270
+ await bridge.send(whatsappTurnContent({
271
+ content: messageContentOf(message),
272
+ message,
273
+ media
274
+ }), {
275
+ thread,
276
+ idempotencyKey: message.id,
277
+ auth,
278
+ ...media.context.length === 0 ? {} : { context: media.context }
279
+ });
280
+ });
281
+ const channel = withDurableTyping(bridge.channel);
282
+ if (options.review === void 0) return channel;
186
283
  const reviewed = channelReview(options.review, {
187
284
  environment,
188
285
  token,
189
286
  ...options.fetch === void 0 ? {} : { fetch: options.fetch }
190
287
  });
191
- return withReviewedReplies(bridge.channel, () => reviewed.review, () => reviewed.archive);
288
+ return withReviewedReplies(channel, () => reviewed.review, () => reviewed.archive);
192
289
  }
193
290
  async function receive(input) {
194
291
  const { thread, message, admission, identities } = input;
@@ -0,0 +1,40 @@
1
+ import type { MessageContent } from "eve/channels";
2
+ import type { InboundFile, PreparedMedia } from "../inbound-media/index.js";
3
+ /**
4
+ * A WhatsApp message's media (`docs/agent.md`, "Attachments"), described for the inbound media
5
+ * pipeline from the message Meta's webhook delivered, which the Chat SDK adapter keeps as the
6
+ * message's `raw.message`. The adapter's own attachments lose what the pipeline needs: a voice
7
+ * note is `audio` with `voice: true`, and a caption is only the message's text. Each file is
8
+ * downloaded by its media id through the connection, as the adapter downloads it.
9
+ */
10
+ /** Downloads WhatsApp media by its id through the connection, at most `maxBytes`. */
11
+ export type WhatsAppMediaDownload = (mediaId: string, maxBytes: number, abortSignal?: AbortSignal) => Promise<Uint8Array>;
12
+ /** What a WhatsApp message carries: its caption, or its text, and its media files. */
13
+ export declare function whatsappMedia(input: {
14
+ /** The message's text as the Chat SDK adapter gives it, and Meta's message as `raw.message`. */
15
+ readonly message: {
16
+ readonly text: string;
17
+ readonly raw: unknown;
18
+ };
19
+ readonly download: WhatsAppMediaDownload;
20
+ }): {
21
+ readonly caption: string;
22
+ readonly files: ReadonlyArray<InboundFile>;
23
+ };
24
+ /**
25
+ * The turn's message: its text, with each spoken file's transcript, then eve's file part for each
26
+ * other file, which eve downloads through the adapter when the turn starts. eve's message content
27
+ * is the text, when not empty, followed by one part per attachment in order; a spoken file's part
28
+ * is left out, and an image the chat model does not read natively becomes its description.
29
+ */
30
+ export declare function whatsappTurnContent(input: {
31
+ /** eve's content for the message, from `messageContentOf`. */
32
+ readonly content: string | MessageContent;
33
+ readonly message: {
34
+ readonly text: string;
35
+ readonly attachments: ReadonlyArray<{
36
+ readonly fetchMetadata?: Record<string, unknown>;
37
+ }>;
38
+ };
39
+ readonly media: PreparedMedia;
40
+ }): string | MessageContent;
@@ -0,0 +1,70 @@
1
+ import { fileURLToPath as __eveFileURLToPath } from "node:url";
2
+ import { dirname as __eveDirname } from "node:path";
3
+ import { createRequire as __eveCreateRequire } from "node:module";
4
+ const __filename = __eveFileURLToPath(import.meta.url);
5
+ __eveDirname(__filename);
6
+ __eveCreateRequire(import.meta.url);
7
+ import { m as turnContent } from "../../../_chunks/principal-D5Tualrk.mjs";
8
+ function record(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
10
+ }
11
+ function text(value) {
12
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
13
+ }
14
+ const MEDIA = [
15
+ "image",
16
+ "document",
17
+ "audio",
18
+ "video",
19
+ "voice",
20
+ "sticker"
21
+ ];
22
+ function kindOf(field, media) {
23
+ switch (field) {
24
+ case "audio": return media.voice === true ? "voice" : "audio";
25
+ case "voice": return "voice";
26
+ default: return field;
27
+ }
28
+ }
29
+ function whatsappMedia(input) {
30
+ const inbound = record(record(input.message.raw)?.message) ?? {};
31
+ const files = MEDIA.flatMap((field) => {
32
+ const media = record(inbound[field]);
33
+ const id = media?.id;
34
+ if (media === void 0 || typeof id !== "string" || id === "") return [];
35
+ const kind = kindOf(field, media);
36
+ return [{
37
+ key: id,
38
+ kind,
39
+ filename: text(media.filename) ?? kind,
40
+ contentType: text(media.mime_type)?.split(";")[0]?.trim().toLowerCase() ?? "application/octet-stream",
41
+ download: (maxBytes, abortSignal) => input.download(id, maxBytes, abortSignal)
42
+ }];
43
+ });
44
+ return {
45
+ caption: files.length === 0 ? input.message.text : MEDIA.map((field) => text(record(inbound[field])?.caption)).find(Boolean) ?? "",
46
+ files
47
+ };
48
+ }
49
+ function whatsappTurnContent(input) {
50
+ const { content, message, media } = input;
51
+ const parts = typeof content === "string" ? [] : content.slice(message.text === "" ? 0 : 1);
52
+ const keys = new Map(parts.flatMap((part, index) => {
53
+ const mediaId = message.attachments[index]?.fetchMetadata?.mediaId;
54
+ return typeof mediaId === "string" ? [[part, mediaId]] : [];
55
+ }));
56
+ const turn = turnContent([...media.text === "" ? [] : [{
57
+ type: "text",
58
+ text: media.text
59
+ }], ...parts], {
60
+ files: media.files,
61
+ keyOf: (part) => keys.get(part),
62
+ spoken: {
63
+ keys: media.spoken.keys,
64
+ text: ""
65
+ }
66
+ });
67
+ if (typeof turn === "string") return turn;
68
+ return turn.length === 0 ? media.text : turn.length === 1 && turn[0]?.type === "text" ? turn[0].text : turn;
69
+ }
70
+ export { whatsappMedia, whatsappTurnContent };
@@ -4,9 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
4
4
  const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
- import { actorHeaders, actorOf } from "./actor.mjs";
8
- import { CHAT_HEADER, SESSION_HEADER } from "./attachments.mjs";
9
- import { chatAddressOf } from "./chat-address.mjs";
7
+ import { U as actorOf, V as actorHeaders, ot as chatAddressOf, v as CHAT_HEADER, x as SESSION_HEADER } from "../../_chunks/principal-D5Tualrk.mjs";
10
8
  import { sandboxRecord } from "./sandbox-session.mjs";
11
9
  import { defineState } from "eve/context";
12
10
  import { gunzipSync } from "node:zlib";
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { chatModelChoiceOf } from "./config.mjs";
8
8
  import { isPreview } from "./lib/environment.mjs";
9
- import { a as rolesOf } from "../_chunks/principal-Dzs8hUDB.mjs";
9
+ import { a as rolesOf } from "../_chunks/principal-D5Tualrk.mjs";
10
10
  import { defineDynamic } from "eve";
11
11
  import { runs } from "eve/events";
12
12
  function chooseModel(input) {
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
8
8
  import { ID_INPUT, attachmentForModel, attachmentOwner, stringArgument, toolAttachments } from "../lib/attachment-tools.mjs";
9
- import { memberTool } from "../lib/actor.mjs";
9
+ import { G as memberTool } from "../../_chunks/principal-D5Tualrk.mjs";
10
10
  import { defineTool } from "eve/tools";
11
11
  const tool = defineTool({
12
12
  description: "Discard a file the member sent, by its attachment id, when it should not be kept. It cannot be read or promoted afterwards.",
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { n as workflowToolResult } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
8
8
  import { attachmentForModel, attachmentOwner, toolAttachments } from "../lib/attachment-tools.mjs";
9
- import { memberTool } from "../lib/actor.mjs";
9
+ import { G as memberTool } from "../../_chunks/principal-D5Tualrk.mjs";
10
10
  import { defineTool } from "eve/tools";
11
11
  const tool = defineTool({
12
12
  description: "List the files the member you act for sent in this chat that are still kept: their ids, names, types, sizes and when they expire. Files are kept for 24 hours unless promoted.",