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
package/src/debug.ts CHANGED
@@ -1,237 +1,238 @@
1
- import * as fs from "node:fs";
2
- import * as os from "node:os";
3
- import * as path from "node:path";
4
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
- import {
6
- COMPACTION_EXTENSION_ID,
7
- REDACTED_VALUE,
8
- type ArtifactContext,
9
- type ArtifactPaths,
10
- type ArtifactSessionInfo,
11
- type DebugArtifactEnvelope,
12
- type DebugArtifactKind,
13
- type DebugConfig,
14
- type RedactOptions,
15
- } from "./types";
16
-
17
- const CRITICAL_KEY_RE = /(authorization|api[-_]?key|token|credential|oauth|auth|account[-_]?id|cookie|set[-_]?cookie|response(?:text)?|completed|encrypted[_-]?(content|output))/i;
18
- const SENSITIVE_KEY_RE = /(authorization|api[-_]?key|token|secret|password|cookie|set-cookie|signature|credential|oauth|auth|account[-_]?id|encrypted[_-]?(content|output))/i;
19
- const BEARER_RE = /\bBearer\s+[A-Za-z0-9._\-+/=]+/gi;
20
- const OPENAI_KEY_RE = /\bsk-[A-Za-z0-9\-_]+\b/g;
21
- const HEADER_TOKEN_RE = /\b(x-api-key|api-key|authorization|chatgpt-account-id)\b\s*[:=]\s*[^\s,;]+/gi;
22
- const SENSITIVE_QUERY_RE = /([?&](?:api[-_]?key|access[-_]?token|token|secret|signature|credential|password)=)[^&#\s]*/gi;
23
-
24
- function ensureDir(dirPath: string) {
25
- fs.mkdirSync(dirPath, { recursive: true });
26
- }
27
-
28
- function toSessionInfo(context: ArtifactContext): ArtifactSessionInfo {
29
- const maybeExtensionContext = context as Pick<ExtensionContext, "cwd" | "sessionManager">;
30
- const sessionManager = maybeExtensionContext.sessionManager;
31
- if (sessionManager) {
32
- return {
33
- cwd: context.cwd,
34
- sessionId: sessionManager.getSessionId(),
35
- sessionFile: sessionManager.getSessionFile(),
36
- sessionDir: sessionManager.getSessionDir(),
37
- };
38
- }
39
- return context;
40
- }
41
-
42
- function sanitizePathSegment(value: string | undefined, fallback: string): string {
43
- if (!value) return fallback;
44
- const normalized = value.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
45
- return normalized.length > 0 ? normalized : fallback;
46
- }
47
-
48
- function redactInlineSecrets(value: string, placeholder: string): string {
49
- return value
50
- .replace(BEARER_RE, `Bearer ${placeholder}`)
51
- .replace(OPENAI_KEY_RE, placeholder)
52
- .replace(HEADER_TOKEN_RE, (_match, key: string) => `${key}: ${placeholder}`)
53
- .replace(SENSITIVE_QUERY_RE, (_match, prefix: string) => `${prefix}${placeholder}`);
54
- }
55
-
56
- function redactWithKeyPattern(
57
- value: unknown,
58
- keyPattern: RegExp,
59
- options: RedactOptions = {},
60
- ): unknown {
61
- const placeholder = options.placeholder ?? REDACTED_VALUE;
62
- const seen = new WeakSet<object>();
63
-
64
- const visit = (input: unknown): unknown => {
65
- if (typeof input === "string") {
66
- return redactInlineSecrets(input, placeholder);
67
- }
68
- if (!input || typeof input !== "object") {
69
- return input;
70
- }
71
- if (seen.has(input)) {
72
- return "[Circular]";
73
- }
74
- seen.add(input);
75
-
76
- if (Array.isArray(input)) {
77
- return input.map((item) => visit(item));
78
- }
79
-
80
- const result: Record<string, unknown> = {};
81
- for (const [key, item] of Object.entries(input)) {
82
- result[key] = keyPattern.test(key) ? placeholder : visit(item);
83
- }
84
- return result;
85
- };
86
-
87
- return visit(value);
88
- }
89
-
90
- /** Credentials and opaque checkpoints are never written to artifacts, even when optional redaction is disabled. */
91
- export function redactCriticalValue(value: unknown, options: RedactOptions = {}): unknown {
92
- return redactWithKeyPattern(value, CRITICAL_KEY_RE, options);
93
- }
94
-
95
- export function redactValue(value: unknown, options: RedactOptions = {}): unknown {
96
- return redactWithKeyPattern(value, SENSITIVE_KEY_RE, options);
97
- }
98
-
99
- export function resolveArtifactPaths(settings: DebugConfig, context: ArtifactContext): ArtifactPaths {
100
- const sessionInfo = toSessionInfo(context);
101
- const rootDir = settings.artifactRoot.startsWith("~/")
102
- ? path.join(os.homedir(), settings.artifactRoot.slice(2))
103
- : path.resolve(settings.artifactRoot);
104
- const sessionDir = path.join(rootDir, "sessions", sanitizePathSegment(sessionInfo.sessionId, "no-session"));
105
-
106
- return {
107
- rootDir,
108
- sessionDir,
109
- providerRequestsDir: path.join(sessionDir, "provider-requests"),
110
- compactResponsesDir: path.join(sessionDir, "compact-responses"),
111
- compactionDir: path.join(sessionDir, "compaction-events"),
112
- lifecycleDir: path.join(sessionDir, "lifecycle"),
113
- };
114
- }
115
-
116
- function selectArtifactDirectory(paths: ArtifactPaths, kind: DebugArtifactKind): string {
117
- switch (kind) {
118
- case "provider-request":
119
- return paths.providerRequestsDir;
120
- case "compact-response":
121
- return paths.compactResponsesDir;
122
- case "compaction-event":
123
- return paths.compactionDir;
124
- case "lifecycle":
125
- default:
126
- return paths.lifecycleDir;
127
- }
128
- }
129
-
130
- function shouldWriteArtifact(kind: DebugArtifactKind, settings: DebugConfig): boolean {
131
- switch (kind) {
132
- case "provider-request":
133
- return settings.logProviderPayloads;
134
- case "compact-response":
135
- return settings.logCompactResponses;
136
- case "compaction-event":
137
- case "lifecycle":
138
- return settings.debug;
139
- default:
140
- return false;
141
- }
142
- }
143
-
144
- export function writeDebugArtifact(
145
- kind: DebugArtifactKind,
146
- data: unknown,
147
- settings: DebugConfig,
148
- context: ArtifactContext,
149
- ): string | undefined {
150
- if (!shouldWriteArtifact(kind, settings)) {
151
- return undefined;
152
- }
153
-
154
- const sessionInfo = toSessionInfo(context);
155
- const paths = resolveArtifactPaths(settings, context);
156
- const targetDir = selectArtifactDirectory(paths, kind);
157
- ensureDir(targetDir);
158
-
159
- const timestamp = new Date().toISOString();
160
- const fileName = `${timestamp.replace(/[.:]/g, "-")}-${kind}.json`;
161
- const filePath = path.join(targetDir, fileName);
162
- const criticallyRedactedData = redactCriticalValue(data);
163
- const envelope: DebugArtifactEnvelope = {
164
- extension: COMPACTION_EXTENSION_ID,
165
- kind,
166
- timestamp,
167
- cwd: sessionInfo.cwd,
168
- sessionId: sessionInfo.sessionId,
169
- sessionFile: sessionInfo.sessionFile,
170
- sessionDir: sessionInfo.sessionDir,
171
- redaction: {
172
- enabled: settings.redactSensitiveData,
173
- },
174
- data: settings.redactSensitiveData ? redactValue(criticallyRedactedData) : criticallyRedactedData,
175
- };
176
-
177
- fs.writeFileSync(filePath, `${JSON.stringify(envelope, null, 2)}\n`, "utf8");
178
- return filePath;
179
- }
180
-
181
- /**
182
- * Always-written, content-free failure record for an opaque replay failure.
183
- *
184
- * Unlike regular payload artifacts this is not gated by logProviderPayloads:
185
- * a replay failure is a continuity-loss incident, not optional payload logging.
186
- * It contains only structural parity signatures and identity metadata; prompt
187
- * text, user content, credentials, and encrypted_content are never included
188
- * (critical redaction is applied unconditionally).
189
- */
190
- export function writeReplayFailureArtifact(
191
- details: {
192
- reason: string;
193
- parity?: { actual: string[]; expected: string[]; mismatches: string[] };
194
- compactionEntryId?: string;
195
- provider?: string;
196
- api?: string;
197
- model?: string;
198
- },
199
- settings: DebugConfig,
200
- context: ArtifactContext,
201
- ): string | undefined {
202
- try {
203
- const sessionInfo = toSessionInfo(context);
204
- const paths = resolveArtifactPaths(settings, context);
205
- const targetDir = selectArtifactDirectory(paths, "provider-request");
206
- ensureDir(targetDir);
207
-
208
- const timestamp = new Date().toISOString();
209
- const filePath = path.join(targetDir, `${timestamp.replace(/[.:]/g, "-")}-replay-failure.json`);
210
- const data = redactCriticalValue({
211
- event: "before_provider_request.rewrite-failed",
212
- reason: details.reason,
213
- parity: details.parity,
214
- compactionEntryId: details.compactionEntryId,
215
- provider: details.provider,
216
- api: details.api,
217
- model: details.model,
218
- });
219
- const envelope: DebugArtifactEnvelope = {
220
- extension: COMPACTION_EXTENSION_ID,
221
- kind: "provider-request",
222
- timestamp,
223
- cwd: sessionInfo.cwd,
224
- sessionId: sessionInfo.sessionId,
225
- sessionFile: sessionInfo.sessionFile,
226
- sessionDir: sessionInfo.sessionDir,
227
- redaction: { enabled: true },
228
- data,
229
- };
230
- fs.writeFileSync(filePath, `${JSON.stringify(envelope, null, 2)}\n`, "utf8");
231
- return filePath;
232
- } catch {
233
- // The replay failure path itself must never be masked by an artifact write
234
- // error; the caller still aborts the provider request.
235
- return undefined;
236
- }
237
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ COMPACTION_EXTENSION_ID,
8
+ REDACTED_VALUE,
9
+ type ArtifactContext,
10
+ type ArtifactPaths,
11
+ type ArtifactSessionInfo,
12
+ type DebugArtifactEnvelope,
13
+ type DebugArtifactKind,
14
+ type DebugConfig,
15
+ type RedactOptions,
16
+ } from "./types";
17
+
18
+ const CRITICAL_KEY_RE = /(authorization|api[-_]?key|token|credential|oauth|auth|account[-_]?id|cookie|set[-_]?cookie|response(?:text)?|completed|encrypted[_-]?(content|output))/i;
19
+ const SENSITIVE_KEY_RE = /(authorization|api[-_]?key|token|secret|password|cookie|set-cookie|signature|credential|oauth|auth|account[-_]?id|encrypted[_-]?(content|output))/i;
20
+ const BEARER_RE = /\bBearer\s+[A-Za-z0-9._\-+/=]+/gi;
21
+ const OPENAI_KEY_RE = /\bsk-[A-Za-z0-9\-_]+\b/g;
22
+ const HEADER_TOKEN_RE = /\b(x-api-key|api-key|authorization|chatgpt-account-id)\b\s*[:=]\s*[^\s,;]+/gi;
23
+ const SENSITIVE_QUERY_RE = /([?&](?:api[-_]?key|access[-_]?token|token|secret|signature|credential|password)=)[^&#\s]*/gi;
24
+
25
+ function ensureDir(dirPath: string) {
26
+ fs.mkdirSync(dirPath, { recursive: true });
27
+ }
28
+
29
+ function toSessionInfo(context: ArtifactContext): ArtifactSessionInfo {
30
+ const maybeExtensionContext = context as Pick<ExtensionContext, "cwd" | "sessionManager">;
31
+ const sessionManager = maybeExtensionContext.sessionManager;
32
+ if (sessionManager) {
33
+ return {
34
+ cwd: context.cwd,
35
+ sessionId: sessionManager.getSessionId(),
36
+ sessionFile: sessionManager.getSessionFile(),
37
+ sessionDir: sessionManager.getSessionDir(),
38
+ };
39
+ }
40
+ return context;
41
+ }
42
+
43
+ function sanitizePathSegment(value: string | undefined, fallback: string): string {
44
+ if (!value) return fallback;
45
+ const normalized = value.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
46
+ return normalized.length > 0 ? normalized : fallback;
47
+ }
48
+
49
+ function redactInlineSecrets(value: string, placeholder: string): string {
50
+ return value
51
+ .replace(BEARER_RE, `Bearer ${placeholder}`)
52
+ .replace(OPENAI_KEY_RE, placeholder)
53
+ .replace(HEADER_TOKEN_RE, (_match, key: string) => `${key}: ${placeholder}`)
54
+ .replace(SENSITIVE_QUERY_RE, (_match, prefix: string) => `${prefix}${placeholder}`);
55
+ }
56
+
57
+ function redactWithKeyPattern(
58
+ value: unknown,
59
+ keyPattern: RegExp,
60
+ options: RedactOptions = {},
61
+ ): unknown {
62
+ const placeholder = options.placeholder ?? REDACTED_VALUE;
63
+ const seen = new WeakSet<object>();
64
+
65
+ const visit = (input: unknown): unknown => {
66
+ if (typeof input === "string") {
67
+ return redactInlineSecrets(input, placeholder);
68
+ }
69
+ if (!input || typeof input !== "object") {
70
+ return input;
71
+ }
72
+ if (seen.has(input)) {
73
+ return "[Circular]";
74
+ }
75
+ seen.add(input);
76
+
77
+ if (Array.isArray(input)) {
78
+ return input.map((item) => visit(item));
79
+ }
80
+
81
+ const result: Record<string, unknown> = {};
82
+ for (const [key, item] of Object.entries(input)) {
83
+ result[key] = keyPattern.test(key) ? placeholder : visit(item);
84
+ }
85
+ return result;
86
+ };
87
+
88
+ return visit(value);
89
+ }
90
+
91
+ /** Credentials and opaque checkpoints are never written to artifacts, even when optional redaction is disabled. */
92
+ export function redactCriticalValue(value: unknown, options: RedactOptions = {}): unknown {
93
+ return redactWithKeyPattern(value, CRITICAL_KEY_RE, options);
94
+ }
95
+
96
+ export function redactValue(value: unknown, options: RedactOptions = {}): unknown {
97
+ return redactWithKeyPattern(value, SENSITIVE_KEY_RE, options);
98
+ }
99
+
100
+ export function resolveArtifactPaths(settings: DebugConfig, context: ArtifactContext): ArtifactPaths {
101
+ const sessionInfo = toSessionInfo(context);
102
+ const rootDir = settings.artifactRoot.startsWith("~/")
103
+ ? path.join(os.homedir(), settings.artifactRoot.slice(2))
104
+ : path.resolve(settings.artifactRoot);
105
+ const sessionDir = path.join(rootDir, "sessions", sanitizePathSegment(sessionInfo.sessionId, "no-session"));
106
+
107
+ return {
108
+ rootDir,
109
+ sessionDir,
110
+ providerRequestsDir: path.join(sessionDir, "provider-requests"),
111
+ compactResponsesDir: path.join(sessionDir, "compact-responses"),
112
+ compactionDir: path.join(sessionDir, "compaction-events"),
113
+ lifecycleDir: path.join(sessionDir, "lifecycle"),
114
+ };
115
+ }
116
+
117
+ function selectArtifactDirectory(paths: ArtifactPaths, kind: DebugArtifactKind): string {
118
+ switch (kind) {
119
+ case "provider-request":
120
+ return paths.providerRequestsDir;
121
+ case "compact-response":
122
+ return paths.compactResponsesDir;
123
+ case "compaction-event":
124
+ return paths.compactionDir;
125
+ case "lifecycle":
126
+ default:
127
+ return paths.lifecycleDir;
128
+ }
129
+ }
130
+
131
+ function shouldWriteArtifact(kind: DebugArtifactKind, settings: DebugConfig): boolean {
132
+ switch (kind) {
133
+ case "provider-request":
134
+ return settings.logProviderPayloads;
135
+ case "compact-response":
136
+ return settings.logCompactResponses;
137
+ case "compaction-event":
138
+ case "lifecycle":
139
+ return settings.debug;
140
+ default:
141
+ return false;
142
+ }
143
+ }
144
+
145
+ export function writeDebugArtifact(
146
+ kind: DebugArtifactKind,
147
+ data: unknown,
148
+ settings: DebugConfig,
149
+ context: ArtifactContext,
150
+ ): string | undefined {
151
+ if (!shouldWriteArtifact(kind, settings)) {
152
+ return undefined;
153
+ }
154
+
155
+ const sessionInfo = toSessionInfo(context);
156
+ const paths = resolveArtifactPaths(settings, context);
157
+ const targetDir = selectArtifactDirectory(paths, kind);
158
+ ensureDir(targetDir);
159
+
160
+ const timestamp = new Date().toISOString();
161
+ const fileName = `${timestamp.replace(/[.:]/g, "-")}-${kind}-${randomUUID()}.json`;
162
+ const filePath = path.join(targetDir, fileName);
163
+ const criticallyRedactedData = redactCriticalValue(data);
164
+ const envelope: DebugArtifactEnvelope = {
165
+ extension: COMPACTION_EXTENSION_ID,
166
+ kind,
167
+ timestamp,
168
+ cwd: sessionInfo.cwd,
169
+ sessionId: sessionInfo.sessionId,
170
+ sessionFile: sessionInfo.sessionFile,
171
+ sessionDir: sessionInfo.sessionDir,
172
+ redaction: {
173
+ enabled: settings.redactSensitiveData,
174
+ },
175
+ data: settings.redactSensitiveData ? redactValue(criticallyRedactedData) : criticallyRedactedData,
176
+ };
177
+
178
+ fs.writeFileSync(filePath, `${JSON.stringify(envelope, null, 2)}\n`, { encoding: "utf8", flag: "wx" });
179
+ return filePath;
180
+ }
181
+
182
+ /**
183
+ * Always-written, content-free failure record for an opaque replay failure.
184
+ *
185
+ * Unlike regular payload artifacts this is not gated by logProviderPayloads:
186
+ * a replay failure is a continuity-loss incident, not optional payload logging.
187
+ * It contains only structural parity signatures and identity metadata; prompt
188
+ * text, user content, credentials, and encrypted_content are never included
189
+ * (critical redaction is applied unconditionally).
190
+ */
191
+ export function writeReplayFailureArtifact(
192
+ details: {
193
+ reason: string;
194
+ parity?: { actual: string[]; expected: string[]; mismatches: string[] };
195
+ compactionEntryId?: string;
196
+ provider?: string;
197
+ api?: string;
198
+ model?: string;
199
+ },
200
+ settings: DebugConfig,
201
+ context: ArtifactContext,
202
+ ): string | undefined {
203
+ try {
204
+ const sessionInfo = toSessionInfo(context);
205
+ const paths = resolveArtifactPaths(settings, context);
206
+ const targetDir = selectArtifactDirectory(paths, "provider-request");
207
+ ensureDir(targetDir);
208
+
209
+ const timestamp = new Date().toISOString();
210
+ const filePath = path.join(targetDir, `${timestamp.replace(/[.:]/g, "-")}-replay-failure-${randomUUID()}.json`);
211
+ const data = redactCriticalValue({
212
+ event: "before_provider_request.rewrite-failed",
213
+ reason: details.reason,
214
+ parity: details.parity,
215
+ compactionEntryId: details.compactionEntryId,
216
+ provider: details.provider,
217
+ api: details.api,
218
+ model: details.model,
219
+ });
220
+ const envelope: DebugArtifactEnvelope = {
221
+ extension: COMPACTION_EXTENSION_ID,
222
+ kind: "provider-request",
223
+ timestamp,
224
+ cwd: sessionInfo.cwd,
225
+ sessionId: sessionInfo.sessionId,
226
+ sessionFile: sessionInfo.sessionFile,
227
+ sessionDir: sessionInfo.sessionDir,
228
+ redaction: { enabled: true },
229
+ data,
230
+ };
231
+ fs.writeFileSync(filePath, `${JSON.stringify(envelope, null, 2)}\n`, { encoding: "utf8", flag: "wx" });
232
+ return filePath;
233
+ } catch {
234
+ // The replay failure path itself must never be masked by an artifact write
235
+ // error; the caller still aborts the provider request.
236
+ return undefined;
237
+ }
238
+ }