@lune_99/pi-compaction 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,154 @@
1
+ import { clampThinkingLevel, getSupportedThinkingLevels } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { defineSettings } from "@lune_99/pi-lune-extensions-core/settings";
4
+ import {
5
+ defineSettingsPanel,
6
+ modelChoices,
7
+ type ModelReference,
8
+ type SettingsChoiceSource,
9
+ } from "@lune_99/pi-lune-extensions-core/panel";
10
+ import { createDefinedSettingsSection } from "@lune_99/pi-lune-extensions-core/panel/host";
11
+ import { compactionSchema, SETTINGS_ID, type CompactionSettingsView } from "./schema.ts";
12
+
13
+ export const summaryModelChoices: SettingsChoiceSource<ModelReference | null> = modelChoices({
14
+ emptyMessage:
15
+ "No summary models are available. Configure a provider in Pi, then press Ctrl+R to refresh.",
16
+ specialChoices: [
17
+ {
18
+ value: null,
19
+ label: "Follow session model",
20
+ description: "Use the current session model and effort for each compaction operation.",
21
+ },
22
+ ],
23
+ });
24
+
25
+ export const classifierChoices: SettingsChoiceSource<ModelReference | null> = modelChoices({
26
+ type: "classifier",
27
+ specialChoices: (_context, entries) => [
28
+ {
29
+ value: null,
30
+ label: "Automatic",
31
+ description: entries.length
32
+ ? `Use the first available Pi classifier at runtime (${entries[0]!.provider}/${entries[0]!.id} currently).`
33
+ : "No classifier is available. Configure a provider in Pi with /login or environment credentials, then press Ctrl+R to refresh.",
34
+ },
35
+ ],
36
+ });
37
+
38
+ export const compactionSettings = defineSettings({ id: SETTINGS_ID, schema: compactionSchema });
39
+
40
+ export function createCompactionPanel(getTools: ExtensionAPI["getAllTools"]) {
41
+ return defineSettingsPanel(compactionSettings, {
42
+ id: "compaction",
43
+ label: "Compaction",
44
+ fields: (field) => [
45
+ field("enabled", {
46
+ label: "Lune compaction",
47
+ description:
48
+ "Enabled by default. Follow the session model and effort, or select a separate summary model. Changes apply on the next operation.",
49
+ }),
50
+ field("summaryModel", {
51
+ label: "Compaction model",
52
+ formatValue: (value) =>
53
+ value ? `${value.provider}/${value.id}` : "Follow session model",
54
+ choiceSource: summaryModelChoices,
55
+ }),
56
+ field("summaryThinkingLevel", {
57
+ label: "Compaction thinking level",
58
+ description:
59
+ "Inherited from the session when following its model; otherwise configured independently.",
60
+ formatValue: (value, { context, values }) => {
61
+ if (!values.summaryModel)
62
+ return `Follow session effort${context.thinkingLevel ? ` · ${context.thinkingLevel}` : ""}`;
63
+ const model = context.modelRegistry.find(
64
+ values.summaryModel.provider,
65
+ values.summaryModel.id,
66
+ );
67
+ if (!model) return `${value} (select an available model first)`;
68
+ const effective = clampThinkingLevel(model, value);
69
+ return effective === value ? value : `${value} → ${effective} (model limit)`;
70
+ },
71
+ choiceSource: {
72
+ load: ({ context, values }) => {
73
+ if (!values.summaryModel)
74
+ throw new Error(
75
+ "Effort follows the session. Select a separate summary model to configure it independently.",
76
+ );
77
+ const model = context.modelRegistry.find(
78
+ values.summaryModel.provider,
79
+ values.summaryModel.id,
80
+ );
81
+ if (!model)
82
+ throw new Error("Selected summary model is no longer registered");
83
+ return getSupportedThinkingLevels(model).map((value) => ({
84
+ value,
85
+ label: value,
86
+ }));
87
+ },
88
+ },
89
+ }),
90
+ field("jevEnabled", {
91
+ label: "Jev preprocessing",
92
+ description:
93
+ "Classify permitted tool outputs before compaction. Configure provider authentication in Pi.",
94
+ }),
95
+ field("classifier", {
96
+ label: "Classifier model",
97
+ formatValue: (value) =>
98
+ value
99
+ ? `${value.provider}/${value.id}`
100
+ : "Automatic · available Pi classifiers",
101
+ choiceSource: classifierChoices,
102
+ }),
103
+ field(["policy", "deleteThreshold"], {
104
+ label: "Drop confidence",
105
+ description:
106
+ "How confident the classifier must be before dropping an output fragment (0–1). 0.7 means at least 70% confidence. Inherited with the whole policy object.",
107
+ }),
108
+ field(["policy", "deletableTools"], {
109
+ label: "Deletable tools →",
110
+ description:
111
+ "Select tools whose whole call may be removed after their results are judged disposable. New tools remain unchecked; unavailable selections are retained until you uncheck them. Inherited with the whole policy object.",
112
+ formatValue: (value) => `${value.length} selected`,
113
+ choiceSource: {
114
+ multiple: true,
115
+ rowLayout: "inline",
116
+ load: ({ values }) => {
117
+ const registered = getTools();
118
+ const available = new Set(registered.map((tool) => tool.name));
119
+ return [
120
+ ...registered.map((tool) => ({
121
+ value: tool.name,
122
+ label: tool.name,
123
+ badge:
124
+ tool.namespace?.name.startsWith("mcp__") ||
125
+ tool.sourceInfo.path.startsWith("builtin:mcp")
126
+ ? `MCP${tool.namespace ? ` · ${tool.namespace.name.replace(/^mcp__/u, "")}` : ""}`
127
+ : tool.sourceInfo.path.startsWith("builtin:")
128
+ ? "Pi"
129
+ : (tool.namespace?.name ?? tool.sourceInfo.source),
130
+ description: `${tool.annotations?.readOnlyHint ? "Read-only · " : ""}${tool.description}`,
131
+ })),
132
+ ...values.policy.deletableTools
133
+ .filter((name) => !available.has(name))
134
+ .map((name) => ({
135
+ value: name,
136
+ label: name,
137
+ badge: "Unavailable",
138
+ description:
139
+ "Not currently registered. Keep selected to restore this permission when the tool returns, or uncheck to remove it.",
140
+ })),
141
+ ];
142
+ },
143
+ },
144
+ }),
145
+ ],
146
+ });
147
+ }
148
+
149
+ export function createCompactionSection(
150
+ settings: CompactionSettingsView,
151
+ getTools: ExtensionAPI["getAllTools"],
152
+ ) {
153
+ return createDefinedSettingsSection(settings, createCompactionPanel(getTools));
154
+ }
@@ -0,0 +1,315 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import { contentText, type JsonObject } from "@earendil-works/pi-ai";
3
+ import type {
4
+ ExtensionContext,
5
+ SessionBeforeCompactEvent,
6
+ SessionProjection,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import type { CompactionPolicy } from "../options.ts";
9
+
10
+ export const MAX_TOOL_RESULT_CHARS = 8_000;
11
+ export const TOOL_RESULT_TRUNCATION_MARKER = "\n[pi-compaction tool result truncated]\n";
12
+ const MAX_CONTEXT_CHARS = 2_000;
13
+
14
+ export type MessageRegion = "history" | "prefix" | "retained";
15
+
16
+ export interface MessageLocation {
17
+ readonly region: MessageRegion;
18
+ readonly index: number;
19
+ readonly message: AgentMessage;
20
+ }
21
+
22
+ export interface ToolPair {
23
+ readonly id: string;
24
+ readonly toolName: string;
25
+ readonly arguments: Record<string, unknown>;
26
+ readonly call: MessageLocation;
27
+ readonly result: MessageLocation;
28
+ }
29
+
30
+ export interface ProtectedTool {
31
+ readonly id: string;
32
+ readonly reasons: readonly string[];
33
+ }
34
+
35
+ export interface ResultChunk {
36
+ readonly id: string;
37
+ readonly toolCallId: string;
38
+ readonly blockIndex: number;
39
+ readonly start: number;
40
+ readonly end: number;
41
+ readonly text: string;
42
+ }
43
+
44
+ function isSurrogatePair(left: number, right: number): boolean {
45
+ return left >= 0xd800 && left <= 0xdbff && right >= 0xdc00 && right <= 0xdfff;
46
+ }
47
+
48
+ /** Move a cut off a surrogate pair or CRLF in the given direction. */
49
+ function safeBoundary(text: string, offset: number, direction: -1 | 1): number {
50
+ const left = text.charCodeAt(offset - 1);
51
+ const right = text.charCodeAt(offset);
52
+ return isSurrogatePair(left, right) || (left === 13 && right === 10)
53
+ ? offset + direction
54
+ : offset;
55
+ }
56
+
57
+ export function truncateToolResult(message: AgentMessage): AgentMessage {
58
+ if (message.role !== "toolResult") return message;
59
+ const raw = contentText(message.content, "");
60
+ if (raw.length <= MAX_TOOL_RESULT_CHARS) return message;
61
+ const budget = MAX_TOOL_RESULT_CHARS - TOOL_RESULT_TRUNCATION_MARKER.length;
62
+ const headEnd = safeBoundary(raw, Math.ceil(budget / 2), -1);
63
+ const tailStart = safeBoundary(raw, raw.length - Math.floor(budget / 2), 1);
64
+ let offset = 0;
65
+ let marked = false;
66
+ const content = message.content.map((block) => {
67
+ if (block.type !== "text") return block;
68
+ const start = offset;
69
+ const end = start + block.text.length;
70
+ offset = end;
71
+ let text = block.text.slice(0, Math.max(0, Math.min(block.text.length, headEnd - start)));
72
+ if (end > headEnd && start < tailStart && !marked) {
73
+ text += TOOL_RESULT_TRUNCATION_MARKER;
74
+ marked = true;
75
+ }
76
+ text += block.text.slice(Math.max(0, tailStart - start));
77
+ return text === block.text ? block : { ...block, text };
78
+ });
79
+ return { ...message, content };
80
+ }
81
+
82
+ export function collectReviewInput(event: SessionBeforeCompactEvent, ctx: ExtensionContext) {
83
+ const projection = ctx.sessionManager.buildSessionProjection();
84
+ const converted = new Map<AgentMessage, AgentMessage>();
85
+ const convert = (message: AgentMessage): AgentMessage => {
86
+ if (!converted.has(message)) converted.set(message, truncateToolResult(message));
87
+ return converted.get(message)!;
88
+ };
89
+ // Pi owns message visibility and compaction boundaries; shared identities preserve entry provenance.
90
+ return {
91
+ preparation: {
92
+ ...event.preparation,
93
+ messagesToSummarize: event.preparation.messagesToSummarize.map(convert),
94
+ turnPrefixMessages: event.preparation.turnPrefixMessages.map(convert),
95
+ },
96
+ projection: {
97
+ ...projection,
98
+ messages: projection.messages.map(convert),
99
+ entries: projection.entries.map((entry) => ({
100
+ ...entry,
101
+ messages: entry.messages.map(convert),
102
+ })),
103
+ },
104
+ };
105
+ }
106
+
107
+ function assertJsonArguments(value: unknown, ancestors = new Set<object>()): void {
108
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
109
+ if (typeof value === "number" && Number.isFinite(value)) return;
110
+ if (typeof value !== "object" || value === null)
111
+ throw new Error("Tool arguments contain a non-JSON value");
112
+ if (
113
+ !Array.isArray(value) &&
114
+ Object.getPrototypeOf(value) !== Object.prototype &&
115
+ Object.getPrototypeOf(value) !== null
116
+ ) {
117
+ throw new Error("Tool arguments must use plain JSON objects");
118
+ }
119
+ if (ancestors.has(value)) throw new Error("Tool arguments contain a cycle");
120
+ ancestors.add(value);
121
+ for (const child of Array.isArray(value) ? value : Object.values(value))
122
+ assertJsonArguments(child, ancestors);
123
+ ancestors.delete(value);
124
+ }
125
+
126
+ export function indexTools(
127
+ history: readonly AgentMessage[],
128
+ prefix: readonly AgentMessage[],
129
+ projection: SessionProjection,
130
+ firstKeptEntryId: string,
131
+ policy: CompactionPolicy,
132
+ ): {
133
+ readonly pairs: readonly ToolPair[];
134
+ readonly protectedTools: readonly ProtectedTool[];
135
+ readonly locations: readonly MessageLocation[];
136
+ } {
137
+ const boundary = projection.entries.findIndex(
138
+ (entry) => entry.sourceEntry.id === firstKeptEntryId,
139
+ );
140
+ if (boundary < 0)
141
+ throw new Error(
142
+ `Retained boundary ${firstKeptEntryId} is missing from the current projection`,
143
+ );
144
+ const locations: MessageLocation[] = [];
145
+ const append = (region: MessageRegion, messages: readonly AgentMessage[]): void => {
146
+ messages.forEach((message, index) => locations.push({ region, index, message }));
147
+ };
148
+ append("history", history);
149
+ append("prefix", prefix);
150
+ append(
151
+ "retained",
152
+ projection.entries.slice(boundary).flatMap((entry) => entry.messages),
153
+ );
154
+ const calls = new Map<
155
+ string,
156
+ { location: MessageLocation; name: string; arguments: Record<string, unknown> }[]
157
+ >();
158
+ const results = new Map<string, MessageLocation[]>();
159
+ for (const location of locations) {
160
+ if (location.message.role === "assistant") {
161
+ for (const block of location.message.content) {
162
+ if (block.type !== "toolCall") continue;
163
+ if (
164
+ block.arguments === null ||
165
+ typeof block.arguments !== "object" ||
166
+ Array.isArray(block.arguments)
167
+ ) {
168
+ throw new Error("Tool arguments must be a JSON object");
169
+ }
170
+ // JSON.stringify would silently erase undefined fields or turn NaN into null, corrupting decision evidence.
171
+ assertJsonArguments(block.arguments);
172
+ const list = calls.get(block.id) ?? [];
173
+ list.push({ location, name: block.name, arguments: block.arguments });
174
+ calls.set(block.id, list);
175
+ }
176
+ } else if (location.message.role === "toolResult") {
177
+ const list = results.get(location.message.toolCallId) ?? [];
178
+ list.push(location);
179
+ results.set(location.message.toolCallId, list);
180
+ }
181
+ }
182
+ const pairs: ToolPair[] = [];
183
+ const protectedTools: ProtectedTool[] = [];
184
+ for (const id of new Set([...calls.keys(), ...results.keys()])) {
185
+ const callList = calls.get(id) ?? [];
186
+ const resultList = results.get(id) ?? [];
187
+ const call = callList[0];
188
+ const result = resultList[0];
189
+ const reasons: string[] = [];
190
+ if (!id.trim()) reasons.push("empty-id");
191
+ if (callList.length !== 1 || resultList.length !== 1)
192
+ reasons.push("unpaired-or-duplicate-id");
193
+ if (call && result) {
194
+ if (call.location.region !== result.region) reasons.push("cross-region-pair");
195
+ if (call.location.region === "retained" || result.region === "retained")
196
+ reasons.push("retained-region");
197
+ if (call.location.region === result.region && call.location.index >= result.index)
198
+ reasons.push("invalid-order");
199
+ if (result.message.role !== "toolResult")
200
+ throw new Error("Tool index contains a non-result message");
201
+ if (call.name !== result.message.toolName) reasons.push("tool-name-mismatch");
202
+ if (result.message.isError) reasons.push("error-result");
203
+ if (result.message.content.some((block) => block.type !== "text"))
204
+ reasons.push("non-text-result");
205
+ if (!policy.deletableTools.includes(call.name)) reasons.push("tool-not-deletable");
206
+ const nested = result.message.nestedCalls;
207
+ // Permission for the outer name cannot authorize nested or unrecorded operations.
208
+ if (nested && (!nested.complete || nested.calls.length > 0))
209
+ reasons.push("nested-calls");
210
+ }
211
+ if (reasons.length > 0) {
212
+ protectedTools.push({ id, reasons });
213
+ continue;
214
+ }
215
+ if (!call || !result) throw new Error(`Incomplete candidate ${id}`);
216
+ pairs.push({
217
+ id,
218
+ toolName: call.name,
219
+ arguments: call.arguments,
220
+ call: call.location,
221
+ result,
222
+ });
223
+ }
224
+ return { pairs, protectedTools, locations };
225
+ }
226
+
227
+ function safeChunkEnd(text: string, proposed: number): number {
228
+ if (proposed >= text.length) return text.length;
229
+ const left = text.charCodeAt(proposed - 1);
230
+ const right = text.charCodeAt(proposed);
231
+ return (left === 13 && right === 10) || isSurrogatePair(left, right) ? proposed - 1 : proposed;
232
+ }
233
+
234
+ /** Partition every UTF-16 position exactly once; prefer line boundaries inside the cap. */
235
+ export function splitText(
236
+ text: string,
237
+ maxChars: number,
238
+ ): readonly { start: number; end: number; text: string }[] {
239
+ if (!Number.isSafeInteger(maxChars) || maxChars < 2)
240
+ throw new Error("maxChars must be an integer of at least 2");
241
+ const pieces: { start: number; end: number; text: string }[] = [];
242
+ let start = 0;
243
+ while (start < text.length) {
244
+ let end = safeChunkEnd(text, Math.min(start + maxChars, text.length));
245
+ if (end < text.length) {
246
+ const newline = text.lastIndexOf("\n", end - 1);
247
+ if (newline >= start) end = newline + 1;
248
+ }
249
+ if (end <= start) throw new Error("Chunk partition made no progress");
250
+ pieces.push({ start, end, text: text.slice(start, end) });
251
+ start = end;
252
+ }
253
+ return pieces;
254
+ }
255
+
256
+ export function chunkResult(pair: ToolPair, maxChars: number): readonly ResultChunk[] {
257
+ const result = pair.result.message;
258
+ if (result.role !== "toolResult") throw new Error(`Candidate ${pair.id} has no result`);
259
+ return result.content.flatMap((block, blockIndex) => {
260
+ if (block.type !== "text")
261
+ throw new Error(`Candidate ${pair.id} contains non-text content`);
262
+ return splitText(block.text, maxChars).map((piece) => ({
263
+ id: `${pair.result.region}:${encodeURIComponent(pair.id)}:${blockIndex}:${piece.start}-${piece.end}`,
264
+ toolCallId: pair.id,
265
+ blockIndex,
266
+ ...piece,
267
+ }));
268
+ });
269
+ }
270
+
271
+ function excerpt(text: string, fromEnd = false): string {
272
+ const characters = Array.from(text);
273
+ return (
274
+ fromEnd ? characters.slice(-MAX_CONTEXT_CHARS) : characters.slice(0, MAX_CONTEXT_CHARS)
275
+ ).join("");
276
+ }
277
+
278
+ export function candidateContext(
279
+ pair: ToolPair,
280
+ locations: readonly MessageLocation[],
281
+ ): JsonObject {
282
+ const callPosition = locations.indexOf(pair.call);
283
+ const resultPosition = locations.indexOf(pair.result);
284
+ if (callPosition < 0 || resultPosition <= callPosition)
285
+ throw new Error(`Candidate ${pair.id} is absent from the conversation`);
286
+
287
+ let originatingRequest: string | undefined;
288
+ for (let index = callPosition - 1; index >= 0; index--) {
289
+ const message = locations[index]!.message;
290
+ if (message.role === "user") {
291
+ originatingRequest = excerpt(contentText(message.content, "\n"));
292
+ break;
293
+ }
294
+ }
295
+ const current = locations.findLast(({ message }) => message.role === "user")?.message;
296
+ const currentRequest =
297
+ current?.role === "user" ? excerpt(contentText(current.content, "\n")) : undefined;
298
+
299
+ const outcome: string[] = [];
300
+ for (let index = resultPosition + 1; index < locations.length; index++) {
301
+ const message = locations[index]!.message;
302
+ if (message.role === "user") break;
303
+ if (message.role === "assistant") {
304
+ const text = contentText(message.content, "\n");
305
+ if (text) outcome.push(text);
306
+ }
307
+ }
308
+ // Like Recap, use bounded visible text; never include thinking or subsequent tool bodies.
309
+ return {
310
+ ...(originatingRequest === undefined ? {} : { originatingRequest }),
311
+ ...(currentRequest === undefined ? {} : { currentRequest }),
312
+ toolCall: { name: pair.toolName, arguments: pair.arguments },
313
+ ...(outcome.length ? { sameTurnOutcome: excerpt(outcome.join("\n"), true) } : {}),
314
+ } as JsonObject;
315
+ }
@@ -0,0 +1,106 @@
1
+ import type { ClassifierContext, ClassifierModel, ClassifierResult } from "@earendil-works/pi-ai";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type { ModelReference } from "@lune_99/pi-lune-extensions-core/panel";
4
+
5
+ const REQUEST_CONCURRENCY = 2;
6
+
7
+ export type Classify = (
8
+ context: ClassifierContext,
9
+ signal: AbortSignal,
10
+ ) => Promise<ClassifierResult>;
11
+
12
+ /** Availability is rechecked per run so an unconfigured provider is never sent a request. */
13
+ export async function resolveClassifier(
14
+ reference: ModelReference | null,
15
+ ctx: ExtensionContext,
16
+ signal?: AbortSignal,
17
+ ): Promise<ClassifierModel<string>> {
18
+ signal?.throwIfAborted();
19
+ const models = await ctx.modelRegistry.getAvailableOfType("classifier", undefined, { signal });
20
+ signal?.throwIfAborted();
21
+ const model = reference
22
+ ? models.find((model) => model.provider === reference.provider && model.id === reference.id)
23
+ : models[0];
24
+ if (!model)
25
+ throw new Error(
26
+ reference
27
+ ? `Classifier ${reference.provider}/${reference.id} is unavailable. Configure its provider in Pi, or select Automatic in Lune settings.`
28
+ : "No classifier is available. Configure a classifier provider in Pi with /login or its environment credentials, then refresh Lune settings.",
29
+ );
30
+ return model;
31
+ }
32
+
33
+ export function isClassifierOverflow(result: ClassifierResult): boolean {
34
+ return (
35
+ result.stopReason === "error" &&
36
+ /\b(?:max_tokens_exceeded|context_length_exceeded|input_too_long|prompt_too_long)\b|maximum context length|context (?:window|length).*exceed|(?:input|prompt) is too long/iu.test(
37
+ result.errorMessage ?? "",
38
+ )
39
+ );
40
+ }
41
+
42
+ export function validateAnswers(result: ClassifierResult, context: ClassifierContext): void {
43
+ if (result.stopReason !== "stop")
44
+ throw new Error(
45
+ `Jev ${result.stopReason}: ${result.errorMessage ?? "classification did not complete"}`,
46
+ );
47
+ const expected = Object.keys(context.questions);
48
+ if (Object.keys(result.answers).some((id) => !expected.includes(id)))
49
+ throw new Error("Jev returned unknown answer IDs");
50
+ for (const id of expected) {
51
+ const answer = result.answers[id];
52
+ if (
53
+ !answer ||
54
+ answer.type !== "bool" ||
55
+ !Number.isFinite(answer.probability) ||
56
+ answer.probability < 0 ||
57
+ answer.probability > 1
58
+ ) {
59
+ throw new Error(`Jev returned an invalid probability for ${id}`);
60
+ }
61
+ }
62
+ }
63
+
64
+ /** One failed request aborts its siblings; context overflow is a result, not a failure. */
65
+ export async function runRequests(
66
+ requests: readonly ClassifierContext[],
67
+ classify: Classify,
68
+ signal: AbortSignal,
69
+ progress: (completed: number, total: number) => void,
70
+ ): Promise<readonly ClassifierResult[]> {
71
+ signal.throwIfAborted();
72
+ const cancel = new AbortController();
73
+ const requestSignal = AbortSignal.any([signal, cancel.signal]);
74
+ const results: ClassifierResult[] = new Array(requests.length);
75
+ let cursor = 0;
76
+ let completed = 0;
77
+ let failure: unknown;
78
+ progress(0, requests.length);
79
+ const worker = async (): Promise<void> => {
80
+ while (cursor < requests.length && !requestSignal.aborted) {
81
+ requestSignal.throwIfAborted();
82
+ const index = cursor++;
83
+ const request = requests[index]!;
84
+ try {
85
+ // A provider may reuse response objects across requests; validate and retain our own snapshot.
86
+ const result = structuredClone(await classify(request, requestSignal));
87
+ requestSignal.throwIfAborted();
88
+ if (!isClassifierOverflow(result)) validateAnswers(result, request);
89
+ results[index] = result;
90
+ progress(++completed, requests.length);
91
+ } catch (error) {
92
+ if (!cancel.signal.aborted) {
93
+ failure = error;
94
+ cancel.abort(error);
95
+ }
96
+ return;
97
+ }
98
+ }
99
+ };
100
+ await Promise.all(
101
+ Array.from({ length: Math.min(REQUEST_CONCURRENCY, requests.length) }, worker),
102
+ );
103
+ signal.throwIfAborted();
104
+ if (cancel.signal.aborted) throw failure;
105
+ return results;
106
+ }