zapagent 1.14.27 → 1.14.29

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/src/codex-auth.ts CHANGED
@@ -1,233 +1,31 @@
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"
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
- // 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
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
- 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.")
23
+ child.once("error", reject)
24
+ child.once("close", code => resolve(code ?? 1))
177
25
  })
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
26
+ options.signal?.throwIfAborted()
27
+ if (action === "logout" && status === 0) {
28
+ await rm(join(getAppDataDir(), "codex-oauth.json"), { force: true })
191
29
  }
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() }
30
+ return status
233
31
  }
@@ -1,13 +1,14 @@
1
- import { CODEX_BASE_URL, getCodexCredentials } from "./codex-auth.js"
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
- /** One explicit account binding; secrets live only in codex-oauth.json. */
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: CODEX_BASE_URL, apiKey: "", authMode: "codex-oauth", protocol: "openai-responses",
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 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",
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
- 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>> }
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.activeAgent) {
331
- deps.addLog("error", `${displayCommand?.type ?? cmd.type} runs on zap's own model, not ${deps.configRef.current.activeAgent}. /agent zap switches back.`)
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.activeAgent
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} over ACP. 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.`)
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).
@@ -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
- makePromptCacheScope,
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 providerLabel = provider ? getProviderDisplayName(config) : "(none)"
170
- const model = config.active.model || "(no model selected)"
171
- const effort = provider ? getEffort(config, provider.id) : null
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 = makePromptCacheScope(config.active.providerId, config.active.model)
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 normalize(makeActive ? { ...next, active: { providerId, model: trimmed } } : next)
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
@@ -323,6 +323,15 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
323
323
  config = ov.config
324
324
  const cacheScope = makePromptCacheScope(config.active.providerId, config.active.model)
325
325
 
326
+ if (config.subscriptionAgent === "claude-code") {
327
+ process.stderr.write("Claude Code runs in the interactive Zap UI. Select an API provider for Zap headless, or use claude --print.\n")
328
+ return EXIT_NO_PROVIDER
329
+ }
330
+ if (getActiveProvider(config)?.authMode === "codex-oauth") {
331
+ process.stderr.write("Codex subscriptions run inside the interactive Zap UI with codex-acp. For Zap headless, select an API provider or use codex exec for a native Codex run.\n")
332
+ return EXIT_NO_PROVIDER
333
+ }
334
+
326
335
  if (!hasApiKey(config)) {
327
336
  process.stderr.write(
328
337
  "no provider configured. Run `zap` interactively once to set one up with /connect.\n",
@@ -1,3 +1,4 @@
1
+ import { agentInstallHint, codexConversationSpec, nativeCommand } from "../agent/official-agents.js"
1
2
  import { goalTurnMeter, type GoalTurnInput } from "../goal-turn.js"
2
3
  import { RetryProvider } from "../../zapsdk/core/retry.js"
3
4
  import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
@@ -19,7 +20,7 @@ import type { CheckpointManager } from "../../zapsdk/checkpoint/index.js"
19
20
  import { AutoMemory } from "../../zapsdk/memory/auto-memory.js"
20
21
  import type { ConversationManager } from "../../zapsdk/index.js"
21
22
  import { extractFilesFromSummary } from "../ui/compact-utils.js"
22
- import { buildCustomSystemPrompt, buildSystemPrompt, deriveCompaction, getActiveProvider } from "../config.js"
23
+ import { buildCustomSystemPrompt, buildSystemPrompt, deriveCompaction, conversationAgentId, getActiveProvider } from "../config.js"
23
24
  import { appendUsage, saveLastOutput, getCurrentSessionId } from "../session.js"
24
25
  import type { AppConfig } from "../config.js"
25
26
  import type { LogType, ToolCallInfo, UserImageRef } from "../ui/types.js"
@@ -47,7 +48,7 @@ import { runRemoteTurn } from "../agent/remote-turn.js"
47
48
  import { appendCacheableSystemSection, buildRuntimePromptToolInputs } from "../agent/systemPrompt.js"
48
49
  import { createPromptSectionDiagnostics, buildPromptCacheDiagnostics, type PromptCacheDiagnostics } from "../agent/promptDiagnostics.js"
49
50
  import { persistRunUsage } from "../agent/usagePersistence.js"
50
- import { makePromptCacheScope, type PromptCacheScope } from "../agent/cacheScope.js"
51
+ import { conversationCacheScope, makePromptCacheScope, type PromptCacheScope } from "../agent/cacheScope.js"
51
52
  import { appendCacheMemoryAudit } from "../agent/cacheMemoryAudit.js"
52
53
  import { compactFailureReason } from "../agent/compactDiagnostics.js"
53
54
  import {
@@ -591,20 +592,30 @@ export function useAgentRunner({
591
592
  let handlers: ReturnType<typeof createRunHandlers> | null = null
592
593
 
593
594
  // Session mode: an external ACP agent answers this turn instead of zap's loop.
594
- const remoteSpec = config.activeAgent ? acpAgents.find(agent => agent.id === config.activeAgent) : undefined
595
- if (config.activeAgent) {
595
+ const agentId = conversationAgentId(config)
596
+ const nativeClaude = agentId === "claude-code"
597
+ let remoteSpec
598
+ if (agentId) {
596
599
  try {
597
- if (!remoteSpec) throw new Error(`ACP agent ${config.activeAgent} is not available; /agent zap switches back`)
600
+ if (nativeClaude) {
601
+ remoteSpec = { id: agentId, ...await nativeCommand("claude") }
602
+ } else if (agentId === "codex") {
603
+ remoteSpec = await codexConversationSpec(config, acpAgents.find(agent => agent.id === "codex"))
604
+ } else {
605
+ remoteSpec = acpAgents.find(agent => agent.id === agentId)
606
+ }
607
+ if (!remoteSpec) throw new Error(`Agent ${agentId} is unavailable. ${agentInstallHint(agentId)}`)
598
608
  if (invocation?.goalTurn) throw new Error("/goal runs on zap's own model; /agent zap switches back")
599
609
  if (systemPrompt) throw new Error("This command runs on zap's own model; /agent zap switches back")
600
610
  completedResult = await runRemoteTurn({
601
- spec: remoteSpec, cwd, conversation, currentConfig: config, controller,
611
+ spec: remoteSpec, nativeClaude, cwd, conversation, currentConfig: config, controller,
602
612
  createPreview: () => {
603
613
  const next = createStreamingPreview({ addLog, setStreamingText, setIsStreaming, setThinkingText, setIsThinking, getIsFrozen: getIsFrozen ?? (() => false) })
604
614
  registerStaticFlushCallback?.(() => next.onStaticFlushed())
605
615
  return next
606
616
  },
607
617
  saveLastOutput,
618
+ onRunUsage: usage => recordUsage(usage, undefined, conversationCacheScope(config)),
608
619
  onInputAccepted: invocation?.onInputAccepted,
609
620
  checkpointTurn: checkpoint ? (() => {
610
621
  const turnStartIndex = conversation.getAllMessages().length
package/src/index.tsx CHANGED
@@ -27,8 +27,8 @@ Options:
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
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
30
+ auth logout codex Sign out of the official Codex CLI and clear legacy Zap credentials
31
+ auth status codex Show the official Codex CLI login status
32
32
  update [--yes] Check, confirm and install the latest version
33
33
  acp Serve Agent Client Protocol v1 over stdio (no TUI)
34
34
  workflow Inspect, wait for or cancel a persisted workflow (--db required)