stitchkit 0.70.4 → 0.70.5

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.
@@ -29,7 +29,7 @@ import {
29
29
  ApplicationShutdownBudgetSchema,
30
30
  ApplicationShutdownOptionsSchema,
31
31
  createApplication
32
- } from "./index-w0445741.js";
32
+ } from "./index-hvftzz91.js";
33
33
  import {
34
34
  defineManagedResource,
35
35
  managedResourceDependencyId
@@ -47,7 +47,7 @@ import {
47
47
  ManagedResourceStateSchema,
48
48
  projectApplicationStatus
49
49
  } from "./index-8eywc9zv.js";
50
- import"./index-7wpgrqa8.js";
50
+ import"./index-3z73fh2c.js";
51
51
  import"./index-0w9abg87.js";
52
52
  import {
53
53
  isRecord
@@ -1,5 +1,84 @@
1
1
  // src/server/shutdown.ts
2
2
  import { z } from "zod";
3
+
4
+ // src/server/http-stream-lifetime.ts
5
+ var requests = new WeakMap;
6
+ function isStreamCancellation(error, signal) {
7
+ return signal.aborted && (error === signal.reason || error instanceof Error && error.name === "AbortError" && error.cause === signal.reason);
8
+ }
9
+ function ownHttpStream(request, stream) {
10
+ requests.get(request)?.add(stream);
11
+ }
12
+ async function settleStreamCleanup(operations) {
13
+ const results = await Promise.allSettled(operations);
14
+ const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
15
+ if (errors.length)
16
+ throw new AggregateError(errors, "HTTP stream source did not close cleanly");
17
+ }
18
+ function createHttpStreamTracker() {
19
+ const streams = new Map;
20
+ const failures = [];
21
+ let draining = false;
22
+ const assertClean = () => {
23
+ if (failures.length) {
24
+ throw new AggregateError(failures, "[stitchkit] HTTP stream cleanup failed");
25
+ }
26
+ };
27
+ return {
28
+ bind(request, onComplete) {
29
+ let handlerDone = false;
30
+ let pending = 0;
31
+ const complete = () => {
32
+ if (!handlerDone || pending !== 0)
33
+ return;
34
+ requests.delete(request);
35
+ onComplete();
36
+ };
37
+ requests.set(request, {
38
+ add(stream) {
39
+ pending += 1;
40
+ streams.set(stream, request);
41
+ stream.settled.then(() => {
42
+ streams.delete(stream);
43
+ pending -= 1;
44
+ complete();
45
+ }, (error) => {
46
+ if (draining)
47
+ failures.push(error);
48
+ else
49
+ console.error("[stitchkit] HTTP stream cleanup failed:", error);
50
+ streams.delete(stream);
51
+ pending -= 1;
52
+ complete();
53
+ });
54
+ if (draining)
55
+ stream.cancel();
56
+ }
57
+ });
58
+ return () => {
59
+ handlerDone = true;
60
+ complete();
61
+ };
62
+ },
63
+ get pendingRequests() {
64
+ return new Set(streams.values()).size;
65
+ },
66
+ cancel() {
67
+ draining = true;
68
+ for (const stream of streams.keys())
69
+ stream.cancel();
70
+ },
71
+ assertClean,
72
+ async drain() {
73
+ while (streams.size) {
74
+ await Promise.allSettled([...streams.keys()].map((stream) => stream.settled));
75
+ }
76
+ assertClean();
77
+ }
78
+ };
79
+ }
80
+
81
+ // src/server/shutdown.ts
3
82
  var ShutdownStateSchema = z.enum([
4
83
  "running",
5
84
  "draining-http",
@@ -109,13 +188,15 @@ function createServerLifecycle(getAdapter) {
109
188
  let pendingApplicationRequests = 0;
110
189
  let retryAfterSeconds = 5;
111
190
  let shutdownPromise;
191
+ const streams = createHttpStreamTracker();
192
+ const pendingRequests = () => Math.max(getAdapter().pendingRequests(), streams.pendingRequests);
112
193
  const status = () => {
113
194
  const adapter = getAdapter();
114
195
  return ShutdownStatusSchema.parse({
115
196
  state,
116
197
  acceptedRequests,
117
198
  completedRequests,
118
- pendingRequests: adapter.pendingRequests(),
199
+ pendingRequests: pendingRequests(),
119
200
  pendingWebSockets: adapter.pendingWebSockets()
120
201
  });
121
202
  };
@@ -125,11 +206,14 @@ function createServerLifecycle(getAdapter) {
125
206
  return rejectedResponse(retryAfterSeconds);
126
207
  acceptedRequests += 1;
127
208
  pendingApplicationRequests += 1;
209
+ const complete = streams.bind(request, () => {
210
+ completedRequests += 1;
211
+ });
128
212
  try {
129
213
  return await handler(request, server);
130
214
  } finally {
131
215
  pendingApplicationRequests -= 1;
132
- completedRequests += 1;
216
+ complete();
133
217
  }
134
218
  };
135
219
  };
@@ -142,6 +226,7 @@ function createServerLifecycle(getAdapter) {
142
226
  const adapter = getAdapter();
143
227
  state = "draining-http";
144
228
  adapter.beginShutdown(retryAfterSeconds);
229
+ streams.cancel();
145
230
  shutdownPromise = new Promise((resolve, reject) => {
146
231
  const phaseAbort = new AbortController;
147
232
  let forcedReason;
@@ -164,7 +249,8 @@ function createServerLifecycle(getAdapter) {
164
249
  };
165
250
  (async () => {
166
251
  try {
167
- await waitForZero(() => pendingApplicationRequests, phaseAbort.signal);
252
+ await waitForZero(() => pendingApplicationRequests + streams.pendingRequests, phaseAbort.signal);
253
+ streams.assertClean();
168
254
  if (!forcedReason) {
169
255
  state = "closing-realtime";
170
256
  const realtimeOutcome = await closeRealtimeWithin(adapter, parsed.realtimeCloseTimeoutMs, phaseAbort.signal);
@@ -189,13 +275,13 @@ function createServerLifecycle(getAdapter) {
189
275
  let pendingWebSocketsAtForce = 0;
190
276
  if (forcedReason) {
191
277
  state = "stopping-runtime";
192
- pendingRequestsAtForce = adapter.pendingRequests();
278
+ pendingRequestsAtForce = pendingRequests();
193
279
  pendingWebSocketsAtForce = adapter.pendingWebSockets();
194
280
  forcedWebSockets += pendingWebSocketsAtForce;
195
281
  let forceError;
196
282
  let forceFailed = false;
197
283
  try {
198
- await withTimeout(adapter.forceStop(), parsed.forceTimeoutMs, `[stitchkit] forced shutdown did not complete within ${parsed.forceTimeoutMs}ms`);
284
+ await withTimeout(Promise.all([adapter.forceStop(), streams.drain()]), parsed.forceTimeoutMs, `[stitchkit] forced shutdown did not complete within ${parsed.forceTimeoutMs}ms`);
199
285
  } catch (error) {
200
286
  forceFailed = true;
201
287
  forceError = error;
@@ -219,7 +305,7 @@ function createServerLifecycle(getAdapter) {
219
305
  ...forcedReason && { reason: forcedReason },
220
306
  acceptedRequests,
221
307
  completedRequests,
222
- pendingRequests: adapter.pendingRequests(),
308
+ pendingRequests: pendingRequests(),
223
309
  pendingWebSockets: adapter.pendingWebSockets(),
224
310
  pendingRequestsAtForce,
225
311
  pendingWebSocketsAtForce,
@@ -243,4 +329,4 @@ function createServerLifecycle(getAdapter) {
243
329
  };
244
330
  }
245
331
 
246
- export { ShutdownStateSchema, ShutdownOptionsSchema, ShutdownStatusSchema, ShutdownResultSchema, createServerLifecycle };
332
+ export { isStreamCancellation, ownHttpStream, settleStreamCleanup, ShutdownStateSchema, ShutdownOptionsSchema, ShutdownStatusSchema, ShutdownResultSchema, createServerLifecycle };
@@ -20,8 +20,11 @@ import {
20
20
  setRequestError
21
21
  } from "./index-w9m1wznn.js";
22
22
  import {
23
- ShutdownOptionsSchema
24
- } from "./index-7wpgrqa8.js";
23
+ ShutdownOptionsSchema,
24
+ isStreamCancellation,
25
+ ownHttpStream,
26
+ settleStreamCleanup
27
+ } from "./index-3z73fh2c.js";
25
28
  import {
26
29
  errorCode,
27
30
  normalizeError,
@@ -598,8 +601,28 @@ function streamingRoute(options) {
598
601
  handler: async (request, context) => {
599
602
  applyIdleTimeout(context.server, request, idleTimeoutSeconds);
600
603
  const departed = new AbortController;
601
- const iterable = await options.source(request, { ...context, signal: departed.signal });
602
- const iterator = iterable[Symbol.asyncIterator]();
604
+ const settled = Promise.withResolvers();
605
+ settled.promise.catch(() => {
606
+ return;
607
+ });
608
+ const pumped = Promise.withResolvers();
609
+ pumped.promise.catch(() => {
610
+ return;
611
+ });
612
+ let cancel = () => departed.abort();
613
+ ownHttpStream(request, { cancel: () => cancel(), settled: settled.promise });
614
+ let iterator;
615
+ try {
616
+ const iterable = await options.source(request, {
617
+ ...context,
618
+ signal: departed.signal
619
+ });
620
+ iterator = iterable[Symbol.asyncIterator]();
621
+ } catch (error) {
622
+ departed.abort();
623
+ settled.reject(error);
624
+ throw error;
625
+ }
603
626
  const encoder2 = new TextEncoder;
604
627
  let heartbeat = null;
605
628
  let closed = false;
@@ -613,15 +636,22 @@ function streamingRoute(options) {
613
636
  if (closed)
614
637
  return;
615
638
  closed = true;
639
+ stopHeartbeat();
640
+ signalDemand();
641
+ request.signal.removeEventListener("abort", onRequestAbort);
642
+ departed.abort();
643
+ const hook = Promise.withResolvers();
616
644
  try {
617
645
  options.onClose?.();
618
- stopHeartbeat();
619
- signalDemand();
620
- departed.abort();
621
- Promise.resolve(iterator.return?.(undefined)).catch(() => {
622
- return;
623
- });
624
- } catch {}
646
+ hook.resolve();
647
+ } catch (error) {
648
+ hook.reject(error);
649
+ }
650
+ settleStreamCleanup([
651
+ hook.promise,
652
+ pumped.promise,
653
+ Promise.resolve().then(() => iterator.return?.(undefined))
654
+ ]).then(() => settled.resolve(), (error) => settled.reject(error));
625
655
  };
626
656
  let demand = null;
627
657
  const signalDemand = () => {
@@ -629,6 +659,7 @@ function streamingRoute(options) {
629
659
  demand = null;
630
660
  resolve?.();
631
661
  };
662
+ const onRequestAbort = () => cancel();
632
663
  const stream = new ReadableStream({
633
664
  start(controller) {
634
665
  const send = (text) => {
@@ -647,15 +678,16 @@ function streamingRoute(options) {
647
678
  controller.close();
648
679
  } catch {}
649
680
  };
650
- if (request.signal.aborted) {
681
+ cancel = () => {
651
682
  release();
652
683
  finish();
684
+ };
685
+ if (request.signal.aborted || departed.signal.aborted) {
686
+ pumped.resolve();
687
+ cancel();
653
688
  return;
654
689
  }
655
- request.signal.addEventListener("abort", () => {
656
- release();
657
- finish();
658
- });
690
+ request.signal.addEventListener("abort", onRequestAbort, { once: true });
659
691
  send(framing.keepAlive);
660
692
  heartbeat = setInterval(() => {
661
693
  if ((controller.desiredSize ?? 1) > 0)
@@ -696,9 +728,13 @@ function streamingRoute(options) {
696
728
  if (framing.done)
697
729
  send(framing.done);
698
730
  } catch (error) {
699
- if (!closed)
731
+ if (closed) {
732
+ if (!isStreamCancellation(error, departed.signal))
733
+ pumped.reject(error);
734
+ } else
700
735
  send(framing.frame(normalizeError(error).toJSON()));
701
736
  } finally {
737
+ pumped.resolve();
702
738
  release();
703
739
  finish();
704
740
  }
@@ -890,9 +926,32 @@ function waitForAbort(signal) {
890
926
  function contractStreamResponse(request, context, source, descriptor, operationAbort) {
891
927
  const format = descriptor.format ?? "ndjson";
892
928
  const maxFrameBytes = descriptor.maxFrameBytes ?? DEFAULT_CONTRACT_STREAM_FRAME_BYTES;
929
+ const iterator = source[Symbol.asyncIterator]();
930
+ let pendingNext;
931
+ const settled = Promise.withResolvers();
932
+ settled.promise.catch(() => {
933
+ return;
934
+ });
893
935
  let lifetime;
894
936
  let lifetimeExpired = false;
895
- if (descriptor.lifetimeMs !== undefined) {
937
+ let closing = false;
938
+ const closeSource = (cancelled = operationAbort.signal.aborted) => {
939
+ if (closing)
940
+ return;
941
+ closing = true;
942
+ if (lifetime !== undefined)
943
+ clearTimeout(lifetime);
944
+ operationAbort.abort();
945
+ settleStreamCleanup([
946
+ Promise.resolve(pendingNext).catch((error) => {
947
+ if (cancelled && !isStreamCancellation(error, operationAbort.signal))
948
+ throw error;
949
+ }),
950
+ Promise.resolve().then(() => iterator.return?.(undefined))
951
+ ]).then(() => settled.resolve(), (error) => settled.reject(error));
952
+ };
953
+ ownHttpStream(request, { cancel: () => closeSource(true), settled: settled.promise });
954
+ if (descriptor.lifetimeMs !== undefined && !closing) {
896
955
  lifetime = setTimeout(() => {
897
956
  lifetimeExpired = true;
898
957
  operationAbort.abort(new Error("Stream lifetime expired"));
@@ -900,12 +959,14 @@ function contractStreamResponse(request, context, source, descriptor, operationA
900
959
  lifetime.unref?.();
901
960
  }
902
961
  const frames = async function* () {
903
- const iterator = source[Symbol.asyncIterator]();
962
+ if (closing)
963
+ return;
904
964
  const aborted = waitForAbort(operationAbort.signal);
905
965
  let terminalSeen = descriptor.terminal === undefined;
906
966
  try {
907
967
  for (;; ) {
908
- const next = await Promise.race([iterator.next(), aborted]);
968
+ pendingNext = Promise.resolve(iterator.next());
969
+ const next = await Promise.race([pendingNext, aborted]);
909
970
  if (next.done)
910
971
  break;
911
972
  const parsed = descriptor.item.safeParse(next.value);
@@ -951,10 +1012,7 @@ function contractStreamResponse(request, context, source, descriptor, operationA
951
1012
  } finally {
952
1013
  if (lifetime !== undefined)
953
1014
  clearTimeout(lifetime);
954
- operationAbort.abort();
955
- Promise.resolve(iterator.return?.(undefined)).catch(() => {
956
- return;
957
- });
1015
+ closeSource();
958
1016
  }
959
1017
  };
960
1018
  const route = streamingRoute({
@@ -8,7 +8,7 @@ import {
8
8
  } from "./index-8eywc9zv.js";
9
9
  import {
10
10
  ShutdownOptionsSchema
11
- } from "./index-7wpgrqa8.js";
11
+ } from "./index-3z73fh2c.js";
12
12
  import {
13
13
  AppError
14
14
  } from "./index-0w9abg87.js";
package/dist/node.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  createHandler,
6
6
  createSocketIOServer,
7
7
  createUnixClientTransport
8
- } from "./index-c97p90dc.js";
8
+ } from "./index-cx84zg25.js";
9
9
  import {
10
10
  createImplement,
11
11
  createImplementRegistry,
@@ -23,7 +23,7 @@ import {
23
23
  ShutdownStateSchema,
24
24
  ShutdownStatusSchema,
25
25
  createServerLifecycle
26
- } from "./index-7wpgrqa8.js";
26
+ } from "./index-3z73fh2c.js";
27
27
  import"./index-nt1mp8km.js";
28
28
  import"./index-vj3vvpaa.js";
29
29
  import {
@@ -1 +1 @@
1
- {"version":3,"file":"contract-stream.d.ts","sourceRoot":"","sources":["../../src/server/contract-stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,wBAAwB,EAC9B,MAAM,aAAa,CAAC;AAGrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAiB/C,gEAAgE;AAChE,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,eAAe,EACxB,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAC9B,UAAU,EAAE,wBAAwB,EACpC,cAAc,EAAE,eAAe,GAC9B,OAAO,CAAC,QAAQ,CAAC,CA6FnB"}
1
+ {"version":3,"file":"contract-stream.d.ts","sourceRoot":"","sources":["../../src/server/contract-stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,wBAAwB,EAC9B,MAAM,aAAa,CAAC;AAQrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAiB/C,gEAAgE;AAChE,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,eAAe,EACxB,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAC9B,UAAU,EAAE,wBAAwB,EACpC,cAAc,EAAE,eAAe,GAC9B,OAAO,CAAC,QAAQ,CAAC,CAoHnB"}
@@ -0,0 +1,19 @@
1
+ /** Request identity stays native: cloning it would break runtime timeout/upgrade APIs. */
2
+ interface StreamLifetime {
3
+ cancel(): void;
4
+ settled: Promise<void>;
5
+ }
6
+ /** Abort-aware I/O may reject with the signal reason or wrap it as its cause. */
7
+ export declare function isStreamCancellation(error: unknown, signal: AbortSignal): boolean;
8
+ /** Internal bridge between Fetch-clean streaming routes and their managed server. */
9
+ export declare function ownHttpStream(request: Request, stream: StreamLifetime): void;
10
+ export declare function settleStreamCleanup(operations: readonly Promise<unknown>[]): Promise<void>;
11
+ export declare function createHttpStreamTracker(): {
12
+ bind(request: Request, onComplete: () => void): () => void;
13
+ readonly pendingRequests: number;
14
+ cancel(): void;
15
+ assertClean: () => void;
16
+ drain(): Promise<void>;
17
+ };
18
+ export {};
19
+ //# sourceMappingURL=http-stream-lifetime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-stream-lifetime.d.ts","sourceRoot":"","sources":["../../src/server/http-stream-lifetime.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,UAAU,cAAc;IACtB,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAQD,iFAAiF;AACjF,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAMjF;AAED,qFAAqF;AACrF,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI,CAE5E;AAED,wBAAsB,mBAAmB,CACvC,UAAU,EAAE,SAAS,OAAO,CAAC,OAAO,CAAC,EAAE,GACtC,OAAO,CAAC,IAAI,CAAC,CAOf;AAED,wBAAgB,uBAAuB;kBAWrB,OAAO,cAAc,MAAM,IAAI,GAAG,MAAM,IAAI;8BAkCnC,MAAM;;;;EAehC"}
@@ -13,7 +13,7 @@ import {
13
13
  sseRoute,
14
14
  streamingRoute,
15
15
  webSocketLane
16
- } from "../index-c97p90dc.js";
16
+ } from "../index-cx84zg25.js";
17
17
  import {
18
18
  composeAuthHooks,
19
19
  createAuthHook,
@@ -60,7 +60,7 @@ import {
60
60
  ShutdownStateSchema,
61
61
  ShutdownStatusSchema,
62
62
  createServerLifecycle
63
- } from "../index-7wpgrqa8.js";
63
+ } from "../index-3z73fh2c.js";
64
64
  import {
65
65
  jsonSchemaFields,
66
66
  toJsonSchema
@@ -1 +1 @@
1
- {"version":3,"file":"shutdown.d.ts","sourceRoot":"","sources":["../../src/server/shutdown.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C,eAAO,MAAM,mBAAmB;;;;;;;EAO9B,CAAC;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEhE,eAAO,MAAM,qBAAqB;;;;;;iBAehC,CAAC;AACH,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAEpE,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;iBAM/B,CAAC;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAElE,eAAO,MAAM,o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C,qBAAqB,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,GACtD,QAAQ,CAAC,OAAO,CAAC,CAEnB"}
package/dist/testing.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  } from "./index-x1th9s8c.js";
5
5
  import {
6
6
  createApplication
7
- } from "./index-w0445741.js";
7
+ } from "./index-hvftzz91.js";
8
8
  import"./index-2k4yrqkc.js";
9
9
  import"./index-8eywc9zv.js";
10
10
  import {
@@ -12,7 +12,7 @@ import {
12
12
  RealtimeRequestInvalidAcknowledgementError,
13
13
  RealtimeRequestTimeoutError
14
14
  } from "./index-7b188kmz.js";
15
- import"./index-7wpgrqa8.js";
15
+ import"./index-3z73fh2c.js";
16
16
  import {
17
17
  mcpProjectionCandidate,
18
18
  prepareProjectedMcpTools,
package/llms-full.txt CHANGED
@@ -960,8 +960,11 @@ const result = await server.shutdown({
960
960
  })
961
961
  ```
962
962
 
963
- The first call closes HTTP and Socket.IO admission, then gives admitted HTTP/application work the
964
- full `gracePeriodMs` budget. Once that work drains, `realtimeCloseTimeoutMs` (default `1_000`)
963
+ The first call closes HTTP and Socket.IO admission and cancels owned contract streams and
964
+ `streamingRoute` / `ndjsonRoute` / `sseRoute` sources. Their supplied `signal` is the lifetime:
965
+ waiting producers must honour it, and their iterator cleanup must finish. No separate application
966
+ abort controller or copied shutdown loop is required. Admitted finite HTTP/application work and
967
+ stream cleanup share the full `gracePeriodMs` budget. Once that work drains, `realtimeCloseTimeoutMs` (default `1_000`)
965
968
  bounds WebSocket close handshakes inside the same outer deadline. Any upgraded sockets still open
966
969
  at that boundary are terminated without shortening HTTP grace, and graceful runtime shutdown
967
970
  continues. If the outer grace budget or external signal forces destructive teardown,
@@ -970,11 +973,18 @@ the first options win. New
970
973
  ordinary HTTP work receives `503`, `Retry-After` and `Connection: close` outside
971
974
  `wrapFetch`. `result.outcome` is `clean` or `forced`; a forced result preserves
972
975
  the pending snapshot and reason while final pending counters describe the
973
- post-close transport state. `forcedWebSockets` counts both sockets terminated at the dedicated
976
+ post-close transport state and any still-owned stream cleanup. A streaming request increments
977
+ `completedRequests` only after its source cleanup settles, not when its `Response` is returned.
978
+ `abortedRequests` counts requests pending at outer force, not subscriptions closed cooperatively
979
+ during grace. `forcedWebSockets` counts both sockets terminated at the dedicated
974
980
  realtime bound and sockets terminated by outer force; `pendingWebSocketsAtForce` is only the latter
975
981
  snapshot, so a clean result can truthfully report a bounded realtime termination. A graceful phase error still runs forced cleanup and
976
982
  then rejects with the original error; a forced transport that cannot confirm
977
- completion before `forceTimeoutMs` rejects instead of reporting a false zero.
983
+ completion before `forceTimeoutMs` rejects instead of reporting a false zero. An uncooperative
984
+ stream stays pending even if its connection is gone; a cleanup error rejects shutdown.
985
+ Standalone `createHandler` and arbitrary raw `Response` bodies have no managed source ownership:
986
+ their embedding host/producer owns cancellation. Request identity must be retained by `wrapFetch`
987
+ when forwarding to owned streaming routes; it is also required by native timeout/upgrade APIs.
978
988
  `runtime` is a diagnostics escape hatch, not a second canonical stop path.
979
989
 
980
990
  ### Trusted HTTPS in development
@@ -5219,6 +5229,12 @@ try {
5219
5229
  `release()` is idempotent. Admission and counter increment are atomic, so work
5220
5230
  cannot slip between the shutdown check and drain accounting.
5221
5231
 
5232
+ `managedServerResource` already owns contract/streaming-route response lifetimes. It cancels
5233
+ their supplied signals at admission close and awaits source cleanup before dependent resources
5234
+ close. Do not add application admission leases or a second cancellation registry for those
5235
+ streams. A source that ignores cancellation or fails its cleanup prevents a clean shutdown;
5236
+ the existing grace and force budgets still bound the result.
5237
+
5222
5238
  ### Bounded operation admission
5223
5239
 
5224
5240
  Compose `createBoundedAdmission` when accepted work also competes for a finite
@@ -11943,7 +11959,7 @@ Also re-exports the error helpers from `stitchkit/contract`.
11943
11959
  | `BunServerHandle` | _type_ | managed Bun handle (`url`, `port`, `runtime`, `status`, `shutdown`) |
11944
11960
  | `ManagedServerHandle` | _type_ | shared lifecycle shape generic over the runtime escape hatch |
11945
11961
  | `ShutdownOptionsSchema` / `ShutdownOptions` | schema / _type_ | HTTP/application grace, a separate WebSocket close-handshake bound, bounded forced-completion timeout, retry hint and optional external abort signal |
11946
- | `ShutdownStatusSchema` / `ShutdownStatus` | schema / _type_ | live state and request/WebSocket counters |
11962
+ | `ShutdownStatusSchema` / `ShutdownStatus` | schema / _type_ | live state and request/WebSocket counters; owned streams remain pending through source cleanup |
11947
11963
  | `ShutdownResultSchema` / `ShutdownResult` | schema / _type_ | clean/forced result with final counters, outer-force snapshots and `forcedWebSockets` including bounded realtime terminations |
11948
11964
  | `ShutdownStateSchema` / `ShutdownState` | schema / _type_ | managed lifecycle state machine |
11949
11965
  | `ServiceDef` | _type_ | the result of `implement` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stitchkit",
3
- "version": "0.70.4",
3
+ "version": "0.70.5",
4
4
  "description": "Contract-first backend framework — one defineContract() into an HTTP API, MCP tools, AI-agent tools and a typed client. Bun and Node.",
5
5
  "keywords": [
6
6
  "bun",