zapagent 1.14.11 → 1.14.13
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/bundled-dependencies.json +201 -201
- package/package.json +1 -1
- package/src/agent-factory.ts +6 -3
- package/src/commands/dispatcher.ts +10 -0
- package/src/commands.ts +4 -0
- package/src/execution-environment.ts +1 -1
- package/src/goal-command.ts +173 -0
- package/src/goal-host.ts +408 -0
- package/src/goal-runner.ts +31 -0
- package/src/headless/goal-npm-install.ts +96 -0
- package/src/headless/goalPhase.ts +380 -0
- package/src/headless/runHeadless.ts +56 -4
- package/src/hooks/useTurnDispatcher.ts +3 -0
- package/src/index.tsx +17 -0
- package/src/ui/slash-palette.tsx +1 -0
- package/zapsdk/agent/loop.ts +13 -2
- package/zapsdk/agent/subagent-assembly.ts +5 -0
- package/zapsdk/agent/tool-execution-guards.ts +30 -17
- package/zapsdk/builtin-tools/command.ts +11 -0
- package/zapsdk/builtin-tools/subagent.ts +10 -3
- package/zapsdk/core/llm.ts +2 -0
- package/zapsdk/core/retry.ts +3 -0
- package/zapsdk/execution/broker.ts +18 -1
- package/zapsdk/execution/goal-workspace-gate.ts +95 -0
- package/zapsdk/execution/required-process-seal.ts +35 -0
- package/zapsdk/execution/types.ts +8 -0
- package/zapsdk/execution/workspace-runtime.ts +6 -0
- package/zapsdk/execution/zapvm.ts +117 -15
- package/zapsdk/goal/acceptance.ts +139 -0
- package/zapsdk/goal/budget.ts +406 -0
- package/zapsdk/goal/contracts.ts +93 -0
- package/zapsdk/goal/controller.ts +234 -0
- package/zapsdk/goal/errors.ts +17 -0
- package/zapsdk/goal/git-history-snapshot.ts +210 -0
- package/zapsdk/goal/git-operation-owner.ts +64 -0
- package/zapsdk/goal/metered-provider.ts +80 -0
- package/zapsdk/goal/npm-installer.ts +362 -0
- package/zapsdk/goal/scheduler.ts +34 -0
- package/zapsdk/goal/store.ts +173 -0
- package/zapsdk/goal/structured-output.ts +84 -0
- package/zapsdk/goal/workspace-broker.ts +11 -0
- package/zapsdk/goal/workspace.ts +425 -0
- package/zapsdk/policy/types.ts +4 -0
- package/zapsdk/runtime/factory.ts +7 -0
- package/zapsdk/scheduler/batch-scheduler.ts +2 -2
- package/zapsdk/tools/executor.ts +79 -6
- package/zapsdk/tools/types.ts +2 -0
- package/zapsdk/workspace/context.ts +8 -4
- package/zapsdk/workspace/copy.ts +14 -1
- package/zapsdk/workspace/manager.ts +67 -3
- package/zapsdk/workspace/types.ts +11 -0
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { spawn } from "node:child_process"
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
3
|
+
import { lstatSync, realpathSync } from "node:fs"
|
|
4
|
+
import { dirname, isAbsolute, relative, sep } from "node:path"
|
|
5
|
+
import { join } from "node:path"
|
|
6
|
+
import { fileURLToPath } from "node:url"
|
|
7
|
+
import type { PermissionMode } from "../config.js"
|
|
8
|
+
import type { HeadlessFormatter, RunSummary } from "./formatter.js"
|
|
9
|
+
import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
|
|
10
|
+
import { GoalBudgetLedger, type GoalBudgetRole } from "../../zapsdk/goal/budget.js"
|
|
11
|
+
import { GoalPhaseError, goalPhaseFailureCode } from "../../zapsdk/goal/errors.js"
|
|
12
|
+
import { meterGoalProvider } from "../../zapsdk/goal/metered-provider.js"
|
|
13
|
+
import { getAppDataDir } from "../../zapsdk/utils/platform.js"
|
|
14
|
+
import type { AgentEvent } from "../../zapsdk/agent/events.js"
|
|
15
|
+
import { isHostDuplicateSuppression } from "../../zapsdk/agent/tool-execution-guards.js"
|
|
16
|
+
import type { Tool, ToolResult } from "../../zapsdk/tools/types.js"
|
|
17
|
+
import type { PrivateGitBinding } from "../../zapsdk/workspace/types.js"
|
|
18
|
+
import { privateGitWriteRoot } from "../../zapsdk/execution/workspace-runtime.js"
|
|
19
|
+
|
|
20
|
+
export function makeGoalMachineToolReadOnly(tool: Tool): Tool {
|
|
21
|
+
const resolveEffects = tool.definition.resolveEffects!
|
|
22
|
+
return { ...tool, definition: { ...tool.definition, resolveEffects: (args, context) => {
|
|
23
|
+
const effects = resolveEffects(args, context)
|
|
24
|
+
return { ...effects, filesystem: effects.filesystem.filter(effect => effect.operation === "read"), workspace: { mode: "shared-readonly" } }
|
|
25
|
+
} } }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A failed receipt cannot be erased by a later successful model response. */
|
|
29
|
+
export class GoalPhaseSealTracker {
|
|
30
|
+
private unsealed = false
|
|
31
|
+
private readonly pendingMutations = new Set<string>()
|
|
32
|
+
markUnsealed(): void { this.unsealed = true }
|
|
33
|
+
observe(event: AgentEvent, shellEnabled: boolean): void {
|
|
34
|
+
if (event.type === "content_final" && (event.kind === "tool_call" || event.kind === "tool_result") &&
|
|
35
|
+
["agent", "merge_agent_artifacts", "write_file", "edit_file", "multi_edit", "delete_file", "move_file"].includes(event.toolName)) {
|
|
36
|
+
const key = JSON.stringify([event.path ?? [], event.id])
|
|
37
|
+
if (event.kind === "tool_call") this.pendingMutations.add(key)
|
|
38
|
+
if (event.kind === "tool_result") {
|
|
39
|
+
this.pendingMutations.delete(key)
|
|
40
|
+
if (!event.result.success) this.unsealed = true
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (shellEnabled && event.type === "content_final" && event.kind === "tool_result" && event.toolName === "bash"
|
|
44
|
+
&& !isHostDuplicateSuppression(event.result)
|
|
45
|
+
&& event.result.runtime?.processSeal?.state !== "sealed") this.unsealed = true
|
|
46
|
+
}
|
|
47
|
+
assertSealed(): void { if (this.unsealed || this.pendingMutations.size) throw new Error("GOAL_SEAL_UNCONFIRMED") }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** These local tools do not launch opaque model requests. */
|
|
51
|
+
const GOAL_TOOLS = new Set([
|
|
52
|
+
"read_file", "write_file", "edit_file", "multi_edit", "delete_file", "move_file",
|
|
53
|
+
"list_tree", "read_document", "read_pdf", "read_docx",
|
|
54
|
+
"read_tool_output", "todo_write", "current_time",
|
|
55
|
+
])
|
|
56
|
+
const READ_ONLY_GOAL_TOOLS = new Set([
|
|
57
|
+
"read_file", "list_tree", "read_document", "read_pdf", "read_docx",
|
|
58
|
+
"read_tool_output", "current_time",
|
|
59
|
+
])
|
|
60
|
+
|
|
61
|
+
export interface GoalPhaseInput {
|
|
62
|
+
cwd: string
|
|
63
|
+
prompt: string
|
|
64
|
+
goalId: string
|
|
65
|
+
epoch: number
|
|
66
|
+
role: GoalBudgetRole
|
|
67
|
+
ledgerPath: string
|
|
68
|
+
/** Host-created private clone identity; never model supplied. */
|
|
69
|
+
privateGit?: PrivateGitBinding
|
|
70
|
+
privateGitOwnerDirectory?: string
|
|
71
|
+
permissionMode?: PermissionMode
|
|
72
|
+
signal?: AbortSignal
|
|
73
|
+
machineCheck?: "bun" | "npm" | "pytest" | "go"
|
|
74
|
+
dependencyInstall?: "npm"
|
|
75
|
+
/** Host must durably record ownership synchronously before input is sent. */
|
|
76
|
+
onSpawn?: (pid: number, mayLaunchSealedProcess: boolean) => void
|
|
77
|
+
/** Called only after the owned process group has ceased to exist. */
|
|
78
|
+
onStopped?: (pid: number) => void
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type WorkerInput = Omit<GoalPhaseInput, "signal" | "onSpawn" | "onStopped"> & { allowSealedShell?: boolean }
|
|
82
|
+
type WorkerResult = { type: "result"; summary: RunSummary; exitCode: number; processSealed: true; toolCalls: number; failureCode?: string; dependencyHash?: string } | { type: "machine"; result: ToolResult } | { type: "fatal"; message: string; code: string }
|
|
83
|
+
|
|
84
|
+
/** Check only concrete existing directories. A Host-owned ledger must not sit
|
|
85
|
+
* underneath a model-writable workspace. */
|
|
86
|
+
function validateInput(input: WorkerInput): void {
|
|
87
|
+
if (!input || typeof input !== "object" || !isAbsolute(input.cwd) || !isAbsolute(input.ledgerPath)
|
|
88
|
+
|| typeof input.prompt !== "string" || !input.prompt.trim() || input.prompt.length > 1024 * 1024
|
|
89
|
+
|| typeof input.goalId !== "string" || !input.goalId || !Number.isSafeInteger(input.epoch) || input.epoch < 0
|
|
90
|
+
|| !["planner", "worker", "verifier", "repair", "maintenance", "finalization"].includes(input.role)
|
|
91
|
+
|| input.machineCheck !== undefined && (input.role !== "verifier" || !["bun", "npm", "pytest", "go"].includes(input.machineCheck))
|
|
92
|
+
|| input.dependencyInstall !== undefined && (input.dependencyInstall !== "npm" || !(["worker", "repair"].includes(input.role) || input.role === "verifier" && input.machineCheck === "npm"))
|
|
93
|
+
|| input.permissionMode !== undefined && !["default", "acceptEdits", "bypassPermissions", "plan"].includes(input.permissionMode)) throw new Error("Invalid Goal phase input")
|
|
94
|
+
const workspace = realpathSync(input.cwd), ledgerDir = realpathSync(dirname(input.ledgerPath))
|
|
95
|
+
if (input.privateGit) {
|
|
96
|
+
if (!["worker", "repair"].includes(input.role) || typeof input.privateGit.directory !== "string"
|
|
97
|
+
|| typeof input.privateGit.device !== "string" || typeof input.privateGit.inode !== "string" || typeof input.privateGitOwnerDirectory !== "string" || !isAbsolute(input.privateGitOwnerDirectory)) throw new Error("Invalid Goal private Git binding")
|
|
98
|
+
privateGitWriteRoot({ root: workspace, mode: "isolated-write", privateGitDirectory: input.privateGit.directory,
|
|
99
|
+
privateGitIdentity: { device: input.privateGit.device, inode: input.privateGit.inode } })
|
|
100
|
+
}
|
|
101
|
+
const rel = relative(workspace, ledgerDir)
|
|
102
|
+
if (!rel || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel))) throw new Error("Goal ledger must be outside the writable workspace")
|
|
103
|
+
const ledgerStat = lstatSync(input.ledgerPath)
|
|
104
|
+
if (!ledgerStat.isFile() || ledgerStat.isSymbolicLink()) throw new Error("Goal ledger must be an existing regular file")
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Execute one phase in a fresh process. The process cwd is established before
|
|
108
|
+
* importing the headless Runtime's cwd-bound singleton modules. */
|
|
109
|
+
async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult> {
|
|
110
|
+
const { signal, onSpawn, onStopped, ...workerInput } = input
|
|
111
|
+
validateInput(workerInput)
|
|
112
|
+
signal?.throwIfAborted()
|
|
113
|
+
// Decide before recording ownership and sending the worker any input. A
|
|
114
|
+
// configuration change later cannot turn on shell in this phase.
|
|
115
|
+
const [{ loadAppConfig }, { createExecutionEnvironment, resolveExecutionBackend }] = await Promise.all([
|
|
116
|
+
import("../config.js"), import("../execution-environment.js"),
|
|
117
|
+
])
|
|
118
|
+
const config = loadAppConfig(join(getAppDataDir(), "config.json"))
|
|
119
|
+
const environment = createExecutionEnvironment(input.cwd, "required", resolveExecutionBackend(config.executionBackend), false, config.sandboxNetwork, [])
|
|
120
|
+
const allowSealedShell = (input.role === "worker" || input.role === "repair" || !!input.machineCheck || !!input.dependencyInstall)
|
|
121
|
+
&& environment.broker.supportsProcessSeal?.({ name: "bash", executionLocation: "workspace" }) === true
|
|
122
|
+
if (input.machineCheck && !allowSealedShell) throw new Error("GOAL_VERIFIER_PROCESS_SEAL_UNSUPPORTED")
|
|
123
|
+
if (input.dependencyInstall && !allowSealedShell) throw new Error("GOAL_NPM_PROCESS_SEAL_UNSUPPORTED")
|
|
124
|
+
const safeEnvironment = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")))
|
|
125
|
+
const isBun = /(?:^|[\\/])bun(?:\.exe)?$/i.test(process.execPath)
|
|
126
|
+
const argv = isBun ? [fileURLToPath(new URL("../index.tsx", import.meta.url)), "--goal-phase-worker"] : ["--goal-phase-worker"]
|
|
127
|
+
const child = spawn(process.execPath, argv, {
|
|
128
|
+
cwd: dirname(workerInput.ledgerPath),
|
|
129
|
+
detached: process.platform !== "win32",
|
|
130
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
131
|
+
env: { ...safeEnvironment, PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ZAPCODE_DEVTOOLS_PORT: "", ZAPCODE_HOST_PROTOCOL_PORT: "" },
|
|
132
|
+
})
|
|
133
|
+
let output = "", cancelled = false, spawnRecorded = false, protocolError: Error | undefined, spawnError: unknown
|
|
134
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
135
|
+
let pipeTimer: ReturnType<typeof setTimeout> | undefined
|
|
136
|
+
const killGroup = (signalName: NodeJS.Signals) => {
|
|
137
|
+
if (process.platform !== "win32" && child.pid) {
|
|
138
|
+
try { process.kill(-child.pid, signalName); return } catch { /* process may already be gone */ }
|
|
139
|
+
}
|
|
140
|
+
try { child.kill(signalName) } catch { /* process may already be gone */ }
|
|
141
|
+
}
|
|
142
|
+
const abort = () => {
|
|
143
|
+
cancelled = true
|
|
144
|
+
killGroup("SIGINT")
|
|
145
|
+
killTimer ??= setTimeout(() => killGroup("SIGKILL"), 3000)
|
|
146
|
+
}
|
|
147
|
+
const completion = new Promise<number | null>((resolve, reject) => {
|
|
148
|
+
child.once("error", reject)
|
|
149
|
+
child.once("close", code => resolve(code))
|
|
150
|
+
})
|
|
151
|
+
// A descendant may retain stdout after its worker exits. Terminate the
|
|
152
|
+
// remaining process group and fail closed if any pipe still stays open.
|
|
153
|
+
child.once("exit", () => {
|
|
154
|
+
if (!child.pid || !goalPhaseGroupAlive(child.pid)) return
|
|
155
|
+
killGroup("SIGTERM")
|
|
156
|
+
killTimer ??= setTimeout(() => killGroup("SIGKILL"), 1000)
|
|
157
|
+
pipeTimer = setTimeout(() => {
|
|
158
|
+
protocolError = new Error("GOAL_SEAL_UNCONFIRMED")
|
|
159
|
+
child.stdout.destroy()
|
|
160
|
+
child.stderr.destroy()
|
|
161
|
+
}, 5000)
|
|
162
|
+
})
|
|
163
|
+
signal?.addEventListener("abort", abort, { once: true })
|
|
164
|
+
if (signal?.aborted) abort()
|
|
165
|
+
child.stdout.setEncoding("utf8")
|
|
166
|
+
child.stdout.on("data", (chunk: string) => {
|
|
167
|
+
output += chunk
|
|
168
|
+
if (Buffer.byteLength(output) > 16 * 1024 * 1024 && !protocolError) {
|
|
169
|
+
protocolError = new Error("Goal phase output exceeds protocol limit")
|
|
170
|
+
abort()
|
|
171
|
+
}
|
|
172
|
+
})
|
|
173
|
+
child.stderr.setEncoding("utf8")
|
|
174
|
+
child.stderr.on("data", () => {})
|
|
175
|
+
child.stdin.on("error", () => {})
|
|
176
|
+
try {
|
|
177
|
+
try {
|
|
178
|
+
if (!child.pid) throw new Error("Goal phase worker has no pid")
|
|
179
|
+
onSpawn?.(child.pid, allowSealedShell)
|
|
180
|
+
spawnRecorded = true
|
|
181
|
+
child.stdin.end(JSON.stringify({ ...workerInput, allowSealedShell }))
|
|
182
|
+
} catch (error) {
|
|
183
|
+
spawnError = error
|
|
184
|
+
abort()
|
|
185
|
+
child.stdin.end()
|
|
186
|
+
}
|
|
187
|
+
const exitCode = await completion
|
|
188
|
+
const pid = child.pid
|
|
189
|
+
if (!pid || process.platform === "win32") throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
190
|
+
if (goalPhaseGroupAlive(pid)) {
|
|
191
|
+
killGroup("SIGTERM")
|
|
192
|
+
killTimer ??= setTimeout(() => killGroup("SIGKILL"), 1000)
|
|
193
|
+
const deadline = Date.now() + 5000
|
|
194
|
+
while (goalPhaseGroupAlive(pid) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 50))
|
|
195
|
+
}
|
|
196
|
+
if (goalPhaseGroupAlive(pid)) throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
197
|
+
if (!allowSealedShell && spawnRecorded) onStopped?.(pid)
|
|
198
|
+
if (spawnError) throw spawnError
|
|
199
|
+
if (protocolError) throw protocolError
|
|
200
|
+
if (cancelled) throw new Error("GOAL_PHASE_CANCELLED")
|
|
201
|
+
let response: WorkerResult
|
|
202
|
+
try { response = JSON.parse(output) as WorkerResult } catch { throw new Error(`Goal phase process returned invalid output (exit ${exitCode})`) }
|
|
203
|
+
if (response.type === "fatal") throw new GoalPhaseError(response.code ?? goalPhaseFailureCode(response.message))
|
|
204
|
+
if (response.type === "machine") {
|
|
205
|
+
if (!input.machineCheck || exitCode !== 0 || response.result.runtime?.processSeal?.state !== "sealed") throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
206
|
+
if (allowSealedShell) onStopped?.(pid)
|
|
207
|
+
return response
|
|
208
|
+
}
|
|
209
|
+
if (response.type !== "result" || !response.summary?.outcome) throw new Error(`Goal phase produced no structured outcome (exit ${exitCode})`)
|
|
210
|
+
// A failed model call can still finish with every tool/process sealed.
|
|
211
|
+
// Only this worker-owned receipt, never model text, may clear ownership.
|
|
212
|
+
if (response.processSealed !== true) throw new GoalPhaseError("GOAL_SEAL_UNCONFIRMED")
|
|
213
|
+
if (allowSealedShell) onStopped?.(pid)
|
|
214
|
+
if (exitCode !== 0 || response.exitCode !== 0 || response.summary.outcome.execution.status !== "finished") {
|
|
215
|
+
throw new GoalPhaseError(response.failureCode ?? "GOAL_PHASE_FAILED")
|
|
216
|
+
}
|
|
217
|
+
return response
|
|
218
|
+
} finally {
|
|
219
|
+
signal?.removeEventListener("abort", abort)
|
|
220
|
+
if (killTimer) clearTimeout(killTimer)
|
|
221
|
+
if (pipeTimer) clearTimeout(pipeTimer)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export async function runGoalPhase(input: GoalPhaseInput): Promise<{ text: string; outcome: AgentOutcomeV1; toolCalls: number; dependencyHash?: string }> {
|
|
226
|
+
const response = await runGoalPhaseProcess(input)
|
|
227
|
+
if (response.type !== "result" || !response.summary.outcome) throw new Error("Unexpected Goal phase response")
|
|
228
|
+
return { text: response.summary.text, outcome: response.summary.outcome, toolCalls: response.toolCalls, ...(response.dependencyHash ? { dependencyHash: response.dependencyHash } : {}) }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export async function runGoalMachinePhase(input: GoalPhaseInput & { machineCheck: "bun" | "npm" | "pytest" | "go" }): Promise<ToolResult> {
|
|
232
|
+
const response = await runGoalPhaseProcess(input)
|
|
233
|
+
if (response.type !== "machine") throw new Error("Unexpected Goal machine response")
|
|
234
|
+
return response.result
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** A persisted pid is only a process-group liveness probe; the Host must
|
|
238
|
+
* separately validate ownership and PID reuse before taking recovery action. */
|
|
239
|
+
export function goalPhaseGroupAlive(pid: number): boolean {
|
|
240
|
+
if (!Number.isSafeInteger(pid) || pid < 1 || process.platform === "win32") return true
|
|
241
|
+
try { process.kill(-pid, 0); return true }
|
|
242
|
+
catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH" }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Internal CLI worker. The input comes from the trusted controller over
|
|
246
|
+
* stdin, not from the model, and is not passed in argv or environment. */
|
|
247
|
+
export async function runGoalPhaseWorker(): Promise<number> {
|
|
248
|
+
let raw = ""
|
|
249
|
+
try {
|
|
250
|
+
for await (const chunk of process.stdin) {
|
|
251
|
+
raw += chunk.toString()
|
|
252
|
+
if (Buffer.byteLength(raw) > 2 * 1024 * 1024) throw new Error("Goal phase input exceeds protocol limit")
|
|
253
|
+
}
|
|
254
|
+
const input = JSON.parse(raw) as WorkerInput
|
|
255
|
+
validateInput(input)
|
|
256
|
+
process.chdir(input.cwd)
|
|
257
|
+
delete process.env.ZAPCODE_DEVTOOLS_PORT
|
|
258
|
+
delete process.env.ZAPCODE_HOST_PROTOCOL_PORT
|
|
259
|
+
// Import only after chdir: session, memory and checkpoint singletons bind cwd.
|
|
260
|
+
const [{ runHeadless }, { loadAppConfig }, { configPath }] = await Promise.all([import("./runHeadless.js"), import("../config.js"), import("../session.js")])
|
|
261
|
+
const { createExecutionEnvironment, resolveExecutionBackend } = await import("../execution-environment.js")
|
|
262
|
+
const ledger = new GoalBudgetLedger(input.ledgerPath)
|
|
263
|
+
try {
|
|
264
|
+
const snapshot = ledger.snapshot(input.goalId)
|
|
265
|
+
if (snapshot.epoch !== input.epoch) throw new Error("Stale Goal phase epoch")
|
|
266
|
+
const config = { ...loadAppConfig(configPath), allowUnsandboxedCommands: false, sandboxExcludedCommands: [] }
|
|
267
|
+
const environment = createExecutionEnvironment(input.cwd, "required", resolveExecutionBackend(config.executionBackend), false, config.sandboxNetwork, [])
|
|
268
|
+
const canSeal = input.allowSealedShell === true && environment.broker.supportsProcessSeal?.({ name: "bash", executionLocation: "workspace" }) === true
|
|
269
|
+
let dependencyProof: import("./goal-npm-install.js").GoalNpmInstallProof | undefined
|
|
270
|
+
const childDependencyProofs = new Map<string, import("./goal-npm-install.js").GoalNpmInstallProof>()
|
|
271
|
+
if (input.dependencyInstall) {
|
|
272
|
+
if (!canSeal) throw new Error("GOAL_NPM_PROCESS_SEAL_UNSUPPORTED")
|
|
273
|
+
const { installGoalNpmDependencies } = await import("./goal-npm-install.js")
|
|
274
|
+
dependencyProof = await installGoalNpmDependencies({ cwd: input.cwd, ledger, goalId: input.goalId, epoch: input.epoch, role: input.role, config })
|
|
275
|
+
}
|
|
276
|
+
if (input.machineCheck) {
|
|
277
|
+
if (!canSeal) throw new Error("GOAL_VERIFIER_PROCESS_SEAL_UNSUPPORTED")
|
|
278
|
+
const [{ ToolRegistry }, { ToolExecutor }, { executeCommandTool }, { requireProcessSealing }] = await Promise.all([
|
|
279
|
+
import("../../zapsdk/tools/registry.js"), import("../../zapsdk/tools/executor.js"),
|
|
280
|
+
import("../../zapsdk/builtin-tools/command.js"), import("../../zapsdk/execution/required-process-seal.js"),
|
|
281
|
+
])
|
|
282
|
+
const registry = new ToolRegistry()
|
|
283
|
+
const commandTool = executeCommandTool({ ...environment.commandOptions, defaultCwd: input.cwd, timeoutMs: 120_000,
|
|
284
|
+
disableBackgroundTasks: true, allowUnsandboxed: false, sandboxNetwork: false, restrictedNetwork: false, workspaceOnly: true })
|
|
285
|
+
registry.register(makeGoalMachineToolReadOnly(commandTool))
|
|
286
|
+
let unsealed = false
|
|
287
|
+
const executor = new ToolExecutor(registry, { cwd: input.cwd, onApproval: async () => true,
|
|
288
|
+
executionBroker: requireProcessSealing(environment.broker, () => { unsealed = true }) })
|
|
289
|
+
const command = { bun: "bun test", npm: "npm test", pytest: "python3 -m pytest", go: "go test ./..." }[input.machineCheck]
|
|
290
|
+
const result = await executor.execute("bash", { command })
|
|
291
|
+
if (unsealed || result.runtime?.processSeal?.state !== "sealed") throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
292
|
+
process.stdout.write(JSON.stringify({ type: "machine", result } satisfies WorkerResult))
|
|
293
|
+
return 0
|
|
294
|
+
}
|
|
295
|
+
const mode = input.permissionMode ?? config.permissionMode
|
|
296
|
+
const readOnly = input.role === "planner" || input.role === "verifier" || input.role === "finalization"
|
|
297
|
+
const canDelegate = canSeal && !readOnly
|
|
298
|
+
const strictOpaque = snapshot.limits.strict !== false && [snapshot.limits.maxTokens, snapshot.limits.maxCostMicro,
|
|
299
|
+
snapshot.limits.maxModelCalls, snapshot.limits.maxProviderAttempts, snapshot.limits.maxSpawns].some(value => value !== undefined)
|
|
300
|
+
const permitted = (name: string) => {
|
|
301
|
+
// A sandboxed shell can still fork and setsid, escaping the process
|
|
302
|
+
// group we can seal. Fail closed until the host owns a process-tree
|
|
303
|
+
// containment primitive (e.g. a job object or equivalent).
|
|
304
|
+
if (["delegate_agent", "cron_create", "monitor", "http_request"].includes(name)) return false
|
|
305
|
+
if (name === "agent" || name === "merge_agent_artifacts") return canDelegate
|
|
306
|
+
if (name === "bash") return canSeal && !readOnly
|
|
307
|
+
if (readOnly) return READ_ONLY_GOAL_TOOLS.has(name) || (!strictOpaque && name === "http_fetch")
|
|
308
|
+
return GOAL_TOOLS.has(name) || (!strictOpaque && name === "http_fetch")
|
|
309
|
+
}
|
|
310
|
+
let summary: RunSummary | undefined
|
|
311
|
+
let failure: { code: string; message: string } | undefined
|
|
312
|
+
let toolCalls = 0
|
|
313
|
+
let runtimeError = ""
|
|
314
|
+
let permissionDenied = false
|
|
315
|
+
let unavailableTool = false
|
|
316
|
+
const sealTracker = new GoalPhaseSealTracker()
|
|
317
|
+
const formatter: HeadlessFormatter = {
|
|
318
|
+
init() {}, onEvent(event) {
|
|
319
|
+
if (event.type === "content_final" && event.kind === "tool_call" && !permitted(event.toolName)) unavailableTool = true
|
|
320
|
+
if (event.type === "content_final" && event.kind === "tool_call") toolCalls++
|
|
321
|
+
if (event.type === "error") runtimeError = event.error
|
|
322
|
+
sealTracker.observe(event, permitted("bash"))
|
|
323
|
+
}, progress() {},
|
|
324
|
+
finalize(value) { summary = value },
|
|
325
|
+
failure(value) { failure = value },
|
|
326
|
+
}
|
|
327
|
+
const exitCode = await runHeadless({
|
|
328
|
+
prompt: input.prompt, permissionMode: mode, outputFormat: "json", resultSchema: "outcome-v1",
|
|
329
|
+
continueOnToolDenial: false, continueLast: false, cwd: input.cwd, quiet: true,
|
|
330
|
+
dangerouslyDisableOsSandbox: false, noDevtools: true,
|
|
331
|
+
}, {
|
|
332
|
+
config, formatter, disableSubagent: !canDelegate, disableShellNetwork: true, requireProcessSeal: canSeal, isolateWorkspace: true, privateGit: input.privateGit, privateGitOwnerDirectory: input.privateGitOwnerDirectory, serializeSubagent: canDelegate,
|
|
333
|
+
...(canDelegate ? { subagentIsolationRoot: join(input.privateGitOwnerDirectory ?? dirname(input.ledgerPath), "child-workspaces", createHash("sha256").update(input.goalId).digest("hex")) } : {}),
|
|
334
|
+
...(input.dependencyInstall ? { prepareSubagentWorkspace: async (cwd: string, signal?: AbortSignal) => {
|
|
335
|
+
const { installGoalNpmDependencies } = await import("./goal-npm-install.js")
|
|
336
|
+
childDependencyProofs.set(cwd, await installGoalNpmDependencies({ cwd, ledger, goalId: input.goalId, epoch: input.epoch, role: input.role, config, signal }))
|
|
337
|
+
}, validateSubagentWorkspace: async (cwd: string) => {
|
|
338
|
+
const proof = childDependencyProofs.get(cwd)
|
|
339
|
+
if (!proof) throw new Error("GOAL_NPM_INSTALLATION_EVIDENCE_MISSING")
|
|
340
|
+
const { assertGoalNpmDependenciesUnchanged } = await import("./goal-npm-install.js")
|
|
341
|
+
await assertGoalNpmDependenciesUnchanged(cwd, proof)
|
|
342
|
+
childDependencyProofs.delete(cwd)
|
|
343
|
+
} } : {}),
|
|
344
|
+
disableRepoMap: true,
|
|
345
|
+
onProcessSealUnconfirmed: () => sealTracker.markUnsealed(),
|
|
346
|
+
onPermissionDenied: () => { permissionDenied = true },
|
|
347
|
+
providerAdapter: provider => meterGoalProvider(provider, ledger, { goalId: input.goalId, epoch: input.epoch, role: input.role,
|
|
348
|
+
scope: { providerId: config.active.providerId, modelId: config.active.model } }),
|
|
349
|
+
prepareRegistry: async registry => {
|
|
350
|
+
for (const definition of registry.definitions()) if (!permitted(definition.name)) registry.unregister(definition.name)
|
|
351
|
+
},
|
|
352
|
+
admitToolExecution: name => {
|
|
353
|
+
if (!permitted(name)) throw new Error("GOAL_UNMETERED_TOOL_UNAVAILABLE")
|
|
354
|
+
const admission = ledger.admit(input.goalId, input.epoch, { operationId: randomUUID(), role: input.role, kind: "tool",
|
|
355
|
+
opaque: !GOAL_TOOLS.has(name) && name !== "agent" && name !== "merge_agent_artifacts" && name !== "bash" })
|
|
356
|
+
if (!admission.ok) throw new Error(`Goal tool admission denied: ${admission.reason}`)
|
|
357
|
+
if (name === "agent") {
|
|
358
|
+
const spawnAdmission = ledger.admit(input.goalId, input.epoch, { operationId: randomUUID(), role: input.role, kind: "spawn" })
|
|
359
|
+
if (!spawnAdmission.ok) throw new Error(`Goal spawn admission denied: ${spawnAdmission.reason}`)
|
|
360
|
+
}
|
|
361
|
+
},
|
|
362
|
+
})
|
|
363
|
+
if (permissionDenied) throw new Error("GOAL_PHASE_PERMISSION_DENIED")
|
|
364
|
+
sealTracker.assertSealed()
|
|
365
|
+
if (dependencyProof) {
|
|
366
|
+
const { assertGoalNpmDependenciesUnchanged } = await import("./goal-npm-install.js")
|
|
367
|
+
await assertGoalNpmDependenciesUnchanged(input.cwd, dependencyProof)
|
|
368
|
+
}
|
|
369
|
+
if (unavailableTool) throw new Error("GOAL_UNMETERED_TOOL_UNAVAILABLE")
|
|
370
|
+
if (!summary) throw new Error(failure?.code ?? `Headless phase failed (${exitCode})`)
|
|
371
|
+
process.stdout.write(JSON.stringify({ type: "result", summary, exitCode, processSealed: true, toolCalls,
|
|
372
|
+
...(exitCode !== 0 ? { failureCode: goalPhaseFailureCode(runtimeError || summary.error || summary.outcome?.execution.error?.code || "") } : {}), dependencyHash: dependencyProof?.dependencyHash } satisfies WorkerResult))
|
|
373
|
+
return exitCode
|
|
374
|
+
} finally { ledger.close() }
|
|
375
|
+
} catch (error) {
|
|
376
|
+
const message = error instanceof Error ? error.message : "Unknown Goal phase failure"
|
|
377
|
+
process.stdout.write(JSON.stringify({ type: "fatal", message: goalPhaseFailureCode(message), code: goalPhaseFailureCode(message) } satisfies WorkerResult))
|
|
378
|
+
return 2
|
|
379
|
+
}
|
|
380
|
+
}
|
|
@@ -2,6 +2,8 @@ import { connectLocalServiceOwner } from "../../zapsdk/services/local-owner.js"
|
|
|
2
2
|
import { createExecutionEnvironment, resolveExecutionBackend } from "../execution-environment.js"
|
|
3
3
|
import { executionExitCode, OutcomeProtocolError, type AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
|
|
4
4
|
import type { CompletionEvidenceProvider } from "../../zapsdk/harness/completion.js"
|
|
5
|
+
import type { LLMProvider } from "../../zapsdk/core/llm.js"
|
|
6
|
+
import { requireProcessSealing } from "../../zapsdk/execution/required-process-seal.js"
|
|
5
7
|
// Headless run loop. Loads config, builds an AgentRuntime (sharing the TUI's
|
|
6
8
|
// provider/registry/executor factory), wires the formatter to AgentEvent
|
|
7
9
|
// streams, and exits with a stop-reason-derived code.
|
|
@@ -15,6 +17,8 @@ import type { CompletionEvidenceProvider } from "../../zapsdk/harness/completion
|
|
|
15
17
|
// - no auto-compact reactive pause (we let it run silently)
|
|
16
18
|
|
|
17
19
|
import process from "node:process"
|
|
20
|
+
import { realpathSync } from "node:fs"
|
|
21
|
+
import type { PrivateGitBinding } from "../../zapsdk/workspace/types.js"
|
|
18
22
|
import { join } from "node:path"
|
|
19
23
|
import { createBoundedRepairSession, type BoundedRepairResult } from "../../zapsdk/runtime/bounded-repair.js"
|
|
20
24
|
import type { CreateAgentRuntimeOptions } from "../../zapsdk/runtime/factory.js"
|
|
@@ -273,9 +277,30 @@ export interface HeadlessHost {
|
|
|
273
277
|
onSealing?: () => void
|
|
274
278
|
sealingTimeoutMs?: number
|
|
275
279
|
getPermissionMode?: () => HeadlessArgs["permissionMode"]
|
|
280
|
+
/** Host workflows must not mistake a denied operation for successful work. */
|
|
281
|
+
onPermissionDenied?: (toolName: string, reason: string) => void
|
|
276
282
|
images?: ImageContent[]
|
|
277
283
|
strictResume?: boolean
|
|
278
284
|
prepareRegistry?: (registry: ToolRegistry) => Promise<void>
|
|
285
|
+
/** Trusted Host instrumentation, applied inside RetryProvider. */
|
|
286
|
+
providerAdapter?: (provider: LLMProvider) => LLMProvider
|
|
287
|
+
admitToolExecution?: (toolName: string) => void
|
|
288
|
+
/** Host-controlled admission may require prohibiting unmetered child agents. */
|
|
289
|
+
disableSubagent?: boolean
|
|
290
|
+
/** Host-owned isolation root for workflows requiring fenced child workspaces. */
|
|
291
|
+
subagentIsolationRoot?: string
|
|
292
|
+
/** Enforce the workspace boundary even in permissive approval modes. */
|
|
293
|
+
isolateWorkspace?: boolean
|
|
294
|
+
privateGit?: PrivateGitBinding
|
|
295
|
+
privateGitOwnerDirectory?: string
|
|
296
|
+
serializeSubagent?: boolean
|
|
297
|
+
prepareSubagentWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>
|
|
298
|
+
validateSubagentWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>
|
|
299
|
+
/** Require an OS sandbox with no network grant and workspace-only shell paths. */
|
|
300
|
+
disableShellNetwork?: boolean
|
|
301
|
+
requireProcessSeal?: boolean
|
|
302
|
+
onProcessSealUnconfirmed?: () => void
|
|
303
|
+
disableRepoMap?: boolean
|
|
279
304
|
}
|
|
280
305
|
|
|
281
306
|
export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}): Promise<number> {
|
|
@@ -404,6 +429,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
404
429
|
disallowedTools: args.disallowedTools,
|
|
405
430
|
onDeny: (tool, reason) => {
|
|
406
431
|
formatter.progress(`✗ denied ${getToolAlias(tool)}: ${reason}`)
|
|
432
|
+
host.onPermissionDenied?.(tool, reason)
|
|
407
433
|
},
|
|
408
434
|
onDecision: (tool, decision, reason) => {
|
|
409
435
|
if (args.outputFormat === "stream-json" && !host.formatter) {
|
|
@@ -456,6 +482,17 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
456
482
|
executionEnvironment = createExecutionEnvironment(cwd, "required", "local", false, config.sandboxNetwork, config.sandboxExcludedCommands, owner)
|
|
457
483
|
} catch { process.stderr.write("Invalid, unavailable or incompatible Host service owner.\n"); return EXIT_BAD_ARGS }
|
|
458
484
|
}
|
|
485
|
+
if (host.disableShellNetwork) {
|
|
486
|
+
if (args.serviceOwner || args.dangerouslyDisableOsSandbox || process.env.ZAPCODE_RESIDENT_AGENT === "1") {
|
|
487
|
+
throw new Error("Goal offline shell requires the local OS sandbox")
|
|
488
|
+
}
|
|
489
|
+
executionEnvironment = createExecutionEnvironment(cwd, "required", resolveExecutionBackend(config.executionBackend), false, config.sandboxNetwork, [])
|
|
490
|
+
executionEnvironment.commandOptions.sandboxNetwork = false
|
|
491
|
+
executionEnvironment.commandOptions.restrictedNetwork = false
|
|
492
|
+
executionEnvironment.commandOptions.workspaceOnly = true
|
|
493
|
+
executionEnvironment.commandOptions.disableBackgroundTasks = true
|
|
494
|
+
if (host.requireProcessSeal) executionEnvironment.broker = requireProcessSealing(executionEnvironment.broker, host.onProcessSealUnconfirmed)
|
|
495
|
+
}
|
|
459
496
|
const { provider: llmProvider, registry, executor: baseExecutor, createRegistryForCwd, executionFacts, executionCapacity, sandboxConfined } = buildAgentObjects(
|
|
460
497
|
config,
|
|
461
498
|
approval.onApproval,
|
|
@@ -470,6 +507,8 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
470
507
|
formatter.onEvent(event)
|
|
471
508
|
host.onEvent?.(event)
|
|
472
509
|
},
|
|
510
|
+
/* askUserCallbacks */ undefined,
|
|
511
|
+
/* providerAdapter */ host.providerAdapter,
|
|
473
512
|
)
|
|
474
513
|
const deniedTools = new Set(args.disallowedTools ?? [])
|
|
475
514
|
const scopedExecutor = deniedTools.size ? baseExecutor.withRuntimePolicy({
|
|
@@ -477,7 +516,9 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
477
516
|
? approval.onApproval(request.call.name, request.call.arguments).then(() => ({ decision: "deny" as const, reason: "disallowed by --disallowed-tools" }))
|
|
478
517
|
: baseExecutor.policyEngine.evaluate(request),
|
|
479
518
|
}, baseExecutor.checkpointMode) : baseExecutor
|
|
480
|
-
const
|
|
519
|
+
const guardedExecutor = resultGuard ? scopedExecutor.withResultGuard(resultGuard) : scopedExecutor
|
|
520
|
+
const isolatedExecutor = host.isolateWorkspace ? guardedExecutor.withWorkspace({ root: realpathSync(cwd), mode: "isolated-write", sandbox: sandboxConfined ? "enforced" : "none", ...(host.privateGit ? { privateGitDirectory: host.privateGit.directory, privateGitIdentity: { device: host.privateGit.device, inode: host.privateGit.inode } } : {}) }) : guardedExecutor
|
|
521
|
+
const executor = host.admitToolExecution ? isolatedExecutor.withExecutionAdmission(host.admitToolExecution) : isolatedExecutor
|
|
481
522
|
approval.setSandboxConfined(sandboxConfined, config.autoAllowSandboxedCommands !== false)
|
|
482
523
|
approval.setSandboxExcludedCommands(config.allowUnsandboxedCommands !== false ? config.sandboxExcludedCommands : undefined)
|
|
483
524
|
await host.prepareRegistry?.(registry)
|
|
@@ -530,7 +571,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
530
571
|
contextWindow: ctxWin,
|
|
531
572
|
diagnosticsLogger: appLogger,
|
|
532
573
|
})
|
|
533
|
-
await buildRepoMapAttachment(cwd, args.prompt, ctxWin).then((repoMap) => {
|
|
574
|
+
if (!host.disableRepoMap) await buildRepoMapAttachment(cwd, args.prompt, ctxWin).then((repoMap) => {
|
|
534
575
|
attachments.repoMapAttachment = repoMap.text
|
|
535
576
|
attachments.repoMapIncluded = repoMap.selectedFiles
|
|
536
577
|
attachments.repoMapRevision = repoMap.revision
|
|
@@ -581,6 +622,8 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
581
622
|
},
|
|
582
623
|
workspace: {
|
|
583
624
|
root: cwd,
|
|
625
|
+
...(host.subagentIsolationRoot ? { tempRoot: host.subagentIsolationRoot, forbidGit: true, retention: false as const } : {}),
|
|
626
|
+
...(host.privateGit && host.privateGitOwnerDirectory ? { capturePrivateGitFromRoot: { ownerDirectory: host.privateGitOwnerDirectory, sourceBinding: host.privateGit } } : {}),
|
|
584
627
|
onTrackEdit: (paths) => checkpoint.trackEdits(paths),
|
|
585
628
|
},
|
|
586
629
|
loopAgent: {
|
|
@@ -606,14 +649,23 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
606
649
|
storageSessionId: getCurrentSessionId(),
|
|
607
650
|
storageProjectCwd: cwd,
|
|
608
651
|
sessionId: getCurrentSessionId(),
|
|
609
|
-
subagentFactory: publicChecks ? undefined :
|
|
652
|
+
subagentFactory: publicChecks || host.disableSubagent ? undefined : host.serializeSubagent ? options => {
|
|
653
|
+
const tool = subagentTool(options)
|
|
654
|
+
const resolveEffects = tool.definition.resolveEffects
|
|
655
|
+
return { ...tool, definition: { ...tool.definition, resolveEffects: (args, context) => {
|
|
656
|
+
const effects = resolveEffects!(args, context)
|
|
657
|
+
return { ...effects, workspace: { mode: "root-integration" as const } }
|
|
658
|
+
} } }
|
|
659
|
+
} : subagentTool,
|
|
610
660
|
},
|
|
611
|
-
subagent: publicChecks ? false : {
|
|
661
|
+
subagent: publicChecks || host.disableSubagent ? false : {
|
|
612
662
|
inheritedInstructions: [args.systemPromptPrepend, config.customSystemPrompt, args.systemPromptAppend]
|
|
613
663
|
.filter(text => text?.trim()).join("\n\n"),
|
|
614
664
|
onEvent: (event) => { formatter.onEvent(event); host.onEvent?.(event) },
|
|
615
665
|
createRegistryForCwd,
|
|
616
666
|
requireWriteIsolation: true,
|
|
667
|
+
prepareWorkspace: host.prepareSubagentWorkspace,
|
|
668
|
+
validateWorkspace: host.validateSubagentWorkspace,
|
|
617
669
|
},
|
|
618
670
|
onRunEnd: async () => {
|
|
619
671
|
observeLifecycle("checkpoint_started")
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { pauseGoalsForUserInput } from "../goal-command.js"
|
|
1
2
|
import { useCallback, useEffect, useRef } from "react"
|
|
2
3
|
import {
|
|
3
4
|
enqueue as enqueueCommand,
|
|
@@ -507,6 +508,8 @@ export function useTurnDispatcher(
|
|
|
507
508
|
|| hasPendingManualCompact(getQueueSnapshot(), opts.editingMessageId)
|
|
508
509
|
|
|
509
510
|
const submitCommand = (command: QueuedCommand, editVersion?: string): boolean => {
|
|
511
|
+
const interrupted = pauseGoalsForUserInput(process.cwd(), getMessageQueue().getSessionId(), command.text)
|
|
512
|
+
if (interrupted.length) addToast("Goal will pause at the next safe boundary · /goal resume to continue", { duration: 3500 })
|
|
510
513
|
if (opts.editingMessageId) {
|
|
511
514
|
if (!getMessageQueue().replace(opts.editingMessageId, command, editVersion)) {
|
|
512
515
|
addLog("error", "Queued message changed while editing; draft was kept.")
|
package/src/index.tsx
CHANGED
|
@@ -101,6 +101,23 @@ if (args[0] === "--acp-worker") {
|
|
|
101
101
|
const { runAcpWorker } = await import("./acp/worker.js")
|
|
102
102
|
process.exit(await runAcpWorker())
|
|
103
103
|
}
|
|
104
|
+
if (args[0] === "--goal-phase-worker") {
|
|
105
|
+
const { runGoalPhaseWorker } = await import("./headless/goalPhase.js")
|
|
106
|
+
process.exit(await runGoalPhaseWorker())
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (args[0] === "--goal-runner") {
|
|
110
|
+
if (args.length !== 2 || !args[1]) { process.stderr.write("Invalid Goal runner request\n"); process.exit(2) }
|
|
111
|
+
const { runGoalRunner } = await import("./goal-runner.js")
|
|
112
|
+
process.exit(await runGoalRunner(args[1]))
|
|
113
|
+
}
|
|
114
|
+
if (args[0] === "goal") {
|
|
115
|
+
const [{ goalCommand }, { loadAppConfig }, { getAppDataDir }] = await Promise.all([
|
|
116
|
+
import("./goal-command.js"), import("./config.js"), import("../zapsdk/utils/platform.js"),
|
|
117
|
+
])
|
|
118
|
+
try { process.stdout.write(goalCommand(args.slice(1), process.cwd(), loadAppConfig(join(getAppDataDir(), "config.json")).permissionMode) + "\n"); process.exit(0) }
|
|
119
|
+
catch (error) { process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); process.exit(1) }
|
|
120
|
+
}
|
|
104
121
|
|
|
105
122
|
const isHeadless = isHeadlessInvocation(args, process.stdin.isTTY)
|
|
106
123
|
|
package/src/ui/slash-palette.tsx
CHANGED
|
@@ -40,6 +40,7 @@ export const BUILTIN_COMMANDS: SlashEntry[] = [
|
|
|
40
40
|
{ name: "/review", desc: "Review code for bugs & security" },
|
|
41
41
|
{ name: "/commit", desc: "Stage changes and create a commit" },
|
|
42
42
|
{ name: "/init", desc: "Generate AGENTS.md for this project" },
|
|
43
|
+
{ name: "/goal", desc: "Verified Goal workflow · status | pause | resume | cancel | budget" },
|
|
43
44
|
{ name: "/supertask", desc: "Long-horizon orchestrated task · resume | abort | status | watch" },
|
|
44
45
|
{ name: "/exit", desc: "Quit zapAgent" },
|
|
45
46
|
]
|
package/zapsdk/agent/loop.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
import type { Tool, ToolDefinition, ToolResult } from "../tools/types.js";
|
|
23
23
|
import type { ToolRegistry } from "../tools/registry.js";
|
|
24
24
|
import { ToolExecutor, type ApprovalCallback, type PostProcessCallback, type ToolExecutorOptions } from "../tools/executor.js";
|
|
25
|
+
import { isEffectivelyReadOnly, unknownToolEffects } from "../tools/effects.js";
|
|
25
26
|
import { formatToolResultForModel, formatToolResultContent, normalizeToolFailure, operationFailure } from "../execution/failure.js";
|
|
26
27
|
import {
|
|
27
28
|
AgentEventEmitter,
|
|
@@ -210,6 +211,9 @@ export interface SubagentConfig {
|
|
|
210
211
|
mergeCoordinator?: MergeCoordinator;
|
|
211
212
|
createRegistryForCwd?: (cwd: string) => ToolRegistry;
|
|
212
213
|
requireWriteIsolation?: boolean;
|
|
214
|
+
/** Host preparation after an isolated child lease is created. */
|
|
215
|
+
prepareWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>;
|
|
216
|
+
validateWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>;
|
|
213
217
|
coordinator?: AgentCoordinator;
|
|
214
218
|
coordinatorExecutorBridge?: DeferredAgentCoordinatorExecutor;
|
|
215
219
|
}
|
|
@@ -252,6 +256,8 @@ export interface SubagentFactoryArgs {
|
|
|
252
256
|
mergeCoordinator?: MergeCoordinator;
|
|
253
257
|
createRegistryForCwd?: (cwd: string) => ToolRegistry;
|
|
254
258
|
requireWriteIsolation?: boolean;
|
|
259
|
+
prepareWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>;
|
|
260
|
+
validateWorkspace?: (cwd: string, signal?: AbortSignal) => Promise<void>;
|
|
255
261
|
coordinator?: AgentCoordinator;
|
|
256
262
|
coordinatorExecutorBridge?: DeferredAgentCoordinatorExecutor;
|
|
257
263
|
}
|
|
@@ -1024,10 +1030,15 @@ export class LoopAgent {
|
|
|
1024
1030
|
const REPEAT_LIMIT = 5;
|
|
1025
1031
|
const observeProgress = (calls: ToolCallRequest[], results: Map<string, ToolResult>) => {
|
|
1026
1032
|
const observation = progressTracker.observeRound(calls.map((call) => {
|
|
1027
|
-
|
|
1033
|
+
// A workspace gate fences the original effect resolution. Do not
|
|
1034
|
+
// re-read filesystem-derived effects outside that fence when producing
|
|
1035
|
+
// progress observations; missing evidence is conservatively unknown.
|
|
1036
|
+
const effects = this.executor.workspaceGate
|
|
1037
|
+
? results.get(call.id)?.runtime?.effects ?? unknownToolEffects()
|
|
1038
|
+
: this.executor.resolveEffects(call.name, call.arguments);
|
|
1028
1039
|
return {
|
|
1029
1040
|
...call,
|
|
1030
|
-
readOnly: this.executor.isReadOnly(call.name, call.arguments),
|
|
1041
|
+
readOnly: this.executor.workspaceGate ? isEffectivelyReadOnly(effects) : this.executor.isReadOnly(call.name, call.arguments),
|
|
1031
1042
|
mayChangeWorkspace: effects.confidence === "unknown"
|
|
1032
1043
|
|| effects.filesystem.some((effect) => effect.operation !== "read")
|
|
1033
1044
|
|| effects.workspace.mode === "root-integration" || effects.workspace.mode === "isolated-write",
|
|
@@ -38,8 +38,11 @@ export function assembleSubagentTool(input: AssemblyInput): { registry: ToolRegi
|
|
|
38
38
|
approvalCoordinator: executor.approvalCoordinator,
|
|
39
39
|
policyEngine: executor.policyEngine,
|
|
40
40
|
executionBroker: executor.executionBroker,
|
|
41
|
+
workspaceGate: executor.workspaceGate,
|
|
42
|
+
workspace: executor.workspace,
|
|
41
43
|
onApprovalLifecycle: executor.onApprovalLifecycle,
|
|
42
44
|
onExecutionLifecycle: executor.onExecutionLifecycle,
|
|
45
|
+
admitExecution: executor.executionAdmission,
|
|
43
46
|
},
|
|
44
47
|
onEvent: config.onEvent,
|
|
45
48
|
budget: input.budget,
|
|
@@ -57,6 +60,8 @@ export function assembleSubagentTool(input: AssemblyInput): { registry: ToolRegi
|
|
|
57
60
|
mergeCoordinator: config.mergeCoordinator,
|
|
58
61
|
createRegistryForCwd: config.createRegistryForCwd,
|
|
59
62
|
requireWriteIsolation: config.requireWriteIsolation,
|
|
63
|
+
prepareWorkspace: config.prepareWorkspace,
|
|
64
|
+
validateWorkspace: config.validateWorkspace,
|
|
60
65
|
coordinator: config.coordinator,
|
|
61
66
|
coordinatorExecutorBridge: config.coordinatorExecutorBridge,
|
|
62
67
|
}));
|