zapagent 1.14.25 → 1.14.27

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.
Files changed (56) hide show
  1. package/LICENSE +2 -3
  2. package/README.md +3 -3
  3. package/README.zh-CN.md +3 -3
  4. package/SECURITY.md +3 -2
  5. package/THIRD_PARTY_NOTICES.md +4 -8
  6. package/bundled-dependencies.json +204 -204
  7. package/package.json +1 -1
  8. package/src/App.tsx +19 -6
  9. package/src/agent/contextAttachments.ts +4 -2
  10. package/src/agent/remote-agent.ts +150 -0
  11. package/src/agent/remote-turn.ts +72 -0
  12. package/src/agent/wireRunHandlers.ts +5 -2
  13. package/src/agent-factory.ts +20 -11
  14. package/src/approval-facts.ts +20 -3
  15. package/src/commands/dispatcher.ts +47 -3
  16. package/src/commands.ts +4 -0
  17. package/src/config.ts +13 -2
  18. package/src/execution-environment.ts +20 -2
  19. package/src/goal-command.ts +6 -3
  20. package/src/goal-session.ts +1 -1
  21. package/src/goal-turn.ts +1 -1
  22. package/src/headless/goalPhase.ts +3 -3
  23. package/src/headless/runHeadless.ts +6 -6
  24. package/src/hooks/useAgentObjects.ts +8 -0
  25. package/src/hooks/useAgentRunner.ts +50 -1
  26. package/src/permission-policy.ts +5 -2
  27. package/src/permissions.ts +19 -12
  28. package/src/singletons.ts +25 -17
  29. package/src/tool-grants.ts +2 -2
  30. package/src/ui/Transcript.tsx +2 -1
  31. package/src/ui/dialog-approval.tsx +1 -1
  32. package/src/ui/dialog-rewind.tsx +1 -1
  33. package/src/ui/dialog-tool-grant.tsx +2 -2
  34. package/src/ui/footer.tsx +4 -1
  35. package/src/ui/group-logs.ts +1 -1
  36. package/src/ui/live-activity.tsx +1 -1
  37. package/src/ui/slash-palette.tsx +1 -0
  38. package/src/ui/transcript-format.ts +5 -1
  39. package/zapsdk/acp-client/connection.ts +228 -0
  40. package/zapsdk/acp-client/detect.ts +28 -0
  41. package/zapsdk/acp-client/event-mapper.ts +231 -0
  42. package/zapsdk/acp-client/host-handlers.ts +225 -0
  43. package/zapsdk/acp-client/index.ts +6 -0
  44. package/zapsdk/acp-client/run.ts +169 -0
  45. package/zapsdk/acp-client/types.ts +52 -0
  46. package/zapsdk/agent/loop.ts +51 -4
  47. package/zapsdk/agent/tool-execution-guards.ts +23 -37
  48. package/zapsdk/builtin-tools/acp-agent.ts +188 -0
  49. package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
  50. package/zapsdk/builtin-tools/index.ts +20 -16
  51. package/zapsdk/builtin-tools/plan-mode.ts +1 -1
  52. package/zapsdk/builtin-tools/subagent.ts +2 -2
  53. package/zapsdk/execution/process.ts +1 -1
  54. package/zapsdk/execution/sandbox.ts +6 -4
  55. package/zapsdk/execution/types.ts +3 -0
  56. package/zapsdk/goal/git-history-snapshot.ts +3 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.25",
3
+ "version": "1.14.27",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
package/src/App.tsx CHANGED
@@ -71,7 +71,9 @@ import { usePermissionApproval } from "./hooks/usePermissionApproval.js"
71
71
  import { usePlanMode } from "./hooks/usePlanMode.js"
72
72
  import { useAskUser } from "./hooks/useAskUser.js"
73
73
  import { usePalettes } from "./hooks/usePalettes.js"
74
+ import { VM_EXECUTION_DISABLED_NOTICE, vmExecutionRequestedButDisabled } from "./execution-environment.js"
74
75
  import { useAgentObjects } from "./hooks/useAgentObjects.js"
76
+ import { remoteAgents } from "./agent/remote-agent.js"
75
77
  import { useMCPSubsystem } from "./hooks/useMCPSubsystem.js"
76
78
  import { useSamplingHandler } from "./hooks/useSamplingHandler.js"
77
79
  import { setMCPManager } from "./singletons.js"
@@ -477,6 +479,9 @@ export function App() {
477
479
  catch (error) { setQueueError(`Queue storage unavailable: ${error instanceof Error ? error.message : String(error)}`) }
478
480
  }, [])
479
481
  useEffect(() => { if (queueError) addLog("error", queueError) }, [queueError, addLog])
482
+ // Tell the user once (per change) that a requested zapVM backend is ignored.
483
+ const vmIgnored = vmExecutionRequestedButDisabled(config.executionBackend)
484
+ useEffect(() => { if (vmIgnored) addLog("system", VM_EXECUTION_DISABLED_NOTICE) }, [vmIgnored, addLog])
480
485
  const systemInboxSize = useSyncExternalStore(subscribeToSystemInbox, getSystemInboxLength, getSystemInboxLength)
481
486
 
482
487
  // ── Plan-mode state machine ──
@@ -747,7 +752,8 @@ export function App() {
747
752
  )
