Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

trigger-authoring-chat-agent

БесплатноБез исполняемых скриптовНе проверен

Author and run a durable AI chat agent with chat.agent from @trigger.dev/sdk/ai: the per-turn run loop, why you MUST take streamText from the run argument…

triggerdotdevот triggerdotdev★ 36 звёзд на GitHub

Об этом скилле

Authoring a chat agent

A chat.agent runs an entire conversation as one long-lived Trigger.dev task. It wakes when a message arrives, freezes when none do, and in-memory state survives page refreshes, deploys, idle gaps, and crashes. Your code is the loop you would write anyway: messages in, streamText out. There are no API routes. The frontend talks to the agent through a TriggerChatTransport, so history accumulates server-side and the client ships only the new message each turn.

Works with Vercel AI SDK v5, v6, or v7. On v7 also install @ai-sdk/otel so model calls are traced (the SDK registers it for you).

Setup

Three pieces: the agent task, two server actions, and the frontend transport.

1. Define the agent

import { chat } from "@trigger.dev/sdk/ai";
import { streamText, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

export const myChat = chat.agent({
  id: "my-chat",
  // `streamText` below is the SDK's, from the run argument. See "Common mistakes".
  run: async ({ messages, signal, streamText }) =>
    streamText({
      model: anthropic("claude-sonnet-5-5"),
      messages,
      abortSignal: signal,
      stopWhen: stepCountIs(15),
    }),
});

run receives messages already converted to ModelMessage[] (the SDK converts the frontend's UIMessage[] for you) plus a signal that aborts on stop or cancel. Returning the StreamTextResult auto-pipes it to the frontend.

2. Add two server actions

Both run on your server, so the browser never holds your environment secret key. This is also where per-user / per-plan authorization and any paired DB writes live.

"use server";
import { auth } from "@trigger.dev/sdk";
import { chat } from "@trigger.dev/sdk/ai";

// Creates the Session + first run, returns a session PAT. Idempotent on (env, chatId).
export const startChatSession = chat.createStartSessionAction("my-chat");

// Pure mint. The transport calls this on 401/403 to refresh an expired token.
export async function mintChatAccessToken(chatId: string) {
  return auth.createPublicToken({
    scopes: { read: { sessions: chatId }, write: { sessions: chatId } },
    expirationTime: "1h",
  });
}

3. Wire the frontend

"use client";
import { useState } from "react";
import { useChat } from "@ai-sdk/react";
import { useTriggerChatTransport } from "@trigger.dev/sdk/chat/react";
import type { myChat } from "@/trigger/chat";
import { mintChatAccessToken, startChatSession } from "@/app/actions";

export function Chat() {
  const transport = useTriggerChatTransport<typeof myChat>({
    task: "my-chat", // typeof myChat gives compile-time task-id validation
    accessToken: ({ chatId }) => mintChatAccessToken(chatId),
    startSession: ({ chatId, clientData }) => startChatSession({ chatId, clientData }),
  });

  const { messages, sendMessage, stop, status } = useChat({ transport });
  const [input, setInput] = useState("");
  // render messages, a form that calls sendMessage({ text: input }),
  // and a Stop button (onClick={stop}) while status === "streaming".
}

The transport is memoized (created once, reused across renders). Passing typeof myChat flows the agent's message type through useChat.

Core patterns

1. Return vs pipe

Return the streamText result from run for the simple case. When streamText is called deep inside nested helpers, call await chat.pipe(result) from anywhere in the task instead, and let run resolve void.

import { chat, type ChatStreamText } from "@trigger.dev/sdk/ai";
import { anthropic } from "@ai-sdk/anthropic";
import type { ModelMessage } from "ai";

export const agentChat = chat.agent({
  id: "agent-chat",
  run: async ({ messages, streamText }) => {
    await runAgentLoop(messages, streamText); // don't return; pipe inside
  },
});

// A loop factored out of `run` takes `streamText` as an argument, so it keeps the
// managed options. `ChatStreamText` (from `@trigger.dev/sdk/ai`) types the parameter.
// `chat.toStreamTextOptions()` is the alternative when threading it down is impractical.
async function runAgentLoop(messages: ModelMessage[], streamText: ChatStreamText) {
  const result = streamText({
    model: anthropic("claude-sonnet-5-5"),
    messages,
  });
  await chat.pipe(result); // works from anywhere in the task
}

2. Typed tools (declare on config AND pass back)

Declare tools on chat.agent({ tools }), read them back typed from the run() payload, and pass that set as tools. One declaration flows everywhere.

import { tool, stepCountIs } from "ai";
import { z } from "zod";

const tools = {
  searchDocs: tool({
    description: "Search the docs.",
    inputSchema: z.object({ query: z.string() }),
    execute: async ({ query }) => searchIndex(query),
  }),
};

export const myChat = chat.agent({
  id: "my-chat",
  tools, // so toModelOutput survives across turns
  run: async ({ mess
Полный SKILL.md на GitHub

Установить trigger-authoring-chat-agent в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл trigger-authoring-chat-agent?

Author and run a durable AI chat agent with chat.agent from @trigger.dev/sdk/ai: the per-turn run loop, why you MUST take streamText from the run argument rather than importing it from ai, returning a StreamTextResult vs calling chat.pipe(), the two server actions (chat.createStartSessionAction + auth.createPublicToken), and wiring useChat to useTriggerChatTransport. Load this when building, modifying, or debugging a chat backend (the agent task or its lifecycle hooks) or its React transport, when declaring typed tools or custom data parts, or when migrating a plain AI SDK streamText route to chat.agent.

Как установить скилл trigger-authoring-chat-agent?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл trigger-authoring-chat-agent запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить trigger-authoring-chat-agent с