@segmentstream/agent 0.54.0 → 0.56.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 (114) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +12 -6
  3. package/dist/_chunks/{build-metadata-2TyBXJEt.mjs → build-metadata-DqDm9a2E.mjs} +1 -1
  4. package/dist/_chunks/{principal-DUla0Xge.mjs → principal-TJ6zB2rF.mjs} +24 -8
  5. package/dist/extension/channels/email.d.ts +4 -3
  6. package/dist/extension/channels/email.mjs +2 -1
  7. package/dist/extension/channels/slack.d.ts +4 -3
  8. package/dist/extension/channels/slack.mjs +2 -1
  9. package/dist/extension/channels/telegram.d.ts +3 -1
  10. package/dist/extension/channels/telegram.mjs +2 -1
  11. package/dist/extension/channels/whatsapp.d.ts +3 -2
  12. package/dist/extension/channels/whatsapp.mjs +2 -1
  13. package/dist/extension/config.d.ts +212 -66
  14. package/dist/extension/config.mjs +196 -34
  15. package/dist/extension/connections/ontology.mjs +1 -1
  16. package/dist/extension/extension.d.ts +7 -1
  17. package/dist/extension/extension.mjs +2 -1
  18. package/dist/extension/hooks/authorization.mjs +1 -1
  19. package/dist/extension/instructions/persona.mjs +1 -1
  20. package/dist/extension/lib/actor.mjs +1 -1
  21. package/dist/extension/lib/attachment-tools.d.ts +1 -1
  22. package/dist/extension/lib/attachment-tools.mjs +2 -2
  23. package/dist/extension/lib/attachments-send.mjs +1 -1
  24. package/dist/extension/lib/attachments.d.ts +1 -1
  25. package/dist/extension/lib/attachments.mjs +1 -1
  26. package/dist/extension/lib/build-metadata.mjs +1 -1
  27. package/dist/extension/lib/channel-scope.d.ts +67 -0
  28. package/dist/extension/lib/channel-scope.mjs +104 -0
  29. package/dist/extension/lib/chat-address.d.ts +27 -4
  30. package/dist/extension/lib/chat-address.mjs +1 -1
  31. package/dist/extension/lib/chat-archive.d.ts +16 -0
  32. package/dist/extension/lib/chat-archive.mjs +22 -2
  33. package/dist/extension/lib/chat-context.mjs +3 -3
  34. package/dist/extension/lib/chat-post-confirmation.d.ts +14 -3
  35. package/dist/extension/lib/chat-post-confirmation.mjs +9 -3
  36. package/dist/extension/lib/chat-recorder.d.ts +17 -0
  37. package/dist/extension/lib/chat-recorder.mjs +24 -11
  38. package/dist/extension/lib/chats.d.ts +7 -0
  39. package/dist/extension/lib/chats.mjs +31 -1
  40. package/dist/extension/lib/confirmations.mjs +1 -1
  41. package/dist/extension/lib/email/attachments-send.d.ts +1 -1
  42. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  43. package/dist/extension/lib/email/channel.d.ts +11 -3
  44. package/dist/extension/lib/email/channel.mjs +53 -42
  45. package/dist/extension/lib/guest-usage.mjs +1 -1
  46. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  47. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  48. package/dist/extension/lib/ontology-connection.mjs +1 -1
  49. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  50. package/dist/extension/lib/ontology-tools.mjs +1 -1
  51. package/dist/extension/lib/review/client.mjs +1 -0
  52. package/dist/extension/lib/review/hold.d.ts +8 -1
  53. package/dist/extension/lib/review/hold.mjs +4 -2
  54. package/dist/extension/lib/review/reply.mjs +3 -3
  55. package/dist/extension/lib/role-skill.mjs +1 -1
  56. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  57. package/dist/extension/lib/sent-files.mjs +1 -1
  58. package/dist/extension/lib/slack/adapter.d.ts +5 -4
  59. package/dist/extension/lib/slack/adapter.mjs +19 -15
  60. package/dist/extension/lib/slack/attachments-send.d.ts +1 -1
  61. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  62. package/dist/extension/lib/stored-files.mjs +1 -1
  63. package/dist/extension/lib/telegram/adapter.d.ts +8 -2
  64. package/dist/extension/lib/telegram/adapter.mjs +43 -31
  65. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  66. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  67. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  68. package/dist/extension/lib/telegram/chat-archive.mjs +11 -10
  69. package/dist/extension/lib/telegram/chat-post-card.mjs +4 -3
  70. package/dist/extension/lib/telegram/confirmations.mjs +2 -2
  71. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  72. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +2 -1
  73. package/dist/extension/lib/telegram/files.d.ts +4 -1
  74. package/dist/extension/lib/telegram/files.mjs +3 -2
  75. package/dist/extension/lib/telegram/health.mjs +1 -1
  76. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  77. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  78. package/dist/extension/lib/telegram/inbound.mjs +4 -4
  79. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  80. package/dist/extension/lib/telegram/principal.mjs +1 -1
  81. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  82. package/dist/extension/lib/telegram/signals.mjs +2 -1
  83. package/dist/extension/lib/telegram/silent.mjs +1 -1
  84. package/dist/extension/lib/telegram/structured.mjs +1 -1
  85. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  86. package/dist/extension/lib/telegram/workspace-action.mjs +1 -1
  87. package/dist/extension/lib/web/auth.mjs +1 -1
  88. package/dist/extension/lib/web/channel.mjs +1 -1
  89. package/dist/extension/lib/whatsapp/adapter.d.ts +12 -6
  90. package/dist/extension/lib/whatsapp/adapter.mjs +17 -10
  91. package/dist/extension/lib/whatsapp/attachments-send.d.ts +1 -1
  92. package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
  93. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  94. package/dist/extension/lib/workspace-channel/attachments-send.d.ts +35 -0
  95. package/dist/extension/lib/workspace-channel/attachments-send.mjs +119 -0
  96. package/dist/extension/lib/workspace-channel/channel.d.ts +229 -0
  97. package/dist/extension/lib/workspace-channel/channel.mjs +525 -0
  98. package/dist/extension/lib/workspace-channel/connection.d.ts +55 -0
  99. package/dist/extension/lib/workspace-channel/connection.mjs +68 -0
  100. package/dist/extension/lib/workspace-channel/secrets.d.ts +32 -0
  101. package/dist/extension/lib/workspace-channel/secrets.mjs +55 -0
  102. package/dist/extension/lib/workspace-source.d.ts +1 -1
  103. package/dist/extension/lib/workspace-source.mjs +3 -2
  104. package/dist/extension/model.mjs +1 -1
  105. package/dist/extension/tools/attachments_discard.mjs +1 -1
  106. package/dist/extension/tools/attachments_list.mjs +1 -1
  107. package/dist/extension/tools/attachments_promote.mjs +1 -1
  108. package/dist/extension/tools/attachments_read.mjs +1 -1
  109. package/dist/extension/tools/attachments_send.mjs +15 -7
  110. package/dist/extension/tools/attachments_stage.mjs +1 -1
  111. package/dist/extension/tools/attachments_table.mjs +1 -1
  112. package/dist/extension/tools/questions_ask.mjs +1 -1
  113. package/dist/extension/tools/workspace_source.mjs +1 -1
  114. package/package.json +2 -2
