@andreprado/agentkit 0.1.0-alpha.9 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -1
- package/docs/guides/add-channel.md +251 -7
- package/docs/guides/add-knowledge.md +10 -0
- package/docs/guides/add-managed-composio.md +165 -0
- package/docs/guides/add-tool.md +10 -3
- package/docs/guides/channel-security.md +162 -32
- package/docs/guides/connect-discord.md +178 -0
- package/docs/guides/connect-slack.md +126 -0
- package/docs/guides/connect-telegram.md +61 -1
- package/docs/guides/connect-whatsapp-evolution.md +121 -0
- package/docs/guides/connect-whatsapp-uazapi.md +139 -0
- package/docs/guides/connect-whatsapp-zapster.md +119 -16
- package/docs/guides/create-agent.md +31 -4
- package/docs/guides/debug-channel.md +159 -0
- package/docs/guides/improve-from-production.md +151 -0
- package/docs/guides/prepare-deploy.md +32 -14
- package/docs/guides/replay-production-traces.md +72 -0
- package/docs/guides/run-evals.md +95 -25
- package/docs/guides/security-rules.md +9 -5
- package/docs/guides/send-feedback.md +135 -0
- package/docs/guides/use-jev.md +67 -0
- package/docs/guides/use-provider.md +70 -3
- package/docs/llms-full.txt +295 -25
- package/docs/llms.txt +54 -7
- package/package.json +3 -7
- package/src/cli/args.ts +23 -2
- package/src/cli/cloud-client.ts +121 -9
- package/src/cli/commands/channels.ts +856 -36
- package/src/cli/commands/feedback.ts +438 -0
- package/src/cli/commands/provider.ts +47 -0
- package/src/cli/commands/transcribe.ts +171 -0
- package/src/cli/deploy-chat-ui.ts +232 -18
- package/src/cli/deploy-readiness.ts +227 -14
- package/src/cli/help.ts +67 -9
- package/src/cli/index.ts +740 -35
- package/src/cli/new-command.ts +41 -0
- package/src/cloud/client.ts +4 -3
- package/src/cloud/contracts.ts +1 -1
- package/src/create-project.ts +18 -35
- package/src/index.ts +565 -11
- package/src/providers/codex-auth.ts +111 -0
- package/src/providers/pi.ts +88 -19
- package/src/providers/test.ts +36 -0
- package/src/providers/types.ts +8 -0
- package/src/runtime/channel-test-harness.ts +21 -1
- package/src/runtime/channels/discord.ts +896 -0
- package/src/runtime/channels/generic-webhook.ts +974 -0
- package/src/runtime/channels/slack.ts +646 -0
- package/src/runtime/channels/telegram.ts +343 -12
- package/src/runtime/channels/whatsapp-evolution.ts +1357 -0
- package/src/runtime/channels/whatsapp-meta.ts +9 -0
- package/src/runtime/channels/whatsapp-uazapi.ts +1323 -0
- package/src/runtime/channels/whatsapp-zapster.ts +674 -40
- package/src/runtime/channels.ts +83 -3
- package/src/runtime/chat.ts +70 -44
- package/src/runtime/config.ts +489 -20
- package/src/runtime/core/manifest.ts +75 -5
- package/src/runtime/core/targets.ts +5 -5
- package/src/runtime/deploy-readiness.ts +34 -4
- package/src/runtime/dev-server.ts +639 -39
- package/src/runtime/env.ts +8 -3
- package/src/runtime/evals.ts +445 -74
- package/src/runtime/improve.ts +868 -0
- package/src/runtime/inspect.ts +173 -4
- package/src/runtime/integrations/composio.ts +425 -0
- package/src/runtime/knowledge/retrieve.ts +25 -5
- package/src/runtime/knowledge/schema.ts +45 -1
- package/src/runtime/prompt-context.ts +141 -0
- package/src/runtime/runtime-contract.ts +71 -7
- package/src/runtime/skills.ts +95 -0
- package/src/runtime/targets/cloudflare/build.ts +1010 -208
- package/src/runtime/targets/container/server.ts +1 -1
- package/src/runtime/targets/vps/deploy.ts +26 -9
- package/src/runtime/tool-runner.ts +9 -1
- package/src/runtime/tools.ts +26 -2
- package/src/runtime/transcription.ts +483 -0
- package/src/storage/sqlite.ts +7 -2
- package/src/templates/blank.ts +37 -9
- package/src/templates/dentista.ts +40 -14
- package/src/templates/skills/agentkit-build-agent/SKILL.md +34 -5
- package/src/templates/skills/agentkit-build-agent/templates/appointment-intake.instructions.md +2 -1
- package/src/templates/skills/agentkit-capsule/SKILL.md +32 -3
- package/src/templates/skills/agentkit-capsule/references/docs-router.md +2 -2
- package/src/templates/skills/agentkit-channels/SKILL.md +66 -1
- package/src/templates/skills/agentkit-channels/references/channel-buffering.md +8 -1
- package/src/templates/skills/agentkit-channels/references/channel-debugging.md +28 -3
- package/src/templates/skills/agentkit-channels/references/discord.md +93 -0
- package/src/templates/skills/agentkit-channels/references/slack.md +56 -0
- package/src/templates/skills/agentkit-channels/references/telegram.md +34 -0
- package/src/templates/skills/agentkit-channels/references/whatsapp-evolution.md +57 -0
- package/src/templates/skills/agentkit-channels/references/whatsapp-uazapi.md +54 -0
- package/src/templates/skills/agentkit-channels/references/whatsapp-zapster.md +42 -8
- package/src/templates/skills/agentkit-database/SKILL.md +11 -0
- package/src/templates/skills/agentkit-deploy/SKILL.md +9 -1
- package/src/templates/skills/agentkit-evals/SKILL.md +77 -13
- package/src/templates/skills/agentkit-evals/templates/multi-turn.eval.md +13 -6
- package/src/templates/skills/agentkit-evals/templates/no-leak.eval.md +8 -4
- package/src/templates/skills/agentkit-evals/templates/smoke.eval.md +8 -4
- package/src/templates/skills/agentkit-evals/templates/tool-call.eval.md +16 -7
- package/src/templates/skills/agentkit-improve/SKILL.md +96 -0
- package/src/templates/skills/agentkit-improve/references/replay-side-effects.md +18 -0
- package/src/templates/skills/agentkit-improve/references/trace-packets.md +22 -0
- package/src/templates/skills/agentkit-improve/templates/regression.eval.md +18 -0
- package/src/templates/skills/agentkit-integrations/SKILL.md +98 -0
- package/src/templates/skills/agentkit-knowledge/SKILL.md +4 -1
- package/src/templates/skills/agentkit-prompts/SKILL.md +3 -1
- package/src/templates/skills/agentkit-provider/SKILL.md +29 -4
- package/src/templates/skills/agentkit-security/SKILL.md +5 -2
- package/src/templates/skills/agentkit-tools/SKILL.md +8 -1
- package/src/templates/skills/agentkit-tools/examples/eval-safe-external-action.tool.md +8 -8
- package/src/templates/skills/agentkit-tools/examples/jev-service-fit.tool.md +110 -0
- package/src/templates/skills/agentkit-troubleshooting/SKILL.md +25 -1
- package/src/templates/support.ts +42 -12
- package/docs/guides/agentkit-skills-architecture.md +0 -471
- package/docs/guides/channels-implementation-map.md +0 -243
- package/docs/guides/channels-production-handoff.md +0 -101
- package/docs/portable-deploy-release-checklist.md +0 -41
|
@@ -1,28 +1,72 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
ChannelAdapter,
|
|
3
|
+
ChannelMediaDownloadInput,
|
|
4
|
+
ChannelMediaDownloadResult,
|
|
5
|
+
ChannelSendInput,
|
|
6
|
+
ChannelSendResult,
|
|
7
|
+
RawWebhookEvent,
|
|
8
|
+
WebhookVerificationInput,
|
|
9
|
+
WebhookVerificationResult,
|
|
10
|
+
} from "../channels";
|
|
2
11
|
import { AgentKitError } from "../errors";
|
|
3
12
|
|
|
4
13
|
export const zapsterWhatsappChannelAdapter: ChannelAdapter = {
|
|
5
14
|
type: "whatsapp",
|
|
6
15
|
provider: "zapster",
|
|
7
|
-
requiredSecrets: ["ZAPSTER_API_KEY", "
|
|
16
|
+
requiredSecrets: ["ZAPSTER_API_KEY", "ZAPSTER_INSTANCE_ID", "ZAPSTER_WEBHOOK_ID", "ZAPSTER_WEBHOOK_TOKEN"],
|
|
8
17
|
verifyWebhook(input) {
|
|
9
|
-
const
|
|
18
|
+
const expectedInstanceId = input.secrets.ZAPSTER_INSTANCE_ID;
|
|
19
|
+
const expectedWebhookId = input.secrets.ZAPSTER_WEBHOOK_ID;
|
|
10
20
|
|
|
11
|
-
if (!
|
|
21
|
+
if (!expectedInstanceId) {
|
|
12
22
|
return {
|
|
13
23
|
ok: false,
|
|
14
24
|
code: "channel_secret_missing",
|
|
15
|
-
message: "Secret
|
|
25
|
+
message: "Secret ZAPSTER_INSTANCE_ID is not set for this channel.",
|
|
16
26
|
};
|
|
17
27
|
}
|
|
18
28
|
|
|
19
|
-
|
|
29
|
+
if (!expectedWebhookId) {
|
|
30
|
+
return {
|
|
31
|
+
ok: false,
|
|
32
|
+
code: "channel_secret_missing",
|
|
33
|
+
message: "Secret ZAPSTER_WEBHOOK_ID is not set for this channel.",
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const tokenResult = verifyWebhookToken(input);
|
|
38
|
+
|
|
39
|
+
if (!tokenResult.ok) {
|
|
40
|
+
return tokenResult;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const instanceId = input.headers.get("x-instance-id");
|
|
44
|
+
const webhookId = input.headers.get("x-webhook-id");
|
|
45
|
+
const messageId = input.headers.get("x-message-id");
|
|
46
|
+
const attemptCount = input.headers.get("x-attempt-count");
|
|
47
|
+
const userAgent = input.headers.get("user-agent");
|
|
20
48
|
|
|
21
|
-
if (
|
|
49
|
+
if (instanceId !== expectedInstanceId) {
|
|
22
50
|
return {
|
|
23
51
|
ok: false,
|
|
24
52
|
code: "channel_signature_invalid",
|
|
25
|
-
message: "Zapster
|
|
53
|
+
message: "Zapster instance id did not match.",
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (webhookId !== expectedWebhookId) {
|
|
58
|
+
return {
|
|
59
|
+
ok: false,
|
|
60
|
+
code: "channel_signature_invalid",
|
|
61
|
+
message: "Zapster webhook id did not match.",
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (!messageId || !isPositiveIntegerHeader(attemptCount) || !userAgent?.toLowerCase().startsWith("zapsterapi/")) {
|
|
66
|
+
return {
|
|
67
|
+
ok: false,
|
|
68
|
+
code: "channel_payload_invalid",
|
|
69
|
+
message: "Missing Zapster webhook headers.",
|
|
26
70
|
};
|
|
27
71
|
}
|
|
28
72
|
|
|
@@ -30,16 +74,21 @@ export const zapsterWhatsappChannelAdapter: ChannelAdapter = {
|
|
|
30
74
|
},
|
|
31
75
|
normalizeInbound(input) {
|
|
32
76
|
const body = parseJsonObject(input);
|
|
33
|
-
const
|
|
34
|
-
const
|
|
35
|
-
const
|
|
77
|
+
const officialMessage = normalizeZapsterOfficialMessage(body);
|
|
78
|
+
const message = officialMessage ?? normalizeZapsterLegacyMessage(body);
|
|
79
|
+
const instanceId = input.headers.get("x-instance-id") ?? readString(body, "instance_id") ?? "default";
|
|
80
|
+
const providerEventId =
|
|
81
|
+
readString(body, "id") ??
|
|
82
|
+
readString(body, "event_id") ??
|
|
83
|
+
input.headers.get("x-message-id") ??
|
|
84
|
+
message.id;
|
|
36
85
|
|
|
37
86
|
if (!providerEventId) {
|
|
38
|
-
throw new AgentKitError("channel_payload_invalid", "Zapster payload is missing event_id or message.id.");
|
|
87
|
+
throw new AgentKitError("channel_payload_invalid", "Zapster payload is missing id, event_id, X-Message-ID, or message.id.");
|
|
39
88
|
}
|
|
40
89
|
|
|
41
|
-
const contactId =
|
|
42
|
-
const messageType =
|
|
90
|
+
const contactId = message.contactId ?? "unknown";
|
|
91
|
+
const messageType = message.type ?? "unknown";
|
|
43
92
|
const base = {
|
|
44
93
|
type: "whatsapp" as const,
|
|
45
94
|
provider: "zapster" as const,
|
|
@@ -54,9 +103,26 @@ export const zapsterWhatsappChannelAdapter: ChannelAdapter = {
|
|
|
54
103
|
providerMetadata: {
|
|
55
104
|
instanceId,
|
|
56
105
|
messageType,
|
|
106
|
+
...(readString(body, "type") ? { eventType: readString(body, "type") } : {}),
|
|
57
107
|
},
|
|
58
108
|
};
|
|
59
109
|
|
|
110
|
+
if (messageType === "audio" && message.audio) {
|
|
111
|
+
return [
|
|
112
|
+
{
|
|
113
|
+
...base,
|
|
114
|
+
kind: "message",
|
|
115
|
+
message: {
|
|
116
|
+
role: "user",
|
|
117
|
+
contentType: "audio",
|
|
118
|
+
content: "",
|
|
119
|
+
providerMessageId: message.id,
|
|
120
|
+
audio: message.audio,
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
];
|
|
124
|
+
}
|
|
125
|
+
|
|
60
126
|
if (messageType !== "text") {
|
|
61
127
|
return [
|
|
62
128
|
{
|
|
@@ -67,7 +133,7 @@ export const zapsterWhatsappChannelAdapter: ChannelAdapter = {
|
|
|
67
133
|
];
|
|
68
134
|
}
|
|
69
135
|
|
|
70
|
-
const text =
|
|
136
|
+
const text = message.text;
|
|
71
137
|
|
|
72
138
|
if (!text) {
|
|
73
139
|
return [
|
|
@@ -87,30 +153,30 @@ export const zapsterWhatsappChannelAdapter: ChannelAdapter = {
|
|
|
87
153
|
role: "user",
|
|
88
154
|
contentType: "text",
|
|
89
155
|
content: text,
|
|
90
|
-
providerMessageId:
|
|
156
|
+
providerMessageId: message.id,
|
|
91
157
|
},
|
|
92
158
|
},
|
|
93
159
|
];
|
|
94
160
|
},
|
|
161
|
+
async downloadMedia(input) {
|
|
162
|
+
return downloadZapsterMedia(input);
|
|
163
|
+
},
|
|
95
164
|
async sendMessage(input) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
return {
|
|
99
|
-
ok: true,
|
|
100
|
-
status: "sent",
|
|
101
|
-
providerRequestId: request.idempotencyKey,
|
|
102
|
-
providerMetadata: {
|
|
103
|
-
method: request.method,
|
|
104
|
-
url: request.url,
|
|
105
|
-
},
|
|
106
|
-
};
|
|
165
|
+
return sendZapsterMessage(input);
|
|
107
166
|
},
|
|
108
167
|
getStatus(input) {
|
|
109
|
-
|
|
168
|
+
const missingSecrets = [
|
|
169
|
+
"ZAPSTER_API_KEY",
|
|
170
|
+
"ZAPSTER_INSTANCE_ID",
|
|
171
|
+
"ZAPSTER_WEBHOOK_ID",
|
|
172
|
+
"ZAPSTER_WEBHOOK_TOKEN",
|
|
173
|
+
].filter((secret) => !input.secrets[secret]);
|
|
174
|
+
|
|
175
|
+
if (missingSecrets.length > 0) {
|
|
110
176
|
return {
|
|
111
177
|
status: "needs_setup",
|
|
112
178
|
checkedAt: new Date().toISOString(),
|
|
113
|
-
message:
|
|
179
|
+
message: `Zapster channel secrets are missing: ${missingSecrets.join(", ")}.`,
|
|
114
180
|
};
|
|
115
181
|
}
|
|
116
182
|
|
|
@@ -122,20 +188,496 @@ export const zapsterWhatsappChannelAdapter: ChannelAdapter = {
|
|
|
122
188
|
},
|
|
123
189
|
};
|
|
124
190
|
|
|
191
|
+
type NormalizedZapsterWebhookMessage = {
|
|
192
|
+
id?: string;
|
|
193
|
+
contactId?: string;
|
|
194
|
+
type?: string;
|
|
195
|
+
text?: string;
|
|
196
|
+
audio?: {
|
|
197
|
+
providerMediaId: string;
|
|
198
|
+
kind: "voice" | "audio";
|
|
199
|
+
mimeType?: string;
|
|
200
|
+
filename?: string;
|
|
201
|
+
durationSeconds?: number;
|
|
202
|
+
sizeBytes?: number;
|
|
203
|
+
downloadUrl?: string;
|
|
204
|
+
};
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
function normalizeZapsterOfficialMessage(body: Record<string, unknown>): NormalizedZapsterWebhookMessage | null {
|
|
208
|
+
if (readString(body, "type") !== "message.received") {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const data = readRecord(body, "data");
|
|
213
|
+
const content = readRecord(data, "content");
|
|
214
|
+
const sender = readRecord(data, "sender");
|
|
215
|
+
|
|
216
|
+
return {
|
|
217
|
+
id: readString(data, "id"),
|
|
218
|
+
contactId: readString(sender, "id"),
|
|
219
|
+
type: readString(data, "type"),
|
|
220
|
+
text: readString(content, "text"),
|
|
221
|
+
audio: normalizeZapsterAudio(content),
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function normalizeZapsterLegacyMessage(body: Record<string, unknown>): NormalizedZapsterWebhookMessage {
|
|
226
|
+
const message = readRecord(body, "message");
|
|
227
|
+
const audio = readRecord(message, "audio");
|
|
228
|
+
|
|
229
|
+
return {
|
|
230
|
+
id: readString(message, "id"),
|
|
231
|
+
contactId: readString(message, "from"),
|
|
232
|
+
type: readString(message, "type"),
|
|
233
|
+
text: readString(readRecord(message, "text"), "body"),
|
|
234
|
+
audio: normalizeZapsterAudio(audio),
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function normalizeZapsterAudio(value: Record<string, unknown>): NormalizedZapsterWebhookMessage["audio"] {
|
|
239
|
+
const mediaId = readString(value, "id") ?? readString(value, "media_id") ?? readString(value, "mediaId");
|
|
240
|
+
const downloadUrl =
|
|
241
|
+
readString(value, "url") ??
|
|
242
|
+
readString(value, "download_url") ??
|
|
243
|
+
readString(value, "downloadUrl") ??
|
|
244
|
+
readString(value, "media_url") ??
|
|
245
|
+
readString(value, "mediaUrl");
|
|
246
|
+
|
|
247
|
+
if (!mediaId && !downloadUrl) {
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
providerMediaId: mediaId ?? downloadUrl ?? "unknown",
|
|
253
|
+
kind: readString(value, "ptt") === "true" ? "voice" : "audio",
|
|
254
|
+
...(readString(value, "mime_type") ?? readString(value, "mimeType")
|
|
255
|
+
? { mimeType: readString(value, "mime_type") ?? readString(value, "mimeType") }
|
|
256
|
+
: {}),
|
|
257
|
+
filename: readString(value, "filename") ?? readString(value, "file_name") ?? defaultZapsterAudioFilename(value),
|
|
258
|
+
...(readNumber(value, "duration") !== undefined ? { durationSeconds: readNumber(value, "duration") } : {}),
|
|
259
|
+
...(readNumber(value, "file_size") ?? readNumber(value, "size")
|
|
260
|
+
? { sizeBytes: readNumber(value, "file_size") ?? readNumber(value, "size") }
|
|
261
|
+
: {}),
|
|
262
|
+
...(downloadUrl ? { downloadUrl } : {}),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function verifyWebhookToken(input: WebhookVerificationInput): WebhookVerificationResult {
|
|
267
|
+
const expectedToken = input.secrets.ZAPSTER_WEBHOOK_TOKEN;
|
|
268
|
+
|
|
269
|
+
if (!expectedToken) {
|
|
270
|
+
return {
|
|
271
|
+
ok: false,
|
|
272
|
+
code: "channel_secret_missing",
|
|
273
|
+
message: "Secret ZAPSTER_WEBHOOK_TOKEN is not set for this channel.",
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
let actualToken: string | null = null;
|
|
278
|
+
|
|
279
|
+
try {
|
|
280
|
+
actualToken = new URL(input.url).searchParams.get("token");
|
|
281
|
+
} catch {
|
|
282
|
+
actualToken = null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (actualToken !== expectedToken) {
|
|
286
|
+
return {
|
|
287
|
+
ok: false,
|
|
288
|
+
code: "channel_signature_invalid",
|
|
289
|
+
message: "Zapster webhook token did not match.",
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return { ok: true };
|
|
294
|
+
}
|
|
295
|
+
|
|
125
296
|
export type ZapsterSendMessageRequest = {
|
|
126
297
|
method: "POST";
|
|
127
298
|
url: string;
|
|
128
299
|
body: {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
body: string;
|
|
133
|
-
};
|
|
300
|
+
recipient: string;
|
|
301
|
+
text: string;
|
|
302
|
+
instance_id: string;
|
|
134
303
|
};
|
|
135
304
|
idempotencyKey: string;
|
|
136
305
|
};
|
|
137
306
|
|
|
307
|
+
type ZapsterFetch = (url: string, init: RequestInit) => Promise<Response>;
|
|
308
|
+
|
|
309
|
+
const ZAPSTER_SEND_MESSAGE_URL = "https://api.zapsterapi.com/v1/wa/messages";
|
|
310
|
+
const ZAPSTER_DEFAULT_MEDIA_HOSTS = ["api.zapsterapi.com"];
|
|
311
|
+
const ZAPSTER_MAX_DOWNLOAD_BYTES = 25_000_000;
|
|
312
|
+
|
|
138
313
|
export function buildZapsterSendMessageRequest(input: ChannelSendInput): ZapsterSendMessageRequest {
|
|
314
|
+
return buildZapsterSendMessageRequestInternal(input, "<redacted>");
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export async function sendZapsterMessage(
|
|
318
|
+
input: ChannelSendInput,
|
|
319
|
+
fetcher: ZapsterFetch = fetch,
|
|
320
|
+
): Promise<ChannelSendResult> {
|
|
321
|
+
if (input.secrets.AGENTKIT_CHANNEL_SEND_DRY_RUN === "1") {
|
|
322
|
+
const request = buildZapsterSendMessageRequest(input);
|
|
323
|
+
|
|
324
|
+
return {
|
|
325
|
+
ok: true,
|
|
326
|
+
status: "stubbed",
|
|
327
|
+
providerRequestId: request.idempotencyKey,
|
|
328
|
+
providerMetadata: {
|
|
329
|
+
method: request.method,
|
|
330
|
+
url: request.url,
|
|
331
|
+
body: request.body,
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const apiKey = input.secrets.ZAPSTER_API_KEY;
|
|
337
|
+
const instanceId = input.secrets.ZAPSTER_INSTANCE_ID;
|
|
338
|
+
|
|
339
|
+
if (!apiKey || !instanceId) {
|
|
340
|
+
return {
|
|
341
|
+
ok: false,
|
|
342
|
+
retryable: false,
|
|
343
|
+
code: "channel_secret_missing",
|
|
344
|
+
message: "Secret ZAPSTER_API_KEY or ZAPSTER_INSTANCE_ID is missing.",
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
let request: ZapsterSendMessageRequest;
|
|
349
|
+
let actualRequest: ZapsterSendMessageRequest;
|
|
350
|
+
|
|
351
|
+
try {
|
|
352
|
+
request = buildZapsterSendMessageRequest(input);
|
|
353
|
+
actualRequest = buildZapsterSendMessageRequestInternal(input, instanceId);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
return {
|
|
356
|
+
ok: false,
|
|
357
|
+
retryable: false,
|
|
358
|
+
code: "channel_send_failed",
|
|
359
|
+
message: error instanceof Error ? error.message : String(error),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
let response: Response;
|
|
364
|
+
|
|
365
|
+
try {
|
|
366
|
+
response = await fetcher(actualRequest.url, {
|
|
367
|
+
method: actualRequest.method,
|
|
368
|
+
headers: {
|
|
369
|
+
Authorization: `Bearer ${apiKey}`,
|
|
370
|
+
"Content-Type": "application/json",
|
|
371
|
+
Accept: "application/json",
|
|
372
|
+
},
|
|
373
|
+
body: JSON.stringify(actualRequest.body),
|
|
374
|
+
});
|
|
375
|
+
} catch (error) {
|
|
376
|
+
const errorMessage = redactString(error instanceof Error ? error.message : String(error), [apiKey, instanceId]);
|
|
377
|
+
|
|
378
|
+
return {
|
|
379
|
+
ok: false,
|
|
380
|
+
retryable: true,
|
|
381
|
+
code: "channel_provider_unavailable",
|
|
382
|
+
message: `Zapster sendMessage request failed before a response: ${errorMessage}`,
|
|
383
|
+
providerRequestId: request.idempotencyKey,
|
|
384
|
+
providerMetadata: {
|
|
385
|
+
method: request.method,
|
|
386
|
+
url: request.url,
|
|
387
|
+
body: request.body,
|
|
388
|
+
},
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const payload = await readZapsterResponseBody(response);
|
|
393
|
+
const redactedPayload = redactValue(payload, [apiKey, instanceId]);
|
|
394
|
+
const messageId = isRecord(payload)
|
|
395
|
+
? readString(payload, "message_id") ?? readString(payload, "id")
|
|
396
|
+
: undefined;
|
|
397
|
+
|
|
398
|
+
if (!response.ok) {
|
|
399
|
+
return {
|
|
400
|
+
ok: false,
|
|
401
|
+
retryable: response.status === 429 || response.status >= 500,
|
|
402
|
+
code: "channel_send_failed",
|
|
403
|
+
message: redactString(readZapsterErrorMessage(payload, response.status), [apiKey, instanceId]),
|
|
404
|
+
providerRequestId: request.idempotencyKey,
|
|
405
|
+
providerMetadata: {
|
|
406
|
+
method: request.method,
|
|
407
|
+
url: request.url,
|
|
408
|
+
status: response.status,
|
|
409
|
+
body: redactedPayload,
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (!messageId) {
|
|
415
|
+
return {
|
|
416
|
+
ok: false,
|
|
417
|
+
retryable: false,
|
|
418
|
+
code: "channel_send_failed",
|
|
419
|
+
message: "Zapster sendMessage did not return message_id or id.",
|
|
420
|
+
providerRequestId: request.idempotencyKey,
|
|
421
|
+
providerMetadata: {
|
|
422
|
+
method: request.method,
|
|
423
|
+
url: request.url,
|
|
424
|
+
status: response.status,
|
|
425
|
+
body: redactedPayload,
|
|
426
|
+
},
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
return {
|
|
431
|
+
ok: true,
|
|
432
|
+
status: "sent",
|
|
433
|
+
providerRequestId: request.idempotencyKey,
|
|
434
|
+
providerMessageId: messageId,
|
|
435
|
+
providerMetadata: {
|
|
436
|
+
method: request.method,
|
|
437
|
+
url: request.url,
|
|
438
|
+
status: response.status,
|
|
439
|
+
body: redactedPayload,
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export async function downloadZapsterMedia(
|
|
445
|
+
input: ChannelMediaDownloadInput,
|
|
446
|
+
fetcher: ZapsterFetch = fetch,
|
|
447
|
+
): Promise<ChannelMediaDownloadResult> {
|
|
448
|
+
const apiKey = input.secrets.ZAPSTER_API_KEY;
|
|
449
|
+
const audio = input.message.audio;
|
|
450
|
+
|
|
451
|
+
if (!apiKey) {
|
|
452
|
+
return {
|
|
453
|
+
ok: false,
|
|
454
|
+
retryable: false,
|
|
455
|
+
code: "channel_secret_missing",
|
|
456
|
+
message: "Secret ZAPSTER_API_KEY is missing.",
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
if (!audio?.downloadUrl) {
|
|
461
|
+
return {
|
|
462
|
+
ok: false,
|
|
463
|
+
retryable: false,
|
|
464
|
+
code: "channel_audio_download_unavailable",
|
|
465
|
+
message: "Zapster audio payload did not include a media download URL.",
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const mediaUrl = validateZapsterMediaDownloadUrl(audio.downloadUrl);
|
|
470
|
+
|
|
471
|
+
if (!mediaUrl.ok) {
|
|
472
|
+
return mediaUrl;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
let response: Response;
|
|
476
|
+
|
|
477
|
+
try {
|
|
478
|
+
response = await fetcher(mediaUrl.url, {
|
|
479
|
+
method: "GET",
|
|
480
|
+
headers: {
|
|
481
|
+
Authorization: `Bearer ${apiKey}`,
|
|
482
|
+
},
|
|
483
|
+
});
|
|
484
|
+
} catch (error) {
|
|
485
|
+
return {
|
|
486
|
+
ok: false,
|
|
487
|
+
retryable: true,
|
|
488
|
+
code: "channel_provider_unavailable",
|
|
489
|
+
message: `Zapster media download failed before a response: ${redactString(
|
|
490
|
+
error instanceof Error ? error.message : String(error),
|
|
491
|
+
[apiKey, mediaUrl.url],
|
|
492
|
+
)}`,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
if (!response.ok) {
|
|
497
|
+
return {
|
|
498
|
+
ok: false,
|
|
499
|
+
retryable: response.status === 429 || response.status >= 500,
|
|
500
|
+
code: response.status === 429 || response.status >= 500
|
|
501
|
+
? "channel_provider_unavailable"
|
|
502
|
+
: "channel_media_download_failed",
|
|
503
|
+
message: `Zapster media download returned HTTP ${response.status}.`,
|
|
504
|
+
providerMetadata: {
|
|
505
|
+
status: response.status,
|
|
506
|
+
},
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const maxDownloadBytes = input.maxBytes ?? ZAPSTER_MAX_DOWNLOAD_BYTES;
|
|
511
|
+
const bytes = await readResponseBytesWithLimit(response, maxDownloadBytes);
|
|
512
|
+
|
|
513
|
+
if (!bytes.ok) {
|
|
514
|
+
return bytes;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
return {
|
|
518
|
+
ok: true,
|
|
519
|
+
audio: bytes.audio,
|
|
520
|
+
filename: audio.filename ?? `${audio.providerMediaId}.ogg`,
|
|
521
|
+
...(audio.mimeType ? { mimeType: audio.mimeType } : {}),
|
|
522
|
+
...(audio.durationSeconds !== undefined ? { durationSeconds: audio.durationSeconds } : {}),
|
|
523
|
+
sizeBytes: bytes.audio.byteLength,
|
|
524
|
+
providerMetadata: {
|
|
525
|
+
status: response.status,
|
|
526
|
+
},
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function validateZapsterMediaDownloadUrl(rawUrl: string):
|
|
531
|
+
| {
|
|
532
|
+
ok: true;
|
|
533
|
+
url: string;
|
|
534
|
+
}
|
|
535
|
+
| {
|
|
536
|
+
ok: false;
|
|
537
|
+
retryable: false;
|
|
538
|
+
code: "channel_audio_download_unavailable";
|
|
539
|
+
message: string;
|
|
540
|
+
} {
|
|
541
|
+
let url: URL;
|
|
542
|
+
|
|
543
|
+
try {
|
|
544
|
+
url = new URL(rawUrl);
|
|
545
|
+
} catch {
|
|
546
|
+
return {
|
|
547
|
+
ok: false,
|
|
548
|
+
retryable: false,
|
|
549
|
+
code: "channel_audio_download_unavailable",
|
|
550
|
+
message: "Zapster audio download URL is not a valid URL.",
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (url.protocol !== "https:") {
|
|
555
|
+
return {
|
|
556
|
+
ok: false,
|
|
557
|
+
retryable: false,
|
|
558
|
+
code: "channel_audio_download_unavailable",
|
|
559
|
+
message: "Zapster audio download URL must use HTTPS.",
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const hostname = url.hostname.toLowerCase();
|
|
564
|
+
const allowed = ZAPSTER_DEFAULT_MEDIA_HOSTS.some((host) => hostname === host || hostname.endsWith(`.${host}`));
|
|
565
|
+
|
|
566
|
+
if (!allowed) {
|
|
567
|
+
return {
|
|
568
|
+
ok: false,
|
|
569
|
+
retryable: false,
|
|
570
|
+
code: "channel_audio_download_unavailable",
|
|
571
|
+
message: "Zapster audio download URL host is not allowed.",
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
url.username = "";
|
|
576
|
+
url.password = "";
|
|
577
|
+
|
|
578
|
+
return {
|
|
579
|
+
ok: true,
|
|
580
|
+
url: url.href,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
async function readResponseBytesWithLimit(
|
|
585
|
+
response: Response,
|
|
586
|
+
maxBytes: number,
|
|
587
|
+
): Promise<
|
|
588
|
+
| {
|
|
589
|
+
ok: true;
|
|
590
|
+
audio: Uint8Array;
|
|
591
|
+
}
|
|
592
|
+
| {
|
|
593
|
+
ok: false;
|
|
594
|
+
retryable: false;
|
|
595
|
+
code: "channel_audio_too_large";
|
|
596
|
+
message: string;
|
|
597
|
+
providerMetadata?: Record<string, unknown>;
|
|
598
|
+
}
|
|
599
|
+
> {
|
|
600
|
+
const contentLength = response.headers.get("content-length");
|
|
601
|
+
const declaredBytes = contentLength ? Number(contentLength) : undefined;
|
|
602
|
+
|
|
603
|
+
if (declaredBytes !== undefined && Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
604
|
+
return {
|
|
605
|
+
ok: false,
|
|
606
|
+
retryable: false,
|
|
607
|
+
code: "channel_audio_too_large",
|
|
608
|
+
message: `Audio response declares ${declaredBytes} bytes, which exceeds the configured ${maxBytes} byte limit.`,
|
|
609
|
+
providerMetadata: {
|
|
610
|
+
sizeBytes: declaredBytes,
|
|
611
|
+
},
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
if (!response.body) {
|
|
616
|
+
const audio = new Uint8Array(await response.arrayBuffer());
|
|
617
|
+
|
|
618
|
+
if (audio.byteLength > maxBytes) {
|
|
619
|
+
return {
|
|
620
|
+
ok: false,
|
|
621
|
+
retryable: false,
|
|
622
|
+
code: "channel_audio_too_large",
|
|
623
|
+
message: `Audio response is ${audio.byteLength} bytes, which exceeds the configured ${maxBytes} byte limit.`,
|
|
624
|
+
providerMetadata: {
|
|
625
|
+
sizeBytes: audio.byteLength,
|
|
626
|
+
},
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
return { ok: true, audio };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
const reader = response.body.getReader();
|
|
634
|
+
const chunks: Uint8Array[] = [];
|
|
635
|
+
let totalBytes = 0;
|
|
636
|
+
|
|
637
|
+
try {
|
|
638
|
+
while (true) {
|
|
639
|
+
const chunk = await reader.read();
|
|
640
|
+
|
|
641
|
+
if (chunk.done) {
|
|
642
|
+
break;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
totalBytes += chunk.value.byteLength;
|
|
646
|
+
|
|
647
|
+
if (totalBytes > maxBytes) {
|
|
648
|
+
await reader.cancel().catch(() => undefined);
|
|
649
|
+
return {
|
|
650
|
+
ok: false,
|
|
651
|
+
retryable: false,
|
|
652
|
+
code: "channel_audio_too_large",
|
|
653
|
+
message: `Audio response exceeded the configured ${maxBytes} byte limit while downloading.`,
|
|
654
|
+
providerMetadata: {
|
|
655
|
+
sizeBytes: totalBytes,
|
|
656
|
+
},
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
chunks.push(chunk.value);
|
|
661
|
+
}
|
|
662
|
+
} finally {
|
|
663
|
+
reader.releaseLock();
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const audio = new Uint8Array(totalBytes);
|
|
667
|
+
let offset = 0;
|
|
668
|
+
|
|
669
|
+
for (const chunk of chunks) {
|
|
670
|
+
audio.set(chunk, offset);
|
|
671
|
+
offset += chunk.byteLength;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
return { ok: true, audio };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
function buildZapsterSendMessageRequestInternal(
|
|
678
|
+
input: ChannelSendInput,
|
|
679
|
+
instanceId: string,
|
|
680
|
+
): ZapsterSendMessageRequest {
|
|
139
681
|
const to = input.externalIdentity.key.match(/contact:([^:]+)$/)?.[1];
|
|
140
682
|
|
|
141
683
|
if (!to) {
|
|
@@ -144,18 +686,83 @@ export function buildZapsterSendMessageRequest(input: ChannelSendInput): Zapster
|
|
|
144
686
|
|
|
145
687
|
return {
|
|
146
688
|
method: "POST",
|
|
147
|
-
url:
|
|
689
|
+
url: ZAPSTER_SEND_MESSAGE_URL,
|
|
148
690
|
body: {
|
|
149
|
-
to,
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
body: input.message.content,
|
|
153
|
-
},
|
|
691
|
+
recipient: to,
|
|
692
|
+
text: input.message.content,
|
|
693
|
+
instance_id: instanceId,
|
|
154
694
|
},
|
|
155
695
|
idempotencyKey: `whatsapp:zapster:${input.channelId}:${input.conversationId}:${redactPhone(to)}`,
|
|
156
696
|
};
|
|
157
697
|
}
|
|
158
698
|
|
|
699
|
+
async function readZapsterResponseBody(response: Response): Promise<unknown> {
|
|
700
|
+
const text = await response.text().catch(() => "");
|
|
701
|
+
|
|
702
|
+
if (!text) {
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
try {
|
|
707
|
+
return JSON.parse(text) as unknown;
|
|
708
|
+
} catch {
|
|
709
|
+
return text;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function readZapsterErrorMessage(payload: unknown, status: number): string {
|
|
714
|
+
if (typeof payload === "string" && payload.length > 0) {
|
|
715
|
+
return payload;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
if (isRecord(payload)) {
|
|
719
|
+
const message = readString(payload, "message") ?? readString(payload, "error") ?? readString(payload, "detail");
|
|
720
|
+
|
|
721
|
+
if (message) {
|
|
722
|
+
return message;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
const error = readRecord(payload, "error");
|
|
726
|
+
const nestedMessage = readString(error, "message") ?? readString(error, "detail");
|
|
727
|
+
|
|
728
|
+
if (nestedMessage) {
|
|
729
|
+
return nestedMessage;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
return `Zapster sendMessage returned HTTP ${status}.`;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function redactValue(value: unknown, secrets: string[]): unknown {
|
|
737
|
+
if (typeof value === "string") {
|
|
738
|
+
return redactString(value, secrets);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
if (!isRecord(value) && !Array.isArray(value)) {
|
|
742
|
+
return value;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
const serialized = redactString(JSON.stringify(value), secrets);
|
|
746
|
+
|
|
747
|
+
try {
|
|
748
|
+
return JSON.parse(serialized) as unknown;
|
|
749
|
+
} catch {
|
|
750
|
+
return serialized;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
function redactString(value: string, secrets: string[]): string {
|
|
755
|
+
let redacted = value;
|
|
756
|
+
|
|
757
|
+
for (const secret of secrets) {
|
|
758
|
+
if (secret) {
|
|
759
|
+
redacted = redacted.split(secret).join("<redacted>");
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
return redacted;
|
|
764
|
+
}
|
|
765
|
+
|
|
159
766
|
function parseJsonObject(input: RawWebhookEvent): Record<string, unknown> {
|
|
160
767
|
try {
|
|
161
768
|
const parsed = JSON.parse(input.rawBody) as unknown;
|
|
@@ -180,6 +787,33 @@ function readString(value: Record<string, unknown>, key: string): string | undef
|
|
|
180
787
|
return typeof field === "string" && field.length > 0 ? field : undefined;
|
|
181
788
|
}
|
|
182
789
|
|
|
790
|
+
function readNumber(value: Record<string, unknown>, key: string): number | undefined {
|
|
791
|
+
const field = value[key];
|
|
792
|
+
return typeof field === "number" && Number.isFinite(field) ? field : undefined;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function defaultZapsterAudioFilename(value: Record<string, unknown>): string {
|
|
796
|
+
const mimeType = readString(value, "mime_type") ?? readString(value, "mimeType");
|
|
797
|
+
|
|
798
|
+
if (mimeType?.includes("ogg")) {
|
|
799
|
+
return "audio.ogg";
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
if (mimeType?.includes("mpeg") || mimeType?.includes("mp3")) {
|
|
803
|
+
return "audio.mp3";
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
if (mimeType?.includes("wav")) {
|
|
807
|
+
return "audio.wav";
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
return "audio.ogg";
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function isPositiveIntegerHeader(value: string | null): value is string {
|
|
814
|
+
return typeof value === "string" && /^[1-9]\d*$/.test(value);
|
|
815
|
+
}
|
|
816
|
+
|
|
183
817
|
function redactPhone(value: string): string {
|
|
184
818
|
if (value.length <= 6) {
|
|
185
819
|
return "*".repeat(value.length);
|