zapagent 1.14.19 → 1.14.21
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 +3 -1
- package/README.zh-CN.md +2 -2
- package/package.json +1 -1
- package/src/App.tsx +4 -1
- package/src/agent-factory.ts +6 -1
- package/src/cli-routing.ts +0 -14
- package/src/codex-auth-command.ts +44 -0
- package/src/codex-auth.ts +233 -0
- package/src/codex-provider.ts +37 -0
- package/src/commands/dispatcher.ts +7 -2
- package/src/config.ts +5 -3
- package/src/goal-view.ts +2 -2
- package/src/headless/run.ts +9 -0
- package/src/headless/runHeadless.ts +1 -1
- package/src/hooks/useAskUser.ts +11 -9
- package/src/hooks/usePendingInteraction.ts +37 -0
- package/src/hooks/usePlanMode.ts +26 -30
- package/src/imageStore.ts +72 -16
- package/src/index.tsx +9 -17
- package/src/provider-catalog.ts +11 -0
- package/src/session.ts +8 -3
- package/src/ui/dialog-codex-login.tsx +44 -0
- package/src/ui/dialog-connect.tsx +12 -3
- package/src/ui/provider-directory.tsx +4 -2
- package/zapsdk/builtin-tools/ask-user.ts +3 -3
- package/zapsdk/builtin-tools/edit.ts +6 -1
- package/zapsdk/builtin-tools/http.ts +24 -2
- package/zapsdk/builtin-tools/multi-edit.ts +7 -1
- package/zapsdk/builtin-tools/plan-mode.ts +3 -3
- package/zapsdk/checkpoint/index.ts +4 -1
- package/zapsdk/context/reactive-compact.ts +15 -0
- package/zapsdk/coordinator/coordinator.ts +13 -4
- package/zapsdk/core/providers/openai-compatible.ts +1 -0
- package/zapsdk/core/providers/openai-responses.ts +64 -6
- package/zapsdk/debug/agent-logger.ts +4 -1
- package/zapsdk/mcp/manager.ts +75 -43
- package/zapsdk/skills/template.ts +5 -3
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
|
|
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/App.tsx
CHANGED
|
@@ -525,7 +525,10 @@ export function App() {
|
|
|
525
525
|
// any history entry) and ~/.zapcode/image-cache/ (SVG/URL caches older
|
|
526
526
|
// than CACHE_TTL). Runs once after first render so it doesn't block
|
|
527
527
|
// startup.
|
|
528
|
-
useEffect(() => {
|
|
528
|
+
useEffect(() => {
|
|
529
|
+
const pruned = pruneImageStorage()
|
|
530
|
+
if (pruned.skipped) appLogger.warn("image_prune_skipped", { reason: pruned.skipped })
|
|
531
|
+
}, [])
|
|
529
532
|
|
|
530
533
|
// ── Track journal index at the start of each turn (for checkpoint slicing) ──
|
|
531
534
|
const turnStartLogIndexRef = useRef(0)
|
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 },
|
|
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),
|
package/src/cli-routing.ts
CHANGED
|
@@ -31,20 +31,6 @@ export function devtoolsPortFromArgs(argv: readonly string[]): string | null {
|
|
|
31
31
|
return maybePort && /^\d+$/.test(maybePort) ? maybePort : "9229"
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
export type HeadlessCwdArg =
|
|
35
|
-
| { ok: true; cwd?: string }
|
|
36
|
-
| { ok: false; message: string }
|
|
37
|
-
|
|
38
|
-
export function headlessCwdFromArgs(argv: readonly string[]): HeadlessCwdArg {
|
|
39
|
-
const cwdIdx = argv.findIndex(a => a === "--cwd")
|
|
40
|
-
if (cwdIdx < 0) return { ok: true }
|
|
41
|
-
const value = argv[cwdIdx + 1]
|
|
42
|
-
if (value === undefined || (value.startsWith("-") && !/^-?\d/.test(value))) {
|
|
43
|
-
return { ok: false, message: "--cwd requires a value" }
|
|
44
|
-
}
|
|
45
|
-
return { ok: true, cwd: value }
|
|
46
|
-
}
|
|
47
|
-
|
|
48
34
|
function isValueFlag(flag: string): boolean {
|
|
49
35
|
return flag === "--cwd" ||
|
|
50
36
|
flag === "--public-checks" ||
|
|
@@ -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,37 @@
|
|
|
1
|
+
import { CODEX_BASE_URL, getCodexCredentials } from "./codex-auth.js"
|
|
2
|
+
import { VERSION } from "./version.js"
|
|
3
|
+
import { setActive, upsertProvider, type AppConfig, type Provider, type ProviderModelMetadata } from "./config.js"
|
|
4
|
+
|
|
5
|
+
/** One explicit account binding; secrets live only in codex-oauth.json. */
|
|
6
|
+
export function connectCodexProvider(config: AppConfig): { config: AppConfig; provider: Provider } {
|
|
7
|
+
const existing = config.providers.find(p => p.authMode === "codex-oauth")
|
|
8
|
+
const provider: Provider = { ...existing, id: existing?.id ?? "sp_codex_oauth", name: existing?.name ?? "OpenAI Codex (ChatGPT)",
|
|
9
|
+
baseURL: CODEX_BASE_URL, apiKey: "", authMode: "codex-oauth", protocol: "openai-responses",
|
|
10
|
+
contextWindow: existing?.contextWindow ?? 128000, contextWindowMode: existing?.contextWindowMode ?? "auto",
|
|
11
|
+
models: existing?.models ?? [] }
|
|
12
|
+
let next = upsertProvider(config, provider)
|
|
13
|
+
if (provider.models.length && config.active.providerId === provider.id) next = setActive(next, provider.id, config.active.model)
|
|
14
|
+
return { config: next, provider }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function discoverCodexModels(signal: AbortSignal): Promise<Array<{ id: string; metadata: ProviderModelMetadata }>> {
|
|
18
|
+
const credentials = await getCodexCredentials(signal)
|
|
19
|
+
const response = await fetch(`${CODEX_BASE_URL}/models?client_version=${encodeURIComponent(VERSION)}`, {
|
|
20
|
+
headers: { Authorization: `Bearer ${credentials.accessToken}`, originator: "zap",
|
|
21
|
+
...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) },
|
|
22
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(6000)]), redirect: "error",
|
|
23
|
+
})
|
|
24
|
+
if (!response.ok) throw new Error(`Codex model discovery failed (HTTP ${response.status}).`)
|
|
25
|
+
const data = await response.json() as { models?: Array<Record<string, unknown>> }
|
|
26
|
+
if (!Array.isArray(data.models)) throw new Error("Invalid Codex models response.")
|
|
27
|
+
return data.models.flatMap(model => {
|
|
28
|
+
// supported_in_api only gates API-key accounts; Codex OAuth can use backend-only models.
|
|
29
|
+
if (typeof model.slug !== "string" || !model.slug || model.visibility === "hide" || model.visibility === "hidden") return []
|
|
30
|
+
return [{ id: model.slug, metadata: {
|
|
31
|
+
name: typeof model.display_name === "string" ? model.display_name : undefined,
|
|
32
|
+
contextWindow: typeof model.context_window === "number" && model.context_window > 0 ? model.context_window : undefined,
|
|
33
|
+
supportsVision: Array.isArray(model.input_modalities) ? model.input_modalities.includes("image") : undefined,
|
|
34
|
+
toolCall: true, reasoning: true, source: "provider" as const,
|
|
35
|
+
} }]
|
|
36
|
+
})
|
|
37
|
+
}
|
|
@@ -369,8 +369,13 @@ export function dispatchSlashCommand(
|
|
|
369
369
|
// session linger in memory under the old id (harmless — listSnapshots
|
|
370
370
|
// filters by the current id and won't surface them), but newly
|
|
371
371
|
// committed snapshots all label + persist under the new id.
|
|
372
|
+
try {
|
|
373
|
+
startNewSession()
|
|
374
|
+
} catch (error) {
|
|
375
|
+
deps.addToast(`Could not start a new session: ${error instanceof Error ? error.message : String(error)}. Retry /new after storage recovers.`, { variant: "error" })
|
|
376
|
+
return true
|
|
377
|
+
}
|
|
372
378
|
wipeTerminalScrollback()
|
|
373
|
-
startNewSession()
|
|
374
379
|
resetConversationState()
|
|
375
380
|
deps.checkpointRef.current.setSessionId(getCurrentSessionId())
|
|
376
381
|
deps.bumpTranscript()
|
|
@@ -828,7 +833,7 @@ export function dispatchSlashCommand(
|
|
|
828
833
|
const params = skill.parameters ?? []
|
|
829
834
|
let prompt = skill.systemPrompt
|
|
830
835
|
if (params.length === 1 && params[0])
|
|
831
|
-
prompt = prompt.replaceAll(`{{${params[0].name}}}`, tail)
|
|
836
|
+
prompt = prompt.replaceAll(`{{${params[0].name}}}`, () => tail)
|
|
832
837
|
const displayTail = displayCommand?.type === "run_skill" && displayCommand.skill === skillName
|
|
833
838
|
? runSkillTailFromRawCommand(meta.displayText ?? "", skillName) ?? (displayCommand.skillInput ?? "").trim()
|
|
834
839
|
: undefined
|
package/src/config.ts
CHANGED
|
@@ -93,7 +93,7 @@ export interface Provider {
|
|
|
93
93
|
name: string // display alias (empty → falls back to baseURL)
|
|
94
94
|
baseURL: string
|
|
95
95
|
apiKey: string // empty for keyless endpoints (Ollama)
|
|
96
|
-
authMode?: "api-key" | "none"
|
|
96
|
+
authMode?: "api-key" | "none" | "codex-oauth"
|
|
97
97
|
/** Exact public catalog identity, independent of endpoint and user alias. */
|
|
98
98
|
catalogProviderId?: string
|
|
99
99
|
contextWindow: number
|
|
@@ -453,7 +453,7 @@ function normalizeProvider(value: unknown, index: number): Provider | null {
|
|
|
453
453
|
name: typeof value.name === "string" ? value.name : "",
|
|
454
454
|
baseURL: typeof value.baseURL === "string" ? value.baseURL : "",
|
|
455
455
|
apiKey: typeof value.apiKey === "string" ? value.apiKey : "",
|
|
456
|
-
authMode: value.authMode === "none" ? "none" : value.authMode === "api-key" ? "api-key" : undefined,
|
|
456
|
+
authMode: value.authMode === "codex-oauth" ? "codex-oauth" : value.authMode === "none" ? "none" : value.authMode === "api-key" ? "api-key" : undefined,
|
|
457
457
|
catalogProviderId: typeof value.catalogProviderId === "string" ? value.catalogProviderId : undefined,
|
|
458
458
|
contextWindow: positiveIntegerOrDefault(value.contextWindow, 128000),
|
|
459
459
|
models: Array.isArray(value.models)
|
|
@@ -750,6 +750,8 @@ export function hasApiKey(config: AppConfig): boolean {
|
|
|
750
750
|
const p = getActiveProvider(config)
|
|
751
751
|
if (!p) return false
|
|
752
752
|
if (p.authMode === "none") return true
|
|
753
|
+
// The transport resolves OAuth credentials lazily, including logout/refresh.
|
|
754
|
+
if (p.authMode === "codex-oauth") return true
|
|
753
755
|
// Keyless endpoints (Ollama) are detected via their source preset's
|
|
754
756
|
// requiresApiKey flag; providers with no sourcePresetId must always have a key.
|
|
755
757
|
const preset = p.sourcePresetId ? presetMap.get(p.sourcePresetId) : undefined
|
|
@@ -1087,7 +1089,7 @@ export function formatStatus(config: AppConfig, configPath: string): string {
|
|
|
1087
1089
|
]
|
|
1088
1090
|
if (effort) lines.push(`Reasoning effort: ${effort}`)
|
|
1089
1091
|
lines.push(
|
|
1090
|
-
`API key: ${maskSecret(p?.apiKey ?? "")}`,
|
|
1092
|
+
p?.authMode === "codex-oauth" ? "Authentication: Codex OAuth (ChatGPT)" : `API key: ${maskSecret(p?.apiKey ?? "")}`,
|
|
1091
1093
|
`Serper key: ${maskSecret(config.serperKey)}`,
|
|
1092
1094
|
`Max tokens: ${config.maxTokens}`,
|
|
1093
1095
|
`Max steps: ${config.maxSteps}`,
|
package/src/goal-view.ts
CHANGED
|
@@ -45,9 +45,9 @@ export function goalObjectiveText(objective: string): string {
|
|
|
45
45
|
export function goalActionText(goal: GoalView, attached: boolean, todos: readonly Todo[] = [], activeTool = ""): string {
|
|
46
46
|
if (goal.status === "completed") return goal.accepted ? "目标已完成,验收通过" : "目标已完成"
|
|
47
47
|
if (goal.status === "cancelled") return "目标已取消"
|
|
48
|
-
if (goal.status === "failed") return
|
|
48
|
+
if (goal.status === "failed") return `/goal status ${goal.id} · 目标执行失败`
|
|
49
49
|
if (goal.status === "paused") return goal.stopReason === "DEADLINE_EXCEEDED" ? "已达到你设置的时间限制" : "已暂停,进度已保留"
|
|
50
|
-
if (goal.status === "blocked") return
|
|
50
|
+
if (goal.status === "blocked") return `/goal status ${goal.id} · 目标暂时无法继续`
|
|
51
51
|
if (goal.status === "awaiting_acceptance") return "等待补充信息或确认"
|
|
52
52
|
if (goal.status === "budget_limited") return "已达到你设置的用量限制"
|
|
53
53
|
if (goal.status === "ready_for_delivery") return goal.accepted ? "验收通过,等待交付授权" : "等待交付授权"
|
package/src/headless/run.ts
CHANGED
|
@@ -7,6 +7,15 @@ import { parseHeadlessArgs, readStdinIfPiped, HEADLESS_HELP } from "./args.js"
|
|
|
7
7
|
const EXIT_BAD_ARGS = 2
|
|
8
8
|
|
|
9
9
|
async function runParsedHeadless(args: import("./args.js").HeadlessArgs, watch?: import("../watch/args.js").WatchOptions): Promise<number> {
|
|
10
|
+
// Apply the fully parsed value exactly once, before importing singletons
|
|
11
|
+
// through Watch/runtime. Repeated --cwd follows the parser's last-value rule.
|
|
12
|
+
if (args.cwd) {
|
|
13
|
+
try { process.chdir(args.cwd) }
|
|
14
|
+
catch (err) {
|
|
15
|
+
process.stderr.write(`bad --cwd: ${err instanceof Error ? err.message : String(err)}\n`)
|
|
16
|
+
return EXIT_BAD_ARGS
|
|
17
|
+
}
|
|
18
|
+
}
|
|
10
19
|
const viewer = watch?.enabled ? await import("../watch/integration.js") : undefined
|
|
11
20
|
if (viewer) {
|
|
12
21
|
try { await viewer.startWatch(watch!) }
|
|
@@ -331,7 +331,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
331
331
|
}
|
|
332
332
|
|
|
333
333
|
// ── Determine working directory ──────────────────────────────────────
|
|
334
|
-
// NOTE: actual `process.chdir(args.cwd)` happens earlier in
|
|
334
|
+
// NOTE: actual `process.chdir(args.cwd)` happens earlier in headless/run.ts,
|
|
335
335
|
// *before* singletons.ts loads, so autoMemory / mdStore / permissionManager
|
|
336
336
|
// all get constructed with the user-requested cwd. By the time we get
|
|
337
337
|
// here, process.cwd() already reflects --cwd. We just use it.
|
package/src/hooks/useAskUser.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { useMemo
|
|
1
|
+
import { useMemo } from "react"
|
|
2
2
|
import type { AskUserAnswer, AskUserCallbacks, AskUserQuestion } from "../../zapsdk/index.js"
|
|
3
3
|
|
|
4
|
+
import { usePendingInteraction } from "./usePendingInteraction.js"
|
|
5
|
+
|
|
4
6
|
export interface PendingQuestions {
|
|
5
7
|
questions: AskUserQuestion[]
|
|
6
8
|
/** null = the user dismissed the questions. */
|
|
@@ -17,14 +19,14 @@ export interface UseAskUserResult {
|
|
|
17
19
|
/** One question set at a time: the tool executor runs `ask_user_question`
|
|
18
20
|
* exclusively, so a second `ask` can only arrive after the first resolved. */
|
|
19
21
|
export function useAskUser(): UseAskUserResult {
|
|
20
|
-
const
|
|
22
|
+
const { pending, request } = usePendingInteraction<AskUserQuestion[], AskUserAnswer[] | null>()
|
|
21
23
|
const askUserCallbacks = useMemo<AskUserCallbacks>(() => ({
|
|
22
|
-
ask: (questions) =>
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
ask: (questions, signal) => request(questions, null, signal),
|
|
25
|
+
}), [request])
|
|
26
|
+
// Keep identity stable across renders; App effects depend on this value.
|
|
27
|
+
const pendingQuestions = useMemo(
|
|
28
|
+
() => pending ? { questions: pending.value, resolve: pending.resolve } : null,
|
|
29
|
+
[pending],
|
|
30
|
+
)
|
|
29
31
|
return { askUserCallbacks, pendingQuestions }
|
|
30
32
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react"
|
|
2
|
+
|
|
3
|
+
/** A single, cancellable UI interaction. Old resolvers cannot settle a newer
|
|
4
|
+
* request; unmount settles the waiter without updating an unmounted view. */
|
|
5
|
+
export function usePendingInteraction<Value, Answer>() {
|
|
6
|
+
const [pending, setPending] = useState<{ value: Value; resolve: (answer: Answer) => void } | null>(null)
|
|
7
|
+
const cancelRef = useRef<(() => void) | null>(null)
|
|
8
|
+
const mounted = useRef(true)
|
|
9
|
+
|
|
10
|
+
useEffect(() => {
|
|
11
|
+
mounted.current = true
|
|
12
|
+
return () => {
|
|
13
|
+
mounted.current = false
|
|
14
|
+
cancelRef.current?.()
|
|
15
|
+
}
|
|
16
|
+
}, [])
|
|
17
|
+
|
|
18
|
+
const request = useCallback((value: Value, cancelled: Answer, signal?: AbortSignal): Promise<Answer> => {
|
|
19
|
+
if (!mounted.current || signal?.aborted) return Promise.resolve(cancelled)
|
|
20
|
+
cancelRef.current?.()
|
|
21
|
+
return new Promise((resolve) => {
|
|
22
|
+
const settle = (answer: Answer) => {
|
|
23
|
+
if (cancelRef.current !== cancel) return
|
|
24
|
+
cancelRef.current = null
|
|
25
|
+
signal?.removeEventListener("abort", cancel)
|
|
26
|
+
if (mounted.current) setPending(null)
|
|
27
|
+
resolve(answer)
|
|
28
|
+
}
|
|
29
|
+
const cancel = () => settle(cancelled)
|
|
30
|
+
cancelRef.current = cancel
|
|
31
|
+
signal?.addEventListener("abort", cancel, { once: true })
|
|
32
|
+
setPending({ value, resolve: settle })
|
|
33
|
+
})
|
|
34
|
+
}, [])
|
|
35
|
+
|
|
36
|
+
return { pending, request }
|
|
37
|
+
}
|