@andreprado/agentkit 0.1.0-alpha.2 → 0.1.0-alpha.20

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 (135) hide show
  1. package/README.md +67 -6
  2. package/docs/guides/add-channel.md +118 -7
  3. package/docs/guides/add-knowledge.md +144 -0
  4. package/docs/guides/add-managed-composio.md +163 -0
  5. package/docs/guides/add-tool.md +1 -1
  6. package/docs/guides/channel-security.md +97 -32
  7. package/docs/guides/connect-discord.md +178 -0
  8. package/docs/guides/connect-slack.md +126 -0
  9. package/docs/guides/connect-telegram.md +78 -1
  10. package/docs/guides/connect-whatsapp-zapster.md +112 -8
  11. package/docs/guides/create-agent.md +45 -4
  12. package/docs/guides/debug-channel.md +147 -0
  13. package/docs/guides/improve-from-production.md +151 -0
  14. package/docs/guides/prepare-deploy.md +47 -17
  15. package/docs/guides/replay-production-traces.md +72 -0
  16. package/docs/guides/run-evals.md +147 -20
  17. package/docs/guides/security-rules.md +7 -6
  18. package/docs/guides/send-feedback.md +135 -0
  19. package/docs/guides/use-provider.md +27 -3
  20. package/docs/llms-full.txt +303 -55
  21. package/docs/llms.txt +57 -7
  22. package/package.json +2 -5
  23. package/src/cli/args.ts +57 -0
  24. package/src/cli/cloud-client.ts +377 -0
  25. package/src/cli/commands/channels.ts +1315 -0
  26. package/src/cli/commands/feedback.ts +438 -0
  27. package/src/cli/commands/knowledge.ts +136 -0
  28. package/src/cli/commands/transcribe.ts +171 -0
  29. package/src/cli/constants.ts +4 -0
  30. package/src/cli/deploy-chat-ui.ts +535 -0
  31. package/src/cli/deploy-readiness.ts +481 -0
  32. package/src/cli/flags.ts +162 -0
  33. package/src/cli/help.ts +236 -0
  34. package/src/cli/index.ts +1167 -1005
  35. package/src/cli/process.ts +31 -0
  36. package/src/cloud/artifact.ts +139 -0
  37. package/src/cloud/client.ts +80 -0
  38. package/src/cloud/contracts.ts +63 -0
  39. package/src/cloud/index.ts +3 -0
  40. package/src/create-project.ts +21 -6
  41. package/src/index.ts +479 -7
  42. package/src/providers/pi.ts +70 -16
  43. package/src/providers/test.ts +88 -1
  44. package/src/providers/types.ts +7 -0
  45. package/src/runtime/channel-buffer.ts +30 -0
  46. package/src/runtime/channel-test-harness.ts +8 -1
  47. package/src/runtime/channels/discord.ts +896 -0
  48. package/src/runtime/channels/slack.ts +646 -0
  49. package/src/runtime/channels/telegram.ts +466 -23
  50. package/src/runtime/channels/whatsapp-meta.ts +9 -0
  51. package/src/runtime/channels/whatsapp-zapster.ts +677 -40
  52. package/src/runtime/channels.ts +86 -3
  53. package/src/runtime/chat.ts +130 -38
  54. package/src/runtime/config.ts +483 -18
  55. package/src/runtime/core/manifest.ts +103 -5
  56. package/src/runtime/core/targets.ts +5 -5
  57. package/src/runtime/database.ts +93 -2
  58. package/src/runtime/db-commands.ts +9 -0
  59. package/src/runtime/deploy-readiness.ts +46 -4
  60. package/src/runtime/deploy.ts +1 -1
  61. package/src/runtime/dev-server.ts +759 -41
  62. package/src/runtime/env.ts +8 -3
  63. package/src/runtime/evals.ts +589 -43
  64. package/src/runtime/improve.ts +868 -0
  65. package/src/runtime/inspect.ts +194 -4
  66. package/src/runtime/integrations/composio.ts +423 -0
  67. package/src/runtime/knowledge/chunk.ts +333 -0
  68. package/src/runtime/knowledge/config.ts +135 -0
  69. package/src/runtime/knowledge/embeddings.ts +133 -0
  70. package/src/runtime/knowledge/ingest.ts +521 -0
  71. package/src/runtime/knowledge/prompt-policy.ts +30 -0
  72. package/src/runtime/knowledge/retrieve.ts +303 -0
  73. package/src/runtime/knowledge/schema.ts +100 -0
  74. package/src/runtime/knowledge/tool.ts +64 -0
  75. package/src/runtime/knowledge/vector.ts +258 -0
  76. package/src/runtime/prompt-context.ts +141 -0
  77. package/src/runtime/runtime-contract.ts +86 -8
  78. package/src/runtime/skills.ts +95 -0
  79. package/src/runtime/spec.ts +152 -0
  80. package/src/runtime/sync.ts +144 -0
  81. package/src/runtime/targets/cloudflare/build.ts +1430 -185
  82. package/src/runtime/targets/container/server.ts +1 -1
  83. package/src/runtime/targets/vps/deploy.ts +26 -9
  84. package/src/runtime/tool-runner.ts +9 -1
  85. package/src/runtime/tools.ts +128 -2
  86. package/src/runtime/traces.ts +41 -0
  87. package/src/runtime/transcription.ts +483 -0
  88. package/src/storage/sqlite.ts +149 -3
  89. package/src/templates/blank.ts +76 -17
  90. package/src/templates/dentista.ts +1011 -0
  91. package/src/templates/index.ts +2 -0
  92. package/src/templates/skills/agentkit-build-agent/SKILL.md +52 -0
  93. package/src/templates/skills/agentkit-build-agent/templates/appointment-intake.instructions.md +21 -0
  94. package/src/templates/skills/agentkit-build-agent/templates/sales-qualifier.instructions.md +17 -0
  95. package/src/templates/skills/agentkit-build-agent/templates/support-agent.instructions.md +16 -0
  96. package/src/templates/skills/agentkit-capsule/SKILL.md +70 -0
  97. package/src/templates/skills/agentkit-capsule/references/docs-router.md +15 -0
  98. package/src/templates/skills/agentkit-channels/SKILL.md +104 -0
  99. package/src/templates/skills/agentkit-channels/references/channel-buffering.md +65 -0
  100. package/src/templates/skills/agentkit-channels/references/channel-debugging.md +66 -0
  101. package/src/templates/skills/agentkit-channels/references/discord.md +93 -0
  102. package/src/templates/skills/agentkit-channels/references/slack.md +56 -0
  103. package/src/templates/skills/agentkit-channels/references/telegram.md +72 -0
  104. package/src/templates/skills/agentkit-channels/references/whatsapp-zapster.md +77 -0
  105. package/src/templates/skills/agentkit-database/SKILL.md +45 -0
  106. package/src/templates/skills/agentkit-database/templates/appointments.schema.sql +15 -0
  107. package/src/templates/skills/agentkit-database/templates/leads.schema.sql +17 -0
  108. package/src/templates/skills/agentkit-deploy/SKILL.md +50 -0
  109. package/src/templates/skills/agentkit-evals/SKILL.md +109 -0
  110. package/src/templates/skills/agentkit-evals/templates/multi-turn.eval.md +29 -0
  111. package/src/templates/skills/agentkit-evals/templates/no-leak.eval.md +18 -0
  112. package/src/templates/skills/agentkit-evals/templates/smoke.eval.md +18 -0
  113. package/src/templates/skills/agentkit-evals/templates/tool-call.eval.md +27 -0
  114. package/src/templates/skills/agentkit-improve/SKILL.md +86 -0
  115. package/src/templates/skills/agentkit-improve/references/replay-side-effects.md +18 -0
  116. package/src/templates/skills/agentkit-improve/references/trace-packets.md +22 -0
  117. package/src/templates/skills/agentkit-improve/templates/regression.eval.md +18 -0
  118. package/src/templates/skills/agentkit-integrations/SKILL.md +76 -0
  119. package/src/templates/skills/agentkit-knowledge/SKILL.md +43 -0
  120. package/src/templates/skills/agentkit-knowledge/templates/faq.md +14 -0
  121. package/src/templates/skills/agentkit-knowledge/templates/policies.md +14 -0
  122. package/src/templates/skills/agentkit-knowledge/templates/prices.csv +3 -0
  123. package/src/templates/skills/agentkit-prompts/SKILL.md +47 -0
  124. package/src/templates/skills/agentkit-prompts/templates/knowledge-grounded-faq.instructions.md +11 -0
  125. package/src/templates/skills/agentkit-provider/SKILL.md +60 -0
  126. package/src/templates/skills/agentkit-security/SKILL.md +56 -0
  127. package/src/templates/skills/agentkit-tools/SKILL.md +37 -0
  128. package/src/templates/skills/agentkit-tools/examples/database-write.tool.md +35 -0
  129. package/src/templates/skills/agentkit-tools/examples/eval-safe-external-action.tool.md +37 -0
  130. package/src/templates/skills/agentkit-tools/examples/lookup-order.tool.md +46 -0
  131. package/src/templates/skills/agentkit-troubleshooting/SKILL.md +76 -0
  132. package/src/templates/support.ts +77 -18
  133. package/docs/guides/channels-production-handoff.md +0 -99
  134. package/docs/portable-deploy-release-checklist.md +0 -41
  135. package/src/runtime/targets/cloudflare/deploy.ts +0 -5475
