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
package/src/debug.ts CHANGED
@@ -1,238 +1,238 @@
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
- }
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
+ }