@andreprado/agentkit 0.1.0-alpha.10

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 (122) hide show
  1. package/README.md +69 -0
  2. package/bin/agentkit.mjs +23 -0
  3. package/docs/guides/add-channel.md +114 -0
  4. package/docs/guides/add-knowledge.md +134 -0
  5. package/docs/guides/add-tool.md +342 -0
  6. package/docs/guides/agentkit-skills-architecture.md +471 -0
  7. package/docs/guides/channel-security.md +81 -0
  8. package/docs/guides/channels-implementation-map.md +243 -0
  9. package/docs/guides/channels-production-handoff.md +102 -0
  10. package/docs/guides/connect-telegram.md +110 -0
  11. package/docs/guides/connect-whatsapp-zapster.md +119 -0
  12. package/docs/guides/create-agent.md +220 -0
  13. package/docs/guides/prepare-deploy.md +209 -0
  14. package/docs/guides/run-evals.md +179 -0
  15. package/docs/guides/security-rules.md +156 -0
  16. package/docs/guides/use-provider.md +140 -0
  17. package/docs/llms-full.txt +876 -0
  18. package/docs/llms.txt +83 -0
  19. package/docs/portable-deploy-release-checklist.md +41 -0
  20. package/package.json +47 -0
  21. package/src/cli/args.ts +36 -0
  22. package/src/cli/cloud-client.ts +265 -0
  23. package/src/cli/commands/channels.ts +810 -0
  24. package/src/cli/commands/knowledge.ts +136 -0
  25. package/src/cli/constants.ts +4 -0
  26. package/src/cli/deploy-chat-ui.ts +392 -0
  27. package/src/cli/deploy-readiness.ts +348 -0
  28. package/src/cli/flags.ts +162 -0
  29. package/src/cli/help.ts +184 -0
  30. package/src/cli/index.ts +1276 -0
  31. package/src/cli/process.ts +31 -0
  32. package/src/cloud/artifact.ts +139 -0
  33. package/src/cloud/client.ts +79 -0
  34. package/src/cloud/contracts.ts +63 -0
  35. package/src/cloud/index.ts +3 -0
  36. package/src/create-project.ts +177 -0
  37. package/src/index.ts +408 -0
  38. package/src/providers/index.ts +25 -0
  39. package/src/providers/pi.ts +286 -0
  40. package/src/providers/test.ts +133 -0
  41. package/src/providers/types.ts +34 -0
  42. package/src/runtime/build.ts +43 -0
  43. package/src/runtime/channel-buffer.ts +30 -0
  44. package/src/runtime/channel-test-harness.ts +112 -0
  45. package/src/runtime/channels/telegram.ts +360 -0
  46. package/src/runtime/channels/website.ts +132 -0
  47. package/src/runtime/channels/whatsapp-meta.ts +71 -0
  48. package/src/runtime/channels/whatsapp-zapster.ts +278 -0
  49. package/src/runtime/channels.ts +138 -0
  50. package/src/runtime/chat.ts +218 -0
  51. package/src/runtime/config.ts +684 -0
  52. package/src/runtime/conversations.ts +38 -0
  53. package/src/runtime/core/deploy-state.ts +54 -0
  54. package/src/runtime/core/manifest.ts +213 -0
  55. package/src/runtime/core/targets.ts +133 -0
  56. package/src/runtime/database.ts +256 -0
  57. package/src/runtime/db-commands.ts +167 -0
  58. package/src/runtime/deploy-readiness.ts +105 -0
  59. package/src/runtime/deploy.ts +1 -0
  60. package/src/runtime/dev-server.ts +1247 -0
  61. package/src/runtime/docs.ts +36 -0
  62. package/src/runtime/env.ts +152 -0
  63. package/src/runtime/errors.ts +13 -0
  64. package/src/runtime/evals.ts +509 -0
  65. package/src/runtime/inspect.ts +203 -0
  66. package/src/runtime/knowledge/chunk.ts +333 -0
  67. package/src/runtime/knowledge/config.ts +135 -0
  68. package/src/runtime/knowledge/embeddings.ts +133 -0
  69. package/src/runtime/knowledge/ingest.ts +521 -0
  70. package/src/runtime/knowledge/prompt-policy.ts +30 -0
  71. package/src/runtime/knowledge/retrieve.ts +283 -0
  72. package/src/runtime/knowledge/schema.ts +56 -0
  73. package/src/runtime/knowledge/tool.ts +64 -0
  74. package/src/runtime/knowledge/vector.ts +258 -0
  75. package/src/runtime/runtime-contract.ts +93 -0
  76. package/src/runtime/spec.ts +152 -0
  77. package/src/runtime/sync.ts +144 -0
  78. package/src/runtime/targets/cloudflare/build.ts +2517 -0
  79. package/src/runtime/targets/container/build.ts +146 -0
  80. package/src/runtime/targets/container/server.ts +33 -0
  81. package/src/runtime/targets/vps/deploy.ts +206 -0
  82. package/src/runtime/tool-runner.ts +65 -0
  83. package/src/runtime/tools.ts +470 -0
  84. package/src/runtime/traces.ts +41 -0
  85. package/src/storage/sqlite.ts +1118 -0
  86. package/src/templates/blank.ts +394 -0
  87. package/src/templates/dentista.ts +1003 -0
  88. package/src/templates/index.ts +33 -0
  89. package/src/templates/skills/agentkit-build-agent/SKILL.md +51 -0
  90. package/src/templates/skills/agentkit-build-agent/templates/appointment-intake.instructions.md +20 -0
  91. package/src/templates/skills/agentkit-build-agent/templates/sales-qualifier.instructions.md +17 -0
  92. package/src/templates/skills/agentkit-build-agent/templates/support-agent.instructions.md +16 -0
  93. package/src/templates/skills/agentkit-capsule/SKILL.md +62 -0
  94. package/src/templates/skills/agentkit-capsule/references/docs-router.md +15 -0
  95. package/src/templates/skills/agentkit-channels/SKILL.md +62 -0
  96. package/src/templates/skills/agentkit-channels/references/channel-buffering.md +58 -0
  97. package/src/templates/skills/agentkit-channels/references/channel-debugging.md +41 -0
  98. package/src/templates/skills/agentkit-channels/references/telegram.md +38 -0
  99. package/src/templates/skills/agentkit-channels/references/whatsapp-zapster.md +44 -0
  100. package/src/templates/skills/agentkit-database/SKILL.md +45 -0
  101. package/src/templates/skills/agentkit-database/templates/appointments.schema.sql +15 -0
  102. package/src/templates/skills/agentkit-database/templates/leads.schema.sql +17 -0
  103. package/src/templates/skills/agentkit-deploy/SKILL.md +44 -0
  104. package/src/templates/skills/agentkit-evals/SKILL.md +60 -0
  105. package/src/templates/skills/agentkit-evals/templates/multi-turn.eval.md +22 -0
  106. package/src/templates/skills/agentkit-evals/templates/no-leak.eval.md +14 -0
  107. package/src/templates/skills/agentkit-evals/templates/smoke.eval.md +14 -0
  108. package/src/templates/skills/agentkit-evals/templates/tool-call.eval.md +18 -0
  109. package/src/templates/skills/agentkit-knowledge/SKILL.md +40 -0
  110. package/src/templates/skills/agentkit-knowledge/templates/faq.md +14 -0
  111. package/src/templates/skills/agentkit-knowledge/templates/policies.md +14 -0
  112. package/src/templates/skills/agentkit-knowledge/templates/prices.csv +3 -0
  113. package/src/templates/skills/agentkit-prompts/SKILL.md +45 -0
  114. package/src/templates/skills/agentkit-prompts/templates/knowledge-grounded-faq.instructions.md +11 -0
  115. package/src/templates/skills/agentkit-provider/SKILL.md +57 -0
  116. package/src/templates/skills/agentkit-security/SKILL.md +55 -0
  117. package/src/templates/skills/agentkit-tools/SKILL.md +36 -0
  118. package/src/templates/skills/agentkit-tools/examples/database-write.tool.md +35 -0
  119. package/src/templates/skills/agentkit-tools/examples/eval-safe-external-action.tool.md +37 -0
  120. package/src/templates/skills/agentkit-tools/examples/lookup-order.tool.md +46 -0
  121. package/src/templates/skills/agentkit-troubleshooting/SKILL.md +52 -0
  122. package/src/templates/support.ts +401 -0
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # AgentKit
2
+
3
+ AgentKit is a CLI-first toolkit for creating, running, inspecting, and deploying Agent Capsules.
4
+
5
+ ## Quick Start
6
+
7
+ ```sh
8
+ npx @andreprado/agentkit@alpha new support-agent --template support
9
+ cd support-agent
10
+ npm run dev
11
+ npm run chat -- --message "hello"
12
+ ```
13
+
14
+ For a Portuguese dental-office starter, use:
15
+
16
+ ```sh
17
+ npx @andreprado/agentkit@alpha new clara-dentista --template dentista
18
+ ```
19
+
20
+ `agentkit new` installs the generated capsule dependencies by default so `agentkit.config.ts` resolves `@andreprado/agentkit` immediately in editors. Use `--no-install` only for offline or scripted scaffolds where you want to run `npm install` later.
21
+
22
+ Generated capsules use the built-in `test/fake` provider by default, so the first local run works without provider keys.
23
+
24
+ ## What To Know First
25
+
26
+ ```sh
27
+ agentkit new <name> [--template blank|support|dentista] [--no-install]
28
+ agentkit dev
29
+ agentkit chat --message <text> [--conversation-id <id>]
30
+ agentkit inspect
31
+ ```
32
+
33
+ Once the capsule is running:
34
+
35
+ ```sh
36
+ agentkit tool <name> [--input <path-or-json>]
37
+ agentkit knowledge add <path-or-url>
38
+ agentkit knowledge sync
39
+ agentkit knowledge search <query> [--top-k <number>]
40
+ agentkit spec init --brief <text>
41
+ agentkit db migrate
42
+ agentkit sync run
43
+ agentkit eval run
44
+ agentkit eval from-conversation <conversation-id>
45
+ agentkit conversations list
46
+ agentkit conversations trace <conversation-id>
47
+ ```
48
+
49
+ Knowledge indexes local `.md`, `.txt`, and `.csv` sources into the capsule database and registers the internal `agentkit_search_knowledge` chat tool when `knowledge` is configured in `agentkit.config.ts`. `agentkit dev` and `agentkit chat` sync configured sources automatically; when embeddings are configured, local semantic search uses a libSQL vector sidecar. Hosted Cloudflare deploys package configured local Knowledge sources and sync them into the project Turso database automatically during `agentkit deploy`; when embeddings are configured, the deploy also creates and populates the hosted Turso vector index.
50
+
51
+ ## Deploy Later
52
+
53
+ ```sh
54
+ agentkit login --token <token>
55
+ agentkit deploy doctor
56
+ agentkit secret set OPENAI_API_KEY --from-local-env
57
+ agentkit deploy
58
+ agentkit deploy status
59
+ agentkit chat-ui --deploy
60
+ ```
61
+
62
+ Production secrets are managed secrets, not committed `.env` values.
63
+ Private hosted deploys automatically store a local chat/UI deploy access token at `.agentkit/chat-access-token.json`. `agentkit chat-ui --deploy` serves a local UI pointed at the hosted deploy without exposing that token to browser code.
64
+
65
+ The npm package contains the public CLI/runtime/client surface only. AgentKit Cloud's control-plane server, operator commands, Postgres store, and Cloudflare/Turso/R2 publisher live in the private repo workspace and are not part of the published package.
66
+
67
+ ## Full Reference
68
+
69
+ `agentkit --help` keeps the first surface focused. Run `agentkit help commands` for the full CLI reference and `agentkit docs full` to print the path to the full agent-facing operating contract.
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawnSync } from "node:child_process";
4
+ import { createRequire } from "node:module";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
10
+ const tsxCli = require.resolve("tsx/cli");
11
+ const entry = join(packageRoot, "src/cli/index.ts");
12
+
13
+ const result = spawnSync(process.execPath, [tsxCli, entry, ...process.argv.slice(2)], {
14
+ stdio: "inherit",
15
+ env: process.env,
16
+ });
17
+
18
+ if (result.error) {
19
+ console.error(result.error.message);
20
+ process.exit(1);
21
+ }
22
+
23
+ process.exit(result.status ?? (result.signal ? 1 : 0));
@@ -0,0 +1,114 @@
1
+ # Add A Channel
2
+
3
+ ## Goal
4
+
5
+ Add a hosted messaging channel to an Agent Capsule, create the hosted channel resource, and verify that inbound messages become AgentKit channel deliveries without exposing secrets.
6
+
7
+ ## When To Use It
8
+
9
+ Use this when the agent should receive messages from website chat, Telegram, or WhatsApp through AgentKit-owned webhook infrastructure.
10
+
11
+ ## Commands
12
+
13
+ ```sh
14
+ agentkit inspect
15
+ agentkit deploy
16
+ agentkit channels list
17
+ agentkit channels add website website-chat
18
+ agentkit channels add telegram support-telegram
19
+ agentkit channels add whatsapp support-whatsapp --provider zapster
20
+ agentkit channels setup support-telegram
21
+ agentkit channels status support-telegram
22
+ agentkit channels test support-telegram --message "hello"
23
+ agentkit channels deliveries list support-telegram
24
+ ```
25
+
26
+ Use `--api <url>` with hosted commands when testing against a non-default AgentKit Cloud API.
27
+
28
+ ## Files Created Or Edited
29
+
30
+ - `agentkit.config.ts`: declare channel config with `websiteChannel`, `telegramChannel`, or `whatsappChannel`.
31
+ - `.agentkit/deploy.json`: written by `agentkit deploy`; used by `agentkit channels ...`.
32
+ - No user Turso tables: AgentKit channel resources, dedupe, identities, queue state, and delivery logs are control-plane owned.
33
+ - Website channel clients must send `AGENTKIT_WEBSITE_CHANNEL_TOKEN` as `Authorization: Bearer <token>` or `X-AgentKit-Channel-Token`.
34
+
35
+ ## Minimal Working Example
36
+
37
+ ```ts
38
+ import { defineAgent, telegramChannel, whatsappChannel, websiteChannel } from "@andreprado/agentkit";
39
+
40
+ export default defineAgent({
41
+ name: "support-agent",
42
+ runtime: "edge",
43
+ provider: { name: "test", model: "fake" },
44
+ instructions: "./prompts/instructions.md",
45
+ secrets: [],
46
+ tools: [],
47
+ channels: [
48
+ websiteChannel({ name: "website-chat" }),
49
+ telegramChannel({ name: "support-telegram" }),
50
+ whatsappChannel({ name: "support-whatsapp", provider: "zapster" }),
51
+ ],
52
+ access: { mode: "public" },
53
+ storage: { driver: "agentkit" },
54
+ });
55
+ ```
56
+
57
+ ## Buffer Bursty Messages
58
+
59
+ Use `buffer` when clients send several short messages in a row and the agent should answer once.
60
+
61
+ ```ts
62
+ whatsappChannel({
63
+ name: "support-whatsapp",
64
+ provider: "zapster",
65
+ buffer: {
66
+ mode: "debounce",
67
+ quietWindowMs: 2500,
68
+ maxWaitMs: 12000,
69
+ maxMessages: 20,
70
+ maxChars: 8000,
71
+ },
72
+ })
73
+ ```
74
+
75
+ Buffering is scoped to one channel conversation. AgentKit still validates and dedupes each provider webhook, then stores the messages in a short-lived channel buffer. When the quiet window expires, AgentKit creates one agent run with the buffered messages and sends one outbound reply.
76
+
77
+ Use `buffer: { mode: "off" }` or omit `buffer` to process each inbound message as its own agent run.
78
+
79
+ ## Safety Rules
80
+
81
+ - Never put provider token values in `agentkit.config.ts`.
82
+ - Keep local values in ignored `.env`; hosted production uses managed secrets with no readback.
83
+ - Treat channel webhook URLs as public transport endpoints. Provider validation or the AgentKit website channel token controls authenticity.
84
+ - Keep channels separate from tools. Channels deliver user messages; tools let the agent call external systems.
85
+ - Keep `maxMessages` and `maxChars` bounded so one burst cannot create an oversized prompt or unexpected model spend.
86
+
87
+ ## Verification
88
+
89
+ ```sh
90
+ npm run typecheck
91
+ bun test
92
+ agentkit inspect
93
+ agentkit channels list
94
+ agentkit channels test support-telegram --message "hello"
95
+ agentkit channels deliveries list support-telegram
96
+ ```
97
+
98
+ Expected hosted status includes `NAME`, `TYPE`, `PROVIDER`, `STATUS`, and `LAST_EVENT`. Secret output is name plus `set` or `missing`, never the value.
99
+
100
+ ## Troubleshooting
101
+
102
+ `No .agentkit/deploy.json found`:
103
+ Run `agentkit deploy` before creating hosted channel resources.
104
+
105
+ `channel_secret_missing`:
106
+ Set the named hosted secret. Do not add production values to `.env`.
107
+
108
+ `channel_signature_invalid`:
109
+ The provider webhook secret, token, or origin header does not match the managed secret.
110
+
111
+ `channel_limit_exceeded`:
112
+ The channel daily message limit was reached. Website requests return `429`; Telegram and WhatsApp are acknowledged and skipped to avoid provider retry storms.
113
+
114
+ Buffered messages stay in `buffered` delivery state until the quiet window or max wait flushes them into one queued run.
@@ -0,0 +1,134 @@
1
+ # Add Knowledge
2
+
3
+ Knowledge is AgentKit's native retrieval layer for facts the agent should not invent: policies, prices, service details, FAQs, CSV tables, procedures, and internal reference docs.
4
+
5
+ Use Knowledge when the answer should come from source files instead of the base prompt. Do not use Knowledge for secrets, credentials, or data that should only be fetched live through a tool.
6
+
7
+ ## Configure
8
+
9
+ Create a `knowledge/` directory in the Agent Capsule and list the sources in `agentkit.config.ts`:
10
+
11
+ ```ts
12
+ export default defineAgent({
13
+ // ...
14
+ knowledge: {
15
+ sources: [
16
+ "knowledge/faq.md",
17
+ { path: "knowledge/prices.csv", title: "Prices" },
18
+ ],
19
+ retrieval: {
20
+ topK: 8,
21
+ hybrid: false,
22
+ },
23
+ },
24
+ });
25
+ ```
26
+
27
+ Local Knowledge supports `.md`, `.markdown`, `.txt`, and `.csv` files. Markdown is chunked by headings, text is chunked by paragraphs, and CSV rows preserve column headers.
28
+
29
+ The default embedding provider is `none`, which gives local lexical search without an API key. To add embeddings, configure them separately from the chat provider:
30
+
31
+ ```ts
32
+ knowledge: {
33
+ sources: ["knowledge/faq.md"],
34
+ embedding: {
35
+ provider: "openai",
36
+ model: "text-embedding-3-small",
37
+ secret: "KNOWLEDGE_OPENAI_API_KEY",
38
+ },
39
+ retrieval: {
40
+ topK: 8,
41
+ hybrid: true,
42
+ },
43
+ },
44
+ ```
45
+
46
+ Then set the local secret without committing it:
47
+
48
+ ```sh
49
+ printf %s "$KNOWLEDGE_OPENAI_API_KEY" | agentkit env set KNOWLEDGE_OPENAI_API_KEY --stdin
50
+ ```
51
+
52
+ ## Index Locally
53
+
54
+ Index one source:
55
+
56
+ ```sh
57
+ agentkit knowledge add knowledge/faq.md
58
+ ```
59
+
60
+ Sync all configured sources:
61
+
62
+ ```sh
63
+ agentkit knowledge sync
64
+ ```
65
+
66
+ Inspect indexed sources:
67
+
68
+ ```sh
69
+ agentkit knowledge inspect
70
+ ```
71
+
72
+ Search locally:
73
+
74
+ ```sh
75
+ agentkit knowledge search "refund policy" --top-k 3
76
+ ```
77
+
78
+ `knowledge add` is useful for one-off local indexing. `knowledge sync` validates and indexes all configured `knowledge.sources` on demand. `agentkit dev` and `agentkit chat` also sync configured Knowledge automatically before local runs, and unchanged files are skipped by content hash.
79
+
80
+ When embeddings are configured locally, AgentKit stores canonical Knowledge chunks in `.agentkit/agentkit.db` and rebuilds a local libSQL vector sidecar at `.agentkit/agentkit.vectors.db`. Local semantic search uses the sidecar's native `libsql_vector_idx` path and falls back to stored JSON embeddings if the native vector path is unavailable.
81
+
82
+ ## Agent Behavior
83
+
84
+ When `knowledge` is configured, AgentKit automatically registers the internal tool `agentkit_search_knowledge` during chat runs and appends a prompt policy. The policy tells the agent to search before answering business-specific factual questions and not to expose raw retrieval JSON, scores, or chunk IDs.
85
+
86
+ With the deterministic `test/fake` provider, verify the internal tool directly:
87
+
88
+ ```sh
89
+ agentkit chat --message '{"tool":"agentkit_search_knowledge","input":{"query":"refund policy","topK":1}}'
90
+ ```
91
+
92
+ Expected output:
93
+
94
+ ```txt
95
+ Tool agentkit_search_knowledge: completed
96
+ ```
97
+
98
+ The retrieved chunks are persisted as internal tool output in local SQLite for evals and inspection, but they are not shown directly to the user.
99
+
100
+ ## Hosted Deploy
101
+
102
+ Cloudflare Knowledge deploys require AgentKit-managed Turso storage:
103
+
104
+ ```ts
105
+ storage: {
106
+ driver: "agentkit",
107
+ database: {
108
+ driver: "turso",
109
+ schema: "./schema.sql",
110
+ },
111
+ },
112
+ ```
113
+
114
+ `agentkit deploy doctor` and `agentkit build --target cloudflare` fail with an actionable error when Knowledge is configured without Turso. The Cloudflare artifact includes the Knowledge manifest, required embedding secret names, internal Knowledge schema, local source file contents, prompt policy, and hosted `agentkit_search_knowledge` runtime.
115
+
116
+ During `agentkit deploy`, AgentKit Cloud provisions or resolves the project Turso database, applies the Knowledge schema, chunks every packaged local source, creates embeddings when an embedding provider is configured, and writes sources, chunks, embedding metadata, FTS rows, and a native Turso `libsql_vector_idx` index into Turso before publishing the Worker. Removed configured sources are deleted from the hosted Knowledge tables during sync.
117
+
118
+ Local `agentkit knowledge add`, `agentkit knowledge sync`, `agentkit dev`, and `agentkit chat` index configured Knowledge into the local SQLite database and local libSQL vector sidecar. Hosted deploy syncs configured local Knowledge sources automatically from the deploy artifact so embedding secrets stay server-side and private source material does not move into client code. Hosted semantic search uses Turso native vector search when embeddings are configured and falls back to stored JSON embeddings if the native vector path is unavailable.
119
+
120
+ ## Safety Rules
121
+
122
+ - Do not put API keys, passwords, private tokens, `.env` contents, or credential exports in Knowledge files.
123
+ - Treat committed Knowledge files as repository content. Use a private repo for private business docs.
124
+ - Use tools for live customer records, payments, orders, or anything requiring authorization checks.
125
+ - Use explicit `title` fields for CSVs or ambiguous files so search results have useful citations.
126
+ - Use `agentkit knowledge sync` to validate source changes explicitly; local `agentkit dev` and `agentkit chat` also sync configured sources automatically.
127
+
128
+ ## Troubleshooting
129
+
130
+ - `No knowledge.sources are configured`: add `knowledge.sources` to `agentkit.config.ts` or use `agentkit knowledge add <path>`.
131
+ - `Knowledge source paths must stay inside the Agent Capsule`: move the source under the capsule root, usually `knowledge/`.
132
+ - `Local Knowledge currently supports .md, .txt, and .csv files`: convert the source or add a tool for unsupported formats.
133
+ - `Knowledge embeddings require missing secret`: set the env var named by `knowledge.embedding.secret`.
134
+ - Hosted build says Turso is required: add `storage.database.driver: "turso"` before deploying Knowledge.
@@ -0,0 +1,342 @@
1
+ # Add A Tool
2
+
3
+ ## Goal
4
+
5
+ Add a TypeScript tool to an Agent Capsule, register it in `agentkit.config.ts`, validate its input and output, and verify that calls are stored without leaking secrets.
6
+
7
+ ## When To Use This
8
+
9
+ Use this when the agent needs to call code, read an API, query a database, or perform a small action behind a typed contract.
10
+
11
+ ## Commands
12
+
13
+ From a capsule root:
14
+
15
+ ```sh
16
+ mkdir -p tools
17
+ $EDITOR tools/lookup-order.ts
18
+ $EDITOR agentkit.config.ts
19
+ npm run typecheck
20
+ npm run agentkit -- tool lookup_order --input '{"orderId":"A100"}'
21
+ npm run agentkit -- conversations list
22
+ ```
23
+
24
+ ## Files Created Or Edited
25
+
26
+ Create:
27
+
28
+ ```txt
29
+ tools/lookup-order.ts
30
+ ```
31
+
32
+ Edit:
33
+
34
+ ```txt
35
+ agentkit.config.ts
36
+ .env.schema
37
+ .env
38
+ ```
39
+
40
+ Edit `.env.schema` only for secret names. Put secret values in ignored `.env`.
41
+ Run local AgentKit commands normally; tools, evals, chat, and inspect load `.env` through the same AgentKit loader.
42
+
43
+ ## Minimal Working Example
44
+
45
+ `tools/lookup-order.ts`:
46
+
47
+ ```ts
48
+ import { defineTool } from "@andreprado/agentkit";
49
+
50
+ const orders: Record<string, { status: string; eta: string }> = {
51
+ A100: { status: "preparing", eta: "today" },
52
+ B200: { status: "shipped", eta: "tomorrow" },
53
+ };
54
+
55
+ export const lookupOrder = defineTool({
56
+ name: "lookup_order",
57
+ description: "Looks up a demo support order by order id.",
58
+ inputSchema: {
59
+ type: "object",
60
+ properties: {
61
+ orderId: { type: "string" },
62
+ },
63
+ required: ["orderId"],
64
+ additionalProperties: false,
65
+ },
66
+ outputSchema: {
67
+ type: "object",
68
+ properties: {
69
+ orderId: { type: "string" },
70
+ found: { type: "boolean" },
71
+ status: { type: "string" },
72
+ eta: { type: "string" },
73
+ },
74
+ required: ["orderId", "found", "status", "eta"],
75
+ },
76
+ execute(input: { orderId: string }) {
77
+ const order = orders[input.orderId];
78
+
79
+ if (!order) {
80
+ return {
81
+ orderId: input.orderId,
82
+ found: false,
83
+ status: "unknown",
84
+ eta: "unknown",
85
+ };
86
+ }
87
+
88
+ return {
89
+ orderId: input.orderId,
90
+ found: true,
91
+ status: order.status,
92
+ eta: order.eta,
93
+ };
94
+ },
95
+ });
96
+ ```
97
+
98
+ Register it:
99
+
100
+ ```ts
101
+ import { defineAgent } from "@andreprado/agentkit";
102
+ import { lookupOrder } from "./tools/lookup-order";
103
+
104
+ export default defineAgent({
105
+ tools: [lookupOrder],
106
+ });
107
+ ```
108
+
109
+ Direct tool test:
110
+
111
+ ```sh
112
+ npm run agentkit -- tool lookup_order --input '{"orderId":"A100"}'
113
+ ```
114
+
115
+ Expected output:
116
+
117
+ ```json
118
+ {
119
+ "orderId": "A100",
120
+ "found": true,
121
+ "status": "preparing",
122
+ "eta": "today"
123
+ }
124
+ ```
125
+
126
+ ## Database Tool Pattern
127
+
128
+ Use this when a tool needs agent-owned tables and must work locally and after deploy through the same AgentKit database helper.
129
+
130
+ Recommended contract:
131
+
132
+ - Put all agent-owned tables in `schema.sql`.
133
+ - Keep deploy-ready capsules on `storage.driver: "agentkit"`.
134
+ - Local `agentkit chat`, `agentkit tool`, `agentkit dev`, and eval runs apply `schema.sql` to local development storage.
135
+ - Use `agentkit db migrate`, `agentkit db reset --yes`, `agentkit db seed [--file seed.sql]`, and `agentkit db shell` for local database setup and inspection.
136
+ - Hosted deploy migrates/provisions the managed database internally and applies the same `schema.sql`.
137
+ - Tools use `ctx.db` as the canonical helper. `ctx.database` and `ctx.storage.sql` are supported aliases.
138
+ - Use `ctx.db.batch([...])` for atomic writes. Local tools can also use `ctx.db.transaction(async (tx) => ...)`.
139
+ - Do not import local database drivers or Node-only APIs from a tool. Use runtime services such as `ctx.db`.
140
+
141
+ `agentkit.config.ts`:
142
+
143
+ ```ts
144
+ import { defineAgent } from "@andreprado/agentkit";
145
+ import { scheduleAppointment } from "./tools/schedule-appointment";
146
+
147
+ export default defineAgent({
148
+ name: "appointments",
149
+ runtime: "edge",
150
+ provider: {
151
+ name: "test",
152
+ model: "fake",
153
+ },
154
+ instructions: "./prompts/instructions.md",
155
+ secrets: [],
156
+ tools: [scheduleAppointment],
157
+ access: {
158
+ mode: "private",
159
+ },
160
+ storage: {
161
+ driver: "agentkit",
162
+ },
163
+ });
164
+ ```
165
+
166
+ `schema.sql`:
167
+
168
+ ```sql
169
+ CREATE TABLE IF NOT EXISTS appointments (
170
+ id TEXT PRIMARY KEY,
171
+ client_name TEXT NOT NULL,
172
+ starts_at TEXT NOT NULL,
173
+ notes TEXT,
174
+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
175
+ UNIQUE (starts_at)
176
+ );
177
+ ```
178
+
179
+ `schema.sql` is an idempotent bootstrap file in v1. Prefer `CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, and safe additive `ALTER TABLE` statements. AgentKit does not run destructive schema changes or ordered `migrations/*.sql` automatically yet.
180
+
181
+ `tools/schedule-appointment.ts`:
182
+
183
+ ```ts
184
+ import { defineTool } from "@andreprado/agentkit";
185
+
186
+ export const scheduleAppointment = defineTool({
187
+ name: "schedule_appointment",
188
+ description: "Schedules an appointment in the agent database.",
189
+ inputSchema: {
190
+ type: "object",
191
+ properties: {
192
+ clientName: { type: "string" },
193
+ startsAt: { type: "string" },
194
+ notes: { type: "string" },
195
+ },
196
+ required: ["clientName", "startsAt"],
197
+ additionalProperties: false,
198
+ },
199
+ outputSchema: {
200
+ type: "object",
201
+ properties: {
202
+ id: { type: "string" },
203
+ clientName: { type: "string" },
204
+ startsAt: { type: "string" },
205
+ },
206
+ required: ["id", "clientName", "startsAt"],
207
+ additionalProperties: false,
208
+ },
209
+ async execute(input: { clientName: string; startsAt: string; notes?: string }, ctx) {
210
+ const id = crypto.randomUUID();
211
+
212
+ await ctx.db.execute(
213
+ "INSERT INTO appointments (id, client_name, starts_at, notes) VALUES (?, ?, ?, ?)",
214
+ [id, input.clientName, input.startsAt, input.notes ?? null],
215
+ );
216
+
217
+ const result = await ctx.db.query("SELECT id, client_name, starts_at FROM appointments WHERE id = ?", [id]);
218
+ const appointment = result.rows[0];
219
+
220
+ return {
221
+ id: String(appointment.id),
222
+ clientName: String(appointment.client_name),
223
+ startsAt: String(appointment.starts_at),
224
+ };
225
+ },
226
+ });
227
+ ```
228
+
229
+ Local test:
230
+
231
+ ```sh
232
+ npm run agentkit -- tool schedule_appointment --input '{"clientName":"Ada Lovelace","startsAt":"2026-06-01T10:00:00Z"}'
233
+ npm run agentkit -- db shell
234
+ ```
235
+
236
+ Build/deploy:
237
+
238
+ ```sh
239
+ npm run agentkit -- inspect
240
+ npm run agentkit -- build
241
+ npm run agentkit -- deploy
242
+ ```
243
+
244
+ `inspect` shows the local runtime state and declared secret names. The user does not create hosted databases or buckets manually; AgentKit handles deploy infrastructure internally.
245
+
246
+ `ctx.runtime` tells a tool where it is running:
247
+
248
+ ```ts
249
+ ctx.runtime // { environment, invocation, target, database }
250
+ ```
251
+
252
+ Use it for diagnostics only, not for bypassing AgentKit runtime services or choosing deploy infrastructure.
253
+
254
+ ## Safety Rules
255
+
256
+ - Use `inputSchema` for every tool.
257
+ - Use `outputSchema` when downstream behavior depends on shape.
258
+ - Set `additionalProperties: false` for strict object inputs.
259
+ - Use JSON Schema unions such as `type: ["string", "null"]` when `null` is meaningful.
260
+ - Optional object properties sent as `null` are treated as omitted unless the property schema allows `null`.
261
+ - List tool secrets in the tool `secrets` field.
262
+ - Do not read arbitrary `process.env` inside tools.
263
+ - Use `ctx.secrets.SECRET_NAME`.
264
+ - Set `timeoutMs` for slow external calls.
265
+ - Set `visibility: "internal"` for operational outputs such as classifications, scores, routing labels, fraud decisions, or other fields the agent should persist but not reveal literally to the user.
266
+ - Do not log secret values.
267
+
268
+ Internal output example:
269
+
270
+ ```ts
271
+ export const triageLead = defineTool({
272
+ name: "triage_real_estate_lead",
273
+ description: "Classifies an incoming lead for routing.",
274
+ visibility: "internal",
275
+ inputSchema: {
276
+ type: "object",
277
+ properties: {
278
+ email: { type: "string" },
279
+ },
280
+ required: ["email"],
281
+ },
282
+ outputSchema: {
283
+ type: "object",
284
+ properties: {
285
+ status: { type: "string" },
286
+ score: { type: "integer" },
287
+ },
288
+ required: ["status", "score"],
289
+ },
290
+ execute() {
291
+ return { status: "hot", score: 92 };
292
+ },
293
+ });
294
+ ```
295
+
296
+ ## Verification
297
+
298
+ ```sh
299
+ npm run typecheck
300
+ npm run agentkit -- tool lookup_order --input '{"orderId":"A100"}'
301
+ npm run agentkit -- conversations list
302
+ ```
303
+
304
+ Optional SQLite check:
305
+
306
+ ```sh
307
+ sqlite3 .agentkit/agentkit.db 'select tool_name,visibility,status,input_json,output_json from tool_calls;'
308
+ ```
309
+
310
+ Expected:
311
+
312
+ - TypeScript passes.
313
+ - The tool command prints the JSON output.
314
+ - `tool_calls` has one completed row.
315
+ - Secret values do not appear in `.agentkit/agentkit.db`.
316
+
317
+ ## Troubleshooting
318
+
319
+ `tool_not_found`:
320
+
321
+ Import the tool and add it to `tools: [...]` in `agentkit.config.ts`.
322
+
323
+ `tool_validation_error`:
324
+
325
+ Compare the JSON message input to `inputSchema`.
326
+
327
+ `tool_secret_missing`:
328
+
329
+ Add the secret name to `.env.schema`, write the local value to ignored `.env`, and inspect again:
330
+
331
+ ```sh
332
+ printf %s "$CRM_API_KEY" | npm run agentkit -- env set CRM_API_KEY --stdin
333
+ npm run agentkit -- inspect
334
+ ```
335
+
336
+ Tool hangs:
337
+
338
+ Set `timeoutMs`, pass `ctx.signal` to external fetch calls, and retry.
339
+
340
+ ## Backend Contracts Used
341
+
342
+ Local tool calls are stored in SQLite `tool_calls`. Hosted tools later run under the managed Tool Gateway contract with scoped secrets, permission checks, timeouts, and redacted logs.