pi-openai-toolkit 0.14.4 → 0.14.6

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 (43) hide show
  1. package/README.md +119 -147
  2. package/README.zh.md +119 -151
  3. package/docs/internals.md +42 -21
  4. package/package.json +127 -127
  5. package/src/auto-mode/classifier.ts +165 -165
  6. package/src/auto-mode/policy.ts +146 -146
  7. package/src/auto-mode/prompt.ts +279 -279
  8. package/src/auto-mode/reviewer.ts +325 -325
  9. package/src/auto-mode/transcript.ts +133 -133
  10. package/src/auto-mode/types.ts +137 -137
  11. package/src/codex-astra/effort-planner.ts +175 -175
  12. package/src/codex-astra/extension.ts +122 -122
  13. package/src/config.ts +621 -592
  14. package/src/context-management/codex-provider.ts +260 -260
  15. package/src/context-management/history-notes.ts +357 -325
  16. package/src/context-management/messages.ts +112 -106
  17. package/src/context-management/namespace-tools.ts +426 -426
  18. package/src/context-management/tool-contract.ts +23 -23
  19. package/src/context-management/tools.ts +306 -311
  20. package/src/context-management/types.ts +168 -161
  21. package/src/context-management/window-budget.ts +83 -83
  22. package/src/context-management/window-manager.ts +60 -51
  23. package/src/context-management/window-request.ts +125 -125
  24. package/src/debug.ts +1 -1
  25. package/src/extension-runtime.ts +34 -9
  26. package/src/image-generation/artifacts.ts +237 -237
  27. package/src/image-generation/client.ts +248 -248
  28. package/src/image-generation/eligibility.ts +18 -18
  29. package/src/image-generation/extension.ts +19 -2
  30. package/src/image-generation/protocol.ts +473 -405
  31. package/src/image-generation/references.ts +194 -194
  32. package/src/image-generation/render.ts +252 -252
  33. package/src/image-generation/service.ts +249 -243
  34. package/src/image-generation/types.ts +189 -184
  35. package/src/model-scope.ts +17 -17
  36. package/src/provider-headers.ts +23 -23
  37. package/src/responses-headers.ts +173 -108
  38. package/src/runtime.ts +513 -477
  39. package/src/types.ts +11 -0
  40. package/src/web-search/extension.ts +80 -80
  41. package/src/web-search/payload.ts +96 -96
  42. package/src/web-search/prompt.ts +20 -20
  43. package/src/web-search/types.ts +45 -45
