From ae44038d07026d1dd07e054784088be98a084634 Mon Sep 17 00:00:00 2001 From: Hugo Dutka Date: Mon, 20 Oct 2025 15:21:19 +0200 Subject: [PATCH 1/2] feat: better example env vars in init templates --- .../blink/src/cli/init-templates/index.ts | 14 +++--- .../scratch/_noignore.env.local | 4 -- .../scratch/_noignore.env.local.hbs | 10 ++++ .../scratch/_noignore.env.production | 4 +- .../slack-bot/_noignore.env.local | 5 -- .../slack-bot/_noignore.env.local.hbs | 12 +++++ .../slack-bot/_noignore.env.production | 6 ++- packages/blink/src/cli/init.ts | 46 +++++++++++-------- 8 files changed, 65 insertions(+), 36 deletions(-) delete mode 100644 packages/blink/src/cli/init-templates/scratch/_noignore.env.local create mode 100644 packages/blink/src/cli/init-templates/scratch/_noignore.env.local.hbs delete mode 100644 packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local create mode 100644 packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local.hbs diff --git a/packages/blink/src/cli/init-templates/index.ts b/packages/blink/src/cli/init-templates/index.ts index cf0f88f..62d744a 100644 --- a/packages/blink/src/cli/init-templates/index.ts +++ b/packages/blink/src/cli/init-templates/index.ts @@ -3,14 +3,14 @@ export const templates = { scratch: { - ".env.local": - "\n# Store local environment variables here.\n# They will be used by blink dev for development.\n# EXTERNAL_SERVICE_API_KEY=\n", + ".env.local.hbs": + '# Store local environment variables here.\n# They will be used by blink dev for development.\n{{#each envLocal}}\n{{this.[0]}}={{this.[1]}}\n{{/each}}\n{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}\n# OPENAI_API_KEY=\n# ANTHROPIC_API_KEY=\n# AI_GATEWAY_API_KEY=\n{{/unless}}', ".env.production": - "# Store production environment variables here.\n# They will be upserted as secrets on blink deploy.\n# EXTERNAL_SERVICE_API_KEY=\n", + "# Store production environment variables here.\n# They will be upserted as secrets on blink deploy.\n# OPENAI_API_KEY=\n# ANTHROPIC_API_KEY=\n# AI_GATEWAY_API_KEY=\n", ".gitignore": "# dependencies\nnode_modules\n\n# config and build\n.blink\n\n# dotenv environment variables file\n.env\n.env.*\n\n# Finder (MacOS) folder config\n.DS_Store\n", "AGENTS.md": - 'This project is a Blink agent.\n\nYou are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.\n\n\n1. Be concise, direct, and to the point.\n2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.\n3. NEVER use emojis unless the user explicitly asks for them.\n4. You must avoid text before/after your response, such as "The answer is" or "Short answer:", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".\n5. Mimic the style of the user\'s messages.\n6. Do not remind the user you are happy to help.\n7. Do not act with sycophantic flattery or over-the-top enthusiasm.\n8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").\n9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.\n10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user\'s goals.\n\n\n\nYour method of assisting the user is by iterating their agent using the context provided by the user in run mode.\n\nYou can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.\n\nThe user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.\n\n\nuser: i want a coding agent\nassistant: Let me take a look at your codebase...\n... tool calls to investigate the codebase...\nassistant: I\'ve created tools for linting, testing, and formatting. Hop back in run mode to use your agent! If you ever encounter undesired behavior from your agent, switch back to edit mode to refine your agent.\n\n\nAlways investigate the current state of the agent before assisting the user.\n\n\n\nAgents are written in TypeScript, and mostly stored in a single `agent.ts` file. Complex agents will have multiple files, like a proper codebase.\n\nEnvironment variables are stored in `.env.local` and `.env.production`. `blink dev` will hot-reload environment variable changes in `.env.local`.\n\nChanges to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.\n\n1. _ALWAYS_ use the package manager the user is using (inferred from lock files or `process.argv`).\n2. You _MUST_ use `agent.store` to persist state. The agent process is designed to be stateless.\n3. Test your changes to the user\'s agent by using the `message_user_agent` tool. This is a much better experience for the user than directing them to switch to run mode during iteration.\n4. Use console.log for debugging. The console output appears for the user.\n5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses `inputSchema` instead of `parameters` (which was in v4).\n6. Output tokens can be increased using the `maxOutputTokens` option on `streamText` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.\n7. Use the TypeScript language service tools (`typescript_completions`, `typescript_quickinfo`, `typescript_definition`, `typescript_diagnostics`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.\n\nIf the user is asking for a behavioral change, you should update the agent\'s system prompt.\nThis will not ensure the behavior, but it will guide the agent towards the desired behavior.\nIf the user needs 100% behavioral certainty, adjust tool behavior instead.\n\n\n\nAgents are HTTP servers, so they can handle web requests. This is commonly used to async-invoke an agent. e.g. for a Slack bot, messages are sent to the agent via a webhook.\n\nBlink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).\n\nTo trigger chats based on web requests, use the `agent.chat.upsert` and `agent.chat.message` APIs.\n\n\n\nBlink agents are Node.js HTTP servers built on the Vercel AI SDK:\n\n```typescript\nimport { convertToModelMessages, streamText } from "ai";\nimport * as blink from "blink";\n\nconst agent = new blink.Agent();\n\nagent.on("chat", async ({ messages, chat, abortSignal }) => {\n return streamText({\n model: "anthropic/claude-sonnet-4.5",\n system: "You are a helpful assistant.",\n messages: convertToModelMessages(messages, {\n ignoreIncompleteToolCalls: true,\n }),\n tools: {\n /* your tools */\n },\n });\n});\n\nagent.on("request", async (request) => {\n // Handle webhooks, OAuth callbacks, etc.\n});\n\nagent.serve();\n```\n\nEvent Handlers:\n\n**`agent.on("chat", handler)`**\n\n1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.\n2. Must return: `streamText()` result, `Response`, `ReadableStream`, or `void`\n3. Parameters: `messages`, `id`, `abortSignal`\n\n_NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.\n\n**`agent.on("request", handler)`**\n• Handles raw HTTP requests before Blink processes them\n• Use for: OAuth callbacks, webhook verification, custom endpoints\n• Return `Response` to handle, or `void` to pass through\n\n**`agent.on("ui", handler)`**\n• Provides dynamic UI options for chat interfaces\n• Returns schema defining user-selectable options\n\n**`agent.on("error", handler)`**\n• Global error handler for the agent\n\nChat Management:\n\nBlink automatically manages chat state:\n\n```typescript\n// Create or get existing chat\n// The parameter can be any JSON-serializable value.\n// e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]\nconst chat = await agent.chat.upsert("unique-key");\n\n// Send a message to a chat\nawait agent.chat.sendMessages(\n chat.id,\n [\n {\n role: "user",\n parts: [{ type: "text", text: "Message" }],\n },\n ],\n {\n behavior: "interrupt" | "enqueue" | "append",\n }\n);\n\n// When sending messages, feel free to inject additional parts to direct the model.\n// e.g. if the user is asking for specific behavior in specific scenarios, the simplest\n// answer is to append a text part: "always do X when Y".\n```\n\nBehaviors:\n• "interrupt": Stop current processing and handle immediately\n• "enqueue": Queue message, process when current chat finishes\n• "append": Add to history without triggering processing\n\nChat keys: Use structured keys like `"slack-${teamId}-${channelId}-${threadTs}"` for uniqueness.\n\nStorage API:\n\nPersistent key-value storage per agent:\n\n```typescript\n// Store data\nawait agent.store.set("key", "value", { ttl: 3600 });\n\n// Retrieve data\nconst value = await agent.store.get("key");\n\n// Delete data\nawait agent.store.delete("key");\n\n// List keys by prefix\nconst result = await agent.store.list("prefix-", { limit: 100 });\n```\n\nCommon uses: OAuth tokens, user preferences, caching, chat-resource associations.\n\nTools:\n\nTools follow Vercel AI SDK patterns with Zod validation:\n\n```typescript\nimport { tool } from "ai";\nimport { z } from "zod";\n\nconst myTool = tool({\n description: "Clear description of what this tool does",\n inputSchema: z.object({\n param: z.string().describe("Parameter description"),\n }),\n execute: async (args, opts) => {\n // opts.abortSignal for cancellation\n // opts.toolCallId for unique identification\n return result;\n },\n});\n```\n\nTool Approvals for destructive operations:\n\n```typescript\n...await blink.tools.withApproval({\n messages,\n tools: {\n delete_database: tool({ /* ... */ }),\n },\n})\n```\n\nTool Context for dependency injection:\n\n```typescript\n...blink.tools.withContext(github.tools, {\n accessToken: process.env.GITHUB_TOKEN,\n})\n```\n\nTool Prefixing to avoid collisions:\n\n```typescript\n...blink.tools.prefix(github.tools, "github_")\n```\n\nLLM Models:\n\n```typescript\nimport { anthropic } from "@ai-sdk/anthropic";\nimport { openai } from "@ai-sdk/openai";\n\nmodel: anthropic("claude-sonnet-4.5", {\n apiKey: process.env.ANTHROPIC_API_KEY,\n});\nmodel: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });\n```\n\n**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:\n\n1. If `ANTHROPIC_API_KEY` is set: uses `claude-sonnet-4.5` via `@ai-sdk/anthropic`\n2. If `OPENAI_API_KEY` is set: uses `gpt-5` via `@ai-sdk/openai`\n\nAvailable SDKs:\n\n**@blink-sdk/compute**\n\n```typescript\nimport * as compute from "@blink-sdk/compute";\n\ntools: {\n ...compute.tools, // execute_bash, read_file, write_file, edit_file, process management\n}\n```\n\n**@blink-sdk/github**\n\n```typescript\nimport * as github from "@blink-sdk/github";\n\ntools: {\n ...blink.tools.withContext(github.tools, {\n accessToken: process.env.GITHUB_TOKEN,\n }),\n}\n```\n\n**@blink-sdk/slack**\n\n```typescript\nimport * as slack from "@blink-sdk/slack";\nimport { App } from "@slack/bolt";\n\nconst receiver = new slack.Receiver();\nconst app = new App({\n token: process.env.SLACK_BOT_TOKEN,\n signingSecret: process.env.SLACK_SIGNING_SECRET,\n receiver,\n});\n\n// This will trigger when the bot is @mentioned.\napp.event("app_mention", async ({ event }) => {\n // The argument here is a JSON-serializable value.\n // To maintain the same chat context, use the same key.\n const chat = await agent.chat.upsert([\n "slack",\n event.channel,\n event.thread_ts ?? event.ts,\n ]);\n const { message } = await slack.createMessageFromEvent({\n client: app.client,\n event,\n });\n await agent.chat.sendMessages(chat.id, [message]);\n // This is a nice immediate indicator for the user.\n await app.client.assistant.threads.setStatus({\n channel_id: event.channel,\n status: "is typing...",\n thread_ts: event.thread_ts ?? event.ts,\n });\n});\n\nconst agent = new blink.Agent();\n\nagent.on("request", async (request) => {\n return receiver.handle(app, request);\n});\n\nagent.on("chat", async ({ messages }) => {\n const tools = slack.createTools({ client: app.client });\n return streamText({\n model: "anthropic/claude-sonnet-4.5",\n system: "You chatting with users in Slack.",\n messages: convertToModelMessages(messages, {\n ignoreIncompleteToolCalls: true,\n tools,\n }),\n });\n});\n```\n\nSlack SDK Notes:\n\n- "app_mention" event is triggered in both private channels and public channels.\n- "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.\n- _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.\n- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.\n- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. `message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=${channel} thread_ts=${thread_ts}" })`\n- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".\n\nSlack App Manifest:\n\n- _ALWAYS_ include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You _MUST_ provide "assistant_view" if you provide this scope.\n- The user can always edit the manifest after creation, but you\'d have to suggest it to them.\n- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.\n- _ALWAYS_ default `token_rotation_enabled` to false unless the user explicitly asks for it. It is a _much_ simpler user-experience to not rotate tokens.\n- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):\n - "app_mentions:read"\n - "reactions:write"\n - "reactions:read"\n - "channels:history"\n - "chat:write"\n - "groups:history"\n - "groups:read"\n - "files:read"\n - "im:history"\n - "im:read"\n - "im:write"\n - "mpim:history"\n - "mpim:read"\n - "users:read"\n - "links:read"\n - "commands"\n- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):\n - "app_mention"\n - "message.channels",\n - "message.groups",\n - "message.im",\n - "reaction_added"\n - "reaction_removed"\n - "assistant_thread_started"\n - "member_joined_channel"\n- _NEVER_ include USER SCOPES unless the user explicitly asks for them.\n\nWARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.\n\nState Management:\n\nBlink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.\n\n_NEVER_ use module-level Maps, Sets, or variables to store state (e.g. `const activeBots = new Map()`).\n\nFor global state persistence, you can use the agent store:\n\n- Use `agent.store` for persistent key-value storage\n- Query external APIs to fetch current state\n- Use webhooks to trigger actions rather than polling in-memory state\n\nFor message-level state persistence, use message metadata:\n\n```typescript\nimport { UIMessage } from "blink";\nimport * as blink from "blink";\n\nconst agent = new blink.Agent<\n UIMessage<{\n source: "github";\n associated_id: string;\n }>\n>();\n\nagent.on("request", async (request) => {\n // comes from github, we want to do something deterministic in the chat loop with that ID...\n // insert a message with that metadata into the chat\n const chat = await agent.chat.upsert("some-github-key");\n await agent.chat.sendMessages(request.chat.id, [\n {\n role: "user",\n parts: [\n {\n type: "text",\n text: "example",\n },\n ],\n metadata: {\n source: "github",\n associated_id: "some-github-id",\n },\n },\n ]);\n});\n\nagent.on("chat", async ({ messages }) => {\n const message = messages.find(\n (message) => message.metadata?.source === "github"\n );\n\n // Now we can use that metadata...\n});\n```\n\nThe agent process can restart at any time, so all important state must be externalized.\n\n\n\n\n- Never use "as any" type assertions. Always figure out the correct typings.\n \n', + 'This project is a Blink agent.\n\nYou are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.\n\n\n1. Be concise, direct, and to the point.\n2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.\n3. NEVER use emojis unless the user explicitly asks for them.\n4. You must avoid text before/after your response, such as "The answer is" or "Short answer:", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".\n5. Mimic the style of the user\'s messages.\n6. Do not remind the user you are happy to help.\n7. Do not act with sycophantic flattery or over-the-top enthusiasm.\n8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").\n9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.\n10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user\'s goals.\n\n\n\nYour method of assisting the user is by iterating their agent using the context provided by the user in run mode.\n\nYou can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.\n\nThe user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.\n\n\nuser: i want a coding agent\nassistant: Let me take a look at your codebase...\n... tool calls to investigate the codebase...\nassistant: I\'ve created tools for linting, testing, and formatting. Hop back in run mode to use your agent! If you ever encounter undesired behavior from your agent, switch back to edit mode to refine your agent.\n\n\nAlways investigate the current state of the agent before assisting the user.\n\n\n\nAgents are written in TypeScript, and mostly stored in a single `agent.ts` file. Complex agents will have multiple files, like a proper codebase.\n\nEnvironment variables are stored in `.env.local` and `.env.production`. `blink dev` will hot-reload environment variable changes in `.env.local`.\n\nChanges to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.\n\n1. _ALWAYS_ use the package manager the user is using (inferred from lock files or `process.argv`).\n2. You _MUST_ use `agent.store` to persist state. The agent process is designed to be stateless.\n3. Test your changes to the user\'s agent by using the `message_user_agent` tool. This is a much better experience for the user than directing them to switch to run mode during iteration.\n4. Use console.log for debugging. The console output appears for the user.\n5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses `inputSchema` instead of `parameters` (which was in v4).\n6. Output tokens can be increased using the `maxOutputTokens` option on `streamText` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.\n7. Use the TypeScript language service tools (`typescript_completions`, `typescript_quickinfo`, `typescript_definition`, `typescript_diagnostics`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.\n\nIf the user is asking for a behavioral change, you should update the agent\'s system prompt.\nThis will not ensure the behavior, but it will guide the agent towards the desired behavior.\nIf the user needs 100% behavioral certainty, adjust tool behavior instead.\n\n\n\nAgents are HTTP servers, so they can handle web requests. This is commonly used to async-invoke an agent. e.g. for a Slack bot, messages are sent to the agent via a webhook.\n\nBlink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).\n\nTo trigger chats based on web requests, use the `agent.chat.upsert` and `agent.chat.message` APIs.\n\n\n\nBlink agents are Node.js HTTP servers built on the Vercel AI SDK:\n\n```typescript\nimport { convertToModelMessages, streamText } from "ai";\nimport * as blink from "blink";\n\nconst agent = new blink.Agent();\n\nagent.on("chat", async ({ messages, chat, abortSignal }) => {\n return streamText({\n model: "anthropic/claude-sonnet-4.5",\n system: "You are a helpful assistant.",\n messages: convertToModelMessages(messages, {\n ignoreIncompleteToolCalls: true,\n }),\n tools: {\n /* your tools */\n },\n });\n});\n\nagent.on("request", async (request) => {\n // Handle webhooks, OAuth callbacks, etc.\n});\n\nagent.serve();\n```\n\nEvent Handlers:\n\n**`agent.on("chat", handler)`**\n\n1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.\n2. Must return: `streamText()` result, `Response`, `ReadableStream`, or `void`\n3. Parameters: `messages`, `id`, `abortSignal`\n\n_NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.\n\n**`agent.on("request", handler)`**\n• Handles raw HTTP requests before Blink processes them\n• Use for: OAuth callbacks, webhook verification, custom endpoints\n• Return `Response` to handle, or `void` to pass through\n\n**`agent.on("ui", handler)`**\n• Provides dynamic UI options for chat interfaces\n• Returns schema defining user-selectable options\n\n**`agent.on("error", handler)`**\n• Global error handler for the agent\n\nChat Management:\n\nBlink automatically manages chat state:\n\n```typescript\n// Create or get existing chat\n// The parameter can be any JSON-serializable value.\n// e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]\nconst chat = await agent.chat.upsert("unique-key");\n\n// Send a message to a chat\nawait agent.chat.sendMessages(\n chat.id,\n [\n {\n role: "user",\n parts: [{ type: "text", text: "Message" }],\n },\n ],\n {\n behavior: "interrupt" | "enqueue" | "append",\n }\n);\n\n// When sending messages, feel free to inject additional parts to direct the model.\n// e.g. if the user is asking for specific behavior in specific scenarios, the simplest\n// answer is to append a text part: "always do X when Y".\n```\n\nBehaviors:\n• "interrupt": Stop current processing and handle immediately\n• "enqueue": Queue message, process when current chat finishes\n• "append": Add to history without triggering processing\n\nChat keys: Use structured keys like `"slack-${teamId}-${channelId}-${threadTs}"` for uniqueness.\n\nStorage API:\n\nPersistent key-value storage per agent:\n\n```typescript\n// Store data\nawait agent.store.set("key", "value", { ttl: 3600 });\n\n// Retrieve data\nconst value = await agent.store.get("key");\n\n// Delete data\nawait agent.store.delete("key");\n\n// List keys by prefix\nconst result = await agent.store.list("prefix-", { limit: 100 });\n```\n\nCommon uses: OAuth tokens, user preferences, caching, chat-resource associations.\n\nTools:\n\nTools follow Vercel AI SDK patterns with Zod validation:\n\n```typescript\nimport { tool } from "ai";\nimport { z } from "zod";\n\nconst myTool = tool({\n description: "Clear description of what this tool does",\n inputSchema: z.object({\n param: z.string().describe("Parameter description"),\n }),\n execute: async (args, opts) => {\n // opts.abortSignal for cancellation\n // opts.toolCallId for unique identification\n return result;\n },\n});\n```\n\nTool Approvals for destructive operations:\n\n```typescript\n...await blink.tools.withApproval({\n messages,\n tools: {\n delete_database: tool({ /* ... */ }),\n },\n})\n```\n\nTool Context for dependency injection:\n\n```typescript\n...blink.tools.withContext(github.tools, {\n accessToken: process.env.GITHUB_TOKEN,\n})\n```\n\nTool Prefixing to avoid collisions:\n\n```typescript\n...blink.tools.prefix(github.tools, "github_")\n```\n\nLLM Models:\n\n```typescript\nimport { anthropic } from "@ai-sdk/anthropic";\nimport { openai } from "@ai-sdk/openai";\n\nmodel: anthropic("claude-sonnet-4.5", {\n apiKey: process.env.ANTHROPIC_API_KEY,\n});\nmodel: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });\n```\n\n**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:\n\n1. If `ANTHROPIC_API_KEY` is set: uses `claude-sonnet-4.5` via `@ai-sdk/anthropic`\n2. If `OPENAI_API_KEY` is set: uses `gpt-5` via `@ai-sdk/openai`\n3. If `AI_GATEWAY_API_KEY` is set: uses `anthropic/claude-sonnet-4-5` via the Vercel AI Gateway\n\nAvailable SDKs:\n\n**@blink-sdk/compute**\n\n```typescript\nimport * as compute from "@blink-sdk/compute";\n\ntools: {\n ...compute.tools, // execute_bash, read_file, write_file, edit_file, process management\n}\n```\n\n**@blink-sdk/github**\n\n```typescript\nimport * as github from "@blink-sdk/github";\n\ntools: {\n ...blink.tools.withContext(github.tools, {\n accessToken: process.env.GITHUB_TOKEN,\n }),\n}\n```\n\n**@blink-sdk/slack**\n\n```typescript\nimport * as slack from "@blink-sdk/slack";\nimport { App } from "@slack/bolt";\n\nconst receiver = new slack.Receiver();\nconst app = new App({\n token: process.env.SLACK_BOT_TOKEN,\n signingSecret: process.env.SLACK_SIGNING_SECRET,\n receiver,\n});\n\n// This will trigger when the bot is @mentioned.\napp.event("app_mention", async ({ event }) => {\n // The argument here is a JSON-serializable value.\n // To maintain the same chat context, use the same key.\n const chat = await agent.chat.upsert([\n "slack",\n event.channel,\n event.thread_ts ?? event.ts,\n ]);\n const { message } = await slack.createMessageFromEvent({\n client: app.client,\n event,\n });\n await agent.chat.sendMessages(chat.id, [message]);\n // This is a nice immediate indicator for the user.\n await app.client.assistant.threads.setStatus({\n channel_id: event.channel,\n status: "is typing...",\n thread_ts: event.thread_ts ?? event.ts,\n });\n});\n\nconst agent = new blink.Agent();\n\nagent.on("request", async (request) => {\n return receiver.handle(app, request);\n});\n\nagent.on("chat", async ({ messages }) => {\n const tools = slack.createTools({ client: app.client });\n return streamText({\n model: "anthropic/claude-sonnet-4.5",\n system: "You chatting with users in Slack.",\n messages: convertToModelMessages(messages, {\n ignoreIncompleteToolCalls: true,\n tools,\n }),\n });\n});\n```\n\nSlack SDK Notes:\n\n- "app_mention" event is triggered in both private channels and public channels.\n- "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.\n- _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.\n- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.\n- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. `message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=${channel} thread_ts=${thread_ts}" })`\n- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".\n\nSlack App Manifest:\n\n- _ALWAYS_ include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You _MUST_ provide "assistant_view" if you provide this scope.\n- The user can always edit the manifest after creation, but you\'d have to suggest it to them.\n- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.\n- _ALWAYS_ default `token_rotation_enabled` to false unless the user explicitly asks for it. It is a _much_ simpler user-experience to not rotate tokens.\n- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):\n - "app_mentions:read"\n - "reactions:write"\n - "reactions:read"\n - "channels:history"\n - "chat:write"\n - "groups:history"\n - "groups:read"\n - "files:read"\n - "im:history"\n - "im:read"\n - "im:write"\n - "mpim:history"\n - "mpim:read"\n - "users:read"\n - "links:read"\n - "commands"\n- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):\n - "app_mention"\n - "message.channels",\n - "message.groups",\n - "message.im",\n - "reaction_added"\n - "reaction_removed"\n - "assistant_thread_started"\n - "member_joined_channel"\n- _NEVER_ include USER SCOPES unless the user explicitly asks for them.\n\nWARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.\n\nState Management:\n\nBlink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.\n\n_NEVER_ use module-level Maps, Sets, or variables to store state (e.g. `const activeBots = new Map()`).\n\nFor global state persistence, you can use the agent store:\n\n- Use `agent.store` for persistent key-value storage\n- Query external APIs to fetch current state\n- Use webhooks to trigger actions rather than polling in-memory state\n\nFor message-level state persistence, use message metadata:\n\n```typescript\nimport { UIMessage } from "blink";\nimport * as blink from "blink";\n\nconst agent = new blink.Agent<\n UIMessage<{\n source: "github";\n associated_id: string;\n }>\n>();\n\nagent.on("request", async (request) => {\n // comes from github, we want to do something deterministic in the chat loop with that ID...\n // insert a message with that metadata into the chat\n const chat = await agent.chat.upsert("some-github-key");\n await agent.chat.sendMessages(request.chat.id, [\n {\n role: "user",\n parts: [\n {\n type: "text",\n text: "example",\n },\n ],\n metadata: {\n source: "github",\n associated_id: "some-github-id",\n },\n },\n ]);\n});\n\nagent.on("chat", async ({ messages }) => {\n const message = messages.find(\n (message) => message.metadata?.source === "github"\n );\n\n // Now we can use that metadata...\n});\n```\n\nThe agent process can restart at any time, so all important state must be externalized.\n\n\n\n\n- Never use "as any" type assertions. Always figure out the correct typings.\n \n', "agent.ts.hbs": 'import { convertToModelMessages, streamText, tool } from "ai";\nimport * as blink from "blink";\nimport { z } from "zod";\n{{#if (eq aiProvider "anthropic")}}\nimport { anthropic } from "@ai-sdk/anthropic";\n{{else if (eq aiProvider "openai")}}\nimport { openai } from "@ai-sdk/openai";\n{{/if}}\n\nconst agent = new blink.Agent();\n\nagent.on("chat", async ({ messages }) => {\n return streamText({\n{{#if (eq aiProvider "anthropic")}}\n model: anthropic("claude-sonnet-4-5"),\n{{else if (eq aiProvider "openai")}}\n model: openai("gpt-5-codex"),\n providerOptions: {\n openai: {\n reasoningSummary: "detailed",\n },\n },\n{{else if (eq aiProvider "vercel")}}\n model: "anthropic/claude-sonnet-4.5",\n{{else}}\n // Unknown provider: {{aiProvider}}. Defaulting to Vercel AI Gateway syntax.\n model: "anthropic/claude-sonnet-4.5",\n{{/if}}\n system: `You are a basic agent the user will customize.\n\nSuggest the user enters edit mode with Ctrl+T or /edit to customize the agent.\nDemonstrate your capabilities with the IP tool.`,\n messages: convertToModelMessages(messages),\n tools: {\n get_ip_info: tool({\n description: "Get IP address information of the computer.",\n inputSchema: z.object({}),\n execute: async () => {\n const response = await fetch("https://ipinfo.io/json");\n return response.json();\n },\n }),\n },\n });\n});\n\nagent.serve();\n', "package.json.hbs": @@ -19,10 +19,10 @@ export const templates = { '{\n "compilerOptions": {\n "lib": ["ESNext"],\n "target": "ESNext",\n "module": "Preserve",\n "moduleDetection": "force",\n\n "moduleResolution": "bundler",\n "allowImportingTsExtensions": true,\n "verbatimModuleSyntax": true,\n "resolveJsonModule": true,\n "noEmit": true,\n\n "strict": true,\n "skipLibCheck": true,\n "noFallthroughCasesInSwitch": true,\n "noUncheckedIndexedAccess": true,\n "noImplicitOverride": true,\n\n "noUnusedLocals": false,\n "noUnusedParameters": false,\n\n "types": ["node"]\n }\n}\n', }, "slack-bot": { - ".env.local": - "\n# Store local environment variables here.\n# They will be used by blink dev for development.\nSLACK_BOT_TOKEN=xoxb-your-token-here\nSLACK_SIGNING_SECRET=your-signing-secret-here\n", + ".env.local.hbs": + '# Store local environment variables here.\n# They will be used by blink dev for development.\n{{#each envLocal}}\n{{this.[0]}}={{this.[1]}}\n{{/each}}\n{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}\n# OPENAI_API_KEY=\n# ANTHROPIC_API_KEY=\n# AI_GATEWAY_API_KEY=\n{{/unless}}\nSLACK_BOT_TOKEN=xoxb-your-token-here\nSLACK_SIGNING_SECRET=your-signing-secret-here\n', ".env.production": - "# Store production environment variables here.\n# They will be upserted as secrets on blink deploy.\n# EXTERNAL_SERVICE_API_KEY=\n", + "# Store production environment variables here.\n# They will be upserted as secrets on blink deploy.\n# SLACK_BOT_TOKEN=\n# SLACK_SIGNING_SECRET=\n# OPENAI_API_KEY=\n# ANTHROPIC_API_KEY=\n# AI_GATEWAY_API_KEY=", ".gitignore": "# dependencies\nnode_modules\n\n# config and build\n.blink\n\n# dotenv environment variables file\n.env\n.env.*\n\n# Finder (MacOS) folder config\n.DS_Store\n", "AGENTS.md": diff --git a/packages/blink/src/cli/init-templates/scratch/_noignore.env.local b/packages/blink/src/cli/init-templates/scratch/_noignore.env.local deleted file mode 100644 index 5c610a6..0000000 --- a/packages/blink/src/cli/init-templates/scratch/_noignore.env.local +++ /dev/null @@ -1,4 +0,0 @@ - -# Store local environment variables here. -# They will be used by blink dev for development. -# EXTERNAL_SERVICE_API_KEY= diff --git a/packages/blink/src/cli/init-templates/scratch/_noignore.env.local.hbs b/packages/blink/src/cli/init-templates/scratch/_noignore.env.local.hbs new file mode 100644 index 0000000..05c127e --- /dev/null +++ b/packages/blink/src/cli/init-templates/scratch/_noignore.env.local.hbs @@ -0,0 +1,10 @@ +# Store local environment variables here. +# They will be used by blink dev for development. +{{#each envLocal}} +{{this.[0]}}={{this.[1]}} +{{/each}} +{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}} +# OPENAI_API_KEY= +# ANTHROPIC_API_KEY= +# AI_GATEWAY_API_KEY= +{{/unless}} \ No newline at end of file diff --git a/packages/blink/src/cli/init-templates/scratch/_noignore.env.production b/packages/blink/src/cli/init-templates/scratch/_noignore.env.production index b823d6e..3eac53b 100644 --- a/packages/blink/src/cli/init-templates/scratch/_noignore.env.production +++ b/packages/blink/src/cli/init-templates/scratch/_noignore.env.production @@ -1,3 +1,5 @@ # Store production environment variables here. # They will be upserted as secrets on blink deploy. -# EXTERNAL_SERVICE_API_KEY= +# OPENAI_API_KEY= +# ANTHROPIC_API_KEY= +# AI_GATEWAY_API_KEY= diff --git a/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local b/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local deleted file mode 100644 index d347914..0000000 --- a/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local +++ /dev/null @@ -1,5 +0,0 @@ - -# Store local environment variables here. -# They will be used by blink dev for development. -SLACK_BOT_TOKEN=xoxb-your-token-here -SLACK_SIGNING_SECRET=your-signing-secret-here diff --git a/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local.hbs b/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local.hbs new file mode 100644 index 0000000..aff1667 --- /dev/null +++ b/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.local.hbs @@ -0,0 +1,12 @@ +# Store local environment variables here. +# They will be used by blink dev for development. +{{#each envLocal}} +{{this.[0]}}={{this.[1]}} +{{/each}} +{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}} +# OPENAI_API_KEY= +# ANTHROPIC_API_KEY= +# AI_GATEWAY_API_KEY= +{{/unless}} +SLACK_BOT_TOKEN=xoxb-your-token-here +SLACK_SIGNING_SECRET=your-signing-secret-here diff --git a/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.production b/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.production index b823d6e..38595fb 100644 --- a/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.production +++ b/packages/blink/src/cli/init-templates/slack-bot/_noignore.env.production @@ -1,3 +1,7 @@ # Store production environment variables here. # They will be upserted as secrets on blink deploy. -# EXTERNAL_SERVICE_API_KEY= +# SLACK_BOT_TOKEN= +# SLACK_SIGNING_SECRET= +# OPENAI_API_KEY= +# ANTHROPIC_API_KEY= +# AI_GATEWAY_API_KEY= \ No newline at end of file diff --git a/packages/blink/src/cli/init.ts b/packages/blink/src/cli/init.ts index fab3e7b..501cf24 100644 --- a/packages/blink/src/cli/init.ts +++ b/packages/blink/src/cli/init.ts @@ -20,6 +20,7 @@ function getFilesForTemplate( variables: { packageName: string; aiProvider: string; + envLocal: Array<[string, string]>; } ): Record { const templateFiles = templates[template]; @@ -28,6 +29,26 @@ function getFilesForTemplate( // Register eq helper for Handlebars Handlebars.registerHelper("eq", (a, b) => a === b); + // Register helper to check if a key exists in envLocal array + Handlebars.registerHelper( + "hasEnvVar", + (envLocal: Array<[string, string]>, key: string) => { + return envLocal.some((tuple) => tuple[0] === key); + } + ); + + // Register helper to check if any of multiple keys exist in envLocal array + Handlebars.registerHelper( + "hasAnyEnvVar", + (envLocal: Array<[string, string]>, ...keys) => { + // Remove the last argument which is the Handlebars options object + const keysToCheck = keys.slice(0, -1); + return keysToCheck.some((key) => + envLocal.some((tuple) => tuple[0] === key) + ); + } + ); + // Copy all files and render .hbs templates for (const [filename, content] of Object.entries(templateFiles)) { let outputFilename = filename; @@ -171,9 +192,16 @@ export default async function init(directory?: string): Promise { log.info(`Using ${packageManager} as the package manager.`); + // Build envLocal array with API key if provided + const envLocal: Array<[string, string]> = []; + if (apiKey && apiKey.trim() !== "") { + envLocal.push([envVarName, apiKey]); + } + const files = getFilesForTemplate(template, { packageName: name, aiProvider: aiProviderChoice, + envLocal, }); await Promise.all( @@ -182,25 +210,7 @@ export default async function init(directory?: string): Promise { }) ); - // Append API key to .env.local if provided if (apiKey && apiKey.trim() !== "") { - const envFilePath = join(directory, ".env.local"); - let existingContent = ""; - - // Read existing content if file exists - try { - existingContent = await readFile(envFilePath, "utf-8"); - } catch (error) { - // File doesn't exist yet, that's fine - } - - // Ensure existing content ends with newline if it has content - if (existingContent.length > 0 && !existingContent.endsWith("\n")) { - existingContent += "\n"; - } - - const newContent = existingContent + `${envVarName}=${apiKey}\n`; - await writeFile(envFilePath, newContent); log.success(`API key saved to .env.local`); } From 24b828188467556d688045fbd6b598c8dccc4642 Mon Sep 17 00:00:00 2001 From: Hugo Dutka Date: Mon, 20 Oct 2025 15:39:55 +0200 Subject: [PATCH 2/2] test --- packages/blink/src/cli/init.test.ts | 214 ++++++++++++++++++ packages/blink/src/cli/init.ts | 2 +- packages/blink/src/cli/lib/templates.ts | 38 ++++ .../cli/scripts/generate-templates.test.ts | 9 + .../src/cli/scripts/generate-templates.ts | 36 +-- 5 files changed, 267 insertions(+), 32 deletions(-) create mode 100644 packages/blink/src/cli/init.test.ts create mode 100644 packages/blink/src/cli/lib/templates.ts create mode 100644 packages/blink/src/cli/scripts/generate-templates.test.ts diff --git a/packages/blink/src/cli/init.test.ts b/packages/blink/src/cli/init.test.ts new file mode 100644 index 0000000..1b64124 --- /dev/null +++ b/packages/blink/src/cli/init.test.ts @@ -0,0 +1,214 @@ +import { describe, it, expect } from "bun:test"; +import { getFilesForTemplate } from "./init"; + +const getFile = (files: Record, filename: string): string => { + const fileContent = files[filename]; + if (fileContent === undefined) { + throw new Error(`File ${filename} is undefined`); + } + return fileContent; +}; + +// Test helper for .env.local AI provider key behavior +function testAiProviderKeyBehavior(template: "scratch" | "slack-bot") { + describe(".env.local AI provider key behavior", () => { + it("should show AI provider placeholders when envLocal is empty", () => { + const files = getFilesForTemplate(template, { + packageName: "test-project", + aiProvider: "anthropic", + envLocal: [], + }); + + const envLocal = getFile(files, ".env.local"); + expect(envLocal).toContain("# OPENAI_API_KEY="); + expect(envLocal).toContain("# ANTHROPIC_API_KEY="); + expect(envLocal).toContain("# AI_GATEWAY_API_KEY="); + }); + + it("should not show AI provider placeholders when ANTHROPIC_API_KEY is provided", () => { + const files = getFilesForTemplate(template, { + packageName: "test-project", + aiProvider: "anthropic", + envLocal: [["ANTHROPIC_API_KEY", "sk-test-123"]], + }); + + const envLocal = getFile(files, ".env.local"); + expect(envLocal).toContain("ANTHROPIC_API_KEY=sk-test-123"); + expect(envLocal).not.toContain("# OPENAI_API_KEY="); + expect(envLocal).not.toContain("# ANTHROPIC_API_KEY="); + expect(envLocal).not.toContain("# AI_GATEWAY_API_KEY="); + }); + + it("should not show AI provider placeholders when OPENAI_API_KEY is provided", () => { + const files = getFilesForTemplate(template, { + packageName: "test-project", + aiProvider: "openai", + envLocal: [["OPENAI_API_KEY", "sk-test-456"]], + }); + + const envLocal = getFile(files, ".env.local"); + expect(envLocal).toContain("OPENAI_API_KEY=sk-test-456"); + expect(envLocal).not.toContain("# OPENAI_API_KEY="); + expect(envLocal).not.toContain("# ANTHROPIC_API_KEY="); + expect(envLocal).not.toContain("# AI_GATEWAY_API_KEY="); + }); + + it("should not show AI provider placeholders when AI_GATEWAY_API_KEY is provided", () => { + const files = getFilesForTemplate(template, { + packageName: "test-project", + aiProvider: "vercel", + envLocal: [["AI_GATEWAY_API_KEY", "gateway-key-789"]], + }); + + const envLocal = getFile(files, ".env.local"); + expect(envLocal).toContain("AI_GATEWAY_API_KEY=gateway-key-789"); + expect(envLocal).not.toContain("# OPENAI_API_KEY="); + expect(envLocal).not.toContain("# ANTHROPIC_API_KEY="); + expect(envLocal).not.toContain("# AI_GATEWAY_API_KEY="); + }); + + it("should preserve variable order from envLocal array", () => { + const files = getFilesForTemplate(template, { + packageName: "test-project", + aiProvider: "anthropic", + envLocal: [ + ["CUSTOM_VAR_1", "value1"], + ["ANTHROPIC_API_KEY", "sk-test-123"], + ["CUSTOM_VAR_2", "value2"], + ], + }); + + const envLocal = getFile(files, ".env.local"); + if (!envLocal) { + throw new Error("envLocal is undefined"); + } + const customVar1Index = envLocal.indexOf("CUSTOM_VAR_1=value1"); + const apiKeyIndex = envLocal.indexOf("ANTHROPIC_API_KEY=sk-test-123"); + const customVar2Index = envLocal.indexOf("CUSTOM_VAR_2=value2"); + + expect(customVar1Index).toBeLessThan(apiKeyIndex); + expect(apiKeyIndex).toBeLessThan(customVar2Index); + }); + }); +} + +describe("getFilesForTemplate", () => { + describe("scratch template", () => { + testAiProviderKeyBehavior("scratch"); + + it("should render package.json with correct dependencies for anthropic provider", () => { + const files = getFilesForTemplate("scratch", { + packageName: "test-project", + aiProvider: "anthropic", + envLocal: [], + }); + const packageJsonContent = getFile(files, "package.json"); + if (!packageJsonContent) { + throw new Error("packageJson is undefined"); + } + + const packageJson = JSON.parse(packageJsonContent); + expect(packageJson.name).toBe("test-project"); + expect(packageJson.devDependencies["@ai-sdk/anthropic"]).toBe("latest"); + expect(packageJson.devDependencies["@ai-sdk/openai"]).toBeUndefined(); + }); + + it("should render package.json with correct dependencies for openai provider", () => { + const files = getFilesForTemplate("scratch", { + packageName: "test-project", + aiProvider: "openai", + envLocal: [], + }); + + const packageJson = JSON.parse(getFile(files, "package.json")); + expect(packageJson.devDependencies["@ai-sdk/openai"]).toBe("latest"); + expect(packageJson.devDependencies["@ai-sdk/anthropic"]).toBeUndefined(); + }); + }); + + describe("slack-bot template", () => { + testAiProviderKeyBehavior("slack-bot"); + + it("should show Slack placeholders when envLocal is empty", () => { + const files = getFilesForTemplate("slack-bot", { + packageName: "test-slack-bot", + aiProvider: "anthropic", + envLocal: [], + }); + + const envLocal = getFile(files, ".env.local"); + expect(envLocal).toContain("SLACK_BOT_TOKEN=xoxb-your-token-here"); + expect(envLocal).toContain( + "SLACK_SIGNING_SECRET=your-signing-secret-here" + ); + }); + + it("should show Slack placeholders even when AI key is provided", () => { + const files = getFilesForTemplate("slack-bot", { + packageName: "test-slack-bot", + aiProvider: "openai", + envLocal: [["OPENAI_API_KEY", "sk-test-456"]], + }); + + const envLocal = getFile(files, ".env.local"); + expect(envLocal).toContain("SLACK_BOT_TOKEN=xoxb-your-token-here"); + expect(envLocal).toContain( + "SLACK_SIGNING_SECRET=your-signing-secret-here" + ); + }); + + it("should render package.json with slack dependencies", () => { + const files = getFilesForTemplate("slack-bot", { + packageName: "test-slack-bot", + aiProvider: "anthropic", + envLocal: [], + }); + + const packageJson = JSON.parse(getFile(files, "package.json")); + expect(packageJson.name).toBe("test-slack-bot"); + expect(packageJson.devDependencies["@slack/bolt"]).toBe("latest"); + expect(packageJson.devDependencies["@blink-sdk/slack"]).toBe("latest"); + }); + }); + + describe("agent.ts template rendering", () => { + it("should render agent.ts with anthropic provider", () => { + const files = getFilesForTemplate("scratch", { + packageName: "test-project", + aiProvider: "anthropic", + envLocal: [], + }); + + const agentTs = getFile(files, "agent.ts"); + expect(agentTs).toContain( + 'import { anthropic } from "@ai-sdk/anthropic"' + ); + expect(agentTs).toContain('model: anthropic("claude-sonnet-4-5")'); + expect(agentTs).not.toContain("import { openai }"); + }); + + it("should render agent.ts with openai provider", () => { + const files = getFilesForTemplate("scratch", { + packageName: "test-project", + aiProvider: "openai", + envLocal: [], + }); + + const agentTs = getFile(files, "agent.ts"); + expect(agentTs).toContain('import { openai } from "@ai-sdk/openai"'); + expect(agentTs).toContain('model: openai("gpt-5-codex")'); + expect(agentTs).not.toContain("import { anthropic }"); + }); + + it("should render agent.ts with vercel provider fallback", () => { + const files = getFilesForTemplate("scratch", { + packageName: "test-project", + aiProvider: "vercel", + envLocal: [], + }); + + const agentTs = getFile(files, "agent.ts"); + expect(agentTs).toContain('model: "anthropic/claude-sonnet-4.5"'); + }); + }); +}); diff --git a/packages/blink/src/cli/init.ts b/packages/blink/src/cli/init.ts index 501cf24..8d65c37 100644 --- a/packages/blink/src/cli/init.ts +++ b/packages/blink/src/cli/init.ts @@ -15,7 +15,7 @@ import Handlebars from "handlebars"; import { templates, type TemplateId } from "./init-templates"; import { setupSlackApp } from "./setup-slack-app"; -function getFilesForTemplate( +export function getFilesForTemplate( template: TemplateId, variables: { packageName: string; diff --git a/packages/blink/src/cli/lib/templates.ts b/packages/blink/src/cli/lib/templates.ts new file mode 100644 index 0000000..0fd9f4d --- /dev/null +++ b/packages/blink/src/cli/lib/templates.ts @@ -0,0 +1,38 @@ +import { readdir, readFile, writeFile } from "fs/promises"; +import stringify from "json-stable-stringify"; +import { join } from "path"; + +export async function generateTemplates(): Promise< + Record> +> { + const templatesDir = join(import.meta.dirname, "..", "init-templates"); + + // Read all template directories + const entries = await readdir(templatesDir, { withFileTypes: true }); + const templateDirs = entries + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name); + + const templates: Record> = {}; + + // Read each template directory + for (const templateId of templateDirs) { + const templatePath = join(templatesDir, templateId); + const files = await readdir(templatePath); + + templates[templateId] = {}; + + for (const file of files) { + const filePath = join(templatePath, file); + const content = await readFile(filePath, "utf-8"); + + // Strip "_noignore" prefix from filename if present + const outputFilename = file.startsWith("_noignore") + ? file.substring("_noignore".length) + : file; + + templates[templateId][outputFilename] = content; + } + } + return templates; +} diff --git a/packages/blink/src/cli/scripts/generate-templates.test.ts b/packages/blink/src/cli/scripts/generate-templates.test.ts new file mode 100644 index 0000000..34560e7 --- /dev/null +++ b/packages/blink/src/cli/scripts/generate-templates.test.ts @@ -0,0 +1,9 @@ +import { describe, it, expect } from "bun:test"; +import { generateTemplates } from "../lib/templates"; +import { templates } from "../init-templates"; + +it("templates are up to date", async () => { + // if this test fails, run `bun run gen-templates` in `packages/blink` + const generatedTemplates = await generateTemplates(); + expect(generatedTemplates).toEqual(templates); +}); diff --git a/packages/blink/src/cli/scripts/generate-templates.ts b/packages/blink/src/cli/scripts/generate-templates.ts index 3d859ee..57240c6 100644 --- a/packages/blink/src/cli/scripts/generate-templates.ts +++ b/packages/blink/src/cli/scripts/generate-templates.ts @@ -1,38 +1,12 @@ +import { generateTemplates } from "../lib/templates"; import { readdir, readFile, writeFile } from "fs/promises"; import stringify from "json-stable-stringify"; import { join } from "path"; -async function generateTemplates() { +const main = async () => { + const templates = await generateTemplates(); const templatesDir = join(import.meta.dirname, "..", "init-templates"); - // Read all template directories - const entries = await readdir(templatesDir, { withFileTypes: true }); - const templateDirs = entries - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name); - - const templates: Record> = {}; - - // Read each template directory - for (const templateId of templateDirs) { - const templatePath = join(templatesDir, templateId); - const files = await readdir(templatePath); - - templates[templateId] = {}; - - for (const file of files) { - const filePath = join(templatePath, file); - const content = await readFile(filePath, "utf-8"); - - // Strip "_noignore" prefix from filename if present - const outputFilename = file.startsWith("_noignore") - ? file.substring("_noignore".length) - : file; - - templates[templateId][outputFilename] = content; - } - } - // Generate the index.ts file const outputPath = join(templatesDir, "index.ts"); const output = `// This file is auto-generated by src/cli/scripts/generate-templates.ts @@ -45,9 +19,9 @@ export type TemplateId = keyof typeof templates; await writeFile(outputPath, output); console.log(`Generated ${outputPath}`); -} +}; -generateTemplates().catch((error) => { +main().catch((error) => { console.error("Error generating templates:", error); process.exit(1); });