@@ -0,0 +1,525 @@
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 { SegmentStreamAgentConfigError, WORKSPACE_CHANNEL_KIND, channelOf, configSchema } from "../../config.mjs";
8
+ import { admitMessage, localizedText } from "../admission.mjs";
9
+ import { agentToolsAttribute } from "../agent-tools.mjs";
10
+ import { providerChat } from "../attachment-tools.mjs";
11
+ import { S as fetchStoredAttachment, b as agentAttachments, bt as withChatAddress, d as prepareInboundMedia, gt as chatAddressOf, i as memberIdOf, m as turnContent, xt as workspaceIdentityProvider } from "../../../_chunks/principal-TJ6zB2rF.mjs";
12
+ import { CHANNEL_ATTRIBUTE, channelKey } from "../channel-scope.mjs";
13
+ import { chatArchive, chatEvent } from "../chat-archive.mjs";
14
+ import { connectionProxy } from "../connection-proxy.mjs";
15
+ import { redactDiagnostic } from "../diagnostics.mjs";
16
+ import { appOrigin, channelsEnabled, proxyEnvironment, runtimeIdentityEnvironment, webhookSecret } from "../environment.mjs";
17
+ import { agentIdentities } from "../identities.mjs";
18
+ import { gatewayMediaCapabilities, turnMediaPlan } from "../inbound-media/plan.mjs";
19
+ import { gatewayImageDescriber } from "../inbound-media/images.mjs";
20
+ import { gatewayTranscriber } from "../inbound-media/speech.mjs";
21
+ import { channelReview } from "../review/reply.mjs";
22
+ import { runtimeTokenVerifier } from "../runtime-identity.mjs";
23
+ import { runtimeToken } from "../runtime-token.mjs";
24
+ import { completionKind } from "../telegram/silent.mjs";
25
+ import { runtimeRequestFailure } from "../telegram/runtime-request.mjs";
26
+ import { channelConnection } from "./connection.mjs";
27
+ import { ChannelCheckUnavailable, channelChecks } from "./secrets.mjs";
28
+ import { decide } from "eve/ai";
29
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
30
+ import { reply } from "eve/events";
31
+ import { WORKSPACE_CHANNEL_ID, workspaceChannelRoute, workspaceChannelSendRoute } from "@segmentstream/ontology/workspace-channel";
32
+ import { POST, defineChannel as defineChannel$1 } from "eve/channels";
33
+ const WORKSPACE_CHANNEL_AUTHENTICATOR = "segmentstream-channel";
34
+ const MAXIMUM_CURSOR_LENGTH = 16384;
35
+ const MAXIMUM_MESSAGES = 50;
36
+ var TooManyMessages = class extends Error {
37
+ name = "TooManyMessages";
38
+ };
39
+ const MAXIMUM_TEXT = 2e4;
40
+ function error(code, status) {
41
+ return Response.json({ error: code }, { status });
42
+ }
43
+ function signed(secret, body, signature) {
44
+ if (signature === null) return false;
45
+ const expected = `sha256=${createHmac("sha256", secret).update(body, "utf8").digest("hex")}`;
46
+ const given = signature.trim().toLowerCase();
47
+ return expected.length === given.length && timingSafeEqual(Buffer.from(expected), Buffer.from(given));
48
+ }
49
+ function isRecord(value) {
50
+ return typeof value === "object" && value !== null && !Array.isArray(value);
51
+ }
52
+ function validMessage(value) {
53
+ if (!isRecord(value) || !isRecord(value.sender)) return;
54
+ const { id, chatId, sender, text, files } = value;
55
+ return typeof id === "string" && WORKSPACE_CHANNEL_ID.test(id) && typeof chatId === "string" && WORKSPACE_CHANNEL_ID.test(chatId) && typeof sender.id === "string" && WORKSPACE_CHANNEL_ID.test(sender.id) && (sender.name === void 0 || typeof sender.name === "string") && typeof text === "string" && (files === void 0 || Array.isArray(files)) ? {
56
+ id,
57
+ chatId,
58
+ sender: {
59
+ id: sender.id,
60
+ ...sender.name?.trim() ? { name: sender.name.trim() } : {}
61
+ },
62
+ text: text.slice(0, MAXIMUM_TEXT),
63
+ ...files === void 0 ? {} : { files }
64
+ } : void 0;
65
+ }
66
+ function splitReply(text, maxLength) {
67
+ if (maxLength === void 0 || text.length <= maxLength) return [text];
68
+ const parts = [];
69
+ let rest = text;
70
+ while (rest.length > maxLength) {
71
+ const window = rest.slice(0, maxLength);
72
+ const end = [
73
+ window.lastIndexOf("\n\n"),
74
+ window.lastIndexOf("\n"),
75
+ window.lastIndexOf(" ")
76
+ ].find((index) => index > 0) ?? maxLength;
77
+ parts.push(rest.slice(0, end).trimEnd());
78
+ rest = rest.slice(end).trimStart();
79
+ }
80
+ if (rest !== "") parts.push(rest);
81
+ return parts;
82
+ }
83
+ function replyText(view, turnId) {
84
+ return reply(view, turnId).filter((part) => part.kind === "text" && part.interrupted !== true).flatMap((part) => typeof part.value === "string" ? [part.value] : []).join("\n").trim();
85
+ }
86
+ function sourceKey(message) {
87
+ return createHash("sha256").update(JSON.stringify([message.chatId, message.id])).digest("base64url");
88
+ }
89
+ function fileKind(contentType) {
90
+ const type = contentType.toLowerCase();
91
+ return type.startsWith("audio/") ? "audio" : type.startsWith("image/") ? "image" : type.startsWith("video/") ? "video" : "document";
92
+ }
93
+ function workspaceChannelPrincipal(channel, member, sender, chatId) {
94
+ return withChatAddress({
95
+ authenticator: WORKSPACE_CHANNEL_AUTHENTICATOR,
96
+ issuer: channel,
97
+ principalId: `${workspaceIdentityProvider(channel)}:${sender.id}`,
98
+ principalType: "user",
99
+ subject: sender.id,
100
+ attributes: {
101
+ memberId: member.id,
102
+ identityProvider: workspaceIdentityProvider(channel),
103
+ roles: member.roles,
104
+ ...agentToolsAttribute(member.agentTools),
105
+ ...member.name === null ? {} : { memberName: member.name },
106
+ ...member.locale === void 0 ? {} : { locale: member.locale },
107
+ [CHANNEL_ATTRIBUTE]: channel
108
+ }
109
+ }, {
110
+ provider: WORKSPACE_CHANNEL_KIND,
111
+ channel,
112
+ chatId,
113
+ threadId: "",
114
+ kind: "private",
115
+ peer: sender.id
116
+ });
117
+ }
118
+ function defineChannel(definition) {
119
+ return defineChannel$1(workspaceChannelDefinition({
120
+ ...definition,
121
+ review: { decide: (options) => decide(options) }
122
+ }));
123
+ }
124
+ function workspaceChannelDefinition(options) {
125
+ const name = options.name;
126
+ const validation = configSchema["~standard"].validate(options.config);
127
+ if (validation.issues !== void 0) throw new SegmentStreamAgentConfigError(validation.issues);
128
+ const config = validation.value;
129
+ const declared = channelOf(config.channels, WORKSPACE_CHANNEL_KIND, name);
130
+ if (declared === null) throw new SegmentStreamAgentConfigError([{
131
+ message: `must declare the channel ${name}, with kind "${WORKSPACE_CHANNEL_KIND}"`,
132
+ path: ["channels", name]
133
+ }]);
134
+ const settings = declared;
135
+ const polled = "poll" in options.receive;
136
+ if (polled !== (settings.receive === "poll")) throw new SegmentStreamAgentConfigError([{
137
+ message: `must be "${polled ? "poll" : "webhook"}", as the channel's code receives`,
138
+ path: [
139
+ "channels",
140
+ name,
141
+ "receive"
142
+ ]
143
+ }]);
144
+ const environment = options.environment ?? process.env;
145
+ const token = options.token ?? runtimeToken;
146
+ const log = options.log ?? ((message, detail) => console.error(message, detail));
147
+ const transport = {
148
+ token,
149
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
150
+ };
151
+ const identity = workspaceIdentityProvider(name);
152
+ const maxLength = options.limits?.maxLength;
153
+ const files = options.limits?.files === true;
154
+ let connection = options.connection;
155
+ let identities = options.identities;
156
+ let attachments = options.attachments;
157
+ let capabilities;
158
+ let reviewed;
159
+ let chats = options.archive ?? options.review?.archive;
160
+ let verifier = options.verify;
161
+ const context = () => ({ connection: connection ??= channelConnection(connectionProxy({
162
+ environment: proxyEnvironment(environment),
163
+ connection: settings.connection,
164
+ ...transport
165
+ })) });
166
+ const people = () => identities ??= agentIdentities({
167
+ origin: appOrigin(environment),
168
+ ...transport
169
+ });
170
+ const stored = () => attachments ??= agentAttachments({
171
+ origin: appOrigin(environment),
172
+ ...transport
173
+ });
174
+ const archive = () => chats ??= chatArchive({
175
+ environment,
176
+ ...transport
177
+ });
178
+ const review = () => options.review === void 0 ? void 0 : reviewed ??= channelReview({
179
+ settings: () => config.review,
180
+ decide: options.review.decide,
181
+ model: () => config.models.decision,
182
+ ...options.review.archive === void 0 ? {} : { archive: options.review.archive },
183
+ ...options.review.hold === void 0 ? {} : { hold: options.review.hold }
184
+ }, {
185
+ environment,
186
+ ...transport
187
+ });
188
+ const report = (operation, cause) => {
189
+ const reference = randomUUID();
190
+ log("[segmentstream] workspace channel diagnostic", {
191
+ channel: name,
192
+ operation,
193
+ reference,
194
+ error: redactDiagnostic(cause, new Set())
195
+ });
196
+ return reference;
197
+ };
198
+ async function deliver(reply) {
199
+ let id = null;
200
+ for (const [index, text] of splitReply(reply.text, maxLength).entries()) {
201
+ const sent = await options.send({
202
+ ...reply,
203
+ text,
204
+ ...index === 0 || reply.files === void 0 ? {} : { files: [] }
205
+ }, context());
206
+ id = typeof sent?.id === "string" && sent.id !== "" ? sent.id : null;
207
+ }
208
+ return id;
209
+ }
210
+ async function dispatch(message, args) {
211
+ const turn = message.text.trim() !== "" || files && (message.files?.length ?? 0) > 0;
212
+ const notice = (text) => deliver({
213
+ chatId: message.chatId,
214
+ to: message.sender.id,
215
+ text
216
+ });
217
+ const resolution = await admitMessage({
218
+ identity: {
219
+ provider: identity,
220
+ externalId: message.sender.id,
221
+ chat: "private",
222
+ turn,
223
+ ...message.sender.name === void 0 ? {} : { display: message.sender.name }
224
+ },
225
+ identities: people(),
226
+ settings: config,
227
+ sendNotice: notice,
228
+ noticeFailed: (cause) => report("notice_failed", cause)
229
+ });
230
+ if (resolution.status === "limited") {
231
+ const replies = config.replies;
232
+ const configured = resolution.scope === "workspaceTurnsPerDay" ? replies.workspaceLimited : resolution.scope === "newUsersPerHour" ? replies.registrationsLimited : replies.perSenderLimited;
233
+ const text = resolution.notify ? localizedText(configured ?? replies.limited) : void 0;
234
+ if (text !== void 0) {
235
+ let delivered = false;
236
+ try {
237
+ await notice(text);
238
+ delivered = true;
239
+ } finally {
240
+ if (resolution.notificationId !== void 0) await people().completeLimitNotice({
241
+ notificationId: resolution.notificationId,
242
+ delivered
243
+ }).catch((cause) => report("limit_notice_completion_failed", cause));
244
+ }
245
+ }
246
+ return;
247
+ }
248
+ if (resolution.status === "pairing_required") {
249
+ const text = localizedText(config.replies.pairingRequired);
250
+ if (text !== void 0 && turn) {
251
+ const code = (await people().createPairing({
252
+ provider: identity,
253
+ externalId: message.sender.id,
254
+ ...message.sender.name === void 0 ? {} : { display: message.sender.name }
255
+ })).code;
256
+ await notice(`${text}\n\n${appOrigin(environment)}/agent/connect?code=${encodeURIComponent(code)}`);
257
+ }
258
+ return;
259
+ }
260
+ if (resolution.status === "refused") {
261
+ const text = localizedText(config.replies.refused);
262
+ if (text !== void 0 && turn) await notice(text);
263
+ return;
264
+ }
265
+ if (!turn) return;
266
+ const auth = workspaceChannelPrincipal(name, resolution.member, message.sender, message.chatId);
267
+ const memberId = memberIdOf(auth);
268
+ const inbound = (files ? message.files ?? [] : []).map((file, index) => ({
269
+ key: `${message.id}:${index}`,
270
+ kind: fileKind(file.contentType),
271
+ filename: file.filename,
272
+ contentType: file.contentType,
273
+ ...file.size === void 0 ? {} : { size: file.size },
274
+ download: async (maxBytes) => {
275
+ const bytes = await file.read();
276
+ if (bytes.byteLength > maxBytes) throw new Error("The attachment is larger than an attachment may be.");
277
+ return bytes;
278
+ }
279
+ }));
280
+ const models = config.models;
281
+ const plan = inbound.length === 0 ? void 0 : await turnMediaPlan({
282
+ models,
283
+ principal: auth,
284
+ capabilities: capabilities ??= options.modelCapabilities ?? gatewayMediaCapabilities(options.fetch, report),
285
+ environment,
286
+ report
287
+ });
288
+ const media = await prepareInboundMedia({
289
+ caption: message.text,
290
+ files: inbound,
291
+ group: false,
292
+ sttModel: models.stt,
293
+ transcribe: options.transcribe ?? gatewayTranscriber,
294
+ report,
295
+ ...plan === void 0 ? {} : { plan },
296
+ describeImage: options.describeImage ?? gatewayImageDescriber,
297
+ ...inbound.length === 0 ? {} : { store: {
298
+ attachments: stored(),
299
+ memberId,
300
+ chat: providerChat(name, message.chatId),
301
+ source: "channel",
302
+ sourceRef: (index) => `${sourceKey(message)}:${index}`
303
+ } }
304
+ });
305
+ const keys = new Map();
306
+ const parts = inbound.filter((file) => media.files.has(file.key) || media.spoken.keys.has(file.key)).map((file) => {
307
+ const part = {
308
+ type: "file",
309
+ data: new Uint8Array(),
310
+ mediaType: file.contentType,
311
+ filename: file.filename
312
+ };
313
+ keys.set(part, file.key);
314
+ return part;
315
+ });
316
+ const content = parts.length === 0 ? media.text : turnContent([{
317
+ type: "text",
318
+ text: media.text
319
+ }, ...parts], {
320
+ files: media.files,
321
+ keyOf: (part) => keys.get(part),
322
+ readStored: true,
323
+ spoken: {
324
+ keys: media.spoken.keys,
325
+ text: ""
326
+ }
327
+ });
328
+ await args.from(channelKey(WORKSPACE_CHANNEL_KIND, name, message.chatId)).send(content, {
329
+ auth,
330
+ idempotencyKey: channelKey(WORKSPACE_CHANNEL_KIND, name, `${WORKSPACE_CHANNEL_KIND}:${message.id}`),
331
+ ...media.context.length === 0 ? {} : { context: media.context }
332
+ });
333
+ }
334
+ async function lastChat(account) {
335
+ const store = archive();
336
+ if (store.lastChat === void 0) return;
337
+ const lookup = await people().lookup({
338
+ provider: identity,
339
+ externalId: account
340
+ });
341
+ return lookup.status === "paired" ? store.lastChat({
342
+ provider: name,
343
+ senderId: account,
344
+ participantId: lookup.member.id
345
+ }) : void 0;
346
+ }
347
+ async function messagesOf(events) {
348
+ const messages = [];
349
+ for (const event of events) {
350
+ const parsed = await options.parse(event, context());
351
+ for (const candidate of Array.isArray(parsed) ? parsed : []) {
352
+ const message = validMessage(candidate);
353
+ if (message === void 0) report("message_invalid", new Error("The channel's parse returned an invalid message."));
354
+ else messages.push(message);
355
+ }
356
+ }
357
+ if (messages.length > 50) throw new TooManyMessages(`The channel's parse read ${messages.length} messages from one delivery or read; at most 50 start turns at once.`);
358
+ return messages;
359
+ }
360
+ async function receive(request, args) {
361
+ if (!channelsEnabled(environment)) return error("not_found", 404);
362
+ const body = await request.text();
363
+ if ("webhook" in options.receive) {
364
+ let verified = false;
365
+ try {
366
+ verified = await options.receive.webhook.verify({
367
+ method: request.method,
368
+ url: request.url,
369
+ headers: request.headers,
370
+ body
371
+ }, options.checks?.(body) ?? channelChecks({
372
+ secret: settings.secret,
373
+ body,
374
+ environment: () => proxyEnvironment(environment),
375
+ token,
376
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch }
377
+ }));
378
+ } catch (cause) {
379
+ report("verify_failed", cause);
380
+ if (cause instanceof ChannelCheckUnavailable) return error("unavailable", 503);
381
+ }
382
+ if (!verified) return error("unauthorized", 401);
383
+ let event = body;
384
+ try {
385
+ event = JSON.parse(body);
386
+ } catch {}
387
+ try {
388
+ for (const message of await messagesOf([event])) await dispatch(message, args);
389
+ } catch (cause) {
390
+ report("webhook_failed", cause);
391
+ return cause instanceof TooManyMessages ? error("too_many_messages", 413) : error("unavailable", 503);
392
+ }
393
+ return Response.json({ received: true });
394
+ }
395
+ const secret = webhookSecret(environment);
396
+ if (secret === void 0 || !signed(secret, body, request.headers.get("x-hub-signature-256"))) return error("unauthorized", 401);
397
+ let wake;
398
+ try {
399
+ wake = JSON.parse(body);
400
+ } catch {
401
+ return error("invalid_request", 400);
402
+ }
403
+ if (!isRecord(wake) || wake.channel !== name || wake.cursor !== null && typeof wake.cursor !== "string") return error("invalid_request", 400);
404
+ try {
405
+ const read = await options.receive.poll.read({
406
+ ...context(),
407
+ cursor: wake.cursor ?? null
408
+ });
409
+ const cursor = read.cursor;
410
+ if (cursor !== null && (typeof cursor !== "string" || cursor.length > MAXIMUM_CURSOR_LENGTH) || !Array.isArray(read.events)) {
411
+ report("read_invalid", new Error("The channel's read returned an invalid cursor or events."));
412
+ return error("unavailable", 503);
413
+ }
414
+ for (const message of await messagesOf(read.events)) await dispatch(message, args);
415
+ return Response.json({
416
+ cursor,
417
+ more: read.more === true
418
+ });
419
+ } catch (cause) {
420
+ report("wake_failed", cause);
421
+ return cause instanceof TooManyMessages ? error("too_many_messages", 413) : error("unavailable", 503);
422
+ }
423
+ }
424
+ async function sendRoute(request) {
425
+ const failure = await runtimeRequestFailure(request, {
426
+ enabled: () => true,
427
+ configured: () => channelsEnabled(environment),
428
+ verify: () => verifier ??= runtimeTokenVerifier(runtimeIdentityEnvironment(environment))
429
+ });
430
+ if (failure !== void 0) return failure;
431
+ let body;
432
+ try {
433
+ body = await request.json();
434
+ } catch {
435
+ return error("invalid_request", 400);
436
+ }
437
+ if (!isRecord(body)) return error("invalid_request", 400);
438
+ const { chat_id: chatId, recipient, reply_to: replyTo, text } = body;
439
+ const sent = Array.isArray(body.files) ? body.files : void 0;
440
+ if (chatId !== null && (typeof chatId !== "string" || !WORKSPACE_CHANNEL_ID.test(chatId)) || typeof recipient !== "string" || !WORKSPACE_CHANNEL_ID.test(recipient) || replyTo !== null && replyTo !== void 0 && (typeof replyTo !== "string" || !WORKSPACE_CHANNEL_ID.test(replyTo)) || typeof text !== "string" || body.files !== void 0 && sent === void 0) return error("invalid_request", 400);
441
+ if (sent !== void 0 && !files) return error("files_unsupported", 422);
442
+ if (sent === void 0 && maxLength !== void 0 && text.length > maxLength) return error("text_too_long", 422);
443
+ const replyFiles = [];
444
+ for (const file of sent ?? []) {
445
+ if (!isRecord(file) || typeof file.filename !== "string" || typeof file.content_type !== "string" || typeof file.data !== "string") return error("invalid_request", 400);
446
+ replyFiles.push({
447
+ filename: file.filename,
448
+ contentType: file.content_type,
449
+ bytes: new Uint8Array(Buffer.from(file.data, "base64"))
450
+ });
451
+ }
452
+ let chat;
453
+ try {
454
+ chat = typeof chatId === "string" ? chatId : await lastChat(recipient);
455
+ } catch (cause) {
456
+ report("chat_lookup_failed", cause);
457
+ return error("unavailable", 503);
458
+ }
459
+ if (chat === void 0) return error("chat_unknown", 422);
460
+ try {
461
+ const reply = {
462
+ chatId: chat,
463
+ to: recipient,
464
+ text,
465
+ ...typeof replyTo === "string" ? { replyTo } : {},
466
+ ...sent === void 0 ? {} : { files: replyFiles }
467
+ };
468
+ const answer = await options.send(reply, context());
469
+ return Response.json({ message_id: typeof answer?.id === "string" && answer.id !== "" ? answer.id : null });
470
+ } catch (cause) {
471
+ const reference = report("send_failed", cause);
472
+ return Response.json({
473
+ error: "send_failed",
474
+ reference
475
+ }, { status: 502 });
476
+ }
477
+ }
478
+ return {
479
+ routes: [POST(workspaceChannelRoute(name), receive), POST(workspaceChannelSendRoute(name), sendRoute)],
480
+ events: { async "turn.settled"(event, ctx) {
481
+ const { outcome, turnId } = event.data;
482
+ const principal = ctx.session.auth.current;
483
+ const chat = chatAddressOf(principal);
484
+ if (outcome !== "completed" || chat?.provider !== "custom" || chat.channel !== name || chat.peer === void 0) return;
485
+ const text = replyText(ctx.view, turnId);
486
+ if (completionKind(text) !== "reply") return;
487
+ const reviewing = review()?.review;
488
+ if (!(reviewing === void 0 ? true : await reviewing.sendOrHold({
489
+ principal,
490
+ sessionId: ctx.session.id,
491
+ turnId,
492
+ partId: turnId,
493
+ text
494
+ }))) return;
495
+ try {
496
+ await deliver({
497
+ chatId: chat.chatId,
498
+ to: chat.peer,
499
+ text
500
+ });
501
+ } catch (cause) {
502
+ report("reply_failed", cause);
503
+ return;
504
+ }
505
+ const memberId = memberIdOf(principal);
506
+ await archive().append(chatEvent({
507
+ eventId: `${WORKSPACE_CHANNEL_KIND}:reply:${ctx.session.id}:${turnId}`,
508
+ provider: name,
509
+ chatId: chat.chatId,
510
+ chatType: "private",
511
+ threadId: null,
512
+ participantIds: memberId === void 0 ? [] : [memberId],
513
+ sessionId: ctx.session.id,
514
+ turnId,
515
+ kind: "outbound",
516
+ text,
517
+ senderId: "agent",
518
+ senderIsBot: true,
519
+ status: "completed"
520
+ }));
521
+ } },
522
+ fetchFile: (url, context) => fetchStoredAttachment(stored(), url, context)
523
+ };
524
+ }
525
+ export { MAXIMUM_MESSAGES, WORKSPACE_CHANNEL_AUTHENTICATOR, defineChannel, splitReply, workspaceChannelDefinition, workspaceChannelPrincipal };
@@ -0,0 +1,55 @@
1
+ import type { ConnectionProxy, ProxyCall } from "../connection-proxy.js";
2
+ /**
3
+ * A workspace channel's connection, as its code calls the provider through it. Calls go through
4
+ * SegmentStream's connection proxy, which adds the provider's credentials, so they never reach the
5
+ * deployment. The options are those of an ontology action's connection calls.
6
+ */
7
+ export type ChannelConnectionMethod = ProxyCall["method"];
8
+ export type QueryValue = string | number | boolean | ReadonlyArray<string | number | boolean>;
9
+ /** The options of `request` and the method helpers. */
10
+ export interface ChannelConnectionRequestOptions {
11
+ /** One of the connection's APIs; the connection's default when omitted. */
12
+ readonly api?: string;
13
+ /** Appended to the path as a query string. `undefined` values are skipped. */
14
+ readonly query?: Readonly<Record<string, QueryValue | undefined>>;
15
+ readonly headers?: Readonly<Record<string, string>> | ReadonlyArray<readonly [string, string]>;
16
+ /** A JSON body, sent with `content-type: application/json`. */
17
+ readonly json?: unknown;
18
+ /** A form body, sent with `content-type: application/x-www-form-urlencoded`. */
19
+ readonly form?: Readonly<Record<string, string>>;
20
+ /** A raw body. Set at most one of `json`, `form` and `body`. */
21
+ readonly body?: string | Uint8Array;
22
+ }
23
+ export interface ChannelConnectionRequest extends ChannelConnectionRequestOptions {
24
+ readonly method: ChannelConnectionMethod;
25
+ /** The path and query relative to the API's base URL. */
26
+ readonly path: string;
27
+ }
28
+ /** The provider's buffered answer. A non-2xx status is an answer, not an error. */
29
+ export interface ChannelConnectionResponse {
30
+ readonly status: number;
31
+ /** `true` for a 2xx status. */
32
+ readonly ok: boolean;
33
+ readonly headers: ReadonlyArray<readonly [string, string]>;
34
+ readonly body: Uint8Array;
35
+ /** The body as UTF-8 text. */
36
+ readonly text: string;
37
+ /** The first value of a header, by case-insensitive name. */
38
+ header(name: string): string | undefined;
39
+ /** The body parsed as JSON; throws when it is not JSON. */
40
+ json(): unknown;
41
+ }
42
+ export interface ChannelConnection {
43
+ /** The connection's key, as `agent/segmentstream.json` names it. */
44
+ readonly key: string;
45
+ request(request: ChannelConnectionRequest): Promise<ChannelConnectionResponse>;
46
+ get(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
47
+ post(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
48
+ put(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
49
+ patch(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
50
+ delete(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
51
+ }
52
+ /** The proxy call of a request: its body encoded and its content type set, as the options say. */
53
+ export declare function connectionCall(request: ChannelConnectionRequest): ProxyCall;
54
+ /** A workspace channel's connection over the deployment's connection proxy. */
55
+ export declare function channelConnection(proxy: ConnectionProxy): ChannelConnection;
@@ -0,0 +1,68 @@
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
+ function queryString(query) {
8
+ const search = new URLSearchParams();
9
+ for (const [name, value] of Object.entries(query ?? {})) {
10
+ if (value === void 0) continue;
11
+ for (const item of Array.isArray(value) ? value : [value]) search.append(name, String(item));
12
+ }
13
+ const text = search.toString();
14
+ return text === "" ? "" : `?${text}`;
15
+ }
16
+ function connectionCall(request) {
17
+ if ((request.json !== void 0 ? 1 : 0) + (request.form !== void 0 ? 1 : 0) + (request.body !== void 0 ? 1 : 0) > 1) throw new TypeError("Set at most one of json, form and body.");
18
+ const headers = Array.isArray(request.headers) ? [...request.headers] : Object.entries(request.headers ?? {});
19
+ const typed = headers.some(([name]) => name.toLowerCase() === "content-type");
20
+ const encoder = new TextEncoder();
21
+ let body = new Uint8Array();
22
+ if (request.json !== void 0) {
23
+ body = encoder.encode(JSON.stringify(request.json));
24
+ if (!typed) headers.push(["content-type", "application/json"]);
25
+ } else if (request.form !== void 0) {
26
+ body = encoder.encode(new URLSearchParams({ ...request.form }).toString());
27
+ if (!typed) headers.push(["content-type", "application/x-www-form-urlencoded"]);
28
+ } else if (request.body !== void 0) body = typeof request.body === "string" ? encoder.encode(request.body) : request.body;
29
+ const separator = request.path.includes("?") && request.query !== void 0 ? "&" : "";
30
+ const query = queryString(request.query);
31
+ return {
32
+ ...request.api === void 0 ? {} : { api: request.api },
33
+ method: request.method,
34
+ path: `${request.path}${separator === "&" ? query.replace("?", "&") : query}`,
35
+ headers,
36
+ body
37
+ };
38
+ }
39
+ function channelConnection(proxy) {
40
+ const request = async (call) => {
41
+ const reply = await proxy.request(connectionCall(call));
42
+ const text = new TextDecoder().decode(reply.body);
43
+ return {
44
+ status: reply.status,
45
+ ok: reply.status >= 200 && reply.status < 300,
46
+ headers: reply.headers,
47
+ body: reply.body,
48
+ text,
49
+ header: (name) => reply.headers.find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1],
50
+ json: () => JSON.parse(text)
51
+ };
52
+ };
53
+ const method = (verb) => (path, options = {}) => request({
54
+ ...options,
55
+ method: verb,
56
+ path
57
+ });
58
+ return {
59
+ key: proxy.connection,
60
+ request,
61
+ get: method("GET"),
62
+ post: method("POST"),
63
+ put: method("PUT"),
64
+ patch: method("PATCH"),
65
+ delete: method("DELETE")
66
+ };
67
+ }
68
+ export { channelConnection, connectionCall };
@@ -0,0 +1,32 @@
1
+ import type { ProxyEnvironment } from "../environment.js";
2
+ import type { RuntimeToken } from "../runtime-token.js";
3
+ /**
4
+ * Checks a workspace channel's code makes of a provider's delivery against the workspace secret
5
+ * the channel's settings name (`channels.<name>.secret`), as the ontology checks its webhooks: the
6
+ * platform reads the secret and answers only whether the check passed, so the secret never reaches
7
+ * the deployment. The deployment asks with its Vercel OIDC token, and only for a secret its
8
+ * deployed agent declares.
9
+ */
10
+ export interface ChannelChecks {
11
+ /**
12
+ * Whether one of `signatures`, hex digests, is the HMAC-SHA256 of the request's body keyed with
13
+ * the secret, as most providers sign their webhooks. Pass the digest without a prefix such as
14
+ * `sha256=`.
15
+ */
16
+ signedWith(signatures: string | ReadonlyArray<string>): Promise<boolean>;
17
+ /** Whether `token` is the secret, as a provider that sends a shared token proves itself. */
18
+ matches(token: string): Promise<boolean>;
19
+ }
20
+ /** The platform could not answer a check: not the request's fault, so the provider tries again. */
21
+ export declare class ChannelCheckUnavailable extends Error {
22
+ readonly name = "ChannelCheckUnavailable";
23
+ constructor(message: string, cause?: unknown);
24
+ }
25
+ /** The checks of one delivery, `body` as it arrived, against the workspace secret `secret`. */
26
+ export declare function channelChecks(input: {
27
+ readonly secret: string | undefined;
28
+ readonly body: string;
29
+ readonly environment: () => ProxyEnvironment;
30
+ readonly token: RuntimeToken;
31
+ readonly fetch?: typeof fetch;
32
+ }): ChannelChecks;