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.
@@ -1,4 +1,4 @@
1
- import { ID, UIOptions, UIOptionsSchema } from "../index.node-UFiKZRHB.cjs";
1
+ import { ID, UIOptions, UIOptionsSchema } from "../index.node-B6plkLLA.cjs";
2
2
  import { BuildLog, BuildResult } from "../index-DlWgNLmT.cjs";
3
3
  import { UIMessage, UIMessageChunk } from "ai";
4
4
 
@@ -1,4 +1,4 @@
1
- import { ID, UIOptions, UIOptionsSchema } from "../index.node-CiqENj_g.js";
1
+ import { ID, UIOptions, UIOptionsSchema } from "../index.node-qJt_7e9E.js";
2
2
  import { BuildLog, BuildResult } from "../index-C28Wm0bG.js";
3
3
  import { UIMessage, UIMessageChunk } from "ai";
4
4
 
@@ -269,411 +269,4 @@ Slack:
269
269
  1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
270
270
  2. Use the \`message_user_agent\` tool to test the agent after you make changes.
271
271
  </agent_development>
272
- `});let p=`This project is a Blink agent.
273
-
274
- 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.
275
-
276
- <communication>
277
- 1. Be concise, direct, and to the point.
278
- 2. You are communicating via a terminal interface, so avoid verbosity, preambles, postambles, and unnecessary whitespace.
279
- 3. NEVER use emojis unless the user explicitly asks for them.
280
- 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...".
281
- 5. Mimic the style of the user's messages.
282
- 6. Do not remind the user you are happy to help.
283
- 7. Do not act with sycophantic flattery or over-the-top enthusiasm.
284
- 8. Do not regurgitate tool output. e.g. if a command succeeds, acknowledge briefly (e.g. "Done" or "Formatted").
285
- 9. *NEVER* create markdown files for the user - *always* guide the user through your efforts.
286
- 10. *NEVER* create example scripts for the user, or examples scripts for you to run. Leverage your tools to accomplish the user's goals.
287
- </communication>
288
-
289
- <goals>
290
- Your method of assisting the user is by iterating their agent using the context provided by the user in run mode.
291
-
292
- You can obtain additional context by leveraging web search and compute tools to read files, run commands, and search the web.
293
-
294
- The user is *extremely happy* to provide additional context. They prefer this over you guessing, and then potentially getting it wrong.
295
-
296
- <example>
297
- user: i want a coding agent
298
- assistant: Let me take a look at your codebase...
299
- ... tool calls to investigate the codebase...
300
- 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.
301
- </example>
302
-
303
- Always investigate the current state of the agent before assisting the user.
304
- </goals>
305
-
306
- <agent_development>
307
- Agents are written in TypeScript, and mostly stored in a single \`agent.ts\` file. Complex agents will have multiple files, like a proper codebase.
308
-
309
- Environment variables are stored in \`.env.local\` and \`.env.production\`. \`blink dev\` will hot-reload environment variable changes in \`.env.local\`.
310
-
311
- Changes to the agent are hot-reloaded. As you make edits, the user can immediately try them in run mode.
312
-
313
- 1. *ALWAYS* use the package manager the user is using (inferred from lock files or \`process.argv\`).
314
- 2. You *MUST* use \`agent.store\` to persist state. The agent process is designed to be stateless.
315
- 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.
316
- 4. Use console.log for debugging. The console output appears for the user.
317
- 5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
318
- 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.
319
- 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.
320
-
321
- If the user is asking for a behavioral change, you should update the agent's system prompt.
322
- This will not ensure the behavior, but it will guide the agent towards the desired behavior.
323
- If the user needs 100% behavioral certainty, adjust tool behavior instead.
324
- </agent_development>
325
-
326
- <agent_web_requests>
327
- 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.
328
-
329
- Blink automatically creates a reverse-tunnel to your local machine for simple local development with external services (think Slack Bot, GitHub Bot, etc.).
330
-
331
- To trigger chats based on web requests, use the \`agent.chat.upsert\` and \`agent.chat.message\` APIs.
332
- </agent_web_requests>
333
-
334
- <technical_knowledge>
335
- Blink agents are Node.js HTTP servers built on the Vercel AI SDK:
336
-
337
- \`\`\`typescript
338
- import { convertToModelMessages, streamText } from "ai";
339
- import * as blink from "blink";
340
-
341
- const agent = new blink.Agent();
342
-
343
- agent.on("chat", async ({ messages, chat, abortSignal }) => {
344
- return streamText({
345
- model: blink.model("anthropic/claude-sonnet-4.5"),
346
- system: "You are a helpful assistant.",
347
- messages: convertToModelMessages(messages, {
348
- ignoreIncompleteToolCalls: true,
349
- }),
350
- tools: { /* your tools */ },
351
- });
352
- });
353
-
354
- agent.on("request", async (request) => {
355
- // Handle webhooks, OAuth callbacks, etc.
356
- });
357
-
358
- agent.serve();
359
- \`\`\`
360
-
361
- Event Handlers:
362
-
363
- **\`agent.on("chat", handler)\`**
364
- 1. Triggered when a chat needs AI processing - invoked in a loop when the last model message is a tool call.
365
- 2. Must return: \`streamText()\` result, \`Response\`, \`ReadableStream<UIMessageChunk>\`, or \`void\`
366
- 3. Parameters: \`messages\`, \`id\`, \`abortSignal\`
367
-
368
- *NEVER* use "maxSteps" from the Vercel AI SDK. It is unnecessary and will cause a worse experience for the user.
369
-
370
- **\`agent.on("request", handler)\`**
371
- • Handles raw HTTP requests before Blink processes them
372
- • Use for: OAuth callbacks, webhook verification, custom endpoints
373
- • Return \`Response\` to handle, or \`void\` to pass through
374
-
375
- **\`agent.on("ui", handler)\`**
376
- • Provides dynamic UI options for chat interfaces
377
- • Returns schema defining user-selectable options
378
-
379
- **\`agent.on("error", handler)\`**
380
- • Global error handler for the agent
381
-
382
- Chat Management:
383
-
384
- Blink automatically manages chat state:
385
-
386
- \`\`\`typescript
387
- // Create or get existing chat
388
- // The parameter can be any JSON-serializable value.
389
- // e.g. for a Slack bot to preserve context in a thread, you might use: ["slack", teamId, channelId, threadTs]
390
- const chat = await agent.chat.upsert("unique-key");
391
-
392
- // Send a message to a chat
393
- await agent.chat.sendMessages(chat.id, [{
394
- role: "user",
395
- parts: [{ type: "text", text: "Message" }],
396
- }], {
397
- behavior: "interrupt" | "enqueue" | "append"
398
- });
399
-
400
- // When sending messages, feel free to inject additional parts to direct the model.
401
- // e.g. if the user is asking for specific behavior in specific scenarios, the simplest
402
- // answer is to append a text part: "always do X when Y".
403
- \`\`\`
404
-
405
- Behaviors:
406
- • "interrupt": Stop current processing and handle immediately
407
- • "enqueue": Queue message, process when current chat finishes
408
- • "append": Add to history without triggering processing
409
-
410
- Chat keys: Use structured keys like \`"slack-\${teamId}-\${channelId}-\${threadTs}"\` for uniqueness.
411
-
412
- Storage API:
413
-
414
- Persistent key-value storage per agent:
415
-
416
- \`\`\`typescript
417
- // Store data
418
- await agent.store.set("key", "value", { ttl: 3600 });
419
-
420
- // Retrieve data
421
- const value = await agent.store.get("key");
422
-
423
- // Delete data
424
- await agent.store.delete("key");
425
-
426
- // List keys by prefix
427
- const result = await agent.store.list("prefix-", { limit: 100 });
428
- \`\`\`
429
-
430
- Common uses: OAuth tokens, user preferences, caching, chat-resource associations.
431
-
432
- Tools:
433
-
434
- Tools follow Vercel AI SDK patterns with Zod validation:
435
-
436
- \`\`\`typescript
437
- import { tool } from "ai";
438
- import { z } from "zod";
439
-
440
- const myTool = tool({
441
- description: "Clear description of what this tool does",
442
- inputSchema: z.object({
443
- param: z.string().describe("Parameter description"),
444
- }),
445
- execute: async (args, opts) => {
446
- // opts.abortSignal for cancellation
447
- // opts.toolCallId for unique identification
448
- return result;
449
- },
450
- });
451
- \`\`\`
452
-
453
- Tool Approvals for destructive operations:
454
-
455
- \`\`\`typescript
456
- ...await blink.tools.withApproval({
457
- messages,
458
- tools: {
459
- delete_database: tool({ /* ... */ }),
460
- },
461
- })
462
- \`\`\`
463
-
464
- Tool Context for dependency injection:
465
-
466
- \`\`\`typescript
467
- ...blink.tools.withContext(github.tools, {
468
- accessToken: process.env.GITHUB_TOKEN,
469
- })
470
- \`\`\`
471
-
472
- Tool Prefixing to avoid collisions:
473
-
474
- \`\`\`typescript
475
- ...blink.tools.prefix(github.tools, "github_")
476
- \`\`\`
477
-
478
- LLM Models:
479
-
480
- **Option 1: Blink Gateway** (Quick Start)
481
- \`\`\`typescript
482
- model: blink.model("anthropic/claude-sonnet-4.5")
483
- model: blink.model("openai/gpt-5")
484
- \`\`\`
485
- Requires: \`blink login\` or \`BLINK_TOKEN\` env var
486
-
487
- **Option 2: Direct Provider** (Production Recommended)
488
- \`\`\`typescript
489
- import { anthropic } from "@ai-sdk/anthropic";
490
- import { openai } from "@ai-sdk/openai";
491
-
492
- model: anthropic("claude-sonnet-4.5", { apiKey: process.env.ANTHROPIC_API_KEY })
493
- model: openai("gpt-5", { apiKey: process.env.OPENAI_API_KEY })
494
- \`\`\`
495
-
496
- **Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
497
- 1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
498
- 2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
499
- 3. Otherwise: falls back to \`blink.model("anthropic/claude-sonnet-4.5")\`
500
-
501
- Available SDKs:
502
-
503
- **@blink-sdk/compute**
504
- \`\`\`typescript
505
- import * as compute from "@blink-sdk/compute";
506
-
507
- tools: {
508
- ...compute.tools, // execute_bash, read_file, write_file, edit_file, process management
509
- }
510
- \`\`\`
511
-
512
- **@blink-sdk/github**
513
- \`\`\`typescript
514
- import * as github from "@blink-sdk/github";
515
-
516
- tools: {
517
- ...blink.tools.withContext(github.tools, {
518
- accessToken: process.env.GITHUB_TOKEN,
519
- }),
520
- }
521
- \`\`\`
522
-
523
- **@blink-sdk/slack**
524
- \`\`\`typescript
525
- import * as slack from "@blink-sdk/slack";
526
- import { App } from "@slack/bolt";
527
-
528
- const receiver = new slack.Receiver();
529
- const app = new App({
530
- token: process.env.SLACK_BOT_TOKEN,
531
- signingSecret: process.env.SLACK_SIGNING_SECRET,
532
- receiver,
533
- })
534
-
535
- // This will trigger when the bot is @mentioned.
536
- app.event("app_mention", async ({ event }) => {
537
- // The argument here is a JSON-serializable value.
538
- // To maintain the same chat context, use the same key.
539
- const chat = await agent.chat.upsert([
540
- "slack",
541
- event.channel,
542
- event.thread_ts ?? event.ts,
543
- ]);
544
- const { message } = await slack.createMessageFromEvent({
545
- client: app.client,
546
- event,
547
- });
548
- await agent.chat.sendMessages(chat.id, [message]);
549
- // This is a nice immediate indicator for the user.
550
- await app.client.assistant.threads.setStatus({
551
- channel_id: event.channel,
552
- status: "is typing...",
553
- thread_ts: event.thread_ts ?? event.ts,
554
- })
555
- })
556
-
557
- const agent = new blink.Agent();
558
-
559
- agent.on("request", async (request) => {
560
- return receiver.handle(app, request);
561
- });
562
-
563
- agent.on("chat", async ({ messages }) => {
564
- const tools = slack.createTools({ client: app.client });
565
- return streamText({
566
- model: blink.model("anthropic/claude-sonnet-4.5"),
567
- system: "You chatting with users in Slack.",
568
- messages: convertToModelMessages(messages, {
569
- ignoreIncompleteToolCalls: true,
570
- tools,
571
- }),
572
- });
573
- })
574
- \`\`\`
575
-
576
- Slack SDK Notes:
577
- - "app_mention" event is triggered in both private channels and public channels.
578
- - "message" event is triggered regardless of being mentioned or not, and will *also* be fired when "app_mention" is triggered.
579
- - *NEVER* register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
580
- - 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.
581
- - 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}" })\`
582
- - 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".
583
-
584
- Slack App Manifest:
585
- - *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.
586
- - The user can always edit the manifest after creation, but you'd have to suggest it to them.
587
- - "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
588
- - *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.
589
- - For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
590
- - "app_mentions:read"
591
- - "reactions:write"
592
- - "reactions:read"
593
- - "channels:history"
594
- - "chat:write"
595
- - "groups:history"
596
- - "groups:read"
597
- - "files:read"
598
- - "im:history"
599
- - "im:read"
600
- - "im:write"
601
- - "mpim:history"
602
- - "mpim:read"
603
- - "users:read"
604
- - "links:read"
605
- - "commands"
606
- - For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
607
- - "app_mention"
608
- - "message.channels",
609
- - "message.groups",
610
- - "message.im",
611
- - "reaction_added"
612
- - "reaction_removed"
613
- - "assistant_thread_started"
614
- - "member_joined_channel"
615
- - *NEVER* include USER SCOPES unless the user explicitly asks for them.
616
-
617
- WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
618
-
619
- **@blink-sdk/web-search**
620
- \`\`\`typescript
621
- import * as webSearch from "@blink-sdk/web-search";
622
-
623
- tools: {
624
- ...webSearch.tools,
625
- }
626
- \`\`\`
627
-
628
- State Management:
629
-
630
- Blink agents are short-lived HTTP servers that restart on code changes and do not persist in-memory state between requests.
631
-
632
- *NEVER* use module-level Maps, Sets, or variables to store state (e.g. \`const activeBots = new Map()\`).
633
-
634
- For global state persistence, you can use the agent store:
635
- - Use \`agent.store\` for persistent key-value storage
636
- - Query external APIs to fetch current state
637
- - Use webhooks to trigger actions rather than polling in-memory state
638
-
639
- For message-level state persistence, use message metadata:
640
- \`\`\`typescript
641
- import { UIMessage } from "blink";
642
- import * as blink from "blink";
643
-
644
- const agent = new blink.Agent<UIMessage<{
645
- source: "github";
646
- associated_id: string;
647
- }>>();
648
-
649
- agent.on("request", async (request) => {
650
- // comes from github, we want to do something deterministic in the chat loop with that ID...
651
- // insert a message with that metadata into the chat
652
- const chat = await agent.chat.upsert("some-github-key");
653
- await agent.chat.sendMessages(request.chat.id, [{
654
- role: "user",
655
- parts: [{
656
- type: "text",
657
- text: "example",
658
- }],
659
- metadata: {
660
- source: "github",
661
- associated_id: "some-github-id",
662
- }
663
- }])
664
- })
665
-
666
- agent.on("chat", async ({ messages }) => {
667
- const message = messages.find(message => message.metadata?.source === "github")
668
-
669
- // Now we can use that metadata...
670
- })
671
- \`\`\`
672
-
673
- The agent process can restart at any time, so all important state must be externalized.
674
- </technical_knowledge>
675
-
676
- <code_quality>
677
- - Never use "as any" type assertions. Always figure out the correct typings.
678
- </code_quality>
679
- `;try{p=await me(oe(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),Ie({model:t_(e.token),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function t_(e){return process.env.ANTHROPIC_API_KEY?Gt({apiKey:process.env.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`):process.env.OPENAI_API_KEY?wi({apiKey:process.env.OPENAI_API_KEY}).responses(`gpt-5`):ne(`anthropic/claude-sonnet-4.5`,{token:e})}function n_(e){let[t,n]=K(void 0),[r,i]=K(void 0),a=Ve(void 0);return G(()=>{let t=new AbortController,r=!1;return i(void 0),n(void 0),(async()=>{a.current=e_({directory:e.directory,token:e.token,getDevhookUrl:e.getDevhookUrl});let r=await r_(),i=a.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}a.current?.cleanup()});let o=new Xi({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(o)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.token,e.getDevhookUrl]),Be(()=>({client:t,error:r,setUserAgentUrl:e=>{a.current?.setUserAgentUrl(e)}}),[t,r])}async function r_(){let e=Me();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function i_(e){let{directory:t}=e,[n,r]=K(),[i,a]=K(!1),[o,s]=K(`run`),c=Ve(`run`);G(()=>{c.current=o},[o]);let l=ze(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=ze(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=El({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=Tl({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=Iu(t),_=Be(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=Ve(void 0);G(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=Ve(void 0),b=Be(()=>ku({port:0,dataDirectory:oe(t,`data`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=Zi({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:E,setUserAgentUrl:D}=n_({directory:t,apiServerUrl:b.url,token:h.token,getDevhookUrl:ze(()=>{let e=au(t)??ou(t);return ne(e),`https://${e}.blink.host`},[t])}),[O,k]=K(`00000000-0000-0000-0000-000000000000`);G(()=>{y.current=x},[x]),G(()=>{x&&D(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(O)?.stopStreaming()},[x,T,o,O,b,D]);let A=Ve(void 0),j=ru({chatId:O,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&A.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:A.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(tu(e.metadata)||e.mode===`edit`)}),N=Ve(0);G(()=>{if(S.length===N.current)return;let t=N.current;for(let n of S.slice(t))e.onAgentLog?.(n);N.current=S.length},[S,e.onAgentLog,j.upsertMessage]);let[P,ee]=K([]);G(()=>{b.listChats().then(e=>{ee(e.map(e=>e.key))})},[b]),G(()=>{O&&!P.includes(O)&&ee(e=>[...e,O])},[O,P]);let[te,ne]=K(()=>au(t)),F=Mu({id:te,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});G(()=>{F.status!==`connected`||!F.url||e.onDevhookConnected?.(F.url)},[F.status,F.url]);let{schema:I,options:L,error:R,setOption:z}=Au({agent:o===`run`?x:T,capabilities:w,messages:j.messages});G(()=>{A.current=L},[L]);let re=Be(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),E&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${E.message}`),j.error&&f!==`building`&&e.set(`chat`,`Chat error: ${j.error}`),R&&e.set(`options`,`Options error: ${R.message}`),e},[C,E,j.error,R,o,f]),B=Ve(new Map);G(()=>{let t=B.current,n=re;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);B.current=new Map(n)},[re,e.onError]);let V=Be(()=>{let e=[...j.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||n===e.id)return;let t=e.parts.filter(Pe);if(t.length!==0&&t.some(e=>M(e.output)&&e.output.outcome===`pending`))return e},[j.messages,n]),H=ze(async(e,t)=>{if(!V)return;t&&e&&a(!0),r(V.id);let n=j.messages;if(n.length===0)return;let i=n[n.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&M(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await j.upsertMessage({...i,parts:o}),await j.start()},[V,j]);G(()=>{i&&V&&H(!0)},[i,V,H]);let ie=ze(()=>{let e=crypto.randomUUID();k(e),ee(t=>[...t,e]),r(void 0)},[]),ae=ze(e=>{k(e),r(void 0)},[]),se=Be(()=>{if(V)return{message:V,approve:e=>H(!0,e),reject:()=>H(!1),autoApproveEnabled:i}},[V,H,i]),ce=Be(()=>{let e=j.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[j.messages]),le=Be(()=>{if(j.status!==`streaming`)return!1;if(!j.streamingMessage)return!0;let e=j.streamingMessage.parts.filter(Pe);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[j.status,j.streamingMessage]);return{mode:o,setMode:l,toggleMode:u,chat:j,chats:P,switchChat:ae,newChat:ie,build:{status:f,error:d,entrypoint:m},devhook:{connected:F.status===`connected`,url:F.status===`connected`?F.url:void 0},capabilities:w,options:{schema:I,selected:L,error:R,setOption:z},approval:se,tokenUsage:ce,auth:h,server:b,showWaitingPlaceholder:le}}export{Zi as useAgent,Tl as useAuth,El as useBundler,ru as useChat,i_ as useDevMode,Mu as useDevhook,Iu as useDotenv,n_ as useEditAgent,Au as useOptions};
272
+ `});let p=agentsMD;try{p=await me(oe(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),Ie({model:t_(e.token),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function t_(e){return process.env.ANTHROPIC_API_KEY?Gt({apiKey:process.env.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`):process.env.OPENAI_API_KEY?wi({apiKey:process.env.OPENAI_API_KEY}).responses(`gpt-5`):ne(`anthropic/claude-sonnet-4.5`,{token:e})}function n_(e){let[t,n]=K(void 0),[r,i]=K(void 0),a=Ve(void 0);return G(()=>{let t=new AbortController,r=!1;return i(void 0),n(void 0),(async()=>{a.current=e_({directory:e.directory,token:e.token,getDevhookUrl:e.getDevhookUrl});let r=await r_(),i=a.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}a.current?.cleanup()});let o=new Xi({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(o)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.token,e.getDevhookUrl]),Be(()=>({client:t,error:r,setUserAgentUrl:e=>{a.current?.setUserAgentUrl(e)}}),[t,r])}async function r_(){let e=Me();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function i_(e){let{directory:t}=e,[n,r]=K(),[i,a]=K(!1),[o,s]=K(`run`),c=Ve(`run`);G(()=>{c.current=o},[o]);let l=ze(t=>{s(t),e.onModeChange?.(t),r(void 0)},[e.onModeChange]),u=ze(()=>{l(o===`run`?`edit`:`run`)},[o,l]),{error:d,status:f,result:p,entry:m}=El({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),h=Tl({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),g=Iu(t),_=Be(()=>{let e=h.token;return e?{...g,BLINK_TOKEN:e}:g},[g,h.token]),v=Ve(void 0);G(()=>{let t=Object.keys(_);if(t.length===v.current||v.current===void 0){v.current=t.length;return}v.current=t.length,e.onEnvLoaded?.(t)},[_,e.onEnvLoaded]);let y=Ve(void 0),b=Be(()=>ku({port:0,dataDirectory:oe(t,`data`),getAgent:()=>y.current}),[t]),{agent:x,logs:S,error:C,capabilities:w}=Zi({buildResult:p,env:_,apiServerUrl:b.url}),{client:T,error:E,setUserAgentUrl:D}=n_({directory:t,apiServerUrl:b.url,token:h.token,getDevhookUrl:ze(()=>{let e=au(t)??ou(t);return ne(e),`https://${e}.blink.host`},[t])}),[O,k]=K(`00000000-0000-0000-0000-000000000000`);G(()=>{y.current=x},[x]),G(()=>{x&&D(x.baseUrl),(o===`run`&&!x||o===`edit`&&!T)&&b.getChatManager(O)?.stopStreaming()},[x,T,o,O,b,D]);let A=Ve(void 0),j=ru({chatId:O,agent:o===`run`?x:T,chatsDirectory:b.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&A.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:A.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=c.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:c.current,metadata:t}},filterMessages:e=>c.current===`edit`?!0:!(tu(e.metadata)||e.mode===`edit`)}),N=Ve(0);G(()=>{if(S.length===N.current)return;let t=N.current;for(let n of S.slice(t))e.onAgentLog?.(n);N.current=S.length},[S,e.onAgentLog,j.upsertMessage]);let[P,ee]=K([]);G(()=>{b.listChats().then(e=>{ee(e.map(e=>e.key))})},[b]),G(()=>{O&&!P.includes(O)&&ee(e=>[...e,O])},[O,P]);let[te,ne]=K(()=>au(t)),F=Mu({id:te,directory:t,disabled:!w?.request,onRequest:async t=>{if(!x)throw Error(`No agent`);let n=new URL(t.url),r=new URL(x.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});G(()=>{F.status!==`connected`||!F.url||e.onDevhookConnected?.(F.url)},[F.status,F.url]);let{schema:I,options:L,error:R,setOption:z}=Au({agent:o===`run`?x:T,capabilities:w,messages:j.messages});G(()=>{A.current=L},[L]);let re=Be(()=>{let e=new Map;return C&&o===`run`&&e.set(`agent`,C.message),E&&o===`edit`&&e.set(`editAgent`,`Edit agent error: ${E.message}`),j.error&&f!==`building`&&e.set(`chat`,`Chat error: ${j.error}`),R&&e.set(`options`,`Options error: ${R.message}`),e},[C,E,j.error,R,o,f]),B=Ve(new Map);G(()=>{let t=B.current,n=re;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);B.current=new Map(n)},[re,e.onError]);let V=Be(()=>{let e=[...j.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||n===e.id)return;let t=e.parts.filter(Pe);if(t.length!==0&&t.some(e=>M(e.output)&&e.output.outcome===`pending`))return e},[j.messages,n]),H=ze(async(e,t)=>{if(!V)return;t&&e&&a(!0),r(V.id);let n=j.messages;if(n.length===0)return;let i=n[n.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&M(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await j.upsertMessage({...i,parts:o}),await j.start()},[V,j]);G(()=>{i&&V&&H(!0)},[i,V,H]);let ie=ze(()=>{let e=crypto.randomUUID();k(e),ee(t=>[...t,e]),r(void 0)},[]),ae=ze(e=>{k(e),r(void 0)},[]),se=Be(()=>{if(V)return{message:V,approve:e=>H(!0,e),reject:()=>H(!1),autoApproveEnabled:i}},[V,H,i]),ce=Be(()=>{let e=j.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[j.messages]),le=Be(()=>{if(j.status!==`streaming`)return!1;if(!j.streamingMessage)return!0;let e=j.streamingMessage.parts.filter(Pe);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[j.status,j.streamingMessage]);return{mode:o,setMode:l,toggleMode:u,chat:j,chats:P,switchChat:ae,newChat:ie,build:{status:f,error:d,entrypoint:m},devhook:{connected:F.status===`connected`,url:F.status===`connected`?F.url:void 0},capabilities:w,options:{schema:I,selected:L,error:R,setOption:z},approval:se,tokenUsage:ce,auth:h,server:b,showWaitingPlaceholder:le}}export{Zi as useAgent,Tl as useAuth,El as useBundler,ru as useChat,i_ as useDevMode,Mu as useDevhook,Iu as useDotenv,n_ as useEditAgent,Au as useOptions};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "1.1.10",
3
+ "version": "1.1.12",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {