pi-openai-toolkit 0.20.8 → 0.21.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.
Files changed (54) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/README.md +8 -26
  4. package/README.zh.md +8 -26
  5. package/config.schema.json +278 -366
  6. package/docs/configuration.md +294 -310
  7. package/docs/internals.md +166 -175
  8. package/package.json +3 -13
  9. package/src/compact-client.ts +412 -389
  10. package/src/compaction-errors.ts +96 -0
  11. package/src/compaction-projection.ts +35 -35
  12. package/src/config/legacy.ts +519 -717
  13. package/src/config/migration.ts +103 -100
  14. package/src/config/notifications.ts +36 -28
  15. package/src/config/policy.ts +10 -18
  16. package/src/config/v2.ts +1167 -1380
  17. package/src/config.ts +310 -319
  18. package/src/context-management/codex-provider.ts +270 -270
  19. package/src/context-management/history-notes.ts +357 -357
  20. package/src/context-management/manual-compact.ts +0 -11
  21. package/src/context-management/tools.ts +371 -371
  22. package/src/context-management/types.ts +168 -168
  23. package/src/context-management/window-manager.ts +801 -801
  24. package/src/debug.ts +238 -237
  25. package/src/deferred-tool-carryover.ts +282 -282
  26. package/src/details-store.ts +151 -151
  27. package/src/extension-runtime.ts +1662 -1616
  28. package/src/image-generation/extension.ts +189 -189
  29. package/src/image-generation/protocol.ts +579 -579
  30. package/src/image-generation/types.ts +300 -300
  31. package/src/payload-rewrite.ts +515 -518
  32. package/src/pi-context-hook.ts +117 -117
  33. package/src/remote-v2-client.ts +811 -814
  34. package/src/request-context-cache.ts +155 -155
  35. package/src/responses-headers.ts +180 -180
  36. package/src/runtime.ts +865 -832
  37. package/src/serializer.ts +882 -882
  38. package/src/supported-environment.ts +27 -27
  39. package/src/types.ts +565 -648
  40. package/src/web-search/alpha-client.ts +876 -876
  41. package/src/web-search/extension.ts +530 -530
  42. package/src/web-search/payload.ts +299 -299
  43. package/src/web-search/prompt.ts +60 -60
  44. package/src/web-search/types.ts +166 -166
  45. package/tsconfig.check.json +50 -54
  46. package/src/auto-mode/classifier.ts +0 -161
  47. package/src/auto-mode/extension.ts +0 -691
  48. package/src/auto-mode/model-selection-guard.ts +0 -52
  49. package/src/auto-mode/policy.ts +0 -146
  50. package/src/auto-mode/prompt.ts +0 -279
  51. package/src/auto-mode/reviewer.ts +0 -325
  52. package/src/auto-mode/tool-review-tui.ts +0 -211
  53. package/src/auto-mode/transcript.ts +0 -135
  54. package/src/auto-mode/types.ts +0 -137
