stitchkit 0.70.0 → 0.70.2

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 (67) hide show
  1. package/dist/agent-runtime/coding-tool-files.d.ts.map +1 -1
  2. package/dist/agent-runtime/coding-tool-paths.d.ts +0 -1
  3. package/dist/agent-runtime/coding-tool-paths.d.ts.map +1 -1
  4. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +1 -1
  5. package/dist/agent-runtime/contained-files.d.ts +30 -7
  6. package/dist/agent-runtime/contained-files.d.ts.map +1 -1
  7. package/dist/agent-runtime/harness-control.d.ts +2 -0
  8. package/dist/agent-runtime/harness-control.d.ts.map +1 -1
  9. package/dist/agent-runtime/history-chronology.d.ts +19 -0
  10. package/dist/agent-runtime/history-chronology.d.ts.map +1 -0
  11. package/dist/agent-runtime/history.d.ts.map +1 -1
  12. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  13. package/dist/agent-runtime/terminal-status.d.ts.map +1 -1
  14. package/dist/agent-runtime-browser.js +51 -51
  15. package/dist/agent-runtime-coding-tools.js +31 -34
  16. package/dist/agent-runtime-harness.js +61 -17
  17. package/dist/agent-runtime-openrouter.js +2 -2
  18. package/dist/agent-runtime-sqlite-bun.js +5 -5
  19. package/dist/agent-runtime-sqlite-node.js +5 -5
  20. package/dist/agent-runtime.js +110 -110
  21. package/dist/application/server-resource.d.ts +1 -0
  22. package/dist/application/server-resource.d.ts.map +1 -1
  23. package/dist/application-grammy.js +2 -2
  24. package/dist/application.js +68 -65
  25. package/dist/browser/live-state.d.ts +126 -0
  26. package/dist/browser/live-state.d.ts.map +1 -0
  27. package/dist/cli.js +5 -5
  28. package/dist/contract/index.js +20 -20
  29. package/dist/declaration.d.ts +4 -0
  30. package/dist/declaration.d.ts.map +1 -1
  31. package/dist/declaration.js +22 -22
  32. package/dist/files.js +3 -3
  33. package/dist/index-1z5xxfst.js +397 -0
  34. package/dist/{index-vy5bjy07.js → index-4qfqy0m6.js} +21 -31
  35. package/dist/{index-dk6e56g0.js → index-7wpgrqa8.js} +37 -2
  36. package/dist/{index-10gbbbaa.js → index-9sx8tbz2.js} +1 -1
  37. package/dist/{index-38hs3a58.js → index-a01jky8m.js} +73 -8
  38. package/dist/{index-hsabxjz0.js → index-jw81xr75.js} +1 -1
  39. package/dist/{index-6wzr93cg.js → index-w0445741.js} +1 -1
  40. package/dist/index-y2s6h5bf.js +83 -0
  41. package/dist/index.d.ts +1 -0
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +667 -56
  44. package/dist/node.js +47 -27
  45. package/dist/observability/index.js +22 -22
  46. package/dist/react.js +2 -2
  47. package/dist/realtime/contract.d.ts +30 -11
  48. package/dist/realtime/contract.d.ts.map +1 -1
  49. package/dist/realtime/index.d.ts +1 -1
  50. package/dist/realtime/index.d.ts.map +1 -1
  51. package/dist/server/bun.d.ts.map +1 -1
  52. package/dist/server/index.js +88 -80
  53. package/dist/server/multipart.d.ts.map +1 -1
  54. package/dist/server/node.d.ts.map +1 -1
  55. package/dist/server/process-signals.d.ts.map +1 -1
  56. package/dist/server/shutdown.d.ts +2 -0
  57. package/dist/server/shutdown.d.ts.map +1 -1
  58. package/dist/testing/surface-conformance.d.ts +4 -2
  59. package/dist/testing/surface-conformance.d.ts.map +1 -1
  60. package/dist/testing.js +124 -113
  61. package/dist/tools.js +57 -57
  62. package/llms-full.txt +246 -17
  63. package/native/darwin-arm64.node +0 -0
  64. package/native/darwin-x64.node +0 -0
  65. package/package.json +3 -1
  66. package/dist/index-es0h4w26.js +0 -63
  67. package/dist/index-xbtcszs7.js +0 -202