@@ -1,108 +1,173 @@
1
- import type { ProviderHeaders } from "@earendil-works/pi-ai";
2
- import { mergeProviderHeaders } from "./provider-headers";
3
-
4
- export type ResponsesHeaderRuntime = {
5
- api: string;
6
- apiKey: string;
7
- headers?: ProviderHeaders;
8
- sessionId?: string;
9
- currentModel: {
10
- headers?: ProviderHeaders;
11
- };
12
- };
13
-
14
- function isRecord(value: unknown): value is Record<string, unknown> {
15
- return !!value && typeof value === "object" && !Array.isArray(value);
16
- }
17
-
18
- function decodeJwtPayload(token: string): Record<string, unknown> | undefined {
19
- const parts = token.split(".");
20
- if (parts.length !== 3) return undefined;
21
- try {
22
- const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8")) as unknown;
23
- return isRecord(payload) ? payload : undefined;
24
- } catch {
25
- return undefined;
26
- }
27
- }
28
-
29
- function extractCodexAccountId(token: string): string | undefined {
30
- const authClaims = decodeJwtPayload(token)?.["https://api.openai.com/auth"];
31
- if (!isRecord(authClaims)) return undefined;
32
- const accountId = authClaims.chatgpt_account_id;
33
- return typeof accountId === "string" && accountId.trim() ? accountId.trim() : undefined;
34
- }
35
-
36
- function buildCodexUserAgent(): string {
37
- const platform = typeof process !== "undefined" ? process.platform : "browser";
38
- const arch = typeof process !== "undefined" ? process.arch : "unknown";
39
- return `pi (${platform}; ${arch})`;
40
- }
41
-
42
- /**
43
- * The Codex backend version-gates model availability on the `version` header
44
- * (the pinned @openai/codex client version). `gpt-6-astra` requires >= 0.153.0;
45
- * an older or absent pin makes the SKU invisible to discovery and rejects
46
- * requests that name it. Keep this in sync with the newest gate Oh My Pi pins
47
- * in @oh-my-pi/pi-wire/codex (`CODEX_CLIENT_VERSION`).
48
- */
49
- export const CODEX_CLIENT_VERSION = "0.153.0";
50
-
51
- /** Prompt cache keys are clamped by the same host rule (`OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH`). */
52
- const CODEX_SESSION_ID_MAX_LENGTH = 64;
53
-
54
- export function clampCodexSessionId(sessionId: string | undefined): string | undefined {
55
- if (!sessionId) return undefined;
56
- const chars = Array.from(sessionId);
57
- return chars.length <= CODEX_SESSION_ID_MAX_LENGTH ? sessionId : chars.slice(0, CODEX_SESSION_ID_MAX_LENGTH).join("");
58
- }
59
-
60
- export type ResponsesHeaderOptions = {
61
- accept: string;
62
- contentType?: string;
63
- /** Conversation identity for Codex cache-affinity headers; clamped to 64 chars here. */
64
- sessionId?: string;
65
- };
66
-
67
- export function buildResponsesRequestHeaders(
68
- runtime: ResponsesHeaderRuntime,
69
- options: ResponsesHeaderOptions,
70
- ): Headers {
71
- const headers = new Headers(
72
- mergeProviderHeaders(runtime.currentModel.headers, runtime.headers),
73
- );
74
- headers.set("accept", options.accept);
75
- headers.set("content-type", options.contentType ?? "application/json");
76
- if (!headers.has("authorization")) {
77
- headers.set("authorization", `Bearer ${runtime.apiKey}`);
78
- }
79
-
80
- if (runtime.api === "openai-codex-responses") {
81
- const accountId = extractCodexAccountId(runtime.apiKey);
82
- if (accountId) headers.set("chatgpt-account-id", accountId);
83
- headers.set("originator", "pi");
84
- headers.set("user-agent", buildCodexUserAgent());
85
- headers.set("openai-beta", "responses=experimental");
86
- // Codex backend gating: a request without a new-enough `version` never
87
- // reaches model SKUs that arrived behind the gate (gpt-6-astra).
88
- headers.set("version", CODEX_CLIENT_VERSION);
89
- // Prompt-cache affinity rides on the conversation identity: the backend
90
- // keeps a conversation's cache prefix on the node that wrote it, so our
91
- // synthetic compaction requests must present the same id the live
92
- // transcript requests used, or every compact pays a full cache miss.
93
- const sessionId = clampCodexSessionId(options.sessionId ?? runtime.sessionId);
94
- if (sessionId) {
95
- // Header names match the installed host's live-request builder
96
- // (`buildSSEHeaders`: `session-id` + `x-client-request-id`) so our
97
- // synthetic requests land in the same conversation affinity group.
98
- headers.set("session-id", sessionId);
99
- headers.set("x-client-request-id", sessionId);
100
- }
101
- }
102
-
103
- return headers;
104
- }
105
-
106
- export const _responsesHeadersTest = {
107
- extractCodexAccountId,
108
- };
1
+ import type { ProviderHeaders } from "@earendil-works/pi-ai";
2
+ import { mergeProviderHeaders } from "./provider-headers";
3
+
4
+ export const CODEX_AFFINITY_SCOPE = "codex-session-v1" as const;
5
+ export const CODEX_GATEWAY_ORIGINATOR = "codex_cli_rs" as const;
6
+
7
+ /** Headers permitted from Pi/provider configuration onto the gateway hop. */
8
+ export const CODEX_GATEWAY_FORWARD_HEADERS = [
9
+ "accept",
10
+ "content-type",
11
+ "session-id",
12
+ "thread-id",
13
+ "x-parent-session-id",
14
+ "x-codex-parent-thread-id",
15
+ "x-client-request-id",
16
+ "x-codex-model",
17
+ "x-codex-affinity-scope",
18
+ "x-codex-window-id",
19
+ "x-codex-turn-metadata",
20
+ "x-codex-beta-features",
21
+ "x-openai-encrypted-tool-arguments",
22
+ "x-openai-tool-output-truncation-policy",
23
+ "x-openai-internal-codex-responses-lite",
24
+ "version",
25
+ "originator",
26
+ "user-agent",
27
+ ] as const;
28
+
29
+ const CODEX_GATEWAY_FORWARD_HEADER_SET = new Set<string>(CODEX_GATEWAY_FORWARD_HEADERS);
30
+
31
+ export function filterCodexGatewayHeaders(headers: ProviderHeaders | undefined): Record<string, string> {
32
+ const result: Record<string, string> = {};
33
+ for (const [name, value] of Object.entries(headers ?? {})) {
34
+ if (typeof value !== "string" || !CODEX_GATEWAY_FORWARD_HEADER_SET.has(name.toLowerCase())) continue;
35
+ result[name] = value;
36
+ }
37
+ return result;
38
+ }
39
+
40
+ export type CodexAffinity = {
41
+ /** Bare model id used by the gateway route selector, never provider/model. */
42
+ model: string;
43
+ scope: typeof CODEX_AFFINITY_SCOPE;
44
+ };
45
+
46
+ export type ResponsesHeaderRuntime = {
47
+ api: string;
48
+ apiKey: string;
49
+ headers?: ProviderHeaders;
50
+ sessionId?: string;
51
+ /** Opt-in gateway Codex routing metadata for synthetic requests. */
52
+ codexAffinity?: CodexAffinity;
53
+ currentModel: {
54
+ headers?: ProviderHeaders;
55
+ };
56
+ };
57
+
58
+ function isRecord(value: unknown): value is Record<string, unknown> {
59
+ return !!value && typeof value === "object" && !Array.isArray(value);
60
+ }
61
+
62
+ function decodeJwtPayload(token: string): Record<string, unknown> | undefined {
63
+ const parts = token.split(".");
64
+ if (parts.length !== 3) return undefined;
65
+ try {
66
+ const payload = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8")) as unknown;
67
+ return isRecord(payload) ? payload : undefined;
68
+ } catch {
69
+ return undefined;
70
+ }
71
+ }
72
+
73
+ function extractCodexAccountId(token: string): string | undefined {
74
+ const authClaims = decodeJwtPayload(token)?.["https://api.openai.com/auth"];
75
+ if (!isRecord(authClaims)) return undefined;
76
+ const accountId = authClaims.chatgpt_account_id;
77
+ return typeof accountId === "string" && accountId.trim() ? accountId.trim() : undefined;
78
+ }
79
+
80
+ function buildCodexUserAgent(): string {
81
+ const platform = typeof process !== "undefined" ? process.platform : "browser";
82
+ const arch = typeof process !== "undefined" ? process.arch : "unknown";
83
+ return `pi (${platform}; ${arch})`;
84
+ }
85
+
86
+ export function buildCodexCliUserAgent(version: string): string {
87
+ const platform = typeof process !== "undefined" ? process.platform : "browser";
88
+ const arch = typeof process !== "undefined" ? process.arch : "unknown";
89
+ return `codex_cli_rs/${version} (${platform}; ${arch})`;
90
+ }
91
+
92
+ /**
93
+ * The Codex backend version-gates model availability on the `version` header
94
+ * (the pinned @openai/codex client version). `gpt-6-astra` requires >= 0.153.0;
95
+ * an older or absent pin makes the SKU invisible to discovery and rejects
96
+ * requests that name it. Keep this in sync with the newest gate Oh My Pi pins
97
+ * in @oh-my-pi/pi-wire/codex (`CODEX_CLIENT_VERSION`).
98
+ */
99
+ export const CODEX_CLIENT_VERSION = "0.153.0";
100
+
101
+ /** Prompt cache keys are clamped by the same host rule (`OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH`). */
102
+ const CODEX_SESSION_ID_MAX_LENGTH = 64;
103
+
104
+ export function clampCodexSessionId(sessionId: string | undefined): string | undefined {
105
+ if (!sessionId) return undefined;
106
+ const chars = Array.from(sessionId);
107
+ return chars.length <= CODEX_SESSION_ID_MAX_LENGTH ? sessionId : chars.slice(0, CODEX_SESSION_ID_MAX_LENGTH).join("");
108
+ }
109
+
110
+ export type ResponsesHeaderOptions = {
111
+ accept: string;
112
+ contentType?: string;
113
+ /** Conversation identity for Codex cache-affinity headers; clamped to 64 chars here. */
114
+ sessionId?: string;
115
+ };
116
+
117
+ export function buildResponsesRequestHeaders(
118
+ runtime: ResponsesHeaderRuntime,
119
+ options: ResponsesHeaderOptions,
120
+ ): Headers {
121
+ const mergedHeaders = mergeProviderHeaders(runtime.currentModel.headers, runtime.headers);
122
+ const headers = new Headers(
123
+ runtime.codexAffinity ? filterCodexGatewayHeaders(mergedHeaders) : mergedHeaders,
124
+ );
125
+ headers.set("accept", options.accept);
126
+ headers.set("content-type", options.contentType ?? "application/json");
127
+ if (!headers.has("authorization")) {
128
+ headers.set("authorization", `Bearer ${runtime.apiKey}`);
129
+ }
130
+
131
+ const isNativeCodex = runtime.api === "openai-codex-responses";
132
+ const gatewayAffinity = runtime.codexAffinity;
133
+ if (isNativeCodex || gatewayAffinity) {
134
+ if (gatewayAffinity) {
135
+ // A gateway request must use the configured data-plane key, never an
136
+ // inherited OAuth/account header from the model registry.
137
+ headers.set("authorization", `Bearer ${runtime.apiKey}`);
138
+ headers.delete("chatgpt-account-id");
139
+ headers.delete("cookie");
140
+ headers.delete("x-api-key");
141
+ headers.set("originator", CODEX_GATEWAY_ORIGINATOR);
142
+ headers.set("user-agent", buildCodexCliUserAgent(CODEX_CLIENT_VERSION));
143
+ headers.set("x-codex-affinity-scope", gatewayAffinity.scope);
144
+ headers.set("x-codex-model", gatewayAffinity.model);
145
+ } else {
146
+ const accountId = extractCodexAccountId(runtime.apiKey);
147
+ if (accountId) headers.set("chatgpt-account-id", accountId);
148
+ headers.set("originator", "pi");
149
+ headers.set("user-agent", buildCodexUserAgent());
150
+ headers.set("openai-beta", "responses=experimental");
151
+ }
152
+ // Codex backend gating: a request without a new-enough `version` never
153
+ // reaches model SKUs that arrived behind the gate (gpt-6-astra).
154
+ headers.set("version", CODEX_CLIENT_VERSION);
155
+ // Prompt-cache/session affinity rides on the conversation identity. The
156
+ // gateway path also uses the bare model hint above so NEWapi can route
157
+ // context/compact requests without inspecting their body.
158
+ const sessionId = clampCodexSessionId(options.sessionId ?? runtime.sessionId);
159
+ if (sessionId) {
160
+ // Header names match the installed host's live-request builder
161
+ // (`buildSSEHeaders`: `session-id` + `x-client-request-id`) so our
162
+ // synthetic requests land in the same conversation affinity group.
163
+ headers.set("session-id", sessionId);
164
+ headers.set("x-client-request-id", sessionId);
165
+ }
166
+ }
167
+
168
+ return headers;
169
+ }
170
+
171
+ export const _responsesHeadersTest = {
172
+ extractCodexAccountId,
173
+ };