zapagent 1.14.14 → 1.14.16
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 +7 -3
- package/src/agent/goalPresentation.ts +43 -0
- package/src/commands/dispatcher.ts +9 -3
- package/src/goal-command.ts +25 -17
- package/src/goal-host.ts +2 -1
- package/src/goal-runner.ts +39 -6
- package/src/goal-session.ts +100 -0
- package/src/goal-turn-host.ts +410 -0
- package/src/goal-turn.ts +41 -0
- package/src/headless/goalPhase.ts +78 -30
- package/src/headless/runHeadless.ts +15 -3
- package/src/headless/sharedGoalTurn.ts +34 -0
- package/src/hooks/useAgentRunner.ts +72 -3
- package/src/hooks/useTurnDispatcher.ts +8 -0
- package/src/index.tsx +19 -3
- package/src/ui/slash-palette.tsx +1 -1
- package/zapsdk/builtin-tools/subagent.ts +52 -17
- package/zapsdk/core/retry.ts +9 -0
- package/zapsdk/goal/contracts.ts +2 -0
- package/zapsdk/goal/store.ts +2 -2
- package/zapsdk/merge/copy.ts +13 -4
- package/zapsdk/runtime/recovery-controller.ts +1 -0
- package/zapsdk/runtime/state-tracker.ts +2 -0
- package/zapsdk/runtime/state-types.ts +1 -0
- package/zapsdk/workspace/copy.ts +29 -4
- package/zapsdk/workspace/manager.ts +34 -3
- package/zapsdk/workspace/types.ts +2 -0
|
@@ -47,6 +47,15 @@ export class GoalPhaseSealTracker {
|
|
|
47
47
|
assertSealed(): void { if (this.unsealed || this.pendingMutations.size) throw new Error("GOAL_SEAL_UNCONFIRMED") }
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
/** Public display events never stand in for the independent sealing result. */
|
|
51
|
+
export async function runGoalMachineCommand(command: string, execute: () => Promise<ToolResult>, onEvent?: (event: AgentEvent) => void): Promise<ToolResult> {
|
|
52
|
+
const id = `machine-${randomUUID()}`
|
|
53
|
+
onEvent?.({ type: "content_final", kind: "tool_call", id, step: 1, toolName: "bash", arguments: { command } })
|
|
54
|
+
const result = await execute()
|
|
55
|
+
onEvent?.({ type: "content_final", kind: "tool_result", id, step: 1, toolName: "bash", result })
|
|
56
|
+
return result
|
|
57
|
+
}
|
|
58
|
+
|
|
50
59
|
/** These local tools do not launch opaque model requests. */
|
|
51
60
|
const GOAL_TOOLS = new Set([
|
|
52
61
|
"read_file", "write_file", "edit_file", "multi_edit", "delete_file", "move_file",
|
|
@@ -60,6 +69,10 @@ const READ_ONLY_GOAL_TOOLS = new Set([
|
|
|
60
69
|
|
|
61
70
|
export interface GoalPhaseInput {
|
|
62
71
|
cwd: string
|
|
72
|
+
/** New Goals reuse the ordinary runtime rather than an isolated phase. */
|
|
73
|
+
executionProfile?: "session"
|
|
74
|
+
sessionId?: string
|
|
75
|
+
streamEvents?: boolean
|
|
63
76
|
prompt: string
|
|
64
77
|
goalId: string
|
|
65
78
|
epoch: number
|
|
@@ -70,21 +83,27 @@ export interface GoalPhaseInput {
|
|
|
70
83
|
privateGitOwnerDirectory?: string
|
|
71
84
|
permissionMode?: PermissionMode
|
|
72
85
|
signal?: AbortSignal
|
|
86
|
+
/** Guarded public runtime events; never a source of process-seal receipts. */
|
|
87
|
+
onEvent?: (event: AgentEvent) => void
|
|
73
88
|
machineCheck?: "bun" | "npm" | "pytest" | "go"
|
|
74
89
|
dependencyInstall?: "npm"
|
|
75
90
|
/** Host must durably record ownership synchronously before input is sent. */
|
|
76
91
|
onSpawn?: (pid: number, mayLaunchSealedProcess: boolean) => void
|
|
77
92
|
/** Called only after the owned process group has ceased to exist. */
|
|
78
93
|
onStopped?: (pid: number) => void
|
|
94
|
+
onSettled?: (result: { text: string; outcome: AgentOutcomeV1; toolCalls: number; sessionId: string }) => void
|
|
79
95
|
}
|
|
80
96
|
|
|
81
|
-
type WorkerInput = Omit<GoalPhaseInput, "signal" | "onSpawn" | "onStopped"> & { allowSealedShell?: boolean }
|
|
82
|
-
type WorkerResult = { type: "result"; summary: RunSummary; exitCode: number; processSealed
|
|
97
|
+
type WorkerInput = Omit<GoalPhaseInput, "signal" | "onSpawn" | "onStopped" | "onSettled" | "onEvent"> & { allowSealedShell?: boolean; streamEvents?: boolean }
|
|
98
|
+
type WorkerResult = { type: "result"; summary: RunSummary; exitCode: number; processSealed?: true; runtimeSettled?: boolean; toolCalls: number; failureCode?: string; dependencyHash?: string } | { type: "machine"; result: ToolResult } | { type: "fatal"; message: string; code: string }
|
|
83
99
|
|
|
84
100
|
/** Check only concrete existing directories. A Host-owned ledger must not sit
|
|
85
101
|
* underneath a model-writable workspace. */
|
|
86
102
|
function validateInput(input: WorkerInput): void {
|
|
87
103
|
if (!input || typeof input !== "object" || !isAbsolute(input.cwd) || !isAbsolute(input.ledgerPath)
|
|
104
|
+
|| input.executionProfile !== undefined && input.executionProfile !== "session"
|
|
105
|
+
|| input.sessionId !== undefined && (typeof input.sessionId !== "string" || !input.sessionId)
|
|
106
|
+
|| input.streamEvents !== undefined && typeof input.streamEvents !== "boolean"
|
|
88
107
|
|| typeof input.prompt !== "string" || !input.prompt.trim() || input.prompt.length > 1024 * 1024
|
|
89
108
|
|| typeof input.goalId !== "string" || !input.goalId || !Number.isSafeInteger(input.epoch) || input.epoch < 0
|
|
90
109
|
|| !["planner", "worker", "verifier", "repair", "maintenance", "finalization"].includes(input.role)
|
|
@@ -99,7 +118,7 @@ function validateInput(input: WorkerInput): void {
|
|
|
99
118
|
privateGitIdentity: { device: input.privateGit.device, inode: input.privateGit.inode } })
|
|
100
119
|
}
|
|
101
120
|
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")
|
|
121
|
+
if (input.executionProfile !== "session" && (!rel || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel)))) throw new Error("Goal ledger must be outside the writable workspace")
|
|
103
122
|
const ledgerStat = lstatSync(input.ledgerPath)
|
|
104
123
|
if (!ledgerStat.isFile() || ledgerStat.isSymbolicLink()) throw new Error("Goal ledger must be an existing regular file")
|
|
105
124
|
}
|
|
@@ -107,30 +126,34 @@ function validateInput(input: WorkerInput): void {
|
|
|
107
126
|
/** Execute one phase in a fresh process. The process cwd is established before
|
|
108
127
|
* importing the headless Runtime's cwd-bound singleton modules. */
|
|
109
128
|
async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult> {
|
|
110
|
-
const { signal, onSpawn, onStopped, ...workerInput } = input
|
|
129
|
+
const { signal, onSpawn, onStopped, onSettled, onEvent, ...workerInput } = input
|
|
111
130
|
validateInput(workerInput)
|
|
112
131
|
signal?.throwIfAborted()
|
|
113
132
|
// Decide before recording ownership and sending the worker any input. A
|
|
114
133
|
// configuration change later cannot turn on shell in this phase.
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
134
|
+
const shared = input.executionProfile === "session"
|
|
135
|
+
let allowSealedShell = false
|
|
136
|
+
if (!shared) {
|
|
137
|
+
const [{ loadAppConfig }, { createExecutionEnvironment, resolveExecutionBackend }] = await Promise.all([
|
|
138
|
+
import("../config.js"), import("../execution-environment.js"),
|
|
139
|
+
])
|
|
140
|
+
const config = loadAppConfig(join(getAppDataDir(), "config.json"))
|
|
141
|
+
const environment = createExecutionEnvironment(input.cwd, "required", resolveExecutionBackend(config.executionBackend), false, config.sandboxNetwork, [])
|
|
142
|
+
allowSealedShell = (input.role === "worker" || input.role === "repair" || !!input.machineCheck || !!input.dependencyInstall)
|
|
143
|
+
&& environment.broker.supportsProcessSeal?.({ name: "bash", executionLocation: "workspace" }) === true
|
|
144
|
+
if (input.machineCheck && !allowSealedShell) throw new Error("GOAL_VERIFIER_PROCESS_SEAL_UNSUPPORTED")
|
|
145
|
+
if (input.dependencyInstall && !allowSealedShell) throw new Error("GOAL_NPM_PROCESS_SEAL_UNSUPPORTED")
|
|
146
|
+
}
|
|
147
|
+
const safeEnvironment = shared ? process.env : Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")))
|
|
125
148
|
const isBun = /(?:^|[\\/])bun(?:\.exe)?$/i.test(process.execPath)
|
|
126
149
|
const argv = isBun ? [fileURLToPath(new URL("../index.tsx", import.meta.url)), "--goal-phase-worker"] : ["--goal-phase-worker"]
|
|
127
150
|
const child = spawn(process.execPath, argv, {
|
|
128
151
|
cwd: dirname(workerInput.ledgerPath),
|
|
129
152
|
detached: process.platform !== "win32",
|
|
130
153
|
stdio: ["pipe", "pipe", "pipe"],
|
|
131
|
-
env: { ...safeEnvironment, PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ZAPCODE_DEVTOOLS_PORT: "", ZAPCODE_HOST_PROTOCOL_PORT: "" },
|
|
154
|
+
env: { ...safeEnvironment, ...(!shared ? { PATH: "/usr/bin:/bin:/usr/sbin:/sbin" } : {}), ZAPCODE_DEVTOOLS_PORT: "", ZAPCODE_HOST_PROTOCOL_PORT: "" },
|
|
132
155
|
})
|
|
133
|
-
let output = "", cancelled = false, spawnRecorded = false, protocolError: Error | undefined, spawnError: unknown
|
|
156
|
+
let output = "", resultOutput: string | undefined, cancelled = false, spawnRecorded = false, protocolError: Error | undefined, spawnError: unknown
|
|
134
157
|
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
135
158
|
let pipeTimer: ReturnType<typeof setTimeout> | undefined
|
|
136
159
|
const killGroup = (signalName: NodeJS.Signals) => {
|
|
@@ -165,6 +188,21 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
165
188
|
child.stdout.setEncoding("utf8")
|
|
166
189
|
child.stdout.on("data", (chunk: string) => {
|
|
167
190
|
output += chunk
|
|
191
|
+
if (onEvent) {
|
|
192
|
+
let newline: number
|
|
193
|
+
while ((newline = output.indexOf("\n")) >= 0 && !protocolError) {
|
|
194
|
+
const line = output.slice(0, newline); output = output.slice(newline + 1)
|
|
195
|
+
if (!line.trim()) continue
|
|
196
|
+
try {
|
|
197
|
+
if (Buffer.byteLength(line) > 16 * 1024 * 1024) throw new Error("Goal phase output exceeds protocol limit")
|
|
198
|
+
const frame = JSON.parse(line)
|
|
199
|
+
if (frame.type === "event" && frame.event && typeof frame.event.type === "string" && !resultOutput) {
|
|
200
|
+
onEvent(frame.event)
|
|
201
|
+
} else if (["result", "machine", "fatal"].includes(frame.type) && !resultOutput) resultOutput = line
|
|
202
|
+
else throw new Error("Invalid Goal phase stream frame")
|
|
203
|
+
} catch (error) { protocolError = error instanceof Error ? error : new Error("Invalid Goal phase stream"); abort() }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
168
206
|
if (Buffer.byteLength(output) > 16 * 1024 * 1024 && !protocolError) {
|
|
169
207
|
protocolError = new Error("Goal phase output exceeds protocol limit")
|
|
170
208
|
abort()
|
|
@@ -176,9 +214,9 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
176
214
|
try {
|
|
177
215
|
try {
|
|
178
216
|
if (!child.pid) throw new Error("Goal phase worker has no pid")
|
|
179
|
-
onSpawn?.(child.pid, allowSealedShell)
|
|
217
|
+
onSpawn?.(child.pid, shared || allowSealedShell)
|
|
180
218
|
spawnRecorded = true
|
|
181
|
-
child.stdin.end(JSON.stringify({ ...workerInput, allowSealedShell }))
|
|
219
|
+
child.stdin.end(JSON.stringify({ ...workerInput, allowSealedShell, ...(onEvent ? { streamEvents: true } : {}) }))
|
|
182
220
|
} catch (error) {
|
|
183
221
|
spawnError = error
|
|
184
222
|
abort()
|
|
@@ -194,12 +232,13 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
194
232
|
while (goalPhaseGroupAlive(pid) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 50))
|
|
195
233
|
}
|
|
196
234
|
if (goalPhaseGroupAlive(pid)) throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
197
|
-
if (!allowSealedShell && spawnRecorded) onStopped?.(pid)
|
|
235
|
+
if (!shared && !allowSealedShell && spawnRecorded) onStopped?.(pid)
|
|
198
236
|
if (spawnError) throw spawnError
|
|
199
237
|
if (protocolError) throw protocolError
|
|
200
|
-
if (cancelled) throw new Error("GOAL_PHASE_CANCELLED")
|
|
238
|
+
if (cancelled && !shared) throw new Error("GOAL_PHASE_CANCELLED")
|
|
239
|
+
if (onEvent && resultOutput && output.trim()) throw new Error("Invalid trailing Goal phase output")
|
|
201
240
|
let response: WorkerResult
|
|
202
|
-
try { response = JSON.parse(output) as WorkerResult } catch { throw new Error(`Goal phase process returned invalid output (exit ${exitCode})`) }
|
|
241
|
+
try { response = JSON.parse(resultOutput ?? output) as WorkerResult } catch { throw new Error(`Goal phase process returned invalid output (exit ${exitCode})`) }
|
|
203
242
|
if (response.type === "fatal") throw new GoalPhaseError(response.code ?? goalPhaseFailureCode(response.message))
|
|
204
243
|
if (response.type === "machine") {
|
|
205
244
|
if (!input.machineCheck || exitCode !== 0 || response.result.runtime?.processSeal?.state !== "sealed") throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
@@ -209,9 +248,11 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
209
248
|
if (response.type !== "result" || !response.summary?.outcome) throw new Error(`Goal phase produced no structured outcome (exit ${exitCode})`)
|
|
210
249
|
// A failed model call can still finish with every tool/process sealed.
|
|
211
250
|
// Only this worker-owned receipt, never model text, may clear ownership.
|
|
212
|
-
if (response.processSealed !== true) throw new GoalPhaseError("GOAL_SEAL_UNCONFIRMED")
|
|
213
|
-
if (
|
|
214
|
-
if (
|
|
251
|
+
if (shared ? response.runtimeSettled !== true : response.processSealed !== true) throw new GoalPhaseError("GOAL_SEAL_UNCONFIRMED")
|
|
252
|
+
if (shared) onSettled?.({ text: response.summary.text, outcome: response.summary.outcome, toolCalls: response.toolCalls, sessionId: response.summary.sessionId })
|
|
253
|
+
if (shared || allowSealedShell) onStopped?.(pid)
|
|
254
|
+
if (cancelled) throw new Error("GOAL_PHASE_CANCELLED")
|
|
255
|
+
if ((!shared && (exitCode !== 0 || response.exitCode !== 0)) || !(shared ? ["finished", "limited"] : ["finished"]).includes(response.summary.outcome.execution.status)) {
|
|
215
256
|
throw new GoalPhaseError(response.failureCode ?? "GOAL_PHASE_FAILED")
|
|
216
257
|
}
|
|
217
258
|
return response
|
|
@@ -222,10 +263,10 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
222
263
|
}
|
|
223
264
|
}
|
|
224
265
|
|
|
225
|
-
export async function runGoalPhase(input: GoalPhaseInput): Promise<{ text: string; outcome: AgentOutcomeV1; toolCalls: number; dependencyHash?: string }> {
|
|
266
|
+
export async function runGoalPhase(input: GoalPhaseInput): Promise<{ text: string; outcome: AgentOutcomeV1; toolCalls: number; sessionId?: string; dependencyHash?: string }> {
|
|
226
267
|
const response = await runGoalPhaseProcess(input)
|
|
227
268
|
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 } : {}) }
|
|
269
|
+
return { text: response.summary.text, outcome: response.summary.outcome, toolCalls: response.toolCalls, sessionId: response.summary.sessionId, ...(response.dependencyHash ? { dependencyHash: response.dependencyHash } : {}) }
|
|
229
270
|
}
|
|
230
271
|
|
|
231
272
|
export async function runGoalMachinePhase(input: GoalPhaseInput & { machineCheck: "bun" | "npm" | "pytest" | "go" }): Promise<ToolResult> {
|
|
@@ -253,6 +294,12 @@ export async function runGoalPhaseWorker(): Promise<number> {
|
|
|
253
294
|
}
|
|
254
295
|
const input = JSON.parse(raw) as WorkerInput
|
|
255
296
|
validateInput(input)
|
|
297
|
+
if (input.executionProfile === "session") {
|
|
298
|
+
process.chdir(input.cwd)
|
|
299
|
+
const { runSharedGoalTurnWorker } = await import("./sharedGoalTurn.js")
|
|
300
|
+
return await runSharedGoalTurnWorker(input)
|
|
301
|
+
}
|
|
302
|
+
validateInput(input)
|
|
256
303
|
process.chdir(input.cwd)
|
|
257
304
|
delete process.env.ZAPCODE_DEVTOOLS_PORT
|
|
258
305
|
delete process.env.ZAPCODE_HOST_PROTOCOL_PORT
|
|
@@ -287,9 +334,9 @@ export async function runGoalPhaseWorker(): Promise<number> {
|
|
|
287
334
|
const executor = new ToolExecutor(registry, { cwd: input.cwd, onApproval: async () => true,
|
|
288
335
|
executionBroker: requireProcessSealing(environment.broker, () => { unsealed = true }) })
|
|
289
336
|
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 })
|
|
337
|
+
const result = await runGoalMachineCommand(command, () => executor.execute("bash", { command }), input.streamEvents ? event => { process.stdout.write(JSON.stringify({ type: "event", event }) + "\n") } : undefined)
|
|
291
338
|
if (unsealed || result.runtime?.processSeal?.state !== "sealed") throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
292
|
-
process.stdout.write(JSON.stringify({ type: "machine", result } satisfies WorkerResult))
|
|
339
|
+
process.stdout.write(JSON.stringify({ type: "machine", result } satisfies WorkerResult) + "\n")
|
|
293
340
|
return 0
|
|
294
341
|
}
|
|
295
342
|
const mode = input.permissionMode ?? config.permissionMode
|
|
@@ -320,6 +367,7 @@ export async function runGoalPhaseWorker(): Promise<number> {
|
|
|
320
367
|
if (event.type === "content_final" && event.kind === "tool_call") toolCalls++
|
|
321
368
|
if (event.type === "error") runtimeError = event.error
|
|
322
369
|
sealTracker.observe(event, permitted("bash"))
|
|
370
|
+
if (input.streamEvents) process.stdout.write(JSON.stringify({ type: "event", event }) + "\n")
|
|
323
371
|
}, progress() {},
|
|
324
372
|
finalize(value) { summary = value },
|
|
325
373
|
failure(value) { failure = value },
|
|
@@ -369,12 +417,12 @@ export async function runGoalPhaseWorker(): Promise<number> {
|
|
|
369
417
|
if (unavailableTool) throw new Error("GOAL_UNMETERED_TOOL_UNAVAILABLE")
|
|
370
418
|
if (!summary) throw new Error(failure?.code ?? `Headless phase failed (${exitCode})`)
|
|
371
419
|
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))
|
|
420
|
+
...(exitCode !== 0 ? { failureCode: goalPhaseFailureCode(runtimeError || summary.error || summary.outcome?.execution.error?.code || "") } : {}), dependencyHash: dependencyProof?.dependencyHash } satisfies WorkerResult) + "\n")
|
|
373
421
|
return exitCode
|
|
374
422
|
} finally { ledger.close() }
|
|
375
423
|
} catch (error) {
|
|
376
424
|
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))
|
|
425
|
+
process.stdout.write(JSON.stringify({ type: "fatal", message: goalPhaseFailureCode(message), code: goalPhaseFailureCode(message) } satisfies WorkerResult) + "\n")
|
|
378
426
|
return 2
|
|
379
427
|
}
|
|
380
428
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readOnlyBashTool } from "../../zapsdk/builtin-tools/subagent.js"
|
|
1
2
|
import { connectLocalServiceOwner } from "../../zapsdk/services/local-owner.js"
|
|
2
3
|
import { createExecutionEnvironment, resolveExecutionBackend } from "../execution-environment.js"
|
|
3
4
|
import { executionExitCode, OutcomeProtocolError, type AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
|
|
@@ -292,6 +293,8 @@ export interface HeadlessHost {
|
|
|
292
293
|
subagentIsolationRoot?: string
|
|
293
294
|
/** Enforce the workspace boundary even in permissive approval modes. */
|
|
294
295
|
isolateWorkspace?: boolean
|
|
296
|
+
/** Independent Goal reviewers can inspect the real workspace, never write. */
|
|
297
|
+
readOnlyWorkspace?: boolean
|
|
295
298
|
privateGit?: PrivateGitBinding
|
|
296
299
|
privateGitOwnerDirectory?: string
|
|
297
300
|
serializeSubagent?: boolean
|
|
@@ -518,10 +521,19 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
518
521
|
: baseExecutor.policyEngine.evaluate(request),
|
|
519
522
|
}, baseExecutor.checkpointMode) : baseExecutor
|
|
520
523
|
const guardedExecutor = resultGuard ? scopedExecutor.withResultGuard(resultGuard) : scopedExecutor
|
|
521
|
-
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
|
|
524
|
+
const isolatedExecutor = host.readOnlyWorkspace ? guardedExecutor.withWorkspace({ root: realpathSync(cwd), mode: "shared-readonly", sandbox: sandboxConfined ? "enforced" : "none" }) : 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
|
|
522
525
|
const executor = host.admitToolExecution ? isolatedExecutor.withExecutionAdmission(host.admitToolExecution) : isolatedExecutor
|
|
523
526
|
approval.setSandboxConfined(sandboxConfined, config.autoAllowSandboxedCommands !== false)
|
|
524
527
|
approval.setSandboxExcludedCommands(config.allowUnsandboxedCommands !== false ? config.sandboxExcludedCommands : undefined)
|
|
528
|
+
if (host.readOnlyWorkspace) {
|
|
529
|
+
// No network tools: read-only Goal roles take worker output and workspace
|
|
530
|
+
// files as untrusted input, and an injected URL could carry them off-host.
|
|
531
|
+
const names = new Set(["read_file", "list_tree", "read_document", "read_pdf", "read_docx", "read_tool_output", "current_time"])
|
|
532
|
+
if (sandboxConfined && registry.has("bash")) {
|
|
533
|
+
registry.unregister("bash"); registry.register(readOnlyBashTool(cwd)); names.add("bash")
|
|
534
|
+
}
|
|
535
|
+
for (const definition of registry.definitions()) if (!names.has(definition.name)) registry.unregister(definition.name)
|
|
536
|
+
}
|
|
525
537
|
await host.prepareRegistry?.(registry)
|
|
526
538
|
if (publicChecks) {
|
|
527
539
|
// These tools start work outside the root provider admission budget.
|
|
@@ -653,7 +665,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
653
665
|
storageSessionId: getCurrentSessionId(),
|
|
654
666
|
storageProjectCwd: cwd,
|
|
655
667
|
sessionId: getCurrentSessionId(),
|
|
656
|
-
subagentFactory: publicChecks || host.disableSubagent ? undefined : host.serializeSubagent ? options => {
|
|
668
|
+
subagentFactory: publicChecks || host.disableSubagent || host.readOnlyWorkspace ? undefined : host.serializeSubagent ? options => {
|
|
657
669
|
const tool = subagentTool(options)
|
|
658
670
|
const resolveEffects = tool.definition.resolveEffects
|
|
659
671
|
return { ...tool, definition: { ...tool.definition, resolveEffects: (args, context) => {
|
|
@@ -662,7 +674,7 @@ export async function runHeadless(args: HeadlessArgs, host: HeadlessHost = {}):
|
|
|
662
674
|
} } }
|
|
663
675
|
} : subagentTool,
|
|
664
676
|
},
|
|
665
|
-
subagent: publicChecks || host.disableSubagent ? false : {
|
|
677
|
+
subagent: publicChecks || host.disableSubagent || host.readOnlyWorkspace ? false : {
|
|
666
678
|
inheritedInstructions: inherited.instructions,
|
|
667
679
|
publicPromptSections: inherited.publicPromptSections,
|
|
668
680
|
onEvent: (event) => { formatter.onEvent(event); host.onEvent?.(event) },
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { goalPhaseFailureCode } from "../../zapsdk/goal/errors.js"
|
|
2
|
+
import type { GoalPhaseInput } from "./goalPhase.js"
|
|
3
|
+
import type { HeadlessFormatter, RunSummary } from "./formatter.js"
|
|
4
|
+
import { goalTurnMeter } from "../goal-turn.js"
|
|
5
|
+
|
|
6
|
+
/** Background execution uses the ordinary headless runtime: normal PATH,
|
|
7
|
+
* network, approvals, checkpointing, child isolation and lifecycle sealing. */
|
|
8
|
+
export async function runSharedGoalTurnWorker(input: GoalPhaseInput): Promise<number> {
|
|
9
|
+
const { runHeadless } = await import("./runHeadless.js")
|
|
10
|
+
const readonly = ["planner", "verifier", "finalization"].includes(input.role)
|
|
11
|
+
const meter = goalTurnMeter(input)
|
|
12
|
+
let summary: RunSummary | undefined
|
|
13
|
+
let toolCalls = 0
|
|
14
|
+
const formatter: HeadlessFormatter = {
|
|
15
|
+
init() {}, progress() {}, failure(error) { throw new Error(error.code) },
|
|
16
|
+
onEvent(event) {
|
|
17
|
+
if (event.type === "content_final" && event.kind === "tool_call") toolCalls++
|
|
18
|
+
if (input.streamEvents) process.stdout.write(JSON.stringify({ type: "event", event }) + "\n")
|
|
19
|
+
},
|
|
20
|
+
finalize(value) { summary = value },
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const code = await runHeadless({ prompt: input.prompt, permissionMode: input.permissionMode ?? "default", outputFormat: "json", resultSchema: "outcome-v1",
|
|
24
|
+
cwd: input.cwd, quiet: true, continueLast: false, continueOnToolDenial: false, dangerouslyDisableOsSandbox: false, ...(input.sessionId ? { sessionId: input.sessionId } : {}), noDevtools: true,
|
|
25
|
+
}, { formatter, ...meter, readOnlyWorkspace: readonly, disableRepoMap: true })
|
|
26
|
+
if (!summary?.outcome) throw new Error("GOAL_TURN_OUTCOME_MISSING")
|
|
27
|
+
const execution = summary.outcome.execution
|
|
28
|
+
// This is the ordinary Runtime's terminal outcome, not an OS process-seal
|
|
29
|
+
// claim. In-flight or pending background actions never clear ownership.
|
|
30
|
+
const settled = execution.unresolvedActions.length === 0 && !execution.backgroundTasks?.some(task => task.disposition === "pending")
|
|
31
|
+
process.stdout.write(JSON.stringify({ type: "result", summary, exitCode: code, runtimeSettled: settled, toolCalls, ...(code !== 0 ? { failureCode: goalPhaseFailureCode(summary.error ?? "") } : {}) }) + "\n")
|
|
32
|
+
return code
|
|
33
|
+
} finally { meter.close() }
|
|
34
|
+
}
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { goalTurnMeter, type GoalTurnInput } from "../goal-turn.js"
|
|
2
|
+
import { RetryProvider } from "../../zapsdk/core/retry.js"
|
|
3
|
+
import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
|
|
4
|
+
import { executeGoalCommand } from "../goal-session.js"
|
|
5
|
+
import { createGoalPresentation } from "../agent/goalPresentation.js"
|
|
1
6
|
import { AgentBudget } from "../../zapsdk/agent/budget.js"
|
|
2
7
|
import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
|
|
3
8
|
import { accumulateTokenUsage } from "../../zapsdk/agent/token-usage.js"
|
|
@@ -354,6 +359,7 @@ export function useAgentRunner({
|
|
|
354
359
|
onUpdateConfig,
|
|
355
360
|
}: UseAgentRunnerOptions) {
|
|
356
361
|
const [status, setStatus] = useState("ready")
|
|
362
|
+
const [goalRunning, setGoalRunning] = useState(false)
|
|
357
363
|
const [outputThroughput, setOutputThroughput] = useState<OutputThroughputSample>()
|
|
358
364
|
const [providerRequest, setProviderRequest] = useState<ProviderRequestEvent>()
|
|
359
365
|
const [step, setStep] = useState(0)
|
|
@@ -535,7 +541,7 @@ export function useAgentRunner({
|
|
|
535
541
|
systemPrompt?: string,
|
|
536
542
|
images?: import("../../zapsdk/core/types.js").ImageContent[],
|
|
537
543
|
memoryQueryText?: string,
|
|
538
|
-
invocation?: { signal?: AbortSignal; propagateErrors?: boolean; resultSchema?: "outcome-v1" | "legacy" } & Pick<import("../../zapsdk/agent/loop.js").RunOptions,
|
|
544
|
+
invocation?: { goalTurn?: GoalTurnInput; goalController?: AbortController; onOutcome?: (outcome: AgentOutcomeV1) => void; signal?: AbortSignal; propagateErrors?: boolean; resultSchema?: "outcome-v1" | "legacy" } & Pick<import("../../zapsdk/agent/loop.js").RunOptions,
|
|
539
545
|
"onInputAccepted" | "hasSteering" | "takeSteering" | "onSteeringAccepted">,
|
|
540
546
|
): Promise<LoopAgentResult | undefined> => {
|
|
541
547
|
running.current = true
|
|
@@ -545,7 +551,7 @@ export function useAgentRunner({
|
|
|
545
551
|
const forwardExternalAbort = () => controller.abort(externalSignal?.reason)
|
|
546
552
|
if (externalSignal?.aborted) forwardExternalAbort()
|
|
547
553
|
else externalSignal?.addEventListener("abort", forwardExternalAbort, { once: true })
|
|
548
|
-
abortRef.current = controller
|
|
554
|
+
abortRef.current = invocation?.goalController ?? controller
|
|
549
555
|
setStatus("preparing")
|
|
550
556
|
setProviderRequest(undefined)
|
|
551
557
|
setStep(0)
|
|
@@ -571,11 +577,17 @@ export function useAgentRunner({
|
|
|
571
577
|
let outcomeExecutionError: Error | undefined
|
|
572
578
|
let caughtError: unknown
|
|
573
579
|
let completedResult: LoopAgentResult | undefined
|
|
580
|
+
let goalMeter: ReturnType<typeof goalTurnMeter> | undefined
|
|
574
581
|
let preview: ReturnType<typeof createStreamingPreview> | null = null
|
|
575
582
|
let handlers: ReturnType<typeof createRunHandlers> | null = null
|
|
576
583
|
|
|
577
584
|
try {
|
|
578
|
-
const
|
|
585
|
+
const objects = agentRef.current
|
|
586
|
+
const { registry, createRegistryForCwd, executionFacts, executionCapacity } = objects
|
|
587
|
+
goalMeter = invocation?.goalTurn ? goalTurnMeter(invocation.goalTurn) : undefined
|
|
588
|
+
const provider = goalMeter ? objects.provider instanceof RetryProvider
|
|
589
|
+
? objects.provider.withInnerAdapter(goalMeter.providerAdapter) : goalMeter.providerAdapter(objects.provider) : objects.provider
|
|
590
|
+
const executor = goalMeter ? objects.executor.withExecutionAdmission(goalMeter.admitToolExecution) : objects.executor
|
|
579
591
|
const currentConfig = config
|
|
580
592
|
const cacheScope = makePromptCacheScope(
|
|
581
593
|
currentConfig.active.providerId,
|
|
@@ -785,6 +797,7 @@ export function useAgentRunner({
|
|
|
785
797
|
setPromptCacheDiagnostics(promptCacheDiagnosticsForRun)
|
|
786
798
|
|
|
787
799
|
handlers.wire(agent)
|
|
800
|
+
if (invocation?.goalTurn) agent.on("*", invocation.goalTurn.onEvent)
|
|
788
801
|
|
|
789
802
|
// ── Per-turn context attachments + turn-end guard ──
|
|
790
803
|
const { contextPrefix, contextDelta, contextDiagnostics } = makeContextBuilders({
|
|
@@ -809,6 +822,7 @@ export function useAgentRunner({
|
|
|
809
822
|
onSteeringAccepted: invocation?.onSteeringAccepted,
|
|
810
823
|
}
|
|
811
824
|
const execution = invocation?.resultSchema === "legacy" ? undefined : await agent.runWithOutcome(task, runOptions)
|
|
825
|
+
if (execution) invocation?.onOutcome?.(execution.outcome)
|
|
812
826
|
const result = execution?.loopResult ?? await agent.run(task, runOptions)
|
|
813
827
|
if (execution?.outcome.execution.status === "failed" || execution?.outcome.execution.status === "blocked") {
|
|
814
828
|
runError = execution.outcome.execution.error?.message ?? execution.outcome.execution.stopReason
|
|
@@ -899,6 +913,7 @@ export function useAgentRunner({
|
|
|
899
913
|
// has already ended. Nulling the callback in this finally re-introduces
|
|
900
914
|
// the "ghost paragraph in tail" bug that commit 57a4bf2 fixed.
|
|
901
915
|
|
|
916
|
+
goalMeter?.close()
|
|
902
917
|
running.current = false
|
|
903
918
|
abortRef.current = null
|
|
904
919
|
setActiveTool("")
|
|
@@ -937,6 +952,58 @@ export function useAgentRunner({
|
|
|
937
952
|
turnStartUiLogIndexRef,
|
|
938
953
|
])
|
|
939
954
|
|
|
955
|
+
const runGoalCommand = useCallback(async (args: string[]): Promise<number> => {
|
|
956
|
+
const controller = new AbortController()
|
|
957
|
+
let presentation: ReturnType<typeof createGoalPresentation> | undefined
|
|
958
|
+
let stateLabel = ""
|
|
959
|
+
try {
|
|
960
|
+
return await executeGoalCommand(args, cwd, {
|
|
961
|
+
runTurn: async input => {
|
|
962
|
+
presentation?.finish()
|
|
963
|
+
let outcome: AgentOutcomeV1 | undefined
|
|
964
|
+
try {
|
|
965
|
+
const result = await runAgent(input.prompt, undefined, undefined, input.prompt, {
|
|
966
|
+
signal: input.signal, goalTurn: input, goalController: controller, onOutcome: value => { outcome = value }, resultSchema: "outcome-v1", propagateErrors: true,
|
|
967
|
+
})
|
|
968
|
+
if (!result || !outcome) throw new Error("GOAL_TURN_OUTCOME_MISSING")
|
|
969
|
+
return { text: result.text, outcome, toolCalls: result.toolResults.length, sessionId: getCurrentSessionId() }
|
|
970
|
+
} finally { running.current = true; abortRef.current = controller }
|
|
971
|
+
},
|
|
972
|
+
permissionMode: config.permissionMode, sessionId: getCurrentSessionId(), signal: controller.signal,
|
|
973
|
+
onStart: () => {
|
|
974
|
+
if (running.current) throw new Error("The current session is already running a task")
|
|
975
|
+
running.current = true; abortRef.current = controller; setGoalRunning(true); setStatus("preparing")
|
|
976
|
+
agentRunStore.clear()
|
|
977
|
+
presentation = createGoalPresentation({ currentConfig: config, controller,
|
|
978
|
+
createPreview: () => {
|
|
979
|
+
const preview = createStreamingPreview({ addLog, setStreamingText, setIsStreaming, setThinkingText, setIsThinking, getIsFrozen: getIsFrozen ?? (() => false) })
|
|
980
|
+
registerStaticFlushCallback?.(() => preview.onStaticFlushed())
|
|
981
|
+
return preview
|
|
982
|
+
},
|
|
983
|
+
setStatus, setStep, setActiveTool, setActiveToolBytes, setProviderRequest, setOutputThroughput,
|
|
984
|
+
addLog, replaceLog, peekNextLogId, onAgentRunState: run => agentRunStore.apply(run),
|
|
985
|
+
})
|
|
986
|
+
},
|
|
987
|
+
onEvent: (event, scope) => presentation?.event(event, scope),
|
|
988
|
+
onState: goal => {
|
|
989
|
+
const label = `${goal.status}/${goal.phase ?? "preparing"} · ${goal.tasks.filter(task => task.status === "passed").length}/${goal.tasks.length} tasks`
|
|
990
|
+
if (label !== stateLabel) {
|
|
991
|
+
stateLabel = label
|
|
992
|
+
addLog("system", `Goal ${label}${goal.stopReason ? ` · ${goal.stopReason}` : ""}`)
|
|
993
|
+
if (!controller.signal.aborted) setStatus(goal.phase ?? "preparing")
|
|
994
|
+
}
|
|
995
|
+
},
|
|
996
|
+
onMessage: text => addLog("system", text),
|
|
997
|
+
})
|
|
998
|
+
} finally {
|
|
999
|
+
if (presentation) {
|
|
1000
|
+
presentation.finish(); running.current = false
|
|
1001
|
+
if (abortRef.current === controller) abortRef.current = null
|
|
1002
|
+
setGoalRunning(false); setStatus("ready"); setActiveTool(""); setStep(0); setProviderRequest(undefined)
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
}, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore, runAgent])
|
|
1006
|
+
|
|
940
1007
|
const runAgentRef = useRef(runAgent)
|
|
941
1008
|
runAgentRef.current = runAgent
|
|
942
1009
|
useEffect(() => {
|
|
@@ -977,6 +1044,8 @@ export function useAgentRunner({
|
|
|
977
1044
|
|
|
978
1045
|
return {
|
|
979
1046
|
runAgent,
|
|
1047
|
+
runGoalCommand,
|
|
1048
|
+
goalRunning,
|
|
980
1049
|
running,
|
|
981
1050
|
abortRef,
|
|
982
1051
|
status,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isGoalSessionControl } from "../goal-session.js"
|
|
1
2
|
import { pauseGoalsForUserInput } from "../goal-command.js"
|
|
2
3
|
import { useCallback, useEffect, useRef } from "react"
|
|
3
4
|
import {
|
|
@@ -578,6 +579,13 @@ export function useTurnDispatcher(
|
|
|
578
579
|
}
|
|
579
580
|
// Provider repair is a local control action, not a follow-up task. It
|
|
580
581
|
// must remain reachable behind a failed head, without reviving that head.
|
|
582
|
+
if (isGoalSessionControl(value)) {
|
|
583
|
+
pushHistory(value)
|
|
584
|
+
addLog("user", displayForm, undefined, undefined, undefined, { restore: false })
|
|
585
|
+
await dispatchCommand(expandPastes(value), { displayText: displayForm })
|
|
586
|
+
setInputValue(current => current === draftAtSubmit ? "" : current)
|
|
587
|
+
return
|
|
588
|
+
}
|
|
581
589
|
const control = parseCommand(value)
|
|
582
590
|
if (!isRunning && !isDispatchingRef.current && !opts.editingMessageId
|
|
583
591
|
&& control && ["open_connect", "open_model_picker", "set_model"].includes(control.type)) {
|
package/src/index.tsx
CHANGED
|
@@ -112,10 +112,25 @@ if (args[0] === "--goal-runner") {
|
|
|
112
112
|
process.exit(await runGoalRunner(args[1]))
|
|
113
113
|
}
|
|
114
114
|
if (args[0] === "goal") {
|
|
115
|
-
const [{
|
|
116
|
-
import("./goal-
|
|
115
|
+
const [{ executeGoalCommand }, { loadAppConfig }, { getAppDataDir }] = await Promise.all([
|
|
116
|
+
import("./goal-session.js"), import("./config.js"), import("../zapsdk/utils/platform.js"),
|
|
117
117
|
])
|
|
118
|
-
|
|
118
|
+
const displayed = new Set<string>()
|
|
119
|
+
let lastPhase = ""
|
|
120
|
+
try { process.exit(await executeGoalCommand(args.slice(1), process.cwd(), {
|
|
121
|
+
permissionMode: loadAppConfig(join(getAppDataDir(), "config.json")).permissionMode,
|
|
122
|
+
onMessage: text => process.stdout.write(text + "\n"),
|
|
123
|
+
onState: goal => { const phase = `${goal.status}/${goal.phase ?? "preparing"}`; if (phase !== lastPhase) { lastPhase = phase; process.stdout.write(`\nGoal ${phase} · ${goal.tasks.filter(t => t.status === "passed").length}/${goal.tasks.length} tasks\n`) } },
|
|
124
|
+
onEvent: (event, scope) => {
|
|
125
|
+
if ((event.type === "content_delta" || event.type === "content_final") && (event.kind === "text" || event.kind === "thinking")) {
|
|
126
|
+
const key = `${scope}:${event.id}`
|
|
127
|
+
if (event.type === "content_delta") { displayed.add(key); process.stdout.write(event.text) }
|
|
128
|
+
else { if (!displayed.has(key)) process.stdout.write(event.text); process.stdout.write("\n") }
|
|
129
|
+
} else if (event.type === "content_final" && event.kind === "tool_call") process.stdout.write(`\n${event.path?.length ? "Child " : ""}Tool ${event.toolName}: ${JSON.stringify(event.arguments)}\n`)
|
|
130
|
+
else if (event.type === "content_final" && event.kind === "tool_result") process.stdout.write(`Tool ${event.toolName}: ${event.result.success ? "ok" : "failed"} ${event.result.output ?? event.result.error ?? ""}\n`)
|
|
131
|
+
else if (event.type === "error") process.stderr.write(event.error + "\n")
|
|
132
|
+
},
|
|
133
|
+
})) }
|
|
119
134
|
catch (error) { process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); process.exit(1) }
|
|
120
135
|
}
|
|
121
136
|
|
|
@@ -409,6 +424,7 @@ if (process.stdout.isTTY) {
|
|
|
409
424
|
// app-side hooks. macOS Cmd-C / pbpaste continue to work as expected.
|
|
410
425
|
|
|
411
426
|
await inst.waitUntilExit()
|
|
427
|
+
await (await import("./goal-session.js")).closeForegroundGoals()
|
|
412
428
|
const restart = (await import("./self-update.js")).takeUpdateRestart()
|
|
413
429
|
if (restart) {
|
|
414
430
|
await (await import("./update-lifecycle.js")).prepareUpdateRestart({
|
package/src/ui/slash-palette.tsx
CHANGED
|
@@ -40,7 +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: "
|
|
43
|
+
{ name: "/goal", desc: "Goal in this session · --background | status | pause | resume | cancel" },
|
|
44
44
|
{ name: "/supertask", desc: "Long-horizon orchestrated task · resume | abort | status | watch" },
|
|
45
45
|
{ name: "/exit", desc: "Quit zapAgent" },
|
|
46
46
|
]
|