@@ -157,27 +157,27 @@ function findProjectRole(declaration, name) {
157
157
  return declaration.roles.find((role) => role.name === name);
158
158
  }
159
159
  export {
160
- BindingVariableSchema,
161
- PROJECT_DECLARATION_SCHEMA_VERSION,
162
- ProjectBuildInputSchema,
163
- ProjectBuildSchema,
164
- ProjectCommandSchema,
165
- ProjectDeclarationSchema,
166
- ProjectDescriptionSchema,
167
- ProjectEnvShapeSchema,
168
- ProjectEnvVariableSchema,
169
- ProjectIdentitySchema,
170
- ProjectListenerSchema,
171
- ProjectMigrationsSchema,
172
- ProjectReleaseSchema,
173
- ProjectRequirementPhaseSchema,
174
- ProjectRequirementSchema,
175
- ProjectRoleCommandSchema,
176
- ProjectRoleSchema,
177
- ProjectRunModeSchema,
178
- ProjectSlugSchema,
179
- RepositoryPathSchema,
180
- findProjectRole,
160
+ parseProjectDeclaration,
181
161
  namesAMachine,
182
- parseProjectDeclaration
162
+ findProjectRole,
163
+ RepositoryPathSchema,
164
+ ProjectSlugSchema,
165
+ ProjectRunModeSchema,
166
+ ProjectRoleSchema,
167
+ ProjectRoleCommandSchema,
168
+ ProjectRequirementSchema,
169
+ ProjectRequirementPhaseSchema,
170
+ ProjectReleaseSchema,
171
+ ProjectMigrationsSchema,
172
+ ProjectListenerSchema,
173
+ ProjectIdentitySchema,
174
+ ProjectEnvVariableSchema,
175
+ ProjectEnvShapeSchema,
176
+ ProjectDescriptionSchema,
177
+ ProjectDeclarationSchema,
178
+ ProjectCommandSchema,
179
+ ProjectBuildSchema,
180
+ ProjectBuildInputSchema,
181
+ PROJECT_DECLARATION_SCHEMA_VERSION,
182
+ BindingVariableSchema
183
183
  };
package/dist/files.js CHANGED
@@ -8,8 +8,8 @@ import {
8
8
  ManagedFileRefSchema
9
9
  } from "./index-6k1937bx.js";
10
10
  export {
11
- ManagedFileError,
12
- ManagedFilePathSchema,
11
+ createManagedFileBoundary,
13
12
  ManagedFileRefSchema,
14
- createManagedFileBoundary
13
+ ManagedFilePathSchema,
14
+ ManagedFileError
15
15
  };
@@ -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 };
@@ -1,8 +1,11 @@
1
1
  import {
2
+ advanceToolChronology,
2
3
  assistantStatus,
4
+ canProjectToolChronology,
5
+ createToolChronology,
3
6
  isAssistantHistoryEvidence,
4
7
  isCompleteAgentHistoryTurn
5
- } from "./index-es0h4w26.js";
8
+ } from "./index-y2s6h5bf.js";
6
9
  import {
7
10
  createBoundedSinkManager
8
11
  } from "./index-a59da114.js";
@@ -511,42 +514,20 @@ function interruptedSystemNote(message) {
511
514
  rendered.add("control");
512
515
  return { text: `[interrupted] partial response: ${text}`, rendered };
513
516
  }
