stitchkit 0.69.0 → 0.70.1

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.
Files changed (59) hide show
  1. package/README.md +4 -4
  2. package/dist/agent-runtime/coding-tool-contract.d.ts +1 -0
  3. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -1
  4. package/dist/agent-runtime/coding-tool-files.d.ts.map +1 -1
  5. package/dist/agent-runtime/coding-tool-paths.d.ts +1 -1
  6. package/dist/agent-runtime/coding-tool-paths.d.ts.map +1 -1
  7. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +1 -1
  8. package/dist/agent-runtime/coding-tool-shell.d.ts.map +1 -1
  9. package/dist/agent-runtime/contained-files.d.ts +52 -4
  10. package/dist/agent-runtime/contained-files.d.ts.map +1 -1
  11. package/dist/agent-runtime/harness-file-resources.d.ts.map +1 -1
  12. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  13. package/dist/agent-runtime-coding-tools.js +202 -145
  14. package/dist/agent-runtime-harness.js +12 -8
  15. package/dist/agent-runtime.js +9 -7
  16. package/dist/application/server-resource.d.ts +1 -0
  17. package/dist/application/server-resource.d.ts.map +1 -1
  18. package/dist/application.js +5 -2
  19. package/dist/cli.js +7 -6
  20. package/dist/{index-t4dpby6e.js → index-0yphgata.js} +1 -1
  21. package/dist/index-1z5xxfst.js +397 -0
  22. package/dist/index-3xnq72rz.js +21 -0
  23. package/dist/{index-444747ww.js → index-4g196jmf.js} +14 -9
  24. package/dist/{index-kg9xx84n.js → index-7rey2b8s.js} +1 -1
  25. package/dist/{index-dk6e56g0.js → index-7wpgrqa8.js} +37 -2
  26. package/dist/{index-zh459sfj.js → index-aczggrty.js} +1 -1
  27. package/dist/index-bd17ytae.js +192 -0
  28. package/dist/{index-q7gdep2c.js → index-da1aqnhb.js} +2 -2
  29. package/dist/{index-p1be103g.js → index-ktsps64f.js} +4 -2
  30. package/dist/{index-mbxds404.js → index-mjx0wt4c.js} +8 -6
  31. package/dist/{index-h8vn1jcr.js → index-qzbg46b6.js} +6 -4
  32. package/dist/{index-h7ctj1kp.js → index-s8nt8c22.js} +14 -11
  33. package/dist/{index-d1jsvkyk.js → index-vbf2p6me.js} +1 -1
  34. package/dist/{index-xxsq3ca1.js → index-vc498pst.js} +1 -1
  35. package/dist/{index-x18ndp4p.js → index-vj3vvpaa.js} +1 -192
  36. package/dist/{index-3eqrkqhg.js → index-vy5bjy07.js} +7 -3
  37. package/dist/{index-6wzr93cg.js → index-w0445741.js} +1 -1
  38. package/dist/{index-kxxyvkka.js → index-wc80at9n.js} +2 -2
  39. package/dist/{index-gqdfpv4n.js → index-y3w12g8d.js} +2 -2
  40. package/dist/node.js +26 -5
  41. package/dist/observability/index.js +4 -3
  42. package/dist/remote.js +4 -3
  43. package/dist/server/bun.d.ts.map +1 -1
  44. package/dist/server/index.js +20 -10
  45. package/dist/server/node.d.ts.map +1 -1
  46. package/dist/server/process-signals.d.ts.map +1 -1
  47. package/dist/server/shutdown.d.ts +2 -0
  48. package/dist/server/shutdown.d.ts.map +1 -1
  49. package/dist/testing.js +6 -5
  50. package/dist/tool-invoker.js +6 -5
  51. package/dist/tools/agent-tool-error.d.ts +14 -0
  52. package/dist/tools/agent-tool-error.d.ts.map +1 -0
  53. package/dist/tools/agent.d.ts.map +1 -1
  54. package/dist/tools.js +15 -12
  55. package/llms-full.txt +73 -22
  56. package/native/darwin-arm64.node +0 -0
  57. package/native/darwin-x64.node +0 -0
  58. package/package.json +3 -1
  59. package/dist/index-v3dpzpjw.js +0 -92
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  normalizeError
3
- } from "./index-x18ndp4p.js";
3
+ } from "./index-bd17ytae.js";
4
4
 