748
753
 
749
754
  const precheckProvider = useCallback(
750
- () => isProviderReady(configRef, addLog),
755
+ // An external ACP agent brings its own model and credentials.
756
+ () => !!configRef.current.activeAgent || isProviderReady(configRef, addLog),
751
757
  [addLog],
752
758
  )
753
759
 
@@ -871,6 +877,8 @@ export function App() {
871
877
  process.stdout.write("\x1b[H\x1b[2J\x1b[3J")
872
878
  }
873
879
  conversation.clear()
880
+ // The external agent's own context goes with the conversation.
881
+ void remoteAgents.reset()
874
882
  restoreMemoryQueryHistoryFromLogs([])
875
883
  setLogs([])
876
884
  todosRef.current = []
@@ -922,7 +930,7 @@ export function App() {
922
930
 
923
931
  // ── Render ──
924
932
  const providerDisplayName = getProviderDisplayName(config)
925
- const hasKey = configHasApiKey(config)
933
+ const hasKey = !!config.activeAgent || configHasApiKey(config)
926
934
  const welcomeHeader = useMemo(() => <Welcome hasApiKey={hasKey} />, [hasKey])
927
935
  const mcpFooterSummary = useMemo(
928
936
  () => summariseMCPStatuses(mcp.snapshots),
@@ -971,6 +979,8 @@ export function App() {
971
979
 
972
980
  const restoreSession = (loaded: DialogSessionRestore) => {
973
981
  const { logs: restored, messages, loadedSessionId, metadata } = loaded
982
+ // A restored session never continues the current agent's context.
983
+ void remoteAgents.reset()
974
984
  appLogger.info("session_restore_begin", {
975
985
  sessionId: loadedSessionId,
976
986
  restoredLogs: restored.length,
@@ -1147,7 +1157,7 @@ export function App() {
1147
1157
  {!inModal && !pendingApproval && !pendingPlan && !pendingQuestions && (
1148
1158
  <Prompt
1149
1159
  config={config}
1150
- providerLabel={`${providerDisplayName}/${config.active.model}`}
1160
+ providerLabel={config.activeAgent ? `ACP/${config.activeAgent}` : `${providerDisplayName}/${config.active.model}`}
1151
1161
  hasActiveKey={hasKey}
1152
1162
  inputValue={inputValue}
1153
1163
  onInput={paste.handleInput}
@@ -1250,6 +1260,8 @@ export function App() {
1250
1260
  addToast(`Restored ${result.succeeded.length} tracked files${result.skipped?.length ? `; skipped ${result.skipped.length}` : ""}`);
1251
1261
  closeDialog(); return;
1252
1262
  }
1263
+ // The agent cannot rewind its own context; start it fresh.
1264
+ void remoteAgents.reset();
1253
1265
  const draft = rewindDraft(snap, logs);
1254
1266
  setInputValue(draft.text);
1255
1267
  setPendingImages([]);
@@ -1327,13 +1339,14 @@ export function App() {
1327
1339
  <Footer
1328
1340
  outputThroughput={outputThroughput}
1329
1341
  cwd={cwdShort}
1330
- provider={providerDisplayName}
1331
- model={config.active.model}
1332
- effort={config.active.providerId ? getEffort(config, config.active.providerId) : undefined}
1342
+ provider={config.activeAgent ? "ACP" : providerDisplayName}
1343
+ model={config.activeAgent ?? config.active.model}
1344
+ effort={!config.activeAgent && config.active.providerId ? getEffort(config, config.active.providerId) : undefined}
1333
1345
  isRunning={isRunning}
1334
1346
  step={step}
1335
1347
  maxSteps={config.maxSteps}
1336
1348
  contextBudget={contextBudget}
1349
+ hideContext={!!config.activeAgent}
1337
1350
  hasApiKey={hasKey}
1338
1351
  showWelcome={logs.length === 0 && !isRunning && !isStreaming}
1339
1352
  shellMode={isShellMode()}
@@ -1371,11 +1371,13 @@ function buildDiagnosticsFromSegments(segments: ContextSegment[], fullText: stri
1371
1371
 
1372
1372
  /** Review observed work against the original request before natural finish.
1373
1373
  * LoopAgent bounds this to one reminder and permits an honest incomplete
1374
- * response. Todo completion does not suppress review of settled tool work. */
1374
+ * response. The review costs a model call, so it runs only when there is
1375
+ * something to reconcile: an unfinished todo or a failed tool call, even if
1376
+ * the todo list was cleared afterwards. */
1375
1377
  export function makeTurnEndGuard(getTodos: () => Todo[]): (result?: Pick<LoopAgentResult, "toolResults">) => string | null {
1376
1378
  return (result) => {
1377
1379
  const active = getTodos().find((t) => t.status === "in_progress")
1378
- if (!active && !result?.toolResults.length) return null
1380
+ if (!active && !result?.toolResults.some((r) => !r.success)) return null
1379
1381
  return (
1380
1382
  "<system-reminder>\n" +
1381
1383
  (active ? `Todo "${escapeContextText(active.content)}" remains in_progress.\n` : "") +
@@ -0,0 +1,150 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import type { ContentBlock } from "@agentclientprotocol/sdk"
3
+ import { AcpAgentSession, type AcpTurnResult } from "../../zapsdk/acp-client/run.js"
4
+ import { stdioTransport, type AcpTransport } from "../../zapsdk/acp-client/connection.js"
5
+ import { createAcpHostHandlers, type AcpHostHandlers } from "../../zapsdk/acp-client/host-handlers.js"
6
+ import type { AcpAgentSpec } from "../../zapsdk/acp-client/types.js"
7
+ import type { AgentEvent } from "../../zapsdk/agent/events.js"
8
+ import type { ImageContent } from "../../zapsdk/core/types.js"
9
+ import { createLocalProcessBroker } from "../../zapsdk/execution/process.js"
10
+ import type { ApprovalCallback, ApprovalContext } from "../../zapsdk/tools/executor.js"
11
+ import { VERSION } from "../version.js"
12
+
13
+ /** Host hooks the live session reads at request time, so approval and
14
+ * checkpoint wiring can change (config rebuilds) without a reconnect. */
15
+ export interface RemoteAgentHost {
16
+ approve?: ApprovalCallback
17
+ trackEdit?: (paths: string[]) => Promise<unknown>
18
+ /** Set when host policy forbids running agents on the host (they run
19
+ * outside zap's OS sandbox): the reason shown instead of starting one. */
20
+ blocked?: string
21
+ }
22
+
23
+ interface LiveSession {
24
+ key: string
25
+ spec: AcpAgentSpec
26
+ session: AcpAgentSession
27
+ handlers: AcpHostHandlers
28
+ }
29
+
30
+ /** One external ACP agent driving the TUI conversation ("session mode").
31
+ * The agent process stays up across turns so the agent keeps its own
32
+ * context. It is replaced on agent/cwd change and closed when the
33
+ * conversation is reset, after a failed turn, and at exit. */
34
+ export class RemoteAgentManager {
35
+ private live?: LiveSession
36
+ private starting?: { key: string; promise: Promise<LiveSession> }
37
+ /** Bumped by reset(); a start that outlives its generation is discarded. */
38
+ private generation = 0
39
+ private readonly transports = new Set<AcpTransport>()
40
+ /** Signal of the turn in flight; approval prompts close when it aborts. */
41
+ private turnSignal?: AbortSignal
42
+ readonly host: RemoteAgentHost = {}
43
+
44
+ constructor(private readonly transportFor: (spec: AcpAgentSpec, cwd: string) => AcpTransport = spawnTransport) {}
45
+
46
+ get current(): { spec: AcpAgentSpec; session: AcpAgentSession } | undefined {
47
+ return this.live ? { spec: this.live.spec, session: this.live.session } : undefined
48
+ }
49
+
50
+ async prompt(spec: AcpAgentSpec, cwd: string, text: string, images: ImageContent[] | undefined, options: {
51
+ signal: AbortSignal
52
+ onEvent: (event: AgentEvent) => void
53
+ onStarted?: (session: AcpAgentSession) => void
54
+ /** Called once the agent is ready and the prompt is about to be sent. */
55
+ onAccepted?: () => void
56
+ }): Promise<AcpTurnResult & { session: AcpAgentSession }> {
57
+ const live = await this.ensure(spec, cwd, options.signal, options.onStarted)
58
+ const content: ContentBlock[] = [{ type: "text", text }]
59
+ if (images?.length) {
60
+ if (!live.session.supportsImages) throw new Error(`${spec.id} does not accept images`)
61
+ for (const image of images) {
62
+ const data = image.base64 ?? (await readFile(image.filePath)).toString("base64")
63
+ content.push({ type: "image", data, mimeType: image.mediaType })
64
+ }
65
+ }
66
+ options.onAccepted?.()
67
+ this.turnSignal = options.signal
68
+ try {
69
+ const result = await live.session.prompt(content, { signal: options.signal, onEvent: options.onEvent })
70
+ return { ...result, session: live.session }
71
+ } catch (error) {
72
+ // A cooperative cancel resolves with stopReason "cancelled"; a throw
73
+ // means the agent died, failed, or ignored cancellation and may still
74
+ // be working. Never reuse it for the next turn.
75
+ if (this.live === live) await this.reset()
76
+ throw error
77
+ } finally {
78
+ this.turnSignal = undefined
79
+ }
80
+ }
81
+
82
+ /** Close the agent (and discard one still starting). Context is lost. */
83
+ async reset(): Promise<void> {
84
+ this.generation += 1
85
+ const live = this.live
86
+ this.live = undefined
87
+ this.starting = undefined
88
+ await live?.session.close().catch(() => {})
89
+ }
90
+
91
+ /** Last resort at process exit: no event loop is left for a graceful close. */
92
+ killAll(): void {
93
+ for (const transport of this.transports) transport.kill?.()
94
+ }
95
+
96
+ private async ensure(spec: AcpAgentSpec, cwd: string, signal: AbortSignal, onStarted?: (session: AcpAgentSession) => void): Promise<LiveSession> {
97
+ 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])
99
+ // Let a start for another agent settle (and be replaced) first.
100
+ while (this.starting && this.starting.key !== key) await this.starting.promise.catch(() => {})
101
+ if (this.live?.key === key) return this.live
102
+ if (this.starting) return this.starting.promise
103
+ if (this.live) await this.reset()
104
+ const generation = this.generation
105
+ const promise = (async () => {
106
+ const handlers = createAcpHostHandlers({
107
+ agentId: spec.id, cwd,
108
+ approve: Object.assign(
109
+ (name: string, args: Record<string, unknown>, s?: AbortSignal, context?: Readonly<ApprovalContext>) => this.host.approve
110
+ ? this.host.approve(name, args, s, context)
111
+ : Promise.resolve({ approved: false as const, source: "policy" as const, reason: "no approval handler" }),
112
+ { precheck: (name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>) =>
113
+ this.host.approve?.precheck?.(name, args, context) },
114
+ ),
115
+ trackEdit: paths => this.host.trackEdit?.(paths) ?? Promise.resolve(),
116
+ signal: () => this.turnSignal,
117
+ })
118
+ const transport = this.transportFor(spec, cwd)
119
+ this.transports.add(transport)
120
+ void transport.exited.then(() => this.transports.delete(transport))
121
+ const session = await AcpAgentSession.start({ spec, cwd, transport, handlers, signal, clientVersion: VERSION })
122
+ if (generation !== this.generation) {
123
+ // reset() ran while the agent was starting (/agent, /new, abort).
124
+ await session.close().catch(() => {})
125
+ throw new Error(`${spec.id} start was cancelled`)
126
+ }
127
+ const live = { key, spec, session, handlers }
128
+ this.live = live
129
+ onStarted?.(session)
130
+ return live
131
+ })()
132
+ const starting = { key, promise }
133
+ this.starting = starting
134
+ try { return await promise }
135
+ finally { if (this.starting === starting) this.starting = undefined }
136
+ }
137
+ }
138
+
139
+ /** Agents inherit zap's environment, like any host process zap starts. */
140
+ function spawnTransport(spec: AcpAgentSpec, cwd: string): AcpTransport {
141
+ return stdioTransport(createLocalProcessBroker().spawnCommand(spec.command, spec.args ?? [], {
142
+ cwd, hostHome: true, environment: spec.env, stdin: "pipe",
143
+ }))
144
+ }
145
+
146
+ export const remoteAgents = new RemoteAgentManager()
147
+
148
+ // Agent processes are detached process groups; never leave one behind.
149
+ // "exit" runs synchronously, so a graceful close cannot complete here.
150
+ process.once("exit", () => { remoteAgents.killAll() })
@@ -0,0 +1,72 @@
1
+ import type { PlanEntry } from "@agentclientprotocol/sdk"
2
+ import { AgentEventEmitter } from "../../zapsdk/agent/events.js"
3
+ import type { LoopAgentResult } from "../../zapsdk/agent/loop.js"
4
+ import type { ImageContent } from "../../zapsdk/core/types.js"
5
+ import type { ConversationManager } from "../../zapsdk/memory/conversation.js"
6
+ import type { AcpAgentSpec } from "../../zapsdk/acp-client/types.js"
7
+ import type { StreamingPreview } from "./streamingPreview.js"
8
+ import { createRunHandlers, type RunHandlersDeps } from "./wireRunHandlers.js"
9
+ import { remoteAgents } from "./remote-agent.js"
10
+
11
+ export interface RemoteTurnDeps extends Omit<RunHandlersDeps, "preview" | "setContextTokens" | "setContextPending" | "currentConfig"> {
12
+ currentConfig: RunHandlersDeps["currentConfig"]
13
+ spec: AcpAgentSpec
14
+ cwd: string
15
+ conversation: ConversationManager
16
+ createPreview: () => StreamingPreview
17
+ saveLastOutput: (text: string) => void
18
+ /** Tells the host queue the agent took the message. */
19
+ onInputAccepted?: () => void
20
+ /** Opens/closes the checkpoint turn, as zap's runtime does around a run,
21
+ * so /rewind attributes the agent's fs writes to this turn. */
22
+ checkpointTurn?: { begin: () => Promise<unknown>; end: () => Promise<unknown> }
23
+ }
24
+
25
+ /** One user turn handled by an external ACP agent instead of zap's loop.
26
+ * Rendering reuses the regular run handlers, so the transcript looks the
27
+ * same; zap's conversation records the exchange so switching back to zap
28
+ * keeps the context. Throws after reporting when the turn fails. */
29
+ export async function runRemoteTurn(deps: RemoteTurnDeps, task: string, images?: ImageContent[]): Promise<LoopAgentResult> {
30
+ const preview = deps.createPreview()
31
+ const handlers = createRunHandlers({ ...deps, preview, setContextTokens() {}, setContextPending() {} })
32
+ const emitter = new AgentEventEmitter()
33
+ handlers.wire(emitter)
34
+ const { spec, controller } = deps
35
+ await deps.checkpointTurn?.begin().catch(() => {})
36
+ try {
37
+ const turn = await remoteAgents.prompt(spec, deps.cwd, task, images, {
38
+ signal: controller.signal,
39
+ onEvent: event => emitter.emit(event),
40
+ onAccepted: deps.onInputAccepted,
41
+ onStarted: session => {
42
+ deps.addLog("system", `Connected to ${session.agentName} (${spec.id}) over ACP${session.warnings.length ? ` · ${session.warnings.join("; ")}` : ""}`)
43
+ },
44
+ })
45
+ deps.conversation.add({ role: "user", content: task })
46
+ deps.conversation.add({ role: "assistant", content: `[${spec.id} via ACP] ${turn.report || "(no message)"}` })
47
+ if (turn.plan.length) deps.addLog("system", formatPlan(spec.id, turn.plan))
48
+ if (turn.stopReason !== "end_turn" && turn.stopReason !== "cancelled") deps.addLog("system", `${spec.id} stopped: ${turn.stopReason}`)
49
+ if (turn.report) deps.saveLastOutput(turn.report)
50
+ const usage = turn.usage ?? { inputTokens: 0, outputTokens: 0, providerUsageReported: false }
51
+ if (!controller.signal.aborted) emitter.emit({ type: "run_ended", steps: turn.toolCalls, stopped: turn.stopReason, usage })
52
+ // The host queue reads this like a LoopAgent result: a non-end_turn stop
53
+ // pauses follow-ups for review.
54
+ const stopped = turn.stopReason === "max_tokens" ? "max_tokens" as const
55
+ : turn.stopReason === "max_turn_requests" ? "max_steps" as const : undefined
56
+ return { text: turn.report, steps: turn.toolCalls, toolResults: [], totalUsage: usage, stopped }
57
+ } catch (error) {
58
+ const message = error instanceof Error ? error.message : String(error)
59
+ // Aborts are silent here; the runner adds the "(interrupted)" marker.
60
+ if (!controller.signal.aborted) emitter.emit({ type: "error", step: 0, error: `${spec.id}: ${message}` })
61
+ throw error
62
+ } finally {
63
+ await deps.checkpointTurn?.end().catch(() => {})
64
+ preview.drainOnAbort()
65
+ handlers.settlePending(controller.signal.aborted ? "aborted" : `${spec.id} ended the turn`)
66
+ }
67
+ }
68
+
69
+ export function formatPlan(agentId: string, plan: PlanEntry[]): string {
70
+ const mark = { completed: "✓", in_progress: "▸", pending: "○" } as const
71
+ return [`${agentId} plan:`, ...plan.map(entry => ` ${mark[entry.status] ?? "○"} ${entry.content}`)].join("\n")
72
+ }
@@ -184,6 +184,9 @@ export interface RunHandlers {
184
184
  settlePending(reason: string): void
185
185
  }
186
186
 
187
+ /** Tools whose child events fold under their row via meta.subagentId. */
188
+ const SUBAGENT_TOOLS = new Set(["agent", "delegate_agent", "acp_agent"])
189
+
187
190
  export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
188
191
  const cacheScope = makePromptCacheScope(
189
192
  deps.currentConfig.active.providerId,
@@ -231,7 +234,7 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
231
234
  const toolCallId = event.run.toolCallId
232
235
  if (!toolCallId) return
233
236
  const pending = pendingToolLogById.get(toolCallId)
234
- if (!pending || (pending.name !== "agent" && pending.name !== "delegate_agent")) return
237
+ if (!pending || !SUBAGENT_TOOLS.has(pending.name)) return
235
238
  claimedAgentToolCallIds.add(toolCallId)
236
239
  const updatedTool: ToolCallInfo = {
237
240
  id: toolCallId,
@@ -256,7 +259,7 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
256
259
  if (!task) return
257
260
  for (const [tuId, pending] of pendingToolLogById) {
258
261
  if (claimedAgentToolCallIds.has(tuId)) continue
259
- if (pending.name !== "agent" && pending.name !== "delegate_agent") continue
262
+ if (!SUBAGENT_TOOLS.has(pending.name)) continue
260
263
  if (getStringArg(pending.arguments, "task") !== task) continue
261
264
  // Claim-first so a second sub_agent_started with the same task
262
265
  // advances to the next pending instead of re-stamping this one.
@@ -1,3 +1,4 @@
1
+ import { VERSION } from "./version.js"
1
2
  import { getAppDataDir } from "../zapsdk/utils/platform.js"
2
3
  import { generateCodexImage } from "../zapsdk/core/providers/codex-image-generation.js"
3
4
  import { modelCanonicalIds } from "./provider-metadata.js"
@@ -29,7 +30,7 @@ import type { CheckpointManager } from "../zapsdk/checkpoint/index.js"
29
30
  import { loadAllSkills } from "../zapsdk/skills/loader.js"
30
31
  import type { SkillDefinition } from "../zapsdk/skills/types.js"
31
32
  import type { AgentEventHandler } from "../zapsdk/agent/events.js"
32
- import { autoMemory, cronHandle, monitorHandle, taskStore, mdStore, globalMdStore, globalMemoryDir, delegateProviders, delegateEventBridge } from "./singletons.js"
33
+ import { autoMemory, taskStore, mdStore, globalMdStore, globalMemoryDir, delegateProviders, delegateEventBridge, acpAgents } from "./singletons.js"
33
34
  import { memorySaveTool } from "../zapsdk/builtin-tools/memory.js"
34
35
  import type { AgentObjects } from "./agent/types.js"
35
36
  import type { LLMProvider } from "../zapsdk/core/llm.js"
@@ -38,8 +39,8 @@ import { createExecutionEnvironment, resolveExecutionBackend, type ExecutionEnvi
38
39
 
39
40
  const CWD_SENSITIVE_TOOLS = new Set([
40
41
  "read_file", "write_file", "edit_file", "multi_edit",
41
- "delete_file", "move_file", "list_tree", "bash",
42
- "search_files", "glob_files", "read_document", "browser_screenshot", "delegate_agent", "generate_image",
42
+ "delete_file", "list_tree", "bash",
43
+ "search_files", "glob_files", "read_document", "browser_screenshot", "delegate_agent", "acp_agent", "generate_image",
43
44
  ])
44
45
 
45
46
  function safeHost(url: string): string {
@@ -158,13 +159,23 @@ export function buildAgentObjects(
158
159
  { maxRetries: 2, initialDelayMs: 1000 }
159
160
  )
160
161
 
162
+ // External ACP agents: their permission and fs requests reuse zap's
163
+ // approval gate and checkpoint tracker, like zap's own tools.
164
+ const acpAgentOptions = acpAgents.length > 0
165
+ ? {
166
+ agents: acpAgents,
167
+ onEvent: delegateOnEvent ?? ((ev: import("../zapsdk/agent/events.js").AgentEvent) => delegateEventBridge.handler?.(ev)),
168
+ approve: onApproval,
169
+ trackEdit: checkpoint?.createEditTracker(),
170
+ clientVersion: VERSION,
171
+ }
172
+ : undefined
161
173
  const registry = createBuiltinRegistry({
162
174
  readFile: { allowedPaths, useExecutionGrants: true },
163
175
  writeFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
164
176
  editFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
165
177
  multiEdit: { allowedPaths, protectedPaths, useExecutionGrants: true },
166
178
  deleteFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
167
- moveFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
168
179
  listTree: { allowedPaths, useExecutionGrants: true },
169
180
  searchFiles: { allowedPaths, useExecutionGrants: true },
170
181
  globFiles: { allowedPaths, useExecutionGrants: true },
@@ -204,12 +215,6 @@ export function buildAgentObjects(
204
215
  }
205
216
  },
206
217
  } : undefined,
207
- // Cron + monitor: session-scoped singleton handles owned by the CLI
208
- // (see singletons.ts). Subagents strip these out of their cloned
209
- // registry — jobs created in a subagent would otherwise outlive it
210
- // and fire with main-agent authority.
211
- cronHandle,
212
- monitorHandle,
213
218
  taskTools: { store: taskStore },
214
219
  // Delegate (claude / codex CLI hand-off): only registered when the PATH
215
220
  // probe in singletons.ts found at least one provider. The onEvent forwards
@@ -222,6 +227,9 @@ export function buildAgentObjects(
222
227
  onEvent: delegateOnEvent ?? ((ev) => delegateEventBridge.handler?.(ev)),
223
228
  }
224
229
  : undefined,
230
+ // External ACP agents: their permission and fs requests reuse zap's
231
+ // approval gate and checkpoint tracker, like zap's own tools.
232
+ acpAgent: acpAgentOptions,
225
233
  exclude: [],
226
234
  })
227
235
  // The model can save a durable fact during normal work. Inventory review
@@ -243,7 +251,6 @@ export function buildAgentObjects(
243
251
  editFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
244
252
  multiEdit: { allowedPaths, protectedPaths, useExecutionGrants: true },
245
253
  deleteFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
246
- moveFile: { allowedPaths, protectedPaths, useExecutionGrants: true },
247
254
  listTree: { allowedPaths, useExecutionGrants: true },
248
255
  searchFiles: { allowedPaths, useExecutionGrants: true },
249
256
  globFiles: { allowedPaths, useExecutionGrants: true },
@@ -261,6 +268,8 @@ export function buildAgentObjects(
261
268
  // is enforced separately by the child's execution grant.
262
269
  },
263
270
  webSearch: config.serperKey ? { searchFn: createSerperSearch(config.serperKey) } : undefined,
271
+ // An isolated workspace's agent must run there, not in the root cwd.
272
+ acpAgent: acpAgentOptions,
264
273
  exclude: [],
265
274
  })
266
275
  for (const definition of cwdBuiltins.definitions()) {
@@ -4,15 +4,32 @@ import { shellExecutionCommands, requiresShellReview } from "../zapsdk/utils/she
4
4
 
5
5
  // Compatibility for pre-effects adapters and direct onApproval embedders.
6
6
  // New tools declare effects/resolveShellCommands; do not extend these lists.
7
- const legacyWrites = new Set(["write_file", "create_file", "edit_file", "multi_edit", "delete_file", "move_file", "bash", "execute_command", "memory_save", "memory_review", "memory_merge", "cron_create", "cron_delete", "monitor", "service_start", "service_stop", "task_stop", "http_request", "delegate_agent"])
7
+ const legacyWrites = new Set(["write_file", "create_file", "edit_file", "multi_edit", "delete_file", "move_file", "bash", "execute_command", "memory_save", "memory_review", "memory_merge", "cron_create", "cron_delete", "monitor", "service_start", "service_stop", "task_stop", "http_request", "delegate_agent", "acp_agent"])
8
8
  const legacyEdits = new Set(["write_file", "create_file", "edit_file", "multi_edit"])
9
9
  const legacyShells = new Set(["bash", "execute_command", "service_start", "monitor"])
10
10
 
11
+ /** Delegation tools whose own approval is scoped to agent@cwd. Running that
12
+ * agent's host process is part of that consent, not a general sandbox
13
+ * escape: it must neither use nor grant the bash outside-sandbox authorization. */
14
+ const SCOPED_AGENT_TOOLS = new Set(["delegate_agent", "acp_agent"])
15
+
16
+ /** Names zap gives an external ACP agent's own permission requests
17
+ * (`acp_<agent>_<kind>`). Only these kinds are read-only. */
18
+ const ACP_REQUEST = /^acp_(?!agent$).+_(\w+)$/
19
+ const ACP_READ_KINDS = new Set(["read", "search", "think"])
20
+
21
+ /** An external ACP agent's own, unmapped permission request. Its free-form
22
+ * input has no reusable scope, so it is approved one call at a time. */
23
+ export function isAcpAgentRequest(name: string): boolean { return ACP_REQUEST.test(name) }
24
+
11
25
  export function approvalFacts(name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): Readonly<ToolApprovalFacts> {
12
26
  const facts = context?.authorization
13
- if (facts && !(facts.legacy && legacyWrites.has(name))) return facts
27
+ if (facts && !(facts.legacy && legacyWrites.has(name))) {
28
+ return SCOPED_AGENT_TOOLS.has(name) && facts.sandboxEscape ? { ...facts, sandboxEscape: false } : facts
29
+ }
30
+ const acpKind = ACP_REQUEST.exec(name)?.[1]
14
31
  return {
15
- readOnly: !legacyWrites.has(name) && !name.startsWith("mcp__"),
32
+ readOnly: acpKind ? ACP_READ_KINDS.has(acpKind) : !legacyWrites.has(name) && !name.startsWith("mcp__"),
16
33
  editOnly: legacyEdits.has(name),
17
34
  sandboxEscape: name === "bash" && args.dangerouslyDisableSandbox === true,
18
35
  workspaceShell: name === "bash",
@@ -15,7 +15,8 @@ import {
15
15
  import { TokenCounter } from "../../zapsdk/context/token-counter.js"
16
16
  import { resolveActiveContextLimits } from "../context-budget.js"
17
17
  import type { CheckpointManager } from "../../zapsdk/checkpoint/index.js"
18
- import { conversation, autoMemory } from "../singletons.js"
18
+ import { acpAgents, conversation, autoMemory } from "../singletons.js"
19
+ import { remoteAgents } from "../agent/remote-agent.js"
19
20
  import { dispatchMCPCommand } from "./mcp.js"
20
21
  import { executeGoalCommand } from "../goal-session.js"
21
22
  import {
@@ -324,6 +325,12 @@ export function dispatchSlashCommand(
324
325
  const displayCommand = meta.displayText ? parseCommand(meta.displayText) : null
325
326
 
326
327
  const dispatchAgentTurn = (...args: Parameters<DispatchSlashCommandDeps["dispatchUserTurn"]>): boolean | Promise<boolean> => {
328
+ // /review, /commit, /init and skills carry zap prompts written for zap's
329
+ // own tools; an external agent would silently ignore them.
330
+ if (deps.configRef.current.activeAgent) {
331
+ deps.addLog("error", `${displayCommand?.type ?? cmd.type} runs on zap's own model, not ${deps.configRef.current.activeAgent}. /agent zap switches back.`)
332
+ return true
333
+ }
327
334
  meta.onInputRequired?.()
328
335
  if (!precheckProvider(deps)) return true
329
336
  return deps.dispatchUserTurn(...args).then(result => {
@@ -346,8 +353,9 @@ export function dispatchSlashCommand(
346
353
 
347
354
  switch (cmd.type) {
348
355
  case "exit":
349
- deps.exit()
350
- return true
356
+ // Close an external agent gracefully (bounded) before leaving.
357
+ return Promise.race([remoteAgents.reset(), new Promise(resolve => setTimeout(resolve, 3_500))])
358
+ .then(() => { deps.exit(); return true })
351
359
 
352
360
  case "clear": {
353
361
  // Wipe everything to a fresh-boot state. Sequence matters: write the
@@ -357,6 +365,7 @@ export function dispatchSlashCommand(
357
365
  // top-left those erases just no-op against blank rows.
358
366
  wipeTerminalScrollback()
359
367
  resetConversationState()
368
+ void remoteAgents.reset()
360
369
  deps.bumpTranscript()
361
370
  return true
362
371
  }
@@ -377,6 +386,8 @@ export function dispatchSlashCommand(
377
386
  }
378
387
  wipeTerminalScrollback()
379
388
  resetConversationState()
389
+ // The external agent's own context belongs to the old session.
390
+ void remoteAgents.reset()
380
391
  deps.checkpointRef.current.setSessionId(getCurrentSessionId())
381
392
  deps.bumpTranscript()
382
393
  return true
@@ -418,6 +429,39 @@ export function dispatchSlashCommand(
418
429
  return true
419
430
  }
420
431
 
432
+ case "set_agent": {
433
+ const value = cmd.value ?? ""
434
+ const current = deps.configRef.current.activeAgent
435
+ if (!value) {
436
+ const lines = acpAgents.length
437
+ ? acpAgents.map(agent => ` ${agent.id === current ? "›" : " "} ${agent.id.padEnd(10)} ${agent.name ?? ""}${agent.selfGoverned ? " · edits files itself (no zap checkpoints)" : ""}`)
438
+ : [" (no ACP agents found on PATH or in acpAgents)"]
439
+ deps.addLog("system", [`Conversation agent: ${current ?? "zap"}`, ` ${current ? " " : "›"} zap zap's own model`, ...lines,
440
+ "Switch with /agent <id>; /agent zap switches back."].join("\n"))
441
+ return true
442
+ }
443
+ if (value === "zap" || value === "off") {
444
+ void remoteAgents.reset()
445
+ if (current) {
446
+ deps.updateConfig({ ...deps.configRef.current, activeAgent: undefined })
447
+ deps.addToast("agent → zap")
448
+ }
449
+ return true
450
+ }
451
+ const spec = acpAgents.find(agent => agent.id === value)
452
+ if (!spec) {
453
+ deps.addLog("error", `Unknown ACP agent: ${value}. Available: ${["zap", ...acpAgents.map(agent => agent.id)].join(", ")}`)
454
+ return true
455
+ }
456
+ if (value !== current) {
457
+ void remoteAgents.reset()
458
+ deps.updateConfig({ ...deps.configRef.current, activeAgent: value })
459
+ deps.addToast(`agent → ${value}`)
460
+ deps.addLog("system", `Messages now go to ${spec.name ?? spec.id} over ACP. Its file reads/writes and permission requests use zap's approvals${spec.selfGoverned ? "; it also edits files itself, which zap checkpoints do not cover" : ""}. /agent zap switches back.`)
461
+ }
462
+ return true
463
+ }
464
+
421
465
  case "set_permission_mode": {
422
466
  const v = parsePermissionMode(cmd.value ?? "default")
423
467
  if (!v) {
package/src/commands.ts CHANGED
@@ -38,6 +38,7 @@ export interface CommandResult {
38
38
  | "set_effort"
39
39
  | "open_mem"
40
40
  | "show_status"
41
+ | "set_agent"
41
42
  text?: string
42
43
  value?: string
43
44
  skill?: string
@@ -202,6 +203,9 @@ export function parseCommand(input: string): CommandResult | null {
202
203
  case "permissions":
203
204
  return { type: "show_permissions", value: rest.trim() }
204
205
 
206
+ case "agent":
207
+ return { type: "set_agent", value: rest.trim() }
208
+
205
209
  case "mode":
206
210
  if (!rest.trim()) return { type: "open_mode_picker" }
207
211
  return { type: "set_permission_mode", value: rest.trim() }
package/src/config.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { AcpAgentSpec } from "../zapsdk/acp-client/types.js"
1
2
  import { modelReasoningFor, normalizeReasoningMap, resolveModelEffort, effortName, type ModelReasoning } from "../zapsdk/core/reasoning-effort.js"
2
3
  import { deriveCompactionThresholds } from "../zapsdk/context/compact-budget.js"
3
4
  import { canonicalModelId } from "../zapsdk/core/model-identity.js"
@@ -222,10 +223,18 @@ export interface AppConfig {
222
223
  promptProfile?: PromptProfile
223
224
  compaction: CompactionConfig
224
225
  mcpServers: MCPServerConfig[]
226
+ /** External ACP agents for the `acp_agent` tool. Known agents on PATH
227
+ * (agy, codex-acp) are added automatically;
228
+ * entries here override them by id. */
229
+ acpAgents?: AcpAgentSpec[]
230
+ /** Session-scoped: id of the external ACP agent driving the conversation
231
+ * (`/agent <id>`). Undefined means zap's own model. Never persisted. */
232
+ activeAgent?: string
225
233
  permissionMode: PermissionMode
226
234
  followUpMode?: "queue" | "steer"
227
235
  /** Where project shell commands run. "local" (default) uses the host OS
228
- * sandbox; "vm" routes them into zapVM. ZAPCODE_EXECUTION overrides. */
236
+ * sandbox. "vm" (zapVM) is currently disabled and treated as "local";
237
+ * see VM_EXECUTION_ENABLED in execution-environment.ts. */
229
238
  executionBackend?: "local" | "vm"
230
239
  /** Let the model retry a sandbox-blocked bash command outside the OS
231
240
  * sandbox, after explicit approval. Default true; false removes the option. */
@@ -598,6 +607,7 @@ export function loadAppConfig(configPath: string): AppConfig {
598
607
  active: parsed.active ?? defaults.active,
599
608
  mcpServers: Array.isArray(parsed.mcpServers) ? parsed.mcpServers : [],
600
609
  permissionMode: "default", // session-scoped
610
+ activeAgent: undefined, // session-scoped
601
611
  }
602
612
  if (process.env.ZAP_DISABLE_FILE_CHECKPOINTING === "1") {
603
613
  merged.fileCheckpointingEnabled = false
@@ -656,7 +666,8 @@ function mergeProjectMCPJson(base: AppConfig): AppConfig {
656
666
  }
657
667
 
658
668
  export function saveAppConfig(configPath: string, config: AppConfig): void {
659
- writeFileAtomic(configPath, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 })
669
+ const { activeAgent: _sessionOnly, ...persisted } = config
670
+ writeFileAtomic(configPath, JSON.stringify(persisted, null, 2) + "\n", { mode: 0o600 })
660
671
  }
661
672
 
662
673
  // ── Vision capability detection ─────────────────────────────────────────────