stitchkit 0.113.3 → 0.114.0

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,14 +1,56 @@
1
- # Upgrading 0.103.13 → 0.113.0 — stitchkit docs slice
1
+ # Upgrading 0.104.0 → 0.114.0 — stitchkit docs slice
2
2
 
3
3
  > Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
4
4
  > `llms.txt` in this package.
5
5
 
6
- Contains: Guide: Upgrading, 0.103.13 → 0.113.0 (docs/guide/upgrading.md)
6
+ Contains: Guide: Upgrading, 0.104.0 → 0.114.0 (docs/guide/upgrading.md)
7
7
 
8
8
  ==============================================================================
9
- # Guide: Upgrading, 0.103.13 → 0.113.0 (docs/guide/upgrading.md)
9
+ # Guide: Upgrading, 0.104.0 → 0.114.0 (docs/guide/upgrading.md)
10
10
  ==============================================================================
11
11
 
12
+ ## Released migration: 0.114.0
13
+
14
+ **Who must act:** code with an exhaustive `switch` or `Record` over
15
+ `TelegramSendFailureReason` or `TELEGRAM_SEND_FAILURE_REASONS`. Code that only
16
+ reads `retryable` and `recipientUnreachable` needs no change.
17
+
18
+ `classifyTelegramSendFailure` now returns `reason: 'bot-to-bot-disabled'` for a
19
+ `400 USER_BOT_TO_BOT_DISABLED` ([ADR 0274](../decisions/0274-a-telegram-token-has-one-outbound-budget.md)).
20
+ It is permanent for that send, so it is not retried; it is **not**
21
+ `recipientUnreachable`, because Telegram disables bot-to-bot messaging when
22
+ either bot has not enabled its Bot to Bot setting, and the missing setting may
23
+ be the sender's.
24
+
25
+ 1. Add the reason to every exhaustive mapping:
26
+
27
+ ```ts
28
+ // before
29
+ const code: Record<TelegramSendFailureReason, string> = { /* … */ unknown: 'E_UNKNOWN' }
30
+ // after
31
+ const code: Record<TelegramSendFailureReason, string> = {
32
+ /* … */ 'bot-to-bot-disabled': 'E_BOT_TO_BOT', unknown: 'E_UNKNOWN',
33
+ }
34
+ ```
35
+
36
+ Search pattern: `TelegramSendFailureReason`, `TELEGRAM_SEND_FAILURE_REASONS`
37
+ and every `switch` over a send-failure reason.
38
+ 2. Type-check: the exhaustive table without the new member fails to compile.
39
+ 3. If the application wants one outbound budget per bot token, opt in at the
40
+ one transformer that already owns its Bot API calls:
41
+
42
+ ```ts
43
+ import { telegramOutboundBudget } from 'stitchkit/telegram'
44
+
45
+ const budget = telegramOutboundBudget({ token: env.BOT_TOKEN })
46
+ api.config.use((previous, method, payload, signal) =>
47
+ budget.run(method, payload, signal, () => previous(method, payload, signal)),
48
+ )
49
+ ```
50
+
51
+ Remove the old limiter rather than running it beside this one. See the
52
+ [Telegram guide](telegram.md#one-token-one-outbound-budget).
53
+
12
54
  ## Released migration: 0.113.0
13
55
 
14
56
  **Who must act:** custom `AgentRuntimeStoreDriver` adapters and custom `AgentRuntimeStore` implementations of `seedConversationInput`. The built-in memory and SQLite stores already implement the contract.
@@ -814,84 +856,3 @@ signals to `createCli` / `createCliInvoker` and cooperative handlers observe `ct
814
856
  `REQUEST_ABORTED` is nonretryable and exits 130. A disconnected caller does not prove that
815
857
  an origin ignoring cancellation or an external provider stopped; keep resource leases until
816
858
  that work actually completes.
817
-
818
- ## Released migration: 0.103.13
819
-
820
- ### Darwin native assets in JS distributions
821
-
822
- **Who must act:** Bun builds that import `stitchkit/server`, `stitchkit/files` or
823
- `stitchkit/process` (Linux-only server apps included) and use `--outfile`, copy only
824
- `outputs[0]`, or package a single file; custom single-file/archive packagers and installers
825
- delivering native process/files capabilities.
826
- First affected publication: **0.103.13**, through **0.104.2**. It shipped as a patch; its
827
- changed delivery graph requires this migration despite unchanged API signatures.
828
-
829
- In those versions every Bun bundle that reaches the lock or process-identity code,
830
- `stitchkit/server` included, carries both Darwin `.node` addons as extra outputs on every
831
- operating system. `bun build --outfile` then fails with
832
- `cannot write multiple output files without an output directory`, and `--outdir` writes the
833
- addons next to a Linux artifact. Releases after 0.104.2 resolve the default loader at run time,
834
- so these bundles are one JS file with no `.node` output again. The static loader exists only
835
- in a build that uses the `stitchkit/files/packaging` plugin.
836
-
837
- ```sh
838
- # Before: one JS file was assumed to be the entire distribution.
839
- bun build src/native.ts --target=bun --outfile=dist/native.js
840
- # After: retain every output, with its relative path.
841
- bun build src/native.ts --target=bun --outdir=dist --entry-naming=native.js
842
- ```
843
-
844
- For `Bun.build`, copy **all** `result.outputs`, not just the JS entry or `outputs[0]`.
845
- A single-file JS distribution cannot embed a native `.node` addon automatically.
846
- An archive may contain JS plus companion assets, materialized together before execution.
847
- Custom output layout uses the evolving build-only packaging contract in the
848
- [native IO guide](native-io.md#public-native-packaging).
849
-
850
- Three deliveries have different rules: an ordinary npm install retains the package's
851
- native assets; a JS distribution must ship its complete output graph; a Bun compiled
852
- executable embeds the matching addon and may still use `--outfile`. In 0.103.13–0.104.2 a plain
853
- `bun build` carries the addon without a plugin. Later releases load it from a bundle only when
854
- the build uses `createNativePackaging` (`delivery: 'companion'` for JS, `'embedded'` for a
855
- compiled executable). Without the plugin, Bun may still copy the addon's bytes into a compiled
856
- executable, but the loader never uses them, so their presence proves nothing.
857
-
858
- What an unpackaged bundle does depends on the release:
859
-
860
- - **0.105.0–0.106.1:** the bundle carries the absolute path of the package on the build machine,
861
- because the loader read `__dirname`. It looks for the addon there, so it works only on that
862
- machine, and the path itself leaks into a distributed artifact. Rebuild with a later release.
863
- - **0.107.0 and later:** no build path is in the artifact, and the first call that needs the
864
- addon reports the Darwin backend `unavailable` with stage `packaging`.
865
-
866
- Only macOS is affected, and only process identity (`observeProcessInstance`,
867
- `probeProcessOwner`), exclusive locks and contained Agent file operations load the addon. The
868
- managed file boundary, atomic writes and the chunk spool never do. The
869
- [native IO guide](native-io.md#libraries-with-a-zod-only-runtime) is the canonical recipe and
870
- shows how to check an artifact by its loader without running it on a Mac. Check the resulting
871
- artifact offline outside the build tree and `node_modules`, including process identity,
872
- live-owner lock refusal, dead-owner recovery and contained IO. A missing or corrupt addon
873
- remains `unavailable`, never evidence that an owner died.
874
-
875
- ### CLI: repeated options are refused
876
-
877
- **Who must act:** wrappers, aliases and scripts that append `--json`, `--profile X` or an
878
- application global to arguments the user may already have given, and anything that passes the
879
- same global twice.
880
- First affected publication: **0.103.13**. It shipped as a patch; the change in grammar needs
881
- this migration.
882
-
883
- A repeated option that is not an array field is an argument error:
884
- `--json --json` and `--profile a --profile b` fail with `--json was passed 2 times`. Before
885
- 0.103.13 the last value won, for framework globals, application globals and repeated
886
- `kind: 'other'` fields alike. Array fields, and untyped passthrough fields that keep their
887
- raw-list grammar, still repeat.
888
-
889
- ```sh
890
- # Before: a wrapper appended its default and the last value won.
891
- mytool deploy --profile staging "$@" --profile production
892
- # After: build the argument list once, so each option appears once.
893
- mytool deploy --profile "${PROFILE:-production}" "$@"
894
- ```
895
-
896
- Dotted leaves such as `--filter.name` follow the same rule as their parent field. Declare a
897
- field as an array when repetition is meant.
@@ -0,0 +1,444 @@
1
+ # Upgrading 0.37.0 → 0.44.0 — stitchkit docs slice
2
+
3
+ > Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
4
+ > `llms.txt` in this package.
5
+
6
+ Contains: Guide: Upgrading, 0.37.0 → 0.44.0 (docs/guide/upgrading.md)
7
+
8
+ ==============================================================================
9
+ # Guide: Upgrading, 0.37.0 → 0.44.0 (docs/guide/upgrading.md)
10
+ ==============================================================================
11
+
12
+ ## Historical breaking migrations through 0.44.0
13
+
14
+ HTTP observability now completes inside the framework handler instead of a
15
+ nested fetch wrapper. Configure request and tool sinks explicitly:
16
+
17
+ ```ts
18
+ // before
19
+ const audit = createAuditHook({ write })
20
+ createServer({
21
+ services,
22
+ wrapFetch: (handler) => wrapInRequestContext(audit.http(handler)),
23
+ })
24
+ mountAgent(services, { hooks: audit.toolCall })
25
+
26
+ // after
27
+ const observability = createObservability({
28
+ request: { write, includePayload: true },
29
+ tools: { write },
30
+ })
31
+ createServer({ services, observability: observability.request })
32
+ mountAgent(services, { hooks: observability.toolCall })
33
+ ```
34
+
35
+ Body capture changed from always-on for body methods to opt-in. Set
36
+ `includePayload: true` only when the request sink needs the sanitized JSON body.
37
+ There is no `createAuditHook` or `audit.http` compatibility path;
38
+ `wrapInRequestContext` remains only for custom fetch pipelines.
39
+
40
+ Tool introspection now accepts one object-shaped contract/runtime surface. Stop
41
+ calling the internal contract collector or merging a locally converted runtime
42
+ manifest:
43
+
44
+ ```ts
45
+ // before
46
+ buildToolManifest(services.flatMap((service) => collectTools(service, 'AGENT')))
47
+ listToolNames(services)
48
+ summarizeTransports(services)
49
+
50
+ // after
51
+ const surface = { services, runtimeTools }
52
+ buildToolManifest({ ...surface, transport: 'AGENT' })
53
+ listToolNames(surface)
54
+ summarizeTransports(surface)
55
+ ```
56
+
57
+ `ToolNameEntry` adds `kind: 'contract' | 'runtime'`. `TransportSummary` is now
58
+ `{ contractServices, runtimeTools, totals, sources }`; replace `services` and
59
+ `perService` reads with the explicit counts and mixed-source breakdown. There
60
+ is no positional overload and no `buildRuntimeToolManifest`: Stitchkit owns the
61
+ combined order, transport filtering, canonical presentation schema and
62
+ cross-origin collision checks.
63
+
64
+ `defineErrors` now uses one Zod-first definition object and returns constructors
65
+ instead of positional throwers. Add explicit `throw`, move message/details/hint
66
+ into one options object, and declare a details schema when that code carries
67
+ structured context:
68
+
69
+ ```ts
70
+ // before
71
+ const { errors } = defineErrors({ QUOTA_EXCEEDED: 429 })
72
+ errors.QUOTA_EXCEEDED('Try later', { retryAfterSeconds: 30 }, 'Wait')
73
+
74
+ // after
75
+ const { errors, definitions } = defineErrors({
76
+ QUOTA_EXCEEDED: {
77
+ status: 429,
78
+ details: z.object({ retryAfterSeconds: z.number().positive() }),
79
+ },
80
+ })
81
+ throw errors.QUOTA_EXCEEDED({
82
+ message: 'Try later',
83
+ details: { retryAfterSeconds: 30 },
84
+ hint: 'Wait',
85
+ })
86
+ ```
87
+
88
+ There is no positional overload. A code without `details` forbids them; use an
89
+ optional object schema when the details object itself is optional. Read status
90
+ and schemas from the frozen `definitions` registry instead of maintaining a
91
+ parallel map.
92
+
93
+ Managed MCP runtime tools are now declared as immutable data. Move protected
94
+ registrar calls to `runtimeTools`; rename deliberate raw SDK registration to
95
+ `rawTools`. There is no registrar alias:
96
+
97
+ ```ts
98
+ // before — protected
99
+ createMcpHandler({
100
+ services,
101
+ nativeTools: ({ registerTool }) => registerTool(preview),
102
+ })
103
+
104
+ // after — protected and prepared with the rest of the surface
105
+ createMcpHandler({ services, runtimeTools: [preview] })
106
+
107
+ // before — deliberate raw SDK opt-out
108
+ nativeTools: ({ rawServer }, auth) => mountRaw(rawServer, auth)
109
+
110
+ // after — still a deliberate raw SDK opt-out
111
+ rawTools: (server, auth) => mountRaw(server, auth)
112
+ ```
113
+
114
+ When identity selects from a bounded set, replace a repeatedly prepared
115
+ `services(auth)` factory with a finite registry:
116
+
117
+ ```ts
118
+ createMcpHandler({
119
+ surfaces: {
120
+ admin: { services: allServices, runtimeTools: [preview] },
121
+ member: { services: memberServices, runtimeTools: [preview] },
122
+ },
123
+ selectSurface: (auth) => auth.isAdmin ? 'admin' : 'member',
124
+ })
125
+ ```
126
+
127
+ Keep direct `services(auth)` / `runtimeTools(auth)` only for genuinely
128
+ unbounded definitions; Stitchkit intentionally does not cache arbitrary auth
129
+ values.
130
+
131
+ Contract success bodies are now determined by the presence of `output`, not by
132
+ the handler's runtime value. A nullable output returns JSON `null` with status
133
+ `200`; `undefined` with a declared output and non-null data without an output
134
+ schema are contract violations:
135
+
136
+ ```ts
137
+ // nullable JSON data: 200 with body `null`
138
+ session: {
139
+ method: 'GET', path: '/session', desc: 'Current session',
140
+ output: SessionSchema.nullable(),
141
+ }
142
+
143
+ // bodyless operation: 204 with no body
144
+ logout: {
145
+ method: 'POST', path: '/logout', desc: 'End the session',
146
+ }
147
+ ```
148
+
149
+ Add an output schema to every handler that returns data. Omit `output` and
150
+ return nothing for bodyless operations; runtime tools follow the same rule and
151
+ type no-output handlers as `void`.
152
+
153
+ `createToolInvoker` now separates immutable registry preparation from per-call
154
+ runtime state. Move source/context/lifecycle/hooks/output-strip reporting from
155
+ the factory config to the third invocation argument. Use `invokeOrThrow` when a
156
+ nested operation should preserve the normalized `AppError` instead of returning
157
+ a model-facing failure envelope:
158
+
159
+ ```ts
160
+ // before
161
+ const invoker = createToolInvoker(services, {
162
+ transport: 'AGENT', context: { identity }, lifecycle, hooks,
163
+ })
164
+ const result = await invoker.invoke(name, args)
165
+
166
+ // after
167
+ const invoker = createToolInvoker(services, { transport: 'AGENT' })
168
+ const result = await invoker.invoke(name, args, {
169
+ context: { identity }, lifecycle, hooks,
170
+ })
171
+ const data = await invoker.invokeOrThrow(name, args, {
172
+ context: { identity }, lifecycle, hooks,
173
+ })
174
+ ```
175
+
176
+ There is no static runtime-config overload: request identity must not be retained
177
+ by a reusable compiled registry.
178
+
179
+ Entity cache handlers now require the cached list shape and CRUD policies. Move
180
+ `listKey` under `list`, make detail keys event-aware, and state the list-item
181
+ identity/projection explicitly:
182
+
183
+ ```ts
184
+ // before
185
+ createEntityCacheHandlers<Entity>({
186
+ getId,
187
+ listKey: ['entities'],
188
+ detailKey: (id) => ['entities', id],
189
+ })
190
+
191
+ // after
192
+ createEntityCacheHandlers<Entity, EntityListItem>({
193
+ getId,
194
+ getListItemId: (item) => item.id,
195
+ toListItem: (entity) => ({ id: entity.id, name: entity.name }),
196
+ list: {
197
+ key: ['entities'],
198
+ shape: 'paginated',
199
+ createAt: 'start',
200
+ updateMissing: 'skip',
201
+ },
202
+ detailKey: (event) => ['entities', event.id],
203
+ })
204
+ ```
205
+
206
+ Choose `array`, `paginated`, `infinite-array` or `infinite-paginated` to match
207
+ the actual cached data. A dynamic `list.key` / `detailKey` receives a
208
+ discriminated event and can derive scoped keys from the created/updated entity
209
+ or deleted payload. Add `compare` only when the backend has a canonical order;
210
+ the framework does not guess it or mutate pagination metadata.
211
+
212
+ Protected native MCP operations now use the transport-neutral runtime tool
213
+ definition. Return the schema-owned value from the handler and move MCP content
214
+ or metadata into `present.mcp`; `structuredContent` and `isError` are
215
+ framework-owned:
216
+
217
+ ```ts
218
+ // before
219
+ registerTool({ input, output, handler: async () => ({
220
+ content: [{ type: 'image', data, mimeType: 'image/png' }],
221
+ structuredContent: { assetId },
222
+ }) })
223
+
224
+ // after
225
+ const preview = defineRuntimeTool({
226
+ name: 'render_preview', description, identity, input, output,
227
+ handler: async () => ({ assetId, data }),
228
+ present: {
229
+ mcp: (result) => ({
230
+ content: [{ type: 'image', data: result.data, mimeType: 'image/png' }],
231
+ }),
232
+ },
233
+ })
234
+ runtimeTools: [preview]
235
+ ```
236
+
237
+ The removed `NativeMcp*` types have no aliases. Use `RuntimeToolDefinition`,
238
+ `RuntimeToolIdentity`, `RuntimeToolHandlerContext` and
239
+ `RuntimeMcpPresentation`. The same definition can now be passed to
240
+ `mountAgent(services, { runtimeTools: [preview] })`; add `present.agent` only
241
+ when the model needs rich text/file content instead of the neutral JSON result.
242
+
243
+ Trailing wildcards must be named consistently across the path and params schema:
244
+
245
+ ```ts
246
+ // before
247
+ path: '/app/:slug/*'
248
+ params: z.object({ slug: z.string(), '*': z.string() })
249
+ ctx.params['*']
250
+ api.app({ slug: 'foo', '*': 'a/b' })
251
+
252
+ // after
253
+ path: '/app/:slug/*filePath'
254
+ params: z.object({ slug: z.string(), filePath: z.string() })
255
+ ctx.params.filePath
256
+ api.app({ slug: 'foo', filePath: 'a/b' })
257
+ ```
258
+
259
+ Bare wildcards have no compatibility alias; raw routes use the same named form.
260
+
261
+ ### Expected-401 matchers
262
+
263
+ `HttpClientConfig.authEndpoints` is removed. Replace manual path prefixes with
264
+ the operations whose 401 response is expected:
265
+
266
+ ```ts
267
+ // before
268
+ createHttpClient({ baseUrl, authEndpoints: ['/api/auth/'] })
269
+
270
+ // after
271
+ createHttpClient({
272
+ baseUrl,
273
+ suppressUnauthorizedFor: contractEndpointMatchers(authContract, ['login', 'verify']),
274
+ })
275
+ ```
276
+
277
+ There is no implicit `/auth/` suppression. Omit `suppressUnauthorizedFor` when
278
+ every 401 should emit the global `unauthorized` event.
279
+
280
+ ## The 0.37 migration
281
+
282
+ Tool presentation is no longer an executable Zod parser. Replace the removed
283
+ flatten helpers with the JSON Schema compiler, and choose the explicit
284
+ `MountableTool` surface when using the advanced collection API:
285
+
286
+ ```ts
287
+ // before
288
+ const flat = flattenUnionsDeep(zodSchema)
289
+ mountable.schema
290
+
291
+ // after
292
+ const flat = flattenToolJsonSchema(
293
+ z.toJSONSchema(zodSchema, { target: 'draft-07', io: 'input' }),
294
+ )
295
+ mountable.presentationSchema // model/MCP/manifest JSON Schema
296
+ mountable.argumentSchema // executable CLI argument adapter only
297
+ ```
298
+
299
+ Contract and native handlers keep their original Zod schemas; MCP and agent SDK
300
+ adapters now forward raw arguments so defaults, coercions, refinements and
301
+ transforms execute exactly once inside Stitchkit. There are no compatibility
302
+ exports for `flattenDiscriminatedUnion`, `flattenUnionsDeep` or
303
+ `MountableTool.schema`. → ADR 0050
304
+
305
+ Tool-call hooks now take one options object. Migrate all three callbacks; there
306
+ are no positional overloads:
307
+
308
+ ```ts
309
+ // before
310
+ beforeToolCall: (toolName, args, context, endpoint) => {}
311
+ afterToolCall: (toolName, args, result, durationMs, context, endpoint, error) => {}
312
+ onToolError: (toolName, error, context, endpoint) => {}
313
+
314
+ // after
315
+ beforeToolCall: ({ toolName, args, context, endpoint }) => {}
316
+ afterToolCall: ({ toolName, args, result, durationMs, context, endpoint, error }) => {}
317
+ onToolError: ({ toolName, error, context, endpoint }) => {}
318
+ ```
319
+
320
+ ### MCP schema validation
321
+
322
+ The standalone validator now takes one object and live MCP configs carry the
323
+ same rules under `schemaValidation`. Migrate every positional call and every
324
+ `onIncompatibleSchema` field; there is no old-shape overload:
325
+
326
+ ```ts
327
+ // before
328
+ validateMcpSchemas(services, 'throw', logger, { requireTypedProperties: true })
329
+ createMcpHandler({ services, onIncompatibleSchema: 'throw' })
330
+
331
+ // after
332
+ validateMcpSchemas({ services, policy: 'throw', logger, requireTypedProperties: true })
333
+ createMcpHandler({ services, schemaValidation: { policy: 'throw' } })
334
+ ```
335
+
336
+ Put `extend` and `flattenUnionInput` beside `services`, not inside
337
+ `schemaValidation`. The handler applies the profile to the exact prepared schema
338
+ it advertises. Add `requirePortableFormats: true` when every custom JSON Schema
339
+ format must be rejected before a client sees it.
340
+
341
+ Native MCP registration also changed shape in 0.37. Move protected tools to the
342
+ framework registrar; keep an SDK-raw tool only by naming the opt-out:
343
+
344
+ ```ts
345
+ // before
346
+ nativeTools: (server, auth) => server.registerTool(name, config, handler)
347
+
348
+ // after — lifecycle, hooks and schema policy apply
349
+ nativeTools: ({ registerTool }, auth) => registerTool({
350
+ name, description, identity, input, output, handler,
351
+ })
352
+
353
+ // after — intentionally raw
354
+ nativeTools: ({ rawServer }, auth) => rawServer.registerTool(name, config, handler)
355
+ ```
356
+
357
+ If a tool hook annotated `endpoint` as `MethodDef`, remove that annotation or
358
+ use `OperationIdentity`: native operations have service/action/scope/method but
359
+ no HTTP path.
360
+
361
+ ### Node-facing server types
362
+
363
+ `stitchkit/server` remains Bun-concrete: an explicitly annotated `RawRoute`
364
+ still receives `BunServer`. `stitchkit/node` no longer drags Bun declarations
365
+ into a Node project. Its raw routes default the host server to `unknown`, and
366
+ its Socket.IO handle exposes only Node capabilities:
367
+
368
+ ```ts
369
+ // before — Node entry still leaked Bun-only fields and ambient types
370
+ const route: RawRoute = { handler: (_req, ctx) => ctx.server?.upgrade(...) }
371
+ const socket = await createSocketIOServer(config)
372
+ socket.websocket
373
+
374
+ // after — name a custom embedding host only when one exists
375
+ const route: RawRoute<MyHostServer> = {
376
+ handler: (_req, ctx) => useHost(ctx.server),
377
+ }
378
+ const socket = await createSocketIOServer(config)
379
+ socket.io
380
+ socket.attach(nodeHttpServer)
381
+ ```
382
+
383
+ Node consumers can remove `@types/bun` unless another dependency independently
384
+ requires it.
385
+
386
+ ### Managed server shutdown
387
+
388
+ `createServer()` and `serveNode()` now return the same structural managed
389
+ lifecycle. Replace every direct runtime stop and parallel Socket.IO close:
390
+
391
+ ```ts
392
+ // before — split ownership
393
+ const socket = await createSocketIOServer(config)
394
+ const server = createServer({
395
+ services,
396
+ websocket: socket.websocket,
397
+ rawRoutes: [socket.route],
398
+ })
399
+ server.stop()
400
+ await socket.io.close()
401
+
402
+ // after — one owner and one total deadline
403
+ const socket = await createSocketIOServer(config)
404
+ const server = createServer({ services, socket })
405
+ const result = await server.shutdown({ gracePeriodMs: 30_000 })
406
+ ```
407
+
408
+ On Node, keep the same `socket` field and replace `handle.close()` with
409
+ `handle.shutdown()`. Runtime-specific diagnostics move under `handle.runtime`;
410
+ do not use it as a second shutdown path. Standalone CLI/tools that create a
411
+ Socket.IO handle without an HTTP server call `await socket.close()`.
412
+
413
+ If Bun Socket.IO shares the port with a raw lane, keep the explicit composition
414
+ but let the server mount the Socket.IO route:
415
+
416
+ ```ts
417
+ createServer({
418
+ services,
419
+ socket,
420
+ websocket: composeWebSocketHandlers([
421
+ webSocketLane({ match: isRaw, handlers: rawHandlers }),
422
+ socketIoLane(socket.websocket),
423
+ ]),
424
+ rawRoutes: [rawUpgradeRoute],
425
+ })
426
+ ```
427
+
428
+ Move native Bun `routes` entries to `rawRoutes`. Native routes run before the
429
+ Fetch handler and therefore cannot participate in admission or drain. Wire
430
+ `SIGTERM`/`SIGINT` in the application; the first signal starts `shutdown()`, and
431
+ a later signal may abort the same controller. Close MCP, databases and queues
432
+ after the server result—those resources remain application-owned.
433
+
434
+ Move a handshake policy from the Node-only callback shape inside
435
+ `serverOptions` to the runtime-neutral top-level policy. It receives a Web
436
+ `Request`, may be async, and returns whether to admit the handshake:
437
+
438
+ ```ts
439
+ // before
440
+ serverOptions: { allowRequest: (request, done) => done(null, allowed(request)) }
441
+
442
+ // after
443
+ allowRequest: (request) => allowed(request)
444
+ ```