You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 91b3e63
Browse filesBrowse the repository at this point in the historyBrowse files
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]>
Copy file name to clipboardExpand all lines: showcase/shell-docs/src/content/docs/auth.mdx
+51-10Lines changed: 51 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -446,9 +446,51 @@ This composes with [Human in the loop](/human-in-the-loop): gate on auth first,
446
446
447
447
## Thread authorization
448
448
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.
450
450
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:
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
+
<Callouttype="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
452
494
453
495
Whatever stores your threads, keep a record of who each one belongs to. The minimum is a table your runtime can query:
454
496
@@ -462,7 +504,7 @@ create index on thread_owners (user_id);
462
504
463
505
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.
464
506
465
-
### Enforce it in `onBeforeHandler`
507
+
####Enforce it in `onBeforeHandler`
466
508
467
509
`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`:
468
510
@@ -510,23 +552,22 @@ The routes that carry a `threadId` on `route` are `agent/stop`, `threads/update`
510
552
must own it". Minting UUIDs makes guessing impractical but is not itself a control.
511
553
</Callout>
512
554
513
-
### Filter the thread list
555
+
####Filter the thread list
514
556
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.
516
558
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.
518
560
519
561
<Callouttype="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
-**Always validate** the token on the backend. Never trust the frontend's claim.
528
569
-**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).
530
571
-**Don't log raw tokens.** Log the resolved user id (or `anonymous`) instead.
531
572
-**Use HTTPS in production.** The Bearer token is sensitive.
532
573
-**Refresh strategy.** Your frontend is responsible for rotating expired tokens before they reach the agent. CopilotKit doesn't refresh on your behalf.
description: Run the CopilotKit runtime on AWS Lambda, including the response-streaming setup a chat UI requires.
5
5
---
6
6
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.
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
-
18
11
| Front door | Streams SSE? | Use it when |
19
12
| --- | --- | --- |
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
+
<Callouttype="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>
23
24
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.
`curl -N`on the run endpoint should print SSE events progressively. If the whole body
213
214
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);
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.
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.
- **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.
215
345
</Callout>
216
346
217
-
## API Gateway (no streaming)
347
+
## Buffered fallback: HTTP APIs and ALB
218
348
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.
-**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.
254
384
255
385
Single-route mode pairs well here, since it collapses the runtime to one `POST` and avoids configuring a catch-all proxy resource:
256
386
@@ -265,7 +395,7 @@ createCopilotExpressHandler({
265
395
266
396
## Authentication
267
397
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.
@@ -294,7 +424,7 @@ See [Authentication](/auth) for forwarding user identity through to your agent.
294
424
-**Construct the runtime outside the handler.** Putting `new CopilotRuntime(...)` at module scope means warm invocations reuse it rather than rebuilding it per request.
295
425
-**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.
296
426
-**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.
0 commit comments