@@ -1,389 +1,412 @@
1
- import { writeDebugArtifact } from "./debug";
2
- import { buildResponsesRequestHeaders } from "./responses-headers";
3
- import { stripConfigurationUpdateItems } from "./remote-v2-client";
4
- import type { NativeCompactionRuntime } from "./runtime";
5
- import type { NativeCompactionRequestBody } from "./serializer";
6
- import type { ArtifactContext, CompactionConfig } from "./types";
7
-
8
- const JSON_CONTENT_TYPE = "application/json";
9
-
10
- type CompactResponseEnvelope = {
11
- id?: string;
12
- created_at?: number | string;
13
- output: unknown[];
14
- [key: string]: unknown;
15
- };
16
-
17
- export type NativeCompactionClientFailureReason =
18
- | "aborted"
19
- | "network-error"
20
- | "non-2xx"
21
- | "empty-body"
22
- | "invalid-json"
23
- | "malformed-response"
24
- | "empty-output";
25
-
26
- export type NativeCompactionClientSuccess = {
27
- ok: true;
28
- status: number;
29
- compactedWindow: unknown[];
30
- compactResponseId?: string;
31
- createdAt?: string;
32
- /** Assistant summary text extracted from the compact output, for CompactionEntry.summary. */
33
- summaryText?: string;
34
- response: CompactResponseEnvelope;
35
- };
36
-
37
- export type NativeCompactionClientFailure = {
38
- ok: false;
39
- reason: NativeCompactionClientFailureReason;
40
- status?: number;
41
- errorMessage?: string;
42
- responseText?: string;
43
- responseJson?: unknown;
44
- };
45
-
46
- export type NativeCompactionClientResult = NativeCompactionClientSuccess | NativeCompactionClientFailure;
47
-
48
- export type ExecuteNativeCompactionOptions = {
49
- runtime: NativeCompactionRuntime;
50
- request: NativeCompactionRequestBody;
51
- signal?: AbortSignal;
52
- settings?: CompactionConfig;
53
- context?: ArtifactContext;
54
- };
55
-
56
- function isRecord(value: unknown): value is Record<string, unknown> {
57
- return !!value && typeof value === "object" && !Array.isArray(value);
58
- }
59
-
60
- function isAbortError(error: unknown): boolean {
61
- return (
62
- (error instanceof DOMException && error.name === "AbortError") ||
63
- (error instanceof Error && (error.name === "AbortError" || error.name === "ABORT_ERR"))
64
- );
65
- }
66
-
67
- function normalizeResponseTimestamp(value: unknown): string | undefined {
68
- if (typeof value === "number" && Number.isFinite(value)) {
69
- const milliseconds = value > 1_000_000_000_000 ? value : value * 1000;
70
- return new Date(milliseconds).toISOString();
71
- }
72
-
73
- if (typeof value !== "string") {
74
- return undefined;
75
- }
76
-
77
- const trimmed = value.trim();
78
- if (!trimmed) {
79
- return undefined;
80
- }
81
-
82
- const parsed = Date.parse(trimmed);
83
- return Number.isNaN(parsed) ? trimmed : new Date(parsed).toISOString();
84
- }
85
-
86
- function isCompactOutputItem(value: unknown): value is Record<string, unknown> {
87
- return isRecord(value);
88
- }
89
-
90
- function isCompactResponseEnvelope(value: unknown): value is CompactResponseEnvelope {
91
- return isRecord(value) && Array.isArray(value.output) && value.output.every(isCompactOutputItem);
92
- }
93
-
94
- /**
95
- * Extract the assistant-authored summary text from the compacted window so the
96
- * persisted CompactionEntry.summary carries real context. Without this, switching
97
- * to a non-Responses model later would replay a meaningless placeholder.
98
- */
99
- export function extractCompactedSummaryText(output: readonly unknown[]): string | undefined {
100
- const texts: string[] = [];
101
- for (const item of output) {
102
- if (!isRecord(item) || item.type !== "message" || item.role !== "assistant" || !Array.isArray(item.content)) {
103
- continue;
104
- }
105
- for (const block of item.content) {
106
- if (isRecord(block) && block.type === "output_text" && typeof block.text === "string" && block.text.trim()) {
107
- texts.push(block.text.trim());
108
- }
109
- }
110
- }
111
-
112
- const joined = texts.join("\n\n").trim();
113
- return joined.length > 0 ? joined : undefined;
114
- }
115
-
116
- function toHeaders(runtime: NativeCompactionRuntime): Record<string, string> {
117
- return Object.fromEntries(
118
- buildResponsesRequestHeaders(runtime, {
119
- accept: JSON_CONTENT_TYPE,
120
- sessionId: runtime.sessionId,
121
- }).entries(),
122
- );
123
- }
124
-
125
- function writeCompactArtifact(
126
- data: unknown,
127
- settings: CompactionConfig | undefined,
128
- context: ArtifactContext | undefined,
129
- ): void {
130
- if (!settings || !context) {
131
- return;
132
- }
133
-
134
- writeDebugArtifact("compact-response", data, settings, context);
135
- }
136
-
137
- export async function executeNativeCompaction(
138
- options: ExecuteNativeCompactionOptions,
139
- ): Promise<NativeCompactionClientResult> {
140
- const { runtime, signal, settings, context } = options;
141
- // Same Astra-history rejection as remote v2: `/responses/compact` rejects
142
- // `configuration_update` items, so a replayed history never carries one.
143
- const request: NativeCompactionRequestBody = {
144
- ...options.request,
145
- input: stripConfigurationUpdateItems(options.request.input) as NativeCompactionRequestBody["input"],
146
- };
147
- const headers = toHeaders(runtime);
148
-
149
- if (signal?.aborted) {
150
- const aborted: NativeCompactionClientFailure = {
151
- ok: false,
152
- reason: "aborted",
153
- };
154
- writeCompactArtifact(
155
- {
156
- request: {
157
- url: runtime.compactUrl,
158
- headers,
159
- body: request,
160
- },
161
- outcome: aborted,
162
- },
163
- settings,
164
- context,
165
- );
166
- return aborted;
167
- }
168
-
169
- try {
170
- const response = await fetch(runtime.compactUrl, {
171
- method: "POST",
172
- headers,
173
- body: JSON.stringify(request),
174
- signal,
175
- });
176
- const responseText = await response.text();
177
- const responseHeaders: Record<string, string> = {};
178
- response.headers.forEach((value, key) => {
179
- responseHeaders[key] = value;
180
- });
181
-
182
- if (!response.ok) {
183
- let responseJson: unknown;
184
- if (responseText.trim().length > 0) {
185
- try {
186
- responseJson = JSON.parse(responseText);
187
- } catch {
188
- responseJson = undefined;
189
- }
190
- }
191
-
192
- const failure: NativeCompactionClientFailure = {
193
- ok: false,
194
- reason: "non-2xx",
195
- status: response.status,
196
- responseText: responseText || undefined,
197
- responseJson,
198
- };
199
- writeCompactArtifact(
200
- {
201
- request: {
202
- url: runtime.compactUrl,
203
- headers,
204
- body: request,
205
- },
206
- response: {
207
- status: response.status,
208
- headers: responseHeaders,
209
- body: responseJson ?? responseText,
210
- },
211
- outcome: failure,
212
- },
213
- settings,
214
- context,
215
- );
216
- return failure;
217
- }
218
-
219
- if (!responseText.trim()) {
220
- const failure: NativeCompactionClientFailure = {
221
- ok: false,
222
- reason: "empty-body",
223
- status: response.status,
224
- };
225
- writeCompactArtifact(
226
- {
227
- request: {
228
- url: runtime.compactUrl,
229
- headers,
230
- body: request,
231
- },
232
- response: {
233
- status: response.status,
234
- headers: responseHeaders,
235
- body: responseText,
236
- },
237
- outcome: failure,
238
- },
239
- settings,
240
- context,
241
- );
242
- return failure;
243
- }
244
-
245
- let parsed: unknown;
246
- try {
247
- parsed = JSON.parse(responseText);
248
- } catch (error) {
249
- const failure: NativeCompactionClientFailure = {
250
- ok: false,
251
- reason: "invalid-json",
252
- status: response.status,
253
- errorMessage: error instanceof Error ? error.message : String(error),
254
- responseText,
255
- };
256
- writeCompactArtifact(
257
- {
258
- request: {
259
- url: runtime.compactUrl,
260
- headers,
261
- body: request,
262
- },
263
- response: {
264
- status: response.status,
265
- headers: responseHeaders,
266
- body: responseText,
267
- },
268
- outcome: failure,
269
- },
270
- settings,
271
- context,
272
- );
273
- return failure;
274
- }
275
-
276
- if (!isCompactResponseEnvelope(parsed)) {
277
- const failure: NativeCompactionClientFailure = {
278
- ok: false,
279
- reason: "malformed-response",
280
- status: response.status,
281
- responseJson: parsed,
282
- };
283
- writeCompactArtifact(
284
- {
285
- request: {
286
- url: runtime.compactUrl,
287
- headers,
288
- body: request,
289
- },
290
- response: {
291
- status: response.status,
292
- headers: responseHeaders,
293
- body: parsed,
294
- },
295
- outcome: failure,
296
- },
297
- settings,
298
- context,
299
- );
300
- return failure;
301
- }
302
-
303
- if (parsed.output.length === 0) {
304
- const failure: NativeCompactionClientFailure = {
305
- ok: false,
306
- reason: "empty-output",
307
- status: response.status,
308
- responseJson: parsed,
309
- };
310
- writeCompactArtifact(
311
- {
312
- request: {
313
- url: runtime.compactUrl,
314
- headers,
315
- body: request,
316
- },
317
- response: {
318
- status: response.status,
319
- headers: responseHeaders,
320
- body: parsed,
321
- },
322
- outcome: failure,
323
- },
324
- settings,
325
- context,
326
- );
327
- return failure;
328
- }
329
-
330
- const success: NativeCompactionClientSuccess = {
331
- ok: true,
332
- status: response.status,
333
- compactedWindow: [...parsed.output],
334
- compactResponseId: typeof parsed.id === "string" && parsed.id.trim() ? parsed.id.trim() : undefined,
335
- createdAt: normalizeResponseTimestamp(parsed.created_at),
336
- summaryText: extractCompactedSummaryText(parsed.output),
337
- response: parsed,
338
- };
339
- writeCompactArtifact(
340
- {
341
- request: {
342
- url: runtime.compactUrl,
343
- headers,
344
- body: request,
345
- },
346
- response: {
347
- status: response.status,
348
- headers: responseHeaders,
349
- body: parsed,
350
- },
351
- outcome: {
352
- ok: true,
353
- status: success.status,
354
- compactResponseId: success.compactResponseId,
355
- createdAt: success.createdAt,
356
- compactedItems: success.compactedWindow.length,
357
- },
358
- },
359
- settings,
360
- context,
361
- );
362
- return success;
363
- } catch (error) {
364
- const failure: NativeCompactionClientFailure = isAbortError(error)
365
- ? {
366
- ok: false,
367
- reason: "aborted",
368
- }
369
- : {
370
- ok: false,
371
- reason: "network-error",
372
- errorMessage: error instanceof Error ? error.message : String(error),
373
- };
374
-
375
- writeCompactArtifact(
376
- {
377
- request: {
378
- url: runtime.compactUrl,
379
- headers,
380
- body: request,
381
- },
382
- outcome: failure,
383
- },
384
- settings,
385
- context,
386
- );
387
- return failure;
388
- }
389
- }
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
+ }