@howaboua/pi-codex-web-run 0.0.1
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/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +33 -0
- package/UPSTREAM_SYNC.md +5 -0
- package/biome.json +31 -0
- package/changelog.ts +337 -0
- package/index.ts +97 -0
- package/package.json +83 -0
- package/src/code-mode.ts +23 -0
- package/src/codex-runtime/cloudflare-cookies.ts +133 -0
- package/src/codex-runtime/config.ts +108 -0
- package/src/codex-runtime/headers.ts +33 -0
- package/src/codex-runtime/http.ts +143 -0
- package/src/codex-runtime/policy.ts +47 -0
- package/src/codex-runtime/resolve.ts +174 -0
- package/src/codex-runtime/types.ts +21 -0
- package/src/codex-runtime/urls.ts +36 -0
- package/src/contract.ts +95 -0
- package/src/execute.ts +149 -0
- package/src/render.ts +19 -0
- package/src/request.ts +44 -0
- package/src/tool.ts +103 -0
- package/tsconfig.json +7 -0
- package/upstream/LICENSE +201 -0
- package/upstream/REVISION +1 -0
- package/upstream/codex-api-endpoint/search.rs +318 -0
- package/upstream/codex-api-endpoint/search_types.rs +305 -0
- package/upstream/web-search/extension.rs +220 -0
- package/upstream/web-search/history.rs +205 -0
- package/upstream/web-search/lib.rs +7 -0
- package/upstream/web-search/output.rs +74 -0
- package/upstream/web-search/schema.rs +36 -0
- package/upstream/web-search/tool.rs +332 -0
- package/upstream/web-search/web_run_description.md +105 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
interface StoredCookie {
|
|
2
|
+
name: string;
|
|
3
|
+
value: string;
|
|
4
|
+
domain: string;
|
|
5
|
+
hostOnly: boolean;
|
|
6
|
+
path: string;
|
|
7
|
+
expiresAt?: number | undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const EXACT_HOSTS = new Set([
|
|
11
|
+
"chatgpt.com",
|
|
12
|
+
"chat.openai.com",
|
|
13
|
+
"chatgpt-staging.com",
|
|
14
|
+
]);
|
|
15
|
+
const EXACT_COOKIE_NAMES = new Set([
|
|
16
|
+
"__cf_bm",
|
|
17
|
+
"__cflb",
|
|
18
|
+
"__cfruid",
|
|
19
|
+
"__cfseq",
|
|
20
|
+
"__cfwaitingroom",
|
|
21
|
+
"_cfuvid",
|
|
22
|
+
"cf_clearance",
|
|
23
|
+
"cf_ob_info",
|
|
24
|
+
"cf_use_ob",
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
export function isChatGptCookieUrl(url: URL): boolean {
|
|
28
|
+
return url.protocol === "https:" && isChatGptHost(url.hostname);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class ChatGptCloudflareCookieStore {
|
|
32
|
+
private readonly cookies = new Map<string, StoredCookie>();
|
|
33
|
+
|
|
34
|
+
requestHeader(url: URL): string | undefined {
|
|
35
|
+
if (!isChatGptCookieUrl(url)) return undefined;
|
|
36
|
+
const now = Date.now();
|
|
37
|
+
const matches: StoredCookie[] = [];
|
|
38
|
+
for (const [key, cookie] of this.cookies) {
|
|
39
|
+
if (cookie.expiresAt !== undefined && cookie.expiresAt <= now) {
|
|
40
|
+
this.cookies.delete(key);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (
|
|
44
|
+
(cookie.hostOnly
|
|
45
|
+
? url.hostname === cookie.domain
|
|
46
|
+
: domainMatches(url.hostname, cookie.domain)) &&
|
|
47
|
+
pathMatches(url.pathname, cookie.path)
|
|
48
|
+
)
|
|
49
|
+
matches.push(cookie);
|
|
50
|
+
}
|
|
51
|
+
matches.sort((left, right) => right.path.length - left.path.length);
|
|
52
|
+
return matches.length
|
|
53
|
+
? matches.map((cookie) => cookie.name + "=" + cookie.value).join("; ")
|
|
54
|
+
: undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
storeResponse(url: URL, setCookieHeaders: readonly string[]): void {
|
|
58
|
+
if (!isChatGptCookieUrl(url)) return;
|
|
59
|
+
for (const header of setCookieHeaders) this.storeCookie(url, header);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private storeCookie(url: URL, header: string): void {
|
|
63
|
+
const parts = header.split(";");
|
|
64
|
+
const pair = parts.shift()?.trim();
|
|
65
|
+
const separator = pair?.indexOf("=") ?? -1;
|
|
66
|
+
if (!pair || separator <= 0) return;
|
|
67
|
+
const name = pair.slice(0, separator).trim();
|
|
68
|
+
if (!isAllowedCookieName(name)) return;
|
|
69
|
+
const value = pair.slice(separator + 1).trim();
|
|
70
|
+
let domain = url.hostname;
|
|
71
|
+
let hostOnly = true;
|
|
72
|
+
let path = "/";
|
|
73
|
+
let expiresAt: number | undefined;
|
|
74
|
+
for (const part of parts) {
|
|
75
|
+
const [rawName, ...rawValue] = part.trim().split("=");
|
|
76
|
+
const attribute = rawName?.toLowerCase();
|
|
77
|
+
const attributeValue = rawValue.join("=").trim();
|
|
78
|
+
if (attribute === "domain" && attributeValue) {
|
|
79
|
+
const candidate = attributeValue.replace(/^\./, "").toLowerCase();
|
|
80
|
+
if (
|
|
81
|
+
!isAllowedCookieDomain(candidate) ||
|
|
82
|
+
!domainMatches(url.hostname, candidate)
|
|
83
|
+
)
|
|
84
|
+
return;
|
|
85
|
+
domain = candidate;
|
|
86
|
+
hostOnly = false;
|
|
87
|
+
} else if (attribute === "path" && attributeValue.startsWith("/")) {
|
|
88
|
+
path = attributeValue;
|
|
89
|
+
} else if (attribute === "max-age" && /^-?\d+$/.test(attributeValue)) {
|
|
90
|
+
expiresAt = Date.now() + Number(attributeValue) * 1000;
|
|
91
|
+
} else if (attribute === "expires" && attributeValue) {
|
|
92
|
+
const parsed = Date.parse(attributeValue);
|
|
93
|
+
if (Number.isFinite(parsed)) expiresAt = parsed;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const key = [domain, path, name, hostOnly ? "host" : "domain"].join("\n");
|
|
97
|
+
if (!value || (expiresAt !== undefined && expiresAt <= Date.now())) {
|
|
98
|
+
this.cookies.delete(key);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
this.cookies.set(key, { name, value, domain, hostOnly, path, expiresAt });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function isChatGptHost(host: string): boolean {
|
|
106
|
+
const normalized = host.toLowerCase();
|
|
107
|
+
return (
|
|
108
|
+
EXACT_HOSTS.has(normalized) ||
|
|
109
|
+
normalized.endsWith(".chatgpt.com") ||
|
|
110
|
+
normalized.endsWith(".chatgpt-staging.com")
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isAllowedCookieName(name: string): boolean {
|
|
115
|
+
return EXACT_COOKIE_NAMES.has(name) || name.startsWith("cf_chl_");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function isAllowedCookieDomain(domain: string): boolean {
|
|
119
|
+
return domain === "openai.com" || isChatGptHost(domain);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function domainMatches(host: string, domain: string): boolean {
|
|
123
|
+
return host === domain || host.endsWith("." + domain);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function pathMatches(requestPath: string, cookiePath: string): boolean {
|
|
127
|
+
return (
|
|
128
|
+
requestPath === cookiePath ||
|
|
129
|
+
requestPath.startsWith(
|
|
130
|
+
cookiePath.endsWith("/") ? cookiePath : cookiePath + "/",
|
|
131
|
+
)
|
|
132
|
+
);
|
|
133
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
|
|
6
|
+
export interface CodexToolRouteConfig {
|
|
7
|
+
providers: Record<string, Record<string, string>>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface CodexToolRouteConfigInput {
|
|
11
|
+
providers?: unknown;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function codexToolRouteConfigPath(): string {
|
|
15
|
+
const agentDir =
|
|
16
|
+
process.env["PI_CODING_AGENT_DIR"]?.trim() ||
|
|
17
|
+
join(homedir(), ".pi", "agent");
|
|
18
|
+
return join(agentDir, "pi-codex-tools.json");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function nonEmptyName(value: unknown, field: string): string {
|
|
22
|
+
if (typeof value !== "string" || !value.trim())
|
|
23
|
+
throw new Error(field + " must be a non-empty string");
|
|
24
|
+
return value.trim();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function normalizeCodexToolRouteConfig(
|
|
28
|
+
value: unknown,
|
|
29
|
+
): CodexToolRouteConfig {
|
|
30
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
31
|
+
throw new Error("pi-codex-tools config must be an object");
|
|
32
|
+
const input = value as CodexToolRouteConfigInput;
|
|
33
|
+
const rawProviders = input.providers ?? {};
|
|
34
|
+
if (
|
|
35
|
+
!rawProviders ||
|
|
36
|
+
typeof rawProviders !== "object" ||
|
|
37
|
+
Array.isArray(rawProviders)
|
|
38
|
+
)
|
|
39
|
+
throw new Error("pi-codex-tools providers must be an object");
|
|
40
|
+
const providers: Record<string, Record<string, string>> = Object.create(null);
|
|
41
|
+
for (const [provider, rawModels] of Object.entries(rawProviders)) {
|
|
42
|
+
const providerName = nonEmptyName(
|
|
43
|
+
provider,
|
|
44
|
+
"pi-codex-tools provider name",
|
|
45
|
+
).toLowerCase();
|
|
46
|
+
if (!rawModels || typeof rawModels !== "object" || Array.isArray(rawModels))
|
|
47
|
+
throw new Error(
|
|
48
|
+
"pi-codex-tools provider " + providerName + " must be an object",
|
|
49
|
+
);
|
|
50
|
+
const models: Record<string, string> = Object.create(null);
|
|
51
|
+
for (const [canonical, alias] of Object.entries(rawModels)) {
|
|
52
|
+
models[
|
|
53
|
+
nonEmptyName(canonical, "pi-codex-tools model name").toLowerCase()
|
|
54
|
+
] = nonEmptyName(alias, "pi-codex-tools model alias");
|
|
55
|
+
}
|
|
56
|
+
providers[providerName] = models;
|
|
57
|
+
}
|
|
58
|
+
return { providers };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function readCodexToolRouteConfig(
|
|
62
|
+
path = codexToolRouteConfigPath(),
|
|
63
|
+
): CodexToolRouteConfig {
|
|
64
|
+
let source: string;
|
|
65
|
+
try {
|
|
66
|
+
source = readFileSync(path, "utf8");
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (
|
|
69
|
+
error &&
|
|
70
|
+
typeof error === "object" &&
|
|
71
|
+
"code" in error &&
|
|
72
|
+
error.code === "ENOENT"
|
|
73
|
+
)
|
|
74
|
+
return { providers: Object.create(null) };
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
return normalizeCodexToolRouteConfig(JSON.parse(source));
|
|
79
|
+
} catch (error) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
"Invalid pi-codex-tools config at " +
|
|
82
|
+
path +
|
|
83
|
+
": " +
|
|
84
|
+
(error instanceof Error ? error.message : String(error)),
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function isCodexToolRoute(
|
|
90
|
+
config: CodexToolRouteConfig,
|
|
91
|
+
model: ExtensionContext["model"],
|
|
92
|
+
): boolean {
|
|
93
|
+
const provider = model?.provider?.trim().toLowerCase();
|
|
94
|
+
return Boolean(provider && Object.hasOwn(config.providers, provider));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function resolveCodexToolModel(
|
|
98
|
+
config: CodexToolRouteConfig,
|
|
99
|
+
model: ExtensionContext["model"],
|
|
100
|
+
canonicalModel: string,
|
|
101
|
+
): string {
|
|
102
|
+
const provider = model?.provider?.trim().toLowerCase();
|
|
103
|
+
const models =
|
|
104
|
+
provider && Object.hasOwn(config.providers, provider)
|
|
105
|
+
? config.providers[provider]
|
|
106
|
+
: undefined;
|
|
107
|
+
return models?.[canonicalModel.trim().toLowerCase()] || canonicalModel;
|
|
108
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { CODEX_TOOL_ORIGINATOR, type CodexToolProvider } from "./types.js";
|
|
2
|
+
|
|
3
|
+
export function codexToolProviderHeaders(provider: CodexToolProvider): Headers {
|
|
4
|
+
const headers = new Headers();
|
|
5
|
+
headers.set("Authorization", "Bearer " + provider.token);
|
|
6
|
+
headers.set("ChatGPT-Account-ID", provider.accountId);
|
|
7
|
+
headers.set("originator", CODEX_TOOL_ORIGINATOR);
|
|
8
|
+
headers.set("User-Agent", codexWebRunUserAgent(CODEX_TOOL_ORIGINATOR));
|
|
9
|
+
headers.set("version", "0.0.0");
|
|
10
|
+
headers.set("content-type", "application/json");
|
|
11
|
+
return headers;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function codexWebRunUserAgent(
|
|
15
|
+
originator: string = CODEX_TOOL_ORIGINATOR,
|
|
16
|
+
): string {
|
|
17
|
+
const platform =
|
|
18
|
+
process.platform === "darwin"
|
|
19
|
+
? "Mac OS"
|
|
20
|
+
: process.platform === "win32"
|
|
21
|
+
? "Windows"
|
|
22
|
+
: process.platform === "linux"
|
|
23
|
+
? "Linux"
|
|
24
|
+
: process.platform;
|
|
25
|
+
const arch = process.arch === "arm64" ? "arm64" : process.arch;
|
|
26
|
+
const terminal =
|
|
27
|
+
process.env["TERM_PROGRAM"]?.trim() ||
|
|
28
|
+
process.env["TERM"]?.trim() ||
|
|
29
|
+
"unknown";
|
|
30
|
+
return (
|
|
31
|
+
originator + "/0.0.0 (" + platform + " unknown; " + arch + ") " + terminal
|
|
32
|
+
);
|
|
33
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// @ts-expect-error proxy-from-env ships no declarations.
|
|
2
|
+
import { getProxyForUrl } from "proxy-from-env";
|
|
3
|
+
import { fetch, ProxyAgent } from "undici";
|
|
4
|
+
import {
|
|
5
|
+
ChatGptCloudflareCookieStore,
|
|
6
|
+
isChatGptCookieUrl,
|
|
7
|
+
} from "./cloudflare-cookies.js";
|
|
8
|
+
|
|
9
|
+
const DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
|
|
10
|
+
const MAX_REDIRECTS = 10;
|
|
11
|
+
const cloudflareCookies = new ChatGptCloudflareCookieStore();
|
|
12
|
+
|
|
13
|
+
export interface CodexToolHttpResponse {
|
|
14
|
+
status: number;
|
|
15
|
+
statusText: string;
|
|
16
|
+
headers: Headers;
|
|
17
|
+
text: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function fetchCodexTool(
|
|
21
|
+
url: string,
|
|
22
|
+
options: {
|
|
23
|
+
method?: string;
|
|
24
|
+
headers?: Headers;
|
|
25
|
+
body?: string;
|
|
26
|
+
signal?: AbortSignal | null;
|
|
27
|
+
maxResponseBytes?: number;
|
|
28
|
+
},
|
|
29
|
+
): Promise<CodexToolHttpResponse> {
|
|
30
|
+
const proxy = getProxyForUrl(url);
|
|
31
|
+
const dispatcher = proxy ? new ProxyAgent(proxy) : undefined;
|
|
32
|
+
let currentUrl = new URL(url);
|
|
33
|
+
let method = options.method;
|
|
34
|
+
let body = options.body;
|
|
35
|
+
const baseHeaders = new Headers(options.headers);
|
|
36
|
+
try {
|
|
37
|
+
for (let redirects = 0; ; redirects += 1) {
|
|
38
|
+
const chatGptRequest = isChatGptCookieUrl(currentUrl);
|
|
39
|
+
const headers = new Headers(baseHeaders);
|
|
40
|
+
const cookieHeader = cloudflareCookies.requestHeader(currentUrl);
|
|
41
|
+
if (cookieHeader) headers.set("cookie", cookieHeader);
|
|
42
|
+
const response = await fetch(currentUrl, {
|
|
43
|
+
...(method ? { method } : {}),
|
|
44
|
+
headers,
|
|
45
|
+
...(body === undefined ? {} : { body }),
|
|
46
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
47
|
+
...(dispatcher ? { dispatcher } : {}),
|
|
48
|
+
redirect: chatGptRequest ? "manual" : "follow",
|
|
49
|
+
});
|
|
50
|
+
if (chatGptRequest)
|
|
51
|
+
cloudflareCookies.storeResponse(
|
|
52
|
+
currentUrl,
|
|
53
|
+
response.headers.getSetCookie(),
|
|
54
|
+
);
|
|
55
|
+
const location = redirectLocation(
|
|
56
|
+
response.status,
|
|
57
|
+
response.headers.get("location"),
|
|
58
|
+
);
|
|
59
|
+
if (!location || !chatGptRequest) {
|
|
60
|
+
return {
|
|
61
|
+
status: response.status,
|
|
62
|
+
statusText: response.statusText,
|
|
63
|
+
headers: response.headers as unknown as Headers,
|
|
64
|
+
text: await readBoundedText(
|
|
65
|
+
response,
|
|
66
|
+
options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
|
|
67
|
+
),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (redirects >= MAX_REDIRECTS) {
|
|
71
|
+
await response.body?.cancel();
|
|
72
|
+
throw new Error(
|
|
73
|
+
"Codex tool request exceeded " + MAX_REDIRECTS + " redirects",
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
const nextUrl = new URL(location, currentUrl);
|
|
77
|
+
if (!isChatGptCookieUrl(nextUrl)) {
|
|
78
|
+
await response.body?.cancel();
|
|
79
|
+
throw new Error(
|
|
80
|
+
"Codex tool request refused redirect outside ChatGPT: " +
|
|
81
|
+
nextUrl.origin,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
if (nextUrl.origin !== currentUrl.origin) {
|
|
85
|
+
baseHeaders.delete("authorization");
|
|
86
|
+
baseHeaders.delete("chatgpt-account-id");
|
|
87
|
+
}
|
|
88
|
+
if (
|
|
89
|
+
response.status === 303 ||
|
|
90
|
+
((response.status === 301 || response.status === 302) &&
|
|
91
|
+
method?.toUpperCase() === "POST")
|
|
92
|
+
) {
|
|
93
|
+
method = "GET";
|
|
94
|
+
body = undefined;
|
|
95
|
+
baseHeaders.delete("content-type");
|
|
96
|
+
}
|
|
97
|
+
await response.body?.cancel();
|
|
98
|
+
currentUrl = nextUrl;
|
|
99
|
+
}
|
|
100
|
+
} finally {
|
|
101
|
+
await dispatcher?.close();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function redirectLocation(
|
|
106
|
+
status: number,
|
|
107
|
+
location: string | null,
|
|
108
|
+
): string | undefined {
|
|
109
|
+
return location && [301, 302, 303, 307, 308].includes(status)
|
|
110
|
+
? location
|
|
111
|
+
: undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function readBoundedText(
|
|
115
|
+
response: Awaited<ReturnType<typeof fetch>>,
|
|
116
|
+
maxBytes: number,
|
|
117
|
+
): Promise<string> {
|
|
118
|
+
const contentLength = Number(response.headers.get("content-length"));
|
|
119
|
+
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
|
|
120
|
+
await response.body?.cancel();
|
|
121
|
+
throw new Error("Codex tool response exceeded " + maxBytes + " bytes");
|
|
122
|
+
}
|
|
123
|
+
if (!response.body) return "";
|
|
124
|
+
const reader = response.body.getReader();
|
|
125
|
+
const decoder = new TextDecoder();
|
|
126
|
+
let total = 0;
|
|
127
|
+
let text = "";
|
|
128
|
+
try {
|
|
129
|
+
while (true) {
|
|
130
|
+
const chunk = await reader.read();
|
|
131
|
+
if (chunk.done) break;
|
|
132
|
+
total += chunk.value.byteLength;
|
|
133
|
+
if (total > maxBytes) {
|
|
134
|
+
await reader.cancel();
|
|
135
|
+
throw new Error("Codex tool response exceeded " + maxBytes + " bytes");
|
|
136
|
+
}
|
|
137
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
138
|
+
}
|
|
139
|
+
return text + decoder.decode();
|
|
140
|
+
} finally {
|
|
141
|
+
reader.releaseLock();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionContext,
|
|
4
|
+
} from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import type { CodexToolProviderResolver } from "../contract.js";
|
|
6
|
+
import type { CodexToolProvider } from "./types.js";
|
|
7
|
+
|
|
8
|
+
const CONFIGURED_PROVIDER_CHANNEL =
|
|
9
|
+
"@howaboua/pi-codex-conversion.configured-provider/v1";
|
|
10
|
+
const PROVIDER_RESOLVER_CHANNEL =
|
|
11
|
+
"@howaboua/pi-codex-conversion.provider-resolver/v1";
|
|
12
|
+
|
|
13
|
+
interface ConfiguredProviderRequest {
|
|
14
|
+
model: ExtensionContext["model"];
|
|
15
|
+
allow(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface ProviderResolverRequest {
|
|
19
|
+
use(resolver: CodexToolProviderResolver): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isConfiguredCodexToolProvider(
|
|
23
|
+
pi: ExtensionAPI,
|
|
24
|
+
model: ExtensionContext["model"],
|
|
25
|
+
): boolean {
|
|
26
|
+
let allowed = false;
|
|
27
|
+
pi.events.emit(CONFIGURED_PROVIDER_CHANNEL, {
|
|
28
|
+
model,
|
|
29
|
+
allow() {
|
|
30
|
+
allowed = true;
|
|
31
|
+
},
|
|
32
|
+
} satisfies ConfiguredProviderRequest);
|
|
33
|
+
return allowed;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function resolveHostedCodexToolProvider(
|
|
37
|
+
pi: ExtensionAPI,
|
|
38
|
+
ctx: ExtensionContext,
|
|
39
|
+
): Promise<CodexToolProvider | undefined> {
|
|
40
|
+
let resolver: CodexToolProviderResolver | undefined;
|
|
41
|
+
pi.events.emit(PROVIDER_RESOLVER_CHANNEL, {
|
|
42
|
+
use(candidate) {
|
|
43
|
+
resolver ??= candidate;
|
|
44
|
+
},
|
|
45
|
+
} satisfies ProviderResolverRequest);
|
|
46
|
+
return resolver?.(ctx);
|
|
47
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import type { Model, ProviderHeaders } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import {
|
|
4
|
+
type AllowConfiguredCodexToolProvider,
|
|
5
|
+
CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE,
|
|
6
|
+
type CodexToolProvider,
|
|
7
|
+
OPENAI_CODEX_PROVIDER,
|
|
8
|
+
} from "./types.js";
|
|
9
|
+
import {
|
|
10
|
+
resolveCodexApiProviderBaseUrl,
|
|
11
|
+
resolveCodexResponsesUrl,
|
|
12
|
+
resolveCodexSearchUrl,
|
|
13
|
+
} from "./urls.js";
|
|
14
|
+
|
|
15
|
+
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
|
|
16
|
+
const PREFERRED_MODELS = [
|
|
17
|
+
"gpt-5.6-luna",
|
|
18
|
+
"gpt-5.6-terra",
|
|
19
|
+
"gpt-5.6-sol",
|
|
20
|
+
"gpt-5.5",
|
|
21
|
+
"gpt-5.4-mini",
|
|
22
|
+
"gpt-5.3-codex-spark",
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
function isOpenAICodexModel(
|
|
26
|
+
model: Partial<Model<any>> | null | undefined,
|
|
27
|
+
): boolean {
|
|
28
|
+
return (model?.provider ?? "").trim().toLowerCase() === OPENAI_CODEX_PROVIDER;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isCodexTransportModel(
|
|
32
|
+
model: Partial<Model<any>> | null | undefined,
|
|
33
|
+
isConfiguredCodexTransport?: AllowConfiguredCodexToolProvider,
|
|
34
|
+
): boolean {
|
|
35
|
+
return Boolean(
|
|
36
|
+
model &&
|
|
37
|
+
(isOpenAICodexModel(model) ||
|
|
38
|
+
(model.api ?? "").trim().toLowerCase() === "openai-codex-responses" ||
|
|
39
|
+
isConfiguredCodexTransport?.(model as ExtensionContext["model"])),
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isResponsesModel(model: ExtensionContext["model"]): boolean {
|
|
44
|
+
return Boolean(model?.api?.includes("responses"));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function headerValue(
|
|
48
|
+
headers: ProviderHeaders | undefined,
|
|
49
|
+
name: string,
|
|
50
|
+
): string | undefined {
|
|
51
|
+
if (!headers) return undefined;
|
|
52
|
+
const lowerName = name.toLowerCase();
|
|
53
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
54
|
+
if (key.toLowerCase() === lowerName)
|
|
55
|
+
return typeof value === "string" ? value : undefined;
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function extractAccountId(token: string): string {
|
|
61
|
+
try {
|
|
62
|
+
const payload = token.split(".")[1];
|
|
63
|
+
if (!payload) throw new Error("Invalid token");
|
|
64
|
+
const claims = JSON.parse(
|
|
65
|
+
Buffer.from(payload, "base64").toString("utf8"),
|
|
66
|
+
) as Record<string, unknown>;
|
|
67
|
+
const auth = claims[JWT_CLAIM_PATH];
|
|
68
|
+
const accountId =
|
|
69
|
+
auth && typeof auth === "object"
|
|
70
|
+
? (auth as Record<string, unknown>)["chatgpt_account_id"]
|
|
71
|
+
: undefined;
|
|
72
|
+
if (typeof accountId !== "string" || !accountId)
|
|
73
|
+
throw new Error("No account ID in token");
|
|
74
|
+
return accountId;
|
|
75
|
+
} catch {
|
|
76
|
+
throw new Error("Failed to extract accountId from token");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function resolveOpenAICodexAuthModel(
|
|
81
|
+
ctx: ExtensionContext,
|
|
82
|
+
): Model<any> | undefined {
|
|
83
|
+
const registry = ctx.modelRegistry as {
|
|
84
|
+
find?: (provider: string, modelId: string) => Model<any> | undefined;
|
|
85
|
+
getAvailable?: () => Model<any>[];
|
|
86
|
+
getAll?: () => Model<any>[];
|
|
87
|
+
};
|
|
88
|
+
const usable = (model: ExtensionContext["model"]): model is Model<any> =>
|
|
89
|
+
isOpenAICodexModel(model) && isResponsesModel(model);
|
|
90
|
+
const currentId = ctx.model?.id;
|
|
91
|
+
const direct = currentId
|
|
92
|
+
? registry.find?.(OPENAI_CODEX_PROVIDER, currentId)
|
|
93
|
+
: undefined;
|
|
94
|
+
if (usable(direct)) return direct;
|
|
95
|
+
const preferred = PREFERRED_MODELS.map((id) =>
|
|
96
|
+
registry.find?.(OPENAI_CODEX_PROVIDER, id),
|
|
97
|
+
).find(usable);
|
|
98
|
+
if (preferred) return preferred;
|
|
99
|
+
return (
|
|
100
|
+
registry.getAvailable?.().find(usable) ?? registry.getAll?.().find(usable)
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function resolveAuthModel(
|
|
105
|
+
ctx: ExtensionContext,
|
|
106
|
+
allowConfiguredProvider?: AllowConfiguredCodexToolProvider,
|
|
107
|
+
isConfiguredCodexTransport?: AllowConfiguredCodexToolProvider,
|
|
108
|
+
): Model<any> {
|
|
109
|
+
if (isConfiguredCodexTransport?.(ctx.model)) return ctx.model as Model<any>;
|
|
110
|
+
if (isCodexTransportModel(ctx.model) && isResponsesModel(ctx.model))
|
|
111
|
+
return ctx.model as Model<any>;
|
|
112
|
+
if (isResponsesModel(ctx.model) && allowConfiguredProvider?.(ctx.model))
|
|
113
|
+
return ctx.model as Model<any>;
|
|
114
|
+
const fallback = resolveOpenAICodexAuthModel(ctx);
|
|
115
|
+
if (fallback) return fallback;
|
|
116
|
+
throw new Error(
|
|
117
|
+
CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE +
|
|
118
|
+
"; run /login openai-codex or select an OpenAI Codex-compatible provider",
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function resolveConfiguredResponsesUrl(
|
|
123
|
+
modelBaseUrl: string | undefined,
|
|
124
|
+
): string {
|
|
125
|
+
const base = modelBaseUrl?.trim().replace(/\/+$/, "");
|
|
126
|
+
if (!base)
|
|
127
|
+
throw new Error("Configured Responses provider is missing a base URL");
|
|
128
|
+
return base.endsWith("/responses") ? base : base + "/responses";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function resolveCodexToolProvider(
|
|
132
|
+
ctx: ExtensionContext,
|
|
133
|
+
allowConfiguredProvider?: AllowConfiguredCodexToolProvider,
|
|
134
|
+
isConfiguredCodexTransport?: AllowConfiguredCodexToolProvider,
|
|
135
|
+
): Promise<CodexToolProvider> {
|
|
136
|
+
const model = resolveAuthModel(
|
|
137
|
+
ctx,
|
|
138
|
+
allowConfiguredProvider,
|
|
139
|
+
isConfiguredCodexTransport,
|
|
140
|
+
);
|
|
141
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
142
|
+
if (!auth.ok) throw new Error(auth.error);
|
|
143
|
+
const resolvedBaseUrl = auth.baseUrl ?? model.baseUrl;
|
|
144
|
+
const codexTransport = isCodexTransportModel(
|
|
145
|
+
model,
|
|
146
|
+
isConfiguredCodexTransport,
|
|
147
|
+
);
|
|
148
|
+
const authorization = headerValue(auth.headers, "Authorization")
|
|
149
|
+
?.match(/^Bearer\s+(.+)$/i)?.[1]
|
|
150
|
+
?.trim();
|
|
151
|
+
const token = codexTransport
|
|
152
|
+
? (auth.apiKey ?? authorization)
|
|
153
|
+
: (authorization ?? auth.apiKey);
|
|
154
|
+
if (!token) throw new Error(CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE);
|
|
155
|
+
const baseUrl = codexTransport
|
|
156
|
+
? resolveCodexApiProviderBaseUrl(resolvedBaseUrl)
|
|
157
|
+
: resolvedBaseUrl?.trim().replace(/\/+$/, "");
|
|
158
|
+
if (!baseUrl)
|
|
159
|
+
throw new Error("Configured Responses provider is missing a base URL");
|
|
160
|
+
const responsesUrl = codexTransport
|
|
161
|
+
? resolveCodexResponsesUrl(baseUrl)
|
|
162
|
+
: resolveConfiguredResponsesUrl(baseUrl);
|
|
163
|
+
return {
|
|
164
|
+
route: codexTransport ? "openai-codex" : "configured-responses",
|
|
165
|
+
baseUrl,
|
|
166
|
+
responsesUrl,
|
|
167
|
+
searchUrl: resolveCodexSearchUrl(responsesUrl),
|
|
168
|
+
model: model.id,
|
|
169
|
+
token,
|
|
170
|
+
accountId:
|
|
171
|
+
headerValue(auth.headers, "chatgpt-account-id") ??
|
|
172
|
+
(codexTransport ? extractAccountId(token) : ""),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
export const CODEX_TOOL_PROVIDER_UNSUPPORTED_MESSAGE =
|
|
4
|
+
"Codex-backed tool requires an OpenAI Codex-compatible Responses provider or /login openai-codex";
|
|
5
|
+
export const CODEX_TOOL_ORIGINATOR = "codex_cli_rs";
|
|
6
|
+
export const OPENAI_CODEX_PROVIDER = "openai-codex";
|
|
7
|
+
export const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
|
|
8
|
+
|
|
9
|
+
export interface CodexToolProvider {
|
|
10
|
+
route: "openai-codex" | "configured-responses";
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
responsesUrl: string;
|
|
13
|
+
searchUrl: string;
|
|
14
|
+
model: string | undefined;
|
|
15
|
+
token: string;
|
|
16
|
+
accountId: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type AllowConfiguredCodexToolProvider = (
|
|
20
|
+
model: ExtensionContext["model"],
|
|
21
|
+
) => boolean;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { DEFAULT_CODEX_BASE_URL } from "./types.js";
|
|
2
|
+
|
|
3
|
+
export function resolveCodexApiProviderBaseUrl(
|
|
4
|
+
modelBaseUrl: string | undefined,
|
|
5
|
+
): string {
|
|
6
|
+
const base = modelBaseUrl?.trim() || DEFAULT_CODEX_BASE_URL;
|
|
7
|
+
const normalized = base.replace(/\/+$/, "");
|
|
8
|
+
try {
|
|
9
|
+
const url = new URL(normalized);
|
|
10
|
+
if (url.pathname === "" || url.pathname === "/")
|
|
11
|
+
return normalized + "/api/codex";
|
|
12
|
+
} catch {
|
|
13
|
+
// Keep string-only fallback below.
|
|
14
|
+
}
|
|
15
|
+
if (normalized.endsWith("/codex/responses"))
|
|
16
|
+
return normalized.slice(0, -"/responses".length);
|
|
17
|
+
if (normalized.endsWith("/codex")) return normalized;
|
|
18
|
+
if (normalized.endsWith("/backend-api") || normalized.endsWith("/api"))
|
|
19
|
+
return normalized + "/codex";
|
|
20
|
+
return normalized;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function resolveCodexResponsesUrl(providerBaseUrl: string): string {
|
|
24
|
+
const base = providerBaseUrl.replace(/\/+$/, "");
|
|
25
|
+
if (base.endsWith("/codex/responses")) return base;
|
|
26
|
+
return resolveCodexApiProviderBaseUrl(base) + "/responses";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function resolveCodexSearchUrl(providerBaseUrl: string): string {
|
|
30
|
+
const normalized = providerBaseUrl.trim().replace(/\/+$/, "");
|
|
31
|
+
if (normalized.endsWith("/alpha/search")) return normalized;
|
|
32
|
+
const base = normalized.endsWith("/responses")
|
|
33
|
+
? normalized.slice(0, -"/responses".length)
|
|
34
|
+
: resolveCodexApiProviderBaseUrl(normalized);
|
|
35
|
+
return base + "/alpha/search";
|
|
36
|
+
}
|