@@ -0,0 +1,481 @@
1
+ import { findAgentCapsuleRoot, loadAgentCapsule } from "../runtime/config";
2
+ import { loadDeployReadinessContext, type DeployReadinessContext } from "../runtime/deploy-readiness";
3
+ import { loadCapsuleEnv } from "../runtime/env";
4
+ import { isAgentKitError } from "../runtime/errors";
5
+ import { MANAGED_COMPOSIO_API_KEY_SECRET, MANAGED_COMPOSIO_ENTITLEMENT } from "../runtime/integrations/composio";
6
+ import {
7
+ cloudApiRequest,
8
+ formatCloudAuthSource,
9
+ readCloudAuthForApiUrl,
10
+ type CloudCapabilitiesResponse,
11
+ type CloudLimitsResponse,
12
+ type CloudManagedComposioResponse,
13
+ type CloudMeResponse,
14
+ type CloudProjectResolveResponse,
15
+ type CloudSecretsResponse,
16
+ } from "./cloud-client";
17
+
18
+ type DeployReadinessStatus = "pass" | "fail" | "warn" | "info";
19
+
20
+ type DeployReadinessCheck = {
21
+ status: DeployReadinessStatus;
22
+ title: string;
23
+ message: string;
24
+ action?: string;
25
+ };
26
+
27
+ type DeployReadinessReport = {
28
+ ok: boolean;
29
+ apiUrl: string;
30
+ context: DeployReadinessContext;
31
+ checks: DeployReadinessCheck[];
32
+ };
33
+
34
+ export async function checkDeployReadiness(options: {
35
+ apiUrl: string;
36
+ requireLogin: boolean;
37
+ }): Promise<DeployReadinessReport> {
38
+ const context = await loadDeployReadinessContext(process.cwd(), process.env);
39
+ const auth = options.requireLogin ? await readCloudAuthForApiUrl(options.apiUrl) : null;
40
+ const checks: DeployReadinessCheck[] = [];
41
+ let cloudAuthUsable = false;
42
+
43
+ if (context.runtime !== "edge") {
44
+ checks.push({
45
+ status: "fail",
46
+ title: "Target runtime",
47
+ message: 'Cloudflare deploy requires runtime: "edge" in agentkit.config.ts.',
48
+ action: "set runtime: \"edge\" before deploying to AgentKit Cloud",
49
+ });
50
+ } else {
51
+ checks.push({
52
+ status: "pass",
53
+ title: "Target runtime",
54
+ message: "Capsule is configured for edge deploy.",
55
+ });
56
+ }
57
+
58
+ const nodeMajor = majorNodeVersion(process.versions.node);
59
+ if (nodeMajor !== null && nodeMajor < 24) {
60
+ checks.push({
61
+ status: "warn",
62
+ title: "Node version",
63
+ message: `@andreprado/agentkit requires Node >=24; current Node is ${process.versions.node}.`,
64
+ action: "use Node 24+ before running direct node imports or production container commands",
65
+ });
66
+ } else {
67
+ checks.push({
68
+ status: "pass",
69
+ title: "Node version",
70
+ message: `Node ${process.versions.node} satisfies @andreprado/agentkit engines.node >=24.`,
71
+ });
72
+ }
73
+
74
+ if (!auth?.token) {
75
+ checks.push({
76
+ status: options.requireLogin ? "fail" : "warn",
77
+ title: "Login",
78
+ message: options.requireLogin
79
+ ? "No AgentKit Cloud token was found for hosted production deploy."
80
+ : "No AgentKit Cloud token was found; deploy will request anonymous mode.",
81
+ action: "agentkit login --token <token>",
82
+ });
83
+ } else {
84
+ try {
85
+ const me = (await cloudApiRequest(options.apiUrl, "/v1/me", { method: "GET" })) as CloudMeResponse;
86
+ const email = me.account?.email;
87
+ checks.push({
88
+ status: "pass",
89
+ title: "Login",
90
+ message: email ? `Authenticated as ${email}.` : "AgentKit Cloud token is accepted.",
91
+ });
92
+ cloudAuthUsable = true;
93
+ } catch (error) {
94
+ checks.push({
95
+ status: "fail",
96
+ title: "Login",
97
+ message: `AgentKit Cloud rejected the token from ${formatCloudAuthSource(auth)}. ${formatReadinessError(error)}`,
98
+ action: "agentkit login --token <token>",
99
+ });
100
+ }
101
+ }
102
+
103
+ if (cloudAuthUsable) {
104
+ try {
105
+ context.projectId = await resolveCloudProjectId(options.apiUrl, context.projectName);
106
+ } catch (error) {
107
+ checks.push({
108
+ status: "fail",
109
+ title: "Project identity",
110
+ message: `Could not resolve the account-scoped AgentKit Cloud project. ${formatReadinessError(error)}`,
111
+ });
112
+ cloudAuthUsable = false;
113
+ }
114
+ }
115
+
116
+ if (cloudAuthUsable) {
117
+ try {
118
+ const payload = (await cloudApiRequest(options.apiUrl, "/v1/me/capabilities", {
119
+ method: "GET",
120
+ })) as CloudCapabilitiesResponse;
121
+ const capabilities = payload.capabilities ?? [];
122
+ const hasCloudflareAlpha = capabilities.some(
123
+ (capability) => capability.name === "cloudflare_deploy_alpha" && capability.status === "active",
124
+ );
125
+ const hasManagedComposio = capabilities.some(
126
+ (capability) => capability.name === MANAGED_COMPOSIO_ENTITLEMENT && capability.status === "active",
127
+ );
128
+
129
+ checks.push({
130
+ status: hasCloudflareAlpha ? "pass" : "fail",
131
+ title: "Deploy entitlement",
132
+ message: hasCloudflareAlpha
133
+ ? "cloudflare_deploy_alpha is active."
134
+ : "This account is missing the cloudflare_deploy_alpha entitlement.",
135
+ ...(hasCloudflareAlpha ? {} : { action: "log in with an invited AgentKit Cloud alpha token" }),
136
+ });
137
+
138
+ if (context.integrations.managedComposio.enabled) {
139
+ checks.push({
140
+ status: hasManagedComposio ? "pass" : "fail",
141
+ title: "Managed Composio entitlement",
142
+ message: hasManagedComposio
143
+ ? `${MANAGED_COMPOSIO_ENTITLEMENT} is active.`
144
+ : `This capsule uses AgentKit-managed Composio, but this account is missing ${MANAGED_COMPOSIO_ENTITLEMENT}.`,
145
+ ...(hasManagedComposio ? {} : { action: "upgrade the AgentKit Cloud account or ask an operator to grant managed_composio" }),
146
+ });
147
+ }
148
+ } catch (error) {
149
+ checks.push({
150
+ status: "fail",
151
+ title: "Deploy entitlement",
152
+ message: `Could not verify AgentKit Cloud capabilities. ${formatReadinessError(error)}`,
153
+ });
154
+ }
155
+
156
+ try {
157
+ const payload = (await cloudApiRequest(options.apiUrl, "/v1/me/limits", {
158
+ method: "GET",
159
+ })) as CloudLimitsResponse;
160
+ const account = payload.online_agents?.account;
161
+ const global = payload.online_agents?.global;
162
+ const accountLimit = normalizeOptionalNumber(account?.limit);
163
+ const accountUsed = normalizeOptionalNumber(account?.used);
164
+ const globalLimit = normalizeOptionalNumber(global?.limit);
165
+ const globalUsed = normalizeOptionalNumber(global?.used);
166
+
167
+ if (accountLimit !== undefined && accountUsed !== undefined && accountUsed >= accountLimit) {
168
+ checks.push({
169
+ status: "fail",
170
+ title: "Online agent capacity",
171
+ message: `This account is already using ${accountUsed}/${accountLimit} online AgentKit deploys.`,
172
+ action: "agentkit deploy pause",
173
+ });
174
+ } else if (globalLimit !== undefined && globalUsed !== undefined && globalUsed >= globalLimit) {
175
+ checks.push({
176
+ status: "fail",
177
+ title: "Online agent capacity",
178
+ message: `AgentKit Cloud is already using ${globalUsed}/${globalLimit} global online deploy slots.`,
179
+ action: "agentkit deploy status",
180
+ });
181
+ } else if (accountLimit !== undefined && accountUsed !== undefined) {
182
+ checks.push({
183
+ status: "pass",
184
+ title: "Online agent capacity",
185
+ message: `Account has capacity: ${accountUsed}/${accountLimit} online deploys are in use.`,
186
+ });
187
+ } else if (globalLimit !== undefined && globalUsed !== undefined) {
188
+ checks.push({
189
+ status: "pass",
190
+ title: "Online agent capacity",
191
+ message: `Global capacity is available: ${globalUsed}/${globalLimit} online deploys are in use.`,
192
+ });
193
+ } else {
194
+ checks.push({
195
+ status: "info",
196
+ title: "Online agent capacity",
197
+ message: "No online deploy limit is configured for this account.",
198
+ });
199
+ }
200
+ } catch (error) {
201
+ checks.push({
202
+ status: "warn",
203
+ title: "Online agent capacity",
204
+ message: `Could not verify online deploy capacity. ${formatReadinessError(error)}`,
205
+ });
206
+ }
207
+
208
+ if (context.integrations.managedComposio.enabled) {
209
+ try {
210
+ const payload = (await cloudApiRequest(
211
+ options.apiUrl,
212
+ `/v1/me/managed-composio?toolkits=${encodeURIComponent(context.integrations.managedComposio.toolkits.join(","))}`,
213
+ {
214
+ method: "GET",
215
+ },
216
+ )) as CloudManagedComposioResponse;
217
+ const managed = payload.managed_composio;
218
+ const missingToolkits = (managed?.toolkits ?? []).filter((toolkit) => toolkit.auth_config !== "set");
219
+
220
+ if (managed?.api_key !== "set") {
221
+ checks.push({
222
+ status: "fail",
223
+ title: "Managed Composio API key",
224
+ message: `AgentKit Cloud is missing AGENTKIT_SECRET_${MANAGED_COMPOSIO_API_KEY_SECRET}.`,
225
+ action: "ask the AgentKit Cloud operator to configure managed Composio",
226
+ });
227
+ } else {
228
+ checks.push({
229
+ status: "pass",
230
+ title: "Managed Composio API key",
231
+ message: "AgentKit Cloud has the managed COMPOSIO_API_KEY.",
232
+ });
233
+ }
234
+
235
+ if (missingToolkits.length > 0) {
236
+ checks.push({
237
+ status: "fail",
238
+ title: "Managed Composio auth configs",
239
+ message: `Missing ${missingToolkits
240
+ .map((toolkit) => `${toolkit.auth_config_env ?? "auth config"} for ${toolkit.toolkit ?? "unknown"}`)
241
+ .join(", ")}.`,
242
+ action: "ask the AgentKit Cloud operator to configure the Composio auth config registry or fallback env",
243
+ });
244
+ } else {
245
+ const toolkitSources = (managed?.toolkits ?? []).map((toolkit) =>
246
+ `${toolkit.toolkit ?? "unknown"}${toolkit.auth_config_source ? ` via ${toolkit.auth_config_source}` : ""}`,
247
+ );
248
+ checks.push({
249
+ status: "pass",
250
+ title: "Managed Composio auth configs",
251
+ message: `Auth configs are available for ${toolkitSources.join(", ")}.`,
252
+ });
253
+ }
254
+ } catch (error) {
255
+ checks.push({
256
+ status: "warn",
257
+ title: "Managed Composio auth configs",
258
+ message: `Could not verify managed Composio auth configs. ${formatReadinessError(error)}`,
259
+ });
260
+ }
261
+ }
262
+ }
263
+
264
+ if (context.agentKitManagedSecrets.length > 0) {
265
+ checks.push({
266
+ status: "info",
267
+ title: "AgentKit-managed secrets",
268
+ message: `${context.agentKitManagedSecrets.join(", ")} ${
269
+ context.agentKitManagedSecrets.length === 1 ? "is" : "are"
270
+ } provisioned by AgentKit Cloud during deploy.`,
271
+ });
272
+ }
273
+
274
+ if (context.integrations.managedComposio.enabled) {
275
+ if (!options.requireLogin) {
276
+ checks.push({
277
+ status: "fail",
278
+ title: "Managed Composio access",
279
+ message: "AgentKit-managed Composio is paid hosted infrastructure and cannot be used by anonymous deploys.",
280
+ action: "run agentkit deploy without --anonymous after logging in with a paid AgentKit Cloud account",
281
+ });
282
+ } else {
283
+ checks.push({
284
+ status: "info",
285
+ title: "Managed Composio",
286
+ message: `Configured for ${context.integrations.managedComposio.toolkits.join(", ")} with ${
287
+ context.integrations.managedComposio.toolCount
288
+ } allowed action${context.integrations.managedComposio.toolCount === 1 ? "" : "s"}. AgentKit Cloud injects COMPOSIO_API_KEY.`,
289
+ });
290
+ }
291
+ }
292
+
293
+ if (context.accessMode === "private") {
294
+ checks.push({
295
+ status: "info",
296
+ title: "Private access",
297
+ message: "AGENTKIT_PRIVATE_TOKEN is required at runtime; AgentKit Cloud generates it and saves it in .agentkit/deploy.json.",
298
+ });
299
+ }
300
+
301
+ if (context.knowledge.enabled) {
302
+ if (context.knowledge.databaseDriver !== "turso") {
303
+ checks.push({
304
+ status: "fail",
305
+ title: "Knowledge storage",
306
+ message: "Hosted Knowledge requires a Turso database so indexed chunks are available to the Cloudflare runtime.",
307
+ action: 'set storage.database.driver: "turso" in agentkit.config.ts before deploying Knowledge',
308
+ });
309
+ } else {
310
+ checks.push({
311
+ status: "pass",
312
+ title: "Knowledge storage",
313
+ message: `Knowledge is configured with ${context.knowledge.sourceCount} source${
314
+ context.knowledge.sourceCount === 1 ? "" : "s"
315
+ } and Turso storage.`,
316
+ });
317
+ }
318
+ }
319
+
320
+ if (context.userManagedSecrets.length === 0) {
321
+ checks.push({
322
+ status: "pass",
323
+ title: "Hosted secrets",
324
+ message: "No user-managed hosted secrets are required by this capsule.",
325
+ });
326
+ } else if (!cloudAuthUsable) {
327
+ checks.push({
328
+ status: options.requireLogin ? "fail" : "warn",
329
+ title: "Hosted secrets",
330
+ message: `Could not check hosted secrets without a valid AgentKit Cloud login. Required: ${context.userManagedSecrets.join(", ")}.`,
331
+ action: "agentkit secret list",
332
+ });
333
+ } else {
334
+ try {
335
+ const payload = (await cloudApiRequest(
336
+ options.apiUrl,
337
+ `/v1/projects/${encodeURIComponent(context.projectId)}/secrets`,
338
+ { method: "GET" },
339
+ )) as CloudSecretsResponse;
340
+ const hostedSecretNames = new Set((payload.secrets ?? []).map((secret) => secret.name).filter(isString));
341
+ const missing = context.userManagedSecrets.filter((name) => !hostedSecretNames.has(name));
342
+
343
+ if (missing.length === 0) {
344
+ checks.push({
345
+ status: "pass",
346
+ title: "Hosted secrets",
347
+ message: "All user-managed hosted secrets are set.",
348
+ });
349
+ } else {
350
+ for (const secret of missing) {
351
+ const localSource = context.localSecrets[secret];
352
+ checks.push({
353
+ status: "fail",
354
+ title: `Hosted secret ${secret}`,
355
+ message: localSource
356
+ ? `${secret} is present locally but has not been set in AgentKit Cloud.`
357
+ : `${secret} is required but missing from AgentKit Cloud.`,
358
+ action: secretSetCommand(secret, localSource),
359
+ });
360
+ }
361
+ }
362
+ } catch (error) {
363
+ checks.push({
364
+ status: "fail",
365
+ title: "Hosted secrets",
366
+ message: `Could not list hosted secrets for project ${context.projectId}. ${formatReadinessError(error)}`,
367
+ action: "agentkit secret list",
368
+ });
369
+ }
370
+ }
371
+
372
+ return {
373
+ ok: checks.every((check) => check.status !== "fail"),
374
+ apiUrl: options.apiUrl,
375
+ context,
376
+ checks,
377
+ };
378
+ }
379
+
380
+ export function printDeployReadinessReport(report: DeployReadinessReport): void {
381
+ console.log("AgentKit deploy readiness");
382
+ console.log(`Project: ${report.context.projectName}`);
383
+ console.log(`Project ID: ${report.context.projectId}`);
384
+ console.log(`Target: ${report.context.target}`);
385
+ console.log(`API: ${report.apiUrl}`);
386
+ console.log("");
387
+
388
+ for (const check of report.checks) {
389
+ console.log(`[${check.status}] ${check.title}: ${check.message}`);
390
+
391
+ if (check.action) {
392
+ console.log(` Run: ${check.action}`);
393
+ }
394
+ }
395
+ }
396
+
397
+ export async function syncHostedSecretsFromLocal(options: { apiUrl: string; projectId: string }): Promise<void> {
398
+ const context = await loadDeployReadinessContext(process.cwd(), process.env);
399
+ const localEnv = await loadCapsuleEnv(context.root, {});
400
+ let synced = 0;
401
+ let skipped = 0;
402
+
403
+ for (const secret of context.userManagedSecrets) {
404
+ const value = localEnv[secret];
405
+
406
+ if (value === undefined) {
407
+ skipped += 1;
408
+ console.log(`${secret}\tskipped_missing_local`);
409
+ continue;
410
+ }
411
+
412
+ await cloudApiRequest(options.apiUrl, `/v1/projects/${encodeURIComponent(options.projectId)}/secrets/${encodeURIComponent(secret)}`, {
413
+ method: "PUT",
414
+ body: JSON.stringify({ value }),
415
+ });
416
+ synced += 1;
417
+ console.log(`${secret}\tsynced`);
418
+ }
419
+
420
+ if (context.userManagedSecrets.length === 0) {
421
+ console.log("No user-managed hosted secrets are declared by this capsule.");
422
+ return;
423
+ }
424
+
425
+ console.log("");
426
+ console.log(`${synced} synced, ${skipped} skipped`);
427
+ }
428
+
429
+ export function formatReadinessError(error: unknown): string {
430
+ if (isAgentKitError(error)) {
431
+ return `${error.code}: ${error.message}`;
432
+ }
433
+
434
+ return error instanceof Error ? error.message : String(error);
435
+ }
436
+
437
+ export async function resolveProjectIdForSecretCommand(cwd: string, apiUrl: string): Promise<string> {
438
+ const root = await findAgentCapsuleRoot(cwd);
439
+ const capsule = await loadAgentCapsule(root);
440
+ return resolveCloudProjectId(apiUrl, capsule.config.name);
441
+ }
442
+
443
+ async function resolveCloudProjectId(apiUrl: string, projectName: string): Promise<string> {
444
+ const payload = (await cloudApiRequest(apiUrl, "/v1/projects/resolve", {
445
+ method: "POST",
446
+ body: JSON.stringify({ project_name: projectName }),
447
+ })) as CloudProjectResolveResponse;
448
+ const projectId = payload.project?.id;
449
+
450
+ if (!projectId) {
451
+ throw new Error("AgentKit Cloud did not return a project id.");
452
+ }
453
+
454
+ return projectId;
455
+ }
456
+
457
+ function secretSetCommand(secret: string, source: DeployReadinessContext["localSecrets"][string] | undefined): string {
458
+ if (source?.dotenv) {
459
+ return `npm run agentkit -- secret set ${secret} --from-local-env`;
460
+ }
461
+
462
+ if (source?.environment) {
463
+ return `npm run agentkit -- secret set ${secret} --from-env`;
464
+ }
465
+
466
+ return `npm run agentkit -- secret set ${secret} --stdin`;
467
+ }
468
+
469
+ function normalizeOptionalNumber(value: number | null | undefined): number | undefined {
470
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
471
+ }
472
+
473
+ function majorNodeVersion(version: string): number | null {
474
+ const [major] = version.split(".");
475
+ const parsed = Number(major);
476
+ return Number.isInteger(parsed) ? parsed : null;
477
+ }
478
+
479
+ function isString(value: unknown): value is string {
480
+ return typeof value === "string";
481
+ }
@@ -0,0 +1,162 @@
1
+ import { listTargetsWithCapability } from "../runtime/core/targets";
2
+ import { loadCapsuleEnv } from "../runtime/env";
3
+ import { AgentKitError } from "../runtime/errors";
4
+ import { defaultAgentKitCloudApiUrl } from "./constants";
5
+
6
+ export function parsePort(value: string | boolean | undefined, usage = "agentkit dev --port <number>"): number | undefined {
7
+ if (value === undefined) {
8
+ return undefined;
9
+ }
10
+
11
+ if (typeof value !== "string") {
12
+ throw new Error(`Missing port. Usage: ${usage}`);
13
+ }
14
+
15
+ const port = Number(value);
16
+
17
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
18
+ throw new Error(`Invalid port. Usage: ${usage}`);
19
+ }
20
+
21
+ return port;
22
+ }
23
+
24
+ export function parseTargetFlag(value: string | boolean | undefined, capability: "build" | "deploy"): string {
25
+ if (value === undefined) {
26
+ return "cloudflare";
27
+ }
28
+
29
+ if (typeof value !== "string") {
30
+ throw new Error(
31
+ `Missing target. Usage: agentkit ${capability} --target ${listTargetsWithCapability(capability).join("|")}`,
32
+ );
33
+ }
34
+
35
+ return value;
36
+ }
37
+
38
+ export function parseCloudApiUrl(value: string | boolean | undefined): string {
39
+ if (value === undefined) {
40
+ return process.env.AGENTKIT_CLOUD_API_URL ?? defaultAgentKitCloudApiUrl;
41
+ }
42
+
43
+ if (typeof value !== "string") {
44
+ throw new Error("Missing API URL. Usage: agentkit deploy --api <url>");
45
+ }
46
+
47
+ return value;
48
+ }
49
+
50
+ export function parseRequiredStringFlag(value: string | boolean | undefined, name: string, usage: string): string {
51
+ if (typeof value !== "string" || value.trim().length === 0) {
52
+ throw new Error(`Missing ${name}. Usage: ${usage}`);
53
+ }
54
+
55
+ return value.trim();
56
+ }
57
+
58
+ export function parseOptionalStringFlag(value: string | boolean | undefined, name: string, usage: string): string | undefined {
59
+ if (value === undefined) {
60
+ return undefined;
61
+ }
62
+
63
+ if (typeof value !== "string" || value.trim().length === 0) {
64
+ throw new Error(`Missing ${name}. Usage: ${usage}`);
65
+ }
66
+
67
+ return value.trim();
68
+ }
69
+
70
+ export async function resolveSecretInputValue(options: {
71
+ name: string | undefined;
72
+ valueParts: string[];
73
+ stdinFlag: string | boolean | undefined;
74
+ fromEnvFlag: string | boolean | undefined;
75
+ fromLocalEnvFlag: string | boolean | undefined;
76
+ localEnvRoot?: string;
77
+ usage: string;
78
+ inlineSensitiveHelp?: string;
79
+ }): Promise<string> {
80
+ const { name, valueParts, stdinFlag, fromEnvFlag, fromLocalEnvFlag, localEnvRoot, usage, inlineSensitiveHelp } = options;
81
+
82
+ if (!name) {
83
+ throw new Error(`Missing name. Usage: ${usage}`);
84
+ }
85
+
86
+ const hasInlineValue = valueParts.length > 0;
87
+ const hasStdin = stdinFlag !== undefined;
88
+ const hasFromEnv = fromEnvFlag !== undefined;
89
+ const hasFromLocalEnv = fromLocalEnvFlag !== undefined;
90
+ const inputModes = [hasInlineValue, hasStdin, hasFromEnv, hasFromLocalEnv].filter(Boolean).length;
91
+
92
+ if (inputModes !== 1) {
93
+ throw new Error(`Provide exactly one value source. Usage: ${usage}`);
94
+ }
95
+
96
+ let value: string;
97
+
98
+ if (hasInlineValue) {
99
+ value = valueParts.join(" ");
100
+ if (looksLikeSecretName(name)) {
101
+ console.error(
102
+ `Warning: ${name} looks sensitive. ${inlineSensitiveHelp ?? "Prefer --stdin or --from-env so the value does not enter shell history."}`,
103
+ );
104
+ }
105
+ } else if (hasStdin) {
106
+ if (stdinFlag !== true) {
107
+ throw new Error(`--stdin does not take a value. Usage: ${usage}`);
108
+ }
109
+
110
+ value = stripOneTrailingNewline(await readStdinText());
111
+ } else if (hasFromEnv) {
112
+ const envName = fromEnvFlag === true ? name : parseRequiredStringFlag(fromEnvFlag, "env name", usage);
113
+ const envValue = process.env[envName];
114
+
115
+ if (envValue === undefined) {
116
+ throw new AgentKitError("secret_not_found", `Environment variable ${envName} is not set.`);
117
+ }
118
+
119
+ value = envValue;
120
+ } else {
121
+ if (fromLocalEnvFlag !== true) {
122
+ throw new Error(`--from-local-env does not take a value. Usage: ${usage}`);
123
+ }
124
+
125
+ if (!localEnvRoot) {
126
+ throw new Error(`--from-local-env is not available for this command. Usage: ${usage}`);
127
+ }
128
+
129
+ const localEnv = await loadCapsuleEnv(localEnvRoot, {});
130
+ const localValue = localEnv[name];
131
+
132
+ if (localValue === undefined) {
133
+ throw new AgentKitError("secret_not_found", `Local .env does not contain ${name}.`);
134
+ }
135
+
136
+ value = localValue;
137
+ }
138
+
139
+ if (value.length === 0) {
140
+ throw new Error(`Secret value cannot be empty. Usage: ${usage}`);
141
+ }
142
+
143
+ return value;
144
+ }
145
+
146
+ function looksLikeSecretName(name: string): boolean {
147
+ return /(?:SECRET|TOKEN|KEY|PASSWORD|CREDENTIAL|PRIVATE)/i.test(name);
148
+ }
149
+
150
+ async function readStdinText(): Promise<string> {
151
+ const chunks: Buffer[] = [];
152
+
153
+ for await (const chunk of process.stdin) {
154
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
155
+ }
156
+
157
+ return Buffer.concat(chunks).toString("utf8");
158
+ }
159
+
160
+ function stripOneTrailingNewline(value: string): string {
161
+ return value.replace(/\r?\n$/, "");
162
+ }