pi-openai-toolkit 0.24.1 → 0.24.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/README.md +1 -1
  4. package/README.zh.md +1 -1
  5. package/config.schema.json +264 -264
  6. package/docs/configuration.md +304 -304
  7. package/docs/internals.md +3 -1
  8. package/package.json +123 -123
  9. package/src/codex-fast/extension.ts +1 -1
  10. package/src/compact-client.ts +412 -412
  11. package/src/compaction-projection.ts +35 -35
  12. package/src/config/legacy.ts +469 -469
  13. package/src/config/migration.ts +115 -115
  14. package/src/config/notifications.ts +46 -46
  15. package/src/config/policy.ts +115 -115
  16. package/src/config/v2.ts +1128 -1128
  17. package/src/config.ts +320 -320
  18. package/src/debug.ts +238 -238
  19. package/src/deferred-tool-carryover.ts +282 -282
  20. package/src/details-store.ts +151 -151
  21. package/src/extension-runtime.ts +1095 -1095
  22. package/src/image-generation/extension.ts +189 -189
  23. package/src/image-generation/protocol.ts +579 -579
  24. package/src/image-generation/types.ts +300 -300
  25. package/src/native-fallback.ts +140 -140
  26. package/src/payload-rewrite.ts +515 -515
  27. package/src/pi-context-hook.ts +117 -117
  28. package/src/remote-v2-client.ts +811 -811
  29. package/src/request-context-cache.ts +155 -155
  30. package/src/responses-headers.ts +180 -180
  31. package/src/retired-remote-windows.ts +35 -35
  32. package/src/runtime.ts +875 -875
  33. package/src/serializer.ts +883 -882
  34. package/src/supported-environment.ts +27 -27
  35. package/src/types.ts +541 -541
  36. package/src/web-search/alpha-client.ts +876 -876
  37. package/src/web-search/extension.ts +530 -530
  38. package/src/web-search/payload.ts +299 -299
  39. package/src/web-search/prompt.ts +60 -60
  40. package/src/web-search/types.ts +166 -166
  41. package/tsconfig.check.json +50 -50
