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
@@ -30,13 +30,31 @@ export interface ExecutionEnvironment {
30
30
 
31
31
  export type ExecutionBackend = "local" | "vm"
32
32
 
33
- /** ZAPCODE_EXECUTION wins over settings; anything but "vm" means local. */
34
- export function resolveExecutionBackend(configured?: ExecutionBackend): ExecutionBackend {
33
+ /** zapVM execution is switched off: zapVM now lives in its own repository
34
+ * and zap runs everything on the local backend. The zapVM integration
35
+ * (`zapsdk/execution/zapvm*.ts`) is kept so this can be turned back on. */
36
+ export const VM_EXECUTION_ENABLED = false
37
+
38
+ export const VM_EXECUTION_DISABLED_NOTICE =
39
+ "zapVM execution is disabled in this version of zap; commands run on the local backend (OS sandbox). The \"vm\" setting and ZAPCODE_EXECUTION=vm are ignored."
40
+
41
+ /** The backend the user asked for (ZAPCODE_EXECUTION wins over settings). */
42
+ export function requestedExecutionBackend(configured?: ExecutionBackend): ExecutionBackend {
35
43
  const env = process.env.ZAPCODE_EXECUTION?.trim().toLowerCase()
36
44
  if (env === "vm" || env === "local") return env
37
45
  return configured === "vm" ? "vm" : "local"
38
46
  }
39
47
 
48
+ /** The backend actually used: always local while VM execution is disabled. */
49
+ export function resolveExecutionBackend(configured?: ExecutionBackend): ExecutionBackend {
50
+ return VM_EXECUTION_ENABLED ? requestedExecutionBackend(configured) : "local"
51
+ }
52
+
53
+ /** True when the user asked for the VM but it is disabled; hosts show the notice once. */
54
+ export function vmExecutionRequestedButDisabled(configured?: ExecutionBackend): boolean {
55
+ return !VM_EXECUTION_ENABLED && requestedExecutionBackend(configured) === "vm"
56
+ }
57
+
40
58
  function resolveRuntime(cwd: string, backend: ExecutionBackend) {
41
59
  const resident = process.env.ZAPCODE_RESIDENT_AGENT === "1"
42
60
  // Local is the default: commands run on the host under the OS sandbox and
@@ -10,6 +10,9 @@ import type { GoalRecord } from "../zapsdk/goal/contracts.js"
10
10
  import { loadAppConfig } from "./config.js"
11
11
  import { createExecutionEnvironment, resolveExecutionBackend } from "./execution-environment.js"
12
12
 
13
+ /** zapVM is optional and installed separately; only these Goal options need it. */
14
+ const VM_SETUP_HINT = "zapVM execution is disabled in this version of zap, so this Goal option is unavailable."
15
+
13
16
  function machineCheckSupported(cwd: string): boolean {
14
17
  const config = loadAppConfig(join(getAppDataDir(), "config.json"))
15
18
  const environment = createExecutionEnvironment(cwd, "required", resolveExecutionBackend(config.executionBackend), false, config.sandboxNetwork, [])
@@ -85,8 +88,8 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
85
88
  const modeArgs = args.filter(arg => arg === "--permission-mode" || arg.startsWith("--permission-mode="))
86
89
  if (!control && (modeArgs.length > 1 || modeArgs.some(arg => !/^--permission-mode=(default|acceptEdits|bypassPermissions|plan)$/.test(arg)) || modeArgs.length > 0 && args.includes("--accept-edits"))) throw new Error("Invalid Goal permission mode")
87
90
  if (!control && (installArgs.length > 1 || installArgs.some(arg => arg !== "--install=npm"))) throw new Error("Invalid Goal dependency installation; use --install=npm")
88
- if (!control && args.includes("--artifact") && installArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --install=npm requires a VM backend with verified process sealing.")
89
- if (!control && args.includes("--artifact") && checkArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --check machine verification is currently unavailable: process-tree sealing cannot be verified.")
91
+ if (!control && args.includes("--artifact") && installArgs.length && !machineCheckSupported(cwd)) throw new Error(`Goal --install=npm requires a VM backend with verified process sealing. ${VM_SETUP_HINT}`)
92
+ if (!control && args.includes("--artifact") && checkArgs.length && !machineCheckSupported(cwd)) throw new Error(`Goal --check machine verification is currently unavailable: process-tree sealing cannot be verified. ${VM_SETUP_HINT}`)
90
93
  if (!control && (checkArgs.length > 1 || checkArgs.some(arg => !/^--check=(bun|npm|pytest|go)$/.test(arg)))) throw new Error("Invalid Goal machine check; use --check=bun, npm, pytest or go")
91
94
  const background = args.includes("--background")
92
95
  if (args.filter(arg => arg === "--background").length > 1 || args.some(arg => arg.startsWith("--background="))) throw new Error("Invalid Goal background flag")
@@ -154,7 +157,7 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
154
157
  }
155
158
  if (action === "resume") {
156
159
  const goal = selectGoal(store, cwd, args[1], sessionId)
157
- if (goal.executionMode !== "session" && (goal.machineCheck || goal.dependencyInstall) && !machineCheckSupported(cwd)) throw new Error("Goal VM execution is currently unavailable: process-tree sealing cannot be verified.")
160
+ if (goal.executionMode !== "session" && (goal.machineCheck || goal.dependencyInstall) && !machineCheckSupported(cwd)) throw new Error(`Goal VM execution is currently unavailable: process-tree sealing cannot be verified. ${VM_SETUP_HINT}`)
158
161
  if (enforceSessionMode && !background && goal.executionMode === "session" && goal.permissionMode !== currentMode) throw new Error("Goal permission mode differs from the current session; restore its mode before resuming")
159
162
  const stopped = recoverStoppedOwner(store, goal)
160
163
  if (sessionId && stopped.sessionId === sessionId) store.pauseForInput(cwd, sessionId)
@@ -94,7 +94,7 @@ export function scopeGoalEvent(event: AgentEvent, scope: string): AgentEvent {
94
94
  const value = { ...event } as unknown as Record<string, any>
95
95
  for (const key of ["id", "subagentId", "requestId"]) if (typeof value[key] === "string") value[key] = `${scope}:${value[key]}`
96
96
  if (value.path) value.path = value.path.map((id: string) => `${scope}:${id}`)
97
- if (value.type === "content_final" && value.kind === "tool_result" && ["agent", "delegate_agent"].includes(value.toolName)
97
+ if (value.type === "content_final" && value.kind === "tool_result" && ["agent", "delegate_agent", "acp_agent"].includes(value.toolName)
98
98
  && typeof value.result?.meta?.subagentId === "string") {
99
99
  value.result = { ...value.result, meta: { ...value.result.meta, subagentId: `${scope}:${value.result.meta.subagentId}` } }
100
100
  }
package/src/goal-turn.ts CHANGED
@@ -29,7 +29,7 @@ export function goalTurnMeter(input: Pick<GoalTurnInput, "goalId" | "epoch" | "r
29
29
  return {
30
30
  providerAdapter: (provider: LLMProvider) => meterGoalProvider(provider, ledger, input),
31
31
  admitToolExecution: (name: string) => {
32
- const admission = ledger.admit(input.goalId, input.epoch, { operationId: randomUUID(), role: input.role, kind: "tool", opaque: ["delegate_agent", "cron_create", "monitor"].includes(name) })
32
+ const admission = ledger.admit(input.goalId, input.epoch, { operationId: randomUUID(), role: input.role, kind: "tool", opaque: ["delegate_agent", "acp_agent", "cron_create", "monitor"].includes(name) })
33
33
  if (!admission.ok) throw new Error(`Goal tool admission denied: ${admission.reason}`)
34
34
  if (name === "agent") {
35
35
  const spawn = ledger.admit(input.goalId, input.epoch, { operationId: randomUUID(), role: input.role, kind: "spawn" })
@@ -58,13 +58,13 @@ export async function runGoalMachineCommand(command: string, execute: () => Prom
58
58
 
59
59
  /** These local tools do not launch opaque model requests. */
60
60
  const GOAL_TOOLS = new Set([
61
- "read_file", "write_file", "edit_file", "multi_edit", "delete_file", "move_file",
61
+ "read_file", "write_file", "edit_file", "multi_edit", "delete_file",
62
62
  "list_tree", "read_document", "read_pdf", "read_docx",
63
- "read_tool_output", "todo_write", "current_time",
63
+ "read_tool_output", "todo_write",
64
64
  ])
65
65
  const READ_ONLY_GOAL_TOOLS = new Set([
66
66
  "read_file", "list_tree", "read_document", "read_pdf", "read_docx",
67
- "read_tool_output", "current_time",
67
+ "read_tool_output",
68
68
  ])
69
69
 
70
70
  export interface GoalPhaseInput {
@@ -1,6 +1,6 @@
1
1
  import { readOnlyBashTool } from "../../zapsdk/builtin-tools/subagent.js"
2
2
  import { connectLocalServiceOwner } from "../../zapsdk/services/local-owner.js"
3
- import { createExecutionEnvironment, resolveExecutionBackend } from "../execution-environment.js"
3
+ import { createExecutionEnvironment, resolveExecutionBackend, VM_EXECUTION_DISABLED_NOTICE, vmExecutionRequestedButDisabled } from "../execution-environment.js"
4
4
  import { executionExitCode, OutcomeProtocolError, type AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
5
5
  import type { CompletionEvidenceProvider } from "../../zapsdk/harness/completion.js"
6
6
  import type { LLMProvider } from "../../zapsdk/core/llm.js"
@@ -55,7 +55,7 @@ import {
55
55
  readCheckpointJournal,
56
56
  peekJournalLogIndex,
57
57
  } from "../session.js"
58
- import { conversation, autoMemory, taskStore, cronHandle, mdStore, globalMdStore, globalMemoryDir, memorySemanticRetriever, tokenAccounting, delegateProvidersReady } from "../singletons.js"
58
+ import { conversation, autoMemory, taskStore, mdStore, globalMdStore, globalMemoryDir, memorySemanticRetriever, tokenAccounting, delegateProvidersReady } from "../singletons.js"
59
59
  import { buildAgentObjects } from "../agent-factory.js"
60
60
  import { CheckpointManager } from "../../zapsdk/checkpoint/index.js"
61
61
  import {
@@ -478,6 +478,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
478
478
  const skills = loadAllSkills(cwd)
479
479
  // Detection is asynchronous; a cold worker must not build an empty registry.
480
480
  await delegateProvidersReady
481
+ if (vmExecutionRequestedButDisabled(config.executionBackend)) process.stderr.write(`${VM_EXECUTION_DISABLED_NOTICE}\n`)
481
482
  let executionEnvironment: ReturnType<typeof createExecutionEnvironment> | undefined
482
483
  if (args.serviceOwner) {
483
484
  try {
@@ -531,7 +532,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
531
532
  if (host.readOnlyWorkspace) {
532
533
  // No network tools: read-only Goal roles take worker output and workspace
533
534
  // files as untrusted input, and an injected URL could carry them off-host.
534
- const names = new Set(["read_file", "list_tree", "read_document", "read_pdf", "read_docx", "read_tool_output", "current_time"])
535
+ const names = new Set(["read_file", "list_tree", "read_document", "read_pdf", "read_docx", "read_tool_output"])
535
536
  if (sandboxConfined && registry.has("bash")) {
536
537
  registry.unregister("bash"); registry.register(readOnlyBashTool(cwd)); names.add("bash")
537
538
  }
@@ -540,7 +541,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
540
541
  await host.prepareRegistry?.(registry)
541
542
  if (publicChecks) {
542
543
  // These tools start work outside the root provider admission budget.
543
- for (const name of ["agent", "delegate_agent", "cron_create"]) registry.unregister(name)
544
+ for (const name of ["agent", "delegate_agent"]) registry.unregister(name)
544
545
  }
545
546
 
546
547
  // ── System prompt + per-turn attachments (mirror useAgentRunner) ─────
@@ -778,7 +779,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
778
779
  //
779
780
  // Fix: strip the singleton signal handlers for the duration of the run.
780
781
  // The `process.on("exit", _shutdown)` hook in singletons still fires on
781
- // natural exit, so taskStore / cronHandle cleanup is preserved.
782
+ // natural exit, so taskStore cleanup is preserved.
782
783
  const previousSigintListeners = process.listeners("SIGINT")
783
784
  const previousSigtermListeners = process.listeners("SIGTERM")
784
785
  process.removeAllListeners("SIGINT")
@@ -888,7 +889,6 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
888
889
  // (singletons.ts already wires process.on("exit") cleanup; calling here
889
890
  // ensures cleanup before exit code is set when running embedded.)
890
891
  try { taskStore.stopAll("SIGTERM") } catch {}
891
- try { cronHandle.stop() } catch {}
892
892
 
893
893
  if (outcomeFailure) return outcomeFailure.code === "REPAIR_CANCELLED" ? 130
894
894
  : outcomeFailure.code === "REPAIR_DEADLINE_EXCEEDED" ? 124 : EXIT_ERROR
@@ -6,6 +6,7 @@ import type { ApprovalCallback } from "../../zapsdk/tools/executor.js"
6
6
  import type { SkillDefinition } from "../../zapsdk/skills/types.js"
7
7
  import { buildAgentObjects } from "../agent-factory.js"
8
8
  import { delegateProvidersReady, mdStore, permissionManager } from "../singletons.js"
9
+ import { remoteAgents } from "../agent/remote-agent.js"
9
10
  import type { AgentObjects } from "../agent/types.js"
10
11
  import { REQUEST_CAPABILITIES_TOOL } from "../capabilities.js"
11
12
  import { requestCapabilitiesTool } from "../request-capabilities-tool.js"
@@ -56,6 +57,13 @@ export function useAgentObjects(opts: UseAgentObjectsOptions & {
56
57
 
57
58
  const build = () => {
58
59
  const objs = buildAgentObjects(config, onApproval, todoStore, planCallbacks, checkpoint, skillsRef.current, undefined, undefined, undefined, undefined, askUserCallbacks)
60
+ // The live ACP session (session mode) asks through the current gates.
61
+ remoteAgents.host.approve = onApproval
62
+ remoteAgents.host.trackEdit = checkpoint?.createEditTracker()
63
+ // Agents run on the host, outside zap's OS sandbox.
64
+ remoteAgents.host.blocked = config.allowUnsandboxedCommands === false
65
+ ? "External agents run outside zap's OS sandbox, which allowUnsandboxedCommands: false forbids. /agent zap switches back."
66
+ : undefined
59
67
  permissionManager.setSandboxConfined(objs.sandboxConfined, config.autoAllowSandboxedCommands !== false)
60
68
  permissionManager.setSandboxNetworkPolicy(objs.sandboxNetworkPolicy)
61
69
  permissionManager.setSandboxExcludedCommands(config.allowUnsandboxedCommands !== false ? config.sandboxExcludedCommands : undefined)
@@ -23,7 +23,7 @@ import { buildCustomSystemPrompt, buildSystemPrompt, deriveCompaction, getActive
23
23
  import { appendUsage, saveLastOutput, getCurrentSessionId } from "../session.js"
24
24
  import type { AppConfig } from "../config.js"
25
25
  import type { LogType, ToolCallInfo, UserImageRef } from "../ui/types.js"
26
- import { appLogger, permissionManager, delegateEventBridge, mdStore, globalMdStore, globalMemoryDir, memorySemanticRetriever, tokenAccounting } from "../singletons.js"
26
+ import { acpAgents, appLogger, permissionManager, delegateEventBridge, mdStore, globalMdStore, globalMemoryDir, memorySemanticRetriever, tokenAccounting } from "../singletons.js"
27
27
  import { createStreamingPreview } from "../agent/streamingPreview.js"
28
28
  import {
29
29
  buildMemoryQueryHistoryFromLogs,
@@ -43,6 +43,7 @@ import { watchSession } from "../watch/integration.js"
43
43
  import { registerHostRuntime } from "../agent/hostProtocol.js"
44
44
  import { createProjectRuntimeEventStore, recoverProjectRuntimeOutcome } from "../agent/runtimeEventStore.js"
45
45
  import { contextTokensFromRunUsage, createRunHandlers } from "../agent/wireRunHandlers.js"
46
+ import { runRemoteTurn } from "../agent/remote-turn.js"
46
47
  import { appendCacheableSystemSection, buildRuntimePromptToolInputs } from "../agent/systemPrompt.js"
47
48
  import { createPromptSectionDiagnostics, buildPromptCacheDiagnostics, type PromptCacheDiagnostics } from "../agent/promptDiagnostics.js"
48
49
  import { persistRunUsage } from "../agent/usagePersistence.js"
@@ -589,6 +590,54 @@ export function useAgentRunner({
589
590
  let preview: ReturnType<typeof createStreamingPreview> | null = null
590
591
  let handlers: ReturnType<typeof createRunHandlers> | null = null
591
592
 
593
+ // Session mode: an external ACP agent answers this turn instead of zap's loop.
594
+ const remoteSpec = config.activeAgent ? acpAgents.find(agent => agent.id === config.activeAgent) : undefined
595
+ if (config.activeAgent) {
596
+ try {
597
+ if (!remoteSpec) throw new Error(`ACP agent ${config.activeAgent} is not available; /agent zap switches back`)
598
+ if (invocation?.goalTurn) throw new Error("/goal runs on zap's own model; /agent zap switches back")
599
+ if (systemPrompt) throw new Error("This command runs on zap's own model; /agent zap switches back")
600
+ completedResult = await runRemoteTurn({
601
+ spec: remoteSpec, cwd, conversation, currentConfig: config, controller,
602
+ createPreview: () => {
603
+ const next = createStreamingPreview({ addLog, setStreamingText, setIsStreaming, setThinkingText, setIsThinking, getIsFrozen: getIsFrozen ?? (() => false) })
604
+ registerStaticFlushCallback?.(() => next.onStaticFlushed())
605
+ return next
606
+ },
607
+ saveLastOutput,
608
+ onInputAccepted: invocation?.onInputAccepted,
609
+ checkpointTurn: checkpoint ? (() => {
610
+ const turnStartIndex = conversation.getAllMessages().length
611
+ const position = () => ({ journalLogIndex: turnStartLogIndexRef.current, uiLogIndex: turnStartUiLogIndexRef.current })
612
+ return {
613
+ begin: () => checkpoint.beginTurn(turnStartIndex, position(), task),
614
+ end: () => checkpoint.makeSnapshot(turnStartIndex, position()),
615
+ }
616
+ })() : undefined,
617
+ setStatus, setStep, setActiveTool, setActiveToolBytes, setProviderRequest, setOutputThroughput,
618
+ addLog, replaceLog, peekNextLogId, compactLogs,
619
+ onAgentRunState: (run) => { agentRunStore.apply(run) },
620
+ }, task, images)
621
+ } catch (err) {
622
+ caughtError = err
623
+ if (!remoteSpec || invocation?.goalTurn || systemPrompt) addLog("error", err instanceof Error ? err.message : String(err))
624
+ } finally {
625
+ if (controller.signal.aborted) {
626
+ setOutputThroughput(undefined)
627
+ addLog("system", "(interrupted)")
628
+ }
629
+ running.current = false
630
+ abortRef.current = null
631
+ setActiveTool("")
632
+ setStatus("ready")
633
+ setProviderRequest(undefined)
634
+ setStep(0)
635
+ externalSignal?.removeEventListener("abort", forwardExternalAbort)
636
+ }
637
+ if (invocation?.propagateErrors && caughtError) throw caughtError
638
+ return completedResult
639
+ }
640
+
592
641
  try {
593
642
  const objects = agentRef.current
594
643
  const { registry, createRegistryForCwd, executionFacts, executionCapacity } = objects
@@ -1,7 +1,7 @@
1
1
  import type { PermissionMode } from "./config.js"
2
2
  import { PermissionManager, isPathReadTool } from "./permissions.js"
3
3
  import type { ApprovalContext } from "../zapsdk/tools/executor.js"
4
- import { approvalFacts } from "./approval-facts.js"
4
+ import { approvalFacts, isAcpAgentRequest } from "./approval-facts.js"
5
5
  import { matchDangerousToolCall } from "../zapsdk/utils/safety.js"
6
6
  import { REQUEST_CAPABILITIES_TOOL, parseCapabilityRequest } from "./capabilities.js"
7
7
 
@@ -29,7 +29,10 @@ export type ApprovalCategory = "read" | "edit" | "shell" | "sandbox-escape" | "d
29
29
 
30
30
  /** One factual policy order shared by interactive and headless hosts. */
31
31
  export function evaluateApprovalPolicy(manager: PermissionManager, name: string, args: Record<string, unknown>, options: ApprovalPolicyOptions): ApprovalPolicyDecision {
32
- const decision = decide(manager, name, args, options)
32
+ const decided = decide(manager, name, args, options)
33
+ // No session/project grant for an ACP agent's free-form request: a saved
34
+ // rule could only be the bare tool name, which would allow every future one.
35
+ const decision = isAcpAgentRequest(name) ? { ...decided, allowScope: false } : decided
33
36
  // Only a prompt the user already answered this turn becomes a refusal; a
34
37
  // mode change or new rule that allows the call still lets it run.
35
38
  return decision.decision === "ask" && manager.declinedThisTurn(name, args, options.context)
@@ -4,7 +4,7 @@ import { homedir } from "node:os"
4
4
  import { createHash } from "node:crypto"
5
5
  import { getAppDataDir } from "../zapsdk/utils/platform.js"
6
6
  import { matchGlob } from "../zapsdk/builtin-tools/glob-util.js"
7
- import { approvalFacts, opaqueShell } from "./approval-facts.js"
7
+ import { approvalFacts, isAcpAgentRequest, opaqueShell } from "./approval-facts.js"
8
8
  import type { ApprovalContext } from "../zapsdk/tools/executor.js"
9
9
  import type { Logger } from "../zapsdk/debug/logger.js"
10
10
  import { writeFileAtomic } from "./utils/secure-write.js"
@@ -321,8 +321,13 @@ function normalizeDelegateCwd(value: unknown, cwd: string): string {
321
321
  return rel
322
322
  }
323
323
 
324
- function delegateAgentSubject(args: Record<string, unknown>, cwd: string): string | null {
325
- const provider = typeof args.provider === "string" ? args.provider.trim() : ""
324
+ /** External-agent tools whose grants are scoped to one agent and cwd. */
325
+ const SCOPED_AGENT_TOOLS: Record<string, string> = { delegate_agent: "provider", acp_agent: "agent" }
326
+ export function isScopedAgentTool(name: string): boolean { return Object.hasOwn(SCOPED_AGENT_TOOLS, name) }
327
+
328
+ function delegateAgentSubject(toolName: string, args: Record<string, unknown>, cwd: string): string | null {
329
+ const key = SCOPED_AGENT_TOOLS[toolName] ?? "provider"
330
+ const provider = typeof args[key] === "string" ? (args[key] as string).trim() : ""
326
331
  if (!provider) return null
327
332
  const delegateCwd = normalizeDelegateCwd(args.cwd, cwd)
328
333
  return `${encodeURIComponent(provider)}@${encodeURIComponent(delegateCwd)}`
@@ -343,8 +348,8 @@ function normalizeFileArgs(
343
348
  context?: Readonly<ApprovalContext>,
344
349
  canonical: boolean | "entry" = true,
345
350
  ): Record<string, unknown> {
346
- if (toolName === "delegate_agent") {
347
- const subject = delegateAgentSubject(args, cwd)
351
+ if (isScopedAgentTool(toolName)) {
352
+ const subject = delegateAgentSubject(toolName, args, cwd)
348
353
  return subject ? { ...args, [DELEGATE_AGENT_SUBJECT_ARG]: subject } : args
349
354
  }
350
355
  if (!FILE_TOOLS.has(toolName)) return args
@@ -396,7 +401,7 @@ function extractArgString(toolName: string, args: Record<string, unknown>): stri
396
401
  if (FILE_TOOLS.has(toolName)) {
397
402
  return String(args.path ?? args.source ?? "")
398
403
  }
399
- if (toolName === "delegate_agent") {
404
+ if (isScopedAgentTool(toolName)) {
400
405
  return typeof args[DELEGATE_AGENT_SUBJECT_ARG] === "string"
401
406
  ? args[DELEGATE_AGENT_SUBJECT_ARG]
402
407
  : ""
@@ -441,7 +446,7 @@ export function ruleMatchesTool(
441
446
  ): boolean {
442
447
  const { toolNames, argPattern } = parsePattern(rule.pattern)
443
448
  if (!toolNames.some(n => n === toolName)) return false
444
- if (toolName === "delegate_agent" && argPattern === null) return rule.type === "deny"
449
+ if ((isScopedAgentTool(toolName) || isAcpAgentRequest(toolName)) && argPattern === null) return rule.type === "deny"
445
450
  if (argPattern === null) return true
446
451
  if (toolName === "move_file") {
447
452
  const paths = [args.source, args.destination].filter((value): value is string => typeof value === "string" && !!value)
@@ -449,7 +454,7 @@ export function ruleMatchesTool(
449
454
  }
450
455
  const subject = extractArgString(toolName, args)
451
456
  if (toolName === "bash") return matchCommandGlob(subject, argPattern)
452
- if (toolName === "delegate_agent") return subject === argPattern
457
+ if (isScopedAgentTool(toolName)) return subject === argPattern
453
458
  return FILE_TOOLS.has(toolName) ? matchFilePattern(subject, argPattern, rule.type === "allow" && rule.canonicalPath) : matchGlob(subject, argPattern)
454
459
  }
455
460
 
@@ -459,7 +464,7 @@ export function ruleMatchesTool(
459
464
  * tools from the adapter's effects. Shells and delegation keep their own rules. */
460
465
  function callCapabilities(name: string, args: Record<string, unknown>, context?: Readonly<ApprovalContext>): readonly ToolCapability[] | undefined {
461
466
  if (FILE_TOOLS.has(name)) return fileToolCapabilities(name, args)
462
- if (name === "delegate_agent") return undefined
467
+ if (isScopedAgentTool(name)) return undefined
463
468
  // A capability request needs exactly what it asks for.
464
469
  if (name === REQUEST_CAPABILITIES_TOOL) {
465
470
  const requested = parseCapabilityRequest(args)
@@ -646,9 +651,9 @@ export function inferPattern(toolName: string, args: Record<string, unknown>, cw
646
651
  const prefix = extractCommandPrefix(shellCommandDisplay(args), 2)
647
652
  return prefix ? `Bash(${prefix}:*)` : null
648
653
  }
649
- if (toolName === "delegate_agent") {
650
- const subject = delegateAgentSubject(args, cwd)
651
- return subject ? `delegate_agent(${subject})` : null
654
+ if (isScopedAgentTool(toolName)) {
655
+ const subject = delegateAgentSubject(toolName, args, cwd)
656
+ return subject ? `${toolName}(${subject})` : null
652
657
  }
653
658
  const aliases: Record<string, string> = {
654
659
  write_file: "Write", create_file: "Write",
@@ -668,6 +673,8 @@ export function inferPattern(toolName: string, args: Record<string, unknown>, cw
668
673
  if (isAbsolute(rel)) return `${alias}(${rel})`
669
674
  return `${alias}(${fileRuleScope(toolName, rel)})`
670
675
  }
676
+ // An external ACP agent's unmapped request has no scope to save.
677
+ if (isAcpAgentRequest(toolName)) return null
671
678
  // Non-aliased tools: exact tool-name match is fine (no args to wildcard).
672
679
  // High-risk tools that need arg scoping should get a dedicated branch above.
673
680
  return toolName
package/src/singletons.ts CHANGED
@@ -15,7 +15,9 @@ import {
15
15
  AgentLogger,
16
16
  } from "../zapsdk/index.js"
17
17
  import { getAppDataDir } from "../zapsdk/utils/platform.js"
18
- import { cronTools, monitorTool, detectProviders, type DetectedProvider } from "../zapsdk/builtin-tools/index.js"
18
+ import { detectProviders, type DetectedProvider } from "../zapsdk/builtin-tools/index.js"
19
+ import { detectAcpAgents } from "../zapsdk/acp-client/detect.js"
20
+ import type { AcpAgentSpec } from "../zapsdk/acp-client/types.js"
19
21
  import { TaskStore } from "../zapsdk/tasks/store.js"
20
22
  import { buildTaskNotificationXml, classifyTaskExit } from "../zapsdk/tasks/notification.js"
21
23
  import { pushSystemEvent } from "./queue/systemInbox.js"
@@ -106,17 +108,9 @@ export const tokenAccounting = {
106
108
  promptOverhead: 0,
107
109
  }
108
110
 
109
- // ─── Cron + Monitor session-scoped handles ───
110
- // Singletons (not per-config-reload): session-only jobs should survive
111
- // config changes but die with the process. No `agentId` → main agent has
112
- // team-lead semantics (sees and deletes all jobs). `onFire` is left
113
- // undefined until the CLI prompt-queue integration is wired — fires are
114
- // recorded on the job (lastFiredAt) but do not inject into agent turns yet.
115
- export const cronHandle = cronTools({})
116
- // Single shared TaskStore — monitor, bash bg, and future task_* tools all
111
+ // Single shared TaskStore — bash background commands and the task_* tools
117
112
  // register and look up tasks here so the UI gets a unified view.
118
113
  export const taskStore = new TaskStore({ projectCwd: process.cwd() })
119
- export const monitorHandle = monitorTool({ store: taskStore })
120
114
 
121
115
  // ─── Task-completion → systemInbox bridge ───
122
116
  // When a background task exits, build a `<task-notification>` XML payload
@@ -142,15 +136,13 @@ taskStore.on("exited", (e) => {
142
136
  })
143
137
 
144
138
  // ─── Process shutdown cleanup ───
145
- // Kill every still-running monitor child so Ctrl-C doesn't leave background
146
- // processes orphaned. Cron scheduler is setInterval(unref'd), dies with the
147
- // process; calling stop() is belt-and-suspenders.
139
+ // Kill every still-running background command so Ctrl-C doesn't leave
140
+ // processes orphaned.
148
141
  let _shutdownRan = false
149
142
  function _shutdown(): void {
150
143
  if (_shutdownRan) return
151
144
  _shutdownRan = true
152
145
  try { taskStore.stopAll("SIGTERM") } catch {}
153
- try { cronHandle.stop() } catch {}
154
146
  }
155
147
  process.on("exit", _shutdown)
156
148
  const shutdownOnInterrupt = () => { _shutdown(); process.exit(130) }
@@ -180,9 +172,25 @@ export function stopRuntimeForRestart(): void {
180
172
  // 30–200ms), leaving `delegate_agent` unregistered until the user
181
173
  // independently changes config and triggers a rebuild.
182
174
  export let delegateProviders: DetectedProvider[] = []
183
- export const delegateProvidersReady: Promise<DetectedProvider[]> = detectProviders(2000)
184
- .then((found) => { delegateProviders = found; return found })
185
- .catch(() => [] as DetectedProvider[])
175
+ /** ACP agents for `acp_agent`: configured entries plus known agents on PATH. */
176
+ export let acpAgents: AcpAgentSpec[] = []
177
+ const acpAgentsReady: Promise<AcpAgentSpec[]> = (async () => {
178
+ let configured: AcpAgentSpec[] = []
179
+ try { configured = validAcpAgentSpecs(loadAppConfig(configPath).acpAgents) } catch { /* invalid config is reported elsewhere */ }
180
+ acpAgents = await detectAcpAgents(configured)
181
+ return acpAgents
182
+ })().catch(() => [] as AcpAgentSpec[])
183
+ export const delegateProvidersReady: Promise<DetectedProvider[]> = Promise.all([
184
+ detectProviders(2000).then((found) => { delegateProviders = found; return found }).catch(() => [] as DetectedProvider[]),
185
+ acpAgentsReady,
186
+ ]).then(([found]) => found)
187
+
188
+ function validAcpAgentSpecs(value: unknown): AcpAgentSpec[] {
189
+ if (!Array.isArray(value)) return []
190
+ return value.filter((entry): entry is AcpAgentSpec => !!entry && typeof entry === "object"
191
+ && typeof entry.id === "string" && /^[\w.-]+$/.test(entry.id) && typeof entry.command === "string"
192
+ && (entry.args === undefined || (Array.isArray(entry.args) && entry.args.every((arg: unknown) => typeof arg === "string"))))
193
+ }
186
194
 
187
195
  export const delegateEventBridge: { handler: AgentEventHandler | null } = { handler: null }
188
196
 
@@ -1,6 +1,6 @@
1
1
  import { dirname, isAbsolute, join, relative, resolve } from "node:path"
2
2
  import { homedir } from "node:os"
3
- import { WORKSPACE_EDIT_TOOLS, type PermissionRule } from "./permissions.js"
3
+ import { WORKSPACE_EDIT_TOOLS, isScopedAgentTool, type PermissionRule } from "./permissions.js"
4
4
  import { canonicalizeWithNearestExistingAncestorSync } from "../zapsdk/builtin-tools/filesystem.js"
5
5
 
6
6
  export interface ToolGrantRequest {
@@ -43,7 +43,7 @@ function expandToolGrantRules(request: ToolGrantRequest, availableTools: readonl
43
43
  if (!tools.length) throw new Error("Select at least one tool")
44
44
  for (const tool of tools) {
45
45
  if (!availableTools.includes(tool) || !/^[\w.-]+$/.test(tool)) throw new Error(`Tool is not available: ${tool}`)
46
- if (tool === "delegate_agent") throw new Error("delegate_agent requires a provider/cwd-scoped approval")
46
+ if (isScopedAgentTool(tool)) throw new Error(`${tool} requires an agent/cwd-scoped approval`)
47
47
  }
48
48
  if (request.resource.kind === "all") return tools.map(tool => ({ pattern: tool, type: "allow" }))
49
49
  const filesOnly = tools.every(tool => FILE_GRANT_TOOLS.includes(tool))
@@ -59,7 +59,8 @@ function agentLabel(log: LogEntry): string {
59
59
  const path = log.agentPath
60
60
  if (!path?.length) return ""
61
61
  const short = path.map(seg => {
62
- const m = seg.match(/^da_([^_]+)/)
62
+ // delegate_agent ids are da_<provider>_…, acp_agent ids acp_<agent>_<time>_<rand>.
63
+ const m = seg.match(/^da_([^_]+)/) ?? seg.match(/^acp_(.+)_[a-z0-9]+_[a-z0-9]{1,4}$/)
63
64
  return m ? m[1] : seg
64
65
  }).join("/")
65
66
  return `[${short}]`
@@ -75,7 +75,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
75
75
  : `${getToolAlias(toolName)} commands`)
76
76
  const unsandboxed = escape ?? isUnsandboxedBash(toolName, args)
77
77
  const request = toolName === REQUEST_CAPABILITIES_TOOL
78
- const canCustomize = allowScope && !unsandboxed && !request && toolName !== "delegate_agent" && availableTools.includes(toolName) && !!onGrant
78
+ const canCustomize = allowScope && !unsandboxed && !request && toolName !== "delegate_agent" && toolName !== "acp_agent" && availableTools.includes(toolName) && !!onGrant
79
79
  const directory = canCustomize ? suggestToolGrantDirectory(toolName, args, cwd) : undefined
80
80
  // A capability request is only worth something when it is remembered.
81
81
  const options: Option[] = request && allowScope ? [
@@ -153,7 +153,7 @@ export function RewindDialog({ checkpoint, logs, onApply, onCancel, isRunning }:
153
153
  {diag.enabled && diag.pendingCount === 0 && (
154
154
  <Box marginTop={1} flexDirection="column">
155
155
  <Text color={c.text.faint}>Recovery points are created before each turn. File undo covers:</Text>
156
- <Text color={c.text.faint}> write_file · edit_file · multi_edit · delete_file · move_file</Text>
156
+ <Text color={c.text.faint}> write_file · edit_file · multi_edit · delete_file</Text>
157
157
  <Text color={c.text.faint}>File edits via bash (sed -i, cat &gt; …) are not tracked.</Text>
158
158
  </Box>
159
159
  )}
@@ -21,7 +21,7 @@ interface Props {
21
21
  export function ToolGrantDialog({ availableTools, initialTools = [], initialPattern = "", initialDirectory = "", directoryShortcut = false, cwd = process.cwd(), onSave, onCancel }: Props) {
22
22
  useHideNativeCursor()
23
23
  // Freeze the reviewed registry snapshot: later MCP registrations cannot join it.
24
- const [tools] = useState(() => [...new Set(availableTools)].filter(name => name !== "delegate_agent").sort())
24
+ const [tools] = useState(() => [...new Set(availableTools)].filter(name => name !== "delegate_agent" && name !== "acp_agent").sort())
25
25
  const [selected, setSelected] = useState(() => initialTools.filter(name => tools.includes(name)))
26
26
  const [step, setStep] = useState(0)
27
27
  const [index, setIndex] = useState(0)
@@ -94,7 +94,7 @@ export function ToolGrantDialog({ availableTools, initialTools = [], initialPatt
94
94
  return <Box flexDirection="column" paddingX={1} marginTop={1}>
95
95
  <Text bold color={c.text.primary}>Tool authorization — {["select tools", "resource scope", "resource filter", "lifetime", "review authorization"][step]}</Text>
96
96
  {step === 0 && <>
97
- <Text color={c.text.muted}>{selected.length} selected · {tools.length} available · delegate_agent requires scoped approval</Text>
97
+ <Text color={c.text.muted}>{selected.length} selected · {tools.length} available · agent delegation requires scoped approval</Text>
98
98
  {tools.slice(start, start + 8).map((tool, offset) => <Text key={tool} color={index === start + offset ? c.accent : c.text.primary}>{index === start + offset ? "›" : " "} [{selected.includes(tool) ? "x" : " "}] {tool}</Text>)}
99
99
  <Text color={c.text.muted}>↑↓ navigate · space select · r read · w edit · a all · n none · Enter next · Esc cancel</Text>
100
100
  </>}
package/src/ui/footer.tsx CHANGED
@@ -45,6 +45,8 @@ interface FooterProps {
45
45
  step: number
46
46
  maxSteps: number
47
47
  contextBudget: ContextBudgetSnapshot
48
+ /** Hide zap's context gauge (an external ACP agent owns its own context). */
49
+ hideContext?: boolean
48
50
  hasApiKey: boolean
49
51
  showWelcome?: boolean
50
52
  shellMode?: boolean
@@ -66,6 +68,7 @@ export const Footer = memo(function Footer({
66
68
  effort,
67
69
  isRunning,
68
70
  contextBudget,
71
+ hideContext,
69
72
  hasApiKey,
70
73
  showWelcome,
71
74
  shellMode,
@@ -105,7 +108,7 @@ export const Footer = memo(function Footer({
105
108
  if (!hasApiKey && !showWelcome) rightSegments.push({ text: "! /connect", fg: c.warning, key: "connect" })
106
109
  if (showWelcome && !hasApiKey) rightSegments.push({ text: "/connect", fg: c.accent, key: "connect" })
107
110
  if (tpsText) rightSegments.push({ text: tpsText, fg: c.text.muted, key: "tps" })
108
- if (ctxText) rightSegments.push({ text: ctxText, fg: ctxColor, key: "ctx" })
111
+ if (ctxText && !hideContext) rightSegments.push({ text: ctxText, fg: ctxColor, key: "ctx" })
109
112
  if (mcp && mcp.total > 0) {
110
113
  const hasError = mcp.error > 0 || mcp.needsAuth > 0
111
114
  const hasDegraded = mcp.degraded > 0 || mcp.ready < mcp.total - mcp.error - mcp.needsAuth
@@ -87,7 +87,7 @@ export function groupLogs(logs: LogEntry[]): RenderItem[] {
87
87
  const groupKeyByParent = new Map<LogEntry, { key: string; started: boolean }>()
88
88
  for (const log of logs) {
89
89
  if (log.agentPath?.length) continue
90
- if (log.tool?.name !== "agent" && log.tool?.name !== "delegate_agent") continue
90
+ if (log.tool?.name !== "agent" && log.tool?.name !== "delegate_agent" && log.tool?.name !== "acp_agent") continue
91
91
  const sid = (log.tool.meta as { subagentId?: string } | undefined)?.subagentId
92
92
  if (sid && !parentBySubagent.has(sid)) {
93
93
  parentBySubagent.set(sid, log)
@@ -59,7 +59,7 @@ function formatToolLabel(name: string, args: Record<string, unknown> | undefined
59
59
 
60
60
  export function formatPendingToolsLabel(pendingTools: LogEntry[]): string {
61
61
  const agentTools = pendingTools.filter(log => (
62
- log.tool?.name === "agent" || log.tool?.name === "delegate_agent"
62
+ log.tool?.name === "agent" || log.tool?.name === "delegate_agent" || log.tool?.name === "acp_agent"
63
63
  ))
64
64
  if (agentTools.length > 1) {
65
65
  const otherCount = pendingTools.length - agentTools.length
@@ -22,6 +22,7 @@ export const BUILTIN_COMMANDS: SlashEntry[] = [
22
22
  { name: "/connect", desc: "Set up provider & API key" },
23
23
  { name: "/model", desc: "Show or switch model" },
24
24
  { name: "/effort", desc: "Set reasoning effort (off | cycle | <value>)" },
25
+ { name: "/agent", desc: "Talk to an external ACP agent (agy | codex) · /agent zap" },
25
26
  { name: "/mode", desc: "Permission mode (default | acceptEdits | plan | bypass)" },
26
27
  { name: "/permissions", desc: "Manage active permission rules" },
27
28
  { name: "/sessions", desc: "Browse saved sessions" },
@@ -44,6 +44,7 @@ function formatArgs(name: string, args: Record<string, unknown> | undefined): st
44
44
  if (!args) return ""
45
45
  if (name === "agent") return shortAgentLabel(args.task as string | undefined)
46
46
  if (name === "skill") return oneLine(args.name)
47
+ if (name === "acp_agent") return oneLine(`${String(args.agent ?? "")}: ${String(args.task ?? "")}`)
47
48
  // exit_plan_mode carries the markdown plan as `plan`. Show the first
48
49
  // non-empty line as the in-parens preview so the row reads as
49
50
  // `ExitPlanMode("install foo + wire it through bar…")` instead of an
@@ -74,6 +75,9 @@ function formatArgs(name: string, args: Record<string, unknown> | undefined): st
74
75
  if (args.query) return oneLine(args.query)
75
76
  if (args.url) return oneLine(args.url)
76
77
  if (args.task ?? args.description) return oneLine(args.task ?? args.description)
78
+ // External ACP agents' permission requests carry locations and a title.
79
+ if (Array.isArray(args.paths) && args.paths.length) return oneLine(args.paths.map(p => normalizePath(String(p))).join(", "))
80
+ if (args.title) return oneLine(args.title)
77
81
  return ""
78
82
  }
79
83
 
@@ -84,7 +88,7 @@ const TOOL_ALIASES: Record<string, string> = {
84
88
  bash: "Bash", execute_command: "Bash",
85
89
  glob_files: "Glob", search_files: "Search",
86
90
  web_search: "WebSearch", http_fetch: "Fetch",
87
- agent: "Agent", skill: "Skill", delegate_agent: "Delegate",
91
+ agent: "Agent", skill: "Skill", delegate_agent: "Delegate", acp_agent: "ACP Agent",
88
92
  todo_write: "TodoWrite",
89
93
  enter_plan_mode: "EnterPlanMode", exit_plan_mode: "ExitPlanMode",
90
94
  read_document: "ReadDocument", read_pdf: "ReadPdf", read_docx: "ReadDocx",