@lll9p/pi-better-compaction 0.2.1 → 0.5.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,98 @@
1
+ /**
2
+ * V2 compaction retained-message filtering.
3
+ *
4
+ * After the API returns an encrypted compaction blob, V2 keeps a window of recent
5
+ * user/developer/system messages alongside the blob so the model retains explicit
6
+ * user instructions and context anchors. This module mirrors the filtering and
7
+ * budget logic from codex-rs `compact_remote_v2.rs`.
8
+ */
9
+
10
+ /** Token budget for retained messages (matches codex-rs RETAINED_MESSAGE_TOKEN_BUDGET). */
11
+ export const RETAINED_MESSAGE_TOKEN_BUDGET = 65_536;
12
+
13
+ /** Messages larger than this are excluded even if they are of a retained role. */
14
+ const MAX_SINGLE_ITEM_TOKENS = 10_000;
15
+
16
+ /** Rough chars-per-token ratio for budget estimation. */
17
+ const CHARS_PER_TOKEN = 4;
18
+
19
+ function isRecord(value: unknown): value is Record<string, unknown> {
20
+ return !!value && typeof value === "object" && !Array.isArray(value);
21
+ }
22
+
23
+ /**
24
+ * Estimate the token count of an opaque input item by serializing to JSON and
25
+ * dividing by the chars-per-token ratio. This is intentionally rough — codex-rs
26
+ * uses a real tokenizer but we don't have one in the extension runtime.
27
+ */
28
+ export function estimateItemTokens(item: unknown): number {
29
+ try {
30
+ const length = JSON.stringify(item).length;
31
+ return Math.ceil(length / CHARS_PER_TOKEN);
32
+ } catch {
33
+ return 0;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Whether an input item should be retained alongside the compaction blob.
39
+ *
40
+ * Retained roles (matching codex-rs `is_retained_for_remote_compaction_v2`):
41
+ * - `user` messages
42
+ * - `developer` messages
43
+ * - `system` messages
44
+ *
45
+ * Everything else (assistant, function_call, function_call_output, reasoning,
46
+ * compaction, etc.) is excluded.
47
+ */
48
+ export function isRetainedItem(item: unknown): boolean {
49
+ if (!isRecord(item)) {
50
+ return false;
51
+ }
52
+
53
+ const role = item.role;
54
+ if (typeof role === "string") {
55
+ return role === "user" || role === "developer" || role === "system";
56
+ }
57
+
58
+ return false;
59
+ }
60
+
61
+ /**
62
+ * From a list of Responses API input items, select the most recent retained
63
+ * messages that fit within the token budget. Items are selected newest-first
64
+ * (reverse order) and returned in their original chronological order.
65
+ *
66
+ * Oversized individual items (> MAX_SINGLE_ITEM_TOKENS) are skipped.
67
+ */
68
+ export function buildRetainedMessages(
69
+ input: readonly unknown[],
70
+ budget: number = RETAINED_MESSAGE_TOKEN_BUDGET,
71
+ ): unknown[] {
72
+ // Filter to retained roles first.
73
+ const retained: Array<{ index: number; item: unknown; tokens: number }> = [];
74
+ for (let i = 0; i < input.length; i++) {
75
+ const item = input[i];
76
+ if (!isRetainedItem(item)) continue;
77
+
78
+ const tokens = estimateItemTokens(item);
79
+ if (tokens > MAX_SINGLE_ITEM_TOKENS) continue;
80
+
81
+ retained.push({ index: i, item, tokens });
82
+ }
83
+
84
+ // Select from newest to oldest within the budget.
85
+ let remaining = budget;
86
+ const selected: typeof retained = [];
87
+
88
+ for (let i = retained.length - 1; i >= 0; i--) {
89
+ const entry = retained[i]!;
90
+ if (entry.tokens > remaining) break;
91
+ remaining -= entry.tokens;
92
+ selected.push(entry);
93
+ }
94
+
95
+ // Return in original chronological order.
96
+ selected.reverse();
97
+ return selected.map((entry) => structuredClone(entry.item));
98
+ }
package/src/runtime.ts CHANGED
@@ -4,6 +4,8 @@ import { RESPONSES_COMPACT_CAPABLE_APIS } from "./types";
4
4
 
5
5
  const OPENAI_COMPACT_PATH = "responses/compact";
6
6
  const CODEX_COMPACT_PATH = "codex/responses/compact";
7
+ const OPENAI_RESPONSES_PATH = "responses";
8
+ const CODEX_RESPONSES_PATH = "codex/responses";
7
9
 
8
10
  type ResponsesCompactApi = (typeof RESPONSES_COMPACT_CAPABLE_APIS)[number];
9
11
 
@@ -40,6 +42,7 @@ export type NativeCompactionRuntime = {
40
42
  headers?: Record<string, string>;
41
43
  compactPath: string;
42
44
  compactUrl: string;
45
+ responsesUrl: string;
43
46
  payload?: ResponsesCompatibleRequestPayload;
44
47
  currentModel: RuntimeModel;
45
48
  };
@@ -74,6 +77,29 @@ export function normalizeBaseUrl(baseUrl: string | undefined | null): string | u
74
77
  return normalized ? normalized : undefined;
75
78
  }
76
79
 
80
+ function buildOpenAIResponsesUrl(baseUrl: string): string {
81
+ const normalized = normalizeBaseUrl(baseUrl) ?? baseUrl;
82
+ if (normalized.endsWith("/responses")) {
83
+ return normalized;
84
+ }
85
+ return `${normalized}/${OPENAI_RESPONSES_PATH}`;
86
+ }
87
+
88
+ function buildCodexResponsesUrl(baseUrl: string): string {
89
+ const normalized = normalizeBaseUrl(baseUrl) ?? baseUrl;
90
+ if (normalized.endsWith("/codex/responses")) {
91
+ return normalized;
92
+ }
93
+ if (normalized.endsWith("/codex")) {
94
+ return `${normalized}/responses`;
95
+ }
96
+ return `${normalized}/${CODEX_RESPONSES_PATH}`;
97
+ }
98
+
99
+ export function buildResponsesUrl(baseUrl: string, api: ResponsesCompactApi): string {
100
+ return api === "openai-codex-responses" ? buildCodexResponsesUrl(baseUrl) : buildOpenAIResponsesUrl(baseUrl);
101
+ }
102
+
77
103
  function buildOpenAICompactUrl(baseUrl: string): string {
78
104
  const normalized = normalizeBaseUrl(baseUrl) ?? baseUrl;
79
105
  if (normalized.endsWith("/responses")) {
@@ -101,13 +127,25 @@ export function buildCompactPath(api: ResponsesCompactApi): string {
101
127
  return api === "openai-codex-responses" ? CODEX_COMPACT_PATH : OPENAI_COMPACT_PATH;
102
128
  }
103
129
 
130
+ /** Strip null-valued entries so downstream consumers receive a clean Record<string, string>. */
131
+ function filterNullHeaders(headers: Record<string, string | null> | undefined): Record<string, string> | undefined {
132
+ if (!headers) return undefined;
133
+ const filtered: Record<string, string> = {};
134
+ for (const [key, value] of Object.entries(headers)) {
135
+ if (value !== null) {
136
+ filtered[key] = value;
137
+ }
138
+ }
139
+ return Object.keys(filtered).length > 0 ? filtered : undefined;
140
+ }
141
+
104
142
  async function resolveRequestAuth(
105
143
  ctx: ExtensionContext,
106
144
  model: RuntimeModel,
107
145
  ): Promise<{ apiKey?: string; headers?: Record<string, string> }> {
108
146
  const modelRegistry = ctx.modelRegistry as {
109
147
  getApiKeyAndHeaders?: (currentModel: RuntimeModel) => Promise<
110
- | { ok: true; apiKey?: string; headers?: Record<string, string> }
148
+ | { ok: true; apiKey?: string; headers?: Record<string, string | null> }
111
149
  | { ok: false; error: string }
112
150
  >;
113
151
  };
@@ -117,7 +155,7 @@ async function resolveRequestAuth(
117
155
  }
118
156
 
119
157
  const auth = await modelRegistry.getApiKeyAndHeaders(model);
120
- return auth.ok ? { apiKey: auth.apiKey, headers: auth.headers } : {};
158
+ return auth.ok ? { apiKey: auth.apiKey, headers: filterNullHeaders(auth.headers) } : {};
121
159
  }
122
160
 
123
161
  export function isSupportedApi(api: string): api is ResponsesCompactApi {
@@ -234,6 +272,7 @@ export async function resolveNativeCompactionEnvironment(
234
272
  headers,
235
273
  compactPath: buildCompactPath(descriptor.api),
236
274
  compactUrl: buildCompactUrl(descriptor.baseUrl, descriptor.api),
275
+ responsesUrl: buildResponsesUrl(descriptor.baseUrl, descriptor.api),
237
276
  payload: requestPayload,
238
277
  currentModel,
239
278
  },
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Shared HTTP header construction for V1 and V2 compaction clients.
3
+ *
4
+ * Extracts the header building logic that was previously private in
5
+ * compact-client.ts so both compact-client.ts and compact-client-v2.ts
6
+ * can share it without duplication.
7
+ */
8
+
9
+ import type { NativeCompactionRuntime } from "./runtime";
10
+
11
+ const JSON_CONTENT_TYPE = "application/json";
12
+
13
+ function decodeJwtPayload(token: string): Record<string, unknown> | undefined {
14
+ const parts = token.split(".");
15
+ if (parts.length !== 3) {
16
+ return undefined;
17
+ }
18
+
19
+ try {
20
+ const payloadText = Buffer.from(parts[1]!, "base64url").toString("utf8");
21
+ const payload = JSON.parse(payloadText);
22
+ return payload && typeof payload === "object" && !Array.isArray(payload)
23
+ ? (payload as Record<string, unknown>)
24
+ : undefined;
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ }
29
+
30
+ function isRecord(value: unknown): value is Record<string, unknown> {
31
+ return !!value && typeof value === "object" && !Array.isArray(value);
32
+ }
33
+
34
+ function extractCodexAccountId(token: string): string | undefined {
35
+ const payload = decodeJwtPayload(token);
36
+ const authClaims = payload?.["https://api.openai.com/auth"];
37
+ if (!isRecord(authClaims)) {
38
+ return undefined;
39
+ }
40
+
41
+ const accountId = authClaims.chatgpt_account_id;
42
+ return typeof accountId === "string" && accountId.trim().length > 0 ? accountId.trim() : undefined;
43
+ }
44
+
45
+ function buildCodexUserAgent(): string {
46
+ const platform = typeof process !== "undefined" ? process.platform : "browser";
47
+ const arch = typeof process !== "undefined" ? process.arch : "unknown";
48
+ return `pi (${platform}; ${arch})`;
49
+ }
50
+
51
+ /**
52
+ * Build HTTP headers for a compaction request from the resolved runtime.
53
+ *
54
+ * Handles model-level headers, extension-resolved headers, authorization,
55
+ * and Codex-specific headers (account ID, originator, user-agent, beta flag).
56
+ *
57
+ * @param accept - The Accept header value. Defaults to `application/json`.
58
+ */
59
+ export function toHeaders(
60
+ runtime: NativeCompactionRuntime,
61
+ accept: string = JSON_CONTENT_TYPE,
62
+ ): Record<string, string> {
63
+ const headers = new Headers();
64
+ // Model-level headers may contain null values (ProviderHeaders); null means "unset".
65
+ for (const [key, value] of Object.entries(runtime.currentModel.headers ?? {})) {
66
+ if (value != null) {
67
+ headers.set(key, String(value));
68
+ }
69
+ }
70
+ // Extension-resolved headers (already filtered by resolveRequestAuth, but defensive).
71
+ for (const [key, value] of Object.entries(runtime.headers ?? {})) {
72
+ if (value == null) {
73
+ headers.delete(key);
74
+ } else {
75
+ headers.set(key, value);
76
+ }
77
+ }
78
+ headers.set("accept", accept);
79
+ headers.set("content-type", JSON_CONTENT_TYPE);
80
+ if (!headers.has("authorization")) {
81
+ headers.set("authorization", `Bearer ${runtime.apiKey}`);
82
+ }
83
+
84
+ if (runtime.api === "openai-codex-responses") {
85
+ const accountId = extractCodexAccountId(runtime.apiKey);
86
+ if (accountId) {
87
+ headers.set("chatgpt-account-id", accountId);
88
+ }
89
+ headers.set("originator", "pi");
90
+ headers.set("user-agent", buildCodexUserAgent());
91
+ headers.set("openai-beta", "responses=experimental");
92
+ }
93
+
94
+ return Object.fromEntries(headers.entries());
95
+ }
96
+
97
+ /** Check whether an error represents an intentional abort (AbortController / AbortSignal). */
98
+ export function isAbortError(error: unknown): boolean {
99
+ return (
100
+ (error instanceof DOMException && error.name === "AbortError") ||
101
+ (error instanceof Error && (error.name === "AbortError" || error.name === "ABORT_ERR"))
102
+ );
103
+ }
package/src/types.ts CHANGED
@@ -10,6 +10,7 @@ export const REDACTED_VALUE = "[REDACTED]";
10
10
  */
11
11
  export const RESPONSES_COMPACT_CAPABLE_APIS = ["openai-responses", "openai-codex-responses"] as const;
12
12
  export const NATIVE_COMPACTION_STRATEGY = "openai-native-compact-v1";
13
+ export const NATIVE_COMPACTION_STRATEGY_V2 = "openai-native-compact-v2";
13
14
  /** Used as CompactionEntry.summary only when no summary text could be extracted from the compact response. */
14
15
  export const NATIVE_COMPACTION_FALLBACK_SUMMARY = "[OpenAI native compaction checkpoint]";
15
16
 
@@ -23,14 +24,23 @@ export const THINKING_LEVELS: readonly ThinkingLevel[] = [
23
24
  "max",
24
25
  ];
25
26
 
27
+ export type CompactionVersion = "v1" | "v2";
28
+ export const COMPACTION_VERSIONS: readonly CompactionVersion[] = ["v1", "v2"];
29
+
26
30
  export type DebugArtifactKind =
27
31
  | "provider-request"
28
32
  | "compact-response"
29
33
  | "compaction-event"
30
34
  | "lifecycle";
31
35
 
36
+ export type MidRunConfig = {
37
+ enabled: boolean;
38
+ thresholdPercent: number;
39
+ };
40
+
32
41
  export type ExtensionConfig = {
33
42
  enabled: boolean;
43
+ midRun: MidRunConfig;
34
44
  /**
35
45
  * Allow a Responses session whose latest compaction was not created by this extension
36
46
  * to restart native compaction from Pi's current serialized session context.
@@ -45,6 +55,13 @@ export type ExtensionConfig = {
45
55
  compactionThinkingLevel: ThinkingLevel;
46
56
  /** Subset of RESPONSES_COMPACT_CAPABLE_APIS that should use the compact endpoint. */
47
57
  responsesCompactApis: string[];
58
+ /**
59
+ * Which compaction protocol to use for Responses-family APIs.
60
+ * - "v2" (default): streaming CompactionTrigger via /responses endpoint.
61
+ * - "v1": POST /responses/compact endpoint.
62
+ * V2 failures automatically fall back to V1.
63
+ */
64
+ compactionVersion: CompactionVersion;
48
65
  notifyOnLoad: boolean;
49
66
  debug: boolean;
50
67
  logProviderPayloads: boolean;
@@ -97,6 +114,7 @@ export type RedactOptions = {
97
114
  };
98
115
 
99
116
  export type NativeCompactionStrategy = typeof NATIVE_COMPACTION_STRATEGY;
117
+ export type NativeCompactionStrategyV2 = typeof NATIVE_COMPACTION_STRATEGY_V2;
100
118
 
101
119
  export type NativeCompactionRequestMeta = {
102
120
  tokensBefore?: number;
@@ -111,7 +129,7 @@ export type NativeCompactionIdentity = {
111
129
  };
112
130
 
113
131
  export type NativeCompactionDetails = NativeCompactionIdentity & {
114
- strategy: NativeCompactionStrategy;
132
+ strategy: NativeCompactionStrategy | NativeCompactionStrategyV2;
115
133
  compactedWindow: unknown[];
116
134
  compactResponseId?: string;
117
135
  createdAt: string;
@@ -240,7 +258,7 @@ export function isNativeCompactionDetails(value: unknown): value is NativeCompac
240
258
  }
241
259
 
242
260
  return (
243
- value.strategy === NATIVE_COMPACTION_STRATEGY &&
261
+ (value.strategy === NATIVE_COMPACTION_STRATEGY || value.strategy === NATIVE_COMPACTION_STRATEGY_V2) &&
244
262
  isNativeCompactionIdentity(value) &&
245
263
  Array.isArray(value.compactedWindow) &&
246
264
  value.compactedWindow.every(isCompactedWindowItem) &&
@@ -254,9 +272,12 @@ export function isNativeCompactionEntry(value: unknown): value is NativeCompacti
254
272
  return isRecord(value) && value.type === "compaction" && isNativeCompactionDetails(value.details);
255
273
  }
256
274
 
257
- export function createNativeCompactionDetails(input: CreateNativeCompactionDetailsInput): NativeCompactionDetails {
275
+ export function createNativeCompactionDetails(
276
+ input: CreateNativeCompactionDetailsInput,
277
+ strategy: NativeCompactionStrategy | NativeCompactionStrategyV2 = NATIVE_COMPACTION_STRATEGY,
278
+ ): NativeCompactionDetails {
258
279
  return {
259
- strategy: NATIVE_COMPACTION_STRATEGY,
280
+ strategy,
260
281
  provider: normalizeString(input.provider),
261
282
  api: normalizeString(input.api),
262
283
  model: normalizeString(input.model),
@@ -289,10 +310,15 @@ export function createNativeCompactionResult(
289
310
 
290
311
  export const DEFAULT_EXTENSION_CONFIG: ExtensionConfig = {
291
312
  enabled: true,
313
+ midRun: {
314
+ enabled: false,
315
+ thresholdPercent: 80,
316
+ },
292
317
  allowCompactionContinuityBreak: false,
293
318
  compactionModel: undefined,
294
319
  compactionThinkingLevel: "off",
295
320
  responsesCompactApis: [...RESPONSES_COMPACT_CAPABLE_APIS],
321
+ compactionVersion: "v2",
296
322
  notifyOnLoad: false,
297
323
  debug: false,
298
324
  logProviderPayloads: false,