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/README.md +2 -4
- package/README.zh-CN.md +1 -3
- package/bundled-dependencies.json +191 -191
- package/package.json +1 -1
- package/src/App.tsx +16 -14
- 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/remote-agent.ts +3 -1
- package/src/agent/remote-turn.ts +17 -2
- package/src/agent/wireRunHandlers.ts +2 -5
- 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 +17 -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 +7 -4
- package/src/ui/provider-directory.tsx +5 -3
- package/zapsdk/acp-client/event-mapper.ts +7 -1
- package/zapsdk/acp-client/host-handlers.ts +18 -4
- package/zapsdk/acp-client/run.ts +1 -0
- package/zapsdk/acp-client/types.ts +2 -0
- package/zapsdk/agent/loop.ts +3 -1
- package/zapsdk/agent/single-call.ts +4 -2
- package/zapsdk/core/llm.ts +2 -0
- package/zapsdk/core/providers/openai-responses.ts +25 -7
- package/zapsdk/execution/process.ts +9 -2
package/package.json
CHANGED
package/src/App.tsx
CHANGED
|
@@ -24,7 +24,7 @@ import { initHighlighter } from "./ui/highlight.js"
|
|
|
24
24
|
initHighlighter() // fire-and-forget; harmless when shiki isn't used yet
|
|
25
25
|
|
|
26
26
|
import {
|
|
27
|
-
loadAppConfig,
|
|
27
|
+
conversationAgentId, getActiveProvider, loadAppConfig,
|
|
28
28
|
saveAppConfig,
|
|
29
29
|
hasApiKey as configHasApiKey,
|
|
30
30
|
getActiveContextWindow,
|
|
@@ -139,7 +139,7 @@ import { ProjectRecoveryCenter } from "../zapsdk/index.js"
|
|
|
139
139
|
import { createProjectRuntimeStateStore } from "./agent/runtimeEventStore.js"
|
|
140
140
|
import type { StatusUsageDetail } from "./commands/status.js"
|
|
141
141
|
import {
|
|
142
|
-
|
|
142
|
+
conversationCacheScope,
|
|
143
143
|
samePromptCacheScope,
|
|
144
144
|
type PromptCacheScope,
|
|
145
145
|
} from "./agent/cacheScope.js"
|
|
@@ -265,6 +265,7 @@ export function App() {
|
|
|
265
265
|
useEffect(() => { configRef.current = config }, [config])
|
|
266
266
|
|
|
267
267
|
const updateConfig = useCallback((next: AppConfig) => {
|
|
268
|
+
if (conversationAgentId(configRef.current) !== conversationAgentId(next)) void remoteAgents.reset()
|
|
268
269
|
configRef.current = next
|
|
269
270
|
setConfig(next)
|
|
270
271
|
saveAppConfig(configPath, next)
|
|
@@ -753,7 +754,7 @@ export function App() {
|
|
|
753
754
|
|
|
754
755
|
const precheckProvider = useCallback(
|
|
755
756
|
// An external ACP agent brings its own model and credentials.
|
|
756
|
-
() => !!configRef.current
|
|
757
|
+
() => !!conversationAgentId(configRef.current) || isProviderReady(configRef, addLog),
|
|
757
758
|
[addLog],
|
|
758
759
|
)
|
|
759
760
|
|
|
@@ -930,7 +931,10 @@ export function App() {
|
|
|
930
931
|
|
|
931
932
|
// ── Render ──
|
|
932
933
|
const providerDisplayName = getProviderDisplayName(config)
|
|
933
|
-
const
|
|
934
|
+
const agentId = conversationAgentId(config)
|
|
935
|
+
const subscriptionCodex = agentId === "codex" && getActiveProvider(config)?.authMode === "codex-oauth"
|
|
936
|
+
const agentLabel = agentId === "claude-code" ? "Claude Code" : agentId === "codex" ? "Codex" : agentId ? `ACP/${agentId}` : undefined
|
|
937
|
+
const hasKey = !!agentId || configHasApiKey(config)
|
|
934
938
|
const welcomeHeader = useMemo(() => <Welcome hasApiKey={hasKey} />, [hasKey])
|
|
935
939
|
const mcpFooterSummary = useMemo(
|
|
936
940
|
() => summariseMCPStatuses(mcp.snapshots),
|
|
@@ -998,10 +1002,7 @@ export function App() {
|
|
|
998
1002
|
// a number 10-30k below what the API would receive next.
|
|
999
1003
|
const persistedHistory = metadata.usages
|
|
1000
1004
|
const persisted = persistedHistory.at(-1) ?? null
|
|
1001
|
-
const activeCacheScope =
|
|
1002
|
-
config.active.providerId,
|
|
1003
|
-
config.active.model,
|
|
1004
|
-
)
|
|
1005
|
+
const activeCacheScope = conversationCacheScope(config)
|
|
1005
1006
|
const persistedMatchesActiveModel = !!persisted && (
|
|
1006
1007
|
!persisted.cacheScope || samePromptCacheScope(persisted.cacheScope, activeCacheScope)
|
|
1007
1008
|
)
|
|
@@ -1075,6 +1076,7 @@ export function App() {
|
|
|
1075
1076
|
} catch (err) {
|
|
1076
1077
|
addLog("error", `todo restore failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
1077
1078
|
}
|
|
1079
|
+
if (conversationAgentId(config)) addLog("system", "Transcript restored. The local agent will start a new conversation on your next message.")
|
|
1078
1080
|
bumpTranscript()
|
|
1079
1081
|
appLogger.info("session_restore_end", { sessionId: loadedSessionId })
|
|
1080
1082
|
closeDialog()
|
|
@@ -1157,7 +1159,7 @@ export function App() {
|
|
|
1157
1159
|
{!inModal && !pendingApproval && !pendingPlan && !pendingQuestions && (
|
|
1158
1160
|
<Prompt
|
|
1159
1161
|
config={config}
|
|
1160
|
-
providerLabel={
|
|
1162
|
+
providerLabel={agentLabel ?? `${providerDisplayName}/${config.active.model}`}
|
|
1161
1163
|
hasActiveKey={hasKey}
|
|
1162
1164
|
inputValue={inputValue}
|
|
1163
1165
|
onInput={paste.handleInput}
|
|
@@ -1209,7 +1211,7 @@ export function App() {
|
|
|
1209
1211
|
const persistence = getSessionPersistenceStatus()
|
|
1210
1212
|
if (persistence.pendingWrites || persistence.lastFailure) throw new Error("Save the current session successfully before updating.")
|
|
1211
1213
|
}} onCancel={closeDialog} onRestart={request => { readCurrentSessionLogs(); requestUpdateRestart(request); exit() }} />}
|
|
1212
|
-
{dialog === "connect" && <ConnectDialog config={config} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1214
|
+
{dialog === "connect" && <ConnectDialog config={config} onAgentSelected={addToast} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1213
1215
|
{dialog === "model" && <ModelDialog config={config} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1214
1216
|
{dialog === "mode" && <ModeDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1215
1217
|
{dialog === "effort" && <EffortDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
@@ -1339,14 +1341,14 @@ export function App() {
|
|
|
1339
1341
|
<Footer
|
|
1340
1342
|
outputThroughput={outputThroughput}
|
|
1341
1343
|
cwd={cwdShort}
|
|
1342
|
-
provider={
|
|
1343
|
-
model={config.
|
|
1344
|
-
effort={!
|
|
1344
|
+
provider={agentLabel ?? providerDisplayName}
|
|
1345
|
+
model={agentId === "claude-code" ? "local CLI" : subscriptionCodex ? config.active.model || "default" : agentId ? "agent default" : config.active.model}
|
|
1346
|
+
effort={(!agentId || subscriptionCodex) && config.active.providerId ? getEffort(config, config.active.providerId) : undefined}
|
|
1345
1347
|
isRunning={isRunning}
|
|
1346
1348
|
step={step}
|
|
1347
1349
|
maxSteps={config.maxSteps}
|
|
1348
1350
|
contextBudget={contextBudget}
|
|
1349
|
-
hideContext={!!
|
|
1351
|
+
hideContext={!!agentId}
|
|
1350
1352
|
hasApiKey={hasKey}
|
|
1351
1353
|
showWelcome={logs.length === 0 && !isRunning && !isStreaming}
|
|
1352
1354
|
shellMode={isShellMode()}
|
package/src/acp/agent.ts
CHANGED
|
@@ -235,11 +235,12 @@ export class ZapAcpAgent {
|
|
|
235
235
|
if (!config.providers.some(provider => provider.id === state.providerId)) throw RequestError.authRequired(null, "Session provider is no longer configured")
|
|
236
236
|
config = setActive(config, state.providerId, state.model)
|
|
237
237
|
}
|
|
238
|
+
if (config.subscriptionAgent || getActiveProvider(config)?.authMode === "codex-oauth") throw RequestError.authRequired(null, "Choose an API provider for the Zap ACP server. Local subscriptions run in the Zap UI.")
|
|
238
239
|
if (!getActiveProvider(config) || !hasApiKey(config) || !config.active.model) throw RequestError.authRequired(null, "Configure a provider and model with zap /connect")
|
|
239
240
|
return config
|
|
240
241
|
}
|
|
241
242
|
private modelChoices(config: AppConfig) {
|
|
242
|
-
return config.providers.flatMap(provider => [...new Set([...provider.models,
|
|
243
|
+
return config.providers.filter(provider => provider.authMode !== "codex-oauth").flatMap(provider => [...new Set([...provider.models,
|
|
243
244
|
...(provider.id === config.active.providerId ? [config.active.model] : [])])].filter(Boolean)
|
|
244
245
|
.map(model => ({ value: JSON.stringify([provider.id, model]), name: `${provider.name || provider.id} / ${model}` })))
|
|
245
246
|
}
|
package/src/agent/cacheScope.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { conversationAgentId, type AppConfig } from "../config.js"
|
|
1
2
|
import { countCodePoints, sliceHeadCodePoints } from "../utils/logicalLines.js"
|
|
2
3
|
|
|
3
4
|
export interface PromptCacheScope {
|
|
@@ -18,6 +19,16 @@ export function makePromptCacheScope(
|
|
|
18
19
|
return { providerId: safeProviderId, model: safeModel }
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
export function conversationCacheScope(config: AppConfig): PromptCacheScope | undefined {
|
|
23
|
+
const agent = conversationAgentId(config)
|
|
24
|
+
if (agent) {
|
|
25
|
+
const model = agent === "codex" && config.providers.some(p => p.id === config.active.providerId && p.authMode === "codex-oauth")
|
|
26
|
+
? config.active.model : undefined
|
|
27
|
+
return makePromptCacheScope(`agent:${agent}`, model || "default")
|
|
28
|
+
}
|
|
29
|
+
return makePromptCacheScope(config.active.providerId, config.active.model)
|
|
30
|
+
}
|
|
31
|
+
|
|
21
32
|
export function sanitizePromptCacheScope(value: unknown): PromptCacheScope | undefined {
|
|
22
33
|
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined
|
|
23
34
|
const record = value as Record<string, unknown>
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto"
|
|
2
|
+
import { resolveToolPath } from "../../zapsdk/builtin-tools/filesystem.js"
|
|
3
|
+
import { readFile } from "node:fs/promises"
|
|
4
|
+
import { createInterface } from "node:readline"
|
|
5
|
+
import type { ToolKind } from "@agentclientprotocol/sdk"
|
|
6
|
+
import { nextContentId, type AgentEvent } from "../../zapsdk/agent/events.js"
|
|
7
|
+
import type { AcpTurnResult } from "../../zapsdk/acp-client/run.js"
|
|
8
|
+
import { AcpWorkspace, permissionTarget } from "../../zapsdk/acp-client/host-handlers.js"
|
|
9
|
+
import { makeParserCtx, parseClaudeLine } from "../../zapsdk/builtin-tools/delegate-stream.js"
|
|
10
|
+
import type { ImageContent, TokenUsage } from "../../zapsdk/core/types.js"
|
|
11
|
+
import { createLocalProcessBroker, terminateProcessTree, terminateProcessTreeWithGrace } from "../../zapsdk/execution/process.js"
|
|
12
|
+
import type { ApprovalCallback, ApprovalResponse } from "../../zapsdk/tools/executor.js"
|
|
13
|
+
|
|
14
|
+
const toolKinds: Record<string, ToolKind> = { Bash: "execute", Write: "edit", Edit: "edit", MultiEdit: "edit", NotebookEdit: "edit", Read: "read", Glob: "search", Grep: "search" }
|
|
15
|
+
|
|
16
|
+
interface Options {
|
|
17
|
+
command: string
|
|
18
|
+
args?: string[]
|
|
19
|
+
cwd: string
|
|
20
|
+
text: string
|
|
21
|
+
images?: ImageContent[]
|
|
22
|
+
resume?: string
|
|
23
|
+
plan: boolean
|
|
24
|
+
signal: AbortSignal
|
|
25
|
+
approve?: ApprovalCallback
|
|
26
|
+
onEvent: (event: AgentEvent) => void
|
|
27
|
+
onAccepted?: () => void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function approveClaudeTool(
|
|
31
|
+
name: string, input: Record<string, unknown>, workspace: AcpWorkspace, signal: AbortSignal,
|
|
32
|
+
approve?: ApprovalCallback,
|
|
33
|
+
): Promise<ApprovalResponse> {
|
|
34
|
+
if (!approve || signal.aborted) return false
|
|
35
|
+
const kind = Object.hasOwn(toolKinds, name) ? toolKinds[name] : "other"
|
|
36
|
+
const file = name === "NotebookEdit" ? input.notebook_path : input.file_path
|
|
37
|
+
let path: string | undefined
|
|
38
|
+
if (kind === "edit" || kind === "read") {
|
|
39
|
+
if (typeof file !== "string" || !file.trim()) return { approved: false, source: "policy", reason: "Missing file path" }
|
|
40
|
+
const absolute = resolveToolPath(file, workspace.root)
|
|
41
|
+
path = workspace.resolve(absolute)
|
|
42
|
+
input[name === "NotebookEdit" ? "notebook_path" : "file_path"] = path
|
|
43
|
+
if (kind === "edit" && (workspace.isProtected(absolute) || workspace.isProtected(path))) {
|
|
44
|
+
return { approved: false, source: "policy", reason: "Writing to Zap or Git control files is prohibited" }
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const target = permissionTarget("claude", { sessionId: "", options: [], toolCall: {
|
|
48
|
+
toolCallId: "", title: name, kind, rawInput: input, locations: path ? [{ path }] : [],
|
|
49
|
+
} }, workspace)
|
|
50
|
+
if (path && workspace.contains(path) && kind === "edit" && name !== "Write") {
|
|
51
|
+
target.name = name === "MultiEdit" ? "multi_edit" : "edit_file"
|
|
52
|
+
target.args = { ...input, path }
|
|
53
|
+
}
|
|
54
|
+
return approve.precheck?.(target.name, target.args, target.context)
|
|
55
|
+
?? approve(target.name, target.args, signal, target.context)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Drive the end user's unmodified Claude Code CLI over its stdio protocol.
|
|
59
|
+
* Each invocation adds one user turn to the native session. */
|
|
60
|
+
export async function promptClaudeCode(options: Options): Promise<AcpTurnResult & { sessionId: string }> {
|
|
61
|
+
const sessionId = options.resume ?? randomUUID()
|
|
62
|
+
const args = [...(options.args ?? []), "--print", "--verbose", "--include-partial-messages", "--input-format", "stream-json", "--output-format", "stream-json",
|
|
63
|
+
"--permission-prompt-tool", "stdio", "--permission-mode", options.plan ? "plan" : "manual",
|
|
64
|
+
options.resume ? "--resume" : "--session-id", sessionId]
|
|
65
|
+
if (options.plan) args.push("--tools", "Read,Grep,Glob")
|
|
66
|
+
const images = await Promise.all((options.images ?? []).map(async image => ({ type: "image", source: {
|
|
67
|
+
type: "base64", media_type: image.mediaType, data: image.base64 ?? (await readFile(image.filePath)).toString("base64"),
|
|
68
|
+
} })))
|
|
69
|
+
options.signal.throwIfAborted()
|
|
70
|
+
const child = createLocalProcessBroker(options.signal).spawnCommand(options.command, args, {
|
|
71
|
+
cwd: options.cwd, hostHome: true, stdin: "pipe",
|
|
72
|
+
})
|
|
73
|
+
const onExit = () => { if (child.pid) terminateProcessTree(child, "SIGKILL") }
|
|
74
|
+
process.once("exit", onExit)
|
|
75
|
+
const abort = new AbortController()
|
|
76
|
+
const signal = AbortSignal.any([options.signal, abort.signal])
|
|
77
|
+
const exited = new Promise<number | null>((resolve, reject) => {
|
|
78
|
+
child.once("error", reject)
|
|
79
|
+
child.once("close", code => { abort.abort(); resolve(code) })
|
|
80
|
+
})
|
|
81
|
+
void exited.catch(() => abort.abort())
|
|
82
|
+
const stdin = child.stdin!
|
|
83
|
+
stdin.on("error", () => {})
|
|
84
|
+
let stderr = ""
|
|
85
|
+
child.stderr!.setEncoding("utf8").on("data", text => { stderr = (stderr + text).slice(-2048) })
|
|
86
|
+
const workspace = new AcpWorkspace(options.cwd)
|
|
87
|
+
const parser = makeParserCtx("claude", [])
|
|
88
|
+
let accepted = false
|
|
89
|
+
let completed = false
|
|
90
|
+
let failure: string | undefined
|
|
91
|
+
let usage: TokenUsage | undefined
|
|
92
|
+
const send = (message: unknown) => stdin.write(JSON.stringify(message) + "\n")
|
|
93
|
+
try {
|
|
94
|
+
send({ type: "user", message: { role: "user", content: [{ type: "text", text: options.text }, ...images] } })
|
|
95
|
+
const blocks = new Map<number, { id: string; kind: "text" | "thinking"; streamed: boolean }>()
|
|
96
|
+
const finalIds: { id: string; kind: "text" | "thinking" }[] = []
|
|
97
|
+
for await (const line of createInterface({ input: child.stdout!, crlfDelay: Infinity })) {
|
|
98
|
+
if (!line.trim()) continue
|
|
99
|
+
let event
|
|
100
|
+
try { event = JSON.parse(line) } catch { continue }
|
|
101
|
+
if (!event || typeof event !== "object") continue
|
|
102
|
+
if (!accepted && (event.type === "assistant" || event.type === "system" && event.subtype === "init")) {
|
|
103
|
+
accepted = true
|
|
104
|
+
options.onAccepted?.()
|
|
105
|
+
}
|
|
106
|
+
if (event.type === "control_request") {
|
|
107
|
+
const request = event.request
|
|
108
|
+
const input = request?.input ?? {}
|
|
109
|
+
const decision = request?.subtype === "can_use_tool"
|
|
110
|
+
? await approveClaudeTool(request.tool_name, input, workspace, signal, options.approve) : false
|
|
111
|
+
const response = decision === true && !signal.aborted
|
|
112
|
+
? { behavior: "allow", updatedInput: input }
|
|
113
|
+
: { behavior: "deny", message: typeof decision === "object" ? decision.reason : "Permission denied" }
|
|
114
|
+
send({ type: "control_response", response: { subtype: "success", request_id: event.request_id, response } })
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
if (event.type === "stream_event" && !event.parent_tool_use_id) {
|
|
118
|
+
const part = event.event
|
|
119
|
+
if (part.type === "message_start") { blocks.clear(); finalIds.length = 0 }
|
|
120
|
+
if (part.type === "content_block_start" && ["text", "thinking"].includes(part.content_block.type)) {
|
|
121
|
+
const block = { id: nextContentId("claude"), streamed: false, kind: part.content_block.type as "text" | "thinking" }
|
|
122
|
+
blocks.set(part.index, block)
|
|
123
|
+
}
|
|
124
|
+
const block = blocks.get(part.index)
|
|
125
|
+
if (part.type === "content_block_delta" && block) {
|
|
126
|
+
const text = block.kind === "text" ? part.delta.text : part.delta.thinking
|
|
127
|
+
if (typeof text === "string" && text.length) {
|
|
128
|
+
if (!block.streamed) finalIds.push(block)
|
|
129
|
+
block.streamed = true
|
|
130
|
+
options.onEvent({ type: "content_delta", kind: block.kind, id: block.id, text })
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
continue
|
|
134
|
+
}
|
|
135
|
+
if (!event.parent_tool_use_id) for (const parsed of parseClaudeLine(line, parser)) {
|
|
136
|
+
if (parsed.type !== "content_final") continue
|
|
137
|
+
const index = finalIds.findIndex(block => block.kind === parsed.kind)
|
|
138
|
+
const id = index === -1 ? parsed.id : finalIds.splice(index, 1)[0].id
|
|
139
|
+
options.onEvent({ ...parsed, id, path: [] })
|
|
140
|
+
}
|
|
141
|
+
if (event.type === "result") {
|
|
142
|
+
completed = true
|
|
143
|
+
if (event.is_error || event.subtype !== "success") failure = String(event.result || event.subtype)
|
|
144
|
+
if (event.usage) usage = {
|
|
145
|
+
inputTokens: event.usage.input_tokens, outputTokens: event.usage.output_tokens, providerUsageReported: true,
|
|
146
|
+
cacheReadInputTokens: event.usage.cache_read_input_tokens, cacheCreationInputTokens: event.usage.cache_creation_input_tokens,
|
|
147
|
+
}
|
|
148
|
+
stdin.end()
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const code = await exited
|
|
152
|
+
options.signal.throwIfAborted()
|
|
153
|
+
if (code !== 0 || !completed || failure) throw new Error(failure || stderr.trim() || `Claude Code exited before returning a result (exit code ${code ?? "unknown"}).`)
|
|
154
|
+
return { sessionId, stopReason: "end_turn", report: parser.finalText, toolCalls: parser.stepCounter.value, plan: [], usage }
|
|
155
|
+
} finally {
|
|
156
|
+
process.off("exit", onExit)
|
|
157
|
+
abort.abort()
|
|
158
|
+
if (child.pid && child.exitCode === null && child.signalCode === null) terminateProcessTreeWithGrace(child)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { readFile, realpath } from "node:fs/promises"
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path"
|
|
3
|
+
import type { AcpAgentSpec } from "../../zapsdk/acp-client/types.js"
|
|
4
|
+
import { getActiveProvider, getEffort, type AppConfig } from "../config.js"
|
|
5
|
+
import { which } from "../../zapsdk/builtin-tools/delegate-detect.js"
|
|
6
|
+
|
|
7
|
+
const packages = {
|
|
8
|
+
codex: "@openai/codex",
|
|
9
|
+
"codex-acp": "@agentclientprotocol/codex-acp",
|
|
10
|
+
claude: "@anthropic-ai/claude-code",
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function agentInstallHint(id: string): string {
|
|
14
|
+
if (id === "codex") return "Install @openai/codex and @agentclientprotocol/codex-acp, then run codex login."
|
|
15
|
+
if (id === "claude-code") return "Install Claude Code, then run claude auth login."
|
|
16
|
+
return "Check the configured ACP command and restart Zap."
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function nativeCommand(name: keyof typeof packages): Promise<{ command: string; args: string[] }> {
|
|
20
|
+
const found = await which(name)
|
|
21
|
+
if (!found) throw new Error(agentInstallHint(name === "claude" ? "claude-code" : "codex"))
|
|
22
|
+
if (process.platform !== "win32" || /\.exe$/i.test(found)) return { command: found, args: [] }
|
|
23
|
+
return windowsNativeCommand(name, found)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Read the selected shim's package entry without executing its shell code. */
|
|
27
|
+
async function windowsNativeCommand(name: keyof typeof packages, found: string) {
|
|
28
|
+
const dir = dirname(found)
|
|
29
|
+
const adjacentExe = await which(join(dir, name + ".exe"))
|
|
30
|
+
if (adjacentExe) return { command: adjacentExe, args: [] }
|
|
31
|
+
const pkg = packages[name]
|
|
32
|
+
const roots = new Set<string>()
|
|
33
|
+
const packageRoot = (entry: string) => {
|
|
34
|
+
const marker = "/node_modules/" + pkg + "/"
|
|
35
|
+
const normalized = entry.replaceAll("\\", "/")
|
|
36
|
+
const end = normalized.lastIndexOf(marker)
|
|
37
|
+
if (end !== -1) roots.add(resolve(dir, normalized.slice(0, end + marker.length - 1)))
|
|
38
|
+
}
|
|
39
|
+
packageRoot(await realpath(found))
|
|
40
|
+
// pnpm and Yarn may put the shim in a different tree from the package.
|
|
41
|
+
// Only inspect literal paths. Never evaluate shell variables or commands.
|
|
42
|
+
for (const shim of new Set([found, join(dir, name + ".cmd")])) {
|
|
43
|
+
const script = await readFile(shim, "utf8").catch(() => "")
|
|
44
|
+
for (const match of script.matchAll(/"([^"\r\n]+)"/g)) {
|
|
45
|
+
const entry = match[1].replace(/^(?:%~dp0|%dp0%|\$basedir)[\\/]?/i, "./")
|
|
46
|
+
if (!/[%$`]/.test(entry)) packageRoot(entry)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
roots.add(join(basename(dir) === ".bin" ? dirname(dir) : join(dir, "node_modules"), pkg))
|
|
50
|
+
for (const root of roots) {
|
|
51
|
+
const json = await readFile(join(root, "package.json"), "utf8").catch(() => undefined)
|
|
52
|
+
if (!json) continue
|
|
53
|
+
const manifest = JSON.parse(json)
|
|
54
|
+
const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.[name]
|
|
55
|
+
if (typeof bin !== "string") continue
|
|
56
|
+
const entry = await which(resolve(root, bin))
|
|
57
|
+
if (!entry) continue
|
|
58
|
+
if (/\.exe$/i.test(entry)) return { command: entry, args: [] }
|
|
59
|
+
const node = await which("node.exe")
|
|
60
|
+
if (!node) throw new Error(`Install Node.js to run the npm installation of ${name}.`)
|
|
61
|
+
return { command: node, args: [entry] }
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`Cannot locate ${name} behind ${found}. Install ${pkg} with npm install -g or put its native executable on PATH.`)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function codexConversationSpec(config: AppConfig, detected?: AcpAgentSpec): Promise<AcpAgentSpec> {
|
|
67
|
+
const provider = getActiveProvider(config)
|
|
68
|
+
const subscription = provider?.authMode === "codex-oauth"
|
|
69
|
+
// Explicit ACP overrides belong to /agent. Subscription connections always
|
|
70
|
+
// use the installed Codex bridge and the selected account's preferences.
|
|
71
|
+
const custom = subscription ? undefined : config.acpAgents?.find(agent => agent.id === "codex")
|
|
72
|
+
const spec = custom ? detected : undefined
|
|
73
|
+
const cli = spec && custom?.command !== "codex-acp" ? spec : await nativeCommand("codex-acp")
|
|
74
|
+
const allowEdits = config.permissionMode === "acceptEdits" || config.permissionMode === "bypassPermissions"
|
|
75
|
+
const effort = subscription ? getEffort(config, provider.id) : undefined
|
|
76
|
+
return {
|
|
77
|
+
...spec, id: "codex", command: cli.command,
|
|
78
|
+
args: cli === spec ? cli.args : [...(cli.args ?? []), ...(spec?.args ?? [])],
|
|
79
|
+
requireSettings: true, mode: allowEdits && spec?.mode !== "read-only" ? "workspace-write" : "read-only",
|
|
80
|
+
model: subscription ? config.active.model || undefined : spec?.model,
|
|
81
|
+
config: effort ? { reasoning_effort: effort } : spec?.config,
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -43,6 +43,8 @@ export class RemoteAgentManager {
|
|
|
43
43
|
|
|
44
44
|
constructor(private readonly transportFor: (spec: AcpAgentSpec, cwd: string) => AcpTransport = spawnTransport) {}
|
|
45
45
|
|
|
46
|
+
get epoch(): number { return this.generation }
|
|
47
|
+
|
|
46
48
|
get current(): { spec: AcpAgentSpec; session: AcpAgentSession } | undefined {
|
|
47
49
|
return this.live ? { spec: this.live.spec, session: this.live.session } : undefined
|
|
48
50
|
}
|
|
@@ -95,7 +97,7 @@ export class RemoteAgentManager {
|
|
|
95
97
|
|
|
96
98
|
private async ensure(spec: AcpAgentSpec, cwd: string, signal: AbortSignal, onStarted?: (session: AcpAgentSession) => void): Promise<LiveSession> {
|
|
97
99
|
if (this.host.blocked) throw new Error(this.host.blocked)
|
|
98
|
-
const key = JSON.stringify([spec.id, spec.command, spec.args ?? [], spec.mode, spec.model, spec.config, cwd])
|
|
100
|
+
const key = JSON.stringify([spec.id, spec.command, spec.args ?? [], spec.requireSettings, spec.mode, spec.model, spec.config, cwd])
|
|
99
101
|
// Let a start for another agent settle (and be replaced) first.
|
|
100
102
|
while (this.starting && this.starting.key !== key) await this.starting.promise.catch(() => {})
|
|
101
103
|
if (this.live?.key === key) return this.live
|
package/src/agent/remote-turn.ts
CHANGED
|
@@ -6,10 +6,12 @@ import type { ConversationManager } from "../../zapsdk/memory/conversation.js"
|
|
|
6
6
|
import type { AcpAgentSpec } from "../../zapsdk/acp-client/types.js"
|
|
7
7
|
import type { StreamingPreview } from "./streamingPreview.js"
|
|
8
8
|
import { createRunHandlers, type RunHandlersDeps } from "./wireRunHandlers.js"
|
|
9
|
+
import { promptClaudeCode } from "./claude-code.js"
|
|
9
10
|
import { remoteAgents } from "./remote-agent.js"
|
|
10
11
|
|
|
11
12
|
export interface RemoteTurnDeps extends Omit<RunHandlersDeps, "preview" | "setContextTokens" | "setContextPending" | "currentConfig"> {
|
|
12
13
|
currentConfig: RunHandlersDeps["currentConfig"]
|
|
14
|
+
nativeClaude?: boolean
|
|
13
15
|
spec: AcpAgentSpec
|
|
14
16
|
cwd: string
|
|
15
17
|
conversation: ConversationManager
|
|
@@ -22,6 +24,8 @@ export interface RemoteTurnDeps extends Omit<RunHandlersDeps, "preview" | "setCo
|
|
|
22
24
|
checkpointTurn?: { begin: () => Promise<unknown>; end: () => Promise<unknown> }
|
|
23
25
|
}
|
|
24
26
|
|
|
27
|
+
const claudeSessions = new WeakMap<ConversationManager, { tip: unknown; sessionId: string; epoch: number; cwd: string }>()
|
|
28
|
+
|
|
25
29
|
/** One user turn handled by an external ACP agent instead of zap's loop.
|
|
26
30
|
* Rendering reuses the regular run handlers, so the transcript looks the
|
|
27
31
|
* same; zap's conversation records the exchange so switching back to zap
|
|
@@ -34,7 +38,16 @@ export async function runRemoteTurn(deps: RemoteTurnDeps, task: string, images?:
|
|
|
34
38
|
const { spec, controller } = deps
|
|
35
39
|
await deps.checkpointTurn?.begin().catch(() => {})
|
|
36
40
|
try {
|
|
37
|
-
|
|
41
|
+
if (remoteAgents.host.blocked) throw new Error(remoteAgents.host.blocked)
|
|
42
|
+
const previous = claudeSessions.get(deps.conversation)
|
|
43
|
+
claudeSessions.delete(deps.conversation)
|
|
44
|
+
const epoch = remoteAgents.epoch
|
|
45
|
+
const turn = deps.nativeClaude ? await promptClaudeCode({
|
|
46
|
+
command: spec.command, args: spec.args, cwd: deps.cwd, text: task, images, signal: controller.signal,
|
|
47
|
+
plan: deps.currentConfig.permissionMode === "plan", approve: remoteAgents.host.approve,
|
|
48
|
+
resume: previous?.cwd === deps.cwd && previous.epoch === epoch && previous.tip === deps.conversation.getTurns().at(-1) ? previous.sessionId : undefined,
|
|
49
|
+
onEvent: event => emitter.emit(event), onAccepted: deps.onInputAccepted,
|
|
50
|
+
}) : await remoteAgents.prompt(spec, deps.cwd, task, images, {
|
|
38
51
|
signal: controller.signal,
|
|
39
52
|
onEvent: event => emitter.emit(event),
|
|
40
53
|
onAccepted: deps.onInputAccepted,
|
|
@@ -43,7 +56,9 @@ export async function runRemoteTurn(deps: RemoteTurnDeps, task: string, images?:
|
|
|
43
56
|
},
|
|
44
57
|
})
|
|
45
58
|
deps.conversation.add({ role: "user", content: task })
|
|
46
|
-
deps.conversation.add({ role: "assistant", content: `[${spec.id}
|
|
59
|
+
deps.conversation.add({ role: "assistant", content: `[${spec.id}] ${turn.report || "(no message)"}` })
|
|
60
|
+
if ("sessionId" in turn) claudeSessions.set(deps.conversation, { tip: deps.conversation.getTurns().at(-1), epoch, cwd: deps.cwd, sessionId: turn.sessionId })
|
|
61
|
+
if (turn.usage) emitter.emit({ type: "run_usage", step: turn.toolCalls, ...turn.usage })
|
|
47
62
|
if (turn.plan.length) deps.addLog("system", formatPlan(spec.id, turn.plan))
|
|
48
63
|
if (turn.stopReason !== "end_turn" && turn.stopReason !== "cancelled") deps.addLog("system", `${spec.id} stopped: ${turn.stopReason}`)
|
|
49
64
|
if (turn.report) deps.saveLastOutput(turn.report)
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
type ContextUsageSource,
|
|
25
25
|
} from "../context-budget.js"
|
|
26
26
|
import { sanitizeContextDiagnostics } from "./diagnosticSanitizers.js"
|
|
27
|
-
import {
|
|
27
|
+
import { conversationCacheScope } from "./cacheScope.js"
|
|
28
28
|
import { CacheMemoryAuditTracker, type CacheMemoryAuditEntry } from "./cacheMemoryAudit.js"
|
|
29
29
|
import type { MemoryUtilityCandidate, MemoryUtilityFingerprint } from "./memoryUtility.js"
|
|
30
30
|
import type { AgentRunSnapshot } from "../../zapsdk/agent/run-state.js"
|
|
@@ -188,10 +188,7 @@ export interface RunHandlers {
|
|
|
188
188
|
const SUBAGENT_TOOLS = new Set(["agent", "delegate_agent", "acp_agent"])
|
|
189
189
|
|
|
190
190
|
export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
191
|
-
const cacheScope =
|
|
192
|
-
deps.currentConfig.active.providerId,
|
|
193
|
-
deps.currentConfig.active.model,
|
|
194
|
-
)
|
|
191
|
+
const cacheScope = conversationCacheScope(deps.currentConfig)
|
|
195
192
|
const throughput = new OutputThroughput()
|
|
196
193
|
const pendingToolLogById = new Map<string, PendingTool>()
|
|
197
194
|
const pendingSubagentToolLogById = new Map<string, PendingSubagentTool>()
|
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
|
}
|