@andreprado/agentkit 0.1.0 → 0.2.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.
Files changed (104) hide show
  1. package/README.md +8 -77
  2. package/docs/guides/add-channel.md +14 -92
  3. package/docs/guides/add-knowledge.md +0 -21
  4. package/docs/guides/add-tool.md +5 -11
  5. package/docs/guides/channel-security.md +3 -207
  6. package/docs/guides/connect-discord.md +7 -172
  7. package/docs/guides/connect-slack.md +6 -121
  8. package/docs/guides/connect-telegram.md +6 -165
  9. package/docs/guides/connect-whatsapp-evolution.md +6 -116
  10. package/docs/guides/connect-whatsapp-uazapi.md +6 -134
  11. package/docs/guides/connect-whatsapp-zapster.md +6 -202
  12. package/docs/guides/create-agent.md +5 -14
  13. package/docs/guides/debug-channel.md +4 -156
  14. package/docs/guides/improve-local.md +13 -0
  15. package/docs/guides/local-only-migration.md +35 -0
  16. package/docs/guides/replay-local-traces.md +11 -0
  17. package/docs/guides/run-evals.md +2 -4
  18. package/docs/guides/security-rules.md +5 -154
  19. package/docs/guides/use-jev.md +3 -6
  20. package/docs/guides/use-provider.md +0 -3
  21. package/docs/guides/write-feedback.md +10 -0
  22. package/docs/llms-full.txt +27 -448
  23. package/docs/llms.txt +8 -44
  24. package/package.json +2 -4
  25. package/src/cli/commands/channels.ts +8 -1613
  26. package/src/cli/commands/feedback.ts +8 -86
  27. package/src/cli/constants.ts +0 -3
  28. package/src/cli/flags.ts +0 -28
  29. package/src/cli/help.ts +16 -92
  30. package/src/cli/index.ts +15 -1091
  31. package/src/index.ts +6 -158
  32. package/src/providers/pi.ts +2 -0
  33. package/src/runtime/channels/discord.ts +16 -8
  34. package/src/runtime/channels/generic-webhook.ts +21 -313
  35. package/src/runtime/channels/net-guard.ts +480 -0
  36. package/src/runtime/channels/provider-fetch.ts +54 -0
  37. package/src/runtime/channels/slack.ts +9 -3
  38. package/src/runtime/channels/telegram.ts +43 -10
  39. package/src/runtime/channels/whatsapp-evolution.ts +33 -60
  40. package/src/runtime/channels/whatsapp-uazapi.ts +33 -164
  41. package/src/runtime/channels/whatsapp-zapster.ts +35 -7
  42. package/src/runtime/chat.ts +5 -3
  43. package/src/runtime/config.ts +36 -147
  44. package/src/runtime/database.ts +2 -2
  45. package/src/runtime/dev-server.ts +8 -8
  46. package/src/runtime/env.ts +11 -0
  47. package/src/runtime/improve.ts +2 -262
  48. package/src/runtime/inspect.ts +13 -73
  49. package/src/runtime/knowledge/embeddings.ts +45 -7
  50. package/src/runtime/knowledge/ingest.ts +70 -7
  51. package/src/runtime/knowledge/tool.ts +16 -2
  52. package/src/runtime/knowledge/vector.ts +31 -31
  53. package/src/runtime/tool-runner.ts +5 -3
  54. package/src/runtime/tools.ts +10 -14
  55. package/src/storage/sqlite.ts +11 -32
  56. package/src/templates/blank.ts +15 -102
  57. package/src/templates/common.ts +60 -0
  58. package/src/templates/dentista.ts +7 -74
  59. package/src/templates/skills/agentkit-capsule/SKILL.md +5 -7
  60. package/src/templates/skills/agentkit-capsule/references/docs-router.md +2 -3
  61. package/src/templates/skills/agentkit-channels/SKILL.md +6 -119
  62. package/src/templates/skills/agentkit-channels/references/channel-buffering.md +0 -9
  63. package/src/templates/skills/agentkit-channels/references/channel-debugging.md +1 -64
  64. package/src/templates/skills/agentkit-channels/references/discord.md +2 -92
  65. package/src/templates/skills/agentkit-channels/references/slack.md +2 -55
  66. package/src/templates/skills/agentkit-channels/references/telegram.md +2 -71
  67. package/src/templates/skills/agentkit-channels/references/whatsapp-evolution.md +2 -56
  68. package/src/templates/skills/agentkit-channels/references/whatsapp-uazapi.md +2 -53
  69. package/src/templates/skills/agentkit-channels/references/whatsapp-zapster.md +2 -70
  70. package/src/templates/skills/agentkit-database/SKILL.md +2 -4
  71. package/src/templates/skills/agentkit-evals/SKILL.md +1 -1
  72. package/src/templates/skills/agentkit-improve/SKILL.md +6 -85
  73. package/src/templates/skills/agentkit-improve/references/trace-packets.md +1 -1
  74. package/src/templates/skills/agentkit-provider/SKILL.md +0 -1
  75. package/src/templates/skills/agentkit-security/SKILL.md +1 -3
  76. package/src/templates/skills/agentkit-tools/SKILL.md +1 -1
  77. package/src/templates/skills/agentkit-tools/examples/database-write.tool.md +1 -2
  78. package/src/templates/skills/agentkit-troubleshooting/SKILL.md +5 -11
  79. package/src/templates/support.ts +8 -92
  80. package/docs/guides/add-managed-composio.md +0 -165
  81. package/docs/guides/improve-from-production.md +0 -151
  82. package/docs/guides/prepare-deploy.md +0 -227
  83. package/docs/guides/replay-production-traces.md +0 -72
  84. package/docs/guides/send-feedback.md +0 -135
  85. package/src/cli/cloud-client.ts +0 -377
  86. package/src/cli/deploy-chat-ui.ts +0 -606
  87. package/src/cli/deploy-readiness.ts +0 -561
  88. package/src/cloud/artifact.ts +0 -139
  89. package/src/cloud/client.ts +0 -80
  90. package/src/cloud/contracts.ts +0 -63
  91. package/src/cloud/index.ts +0 -3
  92. package/src/runtime/build.ts +0 -43
  93. package/src/runtime/core/deploy-state.ts +0 -54
  94. package/src/runtime/core/manifest.ts +0 -283
  95. package/src/runtime/core/targets.ts +0 -133
  96. package/src/runtime/deploy-readiness.ts +0 -135
  97. package/src/runtime/deploy.ts +0 -1
  98. package/src/runtime/integrations/composio.ts +0 -425
  99. package/src/runtime/targets/cloudflare/build.ts +0 -3319
  100. package/src/runtime/targets/container/build.ts +0 -146
  101. package/src/runtime/targets/container/server.ts +0 -33
  102. package/src/runtime/targets/vps/deploy.ts +0 -223
  103. package/src/templates/skills/agentkit-deploy/SKILL.md +0 -52
  104. package/src/templates/skills/agentkit-integrations/SKILL.md +0 -98
