zapagent 1.14.24 → 1.14.26
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/package.json +1 -1
- package/src/App.tsx +4 -1
- package/src/agent/contextAttachments.ts +4 -2
- package/src/agent/types.ts +2 -0
- package/src/agent-factory.ts +3 -11
- package/src/capabilities.ts +121 -0
- package/src/commands/dispatcher.ts +6 -2
- package/src/commands.ts +1 -1
- package/src/config.ts +10 -0
- package/src/execution-environment.ts +17 -7
- package/src/headless/approval.ts +45 -27
- package/src/headless/args.ts +6 -8
- package/src/headless/goalPhase.ts +3 -3
- package/src/headless/runHeadless.ts +9 -7
- package/src/hooks/useAgentObjects.ts +6 -1
- package/src/hooks/useAgentRunner.ts +4 -2
- package/src/hooks/usePermissionApproval.ts +40 -22
- package/src/permission-policy.ts +44 -2
- package/src/permissions.ts +240 -11
- package/src/readonly-commands.ts +31 -0
- package/src/request-capabilities-tool.ts +37 -0
- package/src/singletons.ts +4 -14
- package/src/tool-grants.ts +2 -2
- package/src/ui/dialog-approval.tsx +22 -9
- package/src/ui/dialog-config.tsx +3 -3
- package/src/ui/dialog-permissions.tsx +2 -0
- package/src/ui/dialog-rewind.tsx +1 -1
- package/zapsdk/agent/loop.ts +51 -4
- package/zapsdk/agent/tool-execution-guards.ts +23 -37
- package/zapsdk/builtin-tools/command.ts +19 -3
- package/zapsdk/builtin-tools/http.ts +3 -0
- package/zapsdk/builtin-tools/index.ts +11 -16
- package/zapsdk/builtin-tools/memory.ts +2 -2
- package/zapsdk/builtin-tools/plan-mode.ts +1 -1
- package/zapsdk/builtin-tools/subagent.ts +2 -2
- package/zapsdk/execution/broker.ts +10 -3
- package/zapsdk/execution/network-proxy.ts +15 -2
- package/zapsdk/execution/sandbox.ts +1 -0
- package/zapsdk/execution/types.ts +2 -0
- package/zapsdk/index.ts +1 -1
- package/zapsdk/tools/approval.ts +44 -0
- package/zapsdk/tools/executor.ts +20 -2
- package/zapsdk/utils/destructive-shell.ts +20 -1
package/src/readonly-commands.ts
CHANGED
|
@@ -357,3 +357,34 @@ export function effectiveCommandCwd(workspace: string, cwdArg: unknown): string
|
|
|
357
357
|
if (dir === null || !insideWorkspace(dir, workspace)) return null
|
|
358
358
|
return dir
|
|
359
359
|
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* A subcommand that adds nothing to the command it accompanies: `cd` into a
|
|
363
|
+
* workspace directory, or a stdin filter (`head`/`tail` without operands, a
|
|
364
|
+
* non-recursive `grep` whose only operand is its pattern). Callers skip these
|
|
365
|
+
* only next to a sibling that is judged on its own, which already holds more
|
|
366
|
+
* capability than reading its own output.
|
|
367
|
+
*/
|
|
368
|
+
export function isNeutralShellSubcommand(command: string, workspace: string, runDir: string): boolean {
|
|
369
|
+
if (process.platform === "win32") return false
|
|
370
|
+
if (!command.trim() || SHELL_METACHARACTERS.test(command)) return false
|
|
371
|
+
const tokens = words(command.trim())
|
|
372
|
+
if (!tokens || tokens.length === 0 || tokens.some(token => token.unquotedExpansion)) return false
|
|
373
|
+
const name = tokens[0]!.text
|
|
374
|
+
const args = tokens.slice(1)
|
|
375
|
+
if (name === "cd") {
|
|
376
|
+
const target = args[0]?.text
|
|
377
|
+
if (args.length !== 1 || !target || target.startsWith("-") || target.startsWith("~") || target.includes("$")) return false
|
|
378
|
+
if (target.split(/[\\/]+/).includes("..")) return false
|
|
379
|
+
return effectiveCommandCwd(workspace, isAbsolute(target) ? target : join(runDir, target)) !== null
|
|
380
|
+
}
|
|
381
|
+
if (name !== "head" && name !== "tail" && name !== "grep") return false
|
|
382
|
+
if (!isReadOnlyCommand(command, runDir)) return false
|
|
383
|
+
const operands = parseArgs(args, SPECS[name]!)
|
|
384
|
+
if (operands === null) return false
|
|
385
|
+
if (name !== "grep") return operands.length === 0
|
|
386
|
+
// Conservative flag scan: any r/R or e letter in a short cluster counts.
|
|
387
|
+
const flags = args.filter(token => /^-[^-]/.test(token.text)).map(token => token.text)
|
|
388
|
+
if (flags.some(flag => /r/i.test(flag)) || args.some(token => token.text === "--recursive")) return false
|
|
389
|
+
return operands.length === (flags.some(flag => flag.includes("e")) ? 0 : 1)
|
|
390
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from "zod"
|
|
2
|
+
import type { Tool, ToolResult } from "../zapsdk/tools/types.js"
|
|
3
|
+
import { emptyToolEffects } from "../zapsdk/tools/effects.js"
|
|
4
|
+
import { CAPABILITY_KINDS, MAX_REQUESTED_CAPABILITIES, REQUEST_CAPABILITIES_TOOL, capabilityPattern, describeCapabilityPatterns, parseCapabilityRequest } from "./capabilities.js"
|
|
5
|
+
|
|
6
|
+
/** Asks the user up front for what a task will need. The Host decides: the
|
|
7
|
+
* approval prompt saves the requested capability rules for the session or
|
|
8
|
+
* project, and deny/ask rules keep precedence over them. */
|
|
9
|
+
export function requestCapabilitiesTool(granted: (args: Record<string, unknown>) => boolean): Tool {
|
|
10
|
+
return {
|
|
11
|
+
definition: {
|
|
12
|
+
name: REQUEST_CAPABILITIES_TOOL,
|
|
13
|
+
description: "Ask the user once, before multi-step work, for the file edits, network hosts or external systems it will need, so later calls run without interrupting them.",
|
|
14
|
+
prompt: "Use only when a task will clearly need several approvals of the same kind (for example edits under src/** plus requests to one API host). " +
|
|
15
|
+
"Request the narrowest scopes that cover the work. File scopes are project-relative globs; net scopes are hosts (shell network_destinations need net.write); external scopes are systems such as mcp:<server>. " +
|
|
16
|
+
"This cannot authorize shell commands or running outside the sandbox. If the user declines, continue with ordinary per-call approval or ask them.",
|
|
17
|
+
parameters: z.object({
|
|
18
|
+
capabilities: z.array(z.object({
|
|
19
|
+
kind: z.enum(CAPABILITY_KINDS as [string, ...string[]]),
|
|
20
|
+
scope: z.string().min(1).max(200),
|
|
21
|
+
})).min(1).max(MAX_REQUESTED_CAPABILITIES),
|
|
22
|
+
reason: z.string().min(1).max(300).describe("What the task is and why it needs these capabilities"),
|
|
23
|
+
}),
|
|
24
|
+
permission: "confirm",
|
|
25
|
+
// Changes Host authorization state, so it is never read-only.
|
|
26
|
+
resolveEffects: () => ({ ...emptyToolEffects(), external: [{ kind: "external", system: "zapcode:permissions", operation: "mutate" }] }),
|
|
27
|
+
},
|
|
28
|
+
handler: async (args): Promise<ToolResult> => {
|
|
29
|
+
const requested = parseCapabilityRequest(args)
|
|
30
|
+
if (typeof requested === "string") return { success: false, output: "", error: requested }
|
|
31
|
+
const described = describeCapabilityPatterns(requested.map(capability => capabilityPattern(capability.kind, capability.scope)))
|
|
32
|
+
return granted(args)
|
|
33
|
+
? { success: true, output: `Granted: ${described}. Calls within these capabilities run without asking; deny/ask rules still apply and anything else still asks.` }
|
|
34
|
+
: { success: true, output: `Approved without saving: ${described}. Matching calls may still ask.` }
|
|
35
|
+
},
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/singletons.ts
CHANGED
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
AgentLogger,
|
|
16
16
|
} from "../zapsdk/index.js"
|
|
17
17
|
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
18
|
-
import {
|
|
18
|
+
import { detectProviders, type DetectedProvider } from "../zapsdk/builtin-tools/index.js"
|
|
19
19
|
import { TaskStore } from "../zapsdk/tasks/store.js"
|
|
20
20
|
import { buildTaskNotificationXml, classifyTaskExit } from "../zapsdk/tasks/notification.js"
|
|
21
21
|
import { pushSystemEvent } from "./queue/systemInbox.js"
|
|
@@ -106,17 +106,9 @@ export const tokenAccounting = {
|
|
|
106
106
|
promptOverhead: 0,
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
//
|
|
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
|
|
109
|
+
// Single shared TaskStore — bash background commands and the task_* tools
|
|
117
110
|
// register and look up tasks here so the UI gets a unified view.
|
|
118
111
|
export const taskStore = new TaskStore({ projectCwd: process.cwd() })
|
|
119
|
-
export const monitorHandle = monitorTool({ store: taskStore })
|
|
120
112
|
|
|
121
113
|
// ─── Task-completion → systemInbox bridge ───
|
|
122
114
|
// When a background task exits, build a `<task-notification>` XML payload
|
|
@@ -142,15 +134,13 @@ taskStore.on("exited", (e) => {
|
|
|
142
134
|
})
|
|
143
135
|
|
|
144
136
|
// ─── Process shutdown cleanup ───
|
|
145
|
-
// Kill every still-running
|
|
146
|
-
// processes orphaned.
|
|
147
|
-
// process; calling stop() is belt-and-suspenders.
|
|
137
|
+
// Kill every still-running background command so Ctrl-C doesn't leave
|
|
138
|
+
// processes orphaned.
|
|
148
139
|
let _shutdownRan = false
|
|
149
140
|
function _shutdown(): void {
|
|
150
141
|
if (_shutdownRan) return
|
|
151
142
|
_shutdownRan = true
|
|
152
143
|
try { taskStore.stopAll("SIGTERM") } catch {}
|
|
153
|
-
try { cronHandle.stop() } catch {}
|
|
154
144
|
}
|
|
155
145
|
process.on("exit", _shutdown)
|
|
156
146
|
const shutdownOnInterrupt = () => { _shutdown(); process.exit(130) }
|
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 { type PermissionRule } from "./permissions.js"
|
|
3
|
+
import { WORKSPACE_EDIT_TOOLS, type PermissionRule } from "./permissions.js"
|
|
4
4
|
import { canonicalizeWithNearestExistingAncestorSync } from "../zapsdk/builtin-tools/filesystem.js"
|
|
5
5
|
|
|
6
6
|
export interface ToolGrantRequest {
|
|
@@ -11,7 +11,7 @@ export interface ToolGrantRequest {
|
|
|
11
11
|
|
|
12
12
|
export const FILE_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "search_files", "glob_files", "write_file", "create_file", "edit_file", "multi_edit", "delete_file", "move_file"]
|
|
13
13
|
export const READ_GRANT_TOOLS = ["read_file", "list_tree", "read_document", "search_files", "glob_files"]
|
|
14
|
-
export const EDIT_GRANT_TOOLS = [
|
|
14
|
+
export const EDIT_GRANT_TOOLS = [...WORKSPACE_EDIT_TOOLS]
|
|
15
15
|
|
|
16
16
|
function expandDirectory(value: string): string {
|
|
17
17
|
return value === "~" ? homedir() : value.startsWith("~/") ? join(homedir(), value.slice(2)) : value
|
|
@@ -27,7 +27,8 @@ import { useHideNativeCursor } from "./dialog-frame.js"
|
|
|
27
27
|
import { c } from "./theme.js"
|
|
28
28
|
import { ToolGrantDialog } from "./dialog-tool-grant.js"
|
|
29
29
|
import { suggestToolGrantDirectory, type ToolGrantRequest } from "../tool-grants.js"
|
|
30
|
-
import type
|
|
30
|
+
import { inferPattern, type PermissionRule } from "../permissions.js"
|
|
31
|
+
import { REQUEST_CAPABILITIES_TOOL, describeCapabilityPatterns } from "../capabilities.js"
|
|
31
32
|
import { formatToolCall, getToolAlias } from "./transcript-format.js"
|
|
32
33
|
|
|
33
34
|
export type ApprovalChoice = "once" | "always" | "forever" | "deny"
|
|
@@ -47,6 +48,8 @@ interface Props {
|
|
|
47
48
|
rulePreview?: string | null
|
|
48
49
|
unsandboxed?: boolean
|
|
49
50
|
allowScope?: boolean
|
|
51
|
+
/** One-time approvals of the same consent earlier this session. */
|
|
52
|
+
repeats?: number
|
|
50
53
|
availableTools?: string[]
|
|
51
54
|
cwd?: string
|
|
52
55
|
workspaceRoot?: string
|
|
@@ -58,7 +61,7 @@ interface Option {
|
|
|
58
61
|
label: string
|
|
59
62
|
}
|
|
60
63
|
|
|
61
|
-
export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, availableTools = [], cwd, workspaceRoot, onGrant }: Props) {
|
|
64
|
+
export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed: escape, allowScope = true, repeats = 0, availableTools = [], cwd, workspaceRoot, onGrant }: Props) {
|
|
62
65
|
useHideNativeCursor()
|
|
63
66
|
// Three accept tiers ("once" / session-scoped "always" / persistent
|
|
64
67
|
// "forever") + deny. Both persistent consent and ordinary tool grants
|
|
@@ -66,13 +69,21 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
66
69
|
// When rulePreview is provided, surface the actual saved pattern in
|
|
67
70
|
// both "always" and "forever" labels so the user sees the literal
|
|
68
71
|
// glob/prefix rather than a vague "in this session/project".
|
|
69
|
-
const
|
|
72
|
+
const capabilityText = rulePreview ? describeCapabilityPatterns(rulePreview.split(", ")) : null
|
|
73
|
+
const scopeText = capabilityText ?? (rulePreview
|
|
70
74
|
? rulePreview === toolName ? `${getToolAlias(toolName)} (entire tool)` : `${rulePreview}`
|
|
71
|
-
: `${getToolAlias(toolName)} commands`
|
|
75
|
+
: `${getToolAlias(toolName)} commands`)
|
|
72
76
|
const unsandboxed = escape ?? isUnsandboxedBash(toolName, args)
|
|
73
|
-
const
|
|
77
|
+
const request = toolName === REQUEST_CAPABILITIES_TOOL
|
|
78
|
+
const canCustomize = allowScope && !unsandboxed && !request && toolName !== "delegate_agent" && availableTools.includes(toolName) && !!onGrant
|
|
74
79
|
const directory = canCustomize ? suggestToolGrantDirectory(toolName, args, cwd) : undefined
|
|
75
|
-
|
|
80
|
+
// A capability request is only worth something when it is remembered.
|
|
81
|
+
const options: Option[] = request && allowScope ? [
|
|
82
|
+
{ value: "always", label: `Yes, allow ${scopeText} for this session` },
|
|
83
|
+
{ value: "forever", label: `Yes, allow ${scopeText} for this project` },
|
|
84
|
+
{ value: "deny", label: "No" },
|
|
85
|
+
]
|
|
86
|
+
: !allowScope
|
|
76
87
|
? [
|
|
77
88
|
{ value: "once", label: unsandboxed ? "Yes, run outside the sandbox this once" : "Yes, this once" },
|
|
78
89
|
{ value: "deny", label: "No" },
|
|
@@ -95,14 +106,14 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
95
106
|
useInput((input, key) => {
|
|
96
107
|
if (input === "g" && canCustomize) { setDirectoryShortcut(false); setCustomizing(true); return }
|
|
97
108
|
if (input === "d" && directory) { setDirectoryShortcut(true); setCustomizing(true); return }
|
|
98
|
-
const directChoice = approvalChoiceForInput(input, key, idx, allowScope)
|
|
109
|
+
const directChoice = approvalChoiceForInput(input, key, idx, allowScope, options.map(option => option.value))
|
|
99
110
|
if (directChoice) { onChoose(directChoice); return }
|
|
100
111
|
if (key.upArrow) { setIdx(i => (i - 1 + options.length) % options.length); return }
|
|
101
112
|
if (key.downArrow) { setIdx(i => (i + 1) % options.length); return }
|
|
102
113
|
}, { isActive: !(customizing && canCustomize) })
|
|
103
114
|
|
|
104
115
|
if (customizing && canCustomize && onGrant) return <ToolGrantDialog availableTools={availableTools} initialTools={[toolName]}
|
|
105
|
-
initialPattern={rulePreview?.match(/^[^(]+\(([^()]*)\)$/)?.[1] ?? ""}
|
|
116
|
+
initialPattern={(capabilityText ? inferPattern(toolName, args, workspaceRoot ?? cwd ?? process.cwd()) : rulePreview)?.match(/^[^(]+\(([^()]*)\)$/)?.[1] ?? ""}
|
|
106
117
|
initialDirectory={directory} directoryShortcut={directoryShortcut} cwd={workspaceRoot}
|
|
107
118
|
onSave={(request, reviewedRules) => onGrant(request, availableTools, reviewedRules)} onCancel={() => setCustomizing(false)} />
|
|
108
119
|
|
|
@@ -121,6 +132,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
121
132
|
{toolName === "bash" && ([ ["read_paths", "Additional read access"], ["write_paths", "Additional write access"] ] as const).map(([field, label]) =>
|
|
122
133
|
Array.isArray(args[field]) && args[field].length > 0
|
|
123
134
|
? <Text key={field} color={c.warning}>{label}: {JSON.stringify(args[field])}</Text> : null)}
|
|
135
|
+
{request && typeof args.reason === "string" && <Text color={c.text.secondary} wrap="truncate-end">{`Reason: ${args.reason.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")}`}</Text>}
|
|
124
136
|
{unsandboxed && <Text color={c.error}>Runs outside the OS sandbox: full access to your files and network.</Text>}
|
|
125
137
|
<Text color={c.warning} bold>Approve?</Text>
|
|
126
138
|
<Box flexDirection="column">
|
|
@@ -136,6 +148,7 @@ export function ApprovalBar({ toolName, args, onChoose, rulePreview, unsandboxed
|
|
|
136
148
|
)
|
|
137
149
|
})}
|
|
138
150
|
</Box>
|
|
151
|
+
{allowScope && !unsandboxed && !request && repeats >= 2 && <Text color={c.text.muted}>{`Approved ${repeats} times this session; 2 stops asking for the rest of it`}</Text>}
|
|
139
152
|
{canCustomize && <Text color={c.text.muted}>g customize scope / select tools</Text>}
|
|
140
153
|
{directory && <Text color={c.text.muted}>d authorize folder / select tools: {directory}</Text>}
|
|
141
154
|
</Box>
|
|
@@ -151,9 +164,9 @@ export function approvalChoiceForInput(
|
|
|
151
164
|
key: { escape?: boolean; return?: boolean },
|
|
152
165
|
selectedIndex: number,
|
|
153
166
|
allowScope = true,
|
|
167
|
+
choices: readonly ApprovalChoice[] = allowScope ? APPROVAL_CHOICES : ["once", "deny"],
|
|
154
168
|
): ApprovalChoice | null {
|
|
155
169
|
if (key.escape) return "deny"
|
|
156
|
-
const choices: ApprovalChoice[] = allowScope ? APPROVAL_CHOICES : ["once", "deny"]
|
|
157
170
|
const prefix = commandInput(input, key)
|
|
158
171
|
if (prefix !== null && /^[1-9]$/.test(prefix)) return choices[Number(prefix) - 1] ?? null
|
|
159
172
|
if (isReturnInput(input, key)) return choices[selectedIndex] ?? null
|
package/src/ui/dialog-config.tsx
CHANGED
|
@@ -26,10 +26,10 @@ interface DialogProps {
|
|
|
26
26
|
|
|
27
27
|
// ── Mode picker ──────────────────────────────────────────────────────────
|
|
28
28
|
const MODES: { id: PermissionMode; label: string; meta: string }[] = [
|
|
29
|
-
{ id: "default", label: "default", meta: "ask before write/edit/exec" },
|
|
30
|
-
{ id: "acceptEdits", label: "acceptEdits", meta: "auto-approve file edits" },
|
|
29
|
+
{ id: "default", label: "default", meta: "strict: ask before write/edit/exec" },
|
|
30
|
+
{ id: "acceptEdits", label: "acceptEdits", meta: "balanced: auto-approve file edits" },
|
|
31
31
|
{ id: "plan", label: "plan", meta: "research only — no edits or commands" },
|
|
32
|
-
{ id: "bypassPermissions", label: "bypassPermissions", meta: "auto-approve everything (use with care)" },
|
|
32
|
+
{ id: "bypassPermissions", label: "bypassPermissions", meta: "autonomous: auto-approve everything (use with care)" },
|
|
33
33
|
]
|
|
34
34
|
|
|
35
35
|
export function ModeDialog({ config, onCommit, onCancel }: DialogProps) {
|
|
@@ -24,6 +24,7 @@ import { truncateToWidth } from "./truncate.js"
|
|
|
24
24
|
import { ToolGrantDialog } from "./dialog-tool-grant.js"
|
|
25
25
|
import { buildToolGrantRules } from "../tool-grants.js"
|
|
26
26
|
import { commandInput } from "./controlled-input.js"
|
|
27
|
+
import { describeCapabilityPatterns } from "../capabilities.js"
|
|
27
28
|
|
|
28
29
|
interface Props { onCancel: () => void; availableTools: string[] }
|
|
29
30
|
|
|
@@ -182,6 +183,7 @@ export function PermissionsDialog({ onCancel, availableTools }: Props) {
|
|
|
182
183
|
{truncateToWidth(rule.pattern, 60)}
|
|
183
184
|
</Text>
|
|
184
185
|
{rule.canonicalPath && <Text color={c.text.ghost}> (fixed folder target)</Text>}
|
|
186
|
+
{describeCapabilityPatterns([rule.pattern]) && <Text color={c.text.ghost} wrap="truncate-end"> — {describeCapabilityPatterns([rule.pattern])}</Text>}
|
|
185
187
|
{shadowedBy && (
|
|
186
188
|
<Text color={c.text.ghost} wrap="truncate-end">
|
|
187
189
|
{truncateToWidth(` ⤴ shadowed by ${shadowedBy.rule.type} ${shadowedBy.rule.pattern} (${shadowedBy.scope})`, 70)}
|
package/src/ui/dialog-rewind.tsx
CHANGED
|
@@ -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
|
|
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 > …) are not tracked.</Text>
|
|
158
158
|
</Box>
|
|
159
159
|
)}
|
package/zapsdk/agent/loop.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { normalizeAssistantText } from "./output-text.js";
|
|
|
8
8
|
import { earliestDeadlineAt } from "../execution/deadline.js";
|
|
9
9
|
import { toolOutputTool } from "../builtin-tools/tool-output.js";
|
|
10
10
|
import { assembleSubagentTool } from "./subagent-assembly.js";
|
|
11
|
-
import { type TaskDecompositionMode, primaryArgSig, stepSignature, createRunToolExecutionHooks, isRepeatFriendlyStep, isLiveTaskWait, progressPollSignature } from "./tool-execution-guards.js";
|
|
11
|
+
import { type TaskDecompositionMode, primaryArgSig, stepSignature, createRunToolExecutionHooks, duplicateQueryKey, isDuplicateQuery, isRepeatFriendlyStep, isLiveTaskWait, progressPollSignature } from "./tool-execution-guards.js";
|
|
12
12
|
import type { LLMProvider, LLMCallOptions } from "../core/llm.js";
|
|
13
13
|
import { hasMeaningfulOutput } from "../core/provider-request.js";
|
|
14
14
|
import { assertProviderRequestAllowed } from "../core/provider-deadline.js";
|
|
@@ -962,6 +962,10 @@ export class LoopAgent {
|
|
|
962
962
|
} else {
|
|
963
963
|
localMessages = msgs;
|
|
964
964
|
}
|
|
965
|
+
// Pruning and compaction shorten earlier results. A duplicate notice
|
|
966
|
+
// must never point the model at output it can no longer see.
|
|
967
|
+
seenFiles.clear();
|
|
968
|
+
toolExecutionHooks.forgetObservations();
|
|
965
969
|
};
|
|
966
970
|
this.recoveryContext = (requestMessages) => {
|
|
967
971
|
let revision: string | undefined;
|
|
@@ -2486,7 +2490,9 @@ export class LoopAgent {
|
|
|
2486
2490
|
seenFiles: SeenFiles,
|
|
2487
2491
|
success: boolean,
|
|
2488
2492
|
): { content: string; suppression?: "duplicate" } {
|
|
2489
|
-
if (!toolCall.name.includes("read_file") && toolCall.name !== "pr_file_content")
|
|
2493
|
+
if (!toolCall.name.includes("read_file") && toolCall.name !== "pr_file_content") {
|
|
2494
|
+
return this.deduplicateQuery(toolCall, resultContent, seenFiles, success);
|
|
2495
|
+
}
|
|
2490
2496
|
if (!(toolCall.arguments as any).path && !(toolCall.arguments as any).ref) return { content: resultContent };
|
|
2491
2497
|
|
|
2492
2498
|
const filePath = String((toolCall.arguments as any).path ?? (toolCall.arguments as any).ref ?? "");
|
|
@@ -2507,6 +2513,36 @@ export class LoopAgent {
|
|
|
2507
2513
|
return { content: resultContent };
|
|
2508
2514
|
}
|
|
2509
2515
|
|
|
2516
|
+
/** Fold a repeated search or read-only shell query whose output has not
|
|
2517
|
+
* changed. The query has already run, so a change made outside the agent's
|
|
2518
|
+
* tools still reaches the model. */
|
|
2519
|
+
private deduplicateQuery(
|
|
2520
|
+
toolCall: ToolCallRequest,
|
|
2521
|
+
resultContent: string,
|
|
2522
|
+
seenFiles: SeenFiles,
|
|
2523
|
+
success: boolean,
|
|
2524
|
+
): { content: string; suppression?: "duplicate" } {
|
|
2525
|
+
const args = (toolCall.arguments ?? {}) as Record<string, unknown>;
|
|
2526
|
+
if (!isDuplicateQuery(toolCall.name, args)) return { content: resultContent };
|
|
2527
|
+
const key = duplicateQueryKey(toolCall.name, args);
|
|
2528
|
+
if (!success) {
|
|
2529
|
+
seenFiles.delete(key);
|
|
2530
|
+
return { content: resultContent };
|
|
2531
|
+
}
|
|
2532
|
+
const contentHash = createHash("sha256").update(resultContent).digest("hex");
|
|
2533
|
+
if (seenFiles.get(key) === contentHash) {
|
|
2534
|
+
const target = primaryArgSig(toolCall.name, args) || "the same arguments";
|
|
2535
|
+
this.emitter.emit({ type: "observation", kind: "duplicate_tool_suppressed", detail: { tool: toolCall.name, target } });
|
|
2536
|
+
return {
|
|
2537
|
+
content: `[Duplicate ${toolCall.name} suppressed for ${target}. It returned the same output as the previous call; ` +
|
|
2538
|
+
"reuse that result and choose the next concrete action.]",
|
|
2539
|
+
suppression: "duplicate",
|
|
2540
|
+
};
|
|
2541
|
+
}
|
|
2542
|
+
seenFiles.set(key, contentHash);
|
|
2543
|
+
return { content: resultContent };
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2510
2546
|
/** Append error classification hints or system notices to the result content. */
|
|
2511
2547
|
private classifyError(
|
|
2512
2548
|
toolCall: ToolCallRequest,
|
|
@@ -2515,12 +2551,23 @@ export class LoopAgent {
|
|
|
2515
2551
|
resultContent: string,
|
|
2516
2552
|
): string {
|
|
2517
2553
|
if (result.success) {
|
|
2518
|
-
|
|
2554
|
+
// A successful change to the workspace makes every earlier failure
|
|
2555
|
+
// worth retrying: rerunning tests after an edit is not a blind retry.
|
|
2556
|
+
const readOnly = this.executor.workspaceGate
|
|
2557
|
+
? !!result.runtime?.effects && isEffectivelyReadOnly(result.runtime.effects)
|
|
2558
|
+
: this.executor.isReadOnly(toolCall.name, toolCall.arguments);
|
|
2559
|
+
if (readOnly) errorTracker.delete(toolCall.name);
|
|
2560
|
+
else errorTracker.clear();
|
|
2519
2561
|
return resultContent;
|
|
2520
2562
|
}
|
|
2521
2563
|
if (!result.error) return resultContent;
|
|
2522
2564
|
|
|
2523
|
-
|
|
2565
|
+
// Count only the identical call failing identically. Error headers such as
|
|
2566
|
+
// "Command failed: <cmd> … Message: <first line>" repeat across different
|
|
2567
|
+
// test failures, so the whole observation is part of the signature.
|
|
2568
|
+
const errorSig = createHash("sha256")
|
|
2569
|
+
.update(JSON.stringify([toolCall.arguments ?? {}, result.error, result.output ?? ""]))
|
|
2570
|
+
.digest("hex");
|
|
2524
2571
|
if (!errorTracker.has(toolCall.name)) errorTracker.set(toolCall.name, new Map());
|
|
2525
2572
|
const toolErrors = errorTracker.get(toolCall.name)!;
|
|
2526
2573
|
const count = (toolErrors.get(errorSig) ?? 0) + 1;
|
|
@@ -2,7 +2,6 @@ import type { ToolResult } from "../tools/types.js";
|
|
|
2
2
|
import type { ToolExecutor } from "../tools/executor.js";
|
|
3
3
|
import type { ToolExecutionHooks } from "./streaming-tool-executor.js";
|
|
4
4
|
import { operationFailure } from "../execution/failure.js";
|
|
5
|
-
import { isEffectivelyReadOnly } from "../tools/effects.js";
|
|
6
5
|
import { canonicalizeJsonSchema } from "../tools/schema.js";
|
|
7
6
|
import { sliceHeadCodePoints } from "../utils/logical-lines.js";
|
|
8
7
|
import { createHash } from "node:crypto";
|
|
@@ -103,11 +102,11 @@ const READ_ONLY_GIT_SUBCOMMANDS = new Set([
|
|
|
103
102
|
|
|
104
103
|
/**
|
|
105
104
|
* The shell tool declares a conservative read+write effect because arbitrary
|
|
106
|
-
* shell is impossible to prove safe. For duplicate
|
|
105
|
+
* shell is impossible to prove safe. For duplicate folding we can still
|
|
107
106
|
* recognise a deliberately tiny subset of inspection commands. This is not
|
|
108
|
-
* a permission decision: it
|
|
109
|
-
*
|
|
110
|
-
*
|
|
107
|
+
* a permission decision: it only lets an identical repeated result be folded.
|
|
108
|
+
* Anything involving shell composition or a potentially writing flag is never
|
|
109
|
+
* folded.
|
|
111
110
|
*/
|
|
112
111
|
function isMemoizableBashQuery(args: Record<string, unknown>): boolean {
|
|
113
112
|
if (args.run_in_background === true || typeof args.command !== "string") return false;
|
|
@@ -146,7 +145,11 @@ function isMemoizableBashQuery(args: Record<string, unknown>): boolean {
|
|
|
146
145
|
return true;
|
|
147
146
|
}
|
|
148
147
|
|
|
149
|
-
|
|
148
|
+
/** Local queries whose identical repeated output may be folded into a pointer
|
|
149
|
+
* to the earlier result. They still execute: a file can change outside the
|
|
150
|
+
* agent's own tools (the user's editor, a background job), and only the fresh
|
|
151
|
+
* output can show that. */
|
|
152
|
+
export function isDuplicateQuery(name: string, args: Record<string, unknown>): boolean {
|
|
150
153
|
return DUPLICATE_QUERY_TOOLS.has(name) || (name === "bash" && isMemoizableBashQuery(args));
|
|
151
154
|
}
|
|
152
155
|
|
|
@@ -160,7 +163,7 @@ function httpFetchKey(name: string, args: Record<string, unknown>): string | und
|
|
|
160
163
|
return `${method} ${args.url}${args.raw === true ? " raw" : ""}`;
|
|
161
164
|
}
|
|
162
165
|
|
|
163
|
-
function duplicateQueryKey(name: string, args: Record<string, unknown>): string {
|
|
166
|
+
export function duplicateQueryKey(name: string, args: Record<string, unknown>): string {
|
|
164
167
|
return `${name}:${JSON.stringify(canonicalizeJsonSchema(args))}`;
|
|
165
168
|
}
|
|
166
169
|
|
|
@@ -220,22 +223,28 @@ function taskPlanRequiredResult(mode: TaskDecompositionMode): ToolResult {
|
|
|
220
223
|
};
|
|
221
224
|
}
|
|
222
225
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
226
|
+
export interface RunToolExecutionHooks extends ToolExecutionHooks {
|
|
227
|
+
/** Forget fetched pages once history is rewritten: their results may have
|
|
228
|
+
* been compacted away, so "reuse that result" would point at nothing. */
|
|
229
|
+
forgetObservations(): void;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Reuse a recent remote fetch instead of repeating it. Local reads and
|
|
233
|
+
* searches are not suppressed here; LoopAgent folds an identical result after
|
|
234
|
+
* it runs. */
|
|
228
235
|
export function createRunToolExecutionHooks(
|
|
229
236
|
executor: ToolExecutor,
|
|
230
237
|
onSuppressed: (name: string, args: Record<string, unknown>) => void,
|
|
231
238
|
taskDecomposition: TaskDecompositionMode,
|
|
232
239
|
hasTodoTool: boolean,
|
|
233
|
-
):
|
|
234
|
-
const completedOrInFlight = new Set<string>();
|
|
240
|
+
): RunToolExecutionHooks {
|
|
235
241
|
// Remote GETs do not depend on the workspace, so a mutation must not forget them.
|
|
236
242
|
const fetchedUrls = new Map<string, number>();
|
|
237
243
|
const planState: TaskPlanGateState = { ready: false, baselineReads: 0 };
|
|
238
244
|
return {
|
|
245
|
+
forgetObservations() {
|
|
246
|
+
fetchedUrls.clear();
|
|
247
|
+
},
|
|
239
248
|
beforeExecute(name, args) {
|
|
240
249
|
// Planning is not a permission boundary. Only an explicitly required
|
|
241
250
|
// plan may block execution; auto must not turn a short task into retries.
|
|
@@ -265,20 +274,7 @@ export function createRunToolExecutionHooks(
|
|
|
265
274
|
);
|
|
266
275
|
}
|
|
267
276
|
fetchedUrls.set(fetchKey, Date.now());
|
|
268
|
-
return undefined;
|
|
269
|
-
}
|
|
270
|
-
if (!isDuplicateQuery(name, args)) return undefined;
|
|
271
|
-
const key = duplicateQueryKey(name, args);
|
|
272
|
-
if (completedOrInFlight.has(key)) {
|
|
273
|
-
onSuppressed(name, args);
|
|
274
|
-
const target = primaryArgSig(name, args) || "the same arguments";
|
|
275
|
-
return duplicateSuppression(
|
|
276
|
-
`[Duplicate ${name} suppressed for ${target}. ` +
|
|
277
|
-
"Reuse the previous result; the workspace has not changed since it was returned. " +
|
|
278
|
-
"Choose the next concrete action instead of reading/searching it again.]",
|
|
279
|
-
);
|
|
280
277
|
}
|
|
281
|
-
completedOrInFlight.add(key);
|
|
282
278
|
return undefined;
|
|
283
279
|
},
|
|
284
280
|
afterExecute(name, args, result) {
|
|
@@ -287,19 +283,9 @@ export function createRunToolExecutionHooks(
|
|
|
287
283
|
if (!result.success) fetchedUrls.delete(fetchedKey);
|
|
288
284
|
return;
|
|
289
285
|
}
|
|
290
|
-
if (isDuplicateQuery(name, args)) {
|
|
291
|
-
if (!result.success) completedOrInFlight.delete(duplicateQueryKey(name, args));
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
286
|
if (name === "todo_write" && result.success) {
|
|
295
287
|
planState.ready = true;
|
|
296
288
|
}
|
|
297
|
-
const readOnly = executor.workspaceGate
|
|
298
|
-
? !!result.runtime?.effects && isEffectivelyReadOnly(result.runtime.effects)
|
|
299
|
-
: executor.isReadOnly(name, args);
|
|
300
|
-
if (result.success && !readOnly) {
|
|
301
|
-
completedOrInFlight.clear();
|
|
302
|
-
}
|
|
303
289
|
},
|
|
304
290
|
};
|
|
305
291
|
}
|
|
@@ -43,6 +43,9 @@ export interface ExecuteCommandOptions {
|
|
|
43
43
|
workspaceOnly?: boolean;
|
|
44
44
|
/** Expose destination declarations for a restricted execution backend. */
|
|
45
45
|
restrictedNetwork?: boolean;
|
|
46
|
+
/** The host sandbox filters egress through an allowlist: offer
|
|
47
|
+
* network_destinations for other hosts, which the host approves. */
|
|
48
|
+
declaredNetwork?: boolean;
|
|
46
49
|
/** Offer the per-call `dangerouslyDisableSandbox` retry. Defaults to true;
|
|
47
50
|
* hosts set false when a backend (VM) or policy has no sandbox escape. */
|
|
48
51
|
allowUnsandboxed?: boolean;
|
|
@@ -196,6 +199,12 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
196
199
|
.max(128)
|
|
197
200
|
.optional()
|
|
198
201
|
.describe("Exact HTTP(S) URLs, domains, or wildcard subdomains requested by this command; subject to the execution backend's network policy"),
|
|
202
|
+
} : options.declaredNetwork ? {
|
|
203
|
+
network_destinations: z
|
|
204
|
+
.array(z.string().min(1).max(253))
|
|
205
|
+
.max(16)
|
|
206
|
+
.optional()
|
|
207
|
+
.describe("Hosts outside the sandbox network allowlist this command must reach (api.example.com or *.example.com); each needs approval once"),
|
|
199
208
|
} : {}),
|
|
200
209
|
});
|
|
201
210
|
|
|
@@ -245,6 +254,12 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
245
254
|
"No sleep/ps polling. Exit sends a <task-notification>. For logs, use task_status: task_id with include_output=true (tail) or output_offset=0 (pages). outputFile grants no read_file access. Wait only for dependencies.",
|
|
246
255
|
]
|
|
247
256
|
: [];
|
|
257
|
+
if (options.declaredNetwork) {
|
|
258
|
+
promptLines.push(
|
|
259
|
+
"",
|
|
260
|
+
"Sandboxed network reaches an allowlist (package registries, git hosts, common CDNs). For another host, declare it in network_destinations; the user approves each host once and the command stays sandboxed. Do not use dangerouslyDisableSandbox for network access.",
|
|
261
|
+
);
|
|
262
|
+
}
|
|
248
263
|
if (options.restrictedNetwork) {
|
|
249
264
|
promptLines.push(
|
|
250
265
|
"",
|
|
@@ -294,7 +309,7 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
294
309
|
(args.cwd as string | undefined) ?? options.defaultCwd ?? context.cwd,
|
|
295
310
|
options.defaultCwd ?? context.cwd,
|
|
296
311
|
);
|
|
297
|
-
const declaredDestinations = options.restrictedNetwork
|
|
312
|
+
const declaredDestinations = (options.restrictedNetwork || options.declaredNetwork)
|
|
298
313
|
&& Array.isArray((args as { network_destinations?: unknown }).network_destinations)
|
|
299
314
|
? ((args as { network_destinations: string[] }).network_destinations)
|
|
300
315
|
: [];
|
|
@@ -305,10 +320,11 @@ export function executeCommandTool(options: ExecuteCommandOptions = {}): Tool {
|
|
|
305
320
|
{ kind: "filesystem", operation: "read", paths: [accessRoot, ...((args.read_paths ?? []) as string[]).map(path => resolveToolPathCanonical(path, cwd))] },
|
|
306
321
|
{ kind: "filesystem", operation: "modify", paths: [accessRoot, ...((args.write_paths ?? []) as string[]).map(path => resolveToolPathCanonical(path, cwd))] },
|
|
307
322
|
],
|
|
308
|
-
network: declaredDestinations.length > 0
|
|
323
|
+
network: options.restrictedNetwork && declaredDestinations.length > 0
|
|
309
324
|
? [{ kind: "network", operation: "connect", destinations: declaredDestinations, methods: [] }]
|
|
310
325
|
: options.sandboxNetwork === true
|
|
311
|
-
|
|
326
|
+
// The proxy still filters "*" through its allowlist; declared hosts extend it.
|
|
327
|
+
? [{ kind: "network", operation: "connect", destinations: ["*", ...declaredDestinations], methods: [] }]
|
|
312
328
|
: [],
|
|
313
329
|
process: [{
|
|
314
330
|
kind: "process",
|
|
@@ -185,6 +185,9 @@ async function fetchWithValidatedRedirects(
|
|
|
185
185
|
request = { ...request, method: "GET", body: null, headers };
|
|
186
186
|
}
|
|
187
187
|
const next = await assertSafePublicHttpUrl(new URL(location, current).toString(), options.resolveHostname);
|
|
188
|
+
// Consent is per host: a body approved for one host is never replayed to
|
|
189
|
+
// another. Return the redirect itself instead of following it.
|
|
190
|
+
if (next.host !== current.host && request.body != null) return { response, finalUrl: current };
|
|
188
191
|
if (next.origin !== current.origin) {
|
|
189
192
|
// Fetch drops Authorization on cross-origin redirects; never hand caller
|
|
190
193
|
// credentials to a host the caller did not name. Not restored on return.
|