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
|
@@ -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 {
|
|
@@ -366,6 +367,7 @@ export function useAgentRunner({
|
|
|
366
367
|
const { view: goalStatus, select: selectGoalView, update: updateGoalView, clear: resetGoalView } = useGoalView(currentSessionId, cwd, goalRunning, undefined, appLogger)
|
|
367
368
|
const [goalTodoId, setGoalTodoId] = useState<string>()
|
|
368
369
|
useEffect(() => { setGoalTodoId(undefined) }, [currentSessionId])
|
|
370
|
+
const [remoteContext, setRemoteContext] = useState<{ used: number; size: number }>()
|
|
369
371
|
const [outputThroughput, setOutputThroughput] = useState<OutputThroughputSample>()
|
|
370
372
|
const [providerRequest, setProviderRequest] = useState<ProviderRequestEvent>()
|
|
371
373
|
const [step, setStep] = useState(0)
|
|
@@ -408,6 +410,11 @@ export function useAgentRunner({
|
|
|
408
410
|
)
|
|
409
411
|
const imageTokenContext = resolveModelImageTokenContext(getActiveProvider(config), config.active.model)
|
|
410
412
|
const imageTokenScope = `${config.active.providerId}\0${config.active.model}\0${JSON.stringify(imageTokenContext)}`
|
|
413
|
+
const remoteAgentId = conversationAgentId(config)
|
|
414
|
+
useEffect(() => {
|
|
415
|
+
setRemoteContext(undefined)
|
|
416
|
+
setOutputThroughput(undefined)
|
|
417
|
+
}, [remoteAgentId, currentSessionId, imageTokenScope, config.permissionMode])
|
|
411
418
|
const contextScopeRef = useRef(imageTokenScope)
|
|
412
419
|
useEffect(() => {
|
|
413
420
|
const nextScope = imageTokenScope
|
|
@@ -501,6 +508,7 @@ export function useAgentRunner({
|
|
|
501
508
|
) => {
|
|
502
509
|
const next = buildResetRunDiagnosticsState(usage, context, restoredUsageHistory, restoredContextHistory, promptCache)
|
|
503
510
|
setOutputThroughput(undefined)
|
|
511
|
+
setRemoteContext(undefined)
|
|
504
512
|
setTokens(next.tokens)
|
|
505
513
|
setUsageHistory(next.usageHistory)
|
|
506
514
|
setContextDiagnostics(next.contextDiagnostics)
|
|
@@ -591,20 +599,30 @@ export function useAgentRunner({
|
|
|
591
599
|
let handlers: ReturnType<typeof createRunHandlers> | null = null
|
|
592
600
|
|
|
593
601
|
// Session mode: an external ACP agent answers this turn instead of zap's loop.
|
|
594
|
-
const
|
|
595
|
-
|
|
602
|
+
const agentId = conversationAgentId(config)
|
|
603
|
+
const nativeClaude = agentId === "claude-code"
|
|
604
|
+
let remoteSpec
|
|
605
|
+
if (agentId) {
|
|
596
606
|
try {
|
|
597
|
-
if (
|
|
607
|
+
if (nativeClaude) {
|
|
608
|
+
remoteSpec = { id: agentId, ...await nativeCommand("claude") }
|
|
609
|
+
} else if (agentId === "codex") {
|
|
610
|
+
remoteSpec = await codexConversationSpec(config, acpAgents.find(agent => agent.id === "codex"))
|
|
611
|
+
} else {
|
|
612
|
+
remoteSpec = acpAgents.find(agent => agent.id === agentId)
|
|
613
|
+
}
|
|
614
|
+
if (!remoteSpec) throw new Error(`Agent ${agentId} is unavailable. ${agentInstallHint(agentId)}`)
|
|
598
615
|
if (invocation?.goalTurn) throw new Error("/goal runs on zap's own model; /agent zap switches back")
|
|
599
616
|
if (systemPrompt) throw new Error("This command runs on zap's own model; /agent zap switches back")
|
|
600
617
|
completedResult = await runRemoteTurn({
|
|
601
|
-
spec: remoteSpec, cwd, conversation, currentConfig: config, controller,
|
|
618
|
+
spec: remoteSpec, nativeClaude, setRemoteContext, cwd, conversation, currentConfig: config, controller,
|
|
602
619
|
createPreview: () => {
|
|
603
620
|
const next = createStreamingPreview({ addLog, setStreamingText, setIsStreaming, setThinkingText, setIsThinking, getIsFrozen: getIsFrozen ?? (() => false) })
|
|
604
621
|
registerStaticFlushCallback?.(() => next.onStaticFlushed())
|
|
605
622
|
return next
|
|
606
623
|
},
|
|
607
624
|
saveLastOutput,
|
|
625
|
+
onRunUsage: usage => recordUsage(usage, undefined, conversationCacheScope(config)),
|
|
608
626
|
onInputAccepted: invocation?.onInputAccepted,
|
|
609
627
|
checkpointTurn: checkpoint ? (() => {
|
|
610
628
|
const turnStartIndex = conversation.getAllMessages().length
|
|
@@ -1113,6 +1131,7 @@ export function useAgentRunner({
|
|
|
1113
1131
|
abortRef,
|
|
1114
1132
|
status,
|
|
1115
1133
|
providerRequest,
|
|
1134
|
+
remoteContext,
|
|
1116
1135
|
outputThroughput,
|
|
1117
1136
|
setStatus,
|
|
1118
1137
|
step,
|
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
|
|
31
|
-
auth status codex Show
|
|
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)
|
|
@@ -1,44 +1,40 @@
|
|
|
1
1
|
/** @jsxImportSource react */
|
|
2
2
|
import { useEffect, useRef, useState } from "react"
|
|
3
|
+
import { stripVTControlCharacters } from "node:util"
|
|
3
4
|
import { Text, useInput } from "ink"
|
|
4
|
-
import {
|
|
5
|
+
import { runCodexAuth } from "../codex-auth.js"
|
|
5
6
|
import { DialogFrame } from "./dialog-frame.js"
|
|
6
7
|
import { PickerDialog } from "./dialog-picker.js"
|
|
7
8
|
import { c } from "./theme.js"
|
|
8
9
|
|
|
9
10
|
export function CodexLoginDialog({ onSuccess, onCancel }: { onSuccess: () => void; onCancel: () => void }) {
|
|
10
|
-
const [method, setMethod] = useState<"browser" | "device" | null>(null)
|
|
11
|
-
const [details, setDetails] = useState
|
|
11
|
+
const [method, setMethod] = useState<"browser" | "device" | "existing" | null>(null)
|
|
12
|
+
const [details, setDetails] = useState("")
|
|
12
13
|
const [error, setError] = useState("")
|
|
13
|
-
const callbacks = useRef(
|
|
14
|
-
callbacks.current =
|
|
14
|
+
const callbacks = useRef(onSuccess)
|
|
15
|
+
callbacks.current = onSuccess
|
|
15
16
|
useInput((_input, key) => { if (method && key.escape) setMethod(null) })
|
|
16
17
|
useEffect(() => {
|
|
17
18
|
if (!method) return
|
|
18
19
|
const controller = new AbortController()
|
|
19
|
-
setDetails(
|
|
20
|
+
setDetails(""); setError("")
|
|
20
21
|
void (async () => {
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
setDetails({ url: login.url, instructions: login.instructions })
|
|
24
|
-
openAuthBrowser(login.url)
|
|
25
|
-
const credentials = await login.complete
|
|
22
|
+
const status = await runCodexAuth(method === "existing" ? "status" : "login", { device: method === "device", signal: controller.signal,
|
|
23
|
+
onOutput: text => { if (!controller.signal.aborted) setDetails(previous => (previous + text).slice(-8192)) } })
|
|
26
24
|
if (controller.signal.aborted) return
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
callbacks.current.onSuccess()
|
|
25
|
+
if (status !== 0) throw new Error("Codex login did not complete. Run codex login to retry.")
|
|
26
|
+
callbacks.current()
|
|
30
27
|
})().catch(error => { if (!controller.signal.aborted) setError(error instanceof Error ? error.message : "Codex login failed.") })
|
|
31
28
|
return () => controller.abort()
|
|
32
29
|
}, [method])
|
|
33
30
|
if (!method) return <PickerDialog title="OpenAI Codex · sign in with ChatGPT"
|
|
34
|
-
options={[{ id: "
|
|
31
|
+
options={[{ id: "existing", label: "Use existing Codex login", meta: "checks the local CLI session" },
|
|
32
|
+
{ id: "browser", label: "Browser login", meta: "opens ChatGPT sign-in · local callback on port 1455" },
|
|
35
33
|
{ id: "device", label: "Device code", meta: "for SSH, headless hosts, or a busy callback port" }]}
|
|
36
|
-
onCancel={onCancel} onSelect={id => setMethod(id as "browser" | "device")} />
|
|
34
|
+
onCancel={onCancel} onSelect={id => setMethod(id as "browser" | "device" | "existing")} />
|
|
37
35
|
return <DialogFrame title="OpenAI Codex · sign in with ChatGPT" hint="esc back / cancel login">
|
|
38
36
|
{error ? <Text color={c.warning}>{error}</Text> : <>
|
|
39
|
-
<Text>{details
|
|
40
|
-
{details && <Text color={c.accent}>{details.url}</Text>}
|
|
41
|
-
<Text color={c.text.faint}>If the browser did not open, open this URL manually. Waiting for authorization…</Text>
|
|
37
|
+
<Text>{stripVTControlCharacters(details) || "Starting the official Codex login…"}</Text>
|
|
42
38
|
</>}
|
|
43
39
|
</DialogFrame>
|
|
44
40
|
}
|
package/src/ui/dialog-config.tsx
CHANGED
|
@@ -7,7 +7,7 @@ import { modelReasoningFor } from "../../zapsdk/core/reasoning-effort.js"
|
|
|
7
7
|
import { useEffect, useState } from "react"
|
|
8
8
|
import { discoverCodexModels } from "../codex-provider.js"
|
|
9
9
|
import {
|
|
10
|
-
effortModel,
|
|
10
|
+
agentManagingModel, effortModel,
|
|
11
11
|
upsertProvider,
|
|
12
12
|
getActiveProvider,
|
|
13
13
|
getEffort,
|
|
@@ -53,6 +53,8 @@ export function ModeDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
|
53
53
|
// ── Effort picker ────────────────────────────────────────────────────────
|
|
54
54
|
export function EffortDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
55
55
|
const provider = getActiveProvider(config)
|
|
56
|
+
const agent = agentManagingModel(config)
|
|
57
|
+
if (agent) return <PickerDialog title="Reasoning effort" options={[{ id: "agent", label: `Managed by ${agent}`, disabled: true }]} onCancel={onCancel} onSelect={onCancel} />
|
|
56
58
|
// A changed connection remounts the fetch and picker, including its cursor.
|
|
57
59
|
return <ModelEffortDialog key={provider ? `${provider.id}:${effortModel(config, provider)}` : "none"}
|
|
58
60
|
config={config} onCommit={onCommit} onCancel={onCancel} />
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { useRef, useState } from "react"
|
|
3
3
|
import { Box, Text, useInput } from "ink"
|
|
4
4
|
import { randomUUID } from "node:crypto"
|
|
5
|
-
import { buildConnectedProvider, inferLegacyContextWindowMode, presetForConnection, removeProvider, upsertProvider,
|
|
5
|
+
import { conversationAgentId, buildConnectedProvider, inferLegacyContextWindowMode, presetForConnection, removeProvider, upsertProvider,
|
|
6
6
|
type AppConfig, type ContextWindowMode, type Provider, type ProviderProtocol } from "../config.js"
|
|
7
7
|
import { ProviderDirectory } from "./provider-directory.js"
|
|
8
8
|
import { DialogFrame } from "./dialog-frame.js"
|
|
@@ -15,7 +15,7 @@ import { ContextWindowDialog } from "./dialog-context-window.js"
|
|
|
15
15
|
import { CodexLoginDialog } from "./dialog-codex-login.js"
|
|
16
16
|
import { connectCodexProvider } from "../codex-provider.js"
|
|
17
17
|
|
|
18
|
-
interface Props { config: AppConfig; onSave: (next: AppConfig) => void; onCommit: (next: AppConfig) => void; onCancel: () => void }
|
|
18
|
+
interface Props { onAgentSelected?: (message: string) => void; config: AppConfig; onSave: (next: AppConfig) => void; onCommit: (next: AppConfig) => void; onCancel: () => void }
|
|
19
19
|
type Draft = { name: string; baseURL: string; apiKey: string; protocol: ProviderProtocol;
|
|
20
20
|
authMode: "none" | "api-key"; catalogProviderId?: string; existing?: Provider;
|
|
21
21
|
contextWindow?: number; contextWindowMode?: ContextWindowMode }
|
|
@@ -46,7 +46,7 @@ export function saveConnection(config: AppConfig, draft: Draft): AppConfig {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
/** Persist the connection first, then guide new connections through model selection. */
|
|
49
|
-
export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
49
|
+
export function ConnectDialog({ onAgentSelected, config, onSave, onCommit, onCancel }: Props) {
|
|
50
50
|
const [step, setStep] = useState<Step>("connections")
|
|
51
51
|
const [index, setIndex] = useState(0)
|
|
52
52
|
const [deleting, setDeleting] = useState(false)
|
|
@@ -91,9 +91,10 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
91
91
|
hint={deleting ? "d confirm removal · esc cancel" : "↑↓ navigate · enter/e edit · m models · d remove · esc close"}>
|
|
92
92
|
<Text color={c.text.faint}>Add a connection, then choose its model. Press m to manage models for an existing connection.</Text>
|
|
93
93
|
<Box flexDirection="column" marginTop={1}>
|
|
94
|
+
{conversationAgentId(config) === "claude-code" && <Text color={c.accent}>Claude Code · active local CLI</Text>}
|
|
94
95
|
{config.providers.map((provider, i) => <Box key={provider.id} flexDirection="column">
|
|
95
96
|
<Text color={i === index ? c.accent : c.text.primary}>{`${i === index ? "›" : " "} ${provider.name || "Unnamed connection"}`}</Text>
|
|
96
|
-
<Text color={c.text.faint}>{` ${provider.authMode === "codex-oauth" ? "Codex
|
|
97
|
+
<Text color={c.text.faint}>{` ${provider.authMode === "codex-oauth" ? "Official Codex agent · local CLI login" : `${provider.protocol ?? "openai"} · ${provider.apiKey ? "API key stored" : "no key"}`} · ${provider.models.length} saved models`}</Text>
|
|
97
98
|
<Text color={c.text.faint}>{` ${provider.baseURL}`}</Text>
|
|
98
99
|
</Box>)}
|
|
99
100
|
<Text color={index === config.providers.length ? c.accent : c.text.primary}>{`${index === config.providers.length ? "›" : " "} + New connection`}</Text>
|
|
@@ -107,7 +108,10 @@ export function ConnectDialog({ config, onSave, onCommit, onCancel }: Props) {
|
|
|
107
108
|
setModelTarget({ id: result.provider.id, setup: true })
|
|
108
109
|
}} />
|
|
109
110
|
|
|
110
|
-
if (step === "preset") return <ProviderDirectory onCodex={() => setStep("codex")}
|
|
111
|
+
if (step === "preset") return <ProviderDirectory onCodex={() => setStep("codex")} onClaude={() => {
|
|
112
|
+
onCommit({ ...config, activeAgent: undefined, subscriptionAgent: "claude-code" })
|
|
113
|
+
onAgentSelected?.("agent → Claude Code")
|
|
114
|
+
}}
|
|
111
115
|
onCancel={() => setStep("connections")} onSelect={provider => {
|
|
112
116
|
setDraft({ catalogProviderId: provider?.id, name: provider?.name ?? "", baseURL: provider?.api ?? "", apiKey: "",
|
|
113
117
|
protocol: provider?.protocol ?? "openai", authMode: "api-key" })
|
package/src/ui/dialog-model.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** @jsxImportSource react */
|
|
2
2
|
import { useEffect, useRef, useState } from "react"
|
|
3
3
|
import { Box, Text, useInput } from "ink"
|
|
4
|
-
import { inferLegacyContextWindowMode, resolveProviderContextWindow, upsertProvider, type AppConfig } from "../config.js"
|
|
4
|
+
import { agentManagingModel, inferLegacyContextWindowMode, resolveProviderContextWindow, upsertProvider, type AppConfig } from "../config.js"
|
|
5
5
|
import { associateModelMetadata, describeCatalogRow, selectCatalogModel } from "../provider-catalog.js"
|
|
6
6
|
import { configuredModelRows, discoverConfiguredModels, modelCatalogKey, savedConnectionCatalogs, type ConnectionCatalog, type ConnectionModelRow } from "../model-catalog.js"
|
|
7
7
|
import { DialogFrame } from "./dialog-frame.js"
|
|
@@ -10,12 +10,43 @@ import { TextField } from "./text-field.js"
|
|
|
10
10
|
import { commandInput, isReturnInput } from "./controlled-input.js"
|
|
11
11
|
import { c } from "./theme.js"
|
|
12
12
|
import { useTermWidth } from "./term-width.js"
|
|
13
|
-
import { truncateToWidth } from "./truncate.js"
|
|
13
|
+
import { displayWidth, truncateToWidth } from "./truncate.js"
|
|
14
14
|
import { ModelMetadataDialog } from "./dialog-model-metadata.js"
|
|
15
15
|
import { ContextWindowDialog } from "./dialog-context-window.js"
|
|
16
16
|
|
|
17
17
|
interface Props { config: AppConfig; initialProviderId?: string; setup?: boolean; onSave: (next: AppConfig) => void; onCommit: (next: AppConfig) => void; onCancel: () => void }
|
|
18
18
|
|
|
19
|
+
interface ProviderTab { id: string | null; label: string }
|
|
20
|
+
|
|
21
|
+
function ProviderTabs({ tabs, index, width }: { tabs: ProviderTab[]; index: number; width: number }) {
|
|
22
|
+
const labels = tabs.map((tab, i) => {
|
|
23
|
+
const name = truncateToWidth(tab.label, Math.max(1, width - 6))
|
|
24
|
+
return i === index ? `[${name}]` : name
|
|
25
|
+
})
|
|
26
|
+
// Keep the focused tab in view even with wide Unicode names or a small terminal.
|
|
27
|
+
let first = index
|
|
28
|
+
let last = index
|
|
29
|
+
let used = displayWidth(labels[index])
|
|
30
|
+
const fits = (left: number, right: number, extra: number) =>
|
|
31
|
+
used + 2 + extra + (left > 0 ? 2 : 0) + (right < tabs.length - 1 ? 2 : 0) <= width
|
|
32
|
+
while (first > 0 && fits(first - 1, last, displayWidth(labels[first - 1]))) {
|
|
33
|
+
first -= 1
|
|
34
|
+
used += 2 + displayWidth(labels[first])
|
|
35
|
+
}
|
|
36
|
+
while (last + 1 < tabs.length && fits(first, last + 1, displayWidth(labels[last + 1]))) {
|
|
37
|
+
last += 1
|
|
38
|
+
used += 2 + displayWidth(labels[last])
|
|
39
|
+
}
|
|
40
|
+
return <Text wrap="truncate-end">
|
|
41
|
+
{first > 0 && <Text color={c.text.faint}>‹ </Text>}
|
|
42
|
+
{tabs.slice(first, last + 1).map((tab, offset) => <Text key={tab.id === null ? "all" : `provider:${tab.id}`}
|
|
43
|
+
bold={first + offset === index} color={first + offset === index ? c.accent : c.text.muted}>
|
|
44
|
+
{offset > 0 ? " " : ""}{labels[first + offset]}
|
|
45
|
+
</Text>)}
|
|
46
|
+
{last + 1 < tabs.length && <Text color={c.text.faint}> ›</Text>}
|
|
47
|
+
</Text>
|
|
48
|
+
}
|
|
49
|
+
|
|
19
50
|
export function ModelDialog({ config, initialProviderId, setup = false, onSave, onCommit, onCancel }: Props) {
|
|
20
51
|
const width = Math.max(10, useTermWidth() - 2)
|
|
21
52
|
const [height, setHeight] = useState(process.stdout.rows ?? 24)
|
|
@@ -24,7 +55,12 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
|
|
|
24
55
|
process.stdout.on("resize", resize)
|
|
25
56
|
return () => { process.stdout.off("resize", resize) }
|
|
26
57
|
}, [])
|
|
27
|
-
const [
|
|
58
|
+
const [tabId, setTabId] = useState<string | null>(initialProviderId ?? (config.active.providerId || config.providers[0]?.id || null))
|
|
59
|
+
const tabs: ProviderTab[] = config.providers.map(item => ({ id: item.id, label: item.name || item.id }))
|
|
60
|
+
if (!setup && tabs.length > 1) tabs.push({ id: null, label: "All" })
|
|
61
|
+
const tabIndex = Math.max(0, tabs.findIndex(tab => tab.id === tabId))
|
|
62
|
+
const providerFilter = tabs[tabIndex]?.id ?? null
|
|
63
|
+
const lastModel = useRef(new Map<string | null, string>())
|
|
28
64
|
const [phase, setPhase] = useState<"models" | "providers" | "manual" | "search" | "metadata" | "context">("models")
|
|
29
65
|
const [providerAction, setProviderAction] = useState<"filter" | "manual">("filter")
|
|
30
66
|
const [target, setTarget] = useState<ConnectionModelRow | null>(null)
|
|
@@ -64,12 +100,24 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
|
|
|
64
100
|
return discoverConfiguredModels(requested, update)
|
|
65
101
|
}, [config.providers, refresh, setupProviderId])
|
|
66
102
|
|
|
103
|
+
function switchProvider(id: string | null) {
|
|
104
|
+
if (displayedKey) lastModel.current.set(providerFilter, displayedKey)
|
|
105
|
+
setTabId(id)
|
|
106
|
+
setQuery("")
|
|
107
|
+
setSelectedKey(lastModel.current.get(id) ?? modelCatalogKey(config.active.providerId, config.active.model))
|
|
108
|
+
setPhase("models")
|
|
109
|
+
}
|
|
110
|
+
|
|
67
111
|
useInput((input, key) => {
|
|
68
112
|
const state = live.current
|
|
69
113
|
if (state.phase !== "models") return
|
|
70
114
|
const cmd = commandInput(input, key)
|
|
71
115
|
if (key.escape) { state.onCancel(); return }
|
|
72
116
|
if (!state.provider) return
|
|
117
|
+
if (!setup && tabs.length > 1 && (key.leftArrow || key.rightArrow)) {
|
|
118
|
+
switchProvider(tabs[(tabIndex + (key.leftArrow ? -1 : 1) + tabs.length) % tabs.length].id)
|
|
119
|
+
return
|
|
120
|
+
}
|
|
73
121
|
if (cmd === "p" && !setup) { setProviderAction("filter"); setPhase("providers"); return }
|
|
74
122
|
if (cmd === "t") {
|
|
75
123
|
setManual("")
|
|
@@ -96,8 +144,11 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
|
|
|
96
144
|
}
|
|
97
145
|
})
|
|
98
146
|
|
|
147
|
+
const agent = agentManagingModel(config)
|
|
148
|
+
const agentModel = agent === "claude-code" ? "Claude Code · model selected by local CLI" : agent ? `${agent} · model selected by agent` : undefined
|
|
99
149
|
if (!provider) return <DialogFrame title="Models · /model" hint="esc close">
|
|
100
|
-
<Text>
|
|
150
|
+
{agentModel && <Text>Current: {agentModel}</Text>}
|
|
151
|
+
<Text>No provider models configured. Use /connect to add a model provider.</Text>
|
|
101
152
|
</DialogFrame>
|
|
102
153
|
if (phase === "metadata" && target && targetProvider) return <ModelMetadataDialog modelId={target.id}
|
|
103
154
|
onCancel={() => setPhase("models")} onSelect={metadata => {
|
|
@@ -112,16 +163,16 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
|
|
|
112
163
|
setPhase("models")
|
|
113
164
|
}} />
|
|
114
165
|
if (phase === "providers") return <PickerDialog key={providerAction} title={providerAction === "manual" ? "Manual model · choose connection" : "Models · filter connections"}
|
|
115
|
-
options={[...(providerAction === "filter" ? [{ id: "all", label: "All configured connections", meta: `${config.providers.length} connections` }] : []),
|
|
166
|
+
options={[...(providerAction === "filter" && config.providers.length > 1 ? [{ id: "all", label: "All configured connections", meta: `${config.providers.length} connections` }] : []),
|
|
116
167
|
...config.providers.map(item => ({ id: `provider:${item.id}`, label: item.name || item.baseURL, meta: item.baseURL }))]}
|
|
117
|
-
initialIndex={providerAction === "filter" ? providerFilter === null ? 0 : Math.max(0, config.providers.findIndex(item => item.id === providerFilter) + 1)
|
|
168
|
+
initialIndex={providerAction === "filter" ? providerFilter === null ? 0 : Math.max(0, config.providers.findIndex(item => item.id === providerFilter) + Number(config.providers.length > 1))
|
|
118
169
|
: Math.max(0, config.providers.findIndex(item => item.id === provider.id))}
|
|
119
170
|
onCancel={() => setPhase("models")} onSelect={id => {
|
|
120
171
|
if (providerAction === "manual") { setManualProviderId(id.slice("provider:".length)); setPhase("manual") }
|
|
121
|
-
else
|
|
172
|
+
else switchProvider(id === "all" ? null : id.slice("provider:".length))
|
|
122
173
|
}} />
|
|
123
174
|
if (phase === "search" || phase === "manual" && manualProvider) return <DialogFrame
|
|
124
|
-
title={phase === "manual" ? `Manual model ID · ${manualProvider!.name}` :
|
|
175
|
+
title={phase === "manual" ? `Manual model ID · ${manualProvider!.name}` : `Search models · ${providerFilter === null ? "All" : provider.name}`} hint="enter confirm · esc back">
|
|
125
176
|
<Text color={c.text.faint}>{phase === "manual" ? "Manual IDs are unverified. The endpoint must support this exact ID." : "Search model IDs, connection names or endpoints. Selection changes only on Enter."}</Text>
|
|
126
177
|
<TextField key={phase} isActive value={phase === "manual" ? manual : query}
|
|
127
178
|
onChange={phase === "manual" ? setManual : setQuery} onCancel={() => setPhase("models")}
|
|
@@ -135,26 +186,35 @@ export function ModelDialog({ config, initialProviderId, setup = false, onSave,
|
|
|
135
186
|
const loading = scopedCatalogs.filter(item => item.loading).length
|
|
136
187
|
const failed = scopedCatalogs.filter(item => item.error).length
|
|
137
188
|
const error = catalogs.find(item => item.providerId === provider.id)?.error
|
|
138
|
-
const count = Math.max(1, Math.min(
|
|
139
|
-
const start = Math.max(0, selectedIndex - Math.floor(count / 2))
|
|
189
|
+
const count = Math.max(1, Math.min(12, height - 18))
|
|
190
|
+
const start = Math.max(0, Math.min(shown.length - count, selectedIndex - Math.floor(count / 2)))
|
|
140
191
|
const activeProvider = config.providers.find(item => item.id === config.active.providerId)
|
|
141
|
-
return <DialogFrame title={
|
|
142
|
-
hint={setup ? "↑↓
|
|
192
|
+
return <DialogFrame title={setup ? `Choose a model · ${provider.name || provider.baseURL}` : "Models"}
|
|
193
|
+
hint={setup ? "↑↓ model · enter select and finish · m metadata · c context · / search · t manual · esc choose later" : `${tabs.length > 1 ? "←→ provider · " : ""}↑↓ model · enter select · / search · p providers · m metadata · c context · r refresh · t manual · esc close`}>
|
|
143
194
|
{setup && <Text color={c.accent}>Connection saved. Choose a model to use it, or press esc to choose later with /model.</Text>}
|
|
144
|
-
<
|
|
145
|
-
<Text color={c.text.faint}>{truncateToWidth(
|
|
146
|
-
<Text color={c.text.
|
|
147
|
-
? `${provider.name}: manual context ${provider.contextWindow.toLocaleString("en-US")} tokens · c to change`
|
|
148
|
-
: `${provider.name}: automatic context · m to link metadata · fallback ${provider.contextWindow.toLocaleString("en-US")} tokens`, width)}</Text>
|
|
195
|
+
{!setup && <ProviderTabs tabs={tabs} index={tabIndex} width={width} />}
|
|
196
|
+
<Text color={c.text.faint}>{truncateToWidth(`Current: ${agentModel ?? `${config.active.model || "none"} · ${activeProvider?.name || "none"}`}`, width)}</Text>
|
|
197
|
+
<Text color={c.text.muted}>{truncateToWidth(`${providerFilter !== null ? provider.baseURL + " · " : ""}${shown.length} models${loading ? " · discovering…" : ""}${failed && providerFilter === null ? ` · ${failed} offline` : ""}${query ? ` · filter: ${query}` : ""}`, width)}</Text>
|
|
149
198
|
{error && <Text color={c.warning}>{truncateToWidth(`${provider.name}: ${error}`, width)}</Text>}
|
|
150
199
|
<Box flexDirection="column" marginTop={1}>
|
|
151
|
-
{
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
200
|
+
{start > 0 && <Text color={c.text.faint}>… {start} above</Text>}
|
|
201
|
+
{shown.slice(start, start + count).map((row, i) => {
|
|
202
|
+
const focused = start + i === selectedIndex
|
|
203
|
+
const current = !agent && row.provider.id === config.active.providerId && row.id === config.active.model
|
|
204
|
+
const owner = providerFilter === null ? ` · ${row.provider.name || row.provider.id}` : ""
|
|
205
|
+
return <Text key={modelCatalogKey(row.provider.id, row.id)} color={focused ? c.accent : c.text.primary} bold={focused}>
|
|
206
|
+
{truncateToWidth(`${focused ? "›" : " "} ${row.id}${current ? " (current)" : ""}${owner}`, width)}
|
|
207
|
+
</Text>
|
|
208
|
+
})}
|
|
156
209
|
{!shown.length && <Text color={c.text.faint}>{loading ? "Discovering models… You can enter an ID with t." : "No matching models. Press t to enter an ID or / to change the filter."}</Text>}
|
|
157
210
|
{start + count < shown.length && <Text color={c.text.faint}>{`… ${shown.length - start - count} more`}</Text>}
|
|
158
211
|
</Box>
|
|
212
|
+
{selected && <Box flexDirection="column" marginTop={1}>
|
|
213
|
+
{providerFilter === null && <Text color={c.text.faint}>{truncateToWidth(provider.baseURL, width)}</Text>}
|
|
214
|
+
<Text color={c.text.muted}>{truncateToWidth(describeCatalogRow(selected), width)}</Text>
|
|
215
|
+
<Text color={c.text.faint}>{truncateToWidth((provider.contextWindowMode ?? inferLegacyContextWindowMode(provider)) === "manual"
|
|
216
|
+
? `${provider.name}: manual context ${provider.contextWindow.toLocaleString("en-US")} tokens · c to change`
|
|
217
|
+
: `${provider.name}: automatic context · fallback ${provider.contextWindow.toLocaleString("en-US")} tokens`, width)}</Text>
|
|
218
|
+
</Box>}
|
|
159
219
|
</DialogFrame>
|
|
160
220
|
}
|
package/src/ui/footer.tsx
CHANGED
|
@@ -32,7 +32,7 @@ export function contextFooterText(contextBudget: ContextBudgetSnapshot): string
|
|
|
32
32
|
|
|
33
33
|
export function throughputFooterText(sample: OutputThroughputSample | undefined): string {
|
|
34
34
|
if (!sample || !Number.isFinite(sample.tokensPerSecond) || sample.tokensPerSecond <= 0) return ""
|
|
35
|
-
return `${sample.estimated ? "~" : ""}${sample.tokensPerSecond.toFixed(1)} token/s`
|
|
35
|
+
return `${sample.turnAverage ? "avg " : ""}${sample.estimated ? "~" : ""}${sample.tokensPerSecond.toFixed(1)} token/s`
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
interface FooterProps {
|
|
@@ -45,8 +45,8 @@ interface FooterProps {
|
|
|
45
45
|
step: number
|
|
46
46
|
maxSteps: number
|
|
47
47
|
contextBudget: ContextBudgetSnapshot
|
|
48
|
-
/**
|
|
49
|
-
|
|
48
|
+
/** null while an external agent has not reported its window. */
|
|
49
|
+
remoteContext?: { used: number; size: number } | null
|
|
50
50
|
hasApiKey: boolean
|
|
51
51
|
showWelcome?: boolean
|
|
52
52
|
shellMode?: boolean
|
|
@@ -68,7 +68,7 @@ export const Footer = memo(function Footer({
|
|
|
68
68
|
effort,
|
|
69
69
|
isRunning,
|
|
70
70
|
contextBudget,
|
|
71
|
-
|
|
71
|
+
remoteContext,
|
|
72
72
|
hasApiKey,
|
|
73
73
|
showWelcome,
|
|
74
74
|
shellMode,
|
|
@@ -81,9 +81,11 @@ export const Footer = memo(function Footer({
|
|
|
81
81
|
// computed centrally against compactAt, so Footer, TokenWarning and /status
|
|
82
82
|
// cannot drift into three different threshold systems.
|
|
83
83
|
const tpsText = throughputFooterText(outputThroughput)
|
|
84
|
-
const ctxText = contextFooterText(contextBudget)
|
|
84
|
+
const ctxText = remoteContext === undefined ? contextFooterText(contextBudget)
|
|
85
|
+
: remoteContext ? `ctx ${formatTokensK(remoteContext.used)}/${formatTokensK(remoteContext.size)} (${Math.round(100 * remoteContext.used / remoteContext.size)}%)` : ""
|
|
85
86
|
const ctxColor =
|
|
86
|
-
|
|
87
|
+
remoteContext ? c.text.muted
|
|
88
|
+
: contextBudget.severity === "critical" ? c.error
|
|
87
89
|
: contextBudget.severity === "warning" ? c.warning
|
|
88
90
|
: contextBudget.severity === "notice" ? c.accent
|
|
89
91
|
: c.text.faint
|
|
@@ -108,7 +110,7 @@ export const Footer = memo(function Footer({
|
|
|
108
110
|
if (!hasApiKey && !showWelcome) rightSegments.push({ text: "! /connect", fg: c.warning, key: "connect" })
|
|
109
111
|
if (showWelcome && !hasApiKey) rightSegments.push({ text: "/connect", fg: c.accent, key: "connect" })
|
|
110
112
|
if (tpsText) rightSegments.push({ text: tpsText, fg: c.text.muted, key: "tps" })
|
|
111
|
-
if (ctxText
|
|
113
|
+
if (ctxText) rightSegments.push({ text: ctxText, fg: ctxColor, key: "ctx" })
|
|
112
114
|
if (mcp && mcp.total > 0) {
|
|
113
115
|
const hasError = mcp.error > 0 || mcp.needsAuth > 0
|
|
114
116
|
const hasDegraded = mcp.degraded > 0 || mcp.ready < mcp.total - mcp.error - mcp.needsAuth
|
|
@@ -132,7 +134,7 @@ export const Footer = memo(function Footer({
|
|
|
132
134
|
let rightWidth = computeRightWidth(rightSegments)
|
|
133
135
|
const cwdWidth = displayWidth(cwd)
|
|
134
136
|
for (const key of DROP_ORDER) {
|
|
135
|
-
if (cwdWidth + rightWidth + 1 <= safeWidth) break
|
|
137
|
+
if (Math.min(cwdWidth, 12) + rightWidth + 1 <= safeWidth) break
|
|
136
138
|
const idx = rightSegments.findIndex(s => s.key === key)
|
|
137
139
|
if (idx >= 0) {
|
|
138
140
|
rightSegments.splice(idx, 1)
|
|
@@ -10,11 +10,11 @@ import { useTermWidth } from "./term-width.js"
|
|
|
10
10
|
import { truncateToWidth } from "./truncate.js"
|
|
11
11
|
import { c } from "./theme.js"
|
|
12
12
|
|
|
13
|
-
interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean; onCodex?: () => void }
|
|
13
|
+
interface Props { onSelect: (provider: ModelsDevConnection | null) => void; onCancel: () => void; metadataOnly?: boolean; onCodex?: () => void; onClaude?: () => void }
|
|
14
14
|
|
|
15
15
|
/** Public directory data supplies vendor names and endpoints; adapters only
|
|
16
16
|
* constrain which wire protocols the installed runtime actually supports. */
|
|
17
|
-
export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, onCodex }: Props) {
|
|
17
|
+
export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, onCodex, onClaude }: Props) {
|
|
18
18
|
const [providers, setProviders] = useState<ModelsDevConnection[]>([])
|
|
19
19
|
const [loading, setLoading] = useState(true)
|
|
20
20
|
const [error, setError] = useState("")
|
|
@@ -60,13 +60,15 @@ export function ProviderDirectory({ onSelect, onCancel, metadataOnly = false, on
|
|
|
60
60
|
maxRows={Math.max(3, Math.min(10, (process.stdout.rows ?? 24) - 15))}
|
|
61
61
|
hint="↑↓ select · enter configure · / search · r reload · esc back"
|
|
62
62
|
options={[...(!metadataOnly ? [{ id: "__custom", label: "Custom endpoint", meta: "configure manually" }] : []),
|
|
63
|
-
...(!metadataOnly && onCodex ? [{ id: "__codex", label: "OpenAI Codex (ChatGPT)", meta: "
|
|
63
|
+
...(!metadataOnly && onCodex ? [{ id: "__codex", label: "OpenAI Codex (ChatGPT)", meta: "official agent · sign in with Codex CLI" }] : []),
|
|
64
|
+
...(!metadataOnly && onClaude ? [{ id: "__claude", label: "Claude Code", meta: "official agent · sign in with claude auth login" }] : []),
|
|
64
65
|
...visible.map(provider => ({ id: `catalog:${provider.id}`, label: truncateToWidth(provider.name, labelWidth),
|
|
65
66
|
meta: truncateToWidth(provider.protocol ? `${provider.protocol}${provider.api ? " · endpoint provided" : " · enter endpoint"}` : "unsupported adapter", width - labelWidth - 2),
|
|
66
67
|
disabled: !metadataOnly && !provider.protocol }))]}
|
|
67
68
|
onCancel={onCancel} onSelect={id => {
|
|
68
69
|
if (id === "__custom") onSelect(null)
|
|
69
70
|
else if (id === "__codex") onCodex?.()
|
|
71
|
+
else if (id === "__claude") onClaude?.()
|
|
70
72
|
else {
|
|
71
73
|
const provider = providers.find(item => item.id === id.slice("catalog:".length))
|
|
72
74
|
if (provider && (metadataOnly || provider.protocol)) onSelect(provider)
|
|
@@ -103,7 +103,8 @@ export class AcpEventMapper {
|
|
|
103
103
|
this.plan = update.entries;
|
|
104
104
|
break;
|
|
105
105
|
case "usage_update":
|
|
106
|
-
this.contextUsage =
|
|
106
|
+
this.contextUsage = Number.isSafeInteger(update.used) && update.used >= 0 && Number.isSafeInteger(update.size) && update.size > 0
|
|
107
|
+
? { used: update.used, size: update.size } : undefined;
|
|
107
108
|
break;
|
|
108
109
|
default:
|
|
109
110
|
break;
|
|
@@ -179,8 +180,14 @@ export function contentText(block: ContentBlock | undefined | null): string {
|
|
|
179
180
|
/** Usage from a prompt response or `_meta`, in zap's shape. */
|
|
180
181
|
export function acpUsage(usage: Usage | null | undefined): TokenUsage | undefined {
|
|
181
182
|
if (!usage) return undefined;
|
|
183
|
+
// Some ACP agents include cached tokens in inputTokens. Codex ACP reports
|
|
184
|
+
// disjoint fresh/read/write counts, whose sum reconciles with totalTokens.
|
|
185
|
+
const cached = (usage.cachedReadTokens ?? 0) + (usage.cachedWriteTokens ?? 0);
|
|
186
|
+
const sum = usage.inputTokens + cached + usage.outputTokens;
|
|
187
|
+
const disjoint = usage.inputTokens < cached || usage.totalTokens === sum
|
|
188
|
+
|| usage.totalTokens === sum + (usage.thoughtTokens ?? 0);
|
|
182
189
|
return {
|
|
183
|
-
inputTokens: Math.max(0, usage.inputTokens -
|
|
190
|
+
inputTokens: disjoint ? usage.inputTokens : Math.max(0, usage.inputTokens - cached),
|
|
184
191
|
outputTokens: usage.outputTokens,
|
|
185
192
|
cacheReadInputTokens: usage.cachedReadTokens ?? undefined,
|
|
186
193
|
cacheCreationInputTokens: usage.cachedWriteTokens ?? undefined,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
2
|
-
import { dirname, isAbsolute, join, sep } from "node:path";
|
|
2
|
+
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
3
3
|
import { RequestError, type PermissionOption, type RequestPermissionRequest, type RequestPermissionResponse } from "@agentclientprotocol/sdk";
|
|
4
4
|
import type { ApprovalCallback, ApprovalContext, ApprovalResponse } from "../tools/executor.js";
|
|
5
5
|
import { resolveToolPathCanonical } from "../builtin-tools/filesystem.js";
|
|
@@ -45,7 +45,17 @@ export class AcpWorkspace {
|
|
|
45
45
|
}
|
|
46
46
|
|
|
47
47
|
contains(path: string): boolean { return within(path, this.root); }
|
|
48
|
-
isProtected(path: string): boolean {
|
|
48
|
+
isProtected(path: string): boolean {
|
|
49
|
+
// Reserve control-directory spellings even when a new path has no
|
|
50
|
+
// on-disk casing for realpath to recover on macOS or Windows.
|
|
51
|
+
const fold = process.platform === "win32" || process.platform === "darwin";
|
|
52
|
+
return this.protectedRoots.some(root => fold ? within(path.toLowerCase(), root.toLowerCase()) : within(path, root));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
protectsWrite(path: string): boolean {
|
|
56
|
+
const absolute = resolve(this.root, path);
|
|
57
|
+
return this.isProtected(absolute) || this.isProtected(this.resolve(absolute));
|
|
58
|
+
}
|
|
49
59
|
}
|
|
50
60
|
|
|
51
61
|
function within(path: string, root: string): boolean {
|
|
@@ -86,7 +96,11 @@ export function createAcpHostHandlers(policy: AcpHostPolicy): AcpHostHandlers {
|
|
|
86
96
|
// must be answered "cancelled", not rejected.
|
|
87
97
|
const live = signalFor(signal);
|
|
88
98
|
if (live.aborted) return { outcome: { outcome: "cancelled" } };
|
|
89
|
-
const
|
|
99
|
+
const diffs = tool.content?.flatMap(item => item.type === "diff" ? [item.path] : []) ?? [];
|
|
100
|
+
const mutation = tool.kind === "edit" || tool.kind === "delete" || tool.kind === "move";
|
|
101
|
+
const paths = mutation ? [...diffs, ...(tool.locations ?? []).map(location => location.path)] : diffs;
|
|
102
|
+
const response = paths.some(path => workspace.protectsWrite(path))
|
|
103
|
+
? false : await approve(permissionTarget(policy.agentId, request, workspace), live);
|
|
90
104
|
if (live.aborted) return { outcome: { outcome: "cancelled" } };
|
|
91
105
|
const allowed = response === true;
|
|
92
106
|
decisions.push({ title, kind: tool.kind ?? undefined, allowed });
|
|
@@ -116,7 +130,7 @@ export function createAcpHostHandlers(policy: AcpHostPolicy): AcpHostHandlers {
|
|
|
116
130
|
|
|
117
131
|
async writeTextFile(request, signal) {
|
|
118
132
|
const path = workspace.resolve(request.path);
|
|
119
|
-
if (workspace.isProtected(path)) {
|
|
133
|
+
if (workspace.isProtected(request.path) || workspace.isProtected(path)) {
|
|
120
134
|
throw RequestError.internalError(undefined, "denied by zap: .git and .zapcode are protected and cannot be written");
|
|
121
135
|
}
|
|
122
136
|
const target: ApprovalTarget = workspace.contains(path)
|