@dreb/dashboard 2.45.1 → 2.45.3
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.
- package/README.md +58 -15
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -1
- package/dist/index.js.map +1 -1
- package/dist/server/dashboard-images.d.ts +56 -0
- package/dist/server/dashboard-images.d.ts.map +1 -0
- package/dist/server/dashboard-images.js +317 -0
- package/dist/server/dashboard-images.js.map +1 -0
- package/dist/server/event-hub.d.ts +3 -0
- package/dist/server/event-hub.d.ts.map +1 -1
- package/dist/server/event-hub.js +7 -1
- package/dist/server/event-hub.js.map +1 -1
- package/dist/server/image-preview-worker.d.ts +7 -0
- package/dist/server/image-preview-worker.d.ts.map +1 -0
- package/dist/server/image-preview-worker.js +150 -0
- package/dist/server/image-preview-worker.js.map +1 -0
- package/dist/server/image-preview.d.ts +29 -0
- package/dist/server/image-preview.d.ts.map +1 -0
- package/dist/server/image-preview.js +76 -0
- package/dist/server/image-preview.js.map +1 -0
- package/dist/server/runtime-pool.d.ts +4 -0
- package/dist/server/runtime-pool.d.ts.map +1 -1
- package/dist/server/runtime-pool.js +48 -1
- package/dist/server/runtime-pool.js.map +1 -1
- package/dist/server/server.d.ts +8 -1
- package/dist/server/server.d.ts.map +1 -1
- package/dist/server/server.js +85 -4
- package/dist/server/server.js.map +1 -1
- package/dist/shared/protocol.d.ts +20 -0
- package/dist/shared/protocol.d.ts.map +1 -1
- package/dist/shared/protocol.js +1 -0
- package/dist/shared/protocol.js.map +1 -1
- package/dist/static/assets/index-BcGevXt-.css +1 -0
- package/dist/static/assets/index-d9zGbh25.js +79 -0
- package/dist/static/index.html +2 -2
- package/dist/static/sw.js +1 -1
- package/package.json +2 -1
- package/dist/static/assets/index-0AYVPowv.css +0 -1
- package/dist/static/assets/index-pIhYczTO.js +0 -79
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { parentPort } from "node:worker_threads";
|
|
2
|
+
import * as photon from "@silvia-odwyer/photon-node";
|
|
3
|
+
import { MAX_PREVIEW_BYTES, MAX_PREVIEW_HEIGHT, MAX_PREVIEW_WIDTH } from "./image-preview.js";
|
|
4
|
+
function readExifOrientation(bytes) {
|
|
5
|
+
let tiff = -1;
|
|
6
|
+
if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
|
|
7
|
+
let offset = 2;
|
|
8
|
+
while (offset + 4 <= bytes.length && bytes[offset] === 0xff) {
|
|
9
|
+
const marker = bytes[offset + 1];
|
|
10
|
+
const length = (bytes[offset + 2] << 8) | bytes[offset + 3];
|
|
11
|
+
if (marker === 0xe1 && offset + 10 <= bytes.length) {
|
|
12
|
+
const start = offset + 4;
|
|
13
|
+
if (String.fromCharCode(...bytes.slice(start, start + 6)) === "Exif\0\0")
|
|
14
|
+
tiff = start + 6;
|
|
15
|
+
break;
|
|
16
|
+
}
|
|
17
|
+
if (length < 2)
|
|
18
|
+
break;
|
|
19
|
+
offset += 2 + length;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
else if (bytes.length >= 12 &&
|
|
23
|
+
String.fromCharCode(...bytes.slice(0, 4)) === "RIFF" &&
|
|
24
|
+
String.fromCharCode(...bytes.slice(8, 12)) === "WEBP") {
|
|
25
|
+
let offset = 12;
|
|
26
|
+
while (offset + 8 <= bytes.length) {
|
|
27
|
+
const chunk = String.fromCharCode(...bytes.slice(offset, offset + 4));
|
|
28
|
+
const size = bytes[offset + 4] | (bytes[offset + 5] << 8) | (bytes[offset + 6] << 16) | (bytes[offset + 7] << 24);
|
|
29
|
+
const start = offset + 8;
|
|
30
|
+
if (chunk === "EXIF") {
|
|
31
|
+
tiff = String.fromCharCode(...bytes.slice(start, start + 6)) === "Exif\0\0" ? start + 6 : start;
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
offset = start + size + (size % 2);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (tiff < 0 || tiff + 8 > bytes.length)
|
|
38
|
+
return 1;
|
|
39
|
+
const little = bytes[tiff] === 0x49 && bytes[tiff + 1] === 0x49;
|
|
40
|
+
const read16 = (at) => (little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1]);
|
|
41
|
+
const read32 = (at) => little
|
|
42
|
+
? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16) | (bytes[at + 3] << 24)) >>> 0
|
|
43
|
+
: ((bytes[at] << 24) | (bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3]) >>> 0;
|
|
44
|
+
const ifd = tiff + read32(tiff + 4);
|
|
45
|
+
if (ifd + 2 > bytes.length)
|
|
46
|
+
return 1;
|
|
47
|
+
const count = read16(ifd);
|
|
48
|
+
for (let index = 0; index < count; index++) {
|
|
49
|
+
const entry = ifd + 2 + index * 12;
|
|
50
|
+
if (entry + 12 > bytes.length)
|
|
51
|
+
break;
|
|
52
|
+
if (read16(entry) === 0x0112) {
|
|
53
|
+
const value = read16(entry + 8);
|
|
54
|
+
return value >= 1 && value <= 8 ? value : 1;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return 1;
|
|
58
|
+
}
|
|
59
|
+
function rotate(image, clockwise) {
|
|
60
|
+
const width = image.get_width();
|
|
61
|
+
const height = image.get_height();
|
|
62
|
+
const source = image.get_raw_pixels();
|
|
63
|
+
const target = new Uint8Array(source.length);
|
|
64
|
+
for (let y = 0; y < height; y++) {
|
|
65
|
+
for (let x = 0; x < width; x++) {
|
|
66
|
+
const sourceIndex = (y * width + x) * 4;
|
|
67
|
+
const destinationPixel = clockwise ? x * height + (height - 1 - y) : (width - 1 - x) * height + y;
|
|
68
|
+
target.set(source.slice(sourceIndex, sourceIndex + 4), destinationPixel * 4);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return new photon.PhotonImage(target, height, width);
|
|
72
|
+
}
|
|
73
|
+
function orient(image, bytes) {
|
|
74
|
+
const orientation = readExifOrientation(bytes);
|
|
75
|
+
if (orientation === 2)
|
|
76
|
+
photon.fliph(image);
|
|
77
|
+
else if (orientation === 3) {
|
|
78
|
+
photon.fliph(image);
|
|
79
|
+
photon.flipv(image);
|
|
80
|
+
}
|
|
81
|
+
else if (orientation === 4)
|
|
82
|
+
photon.flipv(image);
|
|
83
|
+
else if (orientation >= 5) {
|
|
84
|
+
const rotated = rotate(image, orientation === 5 || orientation === 6);
|
|
85
|
+
image.free();
|
|
86
|
+
image = rotated;
|
|
87
|
+
if (orientation === 5 || orientation === 7)
|
|
88
|
+
photon.fliph(image);
|
|
89
|
+
}
|
|
90
|
+
return image;
|
|
91
|
+
}
|
|
92
|
+
export function generateImagePreview(bytes) {
|
|
93
|
+
let image = photon.PhotonImage.new_from_byteslice(bytes);
|
|
94
|
+
try {
|
|
95
|
+
image = orient(image, bytes);
|
|
96
|
+
const originalWidth = image.get_width();
|
|
97
|
+
const originalHeight = image.get_height();
|
|
98
|
+
if (originalWidth < 1 || originalHeight < 1)
|
|
99
|
+
throw new Error("Image has invalid dimensions");
|
|
100
|
+
const scale = Math.min(1, MAX_PREVIEW_WIDTH / originalWidth, MAX_PREVIEW_HEIGHT / originalHeight);
|
|
101
|
+
let width = Math.max(1, Math.round(originalWidth * scale));
|
|
102
|
+
let height = Math.max(1, Math.round(originalHeight * scale));
|
|
103
|
+
while (true) {
|
|
104
|
+
const resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3);
|
|
105
|
+
try {
|
|
106
|
+
const candidates = [
|
|
107
|
+
{ bytes: resized.get_bytes(), mimeType: "image/png" },
|
|
108
|
+
...[85, 70, 55, 40].map((quality) => ({
|
|
109
|
+
bytes: resized.get_bytes_jpeg(quality),
|
|
110
|
+
mimeType: "image/jpeg",
|
|
111
|
+
})),
|
|
112
|
+
];
|
|
113
|
+
const acceptable = candidates.filter((candidate) => candidate.bytes.byteLength <= MAX_PREVIEW_BYTES);
|
|
114
|
+
if (acceptable.length > 0) {
|
|
115
|
+
acceptable.sort((left, right) => left.bytes.byteLength - right.bytes.byteLength);
|
|
116
|
+
return { ...acceptable[0], width, height };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
resized.free();
|
|
121
|
+
}
|
|
122
|
+
if (width === 1 && height === 1)
|
|
123
|
+
break;
|
|
124
|
+
width = Math.max(1, Math.floor(width * 0.75));
|
|
125
|
+
height = Math.max(1, Math.floor(height * 0.75));
|
|
126
|
+
}
|
|
127
|
+
throw new Error("Could not encode image within the 256 KiB preview limit");
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
image.free();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const port = parentPort;
|
|
134
|
+
if (port) {
|
|
135
|
+
port.on("message", (request) => {
|
|
136
|
+
try {
|
|
137
|
+
const preview = generateImagePreview(new Uint8Array(request.bytes));
|
|
138
|
+
const transferable = Uint8Array.from(preview.bytes);
|
|
139
|
+
port.postMessage({ id: request.id, ok: true, ...preview, bytes: transferable.buffer }, [transferable.buffer]);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
port.postMessage({
|
|
143
|
+
id: request.id,
|
|
144
|
+
ok: false,
|
|
145
|
+
error: error instanceof Error ? error.message : String(error),
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=image-preview-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-preview-worker.js","sourceRoot":"","sources":["../../src/server/image-preview-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,KAAK,MAAM,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAU9F,SAAS,mBAAmB,CAAC,KAAiB,EAAU;IACvD,IAAI,IAAI,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,EAAE,EAAE,KAAK;gBACT,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC7D,CAAC,CAAC;QACJ,CAAC;IAAA,CACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { parentPort } from \"node:worker_threads\";\nimport * as photon from \"@silvia-odwyer/photon-node\";\nimport { MAX_PREVIEW_BYTES, MAX_PREVIEW_HEIGHT, MAX_PREVIEW_WIDTH } from \"./image-preview.js\";\n\ntype PhotonImage = ReturnType<typeof photon.PhotonImage.new_from_byteslice>;\n\ninterface PreviewRequest {\n\tid: number;\n\tbytes: ArrayBuffer;\n\tmimeType: string;\n}\n\nfunction readExifOrientation(bytes: Uint8Array): number {\n\tlet tiff = -1;\n\tif (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {\n\t\tlet offset = 2;\n\t\twhile (offset + 4 <= bytes.length && bytes[offset] === 0xff) {\n\t\t\tconst marker = bytes[offset + 1];\n\t\t\tconst length = (bytes[offset + 2] << 8) | bytes[offset + 3];\n\t\t\tif (marker === 0xe1 && offset + 10 <= bytes.length) {\n\t\t\t\tconst start = offset + 4;\n\t\t\t\tif (String.fromCharCode(...bytes.slice(start, start + 6)) === \"Exif\\0\\0\") tiff = start + 6;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (length < 2) break;\n\t\t\toffset += 2 + length;\n\t\t}\n\t} else if (\n\t\tbytes.length >= 12 &&\n\t\tString.fromCharCode(...bytes.slice(0, 4)) === \"RIFF\" &&\n\t\tString.fromCharCode(...bytes.slice(8, 12)) === \"WEBP\"\n\t) {\n\t\tlet offset = 12;\n\t\twhile (offset + 8 <= bytes.length) {\n\t\t\tconst chunk = String.fromCharCode(...bytes.slice(offset, offset + 4));\n\t\t\tconst size =\n\t\t\t\tbytes[offset + 4] | (bytes[offset + 5] << 8) | (bytes[offset + 6] << 16) | (bytes[offset + 7] << 24);\n\t\t\tconst start = offset + 8;\n\t\t\tif (chunk === \"EXIF\") {\n\t\t\t\ttiff = String.fromCharCode(...bytes.slice(start, start + 6)) === \"Exif\\0\\0\" ? start + 6 : start;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toffset = start + size + (size % 2);\n\t\t}\n\t}\n\tif (tiff < 0 || tiff + 8 > bytes.length) return 1;\n\tconst little = bytes[tiff] === 0x49 && bytes[tiff + 1] === 0x49;\n\tconst read16 = (at: number) => (little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1]);\n\tconst read32 = (at: number) =>\n\t\tlittle\n\t\t\t? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16) | (bytes[at + 3] << 24)) >>> 0\n\t\t\t: ((bytes[at] << 24) | (bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3]) >>> 0;\n\tconst ifd = tiff + read32(tiff + 4);\n\tif (ifd + 2 > bytes.length) return 1;\n\tconst count = read16(ifd);\n\tfor (let index = 0; index < count; index++) {\n\t\tconst entry = ifd + 2 + index * 12;\n\t\tif (entry + 12 > bytes.length) break;\n\t\tif (read16(entry) === 0x0112) {\n\t\t\tconst value = read16(entry + 8);\n\t\t\treturn value >= 1 && value <= 8 ? value : 1;\n\t\t}\n\t}\n\treturn 1;\n}\n\nfunction rotate(image: PhotonImage, clockwise: boolean): PhotonImage {\n\tconst width = image.get_width();\n\tconst height = image.get_height();\n\tconst source = image.get_raw_pixels();\n\tconst target = new Uint8Array(source.length);\n\tfor (let y = 0; y < height; y++) {\n\t\tfor (let x = 0; x < width; x++) {\n\t\t\tconst sourceIndex = (y * width + x) * 4;\n\t\t\tconst destinationPixel = clockwise ? x * height + (height - 1 - y) : (width - 1 - x) * height + y;\n\t\t\ttarget.set(source.slice(sourceIndex, sourceIndex + 4), destinationPixel * 4);\n\t\t}\n\t}\n\treturn new photon.PhotonImage(target, height, width);\n}\n\nfunction orient(image: PhotonImage, bytes: Uint8Array): PhotonImage {\n\tconst orientation = readExifOrientation(bytes);\n\tif (orientation === 2) photon.fliph(image);\n\telse if (orientation === 3) {\n\t\tphoton.fliph(image);\n\t\tphoton.flipv(image);\n\t} else if (orientation === 4) photon.flipv(image);\n\telse if (orientation >= 5) {\n\t\tconst rotated = rotate(image, orientation === 5 || orientation === 6);\n\t\timage.free();\n\t\timage = rotated;\n\t\tif (orientation === 5 || orientation === 7) photon.fliph(image);\n\t}\n\treturn image;\n}\n\nexport function generateImagePreview(bytes: Uint8Array): {\n\tbytes: Uint8Array;\n\tmimeType: \"image/png\" | \"image/jpeg\";\n\twidth: number;\n\theight: number;\n} {\n\tlet image = photon.PhotonImage.new_from_byteslice(bytes);\n\ttry {\n\t\timage = orient(image, bytes);\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tif (originalWidth < 1 || originalHeight < 1) throw new Error(\"Image has invalid dimensions\");\n\t\tconst scale = Math.min(1, MAX_PREVIEW_WIDTH / originalWidth, MAX_PREVIEW_HEIGHT / originalHeight);\n\t\tlet width = Math.max(1, Math.round(originalWidth * scale));\n\t\tlet height = Math.max(1, Math.round(originalHeight * scale));\n\t\twhile (true) {\n\t\t\tconst resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3);\n\t\t\ttry {\n\t\t\t\tconst candidates: Array<{ bytes: Uint8Array; mimeType: \"image/png\" | \"image/jpeg\" }> = [\n\t\t\t\t\t{ bytes: resized.get_bytes(), mimeType: \"image/png\" },\n\t\t\t\t\t...([85, 70, 55, 40] as const).map((quality) => ({\n\t\t\t\t\t\tbytes: resized.get_bytes_jpeg(quality),\n\t\t\t\t\t\tmimeType: \"image/jpeg\" as const,\n\t\t\t\t\t})),\n\t\t\t\t];\n\t\t\t\tconst acceptable = candidates.filter((candidate) => candidate.bytes.byteLength <= MAX_PREVIEW_BYTES);\n\t\t\t\tif (acceptable.length > 0) {\n\t\t\t\t\tacceptable.sort((left, right) => left.bytes.byteLength - right.bytes.byteLength);\n\t\t\t\t\treturn { ...acceptable[0]!, width, height };\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t\tif (width === 1 && height === 1) break;\n\t\t\twidth = Math.max(1, Math.floor(width * 0.75));\n\t\t\theight = Math.max(1, Math.floor(height * 0.75));\n\t\t}\n\t\tthrow new Error(\"Could not encode image within the 256 KiB preview limit\");\n\t} finally {\n\t\timage.free();\n\t}\n}\n\nconst port = parentPort;\nif (port) {\n\tport.on(\"message\", (request: PreviewRequest) => {\n\t\ttry {\n\t\t\tconst preview = generateImagePreview(new Uint8Array(request.bytes));\n\t\t\tconst transferable = Uint8Array.from(preview.bytes);\n\t\t\tport.postMessage({ id: request.id, ok: true, ...preview, bytes: transferable.buffer }, [transferable.buffer]);\n\t\t} catch (error) {\n\t\t\tport.postMessage({\n\t\t\t\tid: request.id,\n\t\t\t\tok: false,\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t}\n\t});\n}\n"]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare const MAX_PREVIEW_WIDTH = 1024;
|
|
2
|
+
export declare const MAX_PREVIEW_HEIGHT = 1024;
|
|
3
|
+
export declare const MAX_PREVIEW_BYTES: number;
|
|
4
|
+
export interface GeneratedImagePreview {
|
|
5
|
+
bytes: Uint8Array;
|
|
6
|
+
mimeType: "image/png" | "image/jpeg";
|
|
7
|
+
width: number;
|
|
8
|
+
height: number;
|
|
9
|
+
}
|
|
10
|
+
export interface ImagePreviewGenerator {
|
|
11
|
+
generate(bytes: Uint8Array, mimeType: string): Promise<GeneratedImagePreview>;
|
|
12
|
+
close(): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/** One worker keeps Photon decode/resize work off the ordered SSE path. */
|
|
15
|
+
export declare class ImagePreviewWorker implements ImagePreviewGenerator {
|
|
16
|
+
/** Injectable worker URL keeps abnormal-exit handling deterministic in tests. */
|
|
17
|
+
private readonly workerUrl;
|
|
18
|
+
private worker;
|
|
19
|
+
private nextId;
|
|
20
|
+
private closed;
|
|
21
|
+
private readonly pending;
|
|
22
|
+
constructor(
|
|
23
|
+
/** Injectable worker URL keeps abnormal-exit handling deterministic in tests. */
|
|
24
|
+
workerUrl?: import("url").URL);
|
|
25
|
+
generate(bytes: Uint8Array, mimeType: string): Promise<GeneratedImagePreview>;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
private getWorker;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=image-preview.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-preview.d.ts","sourceRoot":"","sources":["../../src/server/image-preview.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,iBAAiB,OAAO,CAAC;AACtC,eAAO,MAAM,kBAAkB,OAAO,CAAC;AACvC,eAAO,MAAM,iBAAiB,QAAa,CAAC;AAE5C,MAAM,WAAW,qBAAqB;IACrC,KAAK,EAAE,UAAU,CAAC;IAClB,QAAQ,EAAE,WAAW,GAAG,YAAY,CAAC;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAC;IAC9E,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAmBD,2EAA2E;AAC3E,qBAAa,kBAAmB,YAAW,qBAAqB;IAU9D,iFAAiF;IACjF,OAAO,CAAC,QAAQ,CAAC,SAAS;IAV3B,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGpB;IAEJ;IACC,iFAAiF;IAChE,SAAS,oBAAwD,EAC/E;IAEE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAUlF;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAQ3B;IAED,OAAO,CAAC,SAAS;CA8BjB","sourcesContent":["import { Worker } from \"node:worker_threads\";\n\nexport const MAX_PREVIEW_WIDTH = 1024;\nexport const MAX_PREVIEW_HEIGHT = 1024;\nexport const MAX_PREVIEW_BYTES = 256 * 1024;\n\nexport interface GeneratedImagePreview {\n\tbytes: Uint8Array;\n\tmimeType: \"image/png\" | \"image/jpeg\";\n\twidth: number;\n\theight: number;\n}\n\nexport interface ImagePreviewGenerator {\n\tgenerate(bytes: Uint8Array, mimeType: string): Promise<GeneratedImagePreview>;\n\tclose(): Promise<void>;\n}\n\ninterface WorkerSuccess {\n\tid: number;\n\tok: true;\n\tbytes: ArrayBuffer;\n\tmimeType: \"image/png\" | \"image/jpeg\";\n\twidth: number;\n\theight: number;\n}\n\ninterface WorkerFailure {\n\tid: number;\n\tok: false;\n\terror: string;\n}\n\ntype WorkerReply = WorkerSuccess | WorkerFailure;\n\n/** One worker keeps Photon decode/resize work off the ordered SSE path. */\nexport class ImagePreviewWorker implements ImagePreviewGenerator {\n\tprivate worker: Worker | undefined;\n\tprivate nextId = 1;\n\tprivate closed = false;\n\tprivate readonly pending = new Map<\n\t\tnumber,\n\t\t{ resolve: (preview: GeneratedImagePreview) => void; reject: (error: Error) => void }\n\t>();\n\n\tconstructor(\n\t\t/** Injectable worker URL keeps abnormal-exit handling deterministic in tests. */\n\t\tprivate readonly workerUrl = new URL(\"./image-preview-worker.js\", import.meta.url),\n\t) {}\n\n\tasync generate(bytes: Uint8Array, mimeType: string): Promise<GeneratedImagePreview> {\n\t\tif (this.closed) throw new Error(\"Image preview worker is closed\");\n\t\tconst worker = this.getWorker();\n\t\tconst id = this.nextId++;\n\t\t// Do not detach repository-owned storage when transferring to the worker.\n\t\tconst copy = Uint8Array.from(bytes);\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve, reject });\n\t\t\tworker.postMessage({ id, bytes: copy.buffer, mimeType }, [copy.buffer]);\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tfor (const pending of this.pending.values()) pending.reject(new Error(\"Image preview worker closed\"));\n\t\tthis.pending.clear();\n\t\tconst worker = this.worker;\n\t\tthis.worker = undefined;\n\t\tif (worker) await worker.terminate();\n\t}\n\n\tprivate getWorker(): Worker {\n\t\tif (this.worker) return this.worker;\n\t\tconst worker = new Worker(this.workerUrl);\n\t\tworker.on(\"message\", (reply: WorkerReply) => {\n\t\t\tconst pending = this.pending.get(reply.id);\n\t\t\tif (!pending) return;\n\t\t\tthis.pending.delete(reply.id);\n\t\t\tif (!reply.ok) {\n\t\t\t\tpending.reject(new Error(reply.error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpending.resolve({\n\t\t\t\tbytes: new Uint8Array(reply.bytes),\n\t\t\t\tmimeType: reply.mimeType,\n\t\t\t\twidth: reply.width,\n\t\t\t\theight: reply.height,\n\t\t\t});\n\t\t});\n\t\tconst fail = (error: Error) => {\n\t\t\tfor (const pending of this.pending.values()) pending.reject(error);\n\t\t\tthis.pending.clear();\n\t\t\tthis.worker = undefined;\n\t\t};\n\t\tworker.on(\"error\", fail);\n\t\tworker.on(\"exit\", (code) => {\n\t\t\tif (!this.closed && code !== 0) fail(new Error(`Image preview worker exited with code ${code}`));\n\t\t});\n\t\tthis.worker = worker;\n\t\treturn worker;\n\t}\n}\n"]}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
export const MAX_PREVIEW_WIDTH = 1024;
|
|
3
|
+
export const MAX_PREVIEW_HEIGHT = 1024;
|
|
4
|
+
export const MAX_PREVIEW_BYTES = 256 * 1024;
|
|
5
|
+
/** One worker keeps Photon decode/resize work off the ordered SSE path. */
|
|
6
|
+
export class ImagePreviewWorker {
|
|
7
|
+
workerUrl;
|
|
8
|
+
worker;
|
|
9
|
+
nextId = 1;
|
|
10
|
+
closed = false;
|
|
11
|
+
pending = new Map();
|
|
12
|
+
constructor(
|
|
13
|
+
/** Injectable worker URL keeps abnormal-exit handling deterministic in tests. */
|
|
14
|
+
workerUrl = new URL("./image-preview-worker.js", import.meta.url)) {
|
|
15
|
+
this.workerUrl = workerUrl;
|
|
16
|
+
}
|
|
17
|
+
async generate(bytes, mimeType) {
|
|
18
|
+
if (this.closed)
|
|
19
|
+
throw new Error("Image preview worker is closed");
|
|
20
|
+
const worker = this.getWorker();
|
|
21
|
+
const id = this.nextId++;
|
|
22
|
+
// Do not detach repository-owned storage when transferring to the worker.
|
|
23
|
+
const copy = Uint8Array.from(bytes);
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
this.pending.set(id, { resolve, reject });
|
|
26
|
+
worker.postMessage({ id, bytes: copy.buffer, mimeType }, [copy.buffer]);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async close() {
|
|
30
|
+
if (this.closed)
|
|
31
|
+
return;
|
|
32
|
+
this.closed = true;
|
|
33
|
+
for (const pending of this.pending.values())
|
|
34
|
+
pending.reject(new Error("Image preview worker closed"));
|
|
35
|
+
this.pending.clear();
|
|
36
|
+
const worker = this.worker;
|
|
37
|
+
this.worker = undefined;
|
|
38
|
+
if (worker)
|
|
39
|
+
await worker.terminate();
|
|
40
|
+
}
|
|
41
|
+
getWorker() {
|
|
42
|
+
if (this.worker)
|
|
43
|
+
return this.worker;
|
|
44
|
+
const worker = new Worker(this.workerUrl);
|
|
45
|
+
worker.on("message", (reply) => {
|
|
46
|
+
const pending = this.pending.get(reply.id);
|
|
47
|
+
if (!pending)
|
|
48
|
+
return;
|
|
49
|
+
this.pending.delete(reply.id);
|
|
50
|
+
if (!reply.ok) {
|
|
51
|
+
pending.reject(new Error(reply.error));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
pending.resolve({
|
|
55
|
+
bytes: new Uint8Array(reply.bytes),
|
|
56
|
+
mimeType: reply.mimeType,
|
|
57
|
+
width: reply.width,
|
|
58
|
+
height: reply.height,
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
const fail = (error) => {
|
|
62
|
+
for (const pending of this.pending.values())
|
|
63
|
+
pending.reject(error);
|
|
64
|
+
this.pending.clear();
|
|
65
|
+
this.worker = undefined;
|
|
66
|
+
};
|
|
67
|
+
worker.on("error", fail);
|
|
68
|
+
worker.on("exit", (code) => {
|
|
69
|
+
if (!this.closed && code !== 0)
|
|
70
|
+
fail(new Error(`Image preview worker exited with code ${code}`));
|
|
71
|
+
});
|
|
72
|
+
this.worker = worker;
|
|
73
|
+
return worker;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=image-preview.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-preview.js","sourceRoot":"","sources":["../../src/server/image-preview.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC;AACvC,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,GAAG,IAAI,CAAC;AA+B5C,2EAA2E;AAC3E,MAAM,OAAO,kBAAkB;IAWZ,SAAS;IAVnB,MAAM,CAAqB;IAC3B,MAAM,GAAG,CAAC,CAAC;IACX,MAAM,GAAG,KAAK,CAAC;IACN,OAAO,GAAG,IAAI,GAAG,EAG/B,CAAC;IAEJ;IACC,iFAAiF;IAChE,SAAS,GAAG,IAAI,GAAG,CAAC,2BAA2B,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,EACjF;yBADgB,SAAS;IACxB,CAAC;IAEJ,KAAK,CAAC,QAAQ,CAAC,KAAiB,EAAE,QAAgB,EAAkC;QACnF,IAAI,IAAI,CAAC,MAAM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C;QACH,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,OAAO,MAAM,CAAC;IAAA,CACd;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\n\nexport const MAX_PREVIEW_WIDTH = 1024;\nexport const MAX_PREVIEW_HEIGHT = 1024;\nexport const MAX_PREVIEW_BYTES = 256 * 1024;\n\nexport interface GeneratedImagePreview {\n\tbytes: Uint8Array;\n\tmimeType: \"image/png\" | \"image/jpeg\";\n\twidth: number;\n\theight: number;\n}\n\nexport interface ImagePreviewGenerator {\n\tgenerate(bytes: Uint8Array, mimeType: string): Promise<GeneratedImagePreview>;\n\tclose(): Promise<void>;\n}\n\ninterface WorkerSuccess {\n\tid: number;\n\tok: true;\n\tbytes: ArrayBuffer;\n\tmimeType: \"image/png\" | \"image/jpeg\";\n\twidth: number;\n\theight: number;\n}\n\ninterface WorkerFailure {\n\tid: number;\n\tok: false;\n\terror: string;\n}\n\ntype WorkerReply = WorkerSuccess | WorkerFailure;\n\n/** One worker keeps Photon decode/resize work off the ordered SSE path. */\nexport class ImagePreviewWorker implements ImagePreviewGenerator {\n\tprivate worker: Worker | undefined;\n\tprivate nextId = 1;\n\tprivate closed = false;\n\tprivate readonly pending = new Map<\n\t\tnumber,\n\t\t{ resolve: (preview: GeneratedImagePreview) => void; reject: (error: Error) => void }\n\t>();\n\n\tconstructor(\n\t\t/** Injectable worker URL keeps abnormal-exit handling deterministic in tests. */\n\t\tprivate readonly workerUrl = new URL(\"./image-preview-worker.js\", import.meta.url),\n\t) {}\n\n\tasync generate(bytes: Uint8Array, mimeType: string): Promise<GeneratedImagePreview> {\n\t\tif (this.closed) throw new Error(\"Image preview worker is closed\");\n\t\tconst worker = this.getWorker();\n\t\tconst id = this.nextId++;\n\t\t// Do not detach repository-owned storage when transferring to the worker.\n\t\tconst copy = Uint8Array.from(bytes);\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve, reject });\n\t\t\tworker.postMessage({ id, bytes: copy.buffer, mimeType }, [copy.buffer]);\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tfor (const pending of this.pending.values()) pending.reject(new Error(\"Image preview worker closed\"));\n\t\tthis.pending.clear();\n\t\tconst worker = this.worker;\n\t\tthis.worker = undefined;\n\t\tif (worker) await worker.terminate();\n\t}\n\n\tprivate getWorker(): Worker {\n\t\tif (this.worker) return this.worker;\n\t\tconst worker = new Worker(this.workerUrl);\n\t\tworker.on(\"message\", (reply: WorkerReply) => {\n\t\t\tconst pending = this.pending.get(reply.id);\n\t\t\tif (!pending) return;\n\t\t\tthis.pending.delete(reply.id);\n\t\t\tif (!reply.ok) {\n\t\t\t\tpending.reject(new Error(reply.error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpending.resolve({\n\t\t\t\tbytes: new Uint8Array(reply.bytes),\n\t\t\t\tmimeType: reply.mimeType,\n\t\t\t\twidth: reply.width,\n\t\t\t\theight: reply.height,\n\t\t\t});\n\t\t});\n\t\tconst fail = (error: Error) => {\n\t\t\tfor (const pending of this.pending.values()) pending.reject(error);\n\t\t\tthis.pending.clear();\n\t\t\tthis.worker = undefined;\n\t\t};\n\t\tworker.on(\"error\", fail);\n\t\tworker.on(\"exit\", (code) => {\n\t\t\tif (!this.closed && code !== 0) fail(new Error(`Image preview worker exited with code ${code}`));\n\t\t});\n\t\tthis.worker = worker;\n\t\treturn worker;\n\t}\n}\n"]}
|
|
@@ -35,6 +35,8 @@ export interface RuntimeHandle {
|
|
|
35
35
|
attention: Map<string, string>;
|
|
36
36
|
/** Last runtime-level error, persisted server-side so fleet refreshes stay honest. */
|
|
37
37
|
error?: string;
|
|
38
|
+
/** Provider error currently responsible for error/attention; retry may clear only this source. */
|
|
39
|
+
providerError?: string;
|
|
38
40
|
/** Last authoritative state, patched only with event-derivable fields between RPC reads. */
|
|
39
41
|
lastState?: SessionStateDto;
|
|
40
42
|
/** Resume-path fallback; events must never invent or overwrite session identity. */
|
|
@@ -143,6 +145,8 @@ export declare class RuntimePool {
|
|
|
143
145
|
*/
|
|
144
146
|
private updateStateFromEvent;
|
|
145
147
|
private recordRuntimeError;
|
|
148
|
+
private recordProviderError;
|
|
149
|
+
private clearProviderError;
|
|
146
150
|
private pruneCompletedBackgroundAgents;
|
|
147
151
|
private fallbackState;
|
|
148
152
|
private describeFleetRuntime;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-pool.d.ts","sourceRoot":"","sources":["../../src/server/runtime-pool.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,OAAO,EAAE,SAAS,EAAoB,MAAM,wBAAwB,CAAC;AACrE,OAAO,EACN,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,+BAA+B,EAC/B,KAAK,cAAc,EAEnB,KAAK,eAAe,EACpB,MAAM,uBAAuB,CAAC;AAE/B,6FAA6F;AAC7F,wBAAgB,kBAAkB,IAAI,MAAM,CAG3C;AAOD,MAAM,MAAM,oBAAoB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;AAEzF,mEAAmE;AACnE,MAAM,MAAM,qBAAqB,GAAG,CAAC,KAAK,EAAE,qBAAqB,KAAK,IAAI,CAAC;AAE3E,OAAO,EAAE,+BAA+B,EAAE,CAAC;AAE3C,UAAU,oBAAoB;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,eAAe,CAAC;IACvB,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,gBAAgB,EAAE,kBAAkB,EAAE,CAAC;CACvC;AAID,MAAM,WAAW,wBAAwB;IACxC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,oBAAoB,CAAC;CAC/B;AAED,MAAM,WAAW,aAAa;IAC7B,GAAG,EAAE,M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UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAIhF;IAED;;;;OAIG;IACG,iBAAiB,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAehF;IAED,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,6BAA6B;IAgBrC,OAAO,CAAC,qBAAqB;IAkB7B,iFAAiF;IAC3E,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CA0BtE;YAEa,mBAAmB;IAsBjC,kDAAkD;IAC5C,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAQxC;IAED;;;;;OAKG;IACG,oBAAoB,CAAC,GAAG,SAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CA+BlE;YAEa,mBAAmB;IAgB3B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAmB7B;IAED,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,WAAW;IA+EnB;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IA0C5B,OAAO,CAAC,kBAAkB;IAM1B,OAAO,CAAC,8BAA8B;IAetC,OAAO,CAAC,aAAa;IAkBrB,OAAO,CAAC,oBAAoB;YAcd,oBAAoB;IAclC,iDAAiD;IAC3C,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CAqE7D;CACD","sourcesContent":["/**\n * RPC runtime pool — one `dreb --mode rpc` child process per live session.\n *\n * dreb's RPC mode is strictly one-session-per-process (switch_session repoints\n * the same process; it never multiplexes), so the pool spawns N children keyed\n * by an opaque runtime key. The telegram bridge is the in-repo precedent.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { RpcClient, type RpcExitInfo } from \"@dreb/coding-agent/rpc\";\nimport {\n\ttype BackgroundAgentDto,\n\ttype FleetRuntimeSnapshotDto,\n\ttype FleetSnapshotEventDto,\n\tMAX_COMPLETED_BACKGROUND_AGENTS,\n\ttype RuntimeInfoDto,\n\ttype RuntimeStatsSummaryDto,\n\ttype SessionStateDto,\n} from \"../shared/protocol.js\";\n\n/** Resolve the absolute path to the dreb CLI (RpcClient defaults to a cwd-relative path). */\nexport function resolveDrebCliPath(): string {\n\tconst resolved = import.meta.resolve(\"@dreb/coding-agent\");\n\treturn join(dirname(fileURLToPath(resolved)), \"cli.js\");\n}\n\nfunction formatRpcExit(info: RpcExitInfo): string {\n\tif (info.error) return `RPC process failed: ${info.error.message}`;\n\treturn `RPC process exited (code ${info.code}, signal ${info.signal})`;\n}\n\nexport type RuntimeEventListener = (key: string, event: Record<string, unknown>) => void;\n\n/** Listener for coalesced, synchronous fleet runtime snapshots. */\nexport type FleetSnapshotListener = (event: FleetSnapshotEventDto) => void;\n\nexport { MAX_COMPLETED_BACKGROUND_AGENTS };\n\ninterface RpcDashboardSnapshot {\n\tsnapshotId: string;\n\tstate: SessionStateDto;\n\tmessages: unknown[];\n\tbackgroundAgents: BackgroundAgentDto[];\n}\n\ntype DashboardSnapshotClient = RpcClient & { getDashboardSnapshot(): Promise<RpcDashboardSnapshot> };\n\nexport interface DashboardRuntimeSnapshot {\n\tkey: string;\n\tbarrierSeq: number;\n\tsnapshot: RpcDashboardSnapshot;\n}\n\nexport interface RuntimeHandle {\n\tkey: string;\n\tcwd: string;\n\tclient: RpcClient;\n\t/** Session start time (ms epoch) — stable tiebreak for deterministic fleet ordering. */\n\tcreatedAt: number;\n\tlastActivity: number;\n\t/** Needs-attention sources, keyed so they can be cleared independently. */\n\tattention: Map<string, string>;\n\t/** Last runtime-level error, persisted server-side so fleet refreshes stay honest. */\n\terror?: string;\n\t/** Last authoritative state, patched only with event-derivable fields between RPC reads. */\n\tlastState?: SessionStateDto;\n\t/** Resume-path fallback; events must never invent or overwrite session identity. */\n\tsessionFileFallback?: string;\n\t/** Background agents seen via events (agentId → latest info). */\n\tbackgroundAgents: Map<string, BackgroundAgentDto>;\n}\n\nexport const DEFAULT_DASHBOARD_BARRIER_TTL_MS = 5 * 60_000;\nexport const DEFAULT_DASHBOARD_BARRIER_LIMIT = 1000;\nexport const DEFAULT_FLEET_SNAPSHOT_DEBOUNCE_MS = 200;\n\n/** Events that mutate a field carried by the lightweight fleet snapshot. */\nconst FLEET_SNAPSHOT_EVENT_TYPES = new Set([\n\t\"agent_start\",\n\t\"agent_end\",\n\t\"auto_compaction_start\",\n\t\"auto_compaction_end\",\n\t\"auto_retry_end\",\n\t\"background_agent_start\",\n\t\"background_agent_end\",\n\t\"extension_ui_request\",\n\t\"extension_ui_response_handled\",\n\t\"message_start\",\n\t\"parent_paused_for_background_agents\",\n\t\"runtime_removed\",\n\t\"session_name_changed\",\n\t\"suggest_next\",\n\t\"tasks_update\",\n]);\n\nexport interface RuntimePoolOptions {\n\tcliPath?: string;\n\t/** Extra args for every runtime (e.g. --provider). */\n\tbaseArgs?: string[];\n\t/** RpcClient factory override for tests. */\n\tclientFactory?: (options: { cliPath: string; cwd: string; args: string[] }) => RpcClient;\n\tlogger?: (line: string) => void;\n\t/** Bounds unclaimed RPC snapshot ordering records. */\n\tdashboardBarrierTtlMs?: number;\n\tdashboardBarrierLimit?: number;\n\t/** Injectable clock for deterministic barrier-expiry tests. */\n\tnow?: () => number;\n\t/** Coalescing delay for event-derived fleet snapshot emissions. */\n\tfleetSnapshotDebounceMs?: number;\n}\n\ninterface DashboardBarrier {\n\tseq: number;\n\trecordedAt: number;\n}\n\nexport class RuntimePool {\n\tprivate readonly runtimes = new Map<string, RuntimeHandle>();\n\tprivate readonly listeners: RuntimeEventListener[] = [];\n\tprivate readonly fleetSnapshotListeners: FleetSnapshotListener[] = [];\n\tprivate readonly cliPath: string;\n\tprivate readonly baseArgs: string[];\n\tprivate readonly clientFactory: (options: { cliPath: string; cwd: string; args: string[] }) => RpcClient;\n\tprivate readonly logger: (line: string) => void;\n\t/**\n\t * A single lazily-spawned utility runtime used to service settings/model/\n\t * agent-type endpoints when no user session is live. Kept out of `runtimes`\n\t * (and therefore out of the fleet) so it never shows as a session card.\n\t */\n\tprivate readonly utilities = new Map<string, RuntimeHandle>();\n\tprivate readonly utilityPromises = new Map<string, Promise<RuntimeHandle>>();\n\tprivate readonly starting = new Set<RuntimeHandle>();\n\tprivate readonly startupPromises = new Set<Promise<unknown>>();\n\tprivate readonly exitedHandles = new WeakSet<RuntimeHandle>();\n\t/** Snapshot ordering records observed synchronously from RpcClient stdout. */\n\tprivate readonly dashboardBarriers = new Map<string, DashboardBarrier>();\n\tprivate readonly dashboardBarrierTtlMs: number;\n\tprivate readonly dashboardBarrierLimit: number;\n\tprivate readonly now: () => number;\n\tprivate readonly fleetSnapshotDebounceMs: number;\n\tprivate dashboardBarrierPruneTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate fleetSnapshotTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate closing = false;\n\n\tconstructor(options: RuntimePoolOptions = {}) {\n\t\tthis.cliPath = options.cliPath ?? resolveDrebCliPath();\n\t\tthis.baseArgs = options.baseArgs ?? [];\n\t\tthis.clientFactory =\n\t\t\toptions.clientFactory ?? ((o) => new RpcClient({ cliPath: o.cliPath, cwd: o.cwd, args: o.args }));\n\t\tthis.logger = options.logger ?? ((line) => console.warn(`[dashboard] ${line}`));\n\t\tthis.dashboardBarrierTtlMs = options.dashboardBarrierTtlMs ?? DEFAULT_DASHBOARD_BARRIER_TTL_MS;\n\t\tthis.dashboardBarrierLimit = options.dashboardBarrierLimit ?? DEFAULT_DASHBOARD_BARRIER_LIMIT;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.fleetSnapshotDebounceMs = options.fleetSnapshotDebounceMs ?? DEFAULT_FLEET_SNAPSHOT_DEBOUNCE_MS;\n\t}\n\n\t/** Subscribe to events from every runtime, tagged with the runtime key. */\n\tonEvent(listener: RuntimeEventListener): () => void {\n\t\tthis.listeners.push(listener);\n\t\treturn () => {\n\t\t\tconst i = this.listeners.indexOf(listener);\n\t\t\tif (i !== -1) this.listeners.splice(i, 1);\n\t\t};\n\t}\n\n\t/** Subscribe to debounced, in-memory fleet snapshots. */\n\tonFleetSnapshot(listener: FleetSnapshotListener): () => void {\n\t\tthis.fleetSnapshotListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst i = this.fleetSnapshotListeners.indexOf(listener);\n\t\t\tif (i !== -1) this.fleetSnapshotListeners.splice(i, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Build the fleet's live-runtime view without RPC or disk access. Map\n\t * insertion order is retained intentionally; the UI owns presentation order.\n\t */\n\tfleetSnapshot(): FleetRuntimeSnapshotDto[] {\n\t\treturn [...this.runtimes.values()].map((handle) => this.describeFleetRuntime(handle));\n\t}\n\n\tlist(): RuntimeHandle[] {\n\t\treturn [...this.runtimes.values()];\n\t}\n\n\tget(key: string): RuntimeHandle | undefined {\n\t\treturn this.runtimes.get(key);\n\t}\n\n\t/**\n\t * Record the EventHub sequence synchronously when the RPC snapshot marker\n\t * arrives. The marker line precedes its response on stdout, so this runs\n\t * before the RpcClient response continuation even across separate chunks.\n\t */\n\trecordDashboardBarrier(runtimeKey: string, snapshotId: string, seq: number): void {\n\t\tthis.pruneDashboardBarriers();\n\t\tthis.dashboardBarriers.set(this.dashboardBarrierKey(runtimeKey, snapshotId), { seq, recordedAt: this.now() });\n\t\tthis.pruneDashboardBarriers();\n\t}\n\n\t/**\n\t * Capture a parent-session recovery snapshot and pair it with the sequence\n\t * captured at its RPC marker. This deliberately does not infer ordering from\n\t * await: later EventHub publications naturally have higher sequence numbers.\n\t */\n\tasync snapshotDashboard(handle: RuntimeHandle): Promise<DashboardRuntimeSnapshot> {\n\t\tconst snapshot = await (handle.client as DashboardSnapshotClient).getDashboardSnapshot();\n\t\tthis.pruneDashboardBarriers();\n\t\tconst barrierKey = this.dashboardBarrierKey(handle.key, snapshot.snapshotId);\n\t\tconst barrier = this.dashboardBarriers.get(barrierKey);\n\t\tthis.dashboardBarriers.delete(barrierKey);\n\t\tthis.scheduleDashboardBarrierPrune();\n\t\tif (!barrier) {\n\t\t\tthrow new Error(`Dashboard snapshot ${snapshot.snapshotId} arrived without its ordering barrier`);\n\t\t}\n\t\t// This is an authoritative RPC baseline, so it may legitimately lower the\n\t\t// count after a fork/rewind instead of retaining an event-derived maximum.\n\t\thandle.lastState = snapshot.state;\n\t\tthis.scheduleFleetSnapshot();\n\t\treturn { key: handle.key, barrierSeq: barrier.seq, snapshot };\n\t}\n\n\tprivate dashboardBarrierKey(runtimeKey: string, snapshotId: string): string {\n\t\treturn `${runtimeKey}\\0${snapshotId}`;\n\t}\n\n\tprivate pruneDashboardBarriers(): void {\n\t\tconst oldestAllowed = this.now() - this.dashboardBarrierTtlMs;\n\t\tfor (const [snapshotId, barrier] of this.dashboardBarriers) {\n\t\t\tif (barrier.recordedAt < oldestAllowed) this.dashboardBarriers.delete(snapshotId);\n\t\t}\n\t\twhile (this.dashboardBarriers.size > this.dashboardBarrierLimit) {\n\t\t\tconst oldest = this.dashboardBarriers.keys().next().value;\n\t\t\tif (oldest === undefined) break;\n\t\t\tthis.dashboardBarriers.delete(oldest);\n\t\t}\n\t\tthis.scheduleDashboardBarrierPrune();\n\t}\n\n\tprivate scheduleDashboardBarrierPrune(): void {\n\t\tif (this.dashboardBarrierPruneTimer) clearTimeout(this.dashboardBarrierPruneTimer);\n\t\tthis.dashboardBarrierPruneTimer = undefined;\n\t\tlet oldest: DashboardBarrier | undefined;\n\t\tfor (const barrier of this.dashboardBarriers.values()) {\n\t\t\tif (!oldest || barrier.recordedAt < oldest.recordedAt) oldest = barrier;\n\t\t}\n\t\tif (!oldest) return;\n\t\tconst delay = Math.max(1, oldest.recordedAt + this.dashboardBarrierTtlMs - this.now() + 1);\n\t\tthis.dashboardBarrierPruneTimer = setTimeout(() => {\n\t\t\tthis.dashboardBarrierPruneTimer = undefined;\n\t\t\tthis.pruneDashboardBarriers();\n\t\t}, delay);\n\t\tthis.dashboardBarrierPruneTimer.unref?.();\n\t}\n\n\tprivate scheduleFleetSnapshot(): void {\n\t\tif (this.closing) return;\n\t\tif (this.fleetSnapshotTimer) clearTimeout(this.fleetSnapshotTimer);\n\t\tthis.fleetSnapshotTimer = setTimeout(() => {\n\t\t\tthis.fleetSnapshotTimer = undefined;\n\t\t\tif (this.closing) return;\n\t\t\tconst event: FleetSnapshotEventDto = { type: \"fleet_snapshot\", runtimes: this.fleetSnapshot() };\n\t\t\tfor (const listener of this.fleetSnapshotListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(event);\n\t\t\t\t} catch {\n\t\t\t\t\t// An SSE bridge subscriber must not break the pool's event loop.\n\t\t\t\t}\n\t\t\t}\n\t\t}, this.fleetSnapshotDebounceMs);\n\t\tthis.fleetSnapshotTimer.unref?.();\n\t}\n\n\t/** Spawn a new runtime in `cwd`, optionally opening an existing session file. */\n\tasync create(cwd: string, sessionPath?: string): Promise<RuntimeHandle> {\n\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\tconst key = randomBytes(6).toString(\"hex\");\n\t\tconst args = [\"--ui\", \"dashboard\", ...this.baseArgs];\n\t\tif (sessionPath) args.push(\"--session\", sessionPath);\n\t\tconst client = this.clientFactory({ cliPath: this.cliPath, cwd, args });\n\t\tconst handle: RuntimeHandle = {\n\t\t\tkey,\n\t\t\tcwd,\n\t\t\tclient,\n\t\t\tcreatedAt: this.now(),\n\t\t\tlastActivity: this.now(),\n\t\t\tattention: new Map(),\n\t\t\tsessionFileFallback: sessionPath,\n\t\t\tbackgroundAgents: new Map(),\n\t\t};\n\t\tclient.onEvent((event) => this.handleEvent(handle, event as unknown as Record<string, unknown>));\n\t\tclient.onExit((info) => this.handleRuntimeExit(handle, info));\n\n\t\tconst startup = this.startSessionRuntime(handle);\n\t\tthis.startupPromises.add(startup);\n\t\ttry {\n\t\t\treturn await startup;\n\t\t} finally {\n\t\t\tthis.startupPromises.delete(startup);\n\t\t}\n\t}\n\n\tprivate async startSessionRuntime(handle: RuntimeHandle): Promise<RuntimeHandle> {\n\t\tthis.starting.add(handle);\n\t\ttry {\n\t\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\t\tawait handle.client.start();\n\t\t\tif (this.closing) {\n\t\t\t\tawait handle.client.stop();\n\t\t\t\tthrow new Error(\"Runtime pool is closing\");\n\t\t\t}\n\t\t\tawait this.seedBackgroundAgents(handle);\n\t\t\tif (this.closing) {\n\t\t\t\tawait handle.client.stop();\n\t\t\t\tthrow new Error(\"Runtime pool is closing\");\n\t\t\t}\n\t\t\tthis.runtimes.set(handle.key, handle);\n\t\t\tthis.scheduleFleetSnapshot();\n\t\t\treturn handle;\n\t\t} finally {\n\t\t\tthis.starting.delete(handle);\n\t\t}\n\t}\n\n\t/** Stop a runtime and remove it from the pool. */\n\tasync stop(key: string): Promise<boolean> {\n\t\tconst handle = this.runtimes.get(key);\n\t\tif (!handle) return false;\n\t\tthis.handleEvent(handle, { type: \"runtime_removed\" });\n\t\tthis.runtimes.delete(key);\n\t\tthis.scheduleFleetSnapshot();\n\t\tawait handle.client.stop();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Return any live runtime suitable for process-global settings work, spawning\n\t * a hidden utility runtime (in the home directory) if no user session exists.\n\t * This is what lets the settings page — models, agent types, defaults — work\n\t * with zero sessions open, instead of 503-ing.\n\t */\n\tasync ensureUtilityRuntime(cwd = homedir()): Promise<RuntimeHandle> {\n\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\tconst existing = this.utilities.get(cwd);\n\t\tif (existing) return existing;\n\t\tlet promise = this.utilityPromises.get(cwd);\n\t\tif (!promise) {\n\t\t\tconst args = [\"--ui\", \"dashboard\", ...this.baseArgs];\n\t\t\tconst client = this.clientFactory({ cliPath: this.cliPath, cwd, args });\n\t\t\tconst handle: RuntimeHandle = {\n\t\t\t\tkey: `utility:${cwd}`,\n\t\t\t\tcwd,\n\t\t\t\tclient,\n\t\t\t\tcreatedAt: this.now(),\n\t\t\t\tlastActivity: this.now(),\n\t\t\t\tattention: new Map(),\n\t\t\t\tbackgroundAgents: new Map(),\n\t\t\t};\n\t\t\tconst startup = this.startUtilityRuntime(cwd, handle);\n\t\t\tthis.startupPromises.add(startup);\n\t\t\tpromise = startup\n\t\t\t\t.catch((err) => {\n\t\t\t\t\t// Allow a retry on the next request instead of caching the failure.\n\t\t\t\t\tthis.utilityPromises.delete(cwd);\n\t\t\t\t\tthrow err;\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.startupPromises.delete(startup);\n\t\t\t\t});\n\t\t\tthis.utilityPromises.set(cwd, promise);\n\t\t}\n\t\treturn promise;\n\t}\n\n\tprivate async startUtilityRuntime(cwd: string, handle: RuntimeHandle): Promise<RuntimeHandle> {\n\t\tthis.starting.add(handle);\n\t\ttry {\n\t\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\t\tawait handle.client.start();\n\t\t\tif (this.closing) {\n\t\t\t\tawait handle.client.stop();\n\t\t\t\tthrow new Error(\"Runtime pool is closing\");\n\t\t\t}\n\t\t\tthis.utilities.set(cwd, handle);\n\t\t\treturn handle;\n\t\t} finally {\n\t\t\tthis.starting.delete(handle);\n\t\t}\n\t}\n\n\tasync stopAll(): Promise<void> {\n\t\tthis.closing = true;\n\t\tif (this.dashboardBarrierPruneTimer) clearTimeout(this.dashboardBarrierPruneTimer);\n\t\tthis.dashboardBarrierPruneTimer = undefined;\n\t\tif (this.fleetSnapshotTimer) clearTimeout(this.fleetSnapshotTimer);\n\t\tthis.fleetSnapshotTimer = undefined;\n\t\tthis.fleetSnapshotListeners.length = 0;\n\t\tthis.dashboardBarriers.clear();\n\t\tconst handles = new Set<RuntimeHandle>([\n\t\t\t...this.runtimes.values(),\n\t\t\t...this.utilities.values(),\n\t\t\t...this.starting.values(),\n\t\t]);\n\t\tconst startupPromises = new Set<Promise<unknown>>([...this.startupPromises, ...this.utilityPromises.values()]);\n\t\tthis.runtimes.clear();\n\t\tthis.utilities.clear();\n\t\tthis.utilityPromises.clear();\n\t\tawait Promise.allSettled([...handles].map((handle) => handle.client.stop()));\n\t\tawait Promise.allSettled([...startupPromises]);\n\t}\n\n\tprivate handleRuntimeExit(handle: RuntimeHandle, info: RpcExitInfo): void {\n\t\tif (this.closing || this.exitedHandles.has(handle) || !this.isLiveHandle(handle)) return;\n\t\tthis.exitedHandles.add(handle);\n\t\tconst message = formatRpcExit(info);\n\t\tthis.recordRuntimeError(handle, message);\n\t\tthis.logger(`runtime ${handle.key} ${message}`);\n\t\tthis.handleEvent(handle, { type: \"agent_end\", messages: [], aborted: true, errorMessage: message });\n\t}\n\n\tprivate isLiveHandle(handle: RuntimeHandle): boolean {\n\t\treturn (\n\t\t\tthis.runtimes.get(handle.key) === handle ||\n\t\t\tthis.utilities.get(handle.cwd) === handle ||\n\t\t\tthis.starting.has(handle)\n\t\t);\n\t}\n\n\tprivate handleEvent(handle: RuntimeHandle, event: Record<string, unknown>): void {\n\t\tconst type = event.type as string;\n\t\tif (type !== \"dashboard_snapshot_barrier\") {\n\t\t\thandle.lastActivity = this.now();\n\t\t\tthis.updateStateFromEvent(handle, event, type);\n\t\t}\n\n\t\t// Track needs-attention sources: extension UI requests, parent\n\t\t// paused, error states.\n\t\tif (type === \"extension_ui_request\") {\n\t\t\tconst method = event.method as string;\n\t\t\tif (method === \"select\" || method === \"confirm\" || method === \"input\" || method === \"editor\") {\n\t\t\t\thandle.attention.set(`ui:${event.id}`, `extension ${method} awaiting response`);\n\t\t\t}\n\t\t}\n\t\tif (type === \"extension_ui_response_handled\") {\n\t\t\thandle.attention.delete(`ui:${event.id}`);\n\t\t}\n\t\tif (type === \"agent_start\") {\n\t\t\t// A new turn clears prior UI-request attention (requests were resolved or timed out).\n\t\t\tfor (const k of [...handle.attention.keys()]) {\n\t\t\t\tif (k.startsWith(\"ui:\")) handle.attention.delete(k);\n\t\t\t}\n\t\t\thandle.attention.delete(\"paused\");\n\t\t\thandle.attention.delete(\"suggest\");\n\t\t\thandle.attention.delete(\"error\");\n\t\t\thandle.error = undefined;\n\t\t}\n\t\tif (type === \"suggest_next\") {\n\t\t\t// suggest_next as the ending action = \"your move\": mark needs-attention\n\t\t\t// so the fleet card doesn't read idle. Cleared on the next agent_start.\n\t\t\thandle.attention.set(\"suggest\", \"suggested command awaiting\");\n\t\t}\n\t\tif (type === \"parent_paused_for_background_agents\") {\n\t\t\thandle.attention.set(\"paused\", `paused — ${event.runningAgentCount} background agents running`);\n\t\t}\n\t\tif (type === \"agent_end\") {\n\t\t\thandle.attention.delete(\"paused\");\n\t\t\tif (event.errorMessage) this.recordRuntimeError(handle, String(event.errorMessage));\n\t\t}\n\t\tif (type === \"auto_retry_end\" && event.success === false && event.finalError) {\n\t\t\tthis.recordRuntimeError(handle, String(event.finalError));\n\t\t}\n\t\tif (type === \"auto_compaction_end\" && event.errorMessage) {\n\t\t\tthis.recordRuntimeError(handle, String(event.errorMessage));\n\t\t}\n\n\t\t// Track background agents from lifecycle events.\n\t\tif (type === \"background_agent_start\") {\n\t\t\thandle.backgroundAgents.set(event.agentId as string, {\n\t\t\t\tagentId: event.agentId as string,\n\t\t\t\tagentType: event.agentType as string,\n\t\t\t\ttaskSummary: event.taskSummary as string,\n\t\t\t\tstartedAt: new Date().toISOString(),\n\t\t\t\tstatus: \"running\",\n\t\t\t\tsessionDir: event.sessionDir as string | undefined,\n\t\t\t});\n\t\t}\n\t\tif (type === \"background_agent_end\") {\n\t\t\tconst existing = handle.backgroundAgents.get(event.agentId as string);\n\t\t\tif (existing) {\n\t\t\t\texisting.status = event.success ? \"completed\" : \"failed\";\n\t\t\t\texisting.sessionFile = (event.sessionFile as string | undefined) ?? existing.sessionFile;\n\t\t\t\tthis.pruneCompletedBackgroundAgents(handle);\n\t\t\t}\n\t\t}\n\n\t\tfor (const listener of this.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(handle.key, event);\n\t\t\t} catch {\n\t\t\t\t// A broken SSE subscriber must not break event distribution.\n\t\t\t}\n\t\t}\n\t\tif (this.runtimes.get(handle.key) === handle && FLEET_SNAPSHOT_EVENT_TYPES.has(type)) {\n\t\t\tthis.scheduleFleetSnapshot();\n\t\t}\n\t}\n\n\t/**\n\t * Events intentionally patch only fields they can prove. Session identity,\n\t * session file, configuration, and context usage remain from the last RPC\n\t * baseline (or the stable creation fallback) until a later reconciliation.\n\t */\n\tprivate updateStateFromEvent(handle: RuntimeHandle, event: Record<string, unknown>, type: string): void {\n\t\tconst state = this.fallbackState(handle);\n\t\tswitch (type) {\n\t\t\tcase \"agent_start\": {\n\t\t\t\tconst model = event.model;\n\t\t\t\tif (\n\t\t\t\t\tmodel &&\n\t\t\t\t\ttypeof model === \"object\" &&\n\t\t\t\t\ttypeof (model as Record<string, unknown>).provider === \"string\" &&\n\t\t\t\t\ttypeof (model as Record<string, unknown>).id === \"string\"\n\t\t\t\t) {\n\t\t\t\t\tconst nextModel = model as { provider: string; id: string };\n\t\t\t\t\tstate.model =\n\t\t\t\t\t\tstate.model?.provider === nextModel.provider && state.model.id === nextModel.id\n\t\t\t\t\t\t\t? { ...state.model, ...nextModel }\n\t\t\t\t\t\t\t: nextModel;\n\t\t\t\t}\n\t\t\t\tstate.isStreaming = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"agent_end\":\n\t\t\t\tstate.isStreaming = false;\n\t\t\t\tbreak;\n\t\t\tcase \"auto_compaction_start\":\n\t\t\t\tstate.isCompacting = true;\n\t\t\t\tbreak;\n\t\t\tcase \"auto_compaction_end\":\n\t\t\t\tstate.isCompacting = false;\n\t\t\t\tbreak;\n\t\t\tcase \"tasks_update\":\n\t\t\t\tif (Array.isArray(event.tasks)) state.tasks = [...event.tasks] as SessionStateDto[\"tasks\"];\n\t\t\t\tbreak;\n\t\t\tcase \"session_name_changed\":\n\t\t\t\tif (typeof event.name === \"string\") state.sessionName = event.name;\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\t\tstate.messageCount += 1;\n\t\t\t\tbreak;\n\t\t}\n\t\thandle.lastState = state;\n\t}\n\n\tprivate recordRuntimeError(handle: RuntimeHandle, message: string): void {\n\t\thandle.error = message;\n\t\thandle.attention.set(\"error\", message);\n\t\tif (this.runtimes.get(handle.key) === handle) this.scheduleFleetSnapshot();\n\t}\n\n\tprivate pruneCompletedBackgroundAgents(handle: RuntimeHandle): void {\n\t\tconst evictable = [...handle.backgroundAgents.values()]\n\t\t\t.map((agent, index) => {\n\t\t\t\tconst startedAtMs = Date.parse(agent.startedAt);\n\t\t\t\treturn { agent, index, startedAtMs: Number.isFinite(startedAtMs) ? startedAtMs : 0 };\n\t\t\t})\n\t\t\t.filter(({ agent }) => agent.status !== \"running\")\n\t\t\t.sort((a, b) => a.startedAtMs - b.startedAtMs || a.index - b.index);\n\t\tconst excess = evictable.length - MAX_COMPLETED_BACKGROUND_AGENTS;\n\t\tif (excess <= 0) return;\n\t\tfor (const { agent } of evictable.slice(0, excess)) {\n\t\t\thandle.backgroundAgents.delete(agent.agentId);\n\t\t}\n\t}\n\n\tprivate fallbackState(handle: RuntimeHandle): SessionStateDto {\n\t\tconst previous = handle.lastState;\n\t\treturn {\n\t\t\t...previous,\n\t\t\tsessionId: previous?.sessionId ?? handle.key,\n\t\t\ttasks: previous?.tasks ? [...previous.tasks] : [],\n\t\t\tthinkingLevel: previous?.thinkingLevel ?? \"off\",\n\t\t\tisStreaming: previous?.isStreaming ?? false,\n\t\t\tisCompacting: previous?.isCompacting ?? false,\n\t\t\tsteeringMode: previous?.steeringMode ?? \"all\",\n\t\t\tfollowUpMode: previous?.followUpMode ?? \"all\",\n\t\t\tsessionFile: previous?.sessionFile ?? handle.sessionFileFallback,\n\t\t\tautoCompactionEnabled: previous?.autoCompactionEnabled ?? false,\n\t\t\tmessageCount: previous?.messageCount ?? 0,\n\t\t\tpendingMessageCount: previous?.pendingMessageCount ?? 0,\n\t\t};\n\t}\n\n\tprivate describeFleetRuntime(handle: RuntimeHandle): FleetRuntimeSnapshotDto {\n\t\tconst state = this.fallbackState(handle);\n\t\treturn {\n\t\t\tkey: handle.key,\n\t\t\tcwd: handle.cwd,\n\t\t\tstate,\n\t\t\tbackgroundAgents: [...handle.backgroundAgents.values()].map((agent) => ({ ...agent })),\n\t\t\tneedsAttention: handle.attention.size > 0,\n\t\t\terror: handle.error,\n\t\t\tcreatedAt: new Date(handle.createdAt).toISOString(),\n\t\t\tlastActivity: new Date(handle.lastActivity).toISOString(),\n\t\t};\n\t}\n\n\tprivate async seedBackgroundAgents(handle: RuntimeHandle): Promise<void> {\n\t\ttry {\n\t\t\tconst agents = (await handle.client.listBackgroundAgents()) as unknown as BackgroundAgentDto[];\n\t\t\tfor (const agent of agents) {\n\t\t\t\thandle.backgroundAgents.set(agent.agentId, agent);\n\t\t\t}\n\t\t\tthis.pruneCompletedBackgroundAgents(handle);\n\t\t} catch (err) {\n\t\t\tthis.logger(\n\t\t\t\t`runtime ${handle.key} background-agent registry unavailable: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Snapshot a runtime for the fleet endpoint. */\n\tasync describe(handle: RuntimeHandle): Promise<RuntimeInfoDto> {\n\t\tconst previousFleetRuntime =\n\t\t\tthis.runtimes.get(handle.key) === handle ? this.describeFleetRuntime(handle) : undefined;\n\t\tlet fleetRuntimeEnriched = false;\n\t\tlet state: SessionStateDto;\n\t\ttry {\n\t\t\tconst authoritative = (await handle.client.getState()) as unknown as SessionStateDto;\n\t\t\tconst fallback = this.fallbackState(handle);\n\t\t\tstate = {\n\t\t\t\t...fallback,\n\t\t\t\t...authoritative,\n\t\t\t\tsessionId: authoritative.sessionId ?? fallback.sessionId,\n\t\t\t\tsessionFile: authoritative.sessionFile ?? fallback.sessionFile,\n\t\t\t\ttasks: authoritative.tasks ?? fallback.tasks,\n\t\t\t};\n\t\t\thandle.lastState = state;\n\t\t\tfleetRuntimeEnriched = true;\n\t\t\tif (handle.error?.startsWith(\"RPC process\")) {\n\t\t\t\thandle.error = undefined;\n\t\t\t\thandle.attention.delete(\"error\");\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthis.recordRuntimeError(handle, message);\n\t\t\tthis.logger(`runtime ${handle.key} state unavailable for fleet card: ${message}`);\n\t\t\tstate = this.fallbackState(handle);\n\t\t}\n\t\tlet stats: RuntimeStatsSummaryDto | undefined;\n\t\ttry {\n\t\t\tconst sessionStats = await handle.client.getSessionStats();\n\t\t\tstats = { tokensTotal: sessionStats.tokens.total, cost: sessionStats.cost };\n\t\t\tif (sessionStats.contextUsage) {\n\t\t\t\thandle.lastState = { ...this.fallbackState(handle), contextUsage: sessionStats.contextUsage };\n\t\t\t\tfleetRuntimeEnriched = true;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis.logger(\n\t\t\t\t`runtime ${handle.key} stats unavailable for fleet card: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t\tlet lastAssistantText: string | undefined;\n\t\ttry {\n\t\t\tconst text = await handle.client.getLastAssistantText();\n\t\t\tlastAssistantText = text ? text.slice(0, 200) : undefined;\n\t\t} catch (err) {\n\t\t\tthis.logger(\n\t\t\t\t`runtime ${handle.key} last assistant text unavailable for fleet card: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tfleetRuntimeEnriched &&\n\t\t\tpreviousFleetRuntime &&\n\t\t\tthis.runtimes.get(handle.key) === handle &&\n\t\t\t!isDeepStrictEqual(previousFleetRuntime, this.describeFleetRuntime(handle))\n\t\t) {\n\t\t\tthis.scheduleFleetSnapshot();\n\t\t}\n\t\treturn {\n\t\t\tkey: handle.key,\n\t\t\tcwd: handle.cwd,\n\t\t\tstate,\n\t\t\tstats,\n\t\t\tbackgroundAgents: [...handle.backgroundAgents.values()],\n\t\t\tneedsAttention: handle.attention.size > 0,\n\t\t\terror: handle.error,\n\t\t\tlastAssistantText,\n\t\t\tcreatedAt: new Date(handle.createdAt).toISOString(),\n\t\t\tlastActivity: new Date(handle.lastActivity).toISOString(),\n\t\t};\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime-pool.d.ts","sourceRoot":"","sources":["../../src/server/runtime-pool.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,OAAO,EAAE,SAAS,EAAoB,MAAM,wBAAwB,CAAC;AACrE,OAAO,EACN,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,+BAA+B,EAC/B,KAAK,cAAc,EAEnB,KAAK,eAAe,EACpB,MAAM,uBAAuB,CAAC;AAE/B,6FAA6F;AAC7F,wBAAgB,kBAAkB,IAAI,MAAM,CAG3C;AAOD,MAAM,MAAM,oBAAoB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;AAEzF,mEAAmE;AACnE,MAAM,MAAM,qBAAqB,GAAG,CAAC,KAAK,EAAE,qBAAqB,KAAK,IAAI,CAAC;AAE3E,OAAO,EAAE,+BAA+B,EAAE,CAAC;AAE3C,UAAU,oBAAoB;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,eAAe,CAAC;IACvB,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,gBAAgB,EAAE,kBAAkB,EAAE,CAAC;CACvC;AAID,MAAM,WAAW,wBAAwB;IACxC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,oBAAoB,CAAC;CAC/B;AAED,MAAM,WAAW,aAAa;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,SAAS,CA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,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAIhF;IAED;;;;OAIG;IACG,iBAAiB,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAehF;IAED,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,6BAA6B;IAgBrC,OAAO,CAAC,qBAAqB;IAkB7B,iFAAiF;IAC3E,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CA0BtE;YAEa,mBAAmB;IAsBjC,kDAAkD;IAC5C,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAQxC;IAED;;;;;OAKG;IACG,oBAAoB,CAAC,GAAG,SAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CA+BlE;YAEa,mBAAmB;IAgB3B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAmB7B;IAED,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,WAAW;IA+FnB;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAkD5B,OAAO,CAAC,kBAAkB;IAM1B,OAAO,CAAC,mBAAmB;IAK3B,OAAO,CAAC,kBAAkB;IAS1B,OAAO,CAAC,8BAA8B;IAetC,OAAO,CAAC,aAAa;IAoBrB,OAAO,CAAC,oBAAoB;YAcd,oBAAoB;IAclC,iDAAiD;IAC3C,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CAqE7D;CACD","sourcesContent":["/**\n * RPC runtime pool — one `dreb --mode rpc` child process per live session.\n *\n * dreb's RPC mode is strictly one-session-per-process (switch_session repoints\n * the same process; it never multiplexes), so the pool spawns N children keyed\n * by an opaque runtime key. The telegram bridge is the in-repo precedent.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { RpcClient, type RpcExitInfo } from \"@dreb/coding-agent/rpc\";\nimport {\n\ttype BackgroundAgentDto,\n\ttype FleetRuntimeSnapshotDto,\n\ttype FleetSnapshotEventDto,\n\tMAX_COMPLETED_BACKGROUND_AGENTS,\n\ttype RuntimeInfoDto,\n\ttype RuntimeStatsSummaryDto,\n\ttype SessionStateDto,\n} from \"../shared/protocol.js\";\n\n/** Resolve the absolute path to the dreb CLI (RpcClient defaults to a cwd-relative path). */\nexport function resolveDrebCliPath(): string {\n\tconst resolved = import.meta.resolve(\"@dreb/coding-agent\");\n\treturn join(dirname(fileURLToPath(resolved)), \"cli.js\");\n}\n\nfunction formatRpcExit(info: RpcExitInfo): string {\n\tif (info.error) return `RPC process failed: ${info.error.message}`;\n\treturn `RPC process exited (code ${info.code}, signal ${info.signal})`;\n}\n\nexport type RuntimeEventListener = (key: string, event: Record<string, unknown>) => void;\n\n/** Listener for coalesced, synchronous fleet runtime snapshots. */\nexport type FleetSnapshotListener = (event: FleetSnapshotEventDto) => void;\n\nexport { MAX_COMPLETED_BACKGROUND_AGENTS };\n\ninterface RpcDashboardSnapshot {\n\tsnapshotId: string;\n\tstate: SessionStateDto;\n\tmessages: unknown[];\n\tbackgroundAgents: BackgroundAgentDto[];\n}\n\ntype DashboardSnapshotClient = RpcClient & { getDashboardSnapshot(): Promise<RpcDashboardSnapshot> };\n\nexport interface DashboardRuntimeSnapshot {\n\tkey: string;\n\tbarrierSeq: number;\n\tsnapshot: RpcDashboardSnapshot;\n}\n\nexport interface RuntimeHandle {\n\tkey: string;\n\tcwd: string;\n\tclient: RpcClient;\n\t/** Session start time (ms epoch) — stable tiebreak for deterministic fleet ordering. */\n\tcreatedAt: number;\n\tlastActivity: number;\n\t/** Needs-attention sources, keyed so they can be cleared independently. */\n\tattention: Map<string, string>;\n\t/** Last runtime-level error, persisted server-side so fleet refreshes stay honest. */\n\terror?: string;\n\t/** Provider error currently responsible for error/attention; retry may clear only this source. */\n\tproviderError?: string;\n\t/** Last authoritative state, patched only with event-derivable fields between RPC reads. */\n\tlastState?: SessionStateDto;\n\t/** Resume-path fallback; events must never invent or overwrite session identity. */\n\tsessionFileFallback?: string;\n\t/** Background agents seen via events (agentId → latest info). */\n\tbackgroundAgents: Map<string, BackgroundAgentDto>;\n}\n\nexport const DEFAULT_DASHBOARD_BARRIER_TTL_MS = 5 * 60_000;\nexport const DEFAULT_DASHBOARD_BARRIER_LIMIT = 1000;\nexport const DEFAULT_FLEET_SNAPSHOT_DEBOUNCE_MS = 200;\n\n/** Events that mutate a field carried by the lightweight fleet snapshot. */\nconst FLEET_SNAPSHOT_EVENT_TYPES = new Set([\n\t\"agent_start\",\n\t\"agent_end\",\n\t\"auto_compaction_start\",\n\t\"auto_compaction_end\",\n\t\"auto_retry_start\",\n\t\"auto_retry_end\",\n\t\"background_agent_start\",\n\t\"background_agent_end\",\n\t\"extension_ui_request\",\n\t\"extension_ui_response_handled\",\n\t\"message_end\",\n\t\"message_start\",\n\t\"parent_paused_for_background_agents\",\n\t\"runtime_removed\",\n\t\"session_name_changed\",\n\t\"suggest_next\",\n\t\"tasks_update\",\n]);\n\nexport interface RuntimePoolOptions {\n\tcliPath?: string;\n\t/** Extra args for every runtime (e.g. --provider). */\n\tbaseArgs?: string[];\n\t/** RpcClient factory override for tests. */\n\tclientFactory?: (options: { cliPath: string; cwd: string; args: string[] }) => RpcClient;\n\tlogger?: (line: string) => void;\n\t/** Bounds unclaimed RPC snapshot ordering records. */\n\tdashboardBarrierTtlMs?: number;\n\tdashboardBarrierLimit?: number;\n\t/** Injectable clock for deterministic barrier-expiry tests. */\n\tnow?: () => number;\n\t/** Coalescing delay for event-derived fleet snapshot emissions. */\n\tfleetSnapshotDebounceMs?: number;\n}\n\ninterface DashboardBarrier {\n\tseq: number;\n\trecordedAt: number;\n}\n\nexport class RuntimePool {\n\tprivate readonly runtimes = new Map<string, RuntimeHandle>();\n\tprivate readonly listeners: RuntimeEventListener[] = [];\n\tprivate readonly fleetSnapshotListeners: FleetSnapshotListener[] = [];\n\tprivate readonly cliPath: string;\n\tprivate readonly baseArgs: string[];\n\tprivate readonly clientFactory: (options: { cliPath: string; cwd: string; args: string[] }) => RpcClient;\n\tprivate readonly logger: (line: string) => void;\n\t/**\n\t * A single lazily-spawned utility runtime used to service settings/model/\n\t * agent-type endpoints when no user session is live. Kept out of `runtimes`\n\t * (and therefore out of the fleet) so it never shows as a session card.\n\t */\n\tprivate readonly utilities = new Map<string, RuntimeHandle>();\n\tprivate readonly utilityPromises = new Map<string, Promise<RuntimeHandle>>();\n\tprivate readonly starting = new Set<RuntimeHandle>();\n\tprivate readonly startupPromises = new Set<Promise<unknown>>();\n\tprivate readonly exitedHandles = new WeakSet<RuntimeHandle>();\n\t/** Snapshot ordering records observed synchronously from RpcClient stdout. */\n\tprivate readonly dashboardBarriers = new Map<string, DashboardBarrier>();\n\tprivate readonly dashboardBarrierTtlMs: number;\n\tprivate readonly dashboardBarrierLimit: number;\n\tprivate readonly now: () => number;\n\tprivate readonly fleetSnapshotDebounceMs: number;\n\tprivate dashboardBarrierPruneTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate fleetSnapshotTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate closing = false;\n\n\tconstructor(options: RuntimePoolOptions = {}) {\n\t\tthis.cliPath = options.cliPath ?? resolveDrebCliPath();\n\t\tthis.baseArgs = options.baseArgs ?? [];\n\t\tthis.clientFactory =\n\t\t\toptions.clientFactory ?? ((o) => new RpcClient({ cliPath: o.cliPath, cwd: o.cwd, args: o.args }));\n\t\tthis.logger = options.logger ?? ((line) => console.warn(`[dashboard] ${line}`));\n\t\tthis.dashboardBarrierTtlMs = options.dashboardBarrierTtlMs ?? DEFAULT_DASHBOARD_BARRIER_TTL_MS;\n\t\tthis.dashboardBarrierLimit = options.dashboardBarrierLimit ?? DEFAULT_DASHBOARD_BARRIER_LIMIT;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.fleetSnapshotDebounceMs = options.fleetSnapshotDebounceMs ?? DEFAULT_FLEET_SNAPSHOT_DEBOUNCE_MS;\n\t}\n\n\t/** Subscribe to events from every runtime, tagged with the runtime key. */\n\tonEvent(listener: RuntimeEventListener): () => void {\n\t\tthis.listeners.push(listener);\n\t\treturn () => {\n\t\t\tconst i = this.listeners.indexOf(listener);\n\t\t\tif (i !== -1) this.listeners.splice(i, 1);\n\t\t};\n\t}\n\n\t/** Subscribe to debounced, in-memory fleet snapshots. */\n\tonFleetSnapshot(listener: FleetSnapshotListener): () => void {\n\t\tthis.fleetSnapshotListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst i = this.fleetSnapshotListeners.indexOf(listener);\n\t\t\tif (i !== -1) this.fleetSnapshotListeners.splice(i, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Build the fleet's live-runtime view without RPC or disk access. Map\n\t * insertion order is retained intentionally; the UI owns presentation order.\n\t */\n\tfleetSnapshot(): FleetRuntimeSnapshotDto[] {\n\t\treturn [...this.runtimes.values()].map((handle) => this.describeFleetRuntime(handle));\n\t}\n\n\tlist(): RuntimeHandle[] {\n\t\treturn [...this.runtimes.values()];\n\t}\n\n\tget(key: string): RuntimeHandle | undefined {\n\t\treturn this.runtimes.get(key);\n\t}\n\n\t/**\n\t * Record the EventHub sequence synchronously when the RPC snapshot marker\n\t * arrives. The marker line precedes its response on stdout, so this runs\n\t * before the RpcClient response continuation even across separate chunks.\n\t */\n\trecordDashboardBarrier(runtimeKey: string, snapshotId: string, seq: number): void {\n\t\tthis.pruneDashboardBarriers();\n\t\tthis.dashboardBarriers.set(this.dashboardBarrierKey(runtimeKey, snapshotId), { seq, recordedAt: this.now() });\n\t\tthis.pruneDashboardBarriers();\n\t}\n\n\t/**\n\t * Capture a parent-session recovery snapshot and pair it with the sequence\n\t * captured at its RPC marker. This deliberately does not infer ordering from\n\t * await: later EventHub publications naturally have higher sequence numbers.\n\t */\n\tasync snapshotDashboard(handle: RuntimeHandle): Promise<DashboardRuntimeSnapshot> {\n\t\tconst snapshot = await (handle.client as DashboardSnapshotClient).getDashboardSnapshot();\n\t\tthis.pruneDashboardBarriers();\n\t\tconst barrierKey = this.dashboardBarrierKey(handle.key, snapshot.snapshotId);\n\t\tconst barrier = this.dashboardBarriers.get(barrierKey);\n\t\tthis.dashboardBarriers.delete(barrierKey);\n\t\tthis.scheduleDashboardBarrierPrune();\n\t\tif (!barrier) {\n\t\t\tthrow new Error(`Dashboard snapshot ${snapshot.snapshotId} arrived without its ordering barrier`);\n\t\t}\n\t\t// This is an authoritative RPC baseline, so it may legitimately lower the\n\t\t// count after a fork/rewind instead of retaining an event-derived maximum.\n\t\thandle.lastState = snapshot.state;\n\t\tthis.scheduleFleetSnapshot();\n\t\treturn { key: handle.key, barrierSeq: barrier.seq, snapshot };\n\t}\n\n\tprivate dashboardBarrierKey(runtimeKey: string, snapshotId: string): string {\n\t\treturn `${runtimeKey}\\0${snapshotId}`;\n\t}\n\n\tprivate pruneDashboardBarriers(): void {\n\t\tconst oldestAllowed = this.now() - this.dashboardBarrierTtlMs;\n\t\tfor (const [snapshotId, barrier] of this.dashboardBarriers) {\n\t\t\tif (barrier.recordedAt < oldestAllowed) this.dashboardBarriers.delete(snapshotId);\n\t\t}\n\t\twhile (this.dashboardBarriers.size > this.dashboardBarrierLimit) {\n\t\t\tconst oldest = this.dashboardBarriers.keys().next().value;\n\t\t\tif (oldest === undefined) break;\n\t\t\tthis.dashboardBarriers.delete(oldest);\n\t\t}\n\t\tthis.scheduleDashboardBarrierPrune();\n\t}\n\n\tprivate scheduleDashboardBarrierPrune(): void {\n\t\tif (this.dashboardBarrierPruneTimer) clearTimeout(this.dashboardBarrierPruneTimer);\n\t\tthis.dashboardBarrierPruneTimer = undefined;\n\t\tlet oldest: DashboardBarrier | undefined;\n\t\tfor (const barrier of this.dashboardBarriers.values()) {\n\t\t\tif (!oldest || barrier.recordedAt < oldest.recordedAt) oldest = barrier;\n\t\t}\n\t\tif (!oldest) return;\n\t\tconst delay = Math.max(1, oldest.recordedAt + this.dashboardBarrierTtlMs - this.now() + 1);\n\t\tthis.dashboardBarrierPruneTimer = setTimeout(() => {\n\t\t\tthis.dashboardBarrierPruneTimer = undefined;\n\t\t\tthis.pruneDashboardBarriers();\n\t\t}, delay);\n\t\tthis.dashboardBarrierPruneTimer.unref?.();\n\t}\n\n\tprivate scheduleFleetSnapshot(): void {\n\t\tif (this.closing) return;\n\t\tif (this.fleetSnapshotTimer) clearTimeout(this.fleetSnapshotTimer);\n\t\tthis.fleetSnapshotTimer = setTimeout(() => {\n\t\t\tthis.fleetSnapshotTimer = undefined;\n\t\t\tif (this.closing) return;\n\t\t\tconst event: FleetSnapshotEventDto = { type: \"fleet_snapshot\", runtimes: this.fleetSnapshot() };\n\t\t\tfor (const listener of this.fleetSnapshotListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(event);\n\t\t\t\t} catch {\n\t\t\t\t\t// An SSE bridge subscriber must not break the pool's event loop.\n\t\t\t\t}\n\t\t\t}\n\t\t}, this.fleetSnapshotDebounceMs);\n\t\tthis.fleetSnapshotTimer.unref?.();\n\t}\n\n\t/** Spawn a new runtime in `cwd`, optionally opening an existing session file. */\n\tasync create(cwd: string, sessionPath?: string): Promise<RuntimeHandle> {\n\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\tconst key = randomBytes(6).toString(\"hex\");\n\t\tconst args = [\"--ui\", \"dashboard\", ...this.baseArgs];\n\t\tif (sessionPath) args.push(\"--session\", sessionPath);\n\t\tconst client = this.clientFactory({ cliPath: this.cliPath, cwd, args });\n\t\tconst handle: RuntimeHandle = {\n\t\t\tkey,\n\t\t\tcwd,\n\t\t\tclient,\n\t\t\tcreatedAt: this.now(),\n\t\t\tlastActivity: this.now(),\n\t\t\tattention: new Map(),\n\t\t\tsessionFileFallback: sessionPath,\n\t\t\tbackgroundAgents: new Map(),\n\t\t};\n\t\tclient.onEvent((event) => this.handleEvent(handle, event as unknown as Record<string, unknown>));\n\t\tclient.onExit((info) => this.handleRuntimeExit(handle, info));\n\n\t\tconst startup = this.startSessionRuntime(handle);\n\t\tthis.startupPromises.add(startup);\n\t\ttry {\n\t\t\treturn await startup;\n\t\t} finally {\n\t\t\tthis.startupPromises.delete(startup);\n\t\t}\n\t}\n\n\tprivate async startSessionRuntime(handle: RuntimeHandle): Promise<RuntimeHandle> {\n\t\tthis.starting.add(handle);\n\t\ttry {\n\t\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\t\tawait handle.client.start();\n\t\t\tif (this.closing) {\n\t\t\t\tawait handle.client.stop();\n\t\t\t\tthrow new Error(\"Runtime pool is closing\");\n\t\t\t}\n\t\t\tawait this.seedBackgroundAgents(handle);\n\t\t\tif (this.closing) {\n\t\t\t\tawait handle.client.stop();\n\t\t\t\tthrow new Error(\"Runtime pool is closing\");\n\t\t\t}\n\t\t\tthis.runtimes.set(handle.key, handle);\n\t\t\tthis.scheduleFleetSnapshot();\n\t\t\treturn handle;\n\t\t} finally {\n\t\t\tthis.starting.delete(handle);\n\t\t}\n\t}\n\n\t/** Stop a runtime and remove it from the pool. */\n\tasync stop(key: string): Promise<boolean> {\n\t\tconst handle = this.runtimes.get(key);\n\t\tif (!handle) return false;\n\t\tthis.handleEvent(handle, { type: \"runtime_removed\" });\n\t\tthis.runtimes.delete(key);\n\t\tthis.scheduleFleetSnapshot();\n\t\tawait handle.client.stop();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Return any live runtime suitable for process-global settings work, spawning\n\t * a hidden utility runtime (in the home directory) if no user session exists.\n\t * This is what lets the settings page — models, agent types, defaults — work\n\t * with zero sessions open, instead of 503-ing.\n\t */\n\tasync ensureUtilityRuntime(cwd = homedir()): Promise<RuntimeHandle> {\n\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\tconst existing = this.utilities.get(cwd);\n\t\tif (existing) return existing;\n\t\tlet promise = this.utilityPromises.get(cwd);\n\t\tif (!promise) {\n\t\t\tconst args = [\"--ui\", \"dashboard\", ...this.baseArgs];\n\t\t\tconst client = this.clientFactory({ cliPath: this.cliPath, cwd, args });\n\t\t\tconst handle: RuntimeHandle = {\n\t\t\t\tkey: `utility:${cwd}`,\n\t\t\t\tcwd,\n\t\t\t\tclient,\n\t\t\t\tcreatedAt: this.now(),\n\t\t\t\tlastActivity: this.now(),\n\t\t\t\tattention: new Map(),\n\t\t\t\tbackgroundAgents: new Map(),\n\t\t\t};\n\t\t\tconst startup = this.startUtilityRuntime(cwd, handle);\n\t\t\tthis.startupPromises.add(startup);\n\t\t\tpromise = startup\n\t\t\t\t.catch((err) => {\n\t\t\t\t\t// Allow a retry on the next request instead of caching the failure.\n\t\t\t\t\tthis.utilityPromises.delete(cwd);\n\t\t\t\t\tthrow err;\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.startupPromises.delete(startup);\n\t\t\t\t});\n\t\t\tthis.utilityPromises.set(cwd, promise);\n\t\t}\n\t\treturn promise;\n\t}\n\n\tprivate async startUtilityRuntime(cwd: string, handle: RuntimeHandle): Promise<RuntimeHandle> {\n\t\tthis.starting.add(handle);\n\t\ttry {\n\t\t\tif (this.closing) throw new Error(\"Runtime pool is closing\");\n\t\t\tawait handle.client.start();\n\t\t\tif (this.closing) {\n\t\t\t\tawait handle.client.stop();\n\t\t\t\tthrow new Error(\"Runtime pool is closing\");\n\t\t\t}\n\t\t\tthis.utilities.set(cwd, handle);\n\t\t\treturn handle;\n\t\t} finally {\n\t\t\tthis.starting.delete(handle);\n\t\t}\n\t}\n\n\tasync stopAll(): Promise<void> {\n\t\tthis.closing = true;\n\t\tif (this.dashboardBarrierPruneTimer) clearTimeout(this.dashboardBarrierPruneTimer);\n\t\tthis.dashboardBarrierPruneTimer = undefined;\n\t\tif (this.fleetSnapshotTimer) clearTimeout(this.fleetSnapshotTimer);\n\t\tthis.fleetSnapshotTimer = undefined;\n\t\tthis.fleetSnapshotListeners.length = 0;\n\t\tthis.dashboardBarriers.clear();\n\t\tconst handles = new Set<RuntimeHandle>([\n\t\t\t...this.runtimes.values(),\n\t\t\t...this.utilities.values(),\n\t\t\t...this.starting.values(),\n\t\t]);\n\t\tconst startupPromises = new Set<Promise<unknown>>([...this.startupPromises, ...this.utilityPromises.values()]);\n\t\tthis.runtimes.clear();\n\t\tthis.utilities.clear();\n\t\tthis.utilityPromises.clear();\n\t\tawait Promise.allSettled([...handles].map((handle) => handle.client.stop()));\n\t\tawait Promise.allSettled([...startupPromises]);\n\t}\n\n\tprivate handleRuntimeExit(handle: RuntimeHandle, info: RpcExitInfo): void {\n\t\tif (this.closing || this.exitedHandles.has(handle) || !this.isLiveHandle(handle)) return;\n\t\tthis.exitedHandles.add(handle);\n\t\tconst message = formatRpcExit(info);\n\t\tthis.recordRuntimeError(handle, message);\n\t\tthis.logger(`runtime ${handle.key} ${message}`);\n\t\tthis.handleEvent(handle, { type: \"agent_end\", messages: [], aborted: true, errorMessage: message });\n\t}\n\n\tprivate isLiveHandle(handle: RuntimeHandle): boolean {\n\t\treturn (\n\t\t\tthis.runtimes.get(handle.key) === handle ||\n\t\t\tthis.utilities.get(handle.cwd) === handle ||\n\t\t\tthis.starting.has(handle)\n\t\t);\n\t}\n\n\tprivate handleEvent(handle: RuntimeHandle, event: Record<string, unknown>): void {\n\t\tconst type = event.type as string;\n\t\tif (type !== \"dashboard_snapshot_barrier\") {\n\t\t\thandle.lastActivity = this.now();\n\t\t\tthis.updateStateFromEvent(handle, event, type);\n\t\t}\n\n\t\t// Track needs-attention sources: extension UI requests, parent\n\t\t// paused, error states.\n\t\tif (type === \"extension_ui_request\") {\n\t\t\tconst method = event.method as string;\n\t\t\tif (method === \"select\" || method === \"confirm\" || method === \"input\" || method === \"editor\") {\n\t\t\t\thandle.attention.set(`ui:${event.id}`, `extension ${method} awaiting response`);\n\t\t\t}\n\t\t}\n\t\tif (type === \"extension_ui_response_handled\") {\n\t\t\thandle.attention.delete(`ui:${event.id}`);\n\t\t}\n\t\tif (type === \"agent_start\") {\n\t\t\t// A new turn clears prior UI-request attention (requests were resolved or timed out).\n\t\t\tfor (const k of [...handle.attention.keys()]) {\n\t\t\t\tif (k.startsWith(\"ui:\")) handle.attention.delete(k);\n\t\t\t}\n\t\t\thandle.attention.delete(\"paused\");\n\t\t\thandle.attention.delete(\"suggest\");\n\t\t\thandle.attention.delete(\"error\");\n\t\t\thandle.error = undefined;\n\t\t\thandle.providerError = undefined;\n\t\t}\n\t\tif (type === \"suggest_next\") {\n\t\t\t// suggest_next as the ending action = \"your move\": mark needs-attention\n\t\t\t// so the fleet card doesn't read idle. Cleared on the next agent_start.\n\t\t\thandle.attention.set(\"suggest\", \"suggested command awaiting\");\n\t\t}\n\t\tif (type === \"parent_paused_for_background_agents\") {\n\t\t\thandle.attention.set(\"paused\", `paused — ${event.runningAgentCount} background agents running`);\n\t\t}\n\t\tif (type === \"agent_end\") {\n\t\t\thandle.attention.delete(\"paused\");\n\t\t\tif (event.errorMessage) this.recordRuntimeError(handle, String(event.errorMessage));\n\t\t}\n\t\tif (type === \"message_end\") {\n\t\t\tconst message = event.message;\n\t\t\tif (message && typeof message === \"object\" && !Array.isArray(message)) {\n\t\t\t\tconst assistant = message as Record<string, unknown>;\n\t\t\t\tif (assistant.role === \"assistant\" && assistant.stopReason === \"error\") {\n\t\t\t\t\tconst rawError = assistant.errorMessage;\n\t\t\t\t\tconst error = typeof rawError === \"string\" && rawError.trim().length > 0 ? rawError : \"Unknown error\";\n\t\t\t\t\tthis.recordProviderError(handle, error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (type === \"auto_retry_start\") this.clearProviderError(handle);\n\t\tif (type === \"auto_compaction_start\" && event.reason === \"overflow\") this.clearProviderError(handle);\n\t\tif (type === \"auto_retry_end\" && event.success === false && event.finalError) {\n\t\t\tthis.recordProviderError(handle, String(event.finalError));\n\t\t} else if (type === \"auto_retry_end\" && event.success === true) {\n\t\t\tthis.clearProviderError(handle);\n\t\t}\n\t\tif (type === \"auto_compaction_end\" && event.errorMessage) {\n\t\t\tthis.recordRuntimeError(handle, String(event.errorMessage));\n\t\t}\n\n\t\t// Track background agents from lifecycle events.\n\t\tif (type === \"background_agent_start\") {\n\t\t\thandle.backgroundAgents.set(event.agentId as string, {\n\t\t\t\tagentId: event.agentId as string,\n\t\t\t\tagentType: event.agentType as string,\n\t\t\t\ttaskSummary: event.taskSummary as string,\n\t\t\t\tstartedAt: new Date().toISOString(),\n\t\t\t\tstatus: \"running\",\n\t\t\t\tsessionDir: event.sessionDir as string | undefined,\n\t\t\t});\n\t\t}\n\t\tif (type === \"background_agent_end\") {\n\t\t\tconst existing = handle.backgroundAgents.get(event.agentId as string);\n\t\t\tif (existing) {\n\t\t\t\texisting.status = event.success ? \"completed\" : \"failed\";\n\t\t\t\texisting.sessionFile = (event.sessionFile as string | undefined) ?? existing.sessionFile;\n\t\t\t\tthis.pruneCompletedBackgroundAgents(handle);\n\t\t\t}\n\t\t}\n\n\t\tfor (const listener of this.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(handle.key, event);\n\t\t\t} catch {\n\t\t\t\t// A broken SSE subscriber must not break event distribution.\n\t\t\t}\n\t\t}\n\t\tif (this.runtimes.get(handle.key) === handle && FLEET_SNAPSHOT_EVENT_TYPES.has(type)) {\n\t\t\tthis.scheduleFleetSnapshot();\n\t\t}\n\t}\n\n\t/**\n\t * Events intentionally patch only fields they can prove. Session identity,\n\t * session file, configuration, and context usage remain from the last RPC\n\t * baseline (or the stable creation fallback) until a later reconciliation.\n\t */\n\tprivate updateStateFromEvent(handle: RuntimeHandle, event: Record<string, unknown>, type: string): void {\n\t\tconst state = this.fallbackState(handle);\n\t\tswitch (type) {\n\t\t\tcase \"agent_start\": {\n\t\t\t\tconst model = event.model;\n\t\t\t\tif (\n\t\t\t\t\tmodel &&\n\t\t\t\t\ttypeof model === \"object\" &&\n\t\t\t\t\ttypeof (model as Record<string, unknown>).provider === \"string\" &&\n\t\t\t\t\ttypeof (model as Record<string, unknown>).id === \"string\"\n\t\t\t\t) {\n\t\t\t\t\tconst nextModel = model as { provider: string; id: string };\n\t\t\t\t\tstate.model =\n\t\t\t\t\t\tstate.model?.provider === nextModel.provider && state.model.id === nextModel.id\n\t\t\t\t\t\t\t? { ...state.model, ...nextModel }\n\t\t\t\t\t\t\t: nextModel;\n\t\t\t\t}\n\t\t\t\tstate.isStreaming = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"agent_end\":\n\t\t\t\tstate.isStreaming = false;\n\t\t\t\tbreak;\n\t\t\tcase \"auto_compaction_start\":\n\t\t\t\tstate.isCompacting = true;\n\t\t\t\tbreak;\n\t\t\tcase \"auto_compaction_end\":\n\t\t\t\tstate.isCompacting = false;\n\t\t\t\tbreak;\n\t\t\tcase \"auto_retry_start\":\n\t\t\t\tstate.isRetrying = true;\n\t\t\t\tstate.retryAttempt = typeof event.attempt === \"number\" ? event.attempt : state.retryAttempt;\n\t\t\t\tbreak;\n\t\t\tcase \"auto_retry_end\":\n\t\t\t\tstate.isRetrying = false;\n\t\t\t\tstate.retryAttempt = 0;\n\t\t\t\tbreak;\n\t\t\tcase \"tasks_update\":\n\t\t\t\tif (Array.isArray(event.tasks)) state.tasks = [...event.tasks] as SessionStateDto[\"tasks\"];\n\t\t\t\tbreak;\n\t\t\tcase \"session_name_changed\":\n\t\t\t\tif (typeof event.name === \"string\") state.sessionName = event.name;\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\t\tstate.messageCount += 1;\n\t\t\t\tbreak;\n\t\t}\n\t\thandle.lastState = state;\n\t}\n\n\tprivate recordRuntimeError(handle: RuntimeHandle, message: string): void {\n\t\thandle.error = message;\n\t\thandle.attention.set(\"error\", message);\n\t\tif (this.runtimes.get(handle.key) === handle) this.scheduleFleetSnapshot();\n\t}\n\n\tprivate recordProviderError(handle: RuntimeHandle, message: string): void {\n\t\thandle.providerError = message;\n\t\tthis.recordRuntimeError(handle, message);\n\t}\n\n\tprivate clearProviderError(handle: RuntimeHandle): void {\n\t\tconst providerError = handle.providerError;\n\t\tif (providerError === undefined) return;\n\t\thandle.providerError = undefined;\n\t\tif (handle.error === providerError) handle.error = undefined;\n\t\tif (handle.attention.get(\"error\") === providerError) handle.attention.delete(\"error\");\n\t\tif (this.runtimes.get(handle.key) === handle) this.scheduleFleetSnapshot();\n\t}\n\n\tprivate pruneCompletedBackgroundAgents(handle: RuntimeHandle): void {\n\t\tconst evictable = [...handle.backgroundAgents.values()]\n\t\t\t.map((agent, index) => {\n\t\t\t\tconst startedAtMs = Date.parse(agent.startedAt);\n\t\t\t\treturn { agent, index, startedAtMs: Number.isFinite(startedAtMs) ? startedAtMs : 0 };\n\t\t\t})\n\t\t\t.filter(({ agent }) => agent.status !== \"running\")\n\t\t\t.sort((a, b) => a.startedAtMs - b.startedAtMs || a.index - b.index);\n\t\tconst excess = evictable.length - MAX_COMPLETED_BACKGROUND_AGENTS;\n\t\tif (excess <= 0) return;\n\t\tfor (const { agent } of evictable.slice(0, excess)) {\n\t\t\thandle.backgroundAgents.delete(agent.agentId);\n\t\t}\n\t}\n\n\tprivate fallbackState(handle: RuntimeHandle): SessionStateDto {\n\t\tconst previous = handle.lastState;\n\t\treturn {\n\t\t\t...previous,\n\t\t\tsessionId: previous?.sessionId ?? handle.key,\n\t\t\ttasks: previous?.tasks ? [...previous.tasks] : [],\n\t\t\tthinkingLevel: previous?.thinkingLevel ?? \"off\",\n\t\t\tisStreaming: previous?.isStreaming ?? false,\n\t\t\tisRetrying: previous?.isRetrying ?? false,\n\t\t\tretryAttempt: previous?.retryAttempt ?? 0,\n\t\t\tisCompacting: previous?.isCompacting ?? false,\n\t\t\tsteeringMode: previous?.steeringMode ?? \"all\",\n\t\t\tfollowUpMode: previous?.followUpMode ?? \"all\",\n\t\t\tsessionFile: previous?.sessionFile ?? handle.sessionFileFallback,\n\t\t\tautoCompactionEnabled: previous?.autoCompactionEnabled ?? false,\n\t\t\tmessageCount: previous?.messageCount ?? 0,\n\t\t\tpendingMessageCount: previous?.pendingMessageCount ?? 0,\n\t\t};\n\t}\n\n\tprivate describeFleetRuntime(handle: RuntimeHandle): FleetRuntimeSnapshotDto {\n\t\tconst state = this.fallbackState(handle);\n\t\treturn {\n\t\t\tkey: handle.key,\n\t\t\tcwd: handle.cwd,\n\t\t\tstate,\n\t\t\tbackgroundAgents: [...handle.backgroundAgents.values()].map((agent) => ({ ...agent })),\n\t\t\tneedsAttention: handle.attention.size > 0,\n\t\t\terror: handle.error,\n\t\t\tcreatedAt: new Date(handle.createdAt).toISOString(),\n\t\t\tlastActivity: new Date(handle.lastActivity).toISOString(),\n\t\t};\n\t}\n\n\tprivate async seedBackgroundAgents(handle: RuntimeHandle): Promise<void> {\n\t\ttry {\n\t\t\tconst agents = (await handle.client.listBackgroundAgents()) as unknown as BackgroundAgentDto[];\n\t\t\tfor (const agent of agents) {\n\t\t\t\thandle.backgroundAgents.set(agent.agentId, agent);\n\t\t\t}\n\t\t\tthis.pruneCompletedBackgroundAgents(handle);\n\t\t} catch (err) {\n\t\t\tthis.logger(\n\t\t\t\t`runtime ${handle.key} background-agent registry unavailable: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Snapshot a runtime for the fleet endpoint. */\n\tasync describe(handle: RuntimeHandle): Promise<RuntimeInfoDto> {\n\t\tconst previousFleetRuntime =\n\t\t\tthis.runtimes.get(handle.key) === handle ? this.describeFleetRuntime(handle) : undefined;\n\t\tlet fleetRuntimeEnriched = false;\n\t\tlet state: SessionStateDto;\n\t\ttry {\n\t\t\tconst authoritative = (await handle.client.getState()) as unknown as SessionStateDto;\n\t\t\tconst fallback = this.fallbackState(handle);\n\t\t\tstate = {\n\t\t\t\t...fallback,\n\t\t\t\t...authoritative,\n\t\t\t\tsessionId: authoritative.sessionId ?? fallback.sessionId,\n\t\t\t\tsessionFile: authoritative.sessionFile ?? fallback.sessionFile,\n\t\t\t\ttasks: authoritative.tasks ?? fallback.tasks,\n\t\t\t};\n\t\t\thandle.lastState = state;\n\t\t\tfleetRuntimeEnriched = true;\n\t\t\tif (handle.error?.startsWith(\"RPC process\")) {\n\t\t\t\thandle.error = undefined;\n\t\t\t\thandle.attention.delete(\"error\");\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthis.recordRuntimeError(handle, message);\n\t\t\tthis.logger(`runtime ${handle.key} state unavailable for fleet card: ${message}`);\n\t\t\tstate = this.fallbackState(handle);\n\t\t}\n\t\tlet stats: RuntimeStatsSummaryDto | undefined;\n\t\ttry {\n\t\t\tconst sessionStats = await handle.client.getSessionStats();\n\t\t\tstats = { tokensTotal: sessionStats.tokens.total, cost: sessionStats.cost };\n\t\t\tif (sessionStats.contextUsage) {\n\t\t\t\thandle.lastState = { ...this.fallbackState(handle), contextUsage: sessionStats.contextUsage };\n\t\t\t\tfleetRuntimeEnriched = true;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis.logger(\n\t\t\t\t`runtime ${handle.key} stats unavailable for fleet card: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t\tlet lastAssistantText: string | undefined;\n\t\ttry {\n\t\t\tconst text = await handle.client.getLastAssistantText();\n\t\t\tlastAssistantText = text ? text.slice(0, 200) : undefined;\n\t\t} catch (err) {\n\t\t\tthis.logger(\n\t\t\t\t`runtime ${handle.key} last assistant text unavailable for fleet card: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tfleetRuntimeEnriched &&\n\t\t\tpreviousFleetRuntime &&\n\t\t\tthis.runtimes.get(handle.key) === handle &&\n\t\t\t!isDeepStrictEqual(previousFleetRuntime, this.describeFleetRuntime(handle))\n\t\t) {\n\t\t\tthis.scheduleFleetSnapshot();\n\t\t}\n\t\treturn {\n\t\t\tkey: handle.key,\n\t\t\tcwd: handle.cwd,\n\t\t\tstate,\n\t\t\tstats,\n\t\t\tbackgroundAgents: [...handle.backgroundAgents.values()],\n\t\t\tneedsAttention: handle.attention.size > 0,\n\t\t\terror: handle.error,\n\t\t\tlastAssistantText,\n\t\t\tcreatedAt: new Date(handle.createdAt).toISOString(),\n\t\t\tlastActivity: new Date(handle.lastActivity).toISOString(),\n\t\t};\n\t}\n}\n"]}
|
|
@@ -32,11 +32,13 @@ const FLEET_SNAPSHOT_EVENT_TYPES = new Set([
|
|
|
32
32
|
"agent_end",
|
|
33
33
|
"auto_compaction_start",
|
|
34
34
|
"auto_compaction_end",
|
|
35
|
+
"auto_retry_start",
|
|
35
36
|
"auto_retry_end",
|
|
36
37
|
"background_agent_start",
|
|
37
38
|
"background_agent_end",
|
|
38
39
|
"extension_ui_request",
|
|
39
40
|
"extension_ui_response_handled",
|
|
41
|
+
"message_end",
|
|
40
42
|
"message_start",
|
|
41
43
|
"parent_paused_for_background_agents",
|
|
42
44
|
"runtime_removed",
|
|
@@ -384,6 +386,7 @@ export class RuntimePool {
|
|
|
384
386
|
handle.attention.delete("suggest");
|
|
385
387
|
handle.attention.delete("error");
|
|
386
388
|
handle.error = undefined;
|
|
389
|
+
handle.providerError = undefined;
|
|
387
390
|
}
|
|
388
391
|
if (type === "suggest_next") {
|
|
389
392
|
// suggest_next as the ending action = "your move": mark needs-attention
|
|
@@ -398,8 +401,26 @@ export class RuntimePool {
|
|
|
398
401
|
if (event.errorMessage)
|
|
399
402
|
this.recordRuntimeError(handle, String(event.errorMessage));
|
|
400
403
|
}
|
|
404
|
+
if (type === "message_end") {
|
|
405
|
+
const message = event.message;
|
|
406
|
+
if (message && typeof message === "object" && !Array.isArray(message)) {
|
|
407
|
+
const assistant = message;
|
|
408
|
+
if (assistant.role === "assistant" && assistant.stopReason === "error") {
|
|
409
|
+
const rawError = assistant.errorMessage;
|
|
410
|
+
const error = typeof rawError === "string" && rawError.trim().length > 0 ? rawError : "Unknown error";
|
|
411
|
+
this.recordProviderError(handle, error);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (type === "auto_retry_start")
|
|
416
|
+
this.clearProviderError(handle);
|
|
417
|
+
if (type === "auto_compaction_start" && event.reason === "overflow")
|
|
418
|
+
this.clearProviderError(handle);
|
|
401
419
|
if (type === "auto_retry_end" && event.success === false && event.finalError) {
|
|
402
|
-
this.
|
|
420
|
+
this.recordProviderError(handle, String(event.finalError));
|
|
421
|
+
}
|
|
422
|
+
else if (type === "auto_retry_end" && event.success === true) {
|
|
423
|
+
this.clearProviderError(handle);
|
|
403
424
|
}
|
|
404
425
|
if (type === "auto_compaction_end" && event.errorMessage) {
|
|
405
426
|
this.recordRuntimeError(handle, String(event.errorMessage));
|
|
@@ -467,6 +488,14 @@ export class RuntimePool {
|
|
|
467
488
|
case "auto_compaction_end":
|
|
468
489
|
state.isCompacting = false;
|
|
469
490
|
break;
|
|
491
|
+
case "auto_retry_start":
|
|
492
|
+
state.isRetrying = true;
|
|
493
|
+
state.retryAttempt = typeof event.attempt === "number" ? event.attempt : state.retryAttempt;
|
|
494
|
+
break;
|
|
495
|
+
case "auto_retry_end":
|
|
496
|
+
state.isRetrying = false;
|
|
497
|
+
state.retryAttempt = 0;
|
|
498
|
+
break;
|
|
470
499
|
case "tasks_update":
|
|
471
500
|
if (Array.isArray(event.tasks))
|
|
472
501
|
state.tasks = [...event.tasks];
|
|
@@ -487,6 +516,22 @@ export class RuntimePool {
|
|
|
487
516
|
if (this.runtimes.get(handle.key) === handle)
|
|
488
517
|
this.scheduleFleetSnapshot();
|
|
489
518
|
}
|
|
519
|
+
recordProviderError(handle, message) {
|
|
520
|
+
handle.providerError = message;
|
|
521
|
+
this.recordRuntimeError(handle, message);
|
|
522
|
+
}
|
|
523
|
+
clearProviderError(handle) {
|
|
524
|
+
const providerError = handle.providerError;
|
|
525
|
+
if (providerError === undefined)
|
|
526
|
+
return;
|
|
527
|
+
handle.providerError = undefined;
|
|
528
|
+
if (handle.error === providerError)
|
|
529
|
+
handle.error = undefined;
|
|
530
|
+
if (handle.attention.get("error") === providerError)
|
|
531
|
+
handle.attention.delete("error");
|
|
532
|
+
if (this.runtimes.get(handle.key) === handle)
|
|
533
|
+
this.scheduleFleetSnapshot();
|
|
534
|
+
}
|
|
490
535
|
pruneCompletedBackgroundAgents(handle) {
|
|
491
536
|
const evictable = [...handle.backgroundAgents.values()]
|
|
492
537
|
.map((agent, index) => {
|
|
@@ -510,6 +555,8 @@ export class RuntimePool {
|
|
|
510
555
|
tasks: previous?.tasks ? [...previous.tasks] : [],
|
|
511
556
|
thinkingLevel: previous?.thinkingLevel ?? "off",
|
|
512
557
|
isStreaming: previous?.isStreaming ?? false,
|
|
558
|
+
isRetrying: previous?.isRetrying ?? false,
|
|
559
|
+
retryAttempt: previous?.retryAttempt ?? 0,
|
|
513
560
|
isCompacting: previous?.isCompacting ?? false,
|
|
514
561
|
steeringMode: previous?.steeringMode ?? "all",
|
|
515
562
|
followUpMode: previous?.followUpMode ?? "all",
|