zapagent 1.14.28 → 1.14.30
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 +2 -4
- package/README.zh-CN.md +1 -3
- package/bundled-dependencies.json +197 -197
- package/package.json +1 -1
- package/src/App.tsx +20 -16
- package/src/acp/agent.ts +2 -1
- package/src/agent/cacheScope.ts +11 -0
- package/src/agent/claude-code.ts +160 -0
- package/src/agent/official-agents.ts +83 -0
- package/src/agent/outputThroughput.ts +27 -0
- package/src/agent/remote-agent.ts +5 -2
- package/src/agent/remote-turn.ts +42 -6
- package/src/agent/wireRunHandlers.ts +6 -7
- package/src/agent-factory.ts +3 -15
- package/src/codex-auth-command.ts +14 -27
- package/src/codex-auth.ts +25 -227
- package/src/codex-provider.ts +9 -11
- package/src/commands/dispatcher.ts +26 -9
- package/src/commands/status.ts +9 -7
- package/src/config.ts +18 -4
- package/src/headless/runHeadless.ts +9 -0
- package/src/hooks/useAgentRunner.ts +25 -6
- package/src/index.tsx +2 -2
- package/src/ui/dialog-codex-login.tsx +15 -19
- package/src/ui/dialog-config.tsx +3 -1
- package/src/ui/dialog-connect.tsx +9 -5
- package/src/ui/dialog-model.tsx +82 -22
- package/src/ui/footer.tsx +10 -8
- package/src/ui/provider-directory.tsx +5 -3
- package/zapsdk/acp-client/event-mapper.ts +9 -2
- package/zapsdk/acp-client/host-handlers.ts +18 -4
- package/zapsdk/acp-client/run.ts +6 -1
- package/zapsdk/acp-client/types.ts +2 -0
- package/zapsdk/execution/process.ts +9 -2
package/src/agent-factory.ts
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { VERSION } from "./version.js"
|
|
2
|
-
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
3
|
-
import { generateCodexImage } from "../zapsdk/core/providers/codex-image-generation.js"
|
|
4
2
|
import { modelCanonicalIds } from "./provider-metadata.js"
|
|
5
|
-
import { getCodexCredentials } from "./codex-auth.js"
|
|
6
3
|
import { serviceTools } from "../zapsdk/services/tools.js"
|
|
7
4
|
// Builds the per-turn agent objects (provider, registry, executor) from
|
|
8
5
|
// the app config. Split out of App.tsx — pure factory, no React state.
|
|
@@ -25,7 +22,7 @@ import {
|
|
|
25
22
|
type SandboxMode,
|
|
26
23
|
} from "../zapsdk/index.js"
|
|
27
24
|
import type { AppConfig } from "./config.js"
|
|
28
|
-
import { getActiveMaxOutputTokens, getActiveProvider, resolveVisionSupport } from "./config.js"
|
|
25
|
+
import { conversationAgentId, getActiveMaxOutputTokens, getActiveProvider, resolveVisionSupport } from "./config.js"
|
|
29
26
|
import type { CheckpointManager } from "../zapsdk/checkpoint/index.js"
|
|
30
27
|
import { loadAllSkills } from "../zapsdk/skills/loader.js"
|
|
31
28
|
import type { SkillDefinition } from "../zapsdk/skills/types.js"
|
|
@@ -87,11 +84,6 @@ export function buildAgentObjects(
|
|
|
87
84
|
const apiKey = rawApiKey || "unconfigured"
|
|
88
85
|
const model = config.active.model
|
|
89
86
|
const maxOutputTokens = getActiveMaxOutputTokens(config)
|
|
90
|
-
const imageCapability = active?.authMode === "codex-oauth" ? {
|
|
91
|
-
generate: (request: import("../zapsdk/core/providers/codex-image-generation.js").ImageGenerationRequest, signal?: AbortSignal) =>
|
|
92
|
-
generateCodexImage({ model: typeof active.extraRequestParams?.model === "string" ? active.extraRequestParams.model : model, getCredentials: getCodexCredentials }, request, signal),
|
|
93
|
-
artifactDirectory: join(getAppDataDir(), "generated-images"),
|
|
94
|
-
} : undefined
|
|
95
87
|
// Protocol selection: explicit `protocol` field on the provider wins;
|
|
96
88
|
// fall back to host substring detection so legacy configs (saved before
|
|
97
89
|
// the field existed) still route the official Anthropic endpoint to
|
|
@@ -127,10 +119,8 @@ export function buildAgentObjects(
|
|
|
127
119
|
"x-stainless-runtime-version": null,
|
|
128
120
|
} as unknown as Record<string, string>
|
|
129
121
|
: undefined
|
|
130
|
-
const rawProvider = active?.authMode === "codex-oauth"
|
|
131
|
-
?
|
|
132
|
-
canonicalModelIds: modelCanonicalIds(active), supportsVision: resolveVisionSupport(active, model),
|
|
133
|
-
extraRequestParams: active.extraRequestParams, maxRequestBytes: active.maxRequestBytes })
|
|
122
|
+
const rawProvider = active?.authMode === "codex-oauth" || conversationAgentId(config) === "claude-code"
|
|
123
|
+
? { async call(): Promise<never> { throw new Error("Subscription conversations run in their native agent. Select an API provider for the Zap runtime.") } }
|
|
134
124
|
: isAnthropic
|
|
135
125
|
? new AnthropicProvider({
|
|
136
126
|
maxRequestBytes: active?.maxRequestBytes,
|
|
@@ -181,7 +171,6 @@ export function buildAgentObjects(
|
|
|
181
171
|
globFiles: { allowedPaths, useExecutionGrants: true },
|
|
182
172
|
documentRead: { allowedPaths, useExecutionGrants: true },
|
|
183
173
|
browserScreenshot: { allowedPaths },
|
|
184
|
-
generateImage: imageCapability ? { ...imageCapability, allowedPaths, protectedPaths, useExecutionGrants: true, defaultCwd: effectiveCwd } : undefined,
|
|
185
174
|
executeCommand: {
|
|
186
175
|
timeoutMs: 60000,
|
|
187
176
|
defaultCwd: effectiveCwd,
|
|
@@ -256,7 +245,6 @@ export function buildAgentObjects(
|
|
|
256
245
|
globFiles: { allowedPaths, useExecutionGrants: true },
|
|
257
246
|
documentRead: { allowedPaths, useExecutionGrants: true },
|
|
258
247
|
browserScreenshot: { allowedPaths },
|
|
259
|
-
generateImage: imageCapability ? { ...imageCapability, allowedPaths, protectedPaths, useExecutionGrants: true, defaultCwd: workspaceCwd } : undefined,
|
|
260
248
|
executeCommand: {
|
|
261
249
|
timeoutMs: 60000,
|
|
262
250
|
defaultCwd: workspaceCwd,
|
|
@@ -2,43 +2,30 @@ import { join } from "node:path"
|
|
|
2
2
|
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
3
3
|
import { loadAppConfig, saveAppConfig } from "./config.js"
|
|
4
4
|
import { connectCodexProvider } from "./codex-provider.js"
|
|
5
|
-
import {
|
|
6
|
-
startCodexBrowserLogin, startCodexDeviceLogin } from "./codex-auth.js"
|
|
5
|
+
import { runCodexAuth } from "./codex-auth.js"
|
|
7
6
|
|
|
8
7
|
export async function runCodexAuthCommand(args: string[]): Promise<number> {
|
|
9
8
|
const [action, provider, ...flags] = args
|
|
10
|
-
if (
|
|
9
|
+
if ((action !== "login" && action !== "logout" && action !== "status") || provider !== "codex" ||
|
|
11
10
|
flags.some(flag => flag !== "--device-code" || action !== "login")) {
|
|
12
11
|
console.error("Usage: zap auth login codex [--device-code] | zap auth logout codex | zap auth status codex")
|
|
13
12
|
return 2
|
|
14
13
|
}
|
|
14
|
+
const controller = new AbortController()
|
|
15
|
+
const cancel = () => controller.abort()
|
|
16
|
+
process.once("SIGINT", cancel)
|
|
17
|
+
process.once("SIGTERM", cancel)
|
|
15
18
|
try {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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()
|
|
19
|
+
const status = await runCodexAuth(action, { device: flags.includes("--device-code"), signal: controller.signal,
|
|
20
|
+
onOutput: text => process.stderr.write(text) })
|
|
21
|
+
if (action === "login" && !status) {
|
|
34
22
|
const path = join(getAppDataDir(), "config.json")
|
|
35
|
-
// Read after login so an in-flight TUI edit is not overwritten by an old snapshot.
|
|
36
23
|
saveAppConfig(path, connectCodexProvider(loadAppConfig(path)).config)
|
|
37
|
-
console.log("Codex connected.
|
|
38
|
-
|
|
39
|
-
|
|
24
|
+
console.log("Codex connected. Choose its model with /model in Zap.")
|
|
25
|
+
}
|
|
26
|
+
return status
|
|
40
27
|
} catch (error) {
|
|
41
|
-
console.error(error instanceof Error ? error.message : "Codex
|
|
28
|
+
console.error(error instanceof Error ? error.message : "Codex authentication failed")
|
|
42
29
|
return 1
|
|
43
|
-
}
|
|
30
|
+
} finally { process.off("SIGINT", cancel); process.off("SIGTERM", cancel) }
|
|
44
31
|
}
|
package/src/codex-auth.ts
CHANGED
|
@@ -1,233 +1,31 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { spawn } from "node:child_process"
|
|
6
|
-
import { setTimeout as delay } from "node:timers/promises"
|
|
1
|
+
import { nativeCommand } from "./agent/official-agents.js"
|
|
2
|
+
import { createLocalProcessBroker } from "../zapsdk/execution/process.js"
|
|
3
|
+
import { rm } from "node:fs/promises"
|
|
4
|
+
import { join } from "node:path"
|
|
7
5
|
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
8
|
-
import { writeFileAtomic } from "./utils/secure-write.js"
|
|
9
6
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
|
7
|
+
/** Authentication stays in the official CLI's credential store. Only its login
|
|
8
|
+
* instructions and exit status are exposed to the host. */
|
|
9
|
+
export async function runCodexAuth(action: "login" | "logout" | "status", options: {
|
|
10
|
+
device?: boolean
|
|
11
|
+
signal?: AbortSignal
|
|
12
|
+
onOutput?: (text: string) => void
|
|
13
|
+
} = {}): Promise<number> {
|
|
14
|
+
const args = action === "status" ? ["login", "status"] : [action]
|
|
15
|
+
if (action === "login" && options.device) args.push("--device-auth")
|
|
16
|
+
const cli = await nativeCommand("codex")
|
|
17
|
+
const status = await new Promise<number>((resolve, reject) => {
|
|
18
|
+
const child = createLocalProcessBroker(options.signal).spawnCommand(cli.command, [...cli.args, ...args], { cwd: process.cwd(), hostHome: true })
|
|
19
|
+
for (const stream of [child.stdout!, child.stderr!]) {
|
|
20
|
+
stream.setEncoding("utf8")
|
|
21
|
+
stream.on("data", (text: string) => options.onOutput?.(text))
|
|
171
22
|
}
|
|
172
|
-
|
|
173
|
-
|
|
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.")
|
|
23
|
+
child.once("error", reject)
|
|
24
|
+
child.once("close", code => resolve(code ?? 1))
|
|
177
25
|
})
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
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
|
|
26
|
+
options.signal?.throwIfAborted()
|
|
27
|
+
if (action === "logout" && status === 0) {
|
|
28
|
+
await rm(join(getAppDataDir(), "codex-oauth.json"), { force: true })
|
|
191
29
|
}
|
|
192
|
-
|
|
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() }
|
|
30
|
+
return status
|
|
233
31
|
}
|
package/src/codex-provider.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { nativeCommand } from "./agent/official-agents.js"
|
|
2
|
+
import { execFile } from "node:child_process"
|
|
3
|
+
import { promisify } from "node:util"
|
|
2
4
|
import { normalizeModelReasoning, type ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
|
|
3
|
-
import { VERSION } from "./version.js"
|
|
4
5
|
import { setActive, upsertProvider, type AppConfig, type Provider, type ProviderModelMetadata } from "./config.js"
|
|
5
6
|
|
|
6
|
-
/**
|
|
7
|
+
/** Compatibility marker for an official Codex runtime connection. */
|
|
7
8
|
export function connectCodexProvider(config: AppConfig): { config: AppConfig; provider: Provider } {
|
|
8
9
|
const existing = config.providers.find(p => p.authMode === "codex-oauth")
|
|
9
10
|
const provider: Provider = { ...existing, id: existing?.id ?? "sp_codex_oauth", name: existing?.name ?? "OpenAI Codex (ChatGPT)",
|
|
10
|
-
baseURL:
|
|
11
|
+
baseURL: "codex://local", apiKey: "", authMode: "codex-oauth", protocol: "openai-responses",
|
|
11
12
|
contextWindow: existing?.contextWindow ?? 128000, contextWindowMode: existing?.contextWindowMode ?? "auto",
|
|
12
13
|
models: existing?.models ?? [] }
|
|
13
14
|
let next = upsertProvider(config, provider)
|
|
@@ -16,14 +17,11 @@ export function connectCodexProvider(config: AppConfig): { config: AppConfig; pr
|
|
|
16
17
|
}
|
|
17
18
|
|
|
18
19
|
export async function discoverCodexModels(signal: AbortSignal): Promise<Array<{ id: string; metadata: ProviderModelMetadata; reasoning?: ModelReasoning }>> {
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) },
|
|
23
|
-
signal: AbortSignal.any([signal, AbortSignal.timeout(6000)]), redirect: "error",
|
|
20
|
+
const cli = await nativeCommand("codex")
|
|
21
|
+
const { stdout } = await promisify(execFile)(cli.command, [...cli.args, "debug", "models"], {
|
|
22
|
+
signal, timeout: 6500, maxBuffer: 8 * 1024 * 1024, encoding: "utf8",
|
|
24
23
|
})
|
|
25
|
-
|
|
26
|
-
const data = await response.json() as { models?: Array<Record<string, unknown>> }
|
|
24
|
+
const data = JSON.parse(stdout) as { models?: Array<Record<string, unknown>> }
|
|
27
25
|
if (!Array.isArray(data.models)) throw new Error("Invalid Codex models response.")
|
|
28
26
|
return data.models.flatMap(model => {
|
|
29
27
|
// supported_in_api only gates API-key accounts; Codex OAuth can use backend-only models.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { agentInstallHint } from "../agent/official-agents.js"
|
|
1
2
|
import { AgentBudget } from "../../zapsdk/agent/budget.js"
|
|
2
3
|
import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
|
|
3
4
|
import { recordMaintenanceUsage } from "../agent/maintenanceUsage.js"
|
|
@@ -6,7 +7,7 @@ import { spawnSync } from "node:child_process"
|
|
|
6
7
|
import { parsePermissionMode, type AppConfig, type PermissionMode } from "../config.js"
|
|
7
8
|
import {
|
|
8
9
|
cycleEffort,
|
|
9
|
-
getActiveProvider,
|
|
10
|
+
agentManagingModel, conversationAgentId, getActiveProvider,
|
|
10
11
|
resolveEffortInput,
|
|
11
12
|
setEffort,
|
|
12
13
|
validateConfig,
|
|
@@ -327,8 +328,8 @@ export function dispatchSlashCommand(
|
|
|
327
328
|
const dispatchAgentTurn = (...args: Parameters<DispatchSlashCommandDeps["dispatchUserTurn"]>): boolean | Promise<boolean> => {
|
|
328
329
|
// /review, /commit, /init and skills carry zap prompts written for zap's
|
|
329
330
|
// own tools; an external agent would silently ignore them.
|
|
330
|
-
if (deps.configRef.current
|
|
331
|
-
deps.addLog("error", `${displayCommand?.type ?? cmd.type} runs on zap's own model, not ${deps.configRef.current
|
|
331
|
+
if (conversationAgentId(deps.configRef.current)) {
|
|
332
|
+
deps.addLog("error", `${displayCommand?.type ?? cmd.type} runs on zap's own model, not ${conversationAgentId(deps.configRef.current)}. /agent zap switches back.`)
|
|
332
333
|
return true
|
|
333
334
|
}
|
|
334
335
|
meta.onInputRequired?.()
|
|
@@ -422,6 +423,7 @@ export function dispatchSlashCommand(
|
|
|
422
423
|
case "set_model": {
|
|
423
424
|
const next = {
|
|
424
425
|
...deps.configRef.current,
|
|
426
|
+
subscriptionAgent: undefined, activeAgent: undefined,
|
|
425
427
|
active: { ...deps.configRef.current.active, model: cmd.value ?? "" },
|
|
426
428
|
}
|
|
427
429
|
deps.updateConfig(next)
|
|
@@ -431,33 +433,38 @@ export function dispatchSlashCommand(
|
|
|
431
433
|
|
|
432
434
|
case "set_agent": {
|
|
433
435
|
const value = cmd.value ?? ""
|
|
434
|
-
const current = deps.configRef.current
|
|
436
|
+
const current = conversationAgentId(deps.configRef.current)
|
|
435
437
|
if (!value) {
|
|
436
438
|
const lines = acpAgents.length
|
|
437
439
|
? acpAgents.map(agent => ` ${agent.id === current ? "›" : " "} ${agent.id.padEnd(10)} ${agent.name ?? ""}${agent.selfGoverned ? " · edits files itself (no zap checkpoints)" : ""}`)
|
|
438
440
|
: [" (no ACP agents found on PATH or in acpAgents)"]
|
|
439
|
-
deps.addLog("system", [`Conversation agent: ${current ?? "zap"}`, ` ${current ? " " : "›"} zap zap's own model`, ...lines,
|
|
441
|
+
deps.addLog("system", [`Conversation agent: ${current ?? "zap"}`, ` ${current ? " " : "›"} zap zap's own model`, ` ${current === "claude-code" ? "›" : " "} claude-code Local Claude Code CLI`, ...lines,
|
|
440
442
|
"Switch with /agent <id>; /agent zap switches back."].join("\n"))
|
|
441
443
|
return true
|
|
442
444
|
}
|
|
443
445
|
if (value === "zap" || value === "off") {
|
|
446
|
+
if (getActiveProvider(deps.configRef.current)?.authMode === "codex-oauth") {
|
|
447
|
+
deps.setDialog("model")
|
|
448
|
+
deps.addLog("system", "Choose an API provider for Zap's own runtime. Use /connect to add one.")
|
|
449
|
+
return true
|
|
450
|
+
}
|
|
444
451
|
void remoteAgents.reset()
|
|
445
452
|
if (current) {
|
|
446
|
-
deps.updateConfig({ ...deps.configRef.current, activeAgent: undefined })
|
|
453
|
+
deps.updateConfig({ ...deps.configRef.current, activeAgent: undefined, subscriptionAgent: undefined })
|
|
447
454
|
deps.addToast("agent → zap")
|
|
448
455
|
}
|
|
449
456
|
return true
|
|
450
457
|
}
|
|
451
|
-
const spec = acpAgents.find(agent => agent.id === value)
|
|
458
|
+
const spec = value === "claude-code" ? { id: value, name: "Claude Code", selfGoverned: true } : acpAgents.find(agent => agent.id === value)
|
|
452
459
|
if (!spec) {
|
|
453
|
-
deps.addLog("error", `Unknown ACP agent: ${value}. Available: ${["zap", ...acpAgents.map(agent => agent.id)].join(", ")}`)
|
|
460
|
+
deps.addLog("error", `Unknown ACP agent: ${value}. ${agentInstallHint(value)} Available: ${["zap", "claude-code", ...acpAgents.map(agent => agent.id)].join(", ")}`)
|
|
454
461
|
return true
|
|
455
462
|
}
|
|
456
463
|
if (value !== current) {
|
|
457
464
|
void remoteAgents.reset()
|
|
458
465
|
deps.updateConfig({ ...deps.configRef.current, activeAgent: value })
|
|
459
466
|
deps.addToast(`agent → ${value}`)
|
|
460
|
-
deps.addLog("system", `Messages now go to ${spec.name ?? spec.id}
|
|
467
|
+
deps.addLog("system", `Messages now go to ${spec.name ?? spec.id} locally. Its file reads/writes and permission requests use zap's approvals${spec.selfGoverned ? "; it also edits files itself, which zap checkpoints do not cover" : ""}. /agent zap switches back.`)
|
|
461
468
|
}
|
|
462
469
|
return true
|
|
463
470
|
}
|
|
@@ -474,6 +481,11 @@ export function dispatchSlashCommand(
|
|
|
474
481
|
}
|
|
475
482
|
|
|
476
483
|
case "set_effort": {
|
|
484
|
+
const agent = agentManagingModel(deps.configRef.current)
|
|
485
|
+
if (agent) {
|
|
486
|
+
deps.addLog("system", `Reasoning effort is managed by ${agent}.`)
|
|
487
|
+
return true
|
|
488
|
+
}
|
|
477
489
|
const provider = getActiveProvider(deps.configRef.current)
|
|
478
490
|
if (!provider) {
|
|
479
491
|
deps.addLog("error", "No active provider")
|
|
@@ -547,6 +559,11 @@ export function dispatchSlashCommand(
|
|
|
547
559
|
}
|
|
548
560
|
|
|
549
561
|
case "compact_session": {
|
|
562
|
+
const agent = conversationAgentId(deps.configRef.current)
|
|
563
|
+
if (agent) {
|
|
564
|
+
deps.addLog("system", `Context compaction is managed by ${agent}.`)
|
|
565
|
+
return true
|
|
566
|
+
}
|
|
550
567
|
// Force-compact the conversation. Uses the current agent's provider as
|
|
551
568
|
// summarizer (agent.run not needed — this is a one-shot LLM call via
|
|
552
569
|
// conversation.compress).
|
package/src/commands/status.ts
CHANGED
|
@@ -19,7 +19,7 @@ import type { PromptCacheDiagnostics } from "../agent/promptDiagnostics.js"
|
|
|
19
19
|
import type { CacheMemoryAuditEntry } from "../agent/cacheMemoryAudit.js"
|
|
20
20
|
import { readProjectGuidelines } from "../prompts/sections/agents-md.js"
|
|
21
21
|
import {
|
|
22
|
-
|
|
22
|
+
conversationCacheScope,
|
|
23
23
|
samePromptCacheScope,
|
|
24
24
|
type PromptCacheScope,
|
|
25
25
|
} from "../agent/cacheScope.js"
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
getActiveProvider,
|
|
28
28
|
getEffort,
|
|
29
29
|
getProviderDisplayName,
|
|
30
|
-
hasApiKey,
|
|
30
|
+
conversationAgentId, hasApiKey,
|
|
31
31
|
type AppConfig,
|
|
32
32
|
} from "../config.js"
|
|
33
33
|
import { getCurrentSessionId } from "../session.js"
|
|
@@ -166,9 +166,11 @@ export function buildStatusText(
|
|
|
166
166
|
suppliedContextBudget?: ContextBudgetSnapshot,
|
|
167
167
|
): string {
|
|
168
168
|
const provider = getActiveProvider(config)
|
|
169
|
-
const
|
|
170
|
-
const
|
|
171
|
-
const
|
|
169
|
+
const agentId = conversationAgentId(config)
|
|
170
|
+
const providerLabel = agentId === "claude-code" ? "Claude Code" : agentId ? `ACP/${agentId}` : provider ? getProviderDisplayName(config) : "(none)"
|
|
171
|
+
const localModel = agentId && !(agentId === "codex" && provider?.authMode === "codex-oauth")
|
|
172
|
+
const model = localModel ? "selected by local agent" : config.active.model || "(no model selected)"
|
|
173
|
+
const effort = provider && !localModel ? getEffort(config, provider.id) : null
|
|
172
174
|
const contextBudget = suppliedContextBudget ?? buildContextBudgetSnapshot(
|
|
173
175
|
config,
|
|
174
176
|
legacyContextUsage(tokenUsage, contextPending),
|
|
@@ -182,12 +184,12 @@ export function buildStatusText(
|
|
|
182
184
|
: 0
|
|
183
185
|
const agentsDoc = detectAgentsDoc(cwd)
|
|
184
186
|
const sessionId = getCurrentSessionId()
|
|
185
|
-
const keyStatus = hasApiKey(config) ? "configured" : "missing — run /connect"
|
|
187
|
+
const keyStatus = agentId ? "managed by local agent" : hasApiKey(config) ? "configured" : "missing — run /connect"
|
|
186
188
|
|
|
187
189
|
const mgr = getMCPManager()
|
|
188
190
|
const mcpSummary = mgr ? summariseMCP(mgr.snapshots()) : "(unavailable)"
|
|
189
191
|
const effectiveContextHistory = appendCurrentContextHistory(contextHistory, context)
|
|
190
|
-
const currentCacheScope =
|
|
192
|
+
const currentCacheScope = conversationCacheScope(config)
|
|
191
193
|
const unscopedUsageHistory = appendCurrentUsageHistory(usageHistory, usage)
|
|
192
194
|
const effectiveUsageHistory = selectUsageForCacheScope(unscopedUsageHistory, currentCacheScope)
|
|
193
195
|
const scopedUsage = usage && usageMatchesCacheScope(usage, currentCacheScope) ? usage : undefined
|
package/src/config.ts
CHANGED
|
@@ -230,6 +230,8 @@ export interface AppConfig {
|
|
|
230
230
|
/** Session-scoped: id of the external ACP agent driving the conversation
|
|
231
231
|
* (`/agent <id>`). Undefined means zap's own model. Never persisted. */
|
|
232
232
|
activeAgent?: string
|
|
233
|
+
/** Preferred native conversation runtime selected in /connect. */
|
|
234
|
+
subscriptionAgent?: "claude-code"
|
|
233
235
|
permissionMode: PermissionMode
|
|
234
236
|
followUpMode?: "queue" | "steer"
|
|
235
237
|
/** Where project shell commands run. "local" (default) uses the host OS
|
|
@@ -475,8 +477,8 @@ function normalizeProvider(value: unknown, index: number): Provider | null {
|
|
|
475
477
|
...value,
|
|
476
478
|
id: typeof value.id === "string" && value.id.trim() ? value.id : `sp_${Date.now()}_${index}`,
|
|
477
479
|
name: typeof value.name === "string" ? value.name : "",
|
|
478
|
-
baseURL: typeof value.baseURL === "string" ? value.baseURL : "",
|
|
479
|
-
apiKey: typeof value.apiKey === "string" ? value.apiKey : "",
|
|
480
|
+
baseURL: value.authMode === "codex-oauth" ? "codex://local" : typeof value.baseURL === "string" ? value.baseURL : "",
|
|
481
|
+
apiKey: value.authMode === "codex-oauth" ? "" : typeof value.apiKey === "string" ? value.apiKey : "",
|
|
480
482
|
authMode: value.authMode === "codex-oauth" ? "codex-oauth" : value.authMode === "none" ? "none" : value.authMode === "api-key" ? "api-key" : undefined,
|
|
481
483
|
catalogProviderId: typeof value.catalogProviderId === "string" ? value.catalogProviderId : undefined,
|
|
482
484
|
contextWindow: positiveIntegerOrDefault(value.contextWindow, 128000),
|
|
@@ -608,6 +610,7 @@ export function loadAppConfig(configPath: string): AppConfig {
|
|
|
608
610
|
mcpServers: Array.isArray(parsed.mcpServers) ? parsed.mcpServers : [],
|
|
609
611
|
permissionMode: "default", // session-scoped
|
|
610
612
|
activeAgent: undefined, // session-scoped
|
|
613
|
+
subscriptionAgent: parsed.subscriptionAgent === "claude-code" ? "claude-code" : undefined,
|
|
611
614
|
}
|
|
612
615
|
if (process.env.ZAP_DISABLE_FILE_CHECKPOINTING === "1") {
|
|
613
616
|
merged.fileCheckpointingEnabled = false
|
|
@@ -788,6 +791,17 @@ export function hasApiKey(config: AppConfig): boolean {
|
|
|
788
791
|
return Boolean(p.apiKey.trim())
|
|
789
792
|
}
|
|
790
793
|
|
|
794
|
+
/** Legacy subscription connections are now conversations owned by Codex. */
|
|
795
|
+
export function conversationAgentId(config: AppConfig): string | undefined {
|
|
796
|
+
return config.activeAgent ?? config.subscriptionAgent ?? (getActiveProvider(config)?.authMode === "codex-oauth" ? "codex" : undefined)
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** External agents without a bound provider select their own model and effort. */
|
|
800
|
+
export function agentManagingModel(config: AppConfig): string | undefined {
|
|
801
|
+
const agent = conversationAgentId(config)
|
|
802
|
+
return agent === "codex" && getActiveProvider(config)?.authMode === "codex-oauth" ? undefined : agent
|
|
803
|
+
}
|
|
804
|
+
|
|
791
805
|
// ── Provider mutations (pure — all return new configs) ─────────────────────
|
|
792
806
|
|
|
793
807
|
export function upsertProvider(config: AppConfig, provider: Provider): AppConfig {
|
|
@@ -809,7 +823,7 @@ export function removeProvider(config: AppConfig, id: string): AppConfig {
|
|
|
809
823
|
}
|
|
810
824
|
|
|
811
825
|
export function setActive(config: AppConfig, providerId: string, model: string): AppConfig {
|
|
812
|
-
return normalize({ ...config, active: { providerId, model } })
|
|
826
|
+
return normalize({ ...config, activeAgent: undefined, subscriptionAgent: undefined, active: { providerId, model } })
|
|
813
827
|
}
|
|
814
828
|
|
|
815
829
|
/** Append a model to a provider's models[]. If `makeActive` is true, also
|
|
@@ -823,7 +837,7 @@ export function addModelToProvider(config: AppConfig, providerId: string, model:
|
|
|
823
837
|
return { ...p, models: [...p.models, trimmed] }
|
|
824
838
|
})
|
|
825
839
|
const next = { ...config, providers }
|
|
826
|
-
return
|
|
840
|
+
return makeActive ? setActive(next, providerId, trimmed) : normalize(next)
|
|
827
841
|
}
|
|
828
842
|
|
|
829
843
|
/** Remove a model from a provider. If it was active, the active model
|