zapagent 1.14.20 → 1.14.22
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/README.md +4 -2
- package/README.zh-CN.md +2 -2
- package/package.json +1 -1
- package/src/agent-factory.ts +6 -1
- package/src/codex-auth-command.ts +44 -0
- package/src/codex-auth.ts +233 -0
- package/src/codex-provider.ts +38 -0
- package/src/config.ts +30 -6
- package/src/index.tsx +8 -0
- package/src/provider-catalog.ts +18 -2
- package/src/provider-metadata.ts +10 -1
- package/src/ui/dialog-codex-login.tsx +44 -0
- package/src/ui/dialog-config.tsx +53 -32
- package/src/ui/dialog-connect.tsx +12 -3
- package/src/ui/provider-directory.tsx +4 -2
- package/zapsdk/core/providers/openai-responses.ts +76 -6
- package/zapsdk/core/reasoning-effort.ts +48 -0
package/README.md
CHANGED
|
@@ -70,7 +70,9 @@ Interact in the terminal and follow task progress in the live browser view.
|
|
|
70
70
|
|
|
71
71
|
On first use, enter `/connect` and follow the setup prompts to connect your model service. Then describe what you want: “Read the materials in this folder, summarize the key points, and write a report.”
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
Use your model service account and API key, or select **OpenAI Codex (ChatGPT)**
|
|
74
|
+
to sign in with a ChatGPT account using OAuth. Usage and model access depend on
|
|
75
|
+
your provider/account. [Connection guide](docs/usage.md#getting-started).
|
|
74
76
|
|
|
75
77
|
Update from your terminal with `zap update` (or `zap update --yes` for unattended installation).
|
|
76
78
|
|
|
@@ -95,7 +97,7 @@ Git workspaces also require [Git](https://git-scm.com).
|
|
|
95
97
|
| Linux | [ARM64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-arm64) · [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-linux-x64) |
|
|
96
98
|
| Windows | [x64](https://github.com/JackCaow/zapagent/releases/latest/download/zap-windows-x64.exe) |
|
|
97
99
|
|
|
98
|
-
**Model configuration** — use `/model` to choose a model and `/effort` to adjust supported reasoning settings. For custom services, enter the Base URL and API key in `/connect` and select the service's API protocol; choose **OpenAI Responses** for a Responses endpoint. [Responses configuration](docs/usage.md#openai-responses-api).
|
|
100
|
+
**Model configuration** — use `/model` to choose a model and `/effort` to adjust supported reasoning settings. For custom services, enter the Base URL and API key in `/connect` and select the service's API protocol; choose **OpenAI Responses** for a Responses endpoint. [Responses configuration](docs/usage.md#openai-responses-api). Codex OAuth reads reasoning levels, descriptions and the default from the current model’s authenticated catalog. Choices are saved per model; **default** (or `/effort off`) lets the server choose. Saved capabilities remain available offline. [Terminal recording](docs/recordings/model-effort.cast).
|
|
99
101
|
|
|
100
102
|
**From source** — the repository pins Bun 1.3.14:
|
|
101
103
|
|
package/README.zh-CN.md
CHANGED
|
@@ -68,9 +68,9 @@ zap --watch
|
|
|
68
68
|
|
|
69
69
|
**3. 连接模型,描述任务**
|
|
70
70
|
|
|
71
|
-
首次使用时,输入 `/connect
|
|
71
|
+
首次使用时,输入 `/connect`,按界面引导连接你的模型服务。使用 ChatGPT 账号时,选择 **New connection → OpenAI Codex (ChatGPT)**,支持浏览器 OAuth 和设备码登录,登录后选择模型。然后直接告诉它你要完成什么,例如:“阅读这个文件夹里的资料,整理重点并生成一份报告。”
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
可以使用模型服务账号和 API Key,也可以通过 OAuth 登录 ChatGPT 账号使用 Codex;可用模型和用量取决于所选服务及账号。[连接指南](docs/usage.md#getting-started)。
|
|
74
74
|
|
|
75
75
|
在终端执行 `zap update` 检查并确认更新;脚本中可用 `zap update --yes` 跳过交互确认。
|
|
76
76
|
|
package/package.json
CHANGED
package/src/agent-factory.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { modelCanonicalIds } from "./provider-metadata.js"
|
|
2
|
+
import { getCodexCredentials } from "./codex-auth.js"
|
|
2
3
|
import { serviceTools } from "../zapsdk/services/tools.js"
|
|
3
4
|
// Builds the per-turn agent objects (provider, registry, executor) from
|
|
4
5
|
// the app config. Split out of App.tsx — pure factory, no React state.
|
|
@@ -118,7 +119,11 @@ export function buildAgentObjects(
|
|
|
118
119
|
"x-stainless-runtime-version": null,
|
|
119
120
|
} as unknown as Record<string, string>
|
|
120
121
|
: undefined
|
|
121
|
-
const rawProvider =
|
|
122
|
+
const rawProvider = active?.authMode === "codex-oauth"
|
|
123
|
+
? new OpenAIResponsesProvider({ model, codex: { getCredentials: getCodexCredentials, reasoningByModel: active.reasoningByModel, effortByModel: active.effortByModel },
|
|
124
|
+
canonicalModelIds: modelCanonicalIds(active), supportsVision: resolveVisionSupport(active, model),
|
|
125
|
+
extraRequestParams: active.extraRequestParams, maxRequestBytes: active.maxRequestBytes })
|
|
126
|
+
: isAnthropic
|
|
122
127
|
? new AnthropicProvider({
|
|
123
128
|
maxRequestBytes: active?.maxRequestBytes,
|
|
124
129
|
canonicalModelIds: modelCanonicalIds(active),
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { join } from "node:path"
|
|
2
|
+
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
3
|
+
import { loadAppConfig, saveAppConfig } from "./config.js"
|
|
4
|
+
import { connectCodexProvider } from "./codex-provider.js"
|
|
5
|
+
import { deleteCodexCredentials, openAuthBrowser, readCodexCredentials, saveCodexCredentials,
|
|
6
|
+
startCodexBrowserLogin, startCodexDeviceLogin } from "./codex-auth.js"
|
|
7
|
+
|
|
8
|
+
export async function runCodexAuthCommand(args: string[]): Promise<number> {
|
|
9
|
+
const [action, provider, ...flags] = args
|
|
10
|
+
if (!["login", "logout", "status"].includes(action) || provider !== "codex" ||
|
|
11
|
+
flags.some(flag => flag !== "--device-code" || action !== "login")) {
|
|
12
|
+
console.error("Usage: zap auth login codex [--device-code] | zap auth logout codex | zap auth status codex")
|
|
13
|
+
return 2
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
if (action === "logout") { await deleteCodexCredentials(); console.log("Codex signed out from Zap."); return 0 }
|
|
17
|
+
if (action === "status") {
|
|
18
|
+
const credentials = readCodexCredentials()
|
|
19
|
+
console.log(credentials ? `Codex signed in${credentials.expiresAt <= Date.now() ? " (token will refresh on next request)" : ""}.` : "Codex signed out.")
|
|
20
|
+
return credentials ? 0 : 1
|
|
21
|
+
}
|
|
22
|
+
const controller = new AbortController()
|
|
23
|
+
const cancel = () => controller.abort()
|
|
24
|
+
process.once("SIGINT", cancel)
|
|
25
|
+
process.once("SIGTERM", cancel)
|
|
26
|
+
try {
|
|
27
|
+
const login = flags.includes("--device-code") ? await startCodexDeviceLogin(controller.signal) : await startCodexBrowserLogin({ signal: controller.signal })
|
|
28
|
+
console.log(`${login.instructions}\n${login.url}`)
|
|
29
|
+
openAuthBrowser(login.url)
|
|
30
|
+
const credentials = await login.complete
|
|
31
|
+
controller.signal.throwIfAborted()
|
|
32
|
+
await saveCodexCredentials(credentials, undefined, controller.signal)
|
|
33
|
+
controller.signal.throwIfAborted()
|
|
34
|
+
const path = join(getAppDataDir(), "config.json")
|
|
35
|
+
// Read after login so an in-flight TUI edit is not overwritten by an old snapshot.
|
|
36
|
+
saveAppConfig(path, connectCodexProvider(loadAppConfig(path)).config)
|
|
37
|
+
console.log("Codex connected. Open Zap and choose a model with /model.")
|
|
38
|
+
return 0
|
|
39
|
+
} finally { process.removeListener("SIGINT", cancel); process.removeListener("SIGTERM", cancel) }
|
|
40
|
+
} catch (error) {
|
|
41
|
+
console.error(error instanceof Error ? error.message : "Codex login failed.")
|
|
42
|
+
return 1
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto"
|
|
2
|
+
import { createServer } from "node:http"
|
|
3
|
+
import { mkdirSync, readFileSync, rmSync, statSync } from "node:fs"
|
|
4
|
+
import { dirname, join } from "node:path"
|
|
5
|
+
import { spawn } from "node:child_process"
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises"
|
|
7
|
+
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
8
|
+
import { writeFileAtomic } from "./utils/secure-write.js"
|
|
9
|
+
|
|
10
|
+
// Public native-client OAuth registration, also used by Codex CLI/OpenCode.
|
|
11
|
+
export const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
|
|
12
|
+
export const CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex"
|
|
13
|
+
const ISSUER = "https://auth.openai.com"
|
|
14
|
+
export interface CodexCredentials {
|
|
15
|
+
accessToken: string
|
|
16
|
+
refreshToken: string
|
|
17
|
+
expiresAt: number
|
|
18
|
+
accountId?: string
|
|
19
|
+
}
|
|
20
|
+
type Fetch = typeof globalThis.fetch
|
|
21
|
+
export const codexCredentialPath = () => join(getAppDataDir(), "codex-oauth.json")
|
|
22
|
+
|
|
23
|
+
export function readCodexCredentials(path = codexCredentialPath()): CodexCredentials | null {
|
|
24
|
+
let data: unknown
|
|
25
|
+
try { data = JSON.parse(readFileSync(path, "utf8")) }
|
|
26
|
+
catch (error) {
|
|
27
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null
|
|
28
|
+
throw new Error("Cannot read Codex credentials. Sign in again with /connect.")
|
|
29
|
+
}
|
|
30
|
+
const value = data as CodexCredentials | null
|
|
31
|
+
if (!value || typeof value.accessToken !== "string" || !value.accessToken ||
|
|
32
|
+
typeof value.refreshToken !== "string" || !value.refreshToken ||
|
|
33
|
+
typeof value.expiresAt !== "number" || !Number.isFinite(value.expiresAt) ||
|
|
34
|
+
(value.accountId !== undefined && typeof value.accountId !== "string")) {
|
|
35
|
+
throw new Error("Invalid Codex credentials. Sign in again with /connect.")
|
|
36
|
+
}
|
|
37
|
+
return value
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function writeCodexCredentials(value: CodexCredentials, path: string): void {
|
|
41
|
+
writeFileAtomic(path, JSON.stringify(value) + "\n", { mode: 0o600 })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function saveCodexCredentials(value: CodexCredentials, path = codexCredentialPath(), signal?: AbortSignal): Promise<void> {
|
|
45
|
+
// An explicit login may replace a previous login; it still serializes with logout.
|
|
46
|
+
await withCredentialLock(path, signal, () => writeCodexCredentials(value, path))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function deleteCodexCredentials(path = codexCredentialPath()): Promise<void> {
|
|
50
|
+
// Wait for in-flight refresh to commit before deleting. Once logout returns,
|
|
51
|
+
// that refresh can no longer recreate the file behind the user's back.
|
|
52
|
+
await withCredentialLock(path, undefined, () => rmSync(path, { force: true }))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function accountId(token: unknown): string | undefined {
|
|
56
|
+
if (typeof token !== "string") return
|
|
57
|
+
try {
|
|
58
|
+
// Claims are routing metadata, not a locally verified authentication proof.
|
|
59
|
+
const claims = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString())
|
|
60
|
+
const id = claims["https://api.openai.com/auth"]?.chatgpt_account_id ?? claims.chatgpt_account_id
|
|
61
|
+
return typeof id === "string" ? id : undefined
|
|
62
|
+
} catch { return undefined }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function tokenRequest(params: Record<string, string>, signal?: AbortSignal,
|
|
66
|
+
fetcher: Fetch = fetch, previous?: CodexCredentials): Promise<CodexCredentials> {
|
|
67
|
+
const response = await fetcher(`${ISSUER}/oauth/token`, {
|
|
68
|
+
method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
69
|
+
body: new URLSearchParams({ client_id: CODEX_CLIENT_ID, ...params }),
|
|
70
|
+
signal: AbortSignal.any([AbortSignal.timeout(15_000), ...(signal ? [signal] : [])]),
|
|
71
|
+
redirect: "error",
|
|
72
|
+
})
|
|
73
|
+
// Do not include response bodies: auth errors can echo credentials/codes.
|
|
74
|
+
if (!response.ok) throw new Error(`Codex authentication failed (HTTP ${response.status}). Sign in again with /connect.`)
|
|
75
|
+
const data = await response.json() as Record<string, unknown>
|
|
76
|
+
if (typeof data.access_token !== "string" || !data.access_token ||
|
|
77
|
+
(!previous && (typeof data.refresh_token !== "string" || !data.refresh_token))) {
|
|
78
|
+
throw new Error("Codex returned an invalid token response.")
|
|
79
|
+
}
|
|
80
|
+
const seconds = typeof data.expires_in === "number" && Number.isFinite(data.expires_in) && data.expires_in > 0 ? data.expires_in : 3600
|
|
81
|
+
return { accessToken: data.access_token,
|
|
82
|
+
refreshToken: typeof data.refresh_token === "string" && data.refresh_token ? data.refresh_token : previous!.refreshToken,
|
|
83
|
+
expiresAt: Date.now() + seconds * 1000,
|
|
84
|
+
accountId: accountId(data.id_token) ?? accountId(data.access_token) ?? previous?.accountId }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Every credential mutation uses this lock, including explicit login/logout. */
|
|
88
|
+
async function withCredentialLock<T>(path: string, signal: AbortSignal | undefined, action: () => T | Promise<T>): Promise<T> {
|
|
89
|
+
const lock = `${path}.lock`
|
|
90
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
91
|
+
const started = Date.now()
|
|
92
|
+
for (;;) {
|
|
93
|
+
signal?.throwIfAborted()
|
|
94
|
+
try { mkdirSync(lock, { mode: 0o700 }); break }
|
|
95
|
+
catch (error) {
|
|
96
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
|
|
97
|
+
// Network refreshes are bounded to 15s; recover a lock left by a crash.
|
|
98
|
+
try { if (Date.now() - statSync(lock).mtimeMs > 60_000) rmSync(lock, { recursive: true, force: true }) }
|
|
99
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error }
|
|
100
|
+
if (Date.now() - started > 30_000) throw new Error("Codex credential store is busy. Try again shortly.")
|
|
101
|
+
await delay(100, undefined, { signal })
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
signal?.throwIfAborted()
|
|
106
|
+
return await action()
|
|
107
|
+
} finally { rmSync(lock, { recursive: true, force: true }) }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Serialize refreshes across Zap processes because refresh tokens rotate. */
|
|
111
|
+
export async function getCodexCredentials(signal?: AbortSignal, options: { path?: string; fetcher?: Fetch } = {}): Promise<CodexCredentials> {
|
|
112
|
+
const path = options.path ?? codexCredentialPath()
|
|
113
|
+
const current = readCodexCredentials(path)
|
|
114
|
+
if (!current) throw new Error("Codex is signed out. Sign in with /connect or zap auth login codex.")
|
|
115
|
+
if (current.expiresAt > Date.now() + 60_000) return current
|
|
116
|
+
return withCredentialLock(path, signal, async () => {
|
|
117
|
+
const latest = readCodexCredentials(path)
|
|
118
|
+
if (!latest) throw new Error("Codex is signed out. Sign in again with /connect.")
|
|
119
|
+
if (latest.expiresAt > Date.now() + 60_000) return latest
|
|
120
|
+
const next = await tokenRequest({ grant_type: "refresh_token", refresh_token: latest.refreshToken }, signal, options.fetcher, latest)
|
|
121
|
+
signal?.throwIfAborted()
|
|
122
|
+
// Detect non-cooperating/manual edits too; public login/logout use our lock.
|
|
123
|
+
if (readCodexCredentials(path)?.refreshToken !== latest.refreshToken) throw new Error("Codex login changed during refresh. Try again.")
|
|
124
|
+
writeCodexCredentials(next, path)
|
|
125
|
+
return next
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function openAuthBrowser(url: string): void {
|
|
130
|
+
const executable = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open"
|
|
131
|
+
const child = spawn(executable, process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url],
|
|
132
|
+
{ detached: true, stdio: "ignore" })
|
|
133
|
+
child.on("error", () => {}) // The UI/CLI always displays the URL as fallback.
|
|
134
|
+
child.unref()
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface CodexLogin {
|
|
138
|
+
url: string
|
|
139
|
+
instructions: string
|
|
140
|
+
complete: Promise<CodexCredentials>
|
|
141
|
+
cancel: () => void
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** PKCE + state, a loopback-only callback, and a bounded, cancellable lifetime. */
|
|
145
|
+
export async function startCodexBrowserLogin(options: {
|
|
146
|
+
signal?: AbortSignal; port?: number; fetcher?: Fetch; timeoutMs?: number
|
|
147
|
+
} = {}): Promise<CodexLogin> {
|
|
148
|
+
const controller = new AbortController()
|
|
149
|
+
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(options.timeoutMs ?? 5 * 60_000),
|
|
150
|
+
...(options.signal ? [options.signal] : [])])
|
|
151
|
+
signal.throwIfAborted()
|
|
152
|
+
const verifier = randomBytes(32).toString("base64url")
|
|
153
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url")
|
|
154
|
+
const state = randomBytes(32).toString("base64url")
|
|
155
|
+
let resolveCode!: (code: string) => void
|
|
156
|
+
let rejectCode!: (error: Error) => void
|
|
157
|
+
const code = new Promise<string>((resolve, reject) => { resolveCode = resolve; rejectCode = reject })
|
|
158
|
+
void code.catch(() => {})
|
|
159
|
+
let accepted = false
|
|
160
|
+
const server = createServer((request, response) => {
|
|
161
|
+
const url = new URL(request.url ?? "/", "http://localhost")
|
|
162
|
+
response.setHeader("Cache-Control", "no-store")
|
|
163
|
+
if (request.method !== "GET" || url.pathname !== "/auth/callback") { response.writeHead(404).end(); return }
|
|
164
|
+
if (url.searchParams.get("state") !== state) { response.writeHead(400).end("Invalid OAuth state."); return }
|
|
165
|
+
if (accepted) { response.writeHead(409).end("Callback already received."); return }
|
|
166
|
+
if (url.searchParams.has("error")) {
|
|
167
|
+
accepted = true
|
|
168
|
+
rejectCode(new Error("Codex authorization was declined. Please try again."))
|
|
169
|
+
response.writeHead(400).end("Authorization declined. Return to Zap.")
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
const value = url.searchParams.get("code")
|
|
173
|
+
if (!value) { response.writeHead(400).end("Missing authorization code."); return }
|
|
174
|
+
accepted = true
|
|
175
|
+
resolveCode(value)
|
|
176
|
+
response.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }).end("Authorization received. Return to Zap to finish signing in.")
|
|
177
|
+
})
|
|
178
|
+
const abort = () => { rejectCode(new DOMException("Codex login cancelled or timed out", "AbortError")); server.close() }
|
|
179
|
+
signal.addEventListener("abort", abort, { once: true })
|
|
180
|
+
try {
|
|
181
|
+
await new Promise<void>((resolve, reject) => {
|
|
182
|
+
const onError = (error: Error) => reject(error)
|
|
183
|
+
server.once("error", onError)
|
|
184
|
+
server.listen(options.port ?? 1455, "localhost", () => { server.off("error", onError); resolve() })
|
|
185
|
+
})
|
|
186
|
+
signal.throwIfAborted()
|
|
187
|
+
} catch (error) {
|
|
188
|
+
signal.removeEventListener("abort", abort); server.close()
|
|
189
|
+
if ((error as NodeJS.ErrnoException).code === "EADDRINUSE") throw new Error("Codex login needs localhost:1455. Close the other login or use device code login.")
|
|
190
|
+
throw error
|
|
191
|
+
}
|
|
192
|
+
const port = (server.address() as { port: number }).port
|
|
193
|
+
const redirect = `http://localhost:${port}/auth/callback`
|
|
194
|
+
const url = `${ISSUER}/oauth/authorize?${new URLSearchParams({
|
|
195
|
+
response_type: "code", client_id: CODEX_CLIENT_ID, redirect_uri: redirect,
|
|
196
|
+
scope: "openid profile email offline_access", code_challenge: challenge,
|
|
197
|
+
code_challenge_method: "S256", state, id_token_add_organizations: "true",
|
|
198
|
+
codex_cli_simplified_flow: "true", originator: "zap",
|
|
199
|
+
})}`
|
|
200
|
+
const complete = code.then(value => tokenRequest({ grant_type: "authorization_code", code: value,
|
|
201
|
+
redirect_uri: redirect, code_verifier: verifier }, signal, options.fetcher))
|
|
202
|
+
.finally(() => { signal.removeEventListener("abort", abort); server.close() })
|
|
203
|
+
void complete.catch(() => {})
|
|
204
|
+
return { url, instructions: "Finish signing in with ChatGPT in your browser.", complete, cancel: () => controller.abort() }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export async function startCodexDeviceLogin(signal?: AbortSignal, options: { fetcher?: Fetch; timeoutMs?: number } = {}): Promise<CodexLogin> {
|
|
208
|
+
const controller = new AbortController()
|
|
209
|
+
const bounded = AbortSignal.any([controller.signal, AbortSignal.timeout(options.timeoutMs ?? 15 * 60_000), ...(signal ? [signal] : [])])
|
|
210
|
+
const post = (path: string, body: unknown) => (options.fetcher ?? fetch)(`${ISSUER}${path}`, { method: "POST",
|
|
211
|
+
headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
|
|
212
|
+
signal: AbortSignal.any([bounded, AbortSignal.timeout(15_000)]), redirect: "error" })
|
|
213
|
+
const response = await post("/api/accounts/deviceauth/usercode", { client_id: CODEX_CLIENT_ID })
|
|
214
|
+
if (!response.ok) throw new Error(`Codex device login failed (HTTP ${response.status}).`)
|
|
215
|
+
const data = await response.json() as { device_auth_id: string; user_code: string; interval: string }
|
|
216
|
+
if (typeof data.device_auth_id !== "string" || !data.device_auth_id || typeof data.user_code !== "string" || !data.user_code) throw new Error("Invalid Codex device authorization response.")
|
|
217
|
+
const interval = Math.max(1, Math.min(60, Number(data.interval) || 5)) * 1000 + 3000
|
|
218
|
+
const complete = (async () => {
|
|
219
|
+
for (;;) {
|
|
220
|
+
await delay(interval, undefined, { signal: bounded })
|
|
221
|
+
const result = await post("/api/accounts/deviceauth/token", { device_auth_id: data.device_auth_id, user_code: data.user_code })
|
|
222
|
+
if (result.ok) {
|
|
223
|
+
const tokens = await result.json() as { authorization_code: string; code_verifier: string }
|
|
224
|
+
if (typeof tokens.authorization_code !== "string" || !tokens.authorization_code || typeof tokens.code_verifier !== "string" || !tokens.code_verifier) throw new Error("Invalid Codex device token response.")
|
|
225
|
+
return tokenRequest({ grant_type: "authorization_code", code: tokens.authorization_code,
|
|
226
|
+
code_verifier: tokens.code_verifier, redirect_uri: `${ISSUER}/deviceauth/callback` }, bounded, options.fetcher)
|
|
227
|
+
}
|
|
228
|
+
if (result.status !== 403 && result.status !== 404) throw new Error(`Codex device authorization failed (HTTP ${result.status}).`)
|
|
229
|
+
}
|
|
230
|
+
})()
|
|
231
|
+
void complete.catch(() => {})
|
|
232
|
+
return { url: `${ISSUER}/codex/device`, instructions: `Enter code: ${data.user_code}`, complete, cancel: () => controller.abort() }
|
|
233
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { CODEX_BASE_URL, getCodexCredentials } from "./codex-auth.js"
|
|
2
|
+
import { normalizeModelReasoning, type ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
|
|
3
|
+
import { VERSION } from "./version.js"
|
|
4
|
+
import { setActive, upsertProvider, type AppConfig, type Provider, type ProviderModelMetadata } from "./config.js"
|
|
5
|
+
|
|
6
|
+
/** One explicit account binding; secrets live only in codex-oauth.json. */
|
|
7
|
+
export function connectCodexProvider(config: AppConfig): { config: AppConfig; provider: Provider } {
|
|
8
|
+
const existing = config.providers.find(p => p.authMode === "codex-oauth")
|
|
9
|
+
const provider: Provider = { ...existing, id: existing?.id ?? "sp_codex_oauth", name: existing?.name ?? "OpenAI Codex (ChatGPT)",
|
|
10
|
+
baseURL: CODEX_BASE_URL, apiKey: "", authMode: "codex-oauth", protocol: "openai-responses",
|
|
11
|
+
contextWindow: existing?.contextWindow ?? 128000, contextWindowMode: existing?.contextWindowMode ?? "auto",
|
|
12
|
+
models: existing?.models ?? [] }
|
|
13
|
+
let next = upsertProvider(config, provider)
|
|
14
|
+
if (provider.models.length && config.active.providerId === provider.id) next = setActive(next, provider.id, config.active.model)
|
|
15
|
+
return { config: next, provider }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function discoverCodexModels(signal: AbortSignal): Promise<Array<{ id: string; metadata: ProviderModelMetadata; reasoning?: ModelReasoning }>> {
|
|
19
|
+
const credentials = await getCodexCredentials(signal)
|
|
20
|
+
const response = await fetch(`${CODEX_BASE_URL}/models?client_version=${encodeURIComponent(VERSION)}`, {
|
|
21
|
+
headers: { Authorization: `Bearer ${credentials.accessToken}`, originator: "zap",
|
|
22
|
+
...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) },
|
|
23
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(6000)]), redirect: "error",
|
|
24
|
+
})
|
|
25
|
+
if (!response.ok) throw new Error(`Codex model discovery failed (HTTP ${response.status}).`)
|
|
26
|
+
const data = await response.json() as { models?: Array<Record<string, unknown>> }
|
|
27
|
+
if (!Array.isArray(data.models)) throw new Error("Invalid Codex models response.")
|
|
28
|
+
return data.models.flatMap(model => {
|
|
29
|
+
// supported_in_api only gates API-key accounts; Codex OAuth can use backend-only models.
|
|
30
|
+
if (typeof model.slug !== "string" || !model.slug || model.visibility === "hide" || model.visibility === "hidden") return []
|
|
31
|
+
return [{ id: model.slug, reasoning: normalizeModelReasoning(model.supported_reasoning_levels, model.default_reasoning_level), metadata: {
|
|
32
|
+
name: typeof model.display_name === "string" ? model.display_name : undefined,
|
|
33
|
+
contextWindow: typeof model.context_window === "number" && model.context_window > 0 ? model.context_window : undefined,
|
|
34
|
+
supportsVision: Array.isArray(model.input_modalities) ? model.input_modalities.includes("image") : undefined,
|
|
35
|
+
toolCall: true, reasoning: true, source: "provider" as const,
|
|
36
|
+
} }]
|
|
37
|
+
})
|
|
38
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { modelReasoningFor, normalizeReasoningMap, resolveModelEffort, effortName, type ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
|
|
1
2
|
import { deriveCompactionThresholds } from "../zapsdk/context/compact-budget.js"
|
|
2
3
|
import { canonicalModelId } from "../zapsdk/core/model-identity.js"
|
|
3
4
|
import { existsSync, readFileSync } from "node:fs"
|
|
@@ -93,7 +94,7 @@ export interface Provider {
|
|
|
93
94
|
name: string // display alias (empty → falls back to baseURL)
|
|
94
95
|
baseURL: string
|
|
95
96
|
apiKey: string // empty for keyless endpoints (Ollama)
|
|
96
|
-
authMode?: "api-key" | "none"
|
|
97
|
+
authMode?: "api-key" | "none" | "codex-oauth"
|
|
97
98
|
/** Exact public catalog identity, independent of endpoint and user alias. */
|
|
98
99
|
catalogProviderId?: string
|
|
99
100
|
contextWindow: number
|
|
@@ -117,6 +118,10 @@ export interface Provider {
|
|
|
117
118
|
* hints apply; unknown capability preserves images. The host can persist
|
|
118
119
|
* LoopAgent's bounded image-rejection fallback here for subsequent runs. */
|
|
119
120
|
visionByModel?: Record<string, boolean>
|
|
121
|
+
/** Authenticated capabilities, independent of public catalog alias metadata. */
|
|
122
|
+
reasoningByModel?: Record<string, ModelReasoning>
|
|
123
|
+
/** Codex model preferences; null explicitly uses the server default. */
|
|
124
|
+
effortByModel?: Record<string, string | null>
|
|
120
125
|
}
|
|
121
126
|
|
|
122
127
|
export interface CompactionConfig {
|
|
@@ -453,7 +458,7 @@ function normalizeProvider(value: unknown, index: number): Provider | null {
|
|
|
453
458
|
name: typeof value.name === "string" ? value.name : "",
|
|
454
459
|
baseURL: typeof value.baseURL === "string" ? value.baseURL : "",
|
|
455
460
|
apiKey: typeof value.apiKey === "string" ? value.apiKey : "",
|
|
456
|
-
authMode: value.authMode === "none" ? "none" : value.authMode === "api-key" ? "api-key" : undefined,
|
|
461
|
+
authMode: value.authMode === "codex-oauth" ? "codex-oauth" : value.authMode === "none" ? "none" : value.authMode === "api-key" ? "api-key" : undefined,
|
|
457
462
|
catalogProviderId: typeof value.catalogProviderId === "string" ? value.catalogProviderId : undefined,
|
|
458
463
|
contextWindow: positiveIntegerOrDefault(value.contextWindow, 128000),
|
|
459
464
|
models: Array.isArray(value.models)
|
|
@@ -461,6 +466,9 @@ function normalizeProvider(value: unknown, index: number): Provider | null {
|
|
|
461
466
|
: [],
|
|
462
467
|
protocol: value.protocol === "anthropic" || value.protocol === "openai" || value.protocol === "openai-responses" ? value.protocol : undefined,
|
|
463
468
|
modelMetadata,
|
|
469
|
+
reasoningByModel: normalizeReasoningMap(value.reasoningByModel),
|
|
470
|
+
effortByModel: isRecord(value.effortByModel) ? Object.fromEntries(Object.entries(value.effortByModel)
|
|
471
|
+
.filter(([model, effort]) => !!model && model.length <= 256 && !/[\x00-\x1f\x7f]/.test(model) && (effort === null || effortName(effort)))) : undefined,
|
|
464
472
|
} as Provider
|
|
465
473
|
provider.contextWindowMode = value.contextWindowMode === "auto" || value.contextWindowMode === "manual"
|
|
466
474
|
? value.contextWindowMode
|
|
@@ -750,6 +758,8 @@ export function hasApiKey(config: AppConfig): boolean {
|
|
|
750
758
|
const p = getActiveProvider(config)
|
|
751
759
|
if (!p) return false
|
|
752
760
|
if (p.authMode === "none") return true
|
|
761
|
+
// The transport resolves OAuth credentials lazily, including logout/refresh.
|
|
762
|
+
if (p.authMode === "codex-oauth") return true
|
|
753
763
|
// Keyless endpoints (Ollama) are detected via their source preset's
|
|
754
764
|
// requiresApiKey flag; providers with no sourcePresetId must always have a key.
|
|
755
765
|
const preset = p.sourcePresetId ? presetMap.get(p.sourcePresetId) : undefined
|
|
@@ -811,11 +821,16 @@ export function removeModelFromProvider(config: AppConfig, providerId: string, m
|
|
|
811
821
|
// reasoning_effort`; "unset" = key absent, server uses its own default.
|
|
812
822
|
// The Responses adapter maps this setting to `reasoning.effort`.
|
|
813
823
|
|
|
814
|
-
/**
|
|
815
|
-
|
|
816
|
-
|
|
824
|
+
/** The request-body model override also controls the effort capability lookup. */
|
|
825
|
+
export function effortModel(config: AppConfig, provider: Provider): string {
|
|
826
|
+
return typeof provider.extraRequestParams?.model === "string" ? provider.extraRequestParams.model
|
|
827
|
+
: config.active.providerId === provider.id ? config.active.model : provider.models[0] ?? ""
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** OAuth uses exact model capabilities; other providers keep preset/passthrough behavior. */
|
|
817
831
|
export function getEffortValuesForProvider(config: AppConfig, providerId: string): readonly string[] {
|
|
818
832
|
const p = config.providers.find(x => x.id === providerId)
|
|
833
|
+
if (p?.authMode === "codex-oauth") return modelReasoningFor(p.reasoningByModel, effortModel(config, p))?.levels.map(level => level.effort) ?? []
|
|
819
834
|
const preset = p?.sourcePresetId ? presetMap.get(p.sourcePresetId) : undefined
|
|
820
835
|
return preset?.effortValues ?? DEFAULT_EFFORT_VALUES
|
|
821
836
|
}
|
|
@@ -828,6 +843,7 @@ export function getEffortValuesForProvider(config: AppConfig, providerId: string
|
|
|
828
843
|
* upstream server enforce its own rules. */
|
|
829
844
|
export function hasDeclaredEffortValues(config: AppConfig, providerId: string): boolean {
|
|
830
845
|
const p = config.providers.find(x => x.id === providerId)
|
|
846
|
+
if (p?.authMode === "codex-oauth") return !!modelReasoningFor(p.reasoningByModel, effortModel(config, p))
|
|
831
847
|
const preset = p?.sourcePresetId ? presetMap.get(p.sourcePresetId) : undefined
|
|
832
848
|
return preset?.effortValues !== undefined
|
|
833
849
|
}
|
|
@@ -859,6 +875,13 @@ export function resolveEffortInput(
|
|
|
859
875
|
/** Current effort, or undefined if unset (= use server default). */
|
|
860
876
|
export function getEffort(config: AppConfig, providerId: string): string | undefined {
|
|
861
877
|
const p = config.providers.find(x => x.id === providerId)
|
|
878
|
+
if (p?.authMode === "codex-oauth") {
|
|
879
|
+
const model = effortModel(config, p)
|
|
880
|
+
const nested = p.extraRequestParams?.reasoning as { effort?: unknown } | undefined
|
|
881
|
+
const value = Object.hasOwn(p.effortByModel ?? {}, model) ? p.effortByModel![model]
|
|
882
|
+
: typeof p.extraRequestParams?.reasoning_effort === "string" ? p.extraRequestParams.reasoning_effort : nested?.effort
|
|
883
|
+
return resolveModelEffort(modelReasoningFor(p.reasoningByModel, model), value)
|
|
884
|
+
}
|
|
862
885
|
const v = p?.extraRequestParams?.reasoning_effort
|
|
863
886
|
return typeof v === "string" ? v : undefined
|
|
864
887
|
}
|
|
@@ -870,6 +893,7 @@ export function setEffort(config: AppConfig, providerId: string, value: string |
|
|
|
870
893
|
const providers = config.providers.map(p => {
|
|
871
894
|
if (p.id !== providerId) return p
|
|
872
895
|
const extra = { ...(p.extraRequestParams ?? {}) }
|
|
896
|
+
if (p.authMode === "codex-oauth") return { ...p, effortByModel: { ...p.effortByModel, [effortModel(config, p)]: value } }
|
|
873
897
|
if (value === null) delete extra.reasoning_effort
|
|
874
898
|
else extra.reasoning_effort = value
|
|
875
899
|
return { ...p, extraRequestParams: extra }
|
|
@@ -1087,7 +1111,7 @@ export function formatStatus(config: AppConfig, configPath: string): string {
|
|
|
1087
1111
|
]
|
|
1088
1112
|
if (effort) lines.push(`Reasoning effort: ${effort}`)
|
|
1089
1113
|
lines.push(
|
|
1090
|
-
`API key: ${maskSecret(p?.apiKey ?? "")}`,
|
|
1114
|
+
p?.authMode === "codex-oauth" ? "Authentication: Codex OAuth (ChatGPT)" : `API key: ${maskSecret(p?.apiKey ?? "")}`,
|
|
1091
1115
|
`Serper key: ${maskSecret(config.serperKey)}`,
|
|
1092
1116
|
`Max tokens: ${config.maxTokens}`,
|
|
1093
1117
|
`Max steps: ${config.maxSteps}`,
|
package/src/index.tsx
CHANGED
|
@@ -26,6 +26,9 @@ Options:
|
|
|
26
26
|
--watch-no-open Print the Watch URL without opening a browser
|
|
27
27
|
--watch-linger <s> Keep the headless viewer available after a run (0..300)
|
|
28
28
|
--help-headless Show non-interactive (headless) mode flags
|
|
29
|
+
auth login codex Sign in to Codex with ChatGPT (--device-code for SSH)
|
|
30
|
+
auth logout codex Remove Zap's Codex credentials
|
|
31
|
+
auth status codex Show Zap's Codex login status
|
|
29
32
|
update [--yes] Check, confirm and install the latest version
|
|
30
33
|
acp Serve Agent Client Protocol v1 over stdio (no TUI)
|
|
31
34
|
workflow Inspect, wait for or cancel a persisted workflow (--db required)
|
|
@@ -62,6 +65,11 @@ if (args.includes("--version") || args.includes("-v")) {
|
|
|
62
65
|
process.exit(0)
|
|
63
66
|
}
|
|
64
67
|
|
|
68
|
+
if (args[0] === "auth") {
|
|
69
|
+
const { runCodexAuthCommand } = await import("./codex-auth-command.js")
|
|
70
|
+
process.exit(await runCodexAuthCommand(args.slice(1)))
|
|
71
|
+
}
|
|
72
|
+
|
|
65
73
|
if (args[0] === "update") {
|
|
66
74
|
const { runUpdateCommand } = await import("./update-cli.js")
|
|
67
75
|
process.exit(await runUpdateCommand(args.slice(1)))
|
package/src/provider-catalog.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import type { ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
|
|
1
2
|
import { listModels } from "../zapsdk/core/list-models.js"
|
|
2
3
|
import { getModelsDevProvider, suggestedModelsDevIds, type ModelsDevProvider } from "../zapsdk/core/models-dev.js"
|
|
3
4
|
import { resolveCatalogProviderId, upsertProvider, setActive, type AppConfig, type Provider, type ProviderModelMetadata } from "./config.js"
|
|
4
5
|
import { enrichProviderMetadata, mergeModelMetadata, modelsDevMetadata, pickModelMetadata } from "./provider-metadata.js"
|
|
6
|
+
import { discoverCodexModels } from "./codex-provider.js"
|
|
5
7
|
|
|
6
8
|
export type ModelSource = "saved" | "provider" | "models.dev" | "manual"
|
|
7
|
-
export interface CatalogRow { id: string; source: ModelSource; metadata?: ProviderModelMetadata }
|
|
9
|
+
export interface CatalogRow { id: string; source: ModelSource; metadata?: ProviderModelMetadata; reasoning?: ModelReasoning }
|
|
8
10
|
export interface DiscoveredCatalog { rows: CatalogRow[]; error?: string }
|
|
9
11
|
|
|
10
12
|
/** User-selected metadata for a gateway alias, independent of transport identity. */
|
|
@@ -27,6 +29,16 @@ export function associateModelMetadata(config: AppConfig, providerId: string, mo
|
|
|
27
29
|
|
|
28
30
|
/** Discovery is read-only: returning a model is not proof of inference access. */
|
|
29
31
|
export async function discoverProviderModels(provider: Provider, signal: AbortSignal): Promise<DiscoveredCatalog> {
|
|
32
|
+
if (provider.authMode === "codex-oauth") {
|
|
33
|
+
const rows = new Map<string, CatalogRow>(provider.models.map(id => [id, { id, source: "saved", metadata: provider.modelMetadata?.[id] }]))
|
|
34
|
+
try {
|
|
35
|
+
for (const row of await discoverCodexModels(signal)) rows.set(row.id, { ...row, source: "provider" })
|
|
36
|
+
return { rows: [...rows.values()] }
|
|
37
|
+
} catch (error) {
|
|
38
|
+
signal.throwIfAborted()
|
|
39
|
+
return { rows: [...rows.values()], error: error instanceof Error ? error.message : "Codex model discovery failed. Sign in again with /connect." }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
30
42
|
const catalogId = resolveCatalogProviderId(provider)
|
|
31
43
|
const [live, catalog] = await Promise.allSettled([
|
|
32
44
|
listModels(provider.baseURL, provider.authMode === "none" ? "" : provider.apiKey, 6000, signal, provider.protocol),
|
|
@@ -62,7 +74,11 @@ export function selectCatalogModel(config: AppConfig, providerId: string, row: C
|
|
|
62
74
|
const models = [...new Set([...provider.models, row.id])]
|
|
63
75
|
const modelMetadata = pickModelMetadata(mergeModelMetadata(provider.modelMetadata ?? {},
|
|
64
76
|
row.metadata ? { [row.id]: row.metadata } : {}), models)
|
|
65
|
-
|
|
77
|
+
const liveReasoning = provider.authMode === "codex-oauth" && row.source === "provider"
|
|
78
|
+
const reasoningByModel = { ...provider.reasoningByModel,
|
|
79
|
+
...(liveReasoning && row.reasoning ? { [row.id]: row.reasoning } : {}) }
|
|
80
|
+
if (liveReasoning && !row.reasoning) delete reasoningByModel[row.id]
|
|
81
|
+
return setActive(upsertProvider(config, { ...provider, models, modelMetadata, reasoningByModel }), providerId, row.id)
|
|
66
82
|
}
|
|
67
83
|
|
|
68
84
|
export function describeCatalogRow(row: CatalogRow): string {
|
package/src/provider-metadata.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { discoverCodexModels } from "./codex-provider.js"
|
|
1
2
|
import type { ImageTokenContext } from "../zapsdk/context/image-tokens.js"
|
|
2
3
|
import { canonicalModelId } from "../zapsdk/core/model-identity.js"
|
|
3
4
|
import {
|
|
@@ -83,6 +84,14 @@ export function enrichProviderMetadata(provider: Provider, catalog: ModelsDevPro
|
|
|
83
84
|
export async function refreshModelsDevMetadata(config: AppConfig): Promise<AppConfig> {
|
|
84
85
|
const providers = await Promise.all(config.providers.map(async provider => {
|
|
85
86
|
if (provider.models.length === 0) return provider
|
|
87
|
+
if (provider.authMode === "codex-oauth") {
|
|
88
|
+
try {
|
|
89
|
+
const rows = await discoverCodexModels(AbortSignal.timeout(6500))
|
|
90
|
+
const reasoningByModel = Object.fromEntries(rows.flatMap(row => row.reasoning ? [[row.id, row.reasoning]] : []))
|
|
91
|
+
return JSON.stringify(reasoningByModel) === JSON.stringify(provider.reasoningByModel ?? {})
|
|
92
|
+
? provider : { ...provider, reasoningByModel }
|
|
93
|
+
} catch { return provider }
|
|
94
|
+
}
|
|
86
95
|
const ids = new Set([resolveCatalogProviderId(provider), ...provider.models.map(id =>
|
|
87
96
|
provider.modelMetadata?.[id]?.catalogRef?.providerId)].filter((id): id is string => !!id))
|
|
88
97
|
const catalogs = await Promise.all([...ids].map(id => getModelsDevProvider(id).catch(() => null)))
|
|
@@ -124,7 +133,7 @@ export function applyMetadataRefresh(current: AppConfig, initial: AppConfig, ref
|
|
|
124
133
|
const after = refreshed.providers.find(item => item.id === provider.id)
|
|
125
134
|
if (!before || !after || before === after || provider !== before) return provider
|
|
126
135
|
return { ...provider, contextWindow: after.contextWindow,
|
|
127
|
-
contextWindowMode: after.contextWindowMode, modelMetadata: after.modelMetadata }
|
|
136
|
+
contextWindowMode: after.contextWindowMode, modelMetadata: after.modelMetadata, reasoningByModel: after.reasoningByModel }
|
|
128
137
|
})
|
|
129
138
|
return providers.every((provider, index) => provider === current.providers[index])
|
|
130
139
|
? current : { ...current, providers }
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** @jsxImportSource react */
|
|
2
|
+
import { useEffect, useRef, useState } from "react"
|
|
3
|
+
import { Text, useInput } from "ink"
|
|
4
|
+
import { openAuthBrowser, saveCodexCredentials, startCodexBrowserLogin, startCodexDeviceLogin } from "../codex-auth.js"
|
|
5
|
+
import { DialogFrame } from "./dialog-frame.js"
|
|
6
|
+
import { PickerDialog } from "./dialog-picker.js"
|
|
7
|
+
import { c } from "./theme.js"
|
|
8
|
+
|
|
9
|
+
export function CodexLoginDialog({ onSuccess, onCancel }: { onSuccess: () => void; onCancel: () => void }) {
|
|
10
|
+
const [method, setMethod] = useState<"browser" | "device" | null>(null)
|
|
11
|
+
const [details, setDetails] = useState<{ url: string; instructions: string } | null>(null)
|
|
12
|
+
const [error, setError] = useState("")
|
|
13
|
+
const callbacks = useRef({ onSuccess, onCancel })
|
|
14
|
+
callbacks.current = { onSuccess, onCancel }
|
|
15
|
+
useInput((_input, key) => { if (method && key.escape) setMethod(null) })
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!method) return
|
|
18
|
+
const controller = new AbortController()
|
|
19
|
+
setDetails(null); setError("")
|
|
20
|
+
void (async () => {
|
|
21
|
+
const login = method === "browser" ? await startCodexBrowserLogin({ signal: controller.signal }) : await startCodexDeviceLogin(controller.signal)
|
|
22
|
+
if (controller.signal.aborted) { login.cancel(); return }
|
|
23
|
+
setDetails({ url: login.url, instructions: login.instructions })
|
|
24
|
+
openAuthBrowser(login.url)
|
|
25
|
+
const credentials = await login.complete
|
|
26
|
+
if (controller.signal.aborted) return
|
|
27
|
+
await saveCodexCredentials(credentials, undefined, controller.signal)
|
|
28
|
+
if (controller.signal.aborted) return
|
|
29
|
+
callbacks.current.onSuccess()
|
|
30
|
+
})().catch(error => { if (!controller.signal.aborted) setError(error instanceof Error ? error.message : "Codex login failed.") })
|
|
31
|
+
return () => controller.abort()
|
|
32
|
+
}, [method])
|
|
33
|
+
if (!method) return <PickerDialog title="OpenAI Codex · sign in with ChatGPT"
|
|
34
|
+
options={[{ id: "browser", label: "Browser login", meta: "opens ChatGPT sign-in · local callback on port 1455" },
|
|
35
|
+
{ id: "device", label: "Device code", meta: "for SSH, headless hosts, or a busy callback port" }]}
|
|
36
|
+
onCancel={onCancel} onSelect={id => setMethod(id as "browser" | "device")} />
|
|
37
|
+
return <DialogFrame title="OpenAI Codex · sign in with ChatGPT" hint="esc back / cancel login">
|
|
38
|
+
{error ? <Text color={c.warning}>{error}</Text> : <>
|
|
39
|
+
<Text>{details?.instructions ?? "Starting Codex login…"}</Text>
|
|
40
|
+
{details && <Text color={c.accent}>{details.url}</Text>}
|
|
41
|
+
<Text color={c.text.faint}>If the browser did not open, open this URL manually. Waiting for authorization…</Text>
|
|
42
|
+
</>}
|
|
43
|
+
</DialogFrame>
|
|
44
|
+
}
|
package/src/ui/dialog-config.tsx
CHANGED
|
@@ -3,7 +3,12 @@
|
|
|
3
3
|
// dialogs: Model, Mode, Effort. Kept in one file because they share the
|
|
4
4
|
// same 30-line shape — caller hands in `{config, onCommit, onCancel}`,
|
|
5
5
|
// the dialog wires options + commit semantics around PickerDialog.
|
|
6
|
+
import { modelReasoningFor } from "../../zapsdk/core/reasoning-effort.js"
|
|
7
|
+
import { useEffect, useState } from "react"
|
|
8
|
+
import { discoverCodexModels } from "../codex-provider.js"
|
|
6
9
|
import {
|
|
10
|
+
effortModel,
|
|
11
|
+
upsertProvider,
|
|
7
12
|
getActiveProvider,
|
|
8
13
|
getEffort,
|
|
9
14
|
setEffort,
|
|
@@ -48,37 +53,53 @@ export function ModeDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
|
48
53
|
// ── Effort picker ────────────────────────────────────────────────────────
|
|
49
54
|
export function EffortDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
50
55
|
const provider = getActiveProvider(config)
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
56
|
+
// A changed connection remounts the fetch and picker, including its cursor.
|
|
57
|
+
return <ModelEffortDialog key={provider ? `${provider.id}:${effortModel(config, provider)}` : "none"}
|
|
58
|
+
config={config} onCommit={onCommit} onCancel={onCancel} />
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function ModelEffortDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
62
|
+
const provider = getActiveProvider(config)
|
|
63
|
+
const [snapshot, setSnapshot] = useState<{ provider: typeof provider; rows: Awaited<ReturnType<typeof discoverCodexModels>> }>()
|
|
64
|
+
const [status, setStatus] = useState("Loading model capabilities…")
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
if (provider?.authMode !== "codex-oauth") return
|
|
67
|
+
const controller = new AbortController()
|
|
68
|
+
setStatus("Loading model capabilities…")
|
|
69
|
+
discoverCodexModels(controller.signal).then(rows => {
|
|
70
|
+
if (controller.signal.aborted) return
|
|
71
|
+
setSnapshot({ provider, rows })
|
|
72
|
+
setStatus("Model has not advertised reasoning levels")
|
|
73
|
+
}, () => {
|
|
74
|
+
if (!controller.signal.aborted) setStatus("Discovery unavailable; using saved model capabilities")
|
|
75
|
+
})
|
|
76
|
+
return () => controller.abort()
|
|
77
|
+
}, [provider])
|
|
78
|
+
let latest = config
|
|
79
|
+
if (provider && snapshot?.provider === provider) {
|
|
80
|
+
const reasoningByModel = Object.fromEntries(snapshot.rows.flatMap(row => row.reasoning ? [[row.id, row.reasoning]] : []))
|
|
81
|
+
latest = upsertProvider(config, { ...provider, reasoningByModel })
|
|
61
82
|
}
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
83
|
+
const active = getActiveProvider(latest)
|
|
84
|
+
const codex = active?.authMode === "codex-oauth"
|
|
85
|
+
const values = active ? getEffortValuesForProvider(latest, active.id) : []
|
|
86
|
+
const model = active ? effortModel(latest, active) : ""
|
|
87
|
+
const profile = modelReasoningFor(active?.reasoningByModel, model)
|
|
88
|
+
if (!active || (!codex && values.length === 0)) {
|
|
89
|
+
return <PickerDialog title="Reasoning effort"
|
|
90
|
+
options={[{ id: "__none", label: "Active provider does not expose reasoning_effort", disabled: true }]}
|
|
91
|
+
onCancel={onCancel} onSelect={onCancel} />
|
|
92
|
+
}
|
|
93
|
+
const current = getEffort(latest, active.id)
|
|
94
|
+
const options: PickerOption[] = [{ id: "__default", label: codex ? "default" : "off",
|
|
95
|
+
meta: `${codex ? `server default${profile?.defaultEffort ? ` (${profile.defaultEffort})` : ""}` : "server default"}${!current ? " (current)" : ""}` },
|
|
96
|
+
...values.map(value => ({ id: `level:${value}`, label: value,
|
|
97
|
+
meta: [profile?.levels.find(level => level.effort === value)?.description,
|
|
98
|
+
current === value ? "(current)" : undefined].filter(Boolean).join(" · ") }))]
|
|
99
|
+
if (codex && !profile) options.push({ id: "__status", label: status, disabled: true })
|
|
100
|
+
if (codex && profile?.levels.length === 0) options.push({ id: "__none", label: "No adjustable reasoning levels", disabled: true })
|
|
101
|
+
return <PickerDialog key={`${model}:${values.join(",")}:${current ?? "default"}`}
|
|
102
|
+
title={`Reasoning effort — ${codex ? model : active.name}`}
|
|
103
|
+
options={options} initialIndex={current ? Math.max(0, values.indexOf(current) + 1) : 0}
|
|
104
|
+
onCancel={onCancel} onSelect={id => onCommit(setEffort(latest, active.id, id === "__default" ? null : id.slice(6)))} />
|
|
84
105
|
}
|
|
@@ -12,12 +12,14 @@ import { commandInput, isReturnInput } from "./controlled-input.js"
|
|
|
12
12
|
import { c } from "./theme.js"
|
|
13
13
|
import { ModelDialog } from "./dialog-model.js"
|
|
14
14
|
import { ContextWindowDialog } from "./dialog-context-window.js"
|
|
15
|
+
import { CodexLoginDialog } from "./dialog-codex-login.js"
|
|
16
|
+
import { connectCodexProvider } from "../codex-provider.js"
|
|
15
17
|
|
|
16
18
|
interface Props { config: AppConfig; onSave: (next: AppConfig) => void; onCommit: (next: AppConfig) => void; onCancel: () => void }
|
|
17
19
|
type Draft = { name: string; baseURL: string; apiKey: string; protocol: ProviderProtocol;
|
|
18
20
|
authMode: "none" | "api-key"; catalogProviderId?: string; existing?: Provider;
|
|
19
21
|
contextWindow?: number; contextWindowMode?: ContextWindowMode }
|
|
20
|
-
type Step = "connections" | "preset" | "name" | "endpoint" | "protocol" | "auth" | "key" | "context" | "review"
|
|
22
|
+
type Step = "connections" | "preset" | "name" | "endpoint" | "protocol" | "auth" | "key" | "context" | "review" | "codex"
|
|
21
23
|
|
|
22
24
|
export function saveConnection(config: AppConfig, draft: Draft): AppConfig {
|
|
23
25
|
const existing = draft.existing
|
|
@@ -73,6 +75,7 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
73
75
|
if (cmd === "d" && provider) { setDeleting(true); return }
|
|
74
76
|
if (isReturnInput(input, key) || cmd === "e") {
|
|
75
77
|
if (!provider) { setStep("preset"); return }
|
|
78
|
+
if (provider.authMode === "codex-oauth") { setStep("codex"); return }
|
|
76
79
|
setDraft({ existing: provider, name: provider.name, baseURL: provider.baseURL,
|
|
77
80
|
apiKey: provider.apiKey, protocol: provider.protocol ?? "openai",
|
|
78
81
|
authMode: provider.authMode ?? (provider.apiKey ? "api-key" : "none"), catalogProviderId: provider.catalogProviderId })
|
|
@@ -90,7 +93,7 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
90
93
|
<Box flexDirection="column" marginTop={1}>
|
|
91
94
|
{config.providers.map((provider, i) => <Box key={provider.id} flexDirection="column">
|
|
92
95
|
<Text color={i === index ? c.accent : c.text.primary}>{`${i === index ? "›" : " "} ${provider.name || "Unnamed connection"}`}</Text>
|
|
93
|
-
<Text color={c.text.faint}>{` ${provider.protocol ?? "openai"} · ${provider.apiKey ? "API key stored" : "no key"} · ${provider.models.length} saved models`}</Text>
|
|
96
|
+
<Text color={c.text.faint}>{` ${provider.authMode === "codex-oauth" ? "Codex Responses · ChatGPT OAuth" : `${provider.protocol ?? "openai"} · ${provider.apiKey ? "API key stored" : "no key"}`} · ${provider.models.length} saved models`}</Text>
|
|
94
97
|
<Text color={c.text.faint}>{` ${provider.baseURL}`}</Text>
|
|
95
98
|
</Box>)}
|
|
96
99
|
<Text color={index === config.providers.length ? c.accent : c.text.primary}>{`${index === config.providers.length ? "›" : " "} + New connection`}</Text>
|
|
@@ -98,7 +101,13 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
98
101
|
{deleting && <Text color={c.warning}>Remove connection and its saved model preferences?</Text>}
|
|
99
102
|
</DialogFrame>
|
|
100
103
|
|
|
101
|
-
if (step === "
|
|
104
|
+
if (step === "codex") return <CodexLoginDialog onCancel={() => setStep("connections")} onSuccess={() => {
|
|
105
|
+
const result = connectCodexProvider(live.current.config)
|
|
106
|
+
onSave(result.config)
|
|
107
|
+
setModelTarget({ id: result.provider.id, setup: true })
|
|
108
|
+
}} />
|
|
109
|
+
|
|
110
|
+
if (step === "preset") return <ProviderDirectory onCodex={() => setStep("codex")}
|
|
102
111
|
onCancel={() => setStep("connections")} onSelect={provider => {
|
|
103
112
|
setDraft({ catalogProviderId: provider?.id, name: provider?.name ?? "", baseURL: provider?.api ?? "", apiKey: "",
|
|
104
113
|
protocol: provider?.protocol ?? "openai", authMode: "api-key" })
|
|
@@ -10,11 +10,11 @@ import { useTermWidth } from "./term-width.js"
|
|
|
10
10
|
import { truncateToWidth } from "./truncate.js"
|
|
11
11
|
import { c } from "./theme.js"
|
|
12
12
|
|
|
13
|
-
interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean }
|
|
13
|
+
interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean; onCodex?: () => void }
|
|
14
14
|
|
|
15
15
|
/** Public directory data supplies vendor names and endpoints; adapters only
|
|
16
16
|
* constrain which wire protocols the installed runtime actually supports. */
|
|
17
|
-
export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false }: Props) {
|
|
17
|
+
export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, onCodex }: Props) {
|
|
18
18
|
const [providers, setProviders] = useState<ModelsDevConnection[]>([])
|
|
19
19
|
const [loading, setLoading] = useState(true)
|
|
20
20
|
const [error, setError] = useState("")
|
|
@@ -60,11 +60,13 @@ export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false }:
|
|
|
60
60
|
maxRows={Math.max(3, Math.min(10, (process.stdout.rows ?? 24) - 15))}
|
|
61
61
|
hint="↑↓ select · enter configure · / search · r reload · esc back"
|
|
62
62
|
options={[...(!metadataOnly ? [{ id: "__custom", label: "Custom endpoint", meta: "configure manually" }] : []),
|
|
63
|
+
...(!metadataOnly && onCodex ? [{ id: "__codex", label: "OpenAI Codex (ChatGPT)", meta: "OAuth · sign in with ChatGPT" }] : []),
|
|
63
64
|
...visible.map(provider => ({ id: `catalog:${provider.id}`, label: truncateToWidth(provider.name, labelWidth),
|
|
64
65
|
meta: truncateToWidth(provider.protocol ? `${provider.protocol}${provider.api ? " · endpoint provided" : " · enter endpoint"}` : "unsupported adapter", width - labelWidth - 2),
|
|
65
66
|
disabled: !metadataOnly && !provider.protocol }))]}
|
|
66
67
|
onCancel={onCancel} onSelect={id => {
|
|
67
68
|
if (id === "__custom") onSelect(null)
|
|
69
|
+
else if (id === "__codex") onCodex?.()
|
|
68
70
|
else {
|
|
69
71
|
const provider = providers.find(item => item.id === id.slice("catalog:".length))
|
|
70
72
|
if (provider && (metadataOnly || provider.protocol)) onSelect(provider)
|
|
@@ -1,14 +1,25 @@
|
|
|
1
1
|
import OpenAI from "openai";
|
|
2
2
|
import type { Response as APIResponse, ResponseInputItem, ResponseCreateParams } from "openai/resources/responses/responses";
|
|
3
3
|
import type { LLMProvider, LLMCallOptions } from "../llm.js";
|
|
4
|
-
import type { LLMChunk, LLMResponse, Message, ToolCallRequest } from "../types.js";
|
|
4
|
+
import type { LLMChunk, LLMResponse, Message, ToolCallRequest, TokenUsage } from "../types.js";
|
|
5
5
|
import type { ToolDefinition } from "../../tools/types.js";
|
|
6
6
|
import { canonicalizeJsonSchema, zodToJsonSchema } from "../../tools/schema.js";
|
|
7
7
|
import { ProviderRequest } from "../provider-request.js";
|
|
8
8
|
import { getStreamIdleMs, withStreamIdleTimeout } from "../stream-idle.js";
|
|
9
9
|
import { OpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from "./openai-compatible.js";
|
|
10
|
+
import { modelReasoningFor, resolveModelEffort, type ModelReasoning } from "../reasoning-effort.js";
|
|
11
|
+
import { stripBoundary } from "../prompt-boundary.js";
|
|
10
12
|
|
|
11
|
-
export
|
|
13
|
+
export const CODEX_RESPONSES_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
14
|
+
export interface OpenAIResponsesProviderOptions extends OpenAICompatibleProviderOptions {
|
|
15
|
+
/** Host-owned ChatGPT credentials, resolved on each call to allow rotation/logout. */
|
|
16
|
+
codex?: {
|
|
17
|
+
getCredentials: (signal?: AbortSignal) => Promise<{ accessToken: string; accountId?: string }>;
|
|
18
|
+
fetch?: typeof globalThis.fetch;
|
|
19
|
+
reasoningByModel?: Record<string, ModelReasoning>;
|
|
20
|
+
effortByModel?: Record<string, string | null>;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
12
23
|
type LayoutItem =
|
|
13
24
|
| { type: "reasoning"; [key: string]: unknown }
|
|
14
25
|
| { type: "message"; length: number; phase?: "commentary" | "final_answer" | null }
|
|
@@ -21,7 +32,8 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
21
32
|
private formatter: OpenAICompatibleProvider;
|
|
22
33
|
|
|
23
34
|
constructor(private options: OpenAIResponsesProviderOptions) {
|
|
24
|
-
this.client = options.
|
|
35
|
+
this.client = options.codex ? new OpenAI({ apiKey: "oauth-pending", baseURL: CODEX_RESPONSES_BASE_URL, maxRetries: 0 })
|
|
36
|
+
: options.client ?? new OpenAI({ apiKey: options.apiKey ?? process.env.OPENAI_API_KEY,
|
|
25
37
|
baseURL: options.baseURL, defaultHeaders: options.defaultHeaders, maxRetries: 0 });
|
|
26
38
|
this.formatter = new OpenAICompatibleProvider({ ...options, client: this.client });
|
|
27
39
|
}
|
|
@@ -29,6 +41,17 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
29
41
|
setVisionSupported(supported: boolean): void { this.formatter.setVisionSupported(supported); }
|
|
30
42
|
getImageTokenContext(options?: LLMCallOptions) { return this.formatter.getImageTokenContext(options); }
|
|
31
43
|
|
|
44
|
+
private async requestClient(request: ProviderRequest): Promise<OpenAI> {
|
|
45
|
+
const codex = this.options.codex;
|
|
46
|
+
if (!codex) return this.client;
|
|
47
|
+
const credentials = await request.wait(codex.getCredentials(request.signal));
|
|
48
|
+
request.signal.throwIfAborted();
|
|
49
|
+
// OAuth tokens are never sent to a user-configurable endpoint/client.
|
|
50
|
+
return new OpenAI({ baseURL: CODEX_RESPONSES_BASE_URL, apiKey: credentials.accessToken, maxRetries: 0,
|
|
51
|
+
fetch: codex.fetch, defaultHeaders: { originator: "zap",
|
|
52
|
+
...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) } });
|
|
53
|
+
}
|
|
54
|
+
|
|
32
55
|
serializeMessages(messages: Message[]): ResponseInputItem[] {
|
|
33
56
|
// Reuse image degradation, tool-image grouping, text sanitization and late
|
|
34
57
|
// system-message normalization; never pass Chat sidecars into Responses.
|
|
@@ -94,7 +117,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
94
117
|
delete extra.conversation;
|
|
95
118
|
delete extra.background;
|
|
96
119
|
const include = Array.isArray(extra.include) ? extra.include.filter(value => typeof value === "string") : [];
|
|
97
|
-
|
|
120
|
+
const body = {
|
|
98
121
|
model: opts?.model ?? this.options.model,
|
|
99
122
|
max_output_tokens: opts?.maxOutputTokens ?? this.options.maxTokens ?? 4096,
|
|
100
123
|
...extra,
|
|
@@ -107,6 +130,27 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
107
130
|
store: false,
|
|
108
131
|
stream,
|
|
109
132
|
} as ResponseCreateParams;
|
|
133
|
+
if (this.options.codex) {
|
|
134
|
+
const { reasoningByModel, effortByModel } = this.options.codex;
|
|
135
|
+
const model = body.model ?? "";
|
|
136
|
+
const reasoning = { ...body.reasoning };
|
|
137
|
+
const value = Object.hasOwn(effortByModel ?? {}, model) ? effortByModel![model] : reasoning.effort;
|
|
138
|
+
const effort = resolveModelEffort(modelReasoningFor(reasoningByModel, model), value);
|
|
139
|
+
if (effort === undefined) delete reasoning.effort;
|
|
140
|
+
else reasoning.effort = effort as typeof reasoning.effort;
|
|
141
|
+
if (Object.keys(reasoning).length) body.reasoning = reasoning;
|
|
142
|
+
else delete body.reasoning;
|
|
143
|
+
let leadingSystemEnd = 0;
|
|
144
|
+
while (messages[leadingSystemEnd]?.role === "system") leadingSystemEnd++;
|
|
145
|
+
body.instructions = messages.slice(0, leadingSystemEnd).map(message => stripBoundary(message.content)).join("\n\n");
|
|
146
|
+
body.input = this.serializeMessages(messages.slice(leadingSystemEnd));
|
|
147
|
+
// Codex requires SSE and rejects generation controls accepted by the API.
|
|
148
|
+
delete body.max_output_tokens;
|
|
149
|
+
delete body.temperature;
|
|
150
|
+
delete body.top_p;
|
|
151
|
+
body.stream = true;
|
|
152
|
+
}
|
|
153
|
+
return body;
|
|
110
154
|
}
|
|
111
155
|
|
|
112
156
|
private parse(response: APIResponse): LLMResponse {
|
|
@@ -150,6 +194,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
150
194
|
}
|
|
151
195
|
|
|
152
196
|
async call(messages: Message[], tools?: ToolDefinition[], opts?: LLMCallOptions): Promise<LLMResponse> {
|
|
197
|
+
if (this.options.codex) return this.collectCodexStream(messages, tools, opts);
|
|
153
198
|
const request = new ProviderRequest(opts);
|
|
154
199
|
try {
|
|
155
200
|
const body = this.body(messages, tools, opts, false);
|
|
@@ -161,6 +206,30 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
161
206
|
} finally { request.close(); }
|
|
162
207
|
}
|
|
163
208
|
|
|
209
|
+
private async collectCodexStream(messages: Message[], tools?: ToolDefinition[], opts?: LLMCallOptions): Promise<LLMResponse> {
|
|
210
|
+
let text = "";
|
|
211
|
+
let usage: TokenUsage = { inputTokens: 0, outputTokens: 0, providerUsageReported: false };
|
|
212
|
+
let finishReason: string | undefined;
|
|
213
|
+
let raw: Record<string, unknown> | undefined;
|
|
214
|
+
const pending = new Map<string, { name: string; json: string }>();
|
|
215
|
+
for await (const chunk of this.stream(messages, tools, opts)) {
|
|
216
|
+
if (chunk.type === "text_delta") text += chunk.text;
|
|
217
|
+
if (chunk.type === "tool_call_start") pending.set(chunk.toolCallId, { name: chunk.toolName, json: "" });
|
|
218
|
+
if (chunk.type === "tool_call_delta") { const call = pending.get(chunk.toolCallId); if (call) call.json += chunk.partialJson; }
|
|
219
|
+
if (chunk.type === "done") { usage = chunk.usage; finishReason = chunk.finishReason; raw = chunk.raw; }
|
|
220
|
+
}
|
|
221
|
+
opts?.signal?.throwIfAborted();
|
|
222
|
+
const toolCalls: ToolCallRequest[] = [...pending].map(([id, call]) => {
|
|
223
|
+
try {
|
|
224
|
+
const args = JSON.parse(call.json);
|
|
225
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) throw new Error();
|
|
226
|
+
return { id, name: call.name, arguments: args };
|
|
227
|
+
} catch { return { id, name: call.name, arguments: {}, argumentParseError: "Malformed tool arguments JSON from provider: expected an object." }; }
|
|
228
|
+
});
|
|
229
|
+
return { type: toolCalls.length ? "tool_call" : "text", text,
|
|
230
|
+
toolCalls: toolCalls.length ? toolCalls : undefined, usage, finishReason, raw };
|
|
231
|
+
}
|
|
232
|
+
|
|
164
233
|
async *stream(messages: Message[], tools?: ToolDefinition[], opts?: LLMCallOptions): AsyncIterable<LLMChunk> {
|
|
165
234
|
const request = new ProviderRequest(opts);
|
|
166
235
|
yield* request.watch(this.streamResponse(messages, tools, opts, request));
|
|
@@ -168,8 +237,9 @@ export class OpenAIResponsesProvider implements LLMProvider {
|
|
|
168
237
|
|
|
169
238
|
private async *streamResponse(messages: Message[], tools: ToolDefinition[] | undefined, opts: LLMCallOptions | undefined, request: ProviderRequest): AsyncIterable<LLMChunk> {
|
|
170
239
|
const body = this.body(messages, tools, opts, true);
|
|
171
|
-
request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
|
|
172
|
-
const
|
|
240
|
+
request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.codex ? CODEX_RESPONSES_BASE_URL : this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
|
|
241
|
+
const client = await this.requestClient(request);
|
|
242
|
+
const stream = await request.wait(client.responses.create({ ...body, stream: true }, { signal: request.signal, maxRetries: 0 }));
|
|
173
243
|
request.responseReceived();
|
|
174
244
|
let emittedText = "";
|
|
175
245
|
try {
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** Account-advertised capabilities for an exact request model ID. */
|
|
2
|
+
export interface ModelReasoning {
|
|
3
|
+
levels: Array<{ effort: string; description?: string }>;
|
|
4
|
+
defaultEffort?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function effortName(value: unknown): value is string {
|
|
8
|
+
return typeof value === "string" && /^[a-zA-Z0-9_-]{1,64}$/.test(value);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Missing/malformed is unknown; an explicit empty array means no override. */
|
|
12
|
+
export function normalizeModelReasoning(levels: unknown, defaultEffort?: unknown): ModelReasoning | undefined {
|
|
13
|
+
if (!Array.isArray(levels)) return undefined;
|
|
14
|
+
const result: ModelReasoning = { levels: [] };
|
|
15
|
+
const seen = new Set<string>();
|
|
16
|
+
for (const level of levels) {
|
|
17
|
+
if (!level || typeof level !== "object" || !effortName(level.effort)) return undefined;
|
|
18
|
+
const key = level.effort.toLowerCase();
|
|
19
|
+
if (seen.has(key)) continue;
|
|
20
|
+
seen.add(key);
|
|
21
|
+
const description = typeof level.description === "string"
|
|
22
|
+
? level.description.replace(/[\x00-\x1f\x7f-\x9f]/g, " ").slice(0, 256) : undefined;
|
|
23
|
+
result.levels.push({ effort: level.effort, ...(description ? { description } : {}) });
|
|
24
|
+
}
|
|
25
|
+
const canonical = typeof defaultEffort === "string"
|
|
26
|
+
? result.levels.find(level => level.effort.toLowerCase() === defaultEffort.toLowerCase())?.effort : undefined;
|
|
27
|
+
if (canonical) result.defaultEffort = canonical;
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function resolveModelEffort(profile: ModelReasoning | undefined, value: unknown): string | undefined {
|
|
32
|
+
if (typeof value !== "string") return undefined;
|
|
33
|
+
return profile ? profile.levels.find(level => level.effort.toLowerCase() === value.toLowerCase())?.effort : value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function normalizeReasoningMap(value: unknown): Record<string, ModelReasoning> | undefined {
|
|
37
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
38
|
+
const entries = Object.entries(value).flatMap(([model, raw]) => {
|
|
39
|
+
if (!model || model.length > 256 || /[\x00-\x1f\x7f]/.test(model) || !raw || typeof raw !== "object") return [];
|
|
40
|
+
const profile = normalizeModelReasoning(raw.levels, raw.defaultEffort);
|
|
41
|
+
return profile ? [[model, profile]] : [];
|
|
42
|
+
});
|
|
43
|
+
return entries.length ? Object.fromEntries(entries) : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function modelReasoningFor(profiles: Record<string, ModelReasoning> | undefined, model: string): ModelReasoning | undefined {
|
|
47
|
+
return profiles && Object.hasOwn(profiles, model) ? profiles[model] : undefined;
|
|
48
|
+
}
|