514
- function completeToolChronology(message) {
515
- const pending = new Set;
516
- const completed = new Set;
517
- let resultsStarted = false;
518
- for (const part of message.parts) {
519
- if (part.type === "tool-call") {
520
- if (resultsStarted && pending.size > 0)
521
- return false;
522
- if (pending.size === 0)
523
- resultsStarted = false;
524
- if (pending.has(part.callId) || completed.has(part.callId))
525
- return false;
526
- pending.add(part.callId);
527
- }
528
- if (part.type === "tool-result") {
529
- if (!pending.delete(part.callId))
530
- return false;
531
- completed.add(part.callId);
532
- resultsStarted = true;
533
- }
534
- if (part.type === "tool-approval-request") {
535
- if (!pending.delete(part.callId))
536
- return false;
537
- completed.add(part.callId);
538
- resultsStarted = true;
539
- }
540
- }
541
- return pending.size === 0;
542
- }
543
517
  async function projectAgentHistoryDetailed(messages, options = {}) {
544
518
  const projected = [];
545
519
  const system = [];
546
520
  const decisions = [];
547
521
  const interruptedRule = options.interruptedAssistant ?? "assistant-marked";
548
522
  let observedUser = false;
523
+ let chronology = createToolChronology();
524
+ let conversationId;
549
525
  for (const message of messages) {
526
+ if (message.conversationId !== conversationId) {
527
+ conversationId = message.conversationId;
528
+ chronology = createToolChronology();
529
+ observedUser = false;
530
+ }
550
531
  if (message.role === "assistant" && !isAssistantHistoryEvidence(message.status, options.evidencePolicy)) {
551
532
  decisions.push(decide(message, "omitted", message.status === "superseded" ? "superseded" : "draft-or-failed"));
552
533
  continue;
@@ -557,6 +538,8 @@ async function projectAgentHistoryDetailed(messages, options = {}) {
557
538
  }
558
539
  if (message.role === "user") {
559
540
  const user = await userMessage(message, options);
541
+ if (chronology.pending === 0)
542
+ chronology = createToolChronology();
560
543
  observedUser = true;
561
544
  if (user.message) {
562
545
  projected.push(user.message);
@@ -598,7 +581,8 @@ async function projectAgentHistoryDetailed(messages, options = {}) {
598
581
  }
599
582
  continue;
600
583
  }
601
- if (!completeToolChronology(message)) {
584
+ const nextChronology = advanceToolChronology(chronology, message.parts);
585
+ if (!nextChronology || !canProjectToolChronology(nextChronology)) {
602
586
  if (options.incompleteToolTurn === "error") {
603
587
  throw new Error(`Assistant message ${message.id} has incomplete tool chronology`);
604
588
  }
@@ -606,6 +590,7 @@ async function projectAgentHistoryDetailed(messages, options = {}) {
606
590
  continue;
607
591
  }
608
592
  const assistant = assistantMessages(message, interrupted ? "interrupted" : message.status === "failed" ? "failed" : undefined);
593
+ chronology = nextChronology;
609
594
  projected.push(...assistant.messages);
610
595
  decisions.push(assistant.messages.length > 0 ? decide(message, "projected", "projected", assistant.rendered) : decide(message, "omitted", "empty"));
611
596
  }
@@ -1477,6 +1462,11 @@ function createRunExecutor(dependencies) {
1477
1462
  evidencePolicy: config.history.evidencePolicy
1478
1463
  }
1479
1464
  });
1465
+ for (const decision of detailed.decisions) {
1466
+ if (decision.action === "omitted" && run.inputMessageIds.includes(decision.messageId) && source.messages.some((message) => message.id === decision.messageId && message.role === "tool")) {
1467
+ throw new Error(`Invalid approval continuation ${decision.messageId}: ${decision.reason}`);
1468
+ }
1469
+ }
1480
1470
  carriedSystem = detailed.system;
1481
1471
  return [...detailed.messages];
1482
1472
  };
@@ -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) => {
@@ -8,7 +8,7 @@ import {
8
8
  AgentRuntimeHeadSchema,
9
9
  AgentStoredRunSchema,
10
10
  createAgentRuntimeStore
11
- } from "./index-hsabxjz0.js";
11
+ } from "./index-jw81xr75.js";
12
12
  import {
13
13
  AgentMessageSchema,
14
14
  AgentRunSchema