Skip to content

Commit 91b3e63

Browse files
BenTaylorDevclaude
andcommitted
docs: correct API Gateway streaming and Intelligence thread scoping
Two review corrections. API Gateway REST APIs gained Lambda response streaming in November 2025 via responseTransferMode: STREAM, which also lifts the 10 MB payload cap and the 29-second integration timeout. The guide claimed no API Gateway type can stream and steered readers to a buffered serverless-http setup. Split REST from HTTP, document the REST streaming path (payload format 1.0 adapter, AWS_PROXY integration on the response-streaming-invocations URI, CLI/CDK/SAM config), and scope the buffered fallback to HTTP APIs and ALB, which still have no streaming path. The thread-authorization section told every reader to build an ownership table and enforce it in onBeforeHandler. On the Intelligence path the runtime already resolves identifyUser(request) server-side and passes that user id to run, connect, the thread reads, the mutations, and the subscription token; listThreads is scoped by user and filtered by agentId. Document identifyUser as the platform binding and scope the DIY pattern to SSE runtimes, custom stores, and the local in-memory runner. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 24ed6f0 commit 91b3e63

2 files changed

Lines changed: 199 additions & 28 deletions

File tree

‎showcase/shell-docs/src/content/docs/auth.mdx‎

Lines changed: 51 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -446,9 +446,51 @@ This composes with [Human in the loop](/human-in-the-loop): gate on auth first,
446446

447447
## Thread authorization
448448

449-
Verifying *who* the caller is doesn't yet stop them reaching *someone else's conversation*. A `threadId` is just an opaque id travelling in a request — nothing in the runtime ties it to a user on its own. If user A learns user B's `threadId`, every thread route accepts it. Scoping threads to their owner is your responsibility, and it belongs in the runtime.
449+
Verifying *who* the caller is doesn't yet stop them reaching *someone else's conversation*. How much of that you have to build depends on which runtime you're running.
450450

