zapagent 1.14.26 → 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.
- package/LICENSE +2 -3
- package/README.md +3 -3
- package/README.zh-CN.md +3 -3
- package/SECURITY.md +3 -2
- package/THIRD_PARTY_NOTICES.md +4 -8
- package/bundled-dependencies.json +204 -204
- package/package.json +1 -1
- package/src/App.tsx +19 -6
- package/src/agent/remote-agent.ts +150 -0
- package/src/agent/remote-turn.ts +72 -0
- package/src/agent/wireRunHandlers.ts +5 -2
- package/src/agent-factory.ts +19 -2
- package/src/approval-facts.ts +20 -3
- package/src/commands/dispatcher.ts +47 -3
- package/src/commands.ts +4 -0
- package/src/config.ts +13 -2
- package/src/execution-environment.ts +20 -2
- package/src/goal-command.ts +6 -3
- package/src/goal-session.ts +1 -1
- package/src/goal-turn.ts +1 -1
- package/src/headless/runHeadless.ts +2 -1
- package/src/hooks/useAgentObjects.ts +8 -0
- package/src/hooks/useAgentRunner.ts +50 -1
- package/src/permission-policy.ts +5 -2
- package/src/permissions.ts +19 -12
- package/src/singletons.ts +21 -3
- package/src/tool-grants.ts +2 -2
- package/src/ui/Transcript.tsx +2 -1
- package/src/ui/dialog-approval.tsx +1 -1
- package/src/ui/dialog-tool-grant.tsx +2 -2
- package/src/ui/footer.tsx +4 -1
- package/src/ui/group-logs.ts +1 -1
- package/src/ui/live-activity.tsx +1 -1
- package/src/ui/slash-palette.tsx +1 -0
- package/src/ui/transcript-format.ts +5 -1
- package/zapsdk/acp-client/connection.ts +228 -0
- package/zapsdk/acp-client/detect.ts +28 -0
- package/zapsdk/acp-client/event-mapper.ts +231 -0
- package/zapsdk/acp-client/host-handlers.ts +225 -0
- package/zapsdk/acp-client/index.ts +6 -0
- package/zapsdk/acp-client/run.ts +169 -0
- package/zapsdk/acp-client/types.ts +52 -0
- package/zapsdk/builtin-tools/acp-agent.ts +188 -0
- package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
- package/zapsdk/builtin-tools/index.ts +9 -0
- package/zapsdk/execution/process.ts +1 -1
- package/zapsdk/execution/sandbox.ts +6 -4
- package/zapsdk/execution/types.ts +3 -0
- package/zapsdk/goal/git-history-snapshot.ts +3 -1
package/src/goal-command.ts
CHANGED
|
@@ -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(
|
|
89
|
-
if (!control && args.includes("--artifact") && checkArgs.length && !machineCheckSupported(cwd)) throw new Error(
|
|
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(
|
|
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)
|
package/src/goal-session.ts
CHANGED
|
@@ -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" })
|
|
@@ -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"
|
|
@@ -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 {
|
|
@@ -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
|
package/src/permission-policy.ts
CHANGED
|
@@ -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
|
|
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)
|
package/src/permissions.ts
CHANGED
|
@@ -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
|
-
|
|
325
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
650
|
-
const subject = delegateAgentSubject(args, cwd)
|
|
651
|
-
return subject ?
|
|
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
|
@@ -16,6 +16,8 @@ import {
|
|
|
16
16
|
} from "../zapsdk/index.js"
|
|
17
17
|
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
18
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"
|
|
@@ -170,9 +172,25 @@ export function stopRuntimeForRestart(): void {
|
|
|
170
172
|
// 30–200ms), leaving `delegate_agent` unregistered until the user
|
|
171
173
|
// independently changes config and triggers a rebuild.
|
|
172
174
|
export let delegateProviders: DetectedProvider[] = []
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
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
|
+
}
|
|
176
194
|
|
|
177
195
|
export const delegateEventBridge: { handler: AgentEventHandler | null } = { handler: null }
|
|
178
196
|
|
package/src/tool-grants.ts
CHANGED
|
@@ -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
|
|
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))
|
package/src/ui/Transcript.tsx
CHANGED
|
@@ -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
|
-
|
|
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 ? [
|
|
@@ -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 ·
|
|
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
|
package/src/ui/group-logs.ts
CHANGED
|
@@ -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)
|
package/src/ui/live-activity.tsx
CHANGED
|
@@ -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
|
package/src/ui/slash-palette.tsx
CHANGED
|
@@ -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",
|