@@ -1,412 +1,412 @@
1
- import { writeDebugArtifact } from "./debug";
2
- import { decodeCompactionError, readCompactionResponseText, type CompactionErrorInfo } from "./compaction-errors";
3
- import { buildResponsesRequestHeaders } from "./responses-headers";
4
- import { stripConfigurationUpdateItems } from "./remote-v2-client";
5
- import type { NativeCompactionRuntime } from "./runtime";
6
- import type { NativeCompactionRequestBody } from "./serializer";
7
- import { isCompactedWindowItem, type ArtifactContext, type CompactionConfig } from "./types";
8
-
9
- const JSON_CONTENT_TYPE = "application/json";
10
-
11
- type CompactResponseEnvelope = {
12
- id?: string;
13
- created_at?: number | string;
14
- output: unknown[];
15
- [key: string]: unknown;
16
- };
17
-
18
- export type NativeCompactionClientFailureReason =
19
- | "aborted"
20
- | "network-error"
21
- | "non-2xx"
22
- | "empty-body"
23
- | "invalid-json"
24
- | "malformed-response"
25
- | "empty-output"
26
- | "missing-compaction"
27
- | "malformed-compaction-item";
28
-
29
- export type NativeCompactionClientSuccess = {
30
- ok: true;
31
- status: number;
32
- compactedWindow: unknown[];
33
- compactResponseId?: string;
34
- createdAt?: string;
35
- /** Retained assistant text only; not a portable summary of the opaque window. */
36
- summaryText?: string;
37
- response: CompactResponseEnvelope;
38
- };
39
-
40
- export type NativeCompactionClientFailure = CompactionErrorInfo & {
41
- ok: false;
42
- reason: NativeCompactionClientFailureReason;
43
- status?: number;
44
- errorMessage?: string;
45
- responseText?: string;
46
- responseJson?: unknown;
47
- };
48
-
49
- export type NativeCompactionClientResult = NativeCompactionClientSuccess | NativeCompactionClientFailure;
50
-
51
- export type ExecuteNativeCompactionOptions = {
52
- runtime: NativeCompactionRuntime;
53
- request: NativeCompactionRequestBody;
54
- signal?: AbortSignal;
55
- settings?: CompactionConfig;
56
- context?: ArtifactContext;
57
- };
58
-
59
- function isRecord(value: unknown): value is Record<string, unknown> {
60
- return !!value && typeof value === "object" && !Array.isArray(value);
61
- }
62
-
63
- function isAbortError(error: unknown): boolean {
64
- return (
65
- (error instanceof DOMException && error.name === "AbortError") ||
66
- (error instanceof Error && (error.name === "AbortError" || error.name === "ABORT_ERR"))
67
- );
68
- }
69
-
70
- function normalizeResponseTimestamp(value: unknown): string | undefined {
71
- if (typeof value === "number" && Number.isFinite(value)) {
72
- const milliseconds = value > 1_000_000_000_000 ? value : value * 1000;
73
- return new Date(milliseconds).toISOString();
74
- }
75
-
76
- if (typeof value !== "string") {
77
- return undefined;
78
- }
79
-
80
- const trimmed = value.trim();
81
- if (!trimmed) {
82
- return undefined;
83
- }
84
-
85
- const parsed = Date.parse(trimmed);
86
- return Number.isNaN(parsed) ? trimmed : new Date(parsed).toISOString();
87
- }
88
-
89
- function isCompactResponseEnvelope(value: unknown): value is CompactResponseEnvelope {
90
- return isRecord(value) && Array.isArray(value.output) && value.output.every(isCompactedWindowItem);
91
- }
92
-
93
- /** Extract retained assistant text. It must not be used as an opaque-window summary. */
94
- export function extractCompactedSummaryText(output: readonly unknown[]): string | undefined {
95
- const texts: string[] = [];
96
- for (const item of output) {
97
- if (!isRecord(item) || item.type !== "message" || item.role !== "assistant" || !Array.isArray(item.content)) {
98
- continue;
99
- }
100
- for (const block of item.content) {
101
- if (isRecord(block) && block.type === "output_text" && typeof block.text === "string" && block.text.trim()) {
102
- texts.push(block.text.trim());
103
- }
104
- }
105
- }
106
-
107
- const joined = texts.join("\n\n").trim();
108
- return joined.length > 0 ? joined : undefined;
109
- }
110
-
111
- function toHeaders(runtime: NativeCompactionRuntime): Record<string, string> {
112
- return Object.fromEntries(
113
- buildResponsesRequestHeaders(runtime, {
114
- accept: JSON_CONTENT_TYPE,
115
- sessionId: runtime.sessionId,
116
- }).entries(),
117
- );
118
- }
119
-
120
- function writeCompactArtifact(
121
- data: unknown,
122
- settings: CompactionConfig | undefined,
123
- context: ArtifactContext | undefined,
124
- ): void {
125
- if (!settings || !context) {
126
- return;
127
- }
128
-
129
- writeDebugArtifact("compact-response", isRecord(data) ? { ...data, protocol: "standalone-compact" } : { protocol: "standalone-compact", data }, settings, context);
130
- }
131
-
132
- /** Installed SDK CompactParams allowlist; complete input makes previous_response_id unnecessary. */
133
- export function buildStandaloneCompactionRequest(request: NativeCompactionRequestBody): NativeCompactionRequestBody {
134
- const body: NativeCompactionRequestBody = {
135
- model: request.model,
136
- input: structuredClone(stripConfigurationUpdateItems(request.input)) as NativeCompactionRequestBody["input"],
137
- instructions: request.instructions,
138
- };
139
- if (["auto", "default", "fast", "flex", "priority"].includes(request.service_tier ?? "")) body.service_tier = request.service_tier;
140
- if (typeof request.prompt_cache_key === "string") body.prompt_cache_key = request.prompt_cache_key;
141
- if (request.prompt_cache_retention === "in_memory" || request.prompt_cache_retention === "24h") body.prompt_cache_retention = request.prompt_cache_retention;
142
- const cache = request.prompt_cache_options;
143
- if (isRecord(cache) && Object.keys(cache).every((key) => key === "mode" || key === "ttl") &&
144
- (cache.mode === undefined || cache.mode === "implicit" || cache.mode === "explicit") &&
145
- (cache.ttl === undefined || cache.ttl === "30m")) body.prompt_cache_options = structuredClone(cache);
146
- return body;
147
- }
148
-
149
- export async function executeNativeCompaction(
150
- options: ExecuteNativeCompactionOptions,
151
- ): Promise<NativeCompactionClientResult> {
152
- const { runtime, signal, settings, context } = options;
153
- // Same Astra-history rejection as remote v2: `/responses/compact` rejects
154
- // `configuration_update` items, so a replayed history never carries one.
155
- const request = buildStandaloneCompactionRequest(options.request);
156
- const headers = toHeaders(runtime);
157
-
158
- if (signal?.aborted) {
159
- const aborted: NativeCompactionClientFailure = {
160
- ok: false,
161
- reason: "aborted",
162
- };
163
- writeCompactArtifact(
164
- {
165
- request: {
166
- url: runtime.compactUrl,
167
- headers,
168
- body: request,
169
- },
170
- outcome: aborted,
171
- },
172
- settings,
173
- context,
174
- );
175
- return aborted;
176
- }
177
-
178
- try {
179
- const response = await fetch(runtime.compactUrl, {
180
- method: "POST",
181
- headers,
182
- body: JSON.stringify(request),
183
- redirect: "error",
184
- signal,
185
- });
186
- const responseText = await readCompactionResponseText(response, signal);
187
- const responseHeaders: Record<string, string> = {};
188
- response.headers.forEach((value, key) => {
189
- responseHeaders[key] = value;
190
- });
191
-
192
- if (!response.ok) {
193
- let responseJson: unknown;
194
- if (responseText.trim().length > 0) {
195
- try {
196
- responseJson = JSON.parse(responseText);
197
- } catch {
198
- responseJson = undefined;
199
- }
200
- }
201
-
202
- const failure: NativeCompactionClientFailure = {
203
- ok: false,
204
- reason: "non-2xx",
205
- status: response.status,
206
- ...decodeCompactionError(responseJson),
207
- responseText: responseText || undefined,
208
- responseJson,
209
- };
210
- writeCompactArtifact(
211
- {
212
- request: {
213
- url: runtime.compactUrl,
214
- headers,
215
- body: request,
216
- },
217
- response: {
218
- status: response.status,
219
- headers: responseHeaders,
220
- body: responseJson ?? responseText,
221
- },
222
- outcome: failure,
223
- },
224
- settings,
225
- context,
226
- );
227
- return failure;
228
- }
229
-
230
- if (!responseText.trim()) {
231
- const failure: NativeCompactionClientFailure = {
232
- ok: false,
233
- reason: "empty-body",
234
- status: response.status,
235
- };
236
- writeCompactArtifact(
237
- {
238
- request: {
239
- url: runtime.compactUrl,
240
- headers,
241
- body: request,
242
- },
243
- response: {
244
- status: response.status,
245
- headers: responseHeaders,
246
- body: responseText,
247
- },
248
- outcome: failure,
249
- },
250
- settings,
251
- context,
252
- );
253
- return failure;
254
- }
255
-
256
- let parsed: unknown;
257
- try {
258
- parsed = JSON.parse(responseText);
259
- } catch {
260
- const failure: NativeCompactionClientFailure = {
261
- ok: false,
262
- reason: "invalid-json",
263
- status: response.status,
264
- errorMessage: "The compact endpoint returned invalid JSON.",
265
- responseText,
266
- };
267
- writeCompactArtifact(
268
- {
269
- request: {
270
- url: runtime.compactUrl,
271
- headers,
272
- body: request,
273
- },
274
- response: {
275
- status: response.status,
276
- headers: responseHeaders,
277
- body: responseText,
278
- },
279
- outcome: failure,
280
- },
281
- settings,
282
- context,
283
- );
284
- return failure;
285
- }
286
-
287
- if (!isCompactResponseEnvelope(parsed)) {
288
- const failure: NativeCompactionClientFailure = {
289
- ok: false,
290
- reason: "malformed-response",
291
- status: response.status,
292
- responseJson: parsed,
293
- };
294
- writeCompactArtifact(
295
- {
296
- request: {
297
- url: runtime.compactUrl,
298
- headers,
299
- body: request,
300
- },
301
- response: {
302
- status: response.status,
303
- headers: responseHeaders,
304
- body: parsed,
305
- },
306
- outcome: failure,
307
- },
308
- settings,
309
- context,
310
- );
311
- return failure;
312
- }
313
-
314
- if (parsed.output.length === 0) {
315
- const failure: NativeCompactionClientFailure = {
316
- ok: false,
317
- reason: "empty-output",
318
- status: response.status,
319
- responseJson: parsed,
320
- };
321
- writeCompactArtifact(
322
- {
323
- request: {
324
- url: runtime.compactUrl,
325
- headers,
326
- body: request,
327
- },
328
- response: {
329
- status: response.status,
330
- headers: responseHeaders,
331
- body: parsed,
332
- },
333
- outcome: failure,
334
- },
335
- settings,
336
- context,
337
- );
338
- return failure;
339
- }
340
-
341
- const checkpoints = parsed.output.filter((item) => isRecord(item) && item.type === "compaction");
342
- const malformed = checkpoints.some((item) => !isRecord(item) || typeof item.encrypted_content !== "string" || !item.encrypted_content.trim());
343
- if (!checkpoints.length || malformed) {
344
- const failure: NativeCompactionClientFailure = {
345
- ok: false,
346
- reason: malformed ? "malformed-compaction-item" : "missing-compaction",
347
- status: response.status,
348
- };
349
- writeCompactArtifact({ protocol: "standalone-compact", outcome: failure }, settings, context);
350
- return failure;
351
- }
352
- if (signal?.aborted) return { ok: false, reason: "aborted" };
353
- const success: NativeCompactionClientSuccess = {
354
- ok: true,
355
- status: response.status,
356
- compactedWindow: structuredClone(parsed.output),
357
- compactResponseId: typeof parsed.id === "string" && parsed.id.trim() ? parsed.id.trim() : undefined,
358
- createdAt: normalizeResponseTimestamp(parsed.created_at),
359
- summaryText: extractCompactedSummaryText(parsed.output),
360
- response: parsed,
361
- };
362
- writeCompactArtifact(
363
- {
364
- request: {
365
- url: runtime.compactUrl,
366
- headers,
367
- body: request,
368
- },
369
- response: {
370
- status: response.status,
371
- headers: responseHeaders,
372
- body: parsed,
373
- },
374
- outcome: {
375
- ok: true,
376
- status: success.status,
377
- compactResponseId: success.compactResponseId,
378
- createdAt: success.createdAt,
379
- compactedItems: success.compactedWindow.length,
380
- },
381
- },
382
- settings,
383
- context,
384
- );
385
- return success;
386
- } catch (error) {
387
- const failure: NativeCompactionClientFailure = signal?.aborted || isAbortError(error)
388
- ? {
389
- ok: false,
390
- reason: "aborted",
391
- }
392
- : {
393
- ok: false,
394
- reason: "network-error",
395
- errorMessage: "Compaction transport failed; no remote checkpoint was produced.",
396
- };
397
-
398
- writeCompactArtifact(
399
- {
400
- request: {
401
- url: runtime.compactUrl,
402
- headers,
403
- body: request,
404
- },
405
- outcome: failure,
406
- },
407
- settings,
408
- context,
409
- );
410
- return failure;
411
- }
412
- }
1
+ import { writeDebugArtifact } from "./debug";
2
+ import { decodeCompactionError, readCompactionResponseText, type CompactionErrorInfo } from "./compaction-errors";
3
+ import { buildResponsesRequestHeaders } from "./responses-headers";
4
+ import { stripConfigurationUpdateItems } from "./remote-v2-client";
5
+ import type { NativeCompactionRuntime } from "./runtime";
6
+ import type { NativeCompactionRequestBody } from "./serializer";
7
+ import { isCompactedWindowItem, type ArtifactContext, type CompactionConfig } from "./types";
8
+
9
+ const JSON_CONTENT_TYPE = "application/json";
10
+
11
+ type CompactResponseEnvelope = {
12
+ id?: string;
13
+ created_at?: number | string;
14
+ output: unknown[];
15
+ [key: string]: unknown;
16
+ };
17
+
18
+ export type NativeCompactionClientFailureReason =
19
+ | "aborted"
20
+ | "network-error"
21
+ | "non-2xx"
22
+ | "empty-body"
23
+ | "invalid-json"
24
+ | "malformed-response"
25
+ | "empty-output"
26
+ | "missing-compaction"
27
+ | "malformed-compaction-item";
28
+
29
+ export type NativeCompactionClientSuccess = {
30
+ ok: true;
31
+ status: number;
32
+ compactedWindow: unknown[];
33
+ compactResponseId?: string;
34
+ createdAt?: string;
35
+ /** Retained assistant text only; not a portable summary of the opaque window. */
36
+ summaryText?: string;
37
+ response: CompactResponseEnvelope;
38
+ };
39
+
40
+ export type NativeCompactionClientFailure = CompactionErrorInfo & {
41
+ ok: false;
42
+ reason: NativeCompactionClientFailureReason;
43
+ status?: number;
44
+ errorMessage?: string;
45
+ responseText?: string;
46
+ responseJson?: unknown;
47
+ };
48
+
49
+ export type NativeCompactionClientResult = NativeCompactionClientSuccess | NativeCompactionClientFailure;
50
+
51
+ export type ExecuteNativeCompactionOptions = {
52
+ runtime: NativeCompactionRuntime;
53
+ request: NativeCompactionRequestBody;
54
+ signal?: AbortSignal;
55
+ settings?: CompactionConfig;
56
+ context?: ArtifactContext;
57
+ };
58
+
59
+ function isRecord(value: unknown): value is Record<string, unknown> {
60
+ return !!value && typeof value === "object" && !Array.isArray(value);
61
+ }
62
+
63
+ function isAbortError(error: unknown): boolean {
64
+ return (
65
+ (error instanceof DOMException && error.name === "AbortError") ||
66
+ (error instanceof Error && (error.name === "AbortError" || error.name === "ABORT_ERR"))
67
+ );
68
+ }
69
+
70
+ function normalizeResponseTimestamp(value: unknown): string | undefined {
71
+ if (typeof value === "number" && Number.isFinite(value)) {
72
+ const milliseconds = value > 1_000_000_000_000 ? value : value * 1000;
73
+ return new Date(milliseconds).toISOString();
74
+ }
75
+
76
+ if (typeof value !== "string") {
77
+ return undefined;
78
+ }
79
+
80
+ const trimmed = value.trim();
81
+ if (!trimmed) {
82
+ return undefined;
83
+ }
84
+
85
+ const parsed = Date.parse(trimmed);
86
+ return Number.isNaN(parsed) ? trimmed : new Date(parsed).toISOString();
87
+ }
88
+
89
+ function isCompactResponseEnvelope(value: unknown): value is CompactResponseEnvelope {
90
+ return isRecord(value) && Array.isArray(value.output) && value.output.every(isCompactedWindowItem);
91
+ }
92
+
93
+ /** Extract retained assistant text. It must not be used as an opaque-window summary. */
94
+ export function extractCompactedSummaryText(output: readonly unknown[]): string | undefined {
95
+ const texts: string[] = [];
96
+ for (const item of output) {
97
+ if (!isRecord(item) || item.type !== "message" || item.role !== "assistant" || !Array.isArray(item.content)) {
98
+ continue;
99
+ }
100
+ for (const block of item.content) {
101
+ if (isRecord(block) && block.type === "output_text" && typeof block.text === "string" && block.text.trim()) {
102
+ texts.push(block.text.trim());
103
+ }
104
+ }
105
+ }
106
+
107
+ const joined = texts.join("\n\n").trim();
108
+ return joined.length > 0 ? joined : undefined;
109
+ }
110
+
111
+ function toHeaders(runtime: NativeCompactionRuntime): Record<string, string> {
112
+ return Object.fromEntries(
113
+ buildResponsesRequestHeaders(runtime, {
114
+ accept: JSON_CONTENT_TYPE,
115
+ sessionId: runtime.sessionId,
116
+ }).entries(),
117
+ );
118
+ }
119
+
120
+ function writeCompactArtifact(
121
+ data: unknown,
122
+ settings: CompactionConfig | undefined,
123
+ context: ArtifactContext | undefined,
124
+ ): void {
125
+ if (!settings || !context) {
126
+ return;
127
+ }
128
+
129
+ writeDebugArtifact("compact-response", isRecord(data) ? { ...data, protocol: "standalone-compact" } : { protocol: "standalone-compact", data }, settings, context);
130
+ }
131
+
132
+ /** Installed SDK CompactParams allowlist; complete input makes previous_response_id unnecessary. */
133
+ export function buildStandaloneCompactionRequest(request: NativeCompactionRequestBody): NativeCompactionRequestBody {
134
+ const body: NativeCompactionRequestBody = {
135
+ model: request.model,
136
+ input: structuredClone(stripConfigurationUpdateItems(request.input)) as NativeCompactionRequestBody["input"],
137
+ instructions: request.instructions,
138
+ };
139
+ if (["auto", "default", "fast", "flex", "priority"].includes(request.service_tier ?? "")) body.service_tier = request.service_tier;
140
+ if (typeof request.prompt_cache_key === "string") body.prompt_cache_key = request.prompt_cache_key;
141
+ if (request.prompt_cache_retention === "in_memory" || request.prompt_cache_retention === "24h") body.prompt_cache_retention = request.prompt_cache_retention;
142
+ const cache = request.prompt_cache_options;
143
+ if (isRecord(cache) && Object.keys(cache).every((key) => key === "mode" || key === "ttl") &&
144
+ (cache.mode === undefined || cache.mode === "implicit" || cache.mode === "explicit") &&
145
+ (cache.ttl === undefined || cache.ttl === "30m")) body.prompt_cache_options = structuredClone(cache);
146
+ return body;
147
+ }
148
+
149
+ export async function executeNativeCompaction(
150
+ options: ExecuteNativeCompactionOptions,
151
+ ): Promise<NativeCompactionClientResult> {
152
+ const { runtime, signal, settings, context } = options;
153
+ // Same Astra-history rejection as remote v2: `/responses/compact` rejects
154
+ // `configuration_update` items, so a replayed history never carries one.
155
+ const request = buildStandaloneCompactionRequest(options.request);
156
+ const headers = toHeaders(runtime);
157
+
158
+ if (signal?.aborted) {
159
+ const aborted: NativeCompactionClientFailure = {
160
+ ok: false,
161
+ reason: "aborted",
162
+ };
163
+ writeCompactArtifact(
164
+ {
165
+ request: {
166
+ url: runtime.compactUrl,
167
+ headers,
168
+ body: request,
169
+ },
170
+ outcome: aborted,
171
+ },
172
+ settings,
173
+ context,
174
+ );
175
+ return aborted;
176
+ }
177
+
178
+ try {
179
+ const response = await fetch(runtime.compactUrl, {
180
+ method: "POST",
181
+ headers,
182
+ body: JSON.stringify(request),
183
+ redirect: "error",
184
+ signal,
185
+ });
186
+ const responseText = await readCompactionResponseText(response, signal);
187
+ const responseHeaders: Record<string, string> = {};
188
+ response.headers.forEach((value, key) => {
189
+ responseHeaders[key] = value;
190
+ });
191
+
192
+ if (!response.ok) {
193
+ let responseJson: unknown;
194
+ if (responseText.trim().length > 0) {
195
+ try {
196
+ responseJson = JSON.parse(responseText);
197
+ } catch {
198
+ responseJson = undefined;
199
+ }
200
+ }
201
+
202
+ const failure: NativeCompactionClientFailure = {
203
+ ok: false,
204
+ reason: "non-2xx",
205
+ status: response.status,
206
+ ...decodeCompactionError(responseJson),
207
+ responseText: responseText || undefined,
208
+ responseJson,
209
+ };
210
+ writeCompactArtifact(
211
+ {
212
+ request: {
213
+ url: runtime.compactUrl,
214
+ headers,
215
+ body: request,
216
+ },
217
+ response: {
218
+ status: response.status,
219
+ headers: responseHeaders,
220
+ body: responseJson ?? responseText,
221
+ },
222
+ outcome: failure,
223
+ },
224
+ settings,
225
+ context,
226
+ );
227
+ return failure;
228
+ }
229
+
230
+ if (!responseText.trim()) {
231
+ const failure: NativeCompactionClientFailure = {
232
+ ok: false,
233
+ reason: "empty-body",
234
+ status: response.status,
235
+ };
236
+ writeCompactArtifact(
237
+ {
238
+ request: {
239
+ url: runtime.compactUrl,
240
+ headers,
241
+ body: request,
242
+ },
243
+ response: {
244
+ status: response.status,
245
+ headers: responseHeaders,
246
+ body: responseText,
247
+ },
248
+ outcome: failure,
249
+ },
250
+ settings,
251
+ context,
252
+ );
253
+ return failure;
254
+ }
255
+
256
+ let parsed: unknown;
257
+ try {
258
+ parsed = JSON.parse(responseText);
259
+ } catch {
260
+ const failure: NativeCompactionClientFailure = {
261
+ ok: false,
262
+ reason: "invalid-json",
263
+ status: response.status,
264
+ errorMessage: "The compact endpoint returned invalid JSON.",
265
+ responseText,
266
+ };
267
+ writeCompactArtifact(
268
+ {
269
+ request: {
270
+ url: runtime.compactUrl,
271
+ headers,
272
+ body: request,
273
+ },
274
+ response: {
275
+ status: response.status,
276
+ headers: responseHeaders,
277
+ body: responseText,
278
+ },
279
+ outcome: failure,
280
+ },
281
+ settings,
282
+ context,
283
+ );
284
+ return failure;
285
+ }
286
+
287
+ if (!isCompactResponseEnvelope(parsed)) {
288
+ const failure: NativeCompactionClientFailure = {
289
+ ok: false,
290
+ reason: "malformed-response",
291
+ status: response.status,
292
+ responseJson: parsed,
293
+ };
294
+ writeCompactArtifact(
295
+ {
296
+ request: {
297
+ url: runtime.compactUrl,
298
+ headers,
299
+ body: request,
300
+ },
301
+ response: {
302
+ status: response.status,
303
+ headers: responseHeaders,
304
+ body: parsed,
305
+ },
306
+ outcome: failure,
307
+ },
308
+ settings,
309
+ context,
310
+ );
311
+ return failure;
312
+ }
313
+
314
+ if (parsed.output.length === 0) {
315
+ const failure: NativeCompactionClientFailure = {
316
+ ok: false,
317
+ reason: "empty-output",
318
+ status: response.status,
319
+ responseJson: parsed,
320
+ };
321
+ writeCompactArtifact(
322
+ {
323
+ request: {
324
+ url: runtime.compactUrl,
325
+ headers,
326
+ body: request,
327
+ },
328
+ response: {
329
+ status: response.status,
330
+ headers: responseHeaders,
331
+ body: parsed,
332
+ },
333
+ outcome: failure,
334
+ },
335
+ settings,
336
+ context,
337
+ );
338
+ return failure;
339
+ }
340
+
341
+ const checkpoints = parsed.output.filter((item) => isRecord(item) && item.type === "compaction");
342
+ const malformed = checkpoints.some((item) => !isRecord(item) || typeof item.encrypted_content !== "string" || !item.encrypted_content.trim());
343
+ if (!checkpoints.length || malformed) {
344
+ const failure: NativeCompactionClientFailure = {
345
+ ok: false,
346
+ reason: malformed ? "malformed-compaction-item" : "missing-compaction",
347
+ status: response.status,
348
+ };
349
+ writeCompactArtifact({ protocol: "standalone-compact", outcome: failure }, settings, context);
350
+ return failure;
351
+ }
352
+ if (signal?.aborted) return { ok: false, reason: "aborted" };
353
+ const success: NativeCompactionClientSuccess = {
354
+ ok: true,
355
+ status: response.status,
356
+ compactedWindow: structuredClone(parsed.output),
357
+ compactResponseId: typeof parsed.id === "string" && parsed.id.trim() ? parsed.id.trim() : undefined,
358
+ createdAt: normalizeResponseTimestamp(parsed.created_at),
359
+ summaryText: extractCompactedSummaryText(parsed.output),
360
+ response: parsed,
361
+ };
362
+ writeCompactArtifact(
363
+ {
364
+ request: {
365
+ url: runtime.compactUrl,
366
+ headers,
367
+ body: request,
368
+ },
369
+ response: {
370
+ status: response.status,
371
+ headers: responseHeaders,
372
+ body: parsed,
373
+ },
374
+ outcome: {
375
+ ok: true,
376
+ status: success.status,
377
+ compactResponseId: success.compactResponseId,
378
+ createdAt: success.createdAt,
379
+ compactedItems: success.compactedWindow.length,
380
+ },
381
+ },
382
+ settings,
383
+ context,
384
+ );
385
+ return success;
386
+ } catch (error) {
387
+ const failure: NativeCompactionClientFailure = signal?.aborted || isAbortError(error)
388
+ ? {
389
+ ok: false,
390
+ reason: "aborted",
391
+ }
392
+ : {
393
+ ok: false,
394
+ reason: "network-error",
395
+ errorMessage: "Compaction transport failed; no remote checkpoint was produced.",
396
+ };
397
+
398
+ writeCompactArtifact(
399
+ {
400
+ request: {
401
+ url: runtime.compactUrl,
402
+ headers,
403
+ body: request,
404
+ },
405
+ outcome: failure,
406
+ },
407
+ settings,
408
+ context,
409
+ );
410
+ return failure;
411
+ }
412
+ }