5
5
  // src/internal/bounded-lines.ts
6
6
  var DEFAULT_STREAM_LINE_BYTES = 1024 * 1024;
@@ -0,0 +1,397 @@
1
+ // src/agent-runtime/contained-files.ts
2
+ import {
3
+ close as closeDescriptor,
4
+ constants,
5
+ existsSync,
6
+ fchmod,
7
+ fstat,
8
+ read as readDescriptor,
9
+ write as writeDescriptor
10
+ } from "node:fs";
11
+ import { lstat, open, readdir, realpath, rename, unlink, writeFile } from "node:fs/promises";
12
+ import { createRequire } from "node:module";
13
+ import path from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ var FILE_TYPE_MASK = 61440;
16
+ var FILE_TYPE_DIRECTORY = 16384;
17
+ var FILE_TYPE_REGULAR = 32768;
18
+ var FILE_TYPE_SYMLINK = 40960;
19
+ function modeIs(mode, type) {
20
+ return (mode & FILE_TYPE_MASK) === type;
21
+ }
22
+ function hasFunctions(value, names) {
23
+ return typeof value === "object" && value !== null && names.every((name) => typeof Reflect.get(value, name) === "function");
24
+ }
25
+ var darwinBinding;
26
+ function loadDarwinBinding() {
27
+ if (darwinBinding)
28
+ return darwinBinding;
29
+ const directory = path.dirname(fileURLToPath(import.meta.url));
30
+ const binary = `darwin-${process.arch}.node`;
31
+ const candidates = [
32
+ path.resolve(directory, "../native", binary),
33
+ path.resolve(directory, "../../native", binary)
34
+ ];
35
+ const selected = candidates.find((candidate) => existsSync(candidate));
36
+ if (!selected) {
37
+ throw new Error(`Contained filesystem operations need the packaged Darwin ${process.arch} backend`);
38
+ }
39
+ const loaded = createRequire(import.meta.url)(selected);
40
+ const methods = [
41
+ "openDirectoryAt",
42
+ "openFileAt",
43
+ "createFileAt",
44
+ "statAt",
45
+ "listAt",
46
+ "renameAt",
47
+ "unlinkAt"
48
+ ];
49
+ if (!hasFunctions(loaded, methods)) {
50
+ throw new Error("The packaged Darwin contained-files backend has an invalid surface");
51
+ }
52
+ darwinBinding = loaded;
53
+ return darwinBinding;
54
+ }
55
+
56
+ class NumericFileHandle {
57
+ fd;
58
+ constructor(fd) {
59
+ this.fd = fd;
60
+ }
61
+ close() {
62
+ return new Promise((resolve, reject) => {
63
+ closeDescriptor(this.fd, (error) => error ? reject(error) : resolve());
64
+ });
65
+ }
66
+ read(buffer, offset, length, position) {
67
+ return new Promise((resolve, reject) => {
68
+ readDescriptor(this.fd, buffer, offset, length, position, (error, bytesRead) => error ? reject(error) : resolve({ bytesRead }));
69
+ });
70
+ }
71
+ stat() {
72
+ return new Promise((resolve, reject) => {
73
+ fstat(this.fd, (error, metadata) => error ? reject(error) : resolve(metadata));
74
+ });
75
+ }
76
+ }
77
+ function descriptorPath(handle) {
78
+ if (process.platform === "linux")
79
+ return `/proc/self/fd/${handle.fd}`;
80
+ throw new Error("Descriptor paths are available only in the Linux contained-files backend");
81
+ }
82
+ function sameIdentity(left, right) {
83
+ return left.dev === right.dev && left.ino === right.ino;
84
+ }
85
+ async function openPinnedDirectory(absolute) {
86
+ if (process.platform !== "linux" && process.platform !== "darwin") {
87
+ throw new Error("Contained filesystem operations support Linux and macOS only");
88
+ }
89
+ const expected = await realpath(absolute);
90
+ const handle = await open(expected, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
91
+ try {
92
+ const [pathMetadata, handleMetadata] = await Promise.all([lstat(expected), handle.stat()]);
93
+ if (!pathMetadata.isDirectory() || !sameIdentity(pathMetadata, handleMetadata)) {
94
+ throw new Error("Contained directory identity changed while opening");
95
+ }
96
+ return handle;
97
+ } catch (error) {
98
+ await handle.close();
99
+ throw error;
100
+ }
101
+ }
102
+ function safeSegments(relative) {
103
+ if (path.isAbsolute(relative))
104
+ throw new Error("Contained paths must be relative");
105
+ const segments = relative.split(/[\\/]/u);
106
+ if (segments.length === 0 || segments.some((segment) => segment === "" || segment === "." || segment === "..")) {
107
+ throw new Error("Contained path has invalid segments");
108
+ }
109
+ return segments;
110
+ }
111
+ async function openDirectoryAt(directory, name) {
112
+ if (process.platform === "darwin") {
113
+ return new NumericFileHandle(loadDarwinBinding().openDirectoryAt(directory.fd, name));
114
+ }
115
+ return open(path.join(descriptorPath(directory), name), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
116
+ }
117
+ async function openFileAt(directory, name) {
118
+ if (process.platform === "darwin") {
119
+ return new NumericFileHandle(loadDarwinBinding().openFileAt(directory.fd, name));
120
+ }
121
+ return open(path.join(descriptorPath(directory), name), constants.O_RDONLY | constants.O_NOFOLLOW);
122
+ }
123
+ function entryMetadata(mode) {
124
+ return {
125
+ mode,
126
+ isDirectory: () => modeIs(mode, FILE_TYPE_DIRECTORY),
127
+ isFile: () => modeIs(mode, FILE_TYPE_REGULAR),
128
+ isSymbolicLink: () => modeIs(mode, FILE_TYPE_SYMLINK)
129
+ };
130
+ }
131
+ async function statAt(directory, name) {
132
+ if (process.platform === "darwin") {
133
+ const metadata = loadDarwinBinding().statAt(directory.fd, name);
134
+ return metadata ? entryMetadata(metadata.mode) : null;
135
+ }
136
+ return lstat(path.join(descriptorPath(directory), name)).catch((error) => {
137
+ if (error.code === "ENOENT")
138
+ return null;
139
+ throw error;
140
+ });
141
+ }
142
+ async function listAt(directory) {
143
+ if (process.platform === "darwin") {
144
+ return loadDarwinBinding().listAt(directory.fd).map(({ name, mode }) => ({ name, ...entryMetadata(mode) }));
145
+ }
146
+ return readdir(descriptorPath(directory), { withFileTypes: true });
147
+ }
148
+ async function openContainedParent(root, relative) {
149
+ const segments = safeSegments(relative);
150
+ const basename = segments.pop();
151
+ if (!basename)
152
+ throw new Error("Contained path is missing a basename");
153
+ let current = await openPinnedDirectory(root);
154
+ try {
155
+ for (const segment of segments) {
156
+ const next = await openDirectoryAt(current, segment);
157
+ const metadata = await next.stat();
158
+ if (!metadata.isDirectory()) {
159
+ await next.close();
160
+ throw new Error("Contained ancestor is not a directory");
161
+ }
162
+ await current.close();
163
+ current = next;
164
+ }
165
+ return { handle: current, basename };
166
+ } catch (error) {
167
+ await current.close();
168
+ throw error;
169
+ }
170
+ }
171
+ async function openContainedFile(root, relative) {
172
+ const parent = await openContainedParent(root, relative);
173
+ try {
174
+ const handle = await openFileAt(parent.handle, parent.basename);
175
+ const metadata = await handle.stat();
176
+ if (!metadata.isFile()) {
177
+ await handle.close();
178
+ throw new Error("Contained path is not a regular file");
179
+ }
180
+ return handle;
181
+ } finally {
182
+ await parent.handle.close();
183
+ }
184
+ }
185
+ async function assertContainedFileCurrent(root, relative, expected) {
186
+ const current = await openContainedFile(root, relative);
187
+ try {
188
+ if (!sameIdentity(await expected.stat(), await current.stat())) {
189
+ throw new Error("Contained file identity changed during authorization");
190
+ }
191
+ } finally {
192
+ await current.close();
193
+ }
194
+ }
195
+ async function assertContainedParentCurrent(root, relative, expected) {
196
+ const current = await openContainedParent(root, relative);
197
+ try {
198
+ if (!sameIdentity(await expected.stat(), await current.handle.stat())) {
199
+ throw new Error("Contained parent identity changed during authorization");
200
+ }
201
+ } finally {
202
+ await current.handle.close();
203
+ }
204
+ }
205
+ async function writeDescriptorFully(descriptor, content) {
206
+ const bytes = Buffer.from(content);
207
+ let offset = 0;
208
+ while (offset < bytes.byteLength) {
209
+ const written = await new Promise((resolve, reject) => {
210
+ writeDescriptor(descriptor, bytes, offset, bytes.byteLength - offset, null, (error, bytesWritten) => error ? reject(error) : resolve(bytesWritten));
211
+ });
212
+ if (written === 0)
213
+ throw new Error("Contained file write made no progress");
214
+ offset += written;
215
+ }
216
+ }
217
+ async function chmodDescriptor(descriptor, mode) {
218
+ await new Promise((resolve, reject) => {
219
+ fchmod(descriptor, mode & 4095, (error) => error ? reject(error) : resolve());
220
+ });
221
+ }
222
+ async function createDarwinFile(parent, name, content, mode) {
223
+ const binding = loadDarwinBinding();
224
+ const descriptor = binding.createFileAt(parent.fd, name, mode & 4095);
225
+ let failed;
226
+ try {
227
+ await writeDescriptorFully(descriptor, content);
228
+ await chmodDescriptor(descriptor, mode);
229
+ } catch (error) {
230
+ failed = error;
231
+ } finally {
232
+ try {
233
+ await new NumericFileHandle(descriptor).close();
234
+ } catch (error) {
235
+ failed ??= error;
236
+ }
237
+ }
238
+ if (failed) {
239
+ binding.unlinkAt(parent.fd, name);
240
+ throw failed;
241
+ }
242
+ }
243
+ async function writeContainedFile(input) {
244
+ const mode = input.mode ?? 438;
245
+ if (!input.replace) {
246
+ if (process.platform === "darwin") {
247
+ await createDarwinFile(input.parent.handle, input.parent.basename, input.content, mode);
248
+ return;
249
+ }
250
+ await writeFile(path.join(descriptorPath(input.parent.handle), input.parent.basename), input.content, { flag: "wx", mode });
251
+ return;
252
+ }
253
+ const temporary = `.${input.parent.basename}.${process.pid}.${crypto.randomUUID()}.tmp`;
254
+ if (process.platform === "darwin") {
255
+ const binding = loadDarwinBinding();
256
+ let created = false;
257
+ try {
258
+ await createDarwinFile(input.parent.handle, temporary, input.content, mode);
259
+ created = true;
260
+ binding.renameAt(input.parent.handle.fd, temporary, input.parent.basename);
261
+ } catch (error) {
262
+ if (created)
263
+ binding.unlinkAt(input.parent.handle.fd, temporary);
264
+ throw error;
265
+ }
266
+ return;
267
+ }
268
+ const directory = descriptorPath(input.parent.handle);
269
+ const temporaryPath = path.join(directory, temporary);
270
+ try {
271
+ await writeFile(temporaryPath, input.content, { flag: "wx", mode });
272
+ await rename(temporaryPath, path.join(directory, input.parent.basename));
273
+ } catch (error) {
274
+ await unlink(temporaryPath).catch(() => {
275
+ return;
276
+ });
277
+ throw error;
278
+ }
279
+ }
280
+ async function containedEntryMetadata(parent) {
281
+ return statAt(parent.handle, parent.basename);
282
+ }
283
+ async function openContainedParentFile(parent) {
284
+ const handle = await openFileAt(parent.handle, parent.basename);
285
+ if (!(await handle.stat()).isFile()) {
286
+ await handle.close();
287
+ throw new Error("Contained path is not a regular file");
288
+ }
289
+ return handle;
290
+ }
291
+ async function readContainedUtf8Handle(handle, maxBytes) {
292
+ const metadata = await handle.stat();
293
+ if (!metadata.isFile())
294
+ throw new Error("Contained path is not a regular file");
295
+ if (metadata.size > maxBytes)
296
+ throw new Error("Contained file exceeds byte budget");
297
+ const buffer = Buffer.alloc(metadata.size);
298
+ let offset = 0;
299
+ while (offset < buffer.byteLength) {
300
+ const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);
301
+ if (bytesRead === 0)
302
+ break;
303
+ offset += bytesRead;
304
+ }
305
+ if (offset !== metadata.size)
306
+ throw new Error("Contained file changed while being read");
307
+ return {
308
+ text: new TextDecoder("utf-8", { fatal: true }).decode(buffer),
309
+ bytes: offset,
310
+ mode: metadata.mode
311
+ };
312
+ }
313
+ async function walkContainedFiles(input) {
314
+ const scan = await scanContainedFiles({ ...input, symlinks: "refuse" });
315
+ if (scan.truncated)
316
+ throw new Error("Contained file traversal exceeded its bounds");
317
+ return scan.files;
318
+ }
319
+ async function scanContainedFiles(input) {
320
+ const files = [];
321
+ let truncated = false;
322
+ let skippedDirectories = 0;
323
+ let skippedSymlinks = 0;
324
+ const root = await openPinnedDirectory(input.root);
325
+ const visit = async (directory, relativeDirectory, depth) => {
326
+ if (truncated)
327
+ return;
328
+ if (depth > input.maxDepth) {
329
+ truncated = true;
330
+ return;
331
+ }
332
+ const entries = [...await listAt(directory)];
333
+ entries.sort((left, right) => left.name.localeCompare(right.name));
334
+ for (const entry of entries) {
335
+ const relative = relativeDirectory ? path.join(relativeDirectory, entry.name) : entry.name;
336
+ if (entry.isSymbolicLink()) {
337
+ if (input.symlinks === "refuse") {
338
+ throw new Error(`Contained file traversal refuses symlink: ${relative}`);
339
+ }
340
+ skippedSymlinks += 1;
341
+ continue;
342
+ }
343
+ if (entry.isDirectory()) {
344
+ if (input.excludeDirectory?.(relative)) {
345
+ skippedDirectories += 1;
346
+ continue;
347
+ }
348
+ let child;
349
+ try {
350
+ child = await openDirectoryAt(directory, entry.name);
351
+ } catch (error) {
352
+ if (input.symlinks === "skip") {
353
+ skippedSymlinks += 1;
354
+ continue;
355
+ }
356
+ throw error;
357
+ }
358
+ try {
359
+ await visit(child, relative, depth + 1);
360
+ } finally {
361
+ await child.close();
362
+ }
363
+ continue;
364
+ }
365
+ if (!entry.isFile())
366
+ continue;
367
+ if (files.length >= input.maxFiles) {
368
+ truncated = true;
369
+ return;
370
+ }
371
+ let content;
372
+ if (input.readMaxBytes !== undefined) {
373
+ try {
374
+ const handle = await openFileAt(directory, entry.name);
375
+ try {
376
+ content = await readContainedUtf8Handle(handle, input.readMaxBytes);
377
+ } finally {
378
+ await handle.close();
379
+ }
380
+ } catch (error) {
381
+ if (input.skipUnreadable)
382
+ continue;
383
+ throw error;
384
+ }
385
+ }
386
+ files.push({ absolute: relative, relative, ...content && { content } });
387
+ }
388
+ };
389
+ try {
390
+ await visit(root, "", 0);
391
+ } finally {
392
+ await root.close();
393
+ }
394
+ return { files, truncated, skippedDirectories, skippedSymlinks };
395
+ }
396
+
397
+ export { openContainedParent, openContainedFile, assertContainedFileCurrent, assertContainedParentCurrent, writeContainedFile, containedEntryMetadata, openContainedParentFile, readContainedUtf8Handle, walkContainedFiles, scanContainedFiles };
@@ -0,0 +1,21 @@
1
+ // src/tools/agent-tool-error.ts
2
+ var AGENT_TOOL_ERROR_BRAND = Symbol.for("stitchkit.AgentToolError");
3
+
4
+ class AgentToolError extends Error {
5
+ output;
6
+ constructor(output, cause) {
7
+ let message = "Tool execution failed";
8
+ try {
9
+ message = JSON.stringify(output);
10
+ } catch {}
11
+ super(message, cause === undefined ? undefined : { cause });
12
+ this.name = "AgentToolError";
13
+ this.output = output;
14
+ Object.defineProperty(this, AGENT_TOOL_ERROR_BRAND, { value: true });
15
+ }
16
+ }
17
+ function isAgentToolError(value) {
18
+ return typeof value === "object" && value !== null && AGENT_TOOL_ERROR_BRAND in value;
19
+ }
20
+
21
+ export { AgentToolError, isAgentToolError };
@@ -7,7 +7,7 @@ import {
7
7
  defaultSignalSource,
8
8
  guardSignalCallback,
9
9
  reportSignalError
10
- } from "./index-d1jsvkyk.js";
10
+ } from "./index-vbf2p6me.js";
11
11
  import {
12
12
  extractIp,
13
13
  getClientInfo,
@@ -18,23 +18,25 @@ import {
18
18
  runWithRequestContext,
19
19
  setRequestEndpoint,
20
20
  setRequestError
21
- } from "./index-p1be103g.js";
21
+ } from "./index-ktsps64f.js";
22
22
  import {
23
23
  ShutdownOptionsSchema
24
- } from "./index-dk6e56g0.js";
24
+ } from "./index-7wpgrqa8.js";
25
25
  import {
26
- DEFAULT_CONTRACT_STREAM_FRAME_BYTES,
27
26
  errorCode,
28
- isUnsafeKey,
29
- joinRoutePath,
30
27
  normalizeError,
31
- parseTrailingWildcard,
32
28
  recordedErrorMessage,
33
29
  resolveTraceContext,
34
- safeJsonParse,
35
30
  validateDeclaredOutput,
36
31
  zodIssues
37
- } from "./index-x18ndp4p.js";
32
+ } from "./index-bd17ytae.js";
33
+ import {
34
+ DEFAULT_CONTRACT_STREAM_FRAME_BYTES,
35
+ isUnsafeKey,
36
+ joinRoutePath,
37
+ parseTrailingWildcard,
38
+ safeJsonParse
39
+ } from "./index-vj3vvpaa.js";
38
40
  import {
39
41
  AppError,
40
42
  badRequest
@@ -1788,6 +1790,9 @@ function bindProcessSignals(handle, options = {}) {
1788
1790
  ...requested.forceTimeoutMs !== undefined && {
1789
1791
  forceTimeoutMs: validated.forceTimeoutMs
1790
1792
  },
1793
+ ...requested.realtimeCloseTimeoutMs !== undefined && {
1794
+ realtimeCloseTimeoutMs: validated.realtimeCloseTimeoutMs
1795
+ },
1791
1796
  ...requested.retryAfterSeconds !== undefined && {
1792
1797
  retryAfterSeconds: validated.retryAfterSeconds
1793
1798
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  executeToolMethod
3
- } from "./index-h8vn1jcr.js";
3
+ } from "./index-qzbg46b6.js";
4
4
  import {
5
5
  assertToolExtensionCompatible,
6
6
  mergeSchemas,
@@ -10,6 +10,7 @@ var ShutdownStateSchema = z.enum([
10
10
  ]);
11
11
  var ShutdownOptionsSchema = z.object({
12
12
  gracePeriodMs: z.number().int().nonnegative().default(30000),
13
+ realtimeCloseTimeoutMs: z.number().int().nonnegative().default(1000),
13
14
  forceTimeoutMs: z.number().int().nonnegative().default(5000),
14
15
  retryAfterSeconds: z.number().int().nonnegative().default(5),
15
16
  signal: z.custom((value) => typeof value === "object" && value !== null && ("aborted" in value) && ("addEventListener" in value), "Expected an AbortSignal").optional()
@@ -63,6 +64,32 @@ function untilAbort(signal) {
63
64
  return Promise.resolve();
64
65
  return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
65
66
  }
67
+ function closeRealtimeWithin(adapter, timeoutMs, signal) {
68
+ if (signal.aborted)
69
+ return Promise.resolve("aborted");
70
+ return new Promise((resolve, reject) => {
71
+ let settled = false;
72
+ const finish = (outcome) => {
73
+ if (settled)
74
+ return;
75
+ settled = true;
76
+ clearTimeout(timer);
77
+ signal.removeEventListener("abort", onAbort);
78
+ resolve(outcome);
79
+ };
80
+ const onAbort = () => finish("aborted");
81
+ const timer = setTimeout(() => finish("timeout"), timeoutMs);
82
+ signal.addEventListener("abort", onAbort, { once: true });
83
+ adapter.closeRealtime().then(() => finish("closed"), (error) => {
84
+ if (settled)
85
+ return;
86
+ settled = true;
87
+ clearTimeout(timer);
88
+ signal.removeEventListener("abort", onAbort);
89
+ reject(error);
90
+ });
91
+ });
92
+ }
66
93
  function withTimeout(promise, timeoutMs, message) {
67
94
  return new Promise((resolve, reject) => {
68
95
  const timer = setTimeout(() => reject(new Error(message)), timeoutMs);
@@ -119,6 +146,7 @@ function createServerLifecycle(getAdapter) {
119
146
  const phaseAbort = new AbortController;
120
147
  let forcedReason;
121
148
  let phaseError;
149
+ let forcedWebSockets = 0;
122
150
  const force = (reason) => {
123
151
  if (forcedReason)
124
152
  return;
@@ -139,7 +167,13 @@ function createServerLifecycle(getAdapter) {
139
167
  await waitForZero(() => pendingApplicationRequests, phaseAbort.signal);
140
168
  if (!forcedReason) {
141
169
  state = "closing-realtime";
142
- await Promise.race([adapter.closeRealtime(), untilAbort(phaseAbort.signal)]);
170
+ const realtimeOutcome = await closeRealtimeWithin(adapter, parsed.realtimeCloseTimeoutMs, phaseAbort.signal);
171
+ if (!forcedReason && realtimeOutcome === "timeout" && adapter.pendingWebSockets() > 0) {
172
+ forcedWebSockets += await Promise.race([
173
+ adapter.terminateRealtime(),
174
+ untilAbort(phaseAbort.signal).then(() => 0)
175
+ ]);
176
+ }
143
177
  }
144
178
  if (!forcedReason) {
145
179
  state = "stopping-runtime";
@@ -157,6 +191,7 @@ function createServerLifecycle(getAdapter) {
157
191
  state = "stopping-runtime";
158
192
  pendingRequestsAtForce = adapter.pendingRequests();
159
193
  pendingWebSocketsAtForce = adapter.pendingWebSockets();
194
+ forcedWebSockets += pendingWebSocketsAtForce;
160
195
  let forceError;
161
196
  let forceFailed = false;
162
197
  try {
@@ -189,7 +224,7 @@ function createServerLifecycle(getAdapter) {
189
224
  pendingRequestsAtForce,
190
225
  pendingWebSocketsAtForce,
191
226
  abortedRequests: pendingRequestsAtForce,
192
- forcedWebSockets: pendingWebSocketsAtForce,
227
+ forcedWebSockets,
193
228
  durationMs: performance.now() - startedAt
194
229
  }));
195
230
  })().catch((error) => {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isUnsafeKey
3
- } from "./index-x18ndp4p.js";
3
+ } from "./index-vj3vvpaa.js";
4
4
  import {
5
5
  isRecord
6
6
  } from "./index-qyrqwr4c.js";