@lll9p/pi-better-compaction 0.2.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/types.ts ADDED
@@ -0,0 +1,296 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import type { CompactionEntry, CompactionResult, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+
4
+ export const EXTENSION_ID = "pi-better-compaction";
5
+ export const DEFAULT_ARTIFACT_ROOT = "~/.pi/agent/artifacts/pi-better-compaction";
6
+ export const REDACTED_VALUE = "[REDACTED]";
7
+ /**
8
+ * APIs the extension knows how to build a `/responses/compact` URL for.
9
+ * `responsesCompactApis` in config.json may only narrow this set.
10
+ */
11
+ export const RESPONSES_COMPACT_CAPABLE_APIS = ["openai-responses", "openai-codex-responses"] as const;
12
+ export const NATIVE_COMPACTION_STRATEGY = "openai-native-compact-v1";
13
+ /** Used as CompactionEntry.summary only when no summary text could be extracted from the compact response. */
14
+ export const NATIVE_COMPACTION_FALLBACK_SUMMARY = "[OpenAI native compaction checkpoint]";
15
+
16
+ export const THINKING_LEVELS: readonly ThinkingLevel[] = [
17
+ "off",
18
+ "minimal",
19
+ "low",
20
+ "medium",
21
+ "high",
22
+ "xhigh",
23
+ "max",
24
+ ];
25
+
26
+ export type DebugArtifactKind =
27
+ | "provider-request"
28
+ | "compact-response"
29
+ | "compaction-event"
30
+ | "lifecycle";
31
+
32
+ export type ExtensionConfig = {
33
+ enabled: boolean;
34
+ /**
35
+ * "provider/model-id" used for native-method fallback compaction (non-Responses APIs,
36
+ * or when the compact endpoint fails). Unset = current model via pi's default path.
37
+ */
38
+ compactionModel?: string;
39
+ /** Thinking level passed to pi's native compact() when the fallback model runs. */
40
+ compactionThinkingLevel: ThinkingLevel;
41
+ /** Subset of RESPONSES_COMPACT_CAPABLE_APIS that should use the compact endpoint. */
42
+ responsesCompactApis: string[];
43
+ notifyOnLoad: boolean;
44
+ debug: boolean;
45
+ logProviderPayloads: boolean;
46
+ logCompactResponses: boolean;
47
+ redactSensitiveData: boolean;
48
+ artifactRoot: string;
49
+ };
50
+
51
+ export type LoadedExtensionConfig = {
52
+ config: ExtensionConfig;
53
+ /** Path of the config file that was applied, if it existed and parsed. */
54
+ source?: string;
55
+ warnings: string[];
56
+ };
57
+
58
+ export type ArtifactPaths = {
59
+ rootDir: string;
60
+ sessionDir: string;
61
+ providerRequestsDir: string;
62
+ compactResponsesDir: string;
63
+ compactionDir: string;
64
+ lifecycleDir: string;
65
+ };
66
+
67
+ export type ArtifactSessionInfo = {
68
+ cwd: string;
69
+ sessionId?: string;
70
+ sessionFile?: string;
71
+ sessionDir?: string;
72
+ };
73
+
74
+ export type ArtifactContext = ArtifactSessionInfo | Pick<ExtensionContext, "cwd" | "sessionManager">;
75
+
76
+ export type DebugArtifactEnvelope = {
77
+ extension: string;
78
+ kind: DebugArtifactKind;
79
+ timestamp: string;
80
+ cwd: string;
81
+ sessionId?: string;
82
+ sessionFile?: string;
83
+ sessionDir?: string;
84
+ redaction: {
85
+ enabled: boolean;
86
+ };
87
+ data: unknown;
88
+ };
89
+
90
+ export type RedactOptions = {
91
+ placeholder?: string;
92
+ };
93
+
94
+ export type NativeCompactionStrategy = typeof NATIVE_COMPACTION_STRATEGY;
95
+
96
+ export type NativeCompactionRequestMeta = {
97
+ tokensBefore?: number;
98
+ previousSummaryPresent?: boolean;
99
+ };
100
+
101
+ export type NativeCompactionIdentity = {
102
+ provider: string;
103
+ api: string;
104
+ model: string;
105
+ baseUrl: string;
106
+ };
107
+
108
+ export type NativeCompactionDetails = NativeCompactionIdentity & {
109
+ strategy: NativeCompactionStrategy;
110
+ compactedWindow: unknown[];
111
+ compactResponseId?: string;
112
+ createdAt: string;
113
+ requestMeta?: NativeCompactionRequestMeta;
114
+ };
115
+
116
+ export type NativeCompactionEntry = CompactionEntry<NativeCompactionDetails>;
117
+
118
+ export type CreateNativeCompactionDetailsInput = NativeCompactionIdentity & {
119
+ compactedWindow: unknown[];
120
+ compactResponseId?: string;
121
+ createdAt?: string;
122
+ requestMeta?: NativeCompactionRequestMeta;
123
+ };
124
+
125
+ export type CreateNativeCompactionResultInput = {
126
+ firstKeptEntryId: string;
127
+ tokensBefore: number;
128
+ details: NativeCompactionDetails;
129
+ /**
130
+ * Summary text extracted from the compact response. Stored as the entry summary so
131
+ * pi's default replay still has real context after switching to an unsupported model.
132
+ */
133
+ summary?: string;
134
+ };
135
+
136
+ function isRecord(value: unknown): value is Record<string, unknown> {
137
+ return !!value && typeof value === "object" && !Array.isArray(value);
138
+ }
139
+
140
+ function isNonEmptyString(value: unknown): value is string {
141
+ return typeof value === "string" && value.trim().length > 0;
142
+ }
143
+
144
+ function isFiniteNonNegativeNumber(value: unknown): value is number {
145
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
146
+ }
147
+
148
+ function normalizeString(value: string): string {
149
+ return value.trim();
150
+ }
151
+
152
+ function isStructuredValue(value: unknown): boolean {
153
+ if (
154
+ value === null ||
155
+ typeof value === "string" ||
156
+ typeof value === "number" ||
157
+ typeof value === "boolean"
158
+ ) {
159
+ return true;
160
+ }
161
+
162
+ if (Array.isArray(value)) {
163
+ return value.every(isStructuredValue);
164
+ }
165
+
166
+ if (isRecord(value)) {
167
+ return Object.values(value).every(isStructuredValue);
168
+ }
169
+
170
+ return false;
171
+ }
172
+
173
+ function cloneStructuredValue(value: unknown): unknown {
174
+ if (
175
+ value === null ||
176
+ typeof value === "string" ||
177
+ typeof value === "number" ||
178
+ typeof value === "boolean"
179
+ ) {
180
+ return value;
181
+ }
182
+
183
+ if (Array.isArray(value)) {
184
+ return value.map(cloneStructuredValue);
185
+ }
186
+
187
+ if (isRecord(value)) {
188
+ const clone: Record<string, unknown> = {};
189
+ for (const [key, nested] of Object.entries(value)) {
190
+ clone[key] = cloneStructuredValue(nested);
191
+ }
192
+ return clone;
193
+ }
194
+
195
+ throw new Error(`Unsupported structured value: ${typeof value}`);
196
+ }
197
+
198
+ function isCompactedWindowItem(value: unknown): value is Record<string, unknown> {
199
+ return isRecord(value) && Object.values(value).every(isStructuredValue);
200
+ }
201
+
202
+ export function isNativeCompactionRequestMeta(value: unknown): value is NativeCompactionRequestMeta {
203
+ if (!isRecord(value)) {
204
+ return false;
205
+ }
206
+
207
+ const { tokensBefore, previousSummaryPresent } = value;
208
+ if (tokensBefore !== undefined && !isFiniteNonNegativeNumber(tokensBefore)) {
209
+ return false;
210
+ }
211
+
212
+ if (previousSummaryPresent !== undefined && typeof previousSummaryPresent !== "boolean") {
213
+ return false;
214
+ }
215
+
216
+ return true;
217
+ }
218
+
219
+ export function isNativeCompactionIdentity(value: unknown): value is NativeCompactionIdentity {
220
+ if (!isRecord(value)) {
221
+ return false;
222
+ }
223
+
224
+ return (
225
+ isNonEmptyString(value.provider) &&
226
+ isNonEmptyString(value.api) &&
227
+ isNonEmptyString(value.model) &&
228
+ isNonEmptyString(value.baseUrl)
229
+ );
230
+ }
231
+
232
+ export function isNativeCompactionDetails(value: unknown): value is NativeCompactionDetails {
233
+ if (!isRecord(value)) {
234
+ return false;
235
+ }
236
+
237
+ return (
238
+ value.strategy === NATIVE_COMPACTION_STRATEGY &&
239
+ isNativeCompactionIdentity(value) &&
240
+ Array.isArray(value.compactedWindow) &&
241
+ value.compactedWindow.every(isCompactedWindowItem) &&
242
+ isNonEmptyString(value.createdAt) &&
243
+ (value.compactResponseId === undefined || isNonEmptyString(value.compactResponseId)) &&
244
+ (value.requestMeta === undefined || isNativeCompactionRequestMeta(value.requestMeta))
245
+ );
246
+ }
247
+
248
+ export function isNativeCompactionEntry(value: unknown): value is NativeCompactionEntry {
249
+ return isRecord(value) && value.type === "compaction" && isNativeCompactionDetails(value.details);
250
+ }
251
+
252
+ export function createNativeCompactionDetails(input: CreateNativeCompactionDetailsInput): NativeCompactionDetails {
253
+ return {
254
+ strategy: NATIVE_COMPACTION_STRATEGY,
255
+ provider: normalizeString(input.provider),
256
+ api: normalizeString(input.api),
257
+ model: normalizeString(input.model),
258
+ baseUrl: normalizeString(input.baseUrl),
259
+ compactedWindow: input.compactedWindow.map((item) => cloneStructuredValue(item)),
260
+ compactResponseId: isNonEmptyString(input.compactResponseId) ? normalizeString(input.compactResponseId) : undefined,
261
+ createdAt: isNonEmptyString(input.createdAt) ? normalizeString(input.createdAt) : new Date().toISOString(),
262
+ requestMeta: input.requestMeta
263
+ ? {
264
+ ...(input.requestMeta.tokensBefore !== undefined ? { tokensBefore: input.requestMeta.tokensBefore } : {}),
265
+ ...(input.requestMeta.previousSummaryPresent !== undefined
266
+ ? { previousSummaryPresent: input.requestMeta.previousSummaryPresent }
267
+ : {}),
268
+ }
269
+ : undefined,
270
+ };
271
+ }
272
+
273
+ export function createNativeCompactionResult(
274
+ input: CreateNativeCompactionResultInput,
275
+ ): CompactionResult<NativeCompactionDetails> {
276
+ const summary = input.summary?.trim();
277
+ return {
278
+ summary: summary && summary.length > 0 ? summary : NATIVE_COMPACTION_FALLBACK_SUMMARY,
279
+ firstKeptEntryId: input.firstKeptEntryId,
280
+ tokensBefore: input.tokensBefore,
281
+ details: input.details,
282
+ };
283
+ }
284
+
285
+ export const DEFAULT_EXTENSION_CONFIG: ExtensionConfig = {
286
+ enabled: true,
287
+ compactionModel: undefined,
288
+ compactionThinkingLevel: "off",
289
+ responsesCompactApis: [...RESPONSES_COMPACT_CAPABLE_APIS],
290
+ notifyOnLoad: false,
291
+ debug: false,
292
+ logProviderPayloads: false,
293
+ logCompactResponses: false,
294
+ redactSensitiveData: true,
295
+ artifactRoot: DEFAULT_ARTIFACT_ROOT,
296
+ };