pi-roundtable-sandbox 0.42.0 → 0.44.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.
package/src/pi-broker.ts CHANGED
@@ -1,101 +1,33 @@
1
- import type { ChannelKey, Logger } from "pi-roundtable";
2
- import { HARD_COMPACT_TOKENS, scrubDiagnostic } from "pi-roundtable/kit";
1
+ import type { ChannelKey } from "pi-roundtable";
2
+ import { type BrokerListener, listenBroker } from "./broker.ts";
3
+ import { BrokerCompaction } from "./pi-broker-compaction.ts";
3
4
  import {
4
- type BrokerListener,
5
- listenBroker,
6
- type SandboxCredentialScope,
7
- } from "./broker.ts";
5
+ type PiBrokerOptions,
6
+ type PiHostContext,
7
+ validateBrokerOptions,
8
+ } from "./pi-broker-options.ts";
9
+ import { failureLog, forwardUpstream } from "./pi-broker-upstream.ts";
8
10
  import { piModelInput } from "./pi-model-input.ts";
9
11
  import {
10
12
  PI_MEDIA_LIMITS,
11
- type PiCompaction,
12
- type PiCompactionReport,
13
- type PiCompactRequest,
14
- type PiCompactResponse,
15
- type PiThinkingLevel,
16
- type PiToolResponse,
17
13
  type PiTurnRequest,
18
14
  type PiTurnResponse,
19
15
  type PiWorkerConfig,
20
16
  type PiWorkerReady,
21
- validateCompactionReport,
22
- validateCompactRequest,
23
17
  validateImages,
24
18
  validateReplyFiles,
25
19
  } from "./pi-protocol.ts";
26
20
  import { boundedText, isRecord } from "./protocol.ts";
27
21
 