@@ -1,135 +0,0 @@
1
- import { createHash } from "node:crypto";
2
-
3
- import { loadAgentCapsule } from "./config";
4
- import { buildSharedAgentManifest } from "./core/manifest";
5
- import { listCapsuleEnv } from "./env";
6
- import {
7
- MANAGED_COMPOSIO_API_KEY_SECRET,
8
- resolveManagedComposioIntegrations,
9
- } from "./integrations/composio";
10
-
11
- export type DeployReadinessSecretSource = {
12
- dotenv: boolean;
13
- environment: boolean;
14
- };
15
-
16
- export type DeployReadinessContext = {
17
- root: string;
18
- projectName: string;
19
- projectId: string;
20
- target: "cloudflare";
21
- runtime: "edge" | "local";
22
- provider: {
23
- name: string;
24
- model: string;
25
- };
26
- accessMode: "private" | "token" | "public";
27
- requiredSecrets: string[];
28
- userManagedSecrets: string[];
29
- agentKitManagedSecrets: string[];
30
- localSecrets: Record<string, DeployReadinessSecretSource>;
31
- knowledge: {
32
- enabled: boolean;
33
- sourceCount: number;
34
- embeddingProvider: string;
35
- databaseDriver: "none" | "turso";
36
- };
37
- integrations: {
38
- managedComposio: {
39
- enabled: boolean;
40
- toolkits: string[];
41
- toolCount: number;
42
- userId: string | null;
43
- };
44
- };
45
- };
46
-
47
- export async function loadDeployReadinessContext(
48
- cwd = process.cwd(),
49
- env: Record<string, string | undefined> = process.env,
50
- ): Promise<DeployReadinessContext> {
51
- const capsule = await loadAgentCapsule(cwd);
52
- const manifest = buildSharedAgentManifest(capsule);
53
- const managedComposio = resolveManagedComposioIntegrations(capsule.config)[0];
54
- const dotenvNames = new Set(await listCapsuleEnv(capsule.root));
55
- const requiredSecrets = manifest.secrets;
56
- const localSecrets: Record<string, DeployReadinessSecretSource> = {};
57
-
58
- for (const name of requiredSecrets) {
59
- const source = {
60
- dotenv: dotenvNames.has(name),
61
- environment: Boolean(env[name]),
62
- };
63
-
64
- if (source.dotenv || source.environment) {
65
- localSecrets[name] = source;
66
- }
67
- }
68
-
69
- const agentKitManagedSecrets = requiredSecrets.filter((name) =>
70
- isAgentKitManagedDeploySecret(name, {
71
- accessMode: capsule.config.access.mode,
72
- databaseDriver: manifest.storage.database.driver,
73
- managedComposioEnabled: Boolean(managedComposio),
74
- }),
75
- );
76
- const managed = new Set(agentKitManagedSecrets);
77
-
78
- return {
79
- root: capsule.root,
80
- projectName: capsule.config.name,
81
- projectId: stableCloudProjectId(capsule.config.name),
82
- target: "cloudflare",
83
- runtime: capsule.config.runtime,
84
- provider: {
85
- name: capsule.config.provider.name,
86
- model: capsule.config.provider.model,
87
- },
88
- accessMode: capsule.config.access.mode,
89
- requiredSecrets,
90
- userManagedSecrets: requiredSecrets.filter((name) => !managed.has(name)),
91
- agentKitManagedSecrets,
92
- localSecrets,
93
- knowledge: {
94
- enabled: manifest.knowledge.enabled,
95
- sourceCount: manifest.knowledge.sources.length,
96
- embeddingProvider: manifest.knowledge.embedding.provider,
97
- databaseDriver: manifest.storage.database.driver,
98
- },
99
- integrations: {
100
- managedComposio: {
101
- enabled: Boolean(managedComposio),
102
- toolkits: managedComposio?.toolkits ?? [],
103
- toolCount: managedComposio?.allowedTools.length ?? 0,
104
- userId: managedComposio?.userId ?? null,
105
- },
106
- },
107
- };
108
- }
109
-
110
- export function stableCloudProjectId(name: string, accountId?: string | null): string {
111
- return `proj_${createHash("sha256").update(`${accountId ? `account:${accountId}` : "anonymous"}:${name}`).digest("hex").slice(0, 16)}`;
112
- }
113
-
114
- function isAgentKitManagedDeploySecret(
115
- name: string,
116
- context: {
117
- accessMode: DeployReadinessContext["accessMode"];
118
- databaseDriver: "none" | "turso";
119
- managedComposioEnabled: boolean;
120
- },
121
- ): boolean {
122
- if (context.databaseDriver === "turso" && (name === "TURSO_DATABASE_URL" || name === "TURSO_AUTH_TOKEN")) {
123
- return true;
124
- }
125
-
126
- if (name === "AGENTKIT_PRIVATE_TOKEN") {
127
- return true;
128
- }
129
-
130
- if (context.managedComposioEnabled && name === MANAGED_COMPOSIO_API_KEY_SECRET) {
131
- return true;
132
- }
133
-
134
- return false;
135
- }
@@ -1 +0,0 @@
1
- export * from "../cloud";
@@ -1,425 +0,0 @@
1
- import type { AgentConfig, AgentTool, ComposioManagedIntegration } from "../../index";
2
- import { AgentKitError } from "../errors";
3
-
4
- export const MANAGED_COMPOSIO_TOOL_NAME = "agentkit_composio_execute";
5
- export const MANAGED_COMPOSIO_API_KEY_SECRET = "COMPOSIO_API_KEY";
6
- export const MANAGED_COMPOSIO_WEBHOOK_SECRET = "COMPOSIO_WEBHOOK_SECRET";
7
- export const MANAGED_COMPOSIO_ENTITLEMENT = "managed_composio";
8
- export const MANAGED_COMPOSIO_USER_ID_BINDING = "AGENTKIT_MANAGED_COMPOSIO_USER_ID";
9
-
10
- export type ResolvedComposioManagedIntegration = ComposioManagedIntegration & {
11
- userId: string;
12
- allowedTools: string[];
13
- };
14
-
15
- export type ManagedComposioResolutionOptions = {
16
- userId?: string;
17
- userIdScope?: string;
18
- };
19
-
20
- type ManagedComposioToolInput = {
21
- toolSlug: string;
22
- arguments: Record<string, unknown>;
23
- confirmed?: boolean;
24
- };
25
-
26
- type ManagedComposioToolOutput = {
27
- successful: boolean;
28
- data: unknown;
29
- error: unknown;
30
- logId: string | null;
31
- toolkit: string;
32
- toolSlug: string;
33
- userId: string;
34
- };
35
-
36
- type ComposioActionGuide = {
37
- summary: string;
38
- argumentNotes: string[];
39
- dangerousDefaults?: string[];
40
- examples?: Array<Record<string, unknown>>;
41
- };
42
-
43
- export function resolveManagedComposioIntegrations(
44
- config: Pick<AgentConfig, "name" | "integrations">,
45
- options: ManagedComposioResolutionOptions = {},
46
- ): ResolvedComposioManagedIntegration[] {
47
- return (config.integrations ?? [])
48
- .filter((integration): integration is ComposioManagedIntegration => integration.provider === "composio" && integration.mode === "managed")
49
- .map((integration) => ({
50
- ...integration,
51
- userId: options.userId ?? managedComposioUserId(config.name, options.userIdScope),
52
- allowedTools: allowedComposioTools(integration),
53
- }));
54
- }
55
-
56
- export function hasManagedComposioIntegration(config: Pick<AgentConfig, "name" | "integrations">): boolean {
57
- return resolveManagedComposioIntegrations(config).length > 0;
58
- }
59
-
60
- export function managedComposioRequiredSecrets(config: Pick<AgentConfig, "name" | "integrations">): string[] {
61
- return hasManagedComposioIntegration(config) ? [MANAGED_COMPOSIO_API_KEY_SECRET] : [];
62
- }
63
-
64
- export function createManagedComposioTools(
65
- config: Pick<AgentConfig, "name" | "integrations">,
66
- options: ManagedComposioResolutionOptions = {},
67
- ): AgentTool[] {
68
- const integrations = resolveManagedComposioIntegrations(config, options);
69
-
70
- return integrations.flatMap((integration) => {
71
- if (integration.allowedTools.length === 0) {
72
- return [];
73
- }
74
-
75
- const toolkitByTool = new Map<string, string>();
76
-
77
- for (const [toolkit, tools] of Object.entries(integration.tools ?? {})) {
78
- for (const tool of tools) {
79
- toolkitByTool.set(tool, toolkit);
80
- }
81
- }
82
-
83
- const tool: AgentTool<ManagedComposioToolInput, ManagedComposioToolOutput> = {
84
- name: MANAGED_COMPOSIO_TOOL_NAME,
85
- description: [
86
- "Executes one explicitly allowed AgentKit-managed Composio action for this deployed agent. Use only for configured connected apps.",
87
- integration.confirmExternalWrites === false
88
- ? "External write confirmation is disabled for this integration by agentkit.config.ts."
89
- : "For write actions, pass confirmed: true only after the user confirms the exact external change.",
90
- describeAllowedComposioActions(integration.allowedTools),
91
- ].join("\n\n"),
92
- visibility: "user",
93
- secrets: [MANAGED_COMPOSIO_API_KEY_SECRET],
94
- permissions: integration.allowedTools.map(
95
- (toolName) => `composio:${toolName.toLowerCase()}:${isComposioWriteAction(toolName) ? "write" : "read"}`,
96
- ),
97
- timeoutMs: 60_000,
98
- inputSchema: {
99
- type: "object",
100
- properties: {
101
- toolSlug: {
102
- type: "string",
103
- enum: integration.allowedTools,
104
- description: "Allowed Composio action slug to execute.",
105
- },
106
- arguments: {
107
- type: "object",
108
- additionalProperties: true,
109
- description:
110
- "Structured arguments for the selected Composio action. Use the action notes in the tool description; do not rely on Composio defaults for dates, times, durations, recipients, or write behavior.",
111
- },
112
- confirmed: {
113
- type: "boolean",
114
- description:
115
- "Set true only after explicit user confirmation for external write actions such as create, update, delete, send, patch, move, insert, clear, remove, import, or quick add.",
116
- },
117
- },
118
- required: ["toolSlug", "arguments"],
119
- additionalProperties: false,
120
- },
121
- outputSchema: {
122
- type: "object",
123
- properties: {
124
- successful: { type: "boolean" },
125
- data: { type: ["object", "array", "string", "number", "boolean", "null"] },
126
- error: { type: ["object", "string", "null"] },
127
- logId: { type: ["string", "null"] },
128
- toolkit: { type: "string" },
129
- toolSlug: { type: "string" },
130
- userId: { type: "string" },
131
- },
132
- required: ["successful", "toolkit", "toolSlug", "userId"],
133
- additionalProperties: true,
134
- },
135
- async execute(input, ctx) {
136
- const toolkit = toolkitByTool.get(input.toolSlug);
137
-
138
- if (!toolkit || !integration.allowedTools.includes(input.toolSlug)) {
139
- throw new AgentKitError(
140
- "composio_tool_not_allowed",
141
- `Composio action "${input.toolSlug}" is not allowed by this agent's managed Composio settings.`,
142
- );
143
- }
144
-
145
- validateComposioArguments(input.toolSlug, input.arguments);
146
- validateComposioConfirmation(input.toolSlug, input.confirmed, integration);
147
-
148
- const result = await executeComposioTool({
149
- apiKey: ctx.secrets[MANAGED_COMPOSIO_API_KEY_SECRET],
150
- userId: integration.userId,
151
- toolSlug: input.toolSlug,
152
- arguments: input.arguments,
153
- signal: ctx.signal,
154
- });
155
-
156
- return {
157
- successful: result.successful,
158
- data: result.data ?? null,
159
- error: result.error ?? null,
160
- logId: result.log_id ?? null,
161
- toolkit,
162
- toolSlug: input.toolSlug,
163
- userId: integration.userId,
164
- };
165
- },
166
- render(output) {
167
- if (output.successful) {
168
- return `Composio action ${output.toolSlug} completed.`;
169
- }
170
-
171
- return {
172
- text: `Composio action ${output.toolSlug} did not complete successfully.`,
173
- blocks: [
174
- {
175
- type: "card",
176
- title: "Composio connection or action issue",
177
- subtitle: typeof output.error === "string" ? output.error : undefined,
178
- fields: [
179
- { label: "Toolkit", value: output.toolkit },
180
- { label: "Action", value: output.toolSlug },
181
- ],
182
- },
183
- ],
184
- };
185
- },
186
- };
187
-
188
- return [tool];
189
- });
190
- }
191
-
192
- export function managedComposioUserId(agentName: string, scope = "local"): string {
193
- return `ak_agent_${stableHash(`${scope}:${agentName}`).slice(0, 24)}`;
194
- }
195
-
196
- function allowedComposioTools(integration: ComposioManagedIntegration): string[] {
197
- return Array.from(new Set(Object.values(integration.tools ?? {}).flat())).sort();
198
- }
199
-
200
- function describeAllowedComposioActions(actions: string[]): string {
201
- const lines = ["Allowed Composio actions:"];
202
-
203
- for (const action of actions) {
204
- const guide = COMPOSIO_ACTION_GUIDES[action];
205
-
206
- if (!guide) {
207
- lines.push(`- ${action}: Pass explicit arguments from the current Composio action schema. Do not invent fields or rely on hidden defaults.`);
208
- continue;
209
- }
210
-
211
- lines.push(`- ${action}: ${guide.summary}`);
212
-
213
- for (const note of guide.argumentNotes) {
214
- lines.push(` - ${note}`);
215
- }
216
-
217
- for (const warning of guide.dangerousDefaults ?? []) {
218
- lines.push(` - Dangerous default: ${warning}`);
219
- }
220
-
221
- for (const example of guide.examples ?? []) {
222
- lines.push(` - Example arguments: ${JSON.stringify(example)}`);
223
- }
224
- }
225
-
226
- return lines.join("\n");
227
- }
228
-
229
- function validateComposioArguments(toolSlug: string, args: Record<string, unknown>): void {
230
- if (toolSlug !== "GOOGLECALENDAR_CREATE_EVENT") {
231
- return;
232
- }
233
-
234
- const start = args.start_datetime;
235
-
236
- if (typeof start !== "string" || !isUtcDateTime(start)) {
237
- throw new AgentKitError(
238
- "composio_argument_invalid",
239
- "GOOGLECALENDAR_CREATE_EVENT requires start_datetime as an explicit UTC RFC3339 timestamp ending in Z or +00:00. Convert user-local times using the runtime time zone before calling Composio.",
240
- );
241
- }
242
-
243
- const minutes = args.event_duration_minutes;
244
- const hours = args.event_duration_hour;
245
-
246
- if (!isPositiveNumber(minutes) && !isPositiveNumber(hours)) {
247
- throw new AgentKitError(
248
- "composio_argument_required",
249
- "GOOGLECALENDAR_CREATE_EVENT requires explicit event_duration_minutes or event_duration_hour. Composio defaults event_duration_minutes to 30, so AgentKit blocks implicit duration.",
250
- );
251
- }
252
- }
253
-
254
- function validateComposioConfirmation(
255
- toolSlug: string,
256
- confirmed: boolean | undefined,
257
- integration: ComposioManagedIntegration,
258
- ): void {
259
- if (integration.confirmExternalWrites === false || !isComposioWriteAction(toolSlug)) {
260
- return;
261
- }
262
-
263
- if (confirmed !== true) {
264
- throw new AgentKitError(
265
- "composio_confirmation_required",
266
- `Composio action ${toolSlug} changes an external system. Ask the user to confirm the exact action and call again with confirmed: true.`,
267
- );
268
- }
269
- }
270
-
271
- function isComposioWriteAction(toolSlug: string): boolean {
272
- return /_(?:BATCH|CLEAR|CREATE|DELETE|DUPLICATE|IMPORT|INSERT|MOVE|PATCH|QUICK_ADD|REMOVE|REVOKE|SEND|UPDATE)(?:_|$)/.test(
273
- toolSlug,
274
- );
275
- }
276
-
277
- function isUtcDateTime(value: string): boolean {
278
- return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|\+00:00)$/.test(value);
279
- }
280
-
281
- function isPositiveNumber(value: unknown): boolean {
282
- return typeof value === "number" && Number.isFinite(value) && value > 0;
283
- }
284
-
285
- const COMPOSIO_ACTION_GUIDES: Record<string, ComposioActionGuide> = {
286
- GOOGLECALENDAR_EVENTS_LIST: {
287
- summary: "List events from a calendar before answering schedule/availability questions.",
288
- argumentNotes: [
289
- "calendarId is required by Composio; use primary unless the user selected a different calendar.",
290
- "Use explicit timeMin and timeMax RFC3339 bounds for the requested window.",
291
- "Pass timeZone when the user or business timezone matters.",
292
- ],
293
- examples: [
294
- {
295
- calendarId: "primary",
296
- timeMin: "2026-06-03T00:00:00-03:00",
297
- timeMax: "2026-06-04T00:00:00-03:00",
298
- singleEvents: true,
299
- orderBy: "startTime",
300
- timeZone: "America/Sao_Paulo",
301
- },
302
- ],
303
- },
304
- GOOGLECALENDAR_CREATE_EVENT: {
305
- summary: "Create an event only after confirming the exact title, date, start time, duration, timezone, and attendees/location when relevant.",
306
- argumentNotes: [
307
- "start_datetime is required and must be UTC RFC3339, for example 2026-06-03T15:00:00Z for 12:00 in America/Sao_Paulo.",
308
- "calendar_id defaults to primary; pass it explicitly when known.",
309
- "event_duration_minutes or event_duration_hour must be explicit.",
310
- "Set timezone to the user/business IANA timezone when known.",
311
- ],
312
- dangerousDefaults: [
313
- "event_duration_minutes defaults to 30 if omitted.",
314
- "calendar_id defaults to primary if omitted.",
315
- ],
316
- examples: [
317
- {
318
- calendar_id: "primary",
319
- summary: "Client call",
320
- start_datetime: "2026-06-03T15:00:00Z",
321
- event_duration_minutes: 60,
322
- timezone: "America/Sao_Paulo",
323
- },
324
- ],
325
- },
326
- GOOGLECALENDAR_UPDATE_EVENT: {
327
- summary: "Update an existing event only after identifying the event and confirming the exact change.",
328
- argumentNotes: [
329
- "Read or find the event first so event_id/calendar_id are correct.",
330
- "When changing time, use explicit UTC RFC3339 values and preserve duration unless the user changed it.",
331
- "Do not infer cancellation/deletion from vague wording.",
332
- ],
333
- },
334
- GMAIL_FETCH_EMAILS: {
335
- summary: "Fetch emails for read/search requests.",
336
- argumentNotes: ["Use narrow query/window arguments when available; do not fetch broad mailbox history unnecessarily."],
337
- },
338
- GMAIL_SEND_EMAIL: {
339
- summary: "Send email only after confirming recipients, subject, body, and attachments/links.",
340
- argumentNotes: ["Pass recipient fields explicitly and avoid using draft-like placeholders in production sends."],
341
- },
342
- };
343
-
344
- async function executeComposioTool(input: {
345
- apiKey: string | undefined;
346
- userId: string;
347
- toolSlug: string;
348
- arguments: Record<string, unknown>;
349
- signal: AbortSignal;
350
- }): Promise<{ successful: boolean; data?: unknown; error?: unknown; log_id?: string }> {
351
- if (!input.apiKey) {
352
- throw new AgentKitError("composio_secret_missing", "AgentKit-managed Composio requires COMPOSIO_API_KEY at runtime.");
353
- }
354
-
355
- const response = await fetch(
356
- `https://backend.composio.dev/api/v3.1/tools/execute/${encodeURIComponent(input.toolSlug)}`,
357
- {
358
- method: "POST",
359
- headers: {
360
- "content-type": "application/json",
361
- "x-api-key": input.apiKey,
362
- },
363
- body: JSON.stringify({
364
- user_id: input.userId,
365
- arguments: input.arguments,
366
- }),
367
- signal: input.signal,
368
- },
369
- );
370
- const payload = await response.json().catch(() => null);
371
-
372
- if (!response.ok) {
373
- throw new AgentKitError(
374
- "composio_execution_failed",
375
- `Composio action ${input.toolSlug} failed with HTTP ${response.status}: ${readComposioError(payload)}`,
376
- );
377
- }
378
-
379
- if (!isRecord(payload)) {
380
- return { successful: true, data: payload };
381
- }
382
-
383
- return {
384
- successful: payload.successful !== false,
385
- data: payload.data,
386
- error: payload.error,
387
- log_id: typeof payload.log_id === "string" ? payload.log_id : undefined,
388
- };
389
- }
390
-
391
- function readComposioError(payload: unknown): string {
392
- if (isRecord(payload)) {
393
- if (typeof payload.error === "string") {
394
- return payload.error;
395
- }
396
-
397
- if (isRecord(payload.error) && typeof payload.error.message === "string") {
398
- return payload.error.message;
399
- }
400
- }
401
-
402
- return "unknown error";
403
- }
404
-
405
- function stableHash(value: string): string {
406
- let first = 2166136261;
407
- let second = 0x811c9dc5;
408
- let third = 0x01000193;
409
-
410
- for (let index = 0; index < value.length; index += 1) {
411
- const code = value.charCodeAt(index);
412
- first ^= code;
413
- first = Math.imul(first, 16777619);
414
- second ^= code + index;
415
- second = Math.imul(second, 1597334677);
416
- third ^= code * (index + 1);
417
- third = Math.imul(third, 2246822519);
418
- }
419
-
420
- return [first, second, third].map((hash) => (hash >>> 0).toString(16).padStart(8, "0")).join("");
421
- }
422
-
423
- function isRecord(value: unknown): value is Record<string, unknown> {
424
- return typeof value === "object" && value !== null && !Array.isArray(value);
425
- }