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/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)
|
|
@@ -550,6 +551,7 @@ export function App() {
|
|
|
550
551
|
abortRef,
|
|
551
552
|
status: runnerStatus,
|
|
552
553
|
providerRequest,
|
|
554
|
+
remoteContext,
|
|
553
555
|
outputThroughput,
|
|
554
556
|
setStatus,
|
|
555
557
|
step,
|
|
@@ -753,7 +755,7 @@ export function App() {
|
|
|
753
755
|
|
|
754
756
|
const precheckProvider = useCallback(
|
|
755
757
|
// An external ACP agent brings its own model and credentials.
|
|
756
|
-
() => !!configRef.current
|
|
758
|
+
() => !!conversationAgentId(configRef.current) || isProviderReady(configRef, addLog),
|
|
757
759
|
[addLog],
|
|
758
760
|
)
|
|
759
761
|
|
|
@@ -930,7 +932,10 @@ export function App() {
|
|
|
930
932
|
|
|
931
933
|
// ── Render ──
|
|
932
934
|
const providerDisplayName = getProviderDisplayName(config)
|
|
933
|
-
const
|
|
935
|
+
const agentId = conversationAgentId(config)
|
|
936
|
+
const subscriptionCodex = agentId === "codex" && getActiveProvider(config)?.authMode === "codex-oauth"
|
|
937
|
+
const agentLabel = agentId === "claude-code" ? "Claude Code" : agentId === "codex" ? "Codex" : agentId ? `ACP/${agentId}` : undefined
|
|
938
|
+
const hasKey = !!agentId || configHasApiKey(config)
|
|
934
939
|
const welcomeHeader = useMemo(() => <Welcome hasApiKey={hasKey} />, [hasKey])
|
|
935
940
|
const mcpFooterSummary = useMemo(
|
|
936
941
|
() => summariseMCPStatuses(mcp.snapshots),
|
|
@@ -998,14 +1003,12 @@ export function App() {
|
|
|
998
1003
|
// a number 10-30k below what the API would receive next.
|
|
999
1004
|
const persistedHistory = metadata.usages
|
|
1000
1005
|
const persisted = persistedHistory.at(-1) ?? null
|
|
1001
|
-
const activeCacheScope =
|
|
1002
|
-
config.active.providerId,
|
|
1003
|
-
config.active.model,
|
|
1004
|
-
)
|
|
1006
|
+
const activeCacheScope = conversationCacheScope(config)
|
|
1005
1007
|
const persistedMatchesActiveModel = !!persisted && (
|
|
1006
1008
|
!persisted.cacheScope || samePromptCacheScope(persisted.cacheScope, activeCacheScope)
|
|
1007
1009
|
)
|
|
1008
|
-
|
|
1010
|
+
// Native agents resume with a fresh window; their saved usage sums every request in a turn.
|
|
1011
|
+
if (persisted && persistedMatchesActiveModel && !conversationAgentId(config)) {
|
|
1009
1012
|
const restoredUsage = resolveRestoredUsageContext(
|
|
1010
1013
|
persisted,
|
|
1011
1014
|
conversation.estimatedTokens,
|
|
@@ -1075,6 +1078,7 @@ export function App() {
|
|
|
1075
1078
|
} catch (err) {
|
|
1076
1079
|
addLog("error", `todo restore failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
1077
1080
|
}
|
|
1081
|
+
if (conversationAgentId(config)) addLog("system", "Transcript restored. The local agent will start a new conversation on your next message.")
|
|
1078
1082
|
bumpTranscript()
|
|
1079
1083
|
appLogger.info("session_restore_end", { sessionId: loadedSessionId })
|
|
1080
1084
|
closeDialog()
|
|
@@ -1109,7 +1113,7 @@ export function App() {
|
|
|
1109
1113
|
<ToastContainer toasts={toasts} />
|
|
1110
1114
|
<UpdateNotice state={updateCheck} />
|
|
1111
1115
|
|
|
1112
|
-
<TokenWarning contextBudget={contextBudget} />
|
|
1116
|
+
{!agentId && <TokenWarning contextBudget={contextBudget} />}
|
|
1113
1117
|
|
|
1114
1118
|
{dialog !== "queue" && <QueuePanel entries={inputQueue} mode={config.followUpMode ?? "queue"} active={isAgentRunning} foregroundId={turnActivity.foregroundId} />}
|
|
1115
1119
|
{editingMessageId && <Text color={c.accent}>Editing queued message · Enter saves · Esc cancels · original draft is kept</Text>}
|
|
@@ -1157,7 +1161,7 @@ export function App() {
|
|
|
1157
1161
|
{!inModal && !pendingApproval && !pendingPlan && !pendingQuestions && (
|
|
1158
1162
|
<Prompt
|
|
1159
1163
|
config={config}
|
|
1160
|
-
providerLabel={
|
|
1164
|
+
providerLabel={agentLabel ?? `${providerDisplayName}/${config.active.model}`}
|
|
1161
1165
|
hasActiveKey={hasKey}
|
|
1162
1166
|
inputValue={inputValue}
|
|
1163
1167
|
onInput={paste.handleInput}
|
|
@@ -1209,7 +1213,7 @@ export function App() {
|
|
|
1209
1213
|
const persistence = getSessionPersistenceStatus()
|
|
1210
1214
|
if (persistence.pendingWrites || persistence.lastFailure) throw new Error("Save the current session successfully before updating.")
|
|
1211
1215
|
}} onCancel={closeDialog} onRestart={request => { readCurrentSessionLogs(); requestUpdateRestart(request); exit() }} />}
|
|
1212
|
-
{dialog === "connect" && <ConnectDialog config={config} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1216
|
+
{dialog === "connect" && <ConnectDialog config={config} onAgentSelected={addToast} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1213
1217
|
{dialog === "model" && <ModelDialog config={config} onSave={updateConfig} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1214
1218
|
{dialog === "mode" && <ModeDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
1215
1219
|
{dialog === "effort" && <EffortDialog config={config} onCommit={commitConfig} onCancel={closeDialog} />}
|
|
@@ -1339,14 +1343,14 @@ export function App() {
|
|
|
1339
1343
|
<Footer
|
|
1340
1344
|
outputThroughput={outputThroughput}
|
|
1341
1345
|
cwd={cwdShort}
|
|
1342
|
-
provider={
|
|
1343
|
-
model={config.
|
|
1344
|
-
effort={!
|
|
1346
|
+
provider={agentLabel ?? providerDisplayName}
|
|
1347
|
+
model={agentId === "claude-code" ? "local CLI" : subscriptionCodex ? config.active.model || "default" : agentId ? "agent default" : config.active.model}
|
|
1348
|
+
effort={(!agentId || subscriptionCodex) && config.active.providerId ? getEffort(config, config.active.providerId) : undefined}
|
|
1345
1349
|
isRunning={isRunning}
|
|
1346
1350
|
step={step}
|
|
1347
1351
|
maxSteps={config.maxSteps}
|
|
1348
1352
|
contextBudget={contextBudget}
|
|
1349
|
-
|
|
1353
|
+
remoteContext={agentId ? remoteContext ?? null : undefined}
|
|
1350
1354
|
hasApiKey={hasKey}
|
|
1351
1355
|
showWelcome={logs.length === 0 && !isRunning && !isStreaming}
|
|
1352
1356
|
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
|
+
}
|
|
@@ -3,6 +3,8 @@ import type { ProviderRequestEvent } from "../../zapsdk/core/llm.js"
|
|
|
3
3
|
export interface OutputThroughputSample {
|
|
4
4
|
tokensPerSecond: number
|
|
5
5
|
estimated: boolean
|
|
6
|
+
/** Output tokens over the full prompt turn, including tools and first-token latency. */
|
|
7
|
+
turnAverage?: boolean
|
|
6
8
|
}
|
|
7
9
|
|
|
8
10
|
/** Latest root request's decode throughput, excluding TTFT and tool time.
|
|
@@ -51,3 +53,28 @@ export class OutputThroughput {
|
|
|
51
53
|
return { tokensPerSecond, estimated }
|
|
52
54
|
}
|
|
53
55
|
}
|
|
56
|
+
|
|
57
|
+
/** ACP exposes message chunks and turn totals, but no per-request decode clock. */
|
|
58
|
+
export class AgentOutputThroughput {
|
|
59
|
+
private segment?: { id: string; firstAt: number; charsAfterFirst: number }
|
|
60
|
+
private latest?: OutputThroughputSample
|
|
61
|
+
|
|
62
|
+
chunk(id: string, text: string, now: number): OutputThroughputSample | undefined {
|
|
63
|
+
if (!text) return
|
|
64
|
+
if (this.segment?.id !== id) {
|
|
65
|
+
this.segment = { id, firstAt: now, charsAfterFirst: 0 }
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
this.segment.charsAfterFirst += text.length
|
|
69
|
+
const elapsed = now - this.segment.firstAt
|
|
70
|
+
if (elapsed < 250) return
|
|
71
|
+
this.latest = { tokensPerSecond: this.segment.charsAfterFirst * 250 / elapsed, estimated: true }
|
|
72
|
+
return this.latest
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
finish(outputTokens: number | undefined, elapsedMs: number): OutputThroughputSample | undefined {
|
|
76
|
+
if (this.latest) return this.latest
|
|
77
|
+
if (!outputTokens || outputTokens <= 0 || !Number.isFinite(outputTokens) || elapsedMs <= 0) return
|
|
78
|
+
return { tokensPerSecond: outputTokens * 1000 / elapsedMs, estimated: false, turnAverage: true }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -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
|
}
|
|
@@ -50,6 +52,7 @@ export class RemoteAgentManager {
|
|
|
50
52
|
async prompt(spec: AcpAgentSpec, cwd: string, text: string, images: ImageContent[] | undefined, options: {
|
|
51
53
|
signal: AbortSignal
|
|
52
54
|
onEvent: (event: AgentEvent) => void
|
|
55
|
+
onContextUsage?: (usage: { used: number; size: number }) => void
|
|
53
56
|
onStarted?: (session: AcpAgentSession) => void
|
|
54
57
|
/** Called once the agent is ready and the prompt is about to be sent. */
|
|
55
58
|
onAccepted?: () => void
|
|
@@ -66,7 +69,7 @@ export class RemoteAgentManager {
|
|
|
66
69
|
options.onAccepted?.()
|
|
67
70
|
this.turnSignal = options.signal
|
|
68
71
|
try {
|
|
69
|
-
const result = await live.session.prompt(content, { signal: options.signal, onEvent: options.onEvent })
|
|
72
|
+
const result = await live.session.prompt(content, { signal: options.signal, onEvent: options.onEvent, onContextUsage: options.onContextUsage })
|
|
70
73
|
return { ...result, session: live.session }
|
|
71
74
|
} catch (error) {
|
|
72
75
|
// A cooperative cancel resolves with stopReason "cancelled"; a throw
|
|
@@ -95,7 +98,7 @@ export class RemoteAgentManager {
|
|
|
95
98
|
|
|
96
99
|
private async ensure(spec: AcpAgentSpec, cwd: string, signal: AbortSignal, onStarted?: (session: AcpAgentSession) => void): Promise<LiveSession> {
|
|
97
100
|
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])
|
|
101
|
+
const key = JSON.stringify([spec.id, spec.command, spec.args ?? [], spec.requireSettings, spec.mode, spec.model, spec.config, cwd])
|
|
99
102
|
// Let a start for another agent settle (and be replaced) first.
|
|
100
103
|
while (this.starting && this.starting.key !== key) await this.starting.promise.catch(() => {})
|
|
101
104
|
if (this.live?.key === key) return this.live
|
package/src/agent/remote-turn.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import type { PlanEntry } from "@agentclientprotocol/sdk"
|
|
2
|
-
import { AgentEventEmitter } from "../../zapsdk/agent/events.js"
|
|
2
|
+
import { AgentEventEmitter, type AgentEvent } from "../../zapsdk/agent/events.js"
|
|
3
3
|
import type { LoopAgentResult } from "../../zapsdk/agent/loop.js"
|
|
4
4
|
import type { ImageContent } from "../../zapsdk/core/types.js"
|
|
5
5
|
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"
|
|
10
|
+
import { AgentOutputThroughput } from "./outputThroughput.js"
|
|
9
11
|
import { remoteAgents } from "./remote-agent.js"
|
|
10
12
|
|
|
11
13
|
export interface RemoteTurnDeps extends Omit<RunHandlersDeps, "preview" | "setContextTokens" | "setContextPending" | "currentConfig"> {
|
|
12
14
|
currentConfig: RunHandlersDeps["currentConfig"]
|
|
15
|
+
setRemoteContext: (usage: { used: number; size: number } | undefined) => void
|
|
16
|
+
nativeClaude?: boolean
|
|
13
17
|
spec: AcpAgentSpec
|
|
14
18
|
cwd: string
|
|
15
19
|
conversation: ConversationManager
|
|
@@ -22,28 +26,60 @@ export interface RemoteTurnDeps extends Omit<RunHandlersDeps, "preview" | "setCo
|
|
|
22
26
|
checkpointTurn?: { begin: () => Promise<unknown>; end: () => Promise<unknown> }
|
|
23
27
|
}
|
|
24
28
|
|
|
29
|
+
const claudeSessions = new WeakMap<ConversationManager, { tip: unknown; sessionId: string; epoch: number; cwd: string }>()
|
|
30
|
+
|
|
25
31
|
/** One user turn handled by an external ACP agent instead of zap's loop.
|
|
26
32
|
* Rendering reuses the regular run handlers, so the transcript looks the
|
|
27
33
|
* same; zap's conversation records the exchange so switching back to zap
|
|
28
34
|
* keeps the context. Throws after reporting when the turn fails. */
|
|
29
35
|
export async function runRemoteTurn(deps: RemoteTurnDeps, task: string, images?: ImageContent[]): Promise<LoopAgentResult> {
|
|
30
36
|
const preview = deps.createPreview()
|
|
31
|
-
const handlers = createRunHandlers({ ...deps, preview, setContextTokens() {}, setContextPending() {} })
|
|
37
|
+
const handlers = createRunHandlers({ ...deps, externalContext: true, preview, setContextTokens() {}, setContextPending() {} })
|
|
32
38
|
const emitter = new AgentEventEmitter()
|
|
33
39
|
handlers.wire(emitter)
|
|
34
40
|
const { spec, controller } = deps
|
|
35
41
|
await deps.checkpointTurn?.begin().catch(() => {})
|
|
36
42
|
try {
|
|
37
|
-
|
|
43
|
+
if (remoteAgents.host.blocked) throw new Error(remoteAgents.host.blocked)
|
|
44
|
+
const previous = claudeSessions.get(deps.conversation)
|
|
45
|
+
claudeSessions.delete(deps.conversation)
|
|
46
|
+
const epoch = remoteAgents.epoch
|
|
47
|
+
const throughput = new AgentOutputThroughput()
|
|
48
|
+
const onEvent = (event: AgentEvent) => {
|
|
49
|
+
emitter.emit(event)
|
|
50
|
+
if (event.type === "content_delta" && !event.path?.length && !controller.signal.aborted && (event.kind === "thinking" || event.kind === "text")) {
|
|
51
|
+
const sample = throughput.chunk(event.id, event.text, performance.now())
|
|
52
|
+
if (sample) deps.setOutputThroughput?.(sample)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
let acceptedAt: number | undefined
|
|
56
|
+
const onAccepted = () => {
|
|
57
|
+
acceptedAt = performance.now()
|
|
58
|
+
deps.onInputAccepted?.()
|
|
59
|
+
}
|
|
60
|
+
const turn = deps.nativeClaude ? await promptClaudeCode({
|
|
61
|
+
command: spec.command, args: spec.args, cwd: deps.cwd, text: task, images, signal: controller.signal,
|
|
62
|
+
plan: deps.currentConfig.permissionMode === "plan", approve: remoteAgents.host.approve,
|
|
63
|
+
resume: previous?.cwd === deps.cwd && previous.epoch === epoch && previous.tip === deps.conversation.getTurns().at(-1) ? previous.sessionId : undefined,
|
|
64
|
+
onEvent, onAccepted,
|
|
65
|
+
}) : await remoteAgents.prompt(spec, deps.cwd, task, images, {
|
|
38
66
|
signal: controller.signal,
|
|
39
|
-
onEvent
|
|
40
|
-
onAccepted
|
|
67
|
+
onEvent,
|
|
68
|
+
onAccepted,
|
|
69
|
+
onContextUsage: usage => { if (!controller.signal.aborted) deps.setRemoteContext(usage) },
|
|
41
70
|
onStarted: session => {
|
|
71
|
+
deps.setRemoteContext(undefined)
|
|
42
72
|
deps.addLog("system", `Connected to ${session.agentName} (${spec.id}) over ACP${session.warnings.length ? ` · ${session.warnings.join("; ")}` : ""}`)
|
|
43
73
|
},
|
|
44
74
|
})
|
|
75
|
+
const elapsedMs = acceptedAt === undefined ? 0 : performance.now() - acceptedAt
|
|
45
76
|
deps.conversation.add({ role: "user", content: task })
|
|
46
|
-
deps.conversation.add({ role: "assistant", content: `[${spec.id}
|
|
77
|
+
deps.conversation.add({ role: "assistant", content: `[${spec.id}] ${turn.report || "(no message)"}` })
|
|
78
|
+
if ("sessionId" in turn) claudeSessions.set(deps.conversation, { tip: deps.conversation.getTurns().at(-1), epoch, cwd: deps.cwd, sessionId: turn.sessionId })
|
|
79
|
+
if (turn.usage) emitter.emit({ type: "run_usage", step: turn.toolCalls, ...turn.usage })
|
|
80
|
+
if (!controller.signal.aborted) {
|
|
81
|
+
deps.setOutputThroughput?.(throughput.finish(turn.usage?.providerUsageReported === false ? undefined : turn.usage?.outputTokens, elapsedMs))
|
|
82
|
+
}
|
|
47
83
|
if (turn.plan.length) deps.addLog("system", formatPlan(spec.id, turn.plan))
|
|
48
84
|
if (turn.stopReason !== "end_turn" && turn.stopReason !== "cancelled") deps.addLog("system", `${spec.id} stopped: ${turn.stopReason}`)
|
|
49
85
|
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"
|
|
@@ -47,6 +47,8 @@ type ReplaceLog = (
|
|
|
47
47
|
) => void
|
|
48
48
|
|
|
49
49
|
export interface RunHandlersDeps {
|
|
50
|
+
/** External agents own their context and report aggregate, multi-request turn usage. */
|
|
51
|
+
externalContext?: boolean
|
|
50
52
|
/** Live snapshot of the app config — read once at handler-creation time
|
|
51
53
|
* for warning thresholds. Doesn't need to be reactive: a handler set up
|
|
52
54
|
* for run N reads the config that was active when run N started. */
|
|
@@ -188,10 +190,7 @@ export interface RunHandlers {
|
|
|
188
190
|
const SUBAGENT_TOOLS = new Set(["agent", "delegate_agent", "acp_agent"])
|
|
189
191
|
|
|
190
192
|
export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
191
|
-
const cacheScope =
|
|
192
|
-
deps.currentConfig.active.providerId,
|
|
193
|
-
deps.currentConfig.active.model,
|
|
194
|
-
)
|
|
193
|
+
const cacheScope = conversationCacheScope(deps.currentConfig)
|
|
195
194
|
const throughput = new OutputThroughput()
|
|
196
195
|
const pendingToolLogById = new Map<string, PendingTool>()
|
|
197
196
|
const pendingSubagentToolLogById = new Map<string, PendingSubagentTool>()
|
|
@@ -462,7 +461,7 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
462
461
|
// against the context window, even though cache reads are billed
|
|
463
462
|
// cheaper. Without this sum the Footer / TokenWarning silently
|
|
464
463
|
// under-report usage by an order of magnitude in long sessions.
|
|
465
|
-
const used = contextTokensFromRunUsage(e)
|
|
464
|
+
const used = deps.externalContext ? null : contextTokensFromRunUsage(e)
|
|
466
465
|
if (used !== null) deps.setContextTokens(used, "provider")
|
|
467
466
|
deps.setContextPending(false)
|
|
468
467
|
deps.onRunUsage?.({
|
|
@@ -498,7 +497,7 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
498
497
|
}, {
|
|
499
498
|
getLocalEstimate: () => localAtTime,
|
|
500
499
|
appendUsage: deps.appendUsage ?? appendUsage,
|
|
501
|
-
setPromptOverhead: (overhead) => { tokenAccounting.promptOverhead = overhead },
|
|
500
|
+
setPromptOverhead: deps.externalContext ? undefined : (overhead) => { tokenAccounting.promptOverhead = overhead },
|
|
502
501
|
})
|
|
503
502
|
deps.onUsagePersistenceFailure?.(undefined)
|
|
504
503
|
} catch (err) {
|