blink 1.1.10 → 1.1.12

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.
@@ -0,0 +1,1108 @@
1
+ import{Ie as e,M as t,Se as n,pD as r,ve as i,xe as a,ye as o}from"./dist-BNbSDxaw.js";import{basename as s,join as c}from"path";import{readdir as l,writeFile as u}from"fs/promises";import{spawn as d}from"child_process";const f={scratch:{"agent.ts":`import { convertToModelMessages, streamText, tool } from "ai";
2
+ import * as blink from "blink";
3
+ import { z } from "zod";
4
+
5
+ const agent = blink.agent();
6
+
7
+ agent.on("chat", async ({ messages }) => {
8
+ return streamText({
9
+ model: blink.model("anthropic/claude-sonnet-4.5"),
10
+ system: \`You are a basic agent the user will customize.
11
+
12
+ Suggest the user enters edit mode with Ctrl+T or /edit to customize the agent.
13
+ Demonstrate your capabilities with the IP tool.\`,
14
+ messages: convertToModelMessages(messages),
15
+ tools: {
16
+ get_ip_info: tool({
17
+ description: "Get IP address information of the computer.",
18
+ inputSchema: z.object({}),
19
+ execute: async () => {
20
+ const response = await fetch("https://ipinfo.io/json");
21
+ return response.json();
22
+ },
23
+ }),
24
+ },
25
+ });
26
+ });
27
+
28
+ agent.serve();
29
+ `,"package.json":`{
30
+ "name": "{{name}}",
31
+ "main": "agent.ts",
32
+ "type": "module",
33
+ "private": true,
34
+ "scripts": {
35
+ "dev": "blink dev",
36
+ "deploy": "blink deploy"
37
+ },
38
+ "devDependencies": {
39
+ "zod": "latest",
40
+ "ai": "latest",
41
+ "blink": "latest",
42
+ "esbuild": "latest",
43
+ "@types/node": "latest",
44
+ "typescript": "latest"
45
+ }
46
+ }
47
+ `,".gitignore":`# dependencies
48
+ node_modules
49
+
50
+ # config and build
51
+ data
52
+
53
+ # dotenv environment variables file
54
+ .env
55
+ .env.*
56
+
57
+ # Finder (MacOS) folder config
58
+ .DS_Store
59
+ `,"tsconfig.json":`{
60
+ "compilerOptions": {
61
+ "lib": ["ESNext"],
62
+ "target": "ESNext",
63
+ "module": "Preserve",
64
+ "moduleDetection": "force",
65
+
66
+ "moduleResolution": "bundler",
67
+ "allowImportingTsExtensions": true,
68
+ "verbatimModuleSyntax": true,
69
+ "resolveJsonModule": true,
70
+ "noEmit": true,
71
+
72
+ "strict": true,
73
+ "skipLibCheck": true,
74
+ "noFallthroughCasesInSwitch": true,
75
+ "noUncheckedIndexedAccess": true,
76
+ "noImplicitOverride": true,
77
+
78
+ "noUnusedLocals": false,
79
+ "noUnusedParameters": false,
80
+
81
+ "types": ["node"]
82
+ }
83
+ }
84
+ `,"AGENTS.md":`This project is a Blink agent.
85
+
86
+ You 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.
87
+
88
+ <communication>
89
+ 1. Be concise, direct, and to the point.
90
+ 2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
91
+ 3. NEVER use emojis unless the user explicitly asks for them.
92
+ 4. 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...".
93
+ 5. Mimic the style of the user's messages.
94
+ 6. Do not remind the user you are happy to help.
95
+ 7. Do not act with sycophantic flattery or over-the-top enthusiasm.
96
+ 8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
97
+ 9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
98
+ 10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
99
+ </communication>
100
+
101
+ <goals>
102
+ Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
103
+
104
+ You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
105
+
106
+ The user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
107
+
108
+ <example>
109
+ user: i want a coding agent
110
+ assistant: Let me take a look at your codebase...
111
+ ... tool calls to investigate the codebase...
112
+ assistant: 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.
113
+ </example>
114
+
115
+ Always investigate the current state of the agent before assisting the user.
116
+ </goals>
117
+
118
+ <agent_development>
119
+ Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
120
+
121
+ Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
122
+
123
+ Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
124
+
125
+ 1. _ALWAYS_ use the package manager the user is using (inferred from lock files or \`process.argv\`).
126
+ 2. You _MUST_ use \`agent.store\` to persist state. The agent process is designed to be stateless.
127
+ 3. 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.
128
+ 4. Use console.log for debugging. The console output appears for the user.
129
+ 5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
130
+ 6. 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.
131
+ 7. 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.
132
+
133
+ If the user is asking for a behavioral change, you should update the agent's system prompt.
134
+ This will not ensure the behavior, but it will guide the agent towards the desired behavior.
135
+ If the user needs 100% behavioral certainty, adjust tool behavior instead.
136
+ </agent_development>
137
+
138
+ <agent_web_requests>
139
+ Agents 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.
140
+
141
+ Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
142
+
143
+ To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
144
+ </agent_web_requests>
145
+
146
+ <technical_knowledge>
147
+ Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
148
+
149
+ \`\`\`typescript
150
+ import { convertToModelMessages, streamText } from "ai";
151
+ import * as blink from "blink";
152
+
153
+ const agent = new blink.Agent();
154
+
155
+ agent.on("chat", async ({ messages, chat, abortSignal }) => {
156
+ return streamText({
157
+ model: blink.model("anthropic/claude-sonnet-4.5"),
158
+ system: "You are a helpful assistant.",
159
+ messages: convertToModelMessages(messages, {
160
+ ignoreIncompleteToolCalls: true,
161
+ }),
162
+ tools: {
163
+ /* your tools */
164
+ },
165
+ });
166
+ });
167
+
168
+ agent.on("request", async (request) => {
169
+ // Handle webhooks, OAuth callbacks, etc.
170
+ });
171
+
172
+ agent.serve();
173
+ \`\`\`
174
+
175
+ Event Handlers:
176
+
177
+ **\`agent.on("chat", handler)\`**
178
+
179
+ 1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
180
+ 2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
181
+ 3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
182
+
183
+ _NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
184
+
185
+ **\`agent.on("request", handler)\`**
186
+ • Handles raw HTTP requests before Blink processes them
187
+ • Use for: OAuth callbacks, webhook verification, custom endpoints
188
+ • Return \`Response\` to handle, or \`void\` to pass through
189
+
190
+ **\`agent.on("ui", handler)\`**
191
+ • Provides dynamic UI options for chat interfaces
192
+ • Returns schema defining user-selectable options
193
+
194
+ **\`agent.on("error", handler)\`**
195
+ • Global error handler for the agent
196
+
197
+ Chat Management:
198
+
199
+ Blink automatically manages chat state:
200
+
201
+ \`\`\`typescript
202
+ // Create or get existing chat
203
+ // The parameter can be any JSON-serializable value.
204
+ // e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
205
+ const chat = await agent.chat.upsert("unique-key");
206
+
207
+ // Send a message to a chat
208
+ await agent.chat.sendMessages(
209
+ chat.id,
210
+ [
211
+ {
212
+ role: "user",
213
+ parts: [{ type: "text", text: "Message" }],
214
+ },
215
+ ],
216
+ {
217
+ behavior: "interrupt" | "enqueue" | "append",
218
+ }
219
+ );
220
+
221
+ // When sending messages, feel free to inject additional parts to direct the model.
222
+ // e.g. if the user is asking for specific behavior in specific scenarios, the simplest
223
+ // answer is to append a text part: "always do X when Y".
224
+ \`\`\`
225
+
226
+ Behaviors:
227
+ • "interrupt": Stop current processing and handle immediately
228
+ • "enqueue": Queue message, process when current chat finishes
229
+ • "append": Add to history without triggering processing
230
+
231
+ Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
232
+
233
+ Storage API:
234
+
235
+ Persistent key-value storage per agent:
236
+
237
+ \`\`\`typescript
238
+ // Store data
239
+ await agent.store.set("key", "value", { ttl: 3600 });
240
+
241
+ // Retrieve data
242
+ const value = await agent.store.get("key");
243
+
244
+ // Delete data
245
+ await agent.store.delete("key");
246
+
247
+ // List keys by prefix
248
+ const result = await agent.store.list("prefix-", { limit: 100 });
249
+ \`\`\`
250
+
251
+ Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
252
+
253
+ Tools:
254
+
255
+ Tools follow Vercel AI SDK patterns with Zod validation:
256
+
257
+ \`\`\`typescript
258
+ import { tool } from "ai";
259
+ import { z } from "zod";
260
+
261
+ const myTool = tool({
262
+ description: "Clear description of what this tool does",
263
+ inputSchema: z.object({
264
+ param: z.string().describe("Parameter description"),
265
+ }),
266
+ execute: async (args, opts) => {
267
+ // opts.abortSignal for cancellation
268
+ // opts.toolCallId for unique identification
269
+ return result;
270
+ },
271
+ });
272
+ \`\`\`
273
+
274
+ Tool Approvals for destructive operations:
275
+
276
+ \`\`\`typescript
277
+ ...await blink.tools.withApproval({
278
+ messages,
279
+ tools: {
280
+ delete_database: tool({ /* ... */ }),
281
+ },
282
+ })
283
+ \`\`\`
284
+
285
+ Tool Context for dependency injection:
286
+
287
+ \`\`\`typescript
288
+ ...blink.tools.withContext(github.tools, {
289
+ accessToken: process.env.GITHUB_TOKEN,
290
+ })
291
+ \`\`\`
292
+
293
+ Tool Prefixing to avoid collisions:
294
+
295
+ \`\`\`typescript
296
+ ...blink.tools.prefix(github.tools, "github_")
297
+ \`\`\`
298
+
299
+ LLM Models:
300
+
301
+ **Option 1: Blink Gateway** (Quick Start)
302
+
303
+ \`\`\`typescript
304
+ model: blink.model("anthropic/claude-sonnet-4.5");
305
+ model: blink.model("openai/gpt-5");
306
+ \`\`\`
307
+
308
+ Requires: \`blink login\` or \`BLINK_TOKEN\` env var
309
+
310
+ **Option 2: Direct Provider** (Production Recommended)
311
+
312
+ \`\`\`typescript
313
+ import { anthropic } from "@ai-sdk/anthropic";
314
+ import { openai } from "@ai-sdk/openai";
315
+
316
+ model: anthropic("claude-sonnet-4.5", {
317
+ apiKey: process.env.ANTHROPIC_API_KEY,
318
+ });
319
+ model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
320
+ \`\`\`
321
+
322
+ **Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
323
+
324
+ 1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
325
+ 2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
326
+ 3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
327
+
328
+ Available SDKs:
329
+
330
+ **@blink-sdk/compute**
331
+
332
+ \`\`\`typescript
333
+ import * as compute from "@blink-sdk/compute";
334
+
335
+ tools: {
336
+ ...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
337
+ }
338
+ \`\`\`
339
+
340
+ **@blink-sdk/github**
341
+
342
+ \`\`\`typescript
343
+ import * as github from "@blink-sdk/github";
344
+
345
+ tools: {
346
+ ...blink.tools.withContext(github.tools, {
347
+ accessToken: process.env.GITHUB_TOKEN,
348
+ }),
349
+ }
350
+ \`\`\`
351
+
352
+ **@blink-sdk/slack**
353
+
354
+ \`\`\`typescript
355
+ import * as slack from "@blink-sdk/slack";
356
+ import { App } from "@slack/bolt";
357
+
358
+ const receiver = new slack.Receiver();
359
+ const app = new App({
360
+ token: process.env.SLACK_BOT_TOKEN,
361
+ signingSecret: process.env.SLACK_SIGNING_SECRET,
362
+ receiver,
363
+ });
364
+
365
+ // This will trigger when the bot is @mentioned.
366
+ app.event("app_mention", async ({ event }) => {
367
+ // The argument here is a JSON-serializable value.
368
+ // To maintain the same chat context, use the same key.
369
+ const chat = await agent.chat.upsert([
370
+ "slack",
371
+ event.channel,
372
+ event.thread_ts ?? event.ts,
373
+ ]);
374
+ const { message } = await slack.createMessageFromEvent({
375
+ client: app.client,
376
+ event,
377
+ });
378
+ await agent.chat.sendMessages(chat.id, [message]);
379
+ // This is a nice immediate indicator for the user.
380
+ await app.client.assistant.threads.setStatus({
381
+ channel_id: event.channel,
382
+ status: "is typing...",
383
+ thread_ts: event.thread_ts ?? event.ts,
384
+ });
385
+ });
386
+
387
+ const agent = new blink.Agent();
388
+
389
+ agent.on("request", async (request) => {
390
+ return receiver.handle(app, request);
391
+ });
392
+
393
+ agent.on("chat", async ({ messages }) => {
394
+ const tools = slack.createTools({ client: app.client });
395
+ return streamText({
396
+ model: blink.model("anthropic/claude-sonnet-4.5"),
397
+ system: "You chatting with users in Slack.",
398
+ messages: convertToModelMessages(messages, {
399
+ ignoreIncompleteToolCalls: true,
400
+ tools,
401
+ }),
402
+ });
403
+ });
404
+ \`\`\`
405
+
406
+ Slack SDK Notes:
407
+
408
+ - "app_mention" event is triggered in both private channels and public channels.
409
+ - "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.
410
+ - _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
411
+ - 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.
412
+ - 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}" })\`
413
+ - 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".
414
+
415
+ Slack App Manifest:
416
+
417
+ - _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.
418
+ - The user can always edit the manifest after creation, but you'd have to suggest it to them.
419
+ - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
420
+ - _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.
421
+ - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
422
+ - "app_mentions:read"
423
+ - "reactions:write"
424
+ - "reactions:read"
425
+ - "channels:history"
426
+ - "chat:write"
427
+ - "groups:history"
428
+ - "groups:read"
429
+ - "files:read"
430
+ - "im:history"
431
+ - "im:read"
432
+ - "im:write"
433
+ - "mpim:history"
434
+ - "mpim:read"
435
+ - "users:read"
436
+ - "links:read"
437
+ - "commands"
438
+ - For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
439
+ - "app_mention"
440
+ - "message.channels",
441
+ - "message.groups",
442
+ - "message.im",
443
+ - "reaction_added"
444
+ - "reaction_removed"
445
+ - "assistant_thread_started"
446
+ - "member_joined_channel"
447
+ - _NEVER_ include USER SCOPES unless the user explicitly asks for them.
448
+
449
+ WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
450
+
451
+ **@blink-sdk/web-search**
452
+
453
+ \`\`\`typescript
454
+ import * as webSearch from "@blink-sdk/web-search";
455
+
456
+ tools: {
457
+ ...webSearch.tools,
458
+ }
459
+ \`\`\`
460
+
461
+ State Management:
462
+
463
+ Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
464
+
465
+ _NEVER_ use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
466
+
467
+ For global state persistence, you can use the agent store:
468
+
469
+ - Use \`agent.store\` for persistent key-value storage
470
+ - Query external APIs to fetch current state
471
+ - Use webhooks to trigger actions rather than polling in-memory state
472
+
473
+ For message-level state persistence, use message metadata:
474
+
475
+ \`\`\`typescript
476
+ import { UIMessage } from "blink";
477
+ import * as blink from "blink";
478
+
479
+ const agent = new blink.Agent<
480
+ UIMessage<{
481
+ source: "github";
482
+ associated_id: string;
483
+ }>
484
+ >();
485
+
486
+ agent.on("request", async (request) => {
487
+ // comes from github, we want to do something deterministic in the chat loop with that ID...
488
+ // insert a message with that metadata into the chat
489
+ const chat = await agent.chat.upsert("some-github-key");
490
+ await agent.chat.sendMessages(request.chat.id, [
491
+ {
492
+ role: "user",
493
+ parts: [
494
+ {
495
+ type: "text",
496
+ text: "example",
497
+ },
498
+ ],
499
+ metadata: {
500
+ source: "github",
501
+ associated_id: "some-github-id",
502
+ },
503
+ },
504
+ ]);
505
+ });
506
+
507
+ agent.on("chat", async ({ messages }) => {
508
+ const message = messages.find(
509
+ (message) => message.metadata?.source === "github"
510
+ );
511
+
512
+ // Now we can use that metadata...
513
+ });
514
+ \`\`\`
515
+
516
+ The agent process can restart at any time, so all important state must be externalized.
517
+ </technical_knowledge>
518
+
519
+ <code_quality>
520
+
521
+ - Never use "as any" type assertions. Always figure out the correct typings.
522
+ </code_quality>
523
+ `,".env.local":`
524
+ # Store local environment variables here.
525
+ # They will be used by blink dev for development.
526
+ # EXTERNAL_SERVICE_API_KEY=
527
+ `,".env.production":`
528
+ # Store production environment variables here.
529
+ # They will be upserted as secrets on blink deploy.
530
+ # EXTERNAL_SERVICE_API_KEY=
531
+ `},"slack-bot":{"agent.ts":`import { convertToModelMessages, streamText } from "ai";
532
+ import * as blink from "blink";
533
+ import * as slack from "@blink-sdk/slack";
534
+ import { App } from "@slack/bolt";
535
+
536
+ const receiver = new slack.Receiver();
537
+ const app = new App({
538
+ token: process.env.SLACK_BOT_TOKEN,
539
+ signingSecret: process.env.SLACK_SIGNING_SECRET,
540
+ receiver,
541
+ });
542
+
543
+ // Triggered when the bot is @mentioned
544
+ app.event("app_mention", async ({ event }) => {
545
+ const chat = await agent.chat.upsert([
546
+ "slack",
547
+ event.channel,
548
+ event.thread_ts ?? event.ts,
549
+ ]);
550
+ const { message } = await slack.createMessageFromEvent({
551
+ client: app.client,
552
+ event,
553
+ });
554
+ await agent.chat.sendMessages(chat.id, [message]);
555
+ await app.client.assistant.threads.setStatus({
556
+ channel_id: event.channel,
557
+ status: "is typing...",
558
+ thread_ts: event.thread_ts ?? event.ts,
559
+ });
560
+ });
561
+
562
+ const agent = new blink.Agent();
563
+
564
+ agent.on("request", async (request) => {
565
+ return receiver.handle(app, request);
566
+ });
567
+
568
+ agent.on("chat", async ({ messages }) => {
569
+ const tools = slack.createTools({ client: app.client });
570
+ const lastMessage = messages[messages.length - 1];
571
+ const threadInfo = lastMessage?.metadata as
572
+ | { channel?: string; thread_ts?: string }
573
+ | undefined;
574
+
575
+ // Add instruction to clear status after completion
576
+ if (threadInfo?.channel && threadInfo?.thread_ts) {
577
+ const clonedMessages = structuredClone(messages);
578
+ const lastClonedMessage = clonedMessages[clonedMessages.length - 1];
579
+ if (lastClonedMessage) {
580
+ lastClonedMessage.parts.push({
581
+ type: "text",
582
+ text: \`*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${threadInfo.channel} thread_ts=\${threadInfo.thread_ts}\`,
583
+ });
584
+ }
585
+ messages = clonedMessages;
586
+ }
587
+
588
+ return streamText({
589
+ model: blink.model("anthropic/claude-sonnet-4.5"),
590
+ system: "You are a helpful Slack bot assistant.",
591
+ messages: convertToModelMessages(messages, {
592
+ ignoreIncompleteToolCalls: true,
593
+ tools,
594
+ }),
595
+ tools,
596
+ });
597
+ });
598
+
599
+ agent.serve();
600
+ `,"package.json":`{
601
+ "name": "{{name}}",
602
+ "main": "agent.ts",
603
+ "type": "module",
604
+ "private": true,
605
+ "scripts": {
606
+ "dev": "blink dev",
607
+ "deploy": "blink deploy"
608
+ },
609
+ "devDependencies": {
610
+ "zod": "latest",
611
+ "ai": "latest",
612
+ "blink": "latest",
613
+ "esbuild": "latest",
614
+ "@types/node": "latest",
615
+ "typescript": "latest",
616
+ "@slack/bolt": "latest",
617
+ "@blink-sdk/slack": "latest"
618
+ }
619
+ }
620
+ `,".gitignore":`# dependencies
621
+ node_modules
622
+
623
+ # config and build
624
+ data
625
+
626
+ # dotenv environment variables file
627
+ .env
628
+ .env.*
629
+
630
+ # Finder (MacOS) folder config
631
+ .DS_Store
632
+ `,"tsconfig.json":`{
633
+ "compilerOptions": {
634
+ "lib": ["ESNext"],
635
+ "target": "ESNext",
636
+ "module": "Preserve",
637
+ "moduleDetection": "force",
638
+
639
+ "moduleResolution": "bundler",
640
+ "allowImportingTsExtensions": true,
641
+ "verbatimModuleSyntax": true,
642
+ "resolveJsonModule": true,
643
+ "noEmit": true,
644
+
645
+ "strict": true,
646
+ "skipLibCheck": true,
647
+ "noFallthroughCasesInSwitch": true,
648
+ "noUncheckedIndexedAccess": true,
649
+ "noImplicitOverride": true,
650
+
651
+ "noUnusedLocals": false,
652
+ "noUnusedParameters": false,
653
+
654
+ "types": ["node"]
655
+ }
656
+ }
657
+ `,"AGENTS.md":`This project is a Blink agent.
658
+
659
+ You 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.
660
+
661
+ <communication>
662
+ 1. Be concise, direct, and to the point.
663
+ 2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
664
+ 3. NEVER use emojis unless the user explicitly asks for them.
665
+ 4. 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...".
666
+ 5. Mimic the style of the user's messages.
667
+ 6. Do not remind the user you are happy to help.
668
+ 7. Do not act with sycophantic flattery or over-the-top enthusiasm.
669
+ 8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
670
+ 9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
671
+ 10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
672
+ </communication>
673
+
674
+ <goals>
675
+ Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
676
+
677
+ You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
678
+
679
+ The user is _extremely happy_ to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
680
+
681
+ <example>
682
+ user: i want a coding agent
683
+ assistant: Let me take a look at your codebase...
684
+ ... tool calls to investigate the codebase...
685
+ assistant: 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.
686
+ </example>
687
+
688
+ Always investigate the current state of the agent before assisting the user.
689
+ </goals>
690
+
691
+ <agent_development>
692
+ Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
693
+
694
+ Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
695
+
696
+ Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
697
+
698
+ 1. _ALWAYS_ use the package manager the user is using (inferred from lock files or \`process.argv\`).
699
+ 2. You _MUST_ use \`agent.store\` to persist state. The agent process is designed to be stateless.
700
+ 3. 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.
701
+ 4. Use console.log for debugging. The console output appears for the user.
702
+ 5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
703
+ 6. 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.
704
+ 7. 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.
705
+
706
+ If the user is asking for a behavioral change, you should update the agent's system prompt.
707
+ This will not ensure the behavior, but it will guide the agent towards the desired behavior.
708
+ If the user needs 100% behavioral certainty, adjust tool behavior instead.
709
+ </agent_development>
710
+
711
+ <agent_web_requests>
712
+ Agents 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.
713
+
714
+ Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
715
+
716
+ To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
717
+ </agent_web_requests>
718
+
719
+ <technical_knowledge>
720
+ Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
721
+
722
+ \`\`\`typescript
723
+ import { convertToModelMessages, streamText } from "ai";
724
+ import * as blink from "blink";
725
+
726
+ const agent = new blink.Agent();
727
+
728
+ agent.on("chat", async ({ messages, chat, abortSignal }) => {
729
+ return streamText({
730
+ model: blink.model("anthropic/claude-sonnet-4.5"),
731
+ system: "You are a helpful assistant.",
732
+ messages: convertToModelMessages(messages, {
733
+ ignoreIncompleteToolCalls: true,
734
+ }),
735
+ tools: {
736
+ /* your tools */
737
+ },
738
+ });
739
+ });
740
+
741
+ agent.on("request", async (request) => {
742
+ // Handle webhooks, OAuth callbacks, etc.
743
+ });
744
+
745
+ agent.serve();
746
+ \`\`\`
747
+
748
+ Event Handlers:
749
+
750
+ **\`agent.on("chat", handler)\`**
751
+
752
+ 1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
753
+ 2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
754
+ 3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
755
+
756
+ _NEVER_ use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
757
+
758
+ **\`agent.on("request", handler)\`**
759
+ • Handles raw HTTP requests before Blink processes them
760
+ • Use for: OAuth callbacks, webhook verification, custom endpoints
761
+ • Return \`Response\` to handle, or \`void\` to pass through
762
+
763
+ **\`agent.on("ui", handler)\`**
764
+ • Provides dynamic UI options for chat interfaces
765
+ • Returns schema defining user-selectable options
766
+
767
+ **\`agent.on("error", handler)\`**
768
+ • Global error handler for the agent
769
+
770
+ Chat Management:
771
+
772
+ Blink automatically manages chat state:
773
+
774
+ \`\`\`typescript
775
+ // Create or get existing chat
776
+ // The parameter can be any JSON-serializable value.
777
+ // e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
778
+ const chat = await agent.chat.upsert("unique-key");
779
+
780
+ // Send a message to a chat
781
+ await agent.chat.sendMessages(
782
+ chat.id,
783
+ [
784
+ {
785
+ role: "user",
786
+ parts: [{ type: "text", text: "Message" }],
787
+ },
788
+ ],
789
+ {
790
+ behavior: "interrupt" | "enqueue" | "append",
791
+ }
792
+ );
793
+
794
+ // When sending messages, feel free to inject additional parts to direct the model.
795
+ // e.g. if the user is asking for specific behavior in specific scenarios, the simplest
796
+ // answer is to append a text part: "always do X when Y".
797
+ \`\`\`
798
+
799
+ Behaviors:
800
+ • "interrupt": Stop current processing and handle immediately
801
+ • "enqueue": Queue message, process when current chat finishes
802
+ • "append": Add to history without triggering processing
803
+
804
+ Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
805
+
806
+ Storage API:
807
+
808
+ Persistent key-value storage per agent:
809
+
810
+ \`\`\`typescript
811
+ // Store data
812
+ await agent.store.set("key", "value", { ttl: 3600 });
813
+
814
+ // Retrieve data
815
+ const value = await agent.store.get("key");
816
+
817
+ // Delete data
818
+ await agent.store.delete("key");
819
+
820
+ // List keys by prefix
821
+ const result = await agent.store.list("prefix-", { limit: 100 });
822
+ \`\`\`
823
+
824
+ Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
825
+
826
+ Tools:
827
+
828
+ Tools follow Vercel AI SDK patterns with Zod validation:
829
+
830
+ \`\`\`typescript
831
+ import { tool } from "ai";
832
+ import { z } from "zod";
833
+
834
+ const myTool = tool({
835
+ description: "Clear description of what this tool does",
836
+ inputSchema: z.object({
837
+ param: z.string().describe("Parameter description"),
838
+ }),
839
+ execute: async (args, opts) => {
840
+ // opts.abortSignal for cancellation
841
+ // opts.toolCallId for unique identification
842
+ return result;
843
+ },
844
+ });
845
+ \`\`\`
846
+
847
+ Tool Approvals for destructive operations:
848
+
849
+ \`\`\`typescript
850
+ ...await blink.tools.withApproval({
851
+ messages,
852
+ tools: {
853
+ delete_database: tool({ /* ... */ }),
854
+ },
855
+ })
856
+ \`\`\`
857
+
858
+ Tool Context for dependency injection:
859
+
860
+ \`\`\`typescript
861
+ ...blink.tools.withContext(github.tools, {
862
+ accessToken: process.env.GITHUB_TOKEN,
863
+ })
864
+ \`\`\`
865
+
866
+ Tool Prefixing to avoid collisions:
867
+
868
+ \`\`\`typescript
869
+ ...blink.tools.prefix(github.tools, "github_")
870
+ \`\`\`
871
+
872
+ LLM Models:
873
+
874
+ **Option 1: Blink Gateway** (Quick Start)
875
+
876
+ \`\`\`typescript
877
+ model: blink.model("anthropic/claude-sonnet-4.5");
878
+ model: blink.model("openai/gpt-5");
879
+ \`\`\`
880
+
881
+ Requires: \`blink login\` or \`BLINK_TOKEN\` env var
882
+
883
+ **Option 2: Direct Provider** (Production Recommended)
884
+
885
+ \`\`\`typescript
886
+ import { anthropic } from "@ai-sdk/anthropic";
887
+ import { openai } from "@ai-sdk/openai";
888
+
889
+ model: anthropic("claude-sonnet-4.5", {
890
+ apiKey: process.env.ANTHROPIC_API_KEY,
891
+ });
892
+ model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
893
+ \`\`\`
894
+
895
+ **Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
896
+
897
+ 1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
898
+ 2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
899
+ 3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
900
+
901
+ Available SDKs:
902
+
903
+ **@blink-sdk/compute**
904
+
905
+ \`\`\`typescript
906
+ import * as compute from "@blink-sdk/compute";
907
+
908
+ tools: {
909
+ ...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
910
+ }
911
+ \`\`\`
912
+
913
+ **@blink-sdk/github**
914
+
915
+ \`\`\`typescript
916
+ import * as github from "@blink-sdk/github";
917
+
918
+ tools: {
919
+ ...blink.tools.withContext(github.tools, {
920
+ accessToken: process.env.GITHUB_TOKEN,
921
+ }),
922
+ }
923
+ \`\`\`
924
+
925
+ **@blink-sdk/slack**
926
+
927
+ \`\`\`typescript
928
+ import * as slack from "@blink-sdk/slack";
929
+ import { App } from "@slack/bolt";
930
+
931
+ const receiver = new slack.Receiver();
932
+ const app = new App({
933
+ token: process.env.SLACK_BOT_TOKEN,
934
+ signingSecret: process.env.SLACK_SIGNING_SECRET,
935
+ receiver,
936
+ });
937
+
938
+ // This will trigger when the bot is @mentioned.
939
+ app.event("app_mention", async ({ event }) => {
940
+ // The argument here is a JSON-serializable value.
941
+ // To maintain the same chat context, use the same key.
942
+ const chat = await agent.chat.upsert([
943
+ "slack",
944
+ event.channel,
945
+ event.thread_ts ?? event.ts,
946
+ ]);
947
+ const { message } = await slack.createMessageFromEvent({
948
+ client: app.client,
949
+ event,
950
+ });
951
+ await agent.chat.sendMessages(chat.id, [message]);
952
+ // This is a nice immediate indicator for the user.
953
+ await app.client.assistant.threads.setStatus({
954
+ channel_id: event.channel,
955
+ status: "is typing...",
956
+ thread_ts: event.thread_ts ?? event.ts,
957
+ });
958
+ });
959
+
960
+ const agent = new blink.Agent();
961
+
962
+ agent.on("request", async (request) => {
963
+ return receiver.handle(app, request);
964
+ });
965
+
966
+ agent.on("chat", async ({ messages }) => {
967
+ const tools = slack.createTools({ client: app.client });
968
+ return streamText({
969
+ model: blink.model("anthropic/claude-sonnet-4.5"),
970
+ system: "You chatting with users in Slack.",
971
+ messages: convertToModelMessages(messages, {
972
+ ignoreIncompleteToolCalls: true,
973
+ tools,
974
+ }),
975
+ });
976
+ });
977
+ \`\`\`
978
+
979
+ Slack SDK Notes:
980
+
981
+ - "app_mention" event is triggered in both private channels and public channels.
982
+ - "message" event is triggered regardless of being mentioned or not, and will _also_ be fired when "app_mention" is triggered.
983
+ - _NEVER_ register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
984
+ - 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.
985
+ - 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}" })\`
986
+ - 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".
987
+
988
+ Slack App Manifest:
989
+
990
+ - _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.
991
+ - The user can always edit the manifest after creation, but you'd have to suggest it to them.
992
+ - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
993
+ - _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.
994
+ - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
995
+ - "app_mentions:read"
996
+ - "reactions:write"
997
+ - "reactions:read"
998
+ - "channels:history"
999
+ - "chat:write"
1000
+ - "groups:history"
1001
+ - "groups:read"
1002
+ - "files:read"
1003
+ - "im:history"
1004
+ - "im:read"
1005
+ - "im:write"
1006
+ - "mpim:history"
1007
+ - "mpim:read"
1008
+ - "users:read"
1009
+ - "links:read"
1010
+ - "commands"
1011
+ - For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
1012
+ - "app_mention"
1013
+ - "message.channels",
1014
+ - "message.groups",
1015
+ - "message.im",
1016
+ - "reaction_added"
1017
+ - "reaction_removed"
1018
+ - "assistant_thread_started"
1019
+ - "member_joined_channel"
1020
+ - _NEVER_ include USER SCOPES unless the user explicitly asks for them.
1021
+
1022
+ WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
1023
+
1024
+ **@blink-sdk/web-search**
1025
+
1026
+ \`\`\`typescript
1027
+ import * as webSearch from "@blink-sdk/web-search";
1028
+
1029
+ tools: {
1030
+ ...webSearch.tools,
1031
+ }
1032
+ \`\`\`
1033
+
1034
+ State Management:
1035
+
1036
+ Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
1037
+
1038
+ _NEVER_ use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
1039
+
1040
+ For global state persistence, you can use the agent store:
1041
+
1042
+ - Use \`agent.store\` for persistent key-value storage
1043
+ - Query external APIs to fetch current state
1044
+ - Use webhooks to trigger actions rather than polling in-memory state
1045
+
1046
+ For message-level state persistence, use message metadata:
1047
+
1048
+ \`\`\`typescript
1049
+ import { UIMessage } from "blink";
1050
+ import * as blink from "blink";
1051
+
1052
+ const agent = new blink.Agent<
1053
+ UIMessage<{
1054
+ source: "github";
1055
+ associated_id: string;
1056
+ }>
1057
+ >();
1058
+
1059
+ agent.on("request", async (request) => {
1060
+ // comes from github, we want to do something deterministic in the chat loop with that ID...
1061
+ // insert a message with that metadata into the chat
1062
+ const chat = await agent.chat.upsert("some-github-key");
1063
+ await agent.chat.sendMessages(request.chat.id, [
1064
+ {
1065
+ role: "user",
1066
+ parts: [
1067
+ {
1068
+ type: "text",
1069
+ text: "example",
1070
+ },
1071
+ ],
1072
+ metadata: {
1073
+ source: "github",
1074
+ associated_id: "some-github-id",
1075
+ },
1076
+ },
1077
+ ]);
1078
+ });
1079
+
1080
+ agent.on("chat", async ({ messages }) => {
1081
+ const message = messages.find(
1082
+ (message) => message.metadata?.source === "github"
1083
+ );
1084
+
1085
+ // Now we can use that metadata...
1086
+ });
1087
+ \`\`\`
1088
+
1089
+ The agent process can restart at any time, so all important state must be externalized.
1090
+ </technical_knowledge>
1091
+
1092
+ <code_quality>
1093
+
1094
+ - Never use "as any" type assertions. Always figure out the correct typings.
1095
+ </code_quality>
1096
+ `,".env.local":`
1097
+ # Store local environment variables here.
1098
+ # They will be used by blink dev for development.
1099
+ SLACK_BOT_TOKEN=xoxb-your-token-here
1100
+ SLACK_SIGNING_SECRET=your-signing-secret-here
1101
+ `,".env.production":`
1102
+ # Store production environment variables here.
1103
+ # They will be upserted as secrets on blink deploy.
1104
+ SLACK_BOT_TOKEN=
1105
+ SLACK_SIGNING_SECRET=
1106
+ `}};function p(e,t){let n=f[e],r={};for(let[e,i]of Object.entries(n))r[e]=i.replace(/\{\{name\}\}/g,t);return r}async function m(f){if(f||=process.cwd(),e(`Initializing a new Blink Agent`),(await l(f)).length>0){let e=await o({message:`Directory is not empty. Initialize anyway?`});(e===!1||r(e))&&(a(`Initialization cancelled.`),process.exit(1))}let m=await i({options:[{label:`Scratch`,value:`scratch`,hint:`Basic agent with example tool`},{label:`Slack Bot`,value:`slack-bot`,hint:`Pre-configured Slack bot`}],message:`Which template do you want to use?`});r(m)&&(a(`Initialization cancelled.`),process.exit(1));let h=m,g=s(f).replace(/[^a-zA-Z0-9]/g,`-`),_;if(process.env.npm_config_user_agent?.includes(`bun/`)?_=`bun`:process.env.npm_config_user_agent?.includes(`pnpm/`)?_=`pnpm`:process.env.npm_config_user_agent?.includes(`yarn/`)?_=`yarn`:process.env.npm_config_user_agent?.includes(`npm/`)&&(_=`npm`),!_){let e=await i({options:[{label:`Bun`,value:`bun`},{label:`NPM`,value:`npm`},{label:`PNPM`,value:`pnpm`},{label:`Yarn`,value:`yarn`}],message:`What package manager do you want to use?`});r(e)&&process.exit(0),_=e}t.info(`Using ${_} as the package manager.`);let v=p(h,g);await Promise.all(Object.entries(v).map(async([e,t])=>{await u(c(f,e),t)})),console.log(``);let y=d(_,[`install`],{stdio:`inherit`,cwd:f});await new Promise((e,t)=>{y.on(`close`,t=>{t===0&&e(void 0)}),y.on(`error`,e=>{t(e)})}),console.log(``);let b={bun:`bun run dev`,npm:`npm run dev`,pnpm:`pnpm run dev`,yarn:`yarn dev`}[_];t.success(`To get started, run:
1107
+
1108
+ ${b??`blink dev`}`),n(`Edit agent.ts to hot-reload your agent.`)}export{m as init};