451-
### Own the mapping
451+
| Runtime | Who scopes threads to a user |
452+
| --- | --- |
453+
| `CopilotRuntime` with `intelligence` | The runtime does, via [`identifyUser`](#the-intelligence-platform-scopes-threads-for-you). |
454+
| Anything else — SSE runtime, custom store, local in-memory runner | You do. See [Scope threads yourself](#scope-threads-yourself). |
455+
456+
### The Intelligence Platform scopes threads for you
457+
458+
The Intelligence runtime requires an `identifyUser` callback — construction throws without one (or without at least one Channel). It runs on the server, once per request, and the id it returns is what the runtime passes to the platform on every thread-bearing route:
459+
460+
```ts title="app/api/copilotkit/[[...slug]]/route.ts"
461+
const runtime = new CopilotRuntime({
462+
agents: { default: agent },
463+
intelligence,
464+
identifyUser: async (request) => {
465+
const session = await verifyAppSession(request); // Your server-side auth.
466+
if (!session?.user) throw new Error("Unauthorized"); // Backstop; see below.
467+
468+
return { id: session.user.id, name: session.user.name };
469+
},
470+
});
471+
```
472+
473+
That resolved id is applied to `agent/run`, `agent/connect`, the thread message, event, and state reads, `threads/update`, `threads/archive`, `threads/delete`, and the token minted for the thread subscription. `threads/list` is scoped by the resolved user *and* filtered by `agentId`, so `useThreads` returns the caller's threads rather than every thread in the project.
474+
475+
So on this path there is no ownership table to build. What you own is `identifyUser` itself:
476+
477+
- **Derive the id from a server-verified credential.** The callback receives the raw `Request`; whatever it returns is trusted from there on. Reading a user id straight out of a header or request body hands every caller the ability to name themselves.
478+
- **Return a stable id.** It is the key threads hang off. Change it — swapping an email for a subject claim, say — and that user's existing threads stop resolving.
479+
- **Send the `401` from `onRequest`.** An `identifyUser` that throws surfaces as a `500`, and returning a malformed id gives a `400` — neither is what an unauthenticated caller should see. Do the authenticate-or-reject step in `onRequest`, which can throw a `Response` directly, and keep the throw inside `identifyUser` as a backstop for the case that slips through.
480+
481+
<Callout type="warn">
482+
A static `identifyUser` value is suitable only for a single-user demo. In a multi-user
483+
application every request must resolve the authenticated user, or those users share one
484+
thread scope.
485+
</Callout>
486+
487+
See [Scope Rich Threads to the signed-in user](/threads-lifecycle#scope-rich-threads-to-the-signed-in-user) for the full runtime contract.
488+
489+
### Scope threads yourself
490+
491+
Without the Intelligence Platform there is no server-side binding between a `threadId` and a user. A `threadId` is just an opaque id travelling in a request: if user A learns user B's, every thread route accepts it. The rest of this section is the pattern for a custom store, a plain SSE runtime, or the local in-memory runner.
492+
493+
#### Own the mapping
452494

453495
Whatever stores your threads, keep a record of who each one belongs to. The minimum is a table your runtime can query:
454496

@@ -462,7 +504,7 @@ create index on thread_owners (user_id);
462504

463505
Write a row when a conversation is first created — see [minting a thread with your own API](/threads-lifecycle#creating-a-thread-with-your-own-api-on-the-first-message) for where that hooks into the chat lifecycle.
464506

465-
### Enforce it in `onBeforeHandler`
507+
#### Enforce it in `onBeforeHandler`
466508

467509
`onRequest` runs before routing, so it can't see which thread is being addressed. `onBeforeHandler` runs after, and receives a `route` that names the operation and — for thread-scoped routes — the `threadId`:
468510

@@ -510,23 +552,22 @@ The routes that carry a `threadId` on `route` are `agent/stop`, `threads/update`
510552
must own it". Minting UUIDs makes guessing impractical but is not itself a control.
511553
</Callout>
512554

513-
### Filter the thread list
555+
#### Filter the thread list
514556

515-
`threads/list` has no `threadId` to check — it returns whatever the configured store holds. On the Enterprise Intelligence Platform, threads are scoped to a project, so every user of one project sees that project's threads. If your product needs per-user thread lists, either give each user their own project scope, or build the list from your own ownership table and drive the chat with the selected id rather than rendering the platform list directly.
557+
`threads/list` has no `threadId` to check, so `onBeforeHandler` has nothing to authorize against. Off the platform the route returns whatever the configured store holds — the local in-memory runner filters by `agentId` only, and a custom store returns exactly what you wrote. Build the list from your own ownership table instead, and drive the chat with the selected id.
516558

517-
`useThreads` is the platform-backed list. When you filter, filter server-side — hiding rows in the UI leaves the underlying route open.
559+
Filter server-side. Hiding rows in the UI leaves the underlying route open.
518560

519561
<Callout type="info">
520-
Running without the Enterprise Intelligence Platform? Then there is no server-side thread
521-
store to authorize in the first place, and the ownership table above *is* your thread list.
522-
See [Self-managed thread persistence](/threads-self-managed).
562+
With no platform thread store, the ownership table above *is* your thread list. See
563+
[Self-managed thread persistence](/threads-self-managed).
523564
</Callout>
524565

525566
## Security checklist
526567

527568
- **Always validate** the token on the backend. Never trust the frontend's claim.
528569
- **Scope every read and write** to the resolved user. Auth context only matters if you actually use it to filter data.
529-
- **Check thread ownership on every thread route**, not just at login. See [Thread authorization](#thread-authorization).
570+
- **Bind threads to a user.** On the Intelligence Platform that means a correct `identifyUser`; off it, an ownership check on every thread route rather than only at login. See [Thread authorization](#thread-authorization).
530571
- **Don't log raw tokens.** Log the resolved user id (or `anonymous`) instead.
531572
- **Use HTTPS in production.** The Bearer token is sensitive.
532573
- **Refresh strategy.** Your frontend is responsible for rotating expired tokens before they reach the agent. CopilotKit doesn't refresh on your behalf.

‎showcase/shell-docs/src/content/docs/deploy/aws-lambda.mdx‎

Lines changed: 148 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,25 @@ icon: "lucide/Cloud"
44
description: Run the CopilotKit runtime on AWS Lambda, including the response-streaming setup a chat UI requires.
55
---
66

7-
The CopilotKit runtime is a Fetch handler, so it runs on Lambda without a server. The one thing that needs care is **streaming**: chat responses are served as Server-Sent Events, and most Lambda front doors buffer the whole response before returning it.
7+
The CopilotKit runtime is a Fetch handler, so it runs on Lambda without a server. The one thing that needs care is **streaming**: chat responses are served as Server-Sent Events, and a front door that buffers turns a live conversation into a long pause followed by the whole reply at once.
88

99
## Start here: pick the right front door
1010

11-
<Callout type="warn" title="API Gateway cannot stream">
12-
Neither API Gateway REST APIs nor HTTP APIs support response streaming. They buffer the
13-
full response, then return it in one piece (capped at 10 MB). A chat UI put behind API
14-
Gateway appears to hang for the length of the agent run, then dumps the entire reply at
15-
once. Application Load Balancer buffers the same way.
16-
</Callout>
17-
1811
| Front door | Streams SSE? | Use it when |
1912
| --- | --- | --- |
20-
| **Lambda Function URL** with `RESPONSE_STREAM` | Yes | Anything with a chat UI. This is the path you want. |
21-
| API Gateway (REST or HTTP) | No | Non-streaming use only, or a runtime you drive entirely through your own non-chat endpoints. |
22-
| Application Load Balancer | No | Same caveat as API Gateway. |
13+
| **Lambda Function URL** with `InvokeMode: RESPONSE_STREAM` | Yes | The default. Nothing sits between the browser and the function. |
14+
| **API Gateway REST API** with `responseTransferMode: STREAM` | Yes | You need REST API features in front of the runtime — WAF, usage plans, a custom authorizer, or an existing REST API to extend. |
15+
| API Gateway **HTTP** API | No | Response streaming is REST-only. Buffered: 10 MB cap, 29-second timeout. |
16+
| Application Load Balancer | No | ALB has no streaming path for Lambda targets. |
17+
18+
<Callout type="warn" title="Streaming is opt-in on every path">
19+
Both streaming front doors default to buffering — a Function URL to `BUFFERED` invoke mode,
20+
an API Gateway integration to `responseTransferMode: BUFFERED`. Deploy either without
21+
flipping the switch and chat appears to hang for the length of the agent run, then dumps
22+
the entire reply in one piece.
23+
</Callout>
2324

24-
The rest of this page covers the Function URL path first, then the API Gateway path for the cases that genuinely don't need streaming.
25+
The handler code below is the same for both streaming paths; only the event shape and the infrastructure config differ.
2526

2627
## Function URL with response streaming
2728

@@ -211,12 +212,141 @@ provideCopilotKit({
211212
<Callout type="info" title="Verify streaming actually works">
212213
`curl -N` on the run endpoint should print SSE events progressively. If the whole body
213214
arrives at once, streaming is not active — check that the Function URL's invoke mode is
214-
`RESPONSE_STREAM` and that nothing buffering (API Gateway, an ALB) sits in front of it.
215+
`RESPONSE_STREAM`, and that nothing buffering (an HTTP API, an ALB, a CloudFront
216+
distribution without streaming configured) sits in front of it.
217+
</Callout>
218+
219+
## API Gateway REST API with response streaming
220+
221+
REST APIs gained response streaming in November 2025. It is per-integration and off by default: setting `responseTransferMode` to `STREAM` makes API Gateway invoke the function through [`InvokeWithResponseStream`](https://docs.aws.amazon.com/lambda/latest/api/API_InvokeWithResponseStream.html) and forward bytes as they arrive, which also lifts the 10 MB response cap and the 29-second integration timeout that apply to buffered integrations.
222+
223+
Use this path when you want REST API features in front of the runtime. If you don't, the Function URL above is less to configure.
224+
225+
### 1. Adapt the handler to payload format 1.0
226+
227+
The streaming half of the handler is unchanged — `awslambda.streamifyResponse` and `HttpResponseStream.from` emit exactly the metadata-plus-delimiter format API Gateway expects. What changes is the event: a REST proxy integration delivers payload format 1.0, not the 2.0 shape a Function URL sends.
228+
229+
```ts title="src/handler.ts"
230+
import type { APIGatewayProxyEvent } from "aws-lambda";
231+
232+
// REST proxy integrations deliver payload format 1.0: `httpMethod` and `path`
233+
// rather than `requestContext.http.method` and `rawPath`. `path` excludes the
234+
// stage name, which is what we want — it lines up with the runtime's basePath.
235+
function toFetchRequest(event: APIGatewayProxyEvent): Request {
236+
const method = event.httpMethod;
237+
const headers = new Headers();
238+
for (const [name, value] of Object.entries(event.headers)) {
239+
if (value != null) headers.append(name, value);
240+
}
241+
242+
const query = new URLSearchParams();
243+
for (const [name, values] of Object.entries(
244+
event.multiValueQueryStringParameters ?? {},
245+
)) {
246+
for (const value of values ?? []) query.append(name, value);
247+
}
248+
const search = query.toString();
249+
250+
const hasBody = method !== "GET" && method !== "HEAD" && event.body != null;
251+
252+
return new Request(
253+
`https://${headers.get("host") ?? "localhost"}${event.path}${search ? `?${search}` : ""}`,
254+
{
255+
method,
256+
headers,
257+
body: hasBody
258+
? event.isBase64Encoded
259+
? Buffer.from(event.body!, "base64")
260+
: event.body
261+
: undefined,
262+
},
263+
);
264+
}
265+
```
266+
267+
The `awslambda.streamifyResponse(...)` block from the Function URL section works as-is on top of this.
268+
269+
### 2. Configure the integration
270+
271+
Three settings matter: a Lambda **proxy** (`AWS_PROXY`) integration, a URI ending in `/response-streaming-invocations`, and `responseTransferMode: STREAM`. Streaming is not supported on non-proxy integration types.
272+
273+
<Tabs groupId="iac" items={["AWS CLI", "AWS CDK", "AWS SAM"]}>
274+
<Tab value="AWS CLI">
275+
On an existing integration, patch the URI and the transfer mode together, then redeploy the stage:
276+
277+
```bash
278+
aws apigateway update-integration \
279+
--rest-api-id a1b2c3 \
280+
--resource-id aaa111 \
281+
--http-method ANY \
282+
--patch-operations '[
283+
{"op":"replace","path":"/uri","value":"arn:aws:apigateway:us-east-1:lambda:path/2021-11-15/functions/arn:aws:lambda:us-east-1:111122223333:function:copilotkit-runtime/response-streaming-invocations"},
284+
{"op":"replace","path":"/responseTransferMode","value":"STREAM"},
285+
{"op":"replace","path":"/timeoutInMillis","value":"900000"}
286+
]'
287+
288+
aws apigateway create-deployment --rest-api-id a1b2c3 --stage-name prod
289+
```
290+
291+
Note the API version in the URI path: `2021-11-15/.../response-streaming-invocations`, not the `2015-03-31/.../invocations` a buffered Lambda proxy integration uses. The permission is unchanged — `InvokeWithResponseStream` authorizes against `lambda:InvokeFunction`, so an existing `add-permission` grant still applies.
292+
</Tab>
293+
<Tab value="AWS CDK">
294+
```ts title="lib/stack.ts"
295+
import { LambdaIntegration, ResponseTransferMode, RestApi, EndpointType } from "aws-cdk-lib/aws-apigateway";
296+
import { Duration } from "aws-cdk-lib";
297+
298+
const api = new RestApi(this, "CopilotKitApi", {
299+
// Regional gets a 5-minute idle timeout; edge-optimized gets 30 seconds.
300+
endpointConfiguration: { types: [EndpointType.REGIONAL] },
301+
});
302+
303+
api.root.addResource("api").addResource("copilotkit").addResource("{proxy+}").addMethod(
304+
"ANY",
305+
new LambdaIntegration(fn, {
306+
responseTransferMode: ResponseTransferMode.STREAM,
307+
timeout: Duration.minutes(15),
308+
}),
309+
);
310+
```
311+
312+
`responseTransferMode` needs a recent `aws-cdk-lib`; the construct sets the streaming invocation URI for you.
313+
</Tab>
314+
<Tab value="AWS SAM">
315+
```yaml title="template.yaml"
316+
CopilotKitMethod:
317+
Type: AWS::ApiGateway::Method
318+
Properties:
319+
RestApiId: !Ref CopilotKitApi
320+
ResourceId: !Ref CopilotKitProxyResource
321+
HttpMethod: ANY
322+
AuthorizationType: NONE
323+
Integration:
324+
Type: AWS_PROXY
325+
IntegrationHttpMethod: POST
326+
ResponseTransferMode: STREAM
327+
TimeoutInMillis: 900000
328+
Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2021-11-15/functions/${CopilotKitRuntime.Arn}/response-streaming-invocations
329+
```
330+
</Tab>
331+
</Tabs>
332+
333+
### 3. Plan around the streaming constraints
334+
335+
- **Pick a Regional endpoint.** Streams are subject to an idle timeout: 5 minutes for Regional and private endpoints, but **30 seconds for edge-optimized ones**. An agent that thinks for longer than 30 seconds between SSE events will have its stream cut on an edge-optimized API. Fronting a Regional API with your own CloudFront distribution and raising its response timeout is the way to keep an edge cache.
336+
- **Raise the integration timeout.** It still defaults to 29 seconds. With `STREAM` you can take it up to 15 minutes on Regional and private APIs — match it to the Lambda timeout.
337+
- **`STREAM` disables buffered-only features** on that integration: endpoint caching, content encoding, and VTL response transformation. Compress inside the integration if you need it.
338+
- **Bandwidth.** The first 10 MB of each streamed response is uncapped; beyond that API Gateway throttles to 2 MB/s.
339+
- **A client timeout doesn't stop the function.** When API Gateway closes the connection, the Lambda keeps running and billing until it finishes or hits its own timeout.
340+
341+
<Callout type="warn" title="The console test tab always buffers">
342+
`TestInvokeMethod` and the console's **Test** tab buffer the stream and return it in one
343+
piece, so a correctly configured integration still looks buffered there. Verify against a
344+
deployed stage with `curl -i --no-buffer` instead.
215345
</Callout>
216346

217-
## API Gateway (no streaming)
347+
## Buffered fallback: HTTP APIs and ALB
218348

219-
If you must sit behind API Gateway, `serverless-http` adapts the Express handler to a Lambda event. Chat still functions end to end, but every response arrives in one piece at the end of the run.
349+
Behind an HTTP API or an Application Load Balancer there is no streaming path, so `serverless-http` adapting the Express handler is as good as it gets. Chat still functions end to end, but every response arrives in one piece at the end of the run.
220350

221351
```
222352
npm install express serverless-http @copilotkit/runtime
@@ -250,7 +380,7 @@ export const handler = serverlessHttp(app);
250380
Two constraints to plan around:
251381

252382
- **10 MB response cap.** A long agent run with large tool results can exceed it, and the request fails rather than truncating.
253-
- **29-second integration timeout** on API Gateway REST and HTTP APIs. Agent runs longer than that return a 504 even though the Lambda keeps executing.
383+
- **29-second integration timeout.** Agent runs longer than that return a 504 even though the Lambda keeps executing. On an HTTP API this ceiling is fixed; both limits are what `responseTransferMode: STREAM` lifts on a REST API.
254384

255385
Single-route mode pairs well here, since it collapses the runtime to one `POST` and avoids configuring a catch-all proxy resource:
256386

@@ -265,7 +395,7 @@ createCopilotExpressHandler({
265395

266396
## Authentication
267397

268-
Use the runtime's `onRequest` hook to reject unauthenticated calls before any routing happens. It works identically on both paths above.
398+
Use the runtime's `onRequest` hook to reject unauthenticated calls before any routing happens. It works identically on every front door above.
269399

270400
```ts
271401
const copilotHandler = createCopilotRuntimeHandler({
@@ -294,7 +424,7 @@ See [Authentication](/auth) for forwarding user identity through to your agent.
294424
- **Construct the runtime outside the handler.** Putting `new CopilotRuntime(...)` at module scope means warm invocations reuse it rather than rebuilding it per request.
295425
- **Set the timeout to cover a full agent run.** Lambda's maximum is 15 minutes; the default of 3 seconds will cut off almost anything.
296426
- **Cold starts are visible in chat.** Provisioned concurrency is the usual fix if first-token latency matters.
297-
- **Streaming has its own limits.** Function URL response streaming allows a larger payload than the 6 MB buffered limit, but bandwidth beyond the first 6 MB is billed separately.
427+
- **Streaming has its own limits.** A streamed response can reach 200 MB against the 6 MB buffered ceiling, but Lambda throttles to 2 MB/s past the first 6 MB (API Gateway, past the first 10 MB). Streaming also incurs cost, and a streamed run is billed for the full function duration even if the client disconnects.
298428

299429
## Related
300430

0 commit comments

Comments
 (0)