28
- export interface PiHostContext {
29
- channel: ChannelKey;
30
- profile: string;
31
- speaker: { id: string; name: string; principalId?: string };
32
- /** The host-judged level for this turn; the worker can request less but never more. */
33
- thinking: PiThinkingLevel;
34
- signal: AbortSignal;
35
- /** When the turn must end, in epoch milliseconds; a host compactor gets at most half the time left. */
36
- deadline?: number;
37
- }
38
- export interface PiMcpServer {
39
- name: string;
40
- url: string;
41
- tools: readonly string[];
42
- }
43
- /** Defaults for a host compactor's limits. */
44
- export const PI_COMPACT_LIMITS = {
45
- /** A larger compact request falls back to Pi's summary unread. */
46
- requestBytes: 32 * 1024 * 1024,
47
- /** A compactor still running after this falls back to Pi's summary. */
48
- timeoutMs: 120_000,
49
- /** Compact requests one turn may make; the rest fall back to Pi's summary. */
50
- compactsPerTurn: 3,
51
- /** Compaction reports one turn may send. */
52
- reportsPerTurn: 16,
53
- } as const;
54
- /** Compacts a sandbox session on the host, with what the worker cannot reach (a remote service, say). */
55
- export interface PiCompactor {
56
- /** The `engine` this compactor's compactions record in their details; the broker stamps it. */
57
- engine: string;
58
- /** A compaction, or undefined to leave it to Pi's own summary. A throw also falls back. */
59
- compact(
60
- request: PiCompactRequest,
61
- context: { channel: ChannelKey; signal: AbortSignal },
62
- ): Promise<PiCompaction | undefined>;
63
- /** Longest a compaction may take before Pi's summary runs instead (default 120 seconds). */
64
- timeoutMs?: number;
65
- /** Largest request accepted, in bytes (default 32 MiB); a larger one falls back to Pi's summary. */
66
- maxRequestBytes?: number;
67
- }
68
- export interface PiBrokerOptions {
69
- model: string;
70
- /** Actual configured image, named in capability failures so the operator can rebuild it. */
71
- workerImage?: string;
72
- /** Host-only, read before each model call for its channel and speaker; a zero-argument function still works. Return `undefined` or an empty string when the scope has no token: the call fails rather than using another credential. Never sent to the worker. */
73
- oauthToken: (
74
- scope: SandboxCredentialScope,
75
- ) => string | undefined | Promise<string | undefined>;
76
- tools?: {
77
- names: readonly string[];
78
- call(
79
- name: string,
80
- input: Record<string, unknown>,
81
- context: PiHostContext,
82
- ): Promise<PiToolResponse>;
83
- };
84
- mcp?: {
85
- servers: readonly PiMcpServer[];
86
- token: () => string | Promise<string>;
87
- };
88
- upstream?: string;
89
- fetchImpl?: (url: string, init: RequestInit) => Promise<Response>;
90
- maxCalls?: number;
91
- maxOutputTokens?: number;
92
- /** Trusted endpoints can use HTTP only for explicitly configured local MCP. */
93
- allowHttpMcp?: boolean;
94
- /** Host-side compaction; without it the worker compacts with Pi's summary alone. */
95
- compaction?: PiCompactor;
96
- /** Receives upstream failures and the worker's compactions, per channel. */
97
- logger?: Logger;
98
- }
22
+ export {
23
+ PI_COMPACT_LIMITS,
24
+ type PiBrokerOptions,
25
+ type PiCompactor,
26
+ type PiHostContext,
27
+ type PiMcpServer,
28
+ } from "./pi-broker-options.ts";
29
+ export { errorText } from "./pi-broker-upstream.ts";
30
+
99
31
  const MODEL_PATHS = new Set([
100
32
  "/anthropic/v1/messages",
101
33
  "/anthropic/v1/messages/count_tokens",
@@ -108,182 +40,10 @@ const HEADERS = [
108
40
  "user-agent",
109
41
  "x-app",
110
42
  ];
111
- const RESPONSE_HEADERS = ["content-type", "request-id", "x-should-retry"];
112
- /** Headers the worker's client uses to back off or recover; each value is short and checked. */
113
- function passthroughHeader(name: string): boolean {
114
- return (
115
- name === "retry-after" ||
116
- name.startsWith("anthropic-ratelimit-") ||
117
- RESPONSE_HEADERS.includes(name)
118
- );
119
- }
120
- /** An error's name, message and cause chain, for a log line. */
121
- export function errorText(error: unknown): string {
122
- if (!(error instanceof Error)) return String(error);
123
- const text = `${error.name}: ${error.message}`;
124
- return error.cause === undefined
125
- ? text
126
- : `${text} (cause: ${errorText(error.cause)})`;
127
- }
128
- function endpoint(raw: string, allowHttp = false): URL {
129
- // pi-lens-ignore: unchecked-throwing-call -- invalid trusted endpoint configuration must fail startup.
130
- const url = new URL(raw);
131
- if (
132
- !(url.protocol === "https:" || (allowHttp && url.protocol === "http:")) ||
133
- url.username ||
134
- url.password ||
135
- url.hash ||
136
- url.search
137
- )
138
- throw new Error("Invalid trusted endpoint");
139
- return url;
140
- }
141
- /**
142
- * Watches a server-sent event stream as it passes and reports its first `error` event: an
143
- * upstream can fail mid-answer after a 200, which the status alone never shows.
144
- */
145
- function sseErrorWatcher(
146
- onError: (data: string) => void,
147
- ): (chunk: Uint8Array, done: boolean) => void {
148
- const decoder = new TextDecoder();
149
- let pending = "";
150
- let reported = false;
151
- const scan = (event: string) => {
152
- const lines = event.split(/\r?\n/);
153
- const type = lines
154
- .find((line) => line.startsWith("event:"))
155
- ?.slice(6)
156
- .trim();
157
- const data = lines
158
- .filter((line) => line.startsWith("data:"))
159
- .map((line) => line.slice(5).replace(/^ /, ""))
160
- .join("\n");
161
- let typed: unknown;
162
- try {
163
- typed = JSON.parse(data);
164
- } catch {
165
- typed = undefined;
166
- }
167
- if (type === "error" || (isRecord(typed) && typed.type === "error")) {
168
- reported = true;
169
- onError(data);
170
- }
171
- };
172
- return (chunk, done) => {
173
- if (reported) return;
174
- pending += decoder.decode(chunk, { stream: !done });
175
- const events = pending.split(/\r?\n\r?\n/);
176
- pending = done ? "" : (events.pop() ?? "");
177
- // An event this long is no error report; keep scanning without holding it.
178
- if (pending.length > 64 * 1024) pending = "";
179
- for (const event of events) if (!reported) scan(event);
180
- };
181
- }
182
-
183
- function streamBounded(
184
- response: Response,
185
- signal: AbortSignal,
186
- maxBytes: number,
187
- secret: string,
188
- onFailure: (error: unknown) => void,
189
- watch?: (chunk: Uint8Array, done: boolean) => void,
190
- ): ReadableStream<Uint8Array> {
191
- const reader = response.body?.getReader();
192
- let total = 0;
193
- let carry = Buffer.alloc(0);
194
- const variants = [
195
- secret,
196
- encodeURIComponent(secret),
197
- Buffer.from(secret).toString("base64"),
198
- Buffer.from(secret).toString("base64url"),
199
- Buffer.from(secret).toString("hex"),
200
- ]
201
- .filter(Boolean)
202
- .map((s) => Buffer.from(s));
203
- const tail = Math.max(0, ...variants.map((s) => s.length)) - 1;
204
- return new ReadableStream({
205
- async pull(controller) {
206
- try {
207
- signal.throwIfAborted();
208
- const result = await reader?.read();
209
- const data = Buffer.concat([carry, result?.value ?? new Uint8Array()]);
210
- if (variants.some((s) => data.includes(s)))
211
- throw new Error("Credential reflected");
212
- total += result?.value?.byteLength ?? 0;
213
- if (total > maxBytes) throw new Error("Response too large");
214
- watch?.(result?.value ?? new Uint8Array(), !result || result.done);
215
- if (!result || result.done) {
216
- if (data.length) controller.enqueue(data);
217
- controller.close();
218
- return;
219
- }
220
- const cut = Math.max(0, data.length - tail);
221
- if (cut) controller.enqueue(data.subarray(0, cut));
222
- carry = data.subarray(cut);
223
- } catch (error) {
224
- onFailure(error);
225
- await reader?.cancel().catch(() => {});
226
- controller.error(new Error("Broker response failed"));
227
- }
228
- },
229
- cancel: () => reader?.cancel(),
230
- });
231
- }
232
-
233
- /** At most `limit` bytes of a body as text; the rest is cancelled, never read. */
234
- async function bodyHead(
235
- body: ReadableStream<Uint8Array>,
236
- limit: number,
237
- ): Promise<string> {
238
- const reader = body.getReader();
239
- const chunks: Uint8Array[] = [];
240
- let size = 0;
241
- try {
242
- while (size < limit) {
243
- const { done, value } = await reader.read();
244
- if (done) break;
245
- chunks.push(value);
246
- size += value.byteLength;
247
- }
248
- } catch {
249
- // The worker's branch reports a broken stream; the log keeps what arrived.
250
- } finally {
251
- await reader.cancel().catch(() => {});
252
- }
253
- return Buffer.concat(chunks).subarray(0, limit).toString("utf8");
254
- }
255
- /** A credential as it may appear in text: raw, URL-encoded, base64 and hex. */
256
- function secretForms(secret: string): string[] {
257
- if (!secret) return [];
258
- return [
259
- secret,
260
- encodeURIComponent(secret),
261
- Buffer.from(secret).toString("base64"),
262
- Buffer.from(secret).toString("base64url"),
263
- Buffer.from(secret).toString("hex"),
264
- ];
265
- }
266
- /** A compactor's answer, or a rejection once the signal aborts, even if the compactor ignores it. */
267
- function abortableCompact<T>(
268
- promise: Promise<T>,
269
- signal: AbortSignal,
270
- ): Promise<T> {
271
- return new Promise((resolve, reject) => {
272
- const abort = () => reject(signal.reason);
273
- if (signal.aborted) {
274
- abort();
275
- return;
276
- }
277
- signal.addEventListener("abort", abort, { once: true });
278
- promise
279
- .then(resolve, reject)
280
- .finally(() => signal.removeEventListener("abort", abort));
281
- });
282
- }
283
-
284
43
  /** Explicit subscription mode. A broker is idle except while the host binds one admitted turn. */
285
44
  export class PiSandboxBroker {
286
45
  readonly #options: PiBrokerOptions;
46
+ readonly #compaction: BrokerCompaction;
287
47
  #ready = false;
288
48
  #capabilities: NonNullable<PiWorkerReady["capabilities"]> = {};
289
49
  #requiresPrivacy = false;
@@ -514,42 +274,9 @@ export class PiSandboxBroker {
514
274
  };
515
275
  }
516
276
  constructor(options: PiBrokerOptions) {
517
- endpoint(options.upstream ?? "https://api.anthropic.com");
518
- for (const server of options.mcp?.servers ?? []) {
519
- endpoint(server.url, options.allowHttpMcp);
520
- if (!/^[a-zA-Z0-9_-]{1,100}$/.test(server.name))
521
- throw new Error("Invalid MCP server name");
522
- }
523
- if (
524
- !Number.isSafeInteger(options.maxCalls ?? 128) ||
525
- (options.maxCalls ?? 128) < 1 ||
526
- (options.maxCalls ?? 128) > 1000
527
- )
528
- throw new Error("Invalid broker budget");
529
- const compaction = options.compaction;
530
- if (
531
- compaction &&
532
- (!/^[a-zA-Z0-9@/._-]{1,100}$/.test(compaction.engine) ||
533
- !Number.isSafeInteger(
534
- compaction.timeoutMs ?? PI_COMPACT_LIMITS.timeoutMs,
535
- ) ||
536
- (compaction.timeoutMs ?? PI_COMPACT_LIMITS.timeoutMs) < 1000 ||
537
- (compaction.timeoutMs ?? PI_COMPACT_LIMITS.timeoutMs) > 600_000 ||
538
- !Number.isSafeInteger(
539
- compaction.maxRequestBytes ?? PI_COMPACT_LIMITS.requestBytes,
540
- ) ||
541
- (compaction.maxRequestBytes ?? PI_COMPACT_LIMITS.requestBytes) < 1 ||
542
- (compaction.maxRequestBytes ?? PI_COMPACT_LIMITS.requestBytes) >
543
- 96 * 1024 * 1024)
544
- )
545
- throw new Error("Invalid compactor");
546
- if (
547
- !Number.isSafeInteger(options.maxOutputTokens ?? 128_000) ||
548
- (options.maxOutputTokens ?? 128_000) < 1025 ||
549
- (options.maxOutputTokens ?? 128_000) > 200_000
550
- )
551
- throw new Error("Invalid output-token budget");
277
+ validateBrokerOptions(options);
552
278
  this.#options = options;
279
+ this.#compaction = new BrokerCompaction(options);
553
280
  }
554
281
  bind(context: PiHostContext): () => void {
555
282
  if (this.#turn) throw new Error("Broker turn already active");
@@ -596,7 +323,7 @@ export class PiSandboxBroker {
596
323
  url.pathname === "/compaction/report") &&
597
324
  !url.search
598
325
  )
599
- return this.#compaction(request, url.pathname);
326
+ return this.#compaction.handle(request, url.pathname, this.#turn);
600
327
  const startup = !this.#turn;
601
328
  const turn = this.#turn ?? this.#startup;
602
329
  if (
@@ -633,7 +360,8 @@ export class PiSandboxBroker {
633
360
  turn.active++;
634
361
  // The turn signal carries the deadline: a long generation or image call must not be cut shorter.
635
362
  const signal = AbortSignal.any([turn.context.signal, request.signal]);
636
- const failed = this.#failureLog(
363
+ const failed = failureLog(
364
+ this.#options.logger,
637
365
  turn.context.channel,
638
366
  toolName ? `tool:${toolName}` : server ? `mcp:${server.name}` : "model",
639
367
  );
@@ -751,66 +479,16 @@ export class PiSandboxBroker {
751
479
  }
752
480
  if (!secret) throw new Error("Credential unavailable");
753
481
  headers.set("authorization", `Bearer ${secret}`);
754
- const upstream = await (this.#options.fetchImpl ?? fetch)(target, {
755
- method: "POST",
756
- redirect: "error",
482
+ return await forwardUpstream({
483
+ fetchImpl: this.#options.fetchImpl ?? fetch,
484
+ target,
757
485
  headers,
758
- body: JSON.stringify(body),
486
+ body,
759
487
  signal,
488
+ secret,
489
+ isMcp: server !== undefined,
490
+ failed,
760
491
  });
761
- // Errors keep their status, body and back-off headers so the worker can recognize an
762
- // oversized context, a rate limit or an expired MCP session; the same scans apply.
763
- const outgoing = new Headers();
764
- for (const [name, value] of upstream.headers) {
765
- if (
766
- passthroughHeader(name) &&
767
- value.length <= 256 &&
768
- !value.includes(secret)
769
- )
770
- outgoing.set(name, value);
771
- }
772
- if (server) {
773
- const id = upstream.headers.get("mcp-session-id");
774
- if (id && !id.includes(secret) && id.length <= 256)
775
- outgoing.set("mcp-session-id", id);
776
- }
777
- if (upstream.status < 200 || upstream.status > 599) {
778
- failed(secret, { status: upstream.status });
779
- return new Response("Upstream refused", { status: 502 });
780
- }
781
- let answer = upstream;
782
- if (upstream.status >= 400 && upstream.body) {
783
- // The log reads the error body's head from one branch; the worker gets all of it from the other.
784
- const [logged, sent] = upstream.body.tee();
785
- void bodyHead(logged, 64 * 1024).then((body) =>
786
- failed(secret, { status: upstream.status, body }),
787
- );
788
- answer = new Response(sent, { status: upstream.status });
789
- } else if (upstream.status >= 400)
790
- failed(secret, { status: upstream.status });
791
- return new Response(
792
- upstream.status === 204 || upstream.status === 205
793
- ? null
794
- : streamBounded(
795
- answer,
796
- signal,
797
- PI_MEDIA_LIMITS.totalFileBytes,
798
- secret,
799
- (error) => failed(secret, { status: upstream.status, error }),
800
- upstream.status < 400 &&
801
- (upstream.headers.get("content-type") ?? "").includes(
802
- "text/event-stream",
803
- )
804
- ? sseErrorWatcher((body) =>
805
- failed(secret, {
806
- status: upstream.status,
807
- body: `stream error event: ${body}`,
808
- }),
809
- )
810
- : undefined,
811
- ),
812
- { headers: outgoing, status: upstream.status },
813
- );
814
492
  } catch (error) {
815
493
  failed(secret, { error });
816
494
  return new Response("Broker call failed", { status: 502 });
@@ -818,218 +496,4 @@ export class PiSandboxBroker {
818
496
  turn.active--;
819
497
  }
820
498
  }
821
- /** Logs a failed upstream call with its latency; the body and error lose any credential. */
822
- #failureLog(channel: ChannelKey, upstream: string) {
823
- const started = Date.now();
824
- return (
825
- secret: string,
826
- failure: { status?: number; body?: string; error?: unknown },
827
- ): void => {
828
- const clean = (text: string) =>
829
- scrubDiagnostic(
830
- secretForms(secret).reduce(
831
- (masked, form) => masked.replaceAll(form, "[redacted]"),
832
- text,
833
- ),
834
- 2000,
835
- );
836
- this.#options.logger?.warn(
837
- {
838
- channel,
839
- upstream,
840
- ...(failure.status === undefined ? {} : { status: failure.status }),
841
- latencyMs: Date.now() - started,
842
- ...(failure.body === undefined ? {} : { body: clean(failure.body) }),
843
- ...(failure.error === undefined
844
- ? {}
845
- : { error: clean(errorText(failure.error)) }),
846
- },
847
- "sandbox upstream call failed",
848
- );
849
- };
850
- }
851
- /** Settles when the running compactor really ends, even after its request fell back. */
852
- #compacting: Promise<unknown> | undefined;
853
- readonly #compactionUse = new WeakMap<
854
- object,
855
- { compacts: number; reports: number }
856
- >();
857
- /** The worker's compactions, only inside an admitted turn: a host compaction, or a report to log. */
858
- async #compaction(request: Request, path: string): Promise<Response> {
859
- const turn = this.#turn;
860
- if (request.method !== "POST")
861
- return new Response("Not found", { status: 404 });
862
- if (!turn || turn.context.signal.aborted)
863
- return new Response("Turn ended", { status: 410 });
864
- const { channel } = turn.context;
865
- const logger = this.#options.logger;
866
- const use = this.#compactionUse.get(turn) ?? { compacts: 0, reports: 0 };
867
- this.#compactionUse.set(turn, use);
868
- if (path === "/compaction/report") {
869
- // A turn compacts a few times at most; more reports only fill the host's log.
870
- if (++use.reports > PI_COMPACT_LIMITS.reportsPerTurn)
871
- return new Response("Report budget exhausted", { status: 429 });
872
- try {
873
- const report: unknown = JSON.parse(
874
- await boundedText(request.body, 64 * 1024, turn.context.signal),
875
- );
876
- validateCompactionReport(report);
877
- this.#logReport(channel, report);
878
- return new Response("Accepted");
879
- } catch {
880
- return new Response("Invalid report", { status: 400 });
881
- }
882
- }
883
- const compactor = this.#options.compaction;
884
- const fallback = (reason: string): Response => {
885
- logger?.warn(
886
- { channel, engine: compactor?.engine, fallback: reason },
887
- "compaction falls back to Pi's summary",
888
- );
889
- return Response.json({
890
- ok: false,
891
- fallback: reason,
892
- } satisfies PiCompactResponse);
893
- };
894
- if (!compactor) return fallback("the host has no compactor");
895
- if (this.#compacting) return fallback("a compaction is already running");
896
- if (++use.compacts > PI_COMPACT_LIMITS.compactsPerTurn)
897
- return fallback(
898
- `the turn already asked for ${PI_COMPACT_LIMITS.compactsPerTurn} compactions`,
899
- );
900
- const maxBytes =
901
- compactor.maxRequestBytes ?? PI_COMPACT_LIMITS.requestBytes;
902
- if (Number(request.headers.get("content-length") ?? 0) > maxBytes)
903
- return fallback(`the request is over ${maxBytes} bytes`);
904
- // Pi's own summary must still fit after a compactor that runs out of time.
905
- const left =
906
- turn.context.deadline === undefined
907
- ? Number.POSITIVE_INFINITY
908
- : turn.context.deadline - Date.now();
909
- const timeoutMs = Math.min(
910
- compactor.timeoutMs ?? PI_COMPACT_LIMITS.timeoutMs,
911
- Math.floor(left / 2),
912
- );
913
- if (timeoutMs < 1000)
914
- return fallback(
915
- "the turn has too little time left for the host compactor",
916
- );
917
- let running: Promise<unknown> = Promise.resolve();
918
- this.#compacting = running;
919
- const timeout = AbortSignal.timeout(timeoutMs);
920
- const signal = AbortSignal.any([
921
- turn.context.signal,
922
- request.signal,
923
- timeout,
924
- ]);
925
- const started = Date.now();
926
- try {
927
- let compactRequest: unknown;
928
- try {
929
- compactRequest = JSON.parse(
930
- await boundedText(request.body, maxBytes, signal),
931
- );
932
- validateCompactRequest(compactRequest);
933
- } catch (error) {
934
- if (signal.aborted) throw error;
935
- return fallback(
936
- error instanceof Error && error.message === "body too large"
937
- ? `the request is over ${maxBytes} bytes`
938
- : "the request is invalid",
939
- );
940
- }
941
- const compacting = compactor.compact(compactRequest, { channel, signal });
942
- running = compacting.catch(() => {});
943
- this.#compacting = running;
944
- const result = await abortableCompact(compacting, signal);
945
- if (!result) return fallback("the compactor declined");
946
- const details =
947
- result.details === undefined
948
- ? { engine: compactor.engine }
949
- : isRecord(result.details)
950
- ? { ...result.details, engine: compactor.engine }
951
- : undefined;
952
- if (
953
- !details ||
954
- typeof result.summary !== "string" ||
955
- result.summary.length === 0 ||
956
- result.firstKeptEntryId !== compactRequest.firstKeptEntryId ||
957
- !Number.isSafeInteger(result.tokensBefore) ||
958
- (result.estimatedTokensAfter !== undefined &&
959
- !Number.isSafeInteger(result.estimatedTokensAfter))
960
- )
961
- return fallback("the compactor's result is invalid");
962
- logger?.info(
963
- {
964
- channel,
965
- engine: compactor.engine,
966
- tokensBefore: result.tokensBefore,
967
- tokensAfter: result.estimatedTokensAfter,
968
- latencyMs: Date.now() - started,
969
- },
970
- "host compactor answered",
971
- );
972
- return Response.json({
973
- ok: true,
974
- compaction: {
975
- summary: result.summary,
976
- firstKeptEntryId: result.firstKeptEntryId,
977
- tokensBefore: result.tokensBefore,
978
- ...(result.estimatedTokensAfter === undefined
979
- ? {}
980
- : { estimatedTokensAfter: result.estimatedTokensAfter }),
981
- details,
982
- },
983
- } satisfies PiCompactResponse);
984
- } catch (error) {
985
- return fallback(
986
- timeout.aborted
987
- ? `the compactor took over ${timeoutMs} ms`
988
- : signal.aborted
989
- ? "the compaction was aborted"
990
- : `the compactor failed: ${scrubDiagnostic(errorText(error), 2000)}`,
991
- );
992
- } finally {
993
- // A compactor that ignored its signal still holds the slot until it really ends.
994
- void running.then(() => {
995
- if (this.#compacting === running) this.#compacting = undefined;
996
- });
997
- }
998
- }
999
- /** Logs a worker compaction the way the host logs its own sessions' compactions. */
1000
- #logReport(channel: ChannelKey, report: PiCompactionReport): void {
1001
- const logger = this.#options.logger;
1002
- if (report.type === "bypass") {
1003
- logger?.info(
1004
- {
1005
- channel,
1006
- reason: report.reason,
1007
- tokensBefore: report.tokensBefore,
1008
- ceiling: HARD_COMPACT_TOKENS,
1009
- },
1010
- "compaction skips the extension for Pi's summary",
1011
- );
1012
- return;
1013
- }
1014
- const trigger = report.reason === "manual" ? "self" : report.reason;
1015
- if (!report.engine) {
1016
- logger?.warn(
1017
- { channel, trigger, aborted: report.aborted, error: report.error },
1018
- "compaction failed",
1019
- );
1020
- return;
1021
- }
1022
- logger?.info(
1023
- {
1024
- channel,
1025
- trigger,
1026
- engine: report.engine,
1027
- tokensBefore: report.tokensBefore,
1028
- tokensAfter: report.tokensAfter,
1029
- contextAfter: report.contextAfter,
1030
- nextCompactionAt: report.nextCompactionAt,
1031
- },
1032
- "conversation compacted",
1033
- );
1034
- }
1035
499
  }