Skip to content

Commit a7a672d

Browse files
jackbridgerTrigger.dev RepoOps
authored andcommitted
docs: fix code samples that throw when run
Mono-RevId: 2740c307c742e4fa55732efb5c881454b1145428
1 parent 079df3a commit a7a672d

18 files changed

Lines changed: 137 additions & 64 deletions

‎docs/ai-chat/background-injection.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export const myChat = chat.agent({
5050
},
5151
run: async ({ messages, signal, streamText }) => {
5252
return streamText({
53+
model: anthropic("claude-sonnet-5-5"),
5354
messages,
5455
abortSignal: signal,
5556
stopWhen: stepCountIs(15),
@@ -144,6 +145,7 @@ export const myChat = chat.agent({
144145
},
145146
run: async ({ messages, signal, streamText }) => {
146147
return streamText({
148+
model: anthropic("claude-sonnet-5-5"),
147149
messages,
148150
abortSignal: signal,
149151
stopWhen: stepCountIs(15),

‎docs/ai-chat/client-protocol.mdx‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ for await (const ev of readSessionOut(sseUrl, publicAccessToken)) {
569569
570570
### Chunk types
571571
572-
Data records on the stream carry a `UIMessageChunk` from the [AI SDK](https://ai-sdk.dev/docs/ai-sdk-ui/ui-message-stream). Two Trigger.dev-specific control events ride alongside as **header-form control records** (see [Records on session.out](#records-on-session-out)).
572+
Data records on the stream carry a `UIMessageChunk` from the [AI SDK](https://ai-sdk.dev/docs/ai-sdk-ui/ui-message-stream). Trigger.dev-specific control events ride alongside as **header-form control records** (see [Records on session.out](#records-on-session-out)).
573573
574574
Within a single assistant turn the AI SDK chunk types you'll typically see, in order:
575575
@@ -584,7 +584,7 @@ Within a single assistant turn the AI SDK chunk types you'll typically see, in o
584584
| `data-subagent` | `{ type: "data-subagent", transient: true, data: { toolCallId, seq, chunks } }` | A batch of a sub-agent's chunks written by [`chat.forwardSubAgent`](/ai-chat/patterns/sub-agents). `seq` counts from 0 per `toolCallId`; skip batches you have already applied when you resume. |
585585
| `finish-step` / `finish` | end markers for the assistant message | Followed by the `turn-complete` control record. |
586586
587-
Refer to the AI SDK docs linked above for the full union — only the two control records below are Trigger.dev-specific.
587+
Refer to the AI SDK docs linked above for the full union — only the control records below are Trigger.dev-specific.
588588
589589
### `turn-complete` control record
590590
@@ -656,6 +656,44 @@ body: ""
656656
657657
Only agents on a recent SDK version write these. Against an older agent a reader sees neither, and has to fall back to the `turn-complete` correlation described above.
658658
659+
### `session-closed` control record
660+
661+
Signals that the session was closed by [`chat.close()`](/ai-chat/backend) and accepts no more messages.
662+
663+
```
664+
headers:
665+
["trigger-control", "session-closed"]
666+
["session-closed-reason", "Monthly budget reached"] // optional
667+
body: ""
668+
```
669+
670+
| Header | Description |
671+
| --- | --- |
672+
| `trigger-control: session-closed` | Always present on this record. |
673+
| `session-closed-reason: <text>` (optional) | The `reason` passed to `chat.close({ reason })`. Omitted when no reason was given. |
674+
675+
This record is written after the turn's `turn-complete`, so a reader that stops on `turn-complete` won't see it; it's there for reconnects and replay. When the close is decided before the turn ends, that `turn-complete` also carries `["session-closed", "true"]` and the optional `session-closed-reason` header.
676+
677+
When you receive this record:
678+
1. Stop reading and stop sending. Further `.in` appends are refused with `409`, and a closed session can't be reopened.
679+
2. Optionally show the reason in your UI.
680+
681+
### `pending-version` control record
682+
683+
Signals that the agent handed the chat to a new run (for example after [`chat.requestUpgrade()`](/ai-chat/patterns/version-upgrades)) and that run is parked waiting for its deployment to land.
684+
685+
```
686+
headers:
687+
["trigger-control", "pending-version"]
688+
body: ""
689+
```
690+
691+
When you receive this record:
692+
1. Treat it as informational and keep the stream open. Messages you send meanwhile are durable and answered once the deployment lands.
693+
2. Optionally show a "deploy in progress" indicator in your UI.
694+
695+
`TriggerChatTransport` surfaces this as a [`run-pending-version`](/ai-chat/reference#transport-events) event.
696+
659697
### Resuming a stream
660698
661699
If the SSE connection drops, or the server sends an `error` event, reconnect with the `Last-Event-ID` header set to the **last `record.seq_num` you successfully processed** (decoded from the batch body, not the SSE `id:` line, which is a comma-list internal to S2):

‎docs/ai-chat/compaction.mdx‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ export const myChat = chat.agent({
245245
onAction: async ({ action, uiMessages }) => {
246246
if (action.type !== "compact") return;
247247

248-
const summary = await summarize(convertToModelMessages(uiMessages));
248+
const summary = await summarize(await convertToModelMessages(uiMessages));
249249

250250
// Replace the full history with a single summary message.
251251
chat.history.set([
@@ -293,7 +293,7 @@ function ChatView({ chatId }: { chatId: string }) {
293293
}
294294
```
295295

296-
The call returns as soon as the backend accepts the action. Because `onTurnComplete` replaces the `uiMessages` with the summary, `useChat` receives the new state via the normal turn-complete flow — the UI updates automatically.
296+
The call returns as soon as the backend accepts the action. Because `onAction` replaces the history with the summary via `chat.history.set`, `useChat` receives the new state via the normal turn-complete flow — the UI updates automatically.
297297

298298
### Indicating compaction in the UI
299299

@@ -304,7 +304,7 @@ onAction: async ({ action, uiMessages }) => {
304304
if (action.type !== "compact") return;
305305

306306
chat.stream.append({ type: "data-compaction", data: { status: "compacting" } });
307-
const summary = await summarize(convertToModelMessages(uiMessages));
307+
const summary = await summarize(await convertToModelMessages(uiMessages));
308308
chat.stream.append({ type: "data-compaction", data: { status: "complete" } });
309309

310310
chat.history.set([ /* ... */ ]);
@@ -368,15 +368,28 @@ const conversation = new chat.MessageAccumulator({
368368
model: anthropic("claude-haiku-5-5"),
369369
messages: [...messages, { role: "user", content: "Summarize this conversation concisely." }],
370370
}).then((r) => r.text),
371-
compactUIMessages: ({ summary }) => [
371+
// Keep the latest user message and reply next to the summary, so a
372+
// regenerate right after compaction still has the question to answer
373+
compactUIMessages: ({ uiMessages, summary }) => [
372374
{ id: generateId(), role: "assistant",
373375
parts: [{ type: "text", text: `[Summary]\n\n${summary}` }] },
376+
...uiMessages.slice(-2),
374377
],
375378
},
376379
});
377380

381+
let currentPayload = payload;
382+
378383
for (let turn = 0; turn < 100; turn++) {
379-
const messages = await conversation.addIncoming(payload.messages, payload.trigger, turn);
384+
// A regenerate carries no message, and addIncoming replaces the history on
385+
// it: pass the history minus the assistant reply being regenerated.
386+
const incoming =
387+
currentPayload.trigger === "regenerate-message"
388+
? conversation.uiMessages.slice(0, -1)
389+
: currentPayload.message
390+
? [currentPayload.message]
391+
: [];
392+
const messages = await conversation.addIncoming(incoming, currentPayload.trigger, turn);
380393

381394
const result = streamText({
382395
model: anthropic("claude-sonnet-5-5"),
@@ -393,13 +406,24 @@ for (let turn = 0; turn < 100; turn++) {
393406
// AI SDK 7, so read it from `steps`, and pass the turn's sum separately.
394407
const lastStepUsage = (await result.steps).at(-1)?.usage;
395408
await conversation.compactIfNeeded(lastStepUsage, {
396-
chatId: payload.chatId,
409+
chatId: currentPayload.chatId,
397410
turn,
398411
turnUsage: await result.totalUsage,
399412
});
400413

401414
await db.chat.update({ data: { messages: conversation.uiMessages } });
402415
await chat.writeTurnComplete();
416+
417+
// Wait for the next message, unless this was the last turn
418+
if (turn === 99) break;
419+
const next = await chat.messages.waitWithIdleTimeout({
420+
idleTimeoutInSeconds: 60,
421+
timeout: "1h",
422+
spanName: "waiting for next message",
423+
});
424+
// A closed chat sends a `close` record: exit instead of running a turn
425+
if (!next.ok || next.output.trigger === "close") break;
426+
currentPayload = next.output;
403427
}
404428
```
405429

‎docs/ai-chat/migrating-from-a-route-handler.mdx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ export async function POST(req: Request) {
121121
const result = streamText({
122122
model: anthropic("claude-sonnet-5-5"),
123123
system: "You are a helpful assistant.",
124-
messages: convertToModelMessages(messages),
124+
messages: await convertToModelMessages(messages, { tools }),
125125
tools,
126126
stopWhen: stepCountIs(15),
127127
abortSignal: req.signal,
@@ -186,7 +186,7 @@ export const tools = {
186186
execute: async ({ spec }) => renderToPng(spec),
187187
toModelOutput: ({ output }) => ({
188188
type: "content",
189-
value: [{ type: "media", mediaType: "image/png", data: output.base64 }],
189+
value: [{ type: "file", mediaType: "image/png", data: { type: "data", data: output.base64 } }],
190190
}),
191191
}),
192192
};
@@ -448,7 +448,7 @@ Head Start brings the route handler back for exactly that first turn. It runs st
448448
execute: async ({ spec }) => renderToPng(spec),
449449
toModelOutput: ({ output }) => ({
450450
type: "content",
451-
value: [{ type: "media", mediaType: "image/png", data: output.base64 }],
451+
value: [{ type: "file", mediaType: "image/png", data: { type: "data", data: output.base64 } }],
452452
}),
453453
}),
454454
};

‎docs/ai-chat/tools.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ const tools = {
7777
// The model should see an image part, not base64 bytes:
7878
toModelOutput: ({ output }) => ({
7979
type: "content",
80-
value: [{ type: "media", mediaType: "image/png", data: output.base64 }],
80+
value: [{ type: "file", mediaType: "image/png", data: { type: "data", data: output.base64 } }],
8181
}),
8282
}),
8383
};

‎docs/errors-retrying.mdx‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -206,12 +206,13 @@ In this complicated example:
206206

207207
```ts tasks.ts
208208
import { task } from "@trigger.dev/sdk";
209+
import OpenAI from "openai";
209210
import { calculateISO8601DurationOpenAIVariantResetAt, openai } from "./openai.js";
210211

211212
export const openaiTask = task({
212213
id: "openai-task",
213214
retry: {
214-
maxAttempts: 1,
215+
maxAttempts: 3,
215216
},
216217
run: async (payload: { prompt: string }) => {
217218
const chatCompletion = await openai.chat.completions.create({
@@ -240,17 +241,17 @@ export const openaiTask = task({
240241
return;
241242
}
242243

243-
const remainingRequests = error.headers["x-ratelimit-remaining-requests"];
244-
const requestResets = error.headers["x-ratelimit-reset-requests"];
244+
const remainingRequests = error.headers.get("x-ratelimit-remaining-requests");
245+
const requestResets = error.headers.get("x-ratelimit-reset-requests");
245246

246247
if (typeof remainingRequests === "string" && Number(remainingRequests) === 0) {
247248
return {
248249
retryAt: calculateISO8601DurationOpenAIVariantResetAt(requestResets),
249250
};
250251
}
251252

252-
const remainingTokens = error.headers["x-ratelimit-remaining-tokens"];
253-
const tokensResets = error.headers["x-ratelimit-reset-tokens"];
253+
const remainingTokens = error.headers.get("x-ratelimit-remaining-tokens");
254+
const tokensResets = error.headers.get("x-ratelimit-reset-tokens");
254255

255256
if (typeof remainingTokens === "string" && Number(remainingTokens) === 0) {
256257
return {
@@ -265,10 +266,10 @@ export const openaiTask = task({
265266
```ts openai.ts
266267
import { OpenAI } from "openai";
267268

268-
export const openai = new OpenAI({ apiKey: env.OPENAI_API_KEY });
269+
export const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
269270

270271
export function calculateISO8601DurationOpenAIVariantResetAt(
271-
resets: string,
272+
resets: string | null,
272273
now: Date = new Date()
273274
): Date | undefined {
274275
// Check if the input is null or undefined

‎docs/how-it-works.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ export const childTask = task({
194194
console.log("Starting child task with data:", payload.data);
195195

196196
// Simulate some work
197-
await sleep(5);
197+
await wait.for({ seconds: 5 });
198198

199199
return "Child task result";
200200
},
@@ -452,5 +452,6 @@ import { AwsInstrumentation } from "@opentelemetry/instrumentation-aws-sdk";
452452
export default defineConfig({
453453
project: "<your-project-ref>",
454454
instrumentations: [new PrismaInstrumentation(), new AwsInstrumentation()],
455+
maxDuration: 3600,
455456
});
456457
```

‎docs/idempotency.mdx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -359,8 +359,9 @@ When a run with an idempotency key **fails**, the key is automatically cleared.
359359
```ts
360360
import { idempotencyKeys } from "@trigger.dev/sdk";
361361

362-
// Clear the idempotency key to allow re-triggering
363-
await idempotencyKeys.reset("my-task", "my-idempotency-key");
362+
// From your backend: clear the idempotency key to allow re-triggering.
363+
// Inside a task, omit `scope` to reset a key that the same run created.
364+
await idempotencyKeys.reset("my-task", "my-idempotency-key", { scope: "global" });
364365

365366
// Now you can trigger the task again
366367
await myTask.trigger(payload, { idempotencyKey: "my-idempotency-key" });

‎docs/machines.mdx‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,14 @@ export const heavyTask = task({
2020
The default machine is `small-1x` which has 0.5 vCPU and 0.5 GB of RAM. You can change the default machine in your `trigger.config.ts` file:
2121

2222
```ts trigger.config.ts
23-
import type { TriggerConfig } from "@trigger.dev/sdk";
23+
import { defineConfig } from "@trigger.dev/sdk";
2424

25-
export const config: TriggerConfig = {
25+
export default defineConfig({
26+
project: "<project ref>",
2627
machine: "small-2x",
28+
maxDuration: 3600,
2729
// ... other config
28-
};
30+
});
2931
```
3032

3133
## Machine configurations
@@ -851,7 +853,8 @@ const kindName = (k: number | string) => {
851853
Then, in your task, you can create an instance of the `ResourceMonitor` class and start monitoring memory, disk, and CPU usage:
852854

853855
```ts /src/trigger/example.ts
854-
import { task, logger, wait } from "@trigger.dev/sdk";
856+
import { task, tasks, logger, wait } from "@trigger.dev/sdk";
857+
import { setTimeout } from "node:timers/promises";
855858
import { ResourceMonitor } from "../resourceMonitor.js";
856859

857860
// Middleware to enable the resource monitor
@@ -873,12 +876,8 @@ tasks.middleware("resource-monitor", async ({ ctx, next }) => {
873876
export const resourceMonitorTest = task({
874877
id: "resource-monitor-test",
875878
run: async (payload: any, { ctx }) => {
876-
const interval = createMemoryPressure();
877-
878879
await setTimeout(180_000);
879880

880-
clearInterval(interval);
881-
882881
return {
883882
message: "Hello, resources!",
884883
};

‎docs/manual-setup.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ export default defineConfig({
177177
project: "<your-project-ref>",
178178
runtime: "bun",
179179
dirs: ["./src/trigger"],
180+
maxDuration: 3600,
180181
});
181182
```
182183

@@ -319,6 +320,7 @@ export default defineConfig({
319320
}),
320321
],
321322
},
323+
maxDuration: 3600,
322324
});
323325
```
324326

0 commit comments

Comments
 (0)