zapagent 1.14.14 → 1.14.15
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 +12 -7
- package/src/goal-host.ts +2 -1
- package/src/goal-runner.ts +36 -6
- package/src/goal-session.ts +99 -0
- package/src/headless/goalPhase.ts +38 -9
- package/src/hooks/useAgentRunner.ts +46 -0
- package/src/hooks/useTurnDispatcher.ts +8 -0
- package/src/index.tsx +19 -3
- package/src/ui/slash-palette.tsx +1 -1
- 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
package/package.json
CHANGED
package/src/App.tsx
CHANGED
|
@@ -534,8 +534,10 @@ export function App() {
|
|
|
534
534
|
// ── Agent runner ──
|
|
535
535
|
const {
|
|
536
536
|
runAgent,
|
|
537
|
+
runGoalCommand,
|
|
538
|
+
goalRunning,
|
|
537
539
|
abortRef,
|
|
538
|
-
status,
|
|
540
|
+
status: runnerStatus,
|
|
539
541
|
providerRequest,
|
|
540
542
|
outputThroughput,
|
|
541
543
|
setStatus,
|
|
@@ -586,7 +588,8 @@ export function App() {
|
|
|
586
588
|
onUpdateConfig: updateConfig,
|
|
587
589
|
})
|
|
588
590
|
|
|
589
|
-
const
|
|
591
|
+
const status = goalRunning && (runnerStatus === "ready" || runnerStatus === "cancelled") ? "sealing" : runnerStatus
|
|
592
|
+
const isAgentRunning = goalRunning || status !== "ready" && status !== "cancelled"
|
|
590
593
|
const turnActivity = resolveTurnActivity(status, inputQueue, queueActiveRunId, queueError)
|
|
591
594
|
const isRunning = turnActivity.busy
|
|
592
595
|
|
|
@@ -750,6 +753,7 @@ export function App() {
|
|
|
750
753
|
): Promise<boolean> => {
|
|
751
754
|
const result = await dispatchSlashCommand(input, {
|
|
752
755
|
exit,
|
|
756
|
+
runGoalCommand,
|
|
753
757
|
bumpTranscript,
|
|
754
758
|
setLogs,
|
|
755
759
|
setTodos,
|
|
@@ -801,7 +805,7 @@ export function App() {
|
|
|
801
805
|
// stable; refs aren't deps. Only addLog/addToast/compactLogs/dispatchUserTurn
|
|
802
806
|
// could realistically change.
|
|
803
807
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
804
|
-
[addLog, addToast, compactLogs, dispatchUserTurn, exit, updateConfig, setContextTokens, resetRunDiagnostics, restoreMemoryQueryHistoryFromLogs, setCompactFailure, setMemoryFailure, bindQueue],
|
|
808
|
+
[addLog, addToast, compactLogs, dispatchUserTurn, runGoalCommand, exit, updateConfig, setContextTokens, resetRunDiagnostics, restoreMemoryQueryHistoryFromLogs, setCompactFailure, setMemoryFailure, bindQueue],
|
|
805
809
|
)
|
|
806
810
|
|
|
807
811
|
// ── Turn dispatcher (unified handleSubmit + drain) ──
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { AgentEventEmitter, type AgentEvent } from "../../zapsdk/agent/events.js"
|
|
2
|
+
import { createRunHandlers, type RunHandlersDeps } from "./wireRunHandlers.js"
|
|
3
|
+
import type { StreamingPreview } from "./streamingPreview.js"
|
|
4
|
+
import { scopeGoalEvent } from "../goal-session.js"
|
|
5
|
+
|
|
6
|
+
type PresentationDeps = Omit<RunHandlersDeps, "preview" | "setContextTokens" | "setContextPending" | "compactLogs"> & {
|
|
7
|
+
createPreview: () => StreamingPreview
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Reuse normal tool/subagent rendering without modifying the chat's context,
|
|
11
|
+
* compacting its transcript or writing phase summaries to its private memory. */
|
|
12
|
+
export function createGoalPresentation(deps: PresentationDeps) {
|
|
13
|
+
let scope: string | undefined
|
|
14
|
+
let preview: StreamingPreview | undefined
|
|
15
|
+
let handlers: ReturnType<typeof createRunHandlers> | undefined
|
|
16
|
+
let emitter: AgentEventEmitter | undefined
|
|
17
|
+
const finish = () => {
|
|
18
|
+
preview?.drainOnAbort()
|
|
19
|
+
handlers?.settlePending("Goal phase ended before this tool returned")
|
|
20
|
+
preview = undefined; handlers = undefined; emitter = undefined
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
event(event: AgentEvent, nextScope: string) {
|
|
24
|
+
if (scope !== nextScope) {
|
|
25
|
+
finish(); scope = nextScope
|
|
26
|
+
preview = deps.createPreview()
|
|
27
|
+
handlers = createRunHandlers({ ...deps, preview, setContextTokens() {}, setContextPending() {}, compactLogs() {} })
|
|
28
|
+
emitter = new AgentEventEmitter()
|
|
29
|
+
handlers.wire(emitter)
|
|
30
|
+
}
|
|
31
|
+
// These records describe an isolated phase, never the main conversation.
|
|
32
|
+
if (event.type === "run_usage") { deps.onRunUsage?.(event); return }
|
|
33
|
+
if (event.type === "observation" && event.kind === "autocompact_done") {
|
|
34
|
+
deps.addLog("system", "Goal phase context compaction finished; current chat history retained.")
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
const scoped = scopeGoalEvent(event, nextScope)
|
|
38
|
+
if (!scoped.path?.length) emitter!.emit(scoped)
|
|
39
|
+
handlers!.subAgentEventHandler(scoped)
|
|
40
|
+
},
|
|
41
|
+
finish,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -17,7 +17,7 @@ import { resolveActiveContextLimits } from "../context-budget.js"
|
|
|
17
17
|
import type { CheckpointManager } from "../../zapsdk/checkpoint/index.js"
|
|
18
18
|
import { conversation, autoMemory } from "../singletons.js"
|
|
19
19
|
import { dispatchMCPCommand } from "./mcp.js"
|
|
20
|
-
import {
|
|
20
|
+
import { executeGoalCommand } from "../goal-session.js"
|
|
21
21
|
import {
|
|
22
22
|
getCurrentSessionId,
|
|
23
23
|
lastOutputPath,
|
|
@@ -105,6 +105,7 @@ export interface ToastOptions {
|
|
|
105
105
|
|
|
106
106
|
export interface DispatchSlashCommandDeps {
|
|
107
107
|
exit: () => void
|
|
108
|
+
runGoalCommand?: (args: string[]) => Promise<number>
|
|
108
109
|
bumpTranscript: () => void
|
|
109
110
|
setLogs: (logs: LogEntry[]) => void
|
|
110
111
|
setTodos: (todos: Todo[]) => void
|
|
@@ -612,10 +613,15 @@ export function dispatchSlashCommand(
|
|
|
612
613
|
case "goal": {
|
|
613
614
|
const raw = cmd.value?.trim() ?? ""
|
|
614
615
|
const parts = raw ? raw.split(/\s+/) : []
|
|
615
|
-
if (parts.length && !["status", "watch", "list", "pause", "resume", "cancel", "budget", "help"].includes(parts[0]!) && !precheckProvider(deps)) return true
|
|
616
|
-
|
|
616
|
+
if (parts.length && !["status", "watch", "list", "pause", "resume", "cancel", "background", "budget", "help"].includes(parts[0]!) && !precheckProvider(deps)) return true
|
|
617
|
+
return (async () => {
|
|
618
|
+
try {
|
|
619
|
+
if (deps.runGoalCommand) await deps.runGoalCommand(parts)
|
|
620
|
+
else await executeGoalCommand(parts, process.cwd(), { permissionMode: deps.configRef.current.permissionMode, sessionId: getCurrentSessionId(), onMessage: text => deps.addLog("system", text) })
|
|
621
|
+
}
|
|
617
622
|
catch (error) { deps.addLog("error", error instanceof Error ? error.message : String(error)) }
|
|
618
623
|
return true
|
|
624
|
+
})()
|
|
619
625
|
}
|
|
620
626
|
|
|
621
627
|
case "supertask": {
|
package/src/goal-command.ts
CHANGED
|
@@ -51,7 +51,7 @@ function recoverStoppedOwner(store: GoalStore, goal: GoalRecord): GoalRecord {
|
|
|
51
51
|
} else if (goal.inFlight) throw new Error("Missing Goal process evidence; manual reconciliation required")
|
|
52
52
|
return store.recoverOwner(goal.id, goal.owner.instanceId, true)
|
|
53
53
|
}
|
|
54
|
-
function
|
|
54
|
+
export function startGoalBackgroundRunner(goal: GoalRecord): void {
|
|
55
55
|
if (goal.owner) throw new Error("Goal already has an active or unresolved owner")
|
|
56
56
|
if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error(`Goal is ${goal.status}`)
|
|
57
57
|
const directory = goalHome(goal.id)
|
|
@@ -67,10 +67,11 @@ function startRunner(goal: GoalRecord): void {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/** The same command implementation is used by the TUI and the CLI. */
|
|
70
|
-
export function goalCommand(args: string[], cwd: string, currentMode: import("./config.js").PermissionMode = "default", platform: NodeJS.Platform = process.platform, sessionId?: string): string {
|
|
70
|
+
export function goalCommand(args: string[], cwd: string, currentMode: import("./config.js").PermissionMode = "default", platform: NodeJS.Platform = process.platform, sessionId?: string, onForeground?: (goal: GoalRecord) => void): string {
|
|
71
71
|
const action = args[0] ?? ""
|
|
72
72
|
if (!action || action === "help") return [
|
|
73
|
-
"Usage: /goal <objective> [--artifact] [--strict] [--accept-edits | --permission-mode=MODE] [--check=bun|npm|pytest|go] [--install=npm] [--tokens=N] [--minutes=N] [--model-calls=N] [--tool-calls=N] | status [id] | list | pause [id] | resume [id] | cancel [id] | budget extend [id] --tokens=N --minutes=N",
|
|
73
|
+
"Usage: /goal <objective> [--background] [--artifact] [--strict] [--accept-edits | --permission-mode=MODE] [--check=bun|npm|pytest|go] [--install=npm] [--tokens=N] [--minutes=N] [--model-calls=N] [--tool-calls=N] | status [id] | list | pause [id] | resume [id] | cancel [id] | budget extend [id] --tokens=N --minutes=N",
|
|
74
|
+
"Goals run in the current session by default. Use --background to detach, or /goal background to hand off at a safe boundary.",
|
|
74
75
|
"Goals run until independent acceptance and delivery, with no default token, call or time limit. Use pause or cancel to interrupt.",
|
|
75
76
|
"Goal execution is not yet supported on Windows; --check requires a VM backend with verified process sealing.",
|
|
76
77
|
"Git Goal currently supports macOS repository roots with an existing commit and ordinary SHA-1 metadata; linked worktrees, alternates, shallow and SHA-256 repositories are unavailable.",
|
|
@@ -89,6 +90,8 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
|
|
|
89
90
|
if (!control && installArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --install=npm requires a VM backend with verified process sealing.")
|
|
90
91
|
if (!control && checkArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --check machine verification is currently unavailable: process-tree sealing cannot be verified.")
|
|
91
92
|
if (!control && (checkArgs.length > 1 || checkArgs.some(arg => !/^--check=(bun|npm|pytest|go)$/.test(arg)))) throw new Error("Invalid Goal machine check; use --check=bun, npm, pytest or go")
|
|
93
|
+
const background = args.includes("--background")
|
|
94
|
+
if (args.filter(arg => arg === "--background").length > 1 || args.some(arg => arg.startsWith("--background="))) throw new Error("Invalid Goal background flag")
|
|
92
95
|
const limits: GoalBudgetLimits = { strict: args.includes("--strict") }
|
|
93
96
|
const limitKeys = { tokens: "maxTokens", "model-calls": "maxModelCalls", "provider-attempts": "maxProviderAttempts", "tool-calls": "maxToolCalls", minutes: "deadlineAt" } as const
|
|
94
97
|
const limitArgs = !control ? args.filter(arg => /^--(?:tokens|model-calls|provider-attempts|tool-calls|minutes)(?:=|$)/.test(arg)) : []
|
|
@@ -103,6 +106,8 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
|
|
|
103
106
|
limits[key] = limit
|
|
104
107
|
}
|
|
105
108
|
if (limits.maxTokens !== undefined) limits.reservedTokens = Math.min(50_000, Math.floor(limits.maxTokens * 0.05))
|
|
109
|
+
if ((!control || action === "resume") && !background && !onForeground) throw new Error("A foreground Goal launcher is required")
|
|
110
|
+
const launch = (goal: GoalRecord) => background ? startGoalBackgroundRunner(goal) : onForeground!(goal)
|
|
106
111
|
const store = new GoalStore(goalDatabasePath(), { requireLedger: true })
|
|
107
112
|
try {
|
|
108
113
|
if (action === "list") {
|
|
@@ -150,13 +155,13 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
|
|
|
150
155
|
if ((goal.machineCheck || goal.dependencyInstall) && !machineCheckSupported(cwd)) throw new Error("Goal VM execution is currently unavailable: process-tree sealing cannot be verified.")
|
|
151
156
|
const stopped = recoverStoppedOwner(store, goal)
|
|
152
157
|
if (sessionId && stopped.sessionId === sessionId) store.pauseForInput(cwd, sessionId)
|
|
153
|
-
|
|
158
|
+
launch(store.prepareResume(stopped.id))
|
|
154
159
|
return `Goal ${goal.id} resumed; budget and task state retained.`
|
|
155
160
|
}
|
|
156
161
|
const permissionMode = args.includes("--accept-edits") ? "acceptEdits" : modeArgs.length ? modeArgs[0]!.slice("--permission-mode=".length) as import("./config.js").PermissionMode : currentMode
|
|
157
162
|
const strict = args.includes("--strict")
|
|
158
163
|
const deliveryPolicy = args.includes("--artifact") ? "artifact" : "workspace"
|
|
159
|
-
const objective = args.filter(arg => arg !== "--strict" && arg !== "--artifact" && arg !== "--accept-edits" && !arg.startsWith("--permission-mode=") && !arg.startsWith("--check=") && !arg.startsWith("--install=") && !limitArgs.includes(arg)).join(" ").trim()
|
|
164
|
+
const objective = args.filter(arg => arg !== "--background" && arg !== "--strict" && arg !== "--artifact" && arg !== "--accept-edits" && !arg.startsWith("--permission-mode=") && !arg.startsWith("--check=") && !arg.startsWith("--install=") && !limitArgs.includes(arg)).join(" ").trim()
|
|
160
165
|
if (!objective) throw new Error("Goal objective is required")
|
|
161
166
|
const machineCheck = checkArgs[0]?.slice("--check=".length) as "bun" | "npm" | "pytest" | "go" | undefined
|
|
162
167
|
if (sessionId) store.pauseForInput(cwd, sessionId)
|
|
@@ -167,7 +172,7 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
|
|
|
167
172
|
// implicit cap may turn an unfinished objective into a stopped Goal.
|
|
168
173
|
ledger.create(goal.id, 0, limits)
|
|
169
174
|
} finally { ledger.close() }
|
|
170
|
-
|
|
171
|
-
return `Goal ${goal.id} started (${limitArgs.length ? "explicit user limits" : "no default usage or time limit"}; ${strict ? "strict accounting" : "observed usage; external tool usage may be unknown"}). Use /goal status ${goal.id} to inspect progress.`
|
|
175
|
+
launch(goal)
|
|
176
|
+
return `Goal ${goal.id} started${background ? " in background" : " in this session"} (${limitArgs.length ? "explicit user limits" : "no default usage or time limit"}; ${strict ? "strict accounting" : "observed usage; external tool usage may be unknown"}). Use /goal status ${goal.id} to inspect progress.`
|
|
172
177
|
} finally { store.close() }
|
|
173
178
|
}
|
package/src/goal-host.ts
CHANGED
|
@@ -173,7 +173,7 @@ export class LocalGoalHost implements GoalHost {
|
|
|
173
173
|
private readonly directory: string
|
|
174
174
|
private readonly metadata: string
|
|
175
175
|
private readonly acceptance: JsonAcceptanceStore
|
|
176
|
-
constructor(private readonly goalId: string) {
|
|
176
|
+
constructor(private readonly goalId: string, private readonly onEvent?: (event: import("../zapsdk/agent/events.js").AgentEvent, operationId: string) => void) {
|
|
177
177
|
this.directory = goalHome(goalId)
|
|
178
178
|
this.metadata = join(this.directory, "workspace.json")
|
|
179
179
|
this.acceptance = new JsonAcceptanceStore(join(this.directory, "acceptance"))
|
|
@@ -186,6 +186,7 @@ export class LocalGoalHost implements GoalHost {
|
|
|
186
186
|
private getWorkspace(): GoalWorkspace { if (!this.workspace) throw new Error("Goal workspace unavailable"); return this.workspace }
|
|
187
187
|
private phaseHooks(context: GoalOperationContext) {
|
|
188
188
|
return {
|
|
189
|
+
...(this.onEvent ? { onEvent: (event: import("../zapsdk/agent/events.js").AgentEvent) => this.onEvent!(event, context.operationId) } : {}),
|
|
189
190
|
onSpawn: (pid: number, mayLaunchSealedProcess: boolean) => {
|
|
190
191
|
if (this.state?.phaseProcess) throw new Error("Previous Goal child process is unresolved")
|
|
191
192
|
this.state!.phaseProcess = { pid, operationId: context.operationId, requiresReceipt: mayLaunchSealedProcess }; this.persist()
|
package/src/goal-runner.ts
CHANGED
|
@@ -3,29 +3,59 @@ import { GoalStore } from "../zapsdk/goal/store.js"
|
|
|
3
3
|
import { LocalGoalHost } from "./goal-host.js"
|
|
4
4
|
import { goalDatabasePath } from "./goal-command.js"
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
export
|
|
6
|
+
/** Shared controller entry for attached sessions and explicitly detached runners. */
|
|
7
|
+
export interface GoalRunnerObserver {
|
|
8
|
+
signal?: AbortSignal
|
|
9
|
+
onEvent?: (event: import("../zapsdk/agent/events.js").AgentEvent, operationId: string) => void
|
|
10
|
+
onState?: (goal: import("../zapsdk/goal/contracts.js").GoalRecord) => void
|
|
11
|
+
onOutcome?: (goal: import("../zapsdk/goal/contracts.js").GoalRecord) => void
|
|
12
|
+
}
|
|
13
|
+
export async function runGoalRunner(id: string, observer: GoalRunnerObserver = {}): Promise<number> {
|
|
8
14
|
if (process.platform === "win32") {
|
|
9
15
|
process.stderr.write("Goal execution is not yet supported on Windows: process-tree sealing cannot be verified.\n")
|
|
10
16
|
return 2
|
|
11
17
|
}
|
|
12
18
|
const store = new GoalStore(goalDatabasePath(), { requireLedger: true })
|
|
19
|
+
let revision = -1
|
|
20
|
+
const publish = () => {
|
|
21
|
+
const goal = store.get(id)
|
|
22
|
+
if (goal && goal.stateRevision !== revision) { revision = goal.stateRevision; observer.onState?.(goal) }
|
|
23
|
+
}
|
|
24
|
+
const pause = () => {
|
|
25
|
+
const goal = store.get(id)
|
|
26
|
+
if (goal && ["created", "running"].includes(goal.status)) store.requestControl(id, "pause")
|
|
27
|
+
}
|
|
28
|
+
const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const
|
|
29
|
+
if (observer.onOutcome) for (const name of signals) process.on(name, pause)
|
|
30
|
+
observer.signal?.addEventListener("abort", pause, { once: true })
|
|
31
|
+
const timer = observer.onState ? setInterval(publish, 100) : undefined
|
|
13
32
|
try {
|
|
14
33
|
const goal = store.get(id)
|
|
15
34
|
if (!goal || goal.cwd !== process.cwd()) throw new Error("Goal does not belong to the current workspace")
|
|
16
|
-
const controller = new GoalController(store, new LocalGoalHost(id), id)
|
|
35
|
+
const controller = new GoalController(store, new LocalGoalHost(id, observer.onEvent), id)
|
|
17
36
|
if (goal.inFlight) {
|
|
18
37
|
const reconciled = await controller.recover()
|
|
19
38
|
if (reconciled.inFlight || reconciled.status === "blocked") {
|
|
20
|
-
|
|
39
|
+
observer.onState?.(reconciled); observer.onOutcome?.(reconciled)
|
|
40
|
+
if (!observer.onOutcome) process.stderr.write(`Goal recovery blocked: ${reconciled.stopReason ?? "unknown effects"}\n`)
|
|
21
41
|
return 1
|
|
22
42
|
}
|
|
23
43
|
}
|
|
44
|
+
publish()
|
|
45
|
+
if (observer.signal?.aborted) { pause(); const stopped = store.get(id)!; observer.onOutcome?.(stopped); return 1 }
|
|
24
46
|
const outcome = await controller.run({ automatic: true })
|
|
25
|
-
|
|
47
|
+
publish()
|
|
48
|
+
observer.onOutcome?.(outcome)
|
|
49
|
+
if (!observer.onOutcome) process.stdout.write(JSON.stringify({ id: outcome.id, status: outcome.status, phase: outcome.phase, reason: outcome.stopReason, delivery: outcome.delivery }) + "\n")
|
|
26
50
|
return outcome.status === "completed" || outcome.status === "ready_for_delivery" ? 0 : 1
|
|
27
51
|
} catch (error) {
|
|
52
|
+
if (observer.onOutcome) throw error
|
|
28
53
|
process.stderr.write(`Goal runner: ${error instanceof Error ? error.message : String(error)}\n`)
|
|
29
54
|
return 1
|
|
30
|
-
} finally {
|
|
55
|
+
} finally {
|
|
56
|
+
if (timer) clearInterval(timer)
|
|
57
|
+
observer.signal?.removeEventListener("abort", pause)
|
|
58
|
+
if (observer.onOutcome) for (const name of signals) process.removeListener(name, pause)
|
|
59
|
+
store.close()
|
|
60
|
+
}
|
|
31
61
|
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { goalCommand, goalDatabasePath } from "./goal-command.js"
|
|
2
|
+
import { GoalStore } from "../zapsdk/goal/store.js"
|
|
3
|
+
import type { GoalRecord } from "../zapsdk/goal/contracts.js"
|
|
4
|
+
import type { AgentEvent } from "../zapsdk/agent/events.js"
|
|
5
|
+
import type { PermissionMode } from "./config.js"
|
|
6
|
+
|
|
7
|
+
export interface GoalSessionOptions {
|
|
8
|
+
permissionMode?: PermissionMode
|
|
9
|
+
sessionId?: string
|
|
10
|
+
signal?: AbortSignal
|
|
11
|
+
onStart?: (goal: GoalRecord) => void
|
|
12
|
+
onMessage: (text: string) => void
|
|
13
|
+
onState?: (goal: GoalRecord) => void
|
|
14
|
+
onEvent?: (event: AgentEvent, scope: string) => void
|
|
15
|
+
}
|
|
16
|
+
const attached = new Map<string, { id: string; background: () => void; pause: () => void; done: Promise<void> }>()
|
|
17
|
+
const sessionKey = (cwd: string, sessionId?: string) => JSON.stringify([goalDatabasePath(), cwd, sessionId])
|
|
18
|
+
|
|
19
|
+
/** Control commands bypass the ordinary turn queue while its Goal is active. */
|
|
20
|
+
export function isGoalSessionControl(text: string): boolean {
|
|
21
|
+
return /^\/goal\s+(?:status|watch|list|pause|cancel|background|budget)(?:\s|$)/.test(text.trim())
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function executeGoalCommand(args: string[], cwd: string, options: GoalSessionOptions): Promise<number> {
|
|
25
|
+
const key = sessionKey(cwd, options.sessionId)
|
|
26
|
+
if (args[0] === "background") {
|
|
27
|
+
const detach = attached.get(key)
|
|
28
|
+
if (!detach || args.length > 2 || args[1] && args[1] !== detach.id) throw new Error("No foreground Goal in this session")
|
|
29
|
+
detach.background()
|
|
30
|
+
options.onMessage("Goal will switch to background at the next safe phase boundary.")
|
|
31
|
+
return 0
|
|
32
|
+
}
|
|
33
|
+
if (attached.has(key) && (!args[0] || !["status", "watch", "list", "pause", "cancel", "budget", "help"].includes(args[0]))) throw new Error("A foreground Goal is already running in this session")
|
|
34
|
+
let foreground: GoalRecord | undefined
|
|
35
|
+
const message = goalCommand(args, cwd, options.permissionMode, process.platform, options.sessionId, goal => {
|
|
36
|
+
if (attached.has(key)) throw new Error("A foreground Goal is already running in this session")
|
|
37
|
+
foreground = goal
|
|
38
|
+
})
|
|
39
|
+
options.onMessage(message)
|
|
40
|
+
if (!foreground) return 0
|
|
41
|
+
const goal = foreground as GoalRecord
|
|
42
|
+
let backgroundRequested = false
|
|
43
|
+
let settle!: () => void
|
|
44
|
+
const done = new Promise<void>(resolve => { settle = resolve })
|
|
45
|
+
attached.set(key, { id: goal.id, done, pause: () => {
|
|
46
|
+
const store = new GoalStore(goalDatabasePath())
|
|
47
|
+
try { const current = store.get(goal.id); if (current && ["created", "running"].includes(current.status)) store.requestControl(goal.id, "pause") } finally { store.close() }
|
|
48
|
+
}, background: () => {
|
|
49
|
+
const store = new GoalStore(goalDatabasePath())
|
|
50
|
+
try {
|
|
51
|
+
const current = store.get(goal.id)
|
|
52
|
+
if (!current?.owner || current.control) throw new Error("Goal is already stopping")
|
|
53
|
+
store.update(goal.id, current.ownerEpoch, current.owner.instanceId, value => { value.yieldRequested = true })
|
|
54
|
+
backgroundRequested = true
|
|
55
|
+
} finally { store.close() }
|
|
56
|
+
} })
|
|
57
|
+
let outcome: GoalRecord | undefined
|
|
58
|
+
try {
|
|
59
|
+
options.onStart?.(goal)
|
|
60
|
+
const { runGoalRunner } = await import("./goal-runner.js")
|
|
61
|
+
const code = await runGoalRunner(goal.id, { signal: options.signal, onState: options.onState,
|
|
62
|
+
onEvent: (event, operationId) => options.onEvent?.(event, `${goal.id}:${operationId}`),
|
|
63
|
+
onOutcome: value => { outcome = value },
|
|
64
|
+
})
|
|
65
|
+
if (backgroundRequested && outcome?.status === "paused" && outcome.stopReason === "USER_INPUT_PENDING") {
|
|
66
|
+
options.onMessage(goalCommand(["resume", goal.id, "--background"], cwd, options.permissionMode, process.platform, options.sessionId))
|
|
67
|
+
options.onMessage(`Goal ${goal.id} is now running in background.`)
|
|
68
|
+
return 0
|
|
69
|
+
}
|
|
70
|
+
if (outcome) {
|
|
71
|
+
options.onMessage(`Goal ${outcome.id} · ${outcome.status}${outcome.stopReason ? ` · ${outcome.stopReason}` : ""}`)
|
|
72
|
+
if (outcome.delivery) options.onMessage(`Goal delivery: ${JSON.stringify(outcome.delivery)}`)
|
|
73
|
+
}
|
|
74
|
+
return code
|
|
75
|
+
} finally { attached.delete(key); settle() }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Separate process-local content/run identities across planning and workers. */
|
|
79
|
+
export function scopeGoalEvent(event: AgentEvent, scope: string): AgentEvent {
|
|
80
|
+
const value = { ...event } as unknown as Record<string, any>
|
|
81
|
+
for (const key of ["id", "subagentId", "requestId"]) if (typeof value[key] === "string") value[key] = `${scope}:${value[key]}`
|
|
82
|
+
if (value.path) value.path = value.path.map((id: string) => `${scope}:${id}`)
|
|
83
|
+
if (value.type === "content_final" && value.kind === "tool_result" && ["agent", "delegate_agent"].includes(value.toolName)
|
|
84
|
+
&& typeof value.result?.meta?.subagentId === "string") {
|
|
85
|
+
value.result = { ...value.result, meta: { ...value.result.meta, subagentId: `${scope}:${value.result.meta.subagentId}` } }
|
|
86
|
+
}
|
|
87
|
+
if (value.run) {
|
|
88
|
+
value.run = { ...value.run }
|
|
89
|
+
for (const key of ["runId", "parentRunId", "toolCallId"]) if (value.run[key]) value.run[key] = `${scope}:${value.run[key]}`
|
|
90
|
+
}
|
|
91
|
+
return value as AgentEvent
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Terminal shutdown waits for the owned phase to seal before process.exit. */
|
|
95
|
+
export async function closeForegroundGoals(): Promise<void> {
|
|
96
|
+
const sessions = [...attached.values()]
|
|
97
|
+
for (const session of sessions) session.pause()
|
|
98
|
+
await Promise.all(sessions.map(session => session.done))
|
|
99
|
+
}
|
|
@@ -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",
|
|
@@ -70,6 +79,8 @@ export interface GoalPhaseInput {
|
|
|
70
79
|
privateGitOwnerDirectory?: string
|
|
71
80
|
permissionMode?: PermissionMode
|
|
72
81
|
signal?: AbortSignal
|
|
82
|
+
/** Guarded public runtime events; never a source of process-seal receipts. */
|
|
83
|
+
onEvent?: (event: AgentEvent) => void
|
|
73
84
|
machineCheck?: "bun" | "npm" | "pytest" | "go"
|
|
74
85
|
dependencyInstall?: "npm"
|
|
75
86
|
/** Host must durably record ownership synchronously before input is sent. */
|
|
@@ -78,13 +89,14 @@ export interface GoalPhaseInput {
|
|
|
78
89
|
onStopped?: (pid: number) => void
|
|
79
90
|
}
|
|
80
91
|
|
|
81
|
-
type WorkerInput = Omit<GoalPhaseInput, "signal" | "onSpawn" | "onStopped"> & { allowSealedShell?: boolean }
|
|
92
|
+
type WorkerInput = Omit<GoalPhaseInput, "signal" | "onSpawn" | "onStopped" | "onEvent"> & { allowSealedShell?: boolean; streamEvents?: boolean }
|
|
82
93
|
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
94
|
|
|
84
95
|
/** Check only concrete existing directories. A Host-owned ledger must not sit
|
|
85
96
|
* underneath a model-writable workspace. */
|
|
86
97
|
function validateInput(input: WorkerInput): void {
|
|
87
98
|
if (!input || typeof input !== "object" || !isAbsolute(input.cwd) || !isAbsolute(input.ledgerPath)
|
|
99
|
+
|| input.streamEvents !== undefined && typeof input.streamEvents !== "boolean"
|
|
88
100
|
|| typeof input.prompt !== "string" || !input.prompt.trim() || input.prompt.length > 1024 * 1024
|
|
89
101
|
|| typeof input.goalId !== "string" || !input.goalId || !Number.isSafeInteger(input.epoch) || input.epoch < 0
|
|
90
102
|
|| !["planner", "worker", "verifier", "repair", "maintenance", "finalization"].includes(input.role)
|
|
@@ -107,7 +119,7 @@ function validateInput(input: WorkerInput): void {
|
|
|
107
119
|
/** Execute one phase in a fresh process. The process cwd is established before
|
|
108
120
|
* importing the headless Runtime's cwd-bound singleton modules. */
|
|
109
121
|
async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult> {
|
|
110
|
-
const { signal, onSpawn, onStopped, ...workerInput } = input
|
|
122
|
+
const { signal, onSpawn, onStopped, onEvent, ...workerInput } = input
|
|
111
123
|
validateInput(workerInput)
|
|
112
124
|
signal?.throwIfAborted()
|
|
113
125
|
// Decide before recording ownership and sending the worker any input. A
|
|
@@ -130,7 +142,7 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
130
142
|
stdio: ["pipe", "pipe", "pipe"],
|
|
131
143
|
env: { ...safeEnvironment, PATH: "/usr/bin:/bin:/usr/sbin:/sbin", ZAPCODE_DEVTOOLS_PORT: "", ZAPCODE_HOST_PROTOCOL_PORT: "" },
|
|
132
144
|
})
|
|
133
|
-
let output = "", cancelled = false, spawnRecorded = false, protocolError: Error | undefined, spawnError: unknown
|
|
145
|
+
let output = "", resultOutput: string | undefined, cancelled = false, spawnRecorded = false, protocolError: Error | undefined, spawnError: unknown
|
|
134
146
|
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
135
147
|
let pipeTimer: ReturnType<typeof setTimeout> | undefined
|
|
136
148
|
const killGroup = (signalName: NodeJS.Signals) => {
|
|
@@ -165,6 +177,21 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
165
177
|
child.stdout.setEncoding("utf8")
|
|
166
178
|
child.stdout.on("data", (chunk: string) => {
|
|
167
179
|
output += chunk
|
|
180
|
+
if (onEvent) {
|
|
181
|
+
let newline: number
|
|
182
|
+
while ((newline = output.indexOf("\n")) >= 0 && !protocolError) {
|
|
183
|
+
const line = output.slice(0, newline); output = output.slice(newline + 1)
|
|
184
|
+
if (!line.trim()) continue
|
|
185
|
+
try {
|
|
186
|
+
if (Buffer.byteLength(line) > 16 * 1024 * 1024) throw new Error("Goal phase output exceeds protocol limit")
|
|
187
|
+
const frame = JSON.parse(line)
|
|
188
|
+
if (frame.type === "event" && frame.event && typeof frame.event.type === "string" && !resultOutput) {
|
|
189
|
+
onEvent(frame.event)
|
|
190
|
+
} else if (["result", "machine", "fatal"].includes(frame.type) && !resultOutput) resultOutput = line
|
|
191
|
+
else throw new Error("Invalid Goal phase stream frame")
|
|
192
|
+
} catch (error) { protocolError = error instanceof Error ? error : new Error("Invalid Goal phase stream"); abort() }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
168
195
|
if (Buffer.byteLength(output) > 16 * 1024 * 1024 && !protocolError) {
|
|
169
196
|
protocolError = new Error("Goal phase output exceeds protocol limit")
|
|
170
197
|
abort()
|
|
@@ -178,7 +205,7 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
178
205
|
if (!child.pid) throw new Error("Goal phase worker has no pid")
|
|
179
206
|
onSpawn?.(child.pid, allowSealedShell)
|
|
180
207
|
spawnRecorded = true
|
|
181
|
-
child.stdin.end(JSON.stringify({ ...workerInput, allowSealedShell }))
|
|
208
|
+
child.stdin.end(JSON.stringify({ ...workerInput, allowSealedShell, ...(onEvent ? { streamEvents: true } : {}) }))
|
|
182
209
|
} catch (error) {
|
|
183
210
|
spawnError = error
|
|
184
211
|
abort()
|
|
@@ -198,8 +225,9 @@ async function runGoalPhaseProcess(input: GoalPhaseInput): Promise<WorkerResult>
|
|
|
198
225
|
if (spawnError) throw spawnError
|
|
199
226
|
if (protocolError) throw protocolError
|
|
200
227
|
if (cancelled) throw new Error("GOAL_PHASE_CANCELLED")
|
|
228
|
+
if (onEvent && resultOutput && output.trim()) throw new Error("Invalid trailing Goal phase output")
|
|
201
229
|
let response: WorkerResult
|
|
202
|
-
try { response = JSON.parse(output) as WorkerResult } catch { throw new Error(`Goal phase process returned invalid output (exit ${exitCode})`) }
|
|
230
|
+
try { response = JSON.parse(resultOutput ?? output) as WorkerResult } catch { throw new Error(`Goal phase process returned invalid output (exit ${exitCode})`) }
|
|
203
231
|
if (response.type === "fatal") throw new GoalPhaseError(response.code ?? goalPhaseFailureCode(response.message))
|
|
204
232
|
if (response.type === "machine") {
|
|
205
233
|
if (!input.machineCheck || exitCode !== 0 || response.result.runtime?.processSeal?.state !== "sealed") throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
@@ -287,9 +315,9 @@ export async function runGoalPhaseWorker(): Promise<number> {
|
|
|
287
315
|
const executor = new ToolExecutor(registry, { cwd: input.cwd, onApproval: async () => true,
|
|
288
316
|
executionBroker: requireProcessSealing(environment.broker, () => { unsealed = true }) })
|
|
289
317
|
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 })
|
|
318
|
+
const result = await runGoalMachineCommand(command, () => executor.execute("bash", { command }), input.streamEvents ? event => { process.stdout.write(JSON.stringify({ type: "event", event }) + "\n") } : undefined)
|
|
291
319
|
if (unsealed || result.runtime?.processSeal?.state !== "sealed") throw new Error("GOAL_SEAL_UNCONFIRMED")
|
|
292
|
-
process.stdout.write(JSON.stringify({ type: "machine", result } satisfies WorkerResult))
|
|
320
|
+
process.stdout.write(JSON.stringify({ type: "machine", result } satisfies WorkerResult) + "\n")
|
|
293
321
|
return 0
|
|
294
322
|
}
|
|
295
323
|
const mode = input.permissionMode ?? config.permissionMode
|
|
@@ -320,6 +348,7 @@ export async function runGoalPhaseWorker(): Promise<number> {
|
|
|
320
348
|
if (event.type === "content_final" && event.kind === "tool_call") toolCalls++
|
|
321
349
|
if (event.type === "error") runtimeError = event.error
|
|
322
350
|
sealTracker.observe(event, permitted("bash"))
|
|
351
|
+
if (input.streamEvents) process.stdout.write(JSON.stringify({ type: "event", event }) + "\n")
|
|
323
352
|
}, progress() {},
|
|
324
353
|
finalize(value) { summary = value },
|
|
325
354
|
failure(value) { failure = value },
|
|
@@ -369,12 +398,12 @@ export async function runGoalPhaseWorker(): Promise<number> {
|
|
|
369
398
|
if (unavailableTool) throw new Error("GOAL_UNMETERED_TOOL_UNAVAILABLE")
|
|
370
399
|
if (!summary) throw new Error(failure?.code ?? `Headless phase failed (${exitCode})`)
|
|
371
400
|
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))
|
|
401
|
+
...(exitCode !== 0 ? { failureCode: goalPhaseFailureCode(runtimeError || summary.error || summary.outcome?.execution.error?.code || "") } : {}), dependencyHash: dependencyProof?.dependencyHash } satisfies WorkerResult) + "\n")
|
|
373
402
|
return exitCode
|
|
374
403
|
} finally { ledger.close() }
|
|
375
404
|
} catch (error) {
|
|
376
405
|
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))
|
|
406
|
+
process.stdout.write(JSON.stringify({ type: "fatal", message: goalPhaseFailureCode(message), code: goalPhaseFailureCode(message) } satisfies WorkerResult) + "\n")
|
|
378
407
|
return 2
|
|
379
408
|
}
|
|
380
409
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { executeGoalCommand } from "../goal-session.js"
|
|
2
|
+
import { createGoalPresentation } from "../agent/goalPresentation.js"
|
|
1
3
|
import { AgentBudget } from "../../zapsdk/agent/budget.js"
|
|
2
4
|
import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
|
|
3
5
|
import { accumulateTokenUsage } from "../../zapsdk/agent/token-usage.js"
|
|
@@ -354,6 +356,7 @@ export function useAgentRunner({
|
|
|
354
356
|
onUpdateConfig,
|
|
355
357
|
}: UseAgentRunnerOptions) {
|
|
356
358
|
const [status, setStatus] = useState("ready")
|
|
359
|
+
const [goalRunning, setGoalRunning] = useState(false)
|
|
357
360
|
const [outputThroughput, setOutputThroughput] = useState<OutputThroughputSample>()
|
|
358
361
|
const [providerRequest, setProviderRequest] = useState<ProviderRequestEvent>()
|
|
359
362
|
const [step, setStep] = useState(0)
|
|
@@ -937,6 +940,47 @@ export function useAgentRunner({
|
|
|
937
940
|
turnStartUiLogIndexRef,
|
|
938
941
|
])
|
|
939
942
|
|
|
943
|
+
const runGoalCommand = useCallback(async (args: string[]): Promise<number> => {
|
|
944
|
+
const controller = new AbortController()
|
|
945
|
+
let presentation: ReturnType<typeof createGoalPresentation> | undefined
|
|
946
|
+
let stateLabel = ""
|
|
947
|
+
try {
|
|
948
|
+
return await executeGoalCommand(args, cwd, {
|
|
949
|
+
permissionMode: config.permissionMode, sessionId: getCurrentSessionId(), signal: controller.signal,
|
|
950
|
+
onStart: () => {
|
|
951
|
+
if (running.current) throw new Error("The current session is already running a task")
|
|
952
|
+
running.current = true; abortRef.current = controller; setGoalRunning(true); setStatus("preparing")
|
|
953
|
+
agentRunStore.clear()
|
|
954
|
+
presentation = createGoalPresentation({ currentConfig: config, controller,
|
|
955
|
+
createPreview: () => {
|
|
956
|
+
const preview = createStreamingPreview({ addLog, setStreamingText, setIsStreaming, setThinkingText, setIsThinking, getIsFrozen: getIsFrozen ?? (() => false) })
|
|
957
|
+
registerStaticFlushCallback?.(() => preview.onStaticFlushed())
|
|
958
|
+
return preview
|
|
959
|
+
},
|
|
960
|
+
setStatus, setStep, setActiveTool, setActiveToolBytes, setProviderRequest, setOutputThroughput,
|
|
961
|
+
addLog, replaceLog, peekNextLogId, onAgentRunState: run => agentRunStore.apply(run),
|
|
962
|
+
})
|
|
963
|
+
},
|
|
964
|
+
onEvent: (event, scope) => presentation?.event(event, scope),
|
|
965
|
+
onState: goal => {
|
|
966
|
+
const label = `${goal.status}/${goal.phase ?? "preparing"} · ${goal.tasks.filter(task => task.status === "passed").length}/${goal.tasks.length} tasks`
|
|
967
|
+
if (label !== stateLabel) {
|
|
968
|
+
stateLabel = label
|
|
969
|
+
addLog("system", `Goal ${label}${goal.stopReason ? ` · ${goal.stopReason}` : ""}`)
|
|
970
|
+
if (!controller.signal.aborted) setStatus(goal.phase ?? "preparing")
|
|
971
|
+
}
|
|
972
|
+
},
|
|
973
|
+
onMessage: text => addLog("system", text),
|
|
974
|
+
})
|
|
975
|
+
} finally {
|
|
976
|
+
if (presentation) {
|
|
977
|
+
presentation.finish(); running.current = false
|
|
978
|
+
if (abortRef.current === controller) abortRef.current = null
|
|
979
|
+
setGoalRunning(false); setStatus("ready"); setActiveTool(""); setStep(0); setProviderRequest(undefined)
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
}, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore])
|
|
983
|
+
|
|
940
984
|
const runAgentRef = useRef(runAgent)
|
|
941
985
|
runAgentRef.current = runAgent
|
|
942
986
|
useEffect(() => {
|
|
@@ -977,6 +1021,8 @@ export function useAgentRunner({
|
|
|
977
1021
|
|
|
978
1022
|
return {
|
|
979
1023
|
runAgent,
|
|
1024
|
+
runGoalCommand,
|
|
1025
|
+
goalRunning,
|
|
980
1026
|
running,
|
|
981
1027
|
abortRef,
|
|
982
1028
|
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
|
]
|
package/zapsdk/merge/copy.ts
CHANGED
|
@@ -99,17 +99,22 @@ export async function mergeCopyArtifacts(
|
|
|
99
99
|
.sort((a, b) => a.path.split("/").length - b.path.split("/").length);
|
|
100
100
|
for (const operation of directories) operation.workingMode = operation.beforeMode! | 0o700;
|
|
101
101
|
async function checkRoot(): Promise<string[]> {
|
|
102
|
-
const
|
|
102
|
+
const rawLinks: Record<string, string> = Object.create(null);
|
|
103
|
+
const current = await scanCopyTree(root, true, true, true, undefined, undefined, rawLinks);
|
|
103
104
|
const conflicts = new Set<string>();
|
|
104
105
|
for (const path of changedPaths) {
|
|
105
106
|
if (!sameEntry(current[path], base[path])) conflicts.add(path);
|
|
107
|
+
const originalLink = manager.originalSourceLink(path) ?? (base[path]?.kind === "symlink" ? base[path].target : undefined);
|
|
108
|
+
if (originalLink !== undefined && originalLink !== rawLinks[path]) conflicts.add(path);
|
|
106
109
|
// A replaced/deleted directory also owns its descendants. Never discard
|
|
107
110
|
// concurrent additions or excluded private/control files inside it.
|
|
108
111
|
if (base[path]?.kind === "directory" && desired[path]?.kind !== "directory") {
|
|
109
112
|
for (const child of new Set([...Object.keys(base), ...Object.keys(current)])) {
|
|
110
113
|
if (descendant(child, path) && !sameEntry(current[child], base[child])) conflicts.add(child);
|
|
111
114
|
}
|
|
112
|
-
|
|
115
|
+
// Root validation above already checked link targets; this subtree
|
|
116
|
+
// inventory never follows links and may contain links to root siblings.
|
|
117
|
+
const complete = await scanCopyTree(join(root, path), false, false);
|
|
113
118
|
for (const child of Object.keys(complete)) {
|
|
114
119
|
// Excluded environments may contain only regular files (--copies).
|
|
115
120
|
// Replacing their parent must not silently delete those local files.
|
|
@@ -140,15 +145,19 @@ export async function mergeCopyArtifacts(
|
|
|
140
145
|
// on failure if rollback cannot complete; never discard the user's originals.
|
|
141
146
|
const transaction = join(root, `.zap-copy-merge-${randomUUID()}`);
|
|
142
147
|
for (const operation of operations) {
|
|
143
|
-
operation.before = await operationOid(join(
|
|
148
|
+
operation.before = await operationOid(join(root, operation.path), operation.modeOnly);
|
|
144
149
|
operation.after = await operationOid(join(staging, operation.path), operation.modeOnly);
|
|
145
150
|
if (!operation.modeOnly && operation.beforeMode !== undefined) {
|
|
146
|
-
operation.beforeWorking = await copyPathOid(join(
|
|
151
|
+
operation.beforeWorking = await copyPathOid(join(root, operation.path), operation.beforeMode | 0o700);
|
|
147
152
|
}
|
|
148
153
|
if (!operation.modeOnly && operation.afterMode !== undefined) {
|
|
149
154
|
operation.afterWorking = await copyPathOid(join(staging, operation.path), operation.afterMode | 0o700);
|
|
150
155
|
}
|
|
151
156
|
}
|
|
157
|
+
// Compare the canonical baseline again after binding the original raw bytes
|
|
158
|
+
// for rollback (source absolute symlinks are relocated in snapshots).
|
|
159
|
+
drift = await checkRoot();
|
|
160
|
+
if (drift.length) return rejected("Root workspace changed while binding the merge", drift);
|
|
152
161
|
const journal: CopyMergeJournal = { version: 1, root, transaction, artifactIds, operations, state: "applying" };
|
|
153
162
|
await writeCopyMergeJournal(batch, journal);
|
|
154
163
|
await mkdir(transaction, { mode: 0o700 });
|
|
@@ -191,6 +191,7 @@ function leaseFromState(workspace: PersistedWorkspaceState): WorkspaceLease {
|
|
|
191
191
|
repoPath: workspace.repoPath,
|
|
192
192
|
baseOid: workspace.baseOid,
|
|
193
193
|
batchPath: workspace.batchPath,
|
|
194
|
+
...(workspace.sourceLinksHash ? { sourceLinksHash: workspace.sourceLinksHash } : {}),
|
|
194
195
|
};
|
|
195
196
|
}
|
|
196
197
|
|
|
@@ -431,6 +431,7 @@ export class RuntimeStateTracker {
|
|
|
431
431
|
mode: event.lease.mode,
|
|
432
432
|
path: event.lease.path,
|
|
433
433
|
batchPath: event.lease.batchPath,
|
|
434
|
+
...(event.lease.sourceLinksHash ? { sourceLinksHash: event.lease.sourceLinksHash } : {}),
|
|
434
435
|
status: "acquiring",
|
|
435
436
|
acquiredAt: event.timestamp,
|
|
436
437
|
updatedAt: event.timestamp,
|
|
@@ -449,6 +450,7 @@ export class RuntimeStateTracker {
|
|
|
449
450
|
repoPath: event.lease.repoPath,
|
|
450
451
|
baseOid: event.lease.baseOid,
|
|
451
452
|
batchPath: event.lease.batchPath,
|
|
453
|
+
...(event.lease.sourceLinksHash ? { sourceLinksHash: event.lease.sourceLinksHash } : {}),
|
|
452
454
|
status: event.type === "workspace_hydrated" ? "preserved" : "active",
|
|
453
455
|
acquiredAt: existing?.acquiredAt ?? event.timestamp,
|
|
454
456
|
updatedAt: event.timestamp,
|
package/zapsdk/workspace/copy.ts
CHANGED
|
@@ -105,10 +105,26 @@ async function fileEntry(path: string, mode: number): Promise<CopyEntry> {
|
|
|
105
105
|
} finally { await handle.close(); }
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/** Find the source-root spelling without flattening any link inside it. */
|
|
109
|
+
async function sourceLinkPath(root: string, canonicalRoot: string, target: string): Promise<string> {
|
|
110
|
+
for (const spelling of [resolve(root), canonicalRoot]) {
|
|
111
|
+
if (target === spelling) return "";
|
|
112
|
+
if (target.startsWith(spelling + sep)) return target.slice(spelling.length + 1);
|
|
113
|
+
}
|
|
114
|
+
// A host prefix such as /tmp may itself alias /private/tmp. Resolve only
|
|
115
|
+
// ancestors that denote the root, preserving the target's internal chain.
|
|
116
|
+
for (let parent = target; ; parent = dirname(parent)) {
|
|
117
|
+
if (await realpath(parent) === canonicalRoot) return target === parent ? "" : target.slice(parent.length + 1);
|
|
118
|
+
if (dirname(parent) === parent) break;
|
|
119
|
+
}
|
|
120
|
+
throw new Error("Absolute symlink does not name this source workspace");
|
|
121
|
+
}
|
|
122
|
+
|
|
108
123
|
/** Never follows directory links. Hashing is streamed, including large inputs.
|
|
109
124
|
* source=true excludes private/control files from the initial snapshot only;
|
|
110
125
|
* introducing one in a child is rejected rather than silently losing edits. */
|
|
111
|
-
export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>, privateGit?: PrivateGitBinding): Promise<CopyTree> {
|
|
126
|
+
export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>, privateGit?: PrivateGitBinding, originalLinks?: Record<string, string>): Promise<CopyTree> {
|
|
127
|
+
const canonicalRoot = await realpath(root);
|
|
112
128
|
const info = await lstat(root);
|
|
113
129
|
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`Unsafe copy workspace root: ${root}`);
|
|
114
130
|
const validatePrivateGit = async () => {
|
|
@@ -134,16 +150,25 @@ export async function scanCopyTree(root: string, source = false, validateLinks =
|
|
|
134
150
|
const full = join(root, path);
|
|
135
151
|
const stat = await lstat(full);
|
|
136
152
|
if (stat.isSymbolicLink()) {
|
|
137
|
-
|
|
138
|
-
if (
|
|
153
|
+
let target = await readlink(full);
|
|
154
|
+
if (originalLinks) originalLinks[path] = target;
|
|
155
|
+
if (validateLinks && (!source && isAbsolute(target) || !isAbsolute(target) && !isWithin(root, resolve(dirname(full), target)))) {
|
|
139
156
|
throw new Error(`Symlink escapes copy workspace: ${path}`);
|
|
140
157
|
}
|
|
141
158
|
// Reject dangling/cyclic links, and links which escape indirectly.
|
|
142
159
|
if (validateLinks) {
|
|
143
160
|
const resolved = await realpath(full);
|
|
144
|
-
if (!isWithin(
|
|
161
|
+
if (!isWithin(canonicalRoot, resolved) || excludedCopyPath(relative(canonicalRoot, resolved).split(sep).join("/"))) {
|
|
145
162
|
throw new Error(`Unsafe copy workspace symlink: ${path}`);
|
|
146
163
|
}
|
|
164
|
+
// Source links may name a host path inside the same tree. Relocate
|
|
165
|
+
// only that verified target; snapshots must never point at the host.
|
|
166
|
+
if (source && isAbsolute(target)) {
|
|
167
|
+
const sourcePath = await sourceLinkPath(root, canonicalRoot, target);
|
|
168
|
+
if (excludedCopyPath(sourcePath)) throw new Error(`Unsafe copy workspace symlink: ${path}`);
|
|
169
|
+
const depth = dirname(path) === "." ? 0 : dirname(path).split("/").length;
|
|
170
|
+
target = "../".repeat(depth) + (sourcePath || ".");
|
|
171
|
+
}
|
|
147
172
|
}
|
|
148
173
|
tree[path] = { kind: "symlink", target };
|
|
149
174
|
} else if (stat.isDirectory()) {
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import {
|
|
4
4
|
copyFile,
|
|
5
5
|
lstat,
|
|
6
6
|
mkdir,
|
|
7
7
|
mkdtemp,
|
|
8
8
|
realpath,
|
|
9
|
+
readFile,
|
|
9
10
|
readlink,
|
|
10
11
|
rm,
|
|
11
12
|
symlink,
|
|
@@ -142,6 +143,8 @@ export class WorkspaceManager {
|
|
|
142
143
|
private mode: "isolated-git" | "isolated-copy" = "isolated-git";
|
|
143
144
|
private templatePath?: string;
|
|
144
145
|
private baseOid?: string;
|
|
146
|
+
private sourceLinksHash?: string;
|
|
147
|
+
private sourceLinks: Record<string, string> = Object.create(null);
|
|
145
148
|
private initializePromise?: Promise<void>;
|
|
146
149
|
private artifacts = new Map<string, AgentArtifact>();
|
|
147
150
|
private leases = new Map<string, WorkspaceLease>();
|
|
@@ -233,6 +236,7 @@ export class WorkspaceManager {
|
|
|
233
236
|
repoPath,
|
|
234
237
|
baseOid: this.baseOid,
|
|
235
238
|
batchPath: this.batchRoot,
|
|
239
|
+
...(this.sourceLinksHash ? { sourceLinksHash: this.sourceLinksHash } : {}),
|
|
236
240
|
...(privateGit ? { privateGit } : {}),
|
|
237
241
|
};
|
|
238
242
|
this.leases.set(lease.workspaceId, lease);
|
|
@@ -499,6 +503,19 @@ export class WorkspaceManager {
|
|
|
499
503
|
this.batchRoot = realBatch;
|
|
500
504
|
this.templatePath = snapshotPath;
|
|
501
505
|
this.baseOid = input.leases[0].baseOid;
|
|
506
|
+
const sourceLinksHash = input.leases[0].sourceLinksHash;
|
|
507
|
+
if (input.leases.some(lease => lease.sourceLinksHash !== sourceLinksHash)) throw new Error("Source link baseline identity mismatch");
|
|
508
|
+
if (copy && sourceLinksHash) {
|
|
509
|
+
const sourceLinksPath = join(realBatch, "source-links.json");
|
|
510
|
+
const info = await lstat(sourceLinksPath);
|
|
511
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 16 * 1024 * 1024) throw new Error("Unsafe source link baseline");
|
|
512
|
+
const bytes = await readFile(sourceLinksPath);
|
|
513
|
+
if (createHash("sha256").update(bytes).digest("hex") !== sourceLinksHash) throw new Error("Source link baseline was modified");
|
|
514
|
+
const links = JSON.parse(bytes.toString("utf8"));
|
|
515
|
+
const baseline = await scanCopyTree(snapshotPath);
|
|
516
|
+
if (!links || Array.isArray(links) || typeof links !== "object" || Object.entries(links).some(([path, target]) => baseline[path]?.kind !== "symlink" || typeof target !== "string")) throw new Error("Invalid source link baseline");
|
|
517
|
+
this.sourceLinks = links; this.sourceLinksHash = sourceLinksHash;
|
|
518
|
+
}
|
|
502
519
|
this.initializePromise = Promise.resolve();
|
|
503
520
|
for (const lease of input.leases) this.leases.set(lease.workspaceId, { ...lease });
|
|
504
521
|
for (const artifact of input.artifacts) this.artifacts.set(artifact.artifactId, { ...artifact });
|
|
@@ -525,6 +542,10 @@ export class WorkspaceManager {
|
|
|
525
542
|
return this.templatePath;
|
|
526
543
|
}
|
|
527
544
|
|
|
545
|
+
originalSourceLink(path: string): string | undefined {
|
|
546
|
+
return Object.hasOwn(this.sourceLinks, path) ? this.sourceLinks[path] : undefined;
|
|
547
|
+
}
|
|
548
|
+
|
|
528
549
|
rootRepoPath(): string {
|
|
529
550
|
if (!this.repoRoot) throw new Error("Workspace snapshot is not initialized");
|
|
530
551
|
return this.repoRoot;
|
|
@@ -557,6 +578,7 @@ export class WorkspaceManager {
|
|
|
557
578
|
this.workspaceTempRoot = undefined;
|
|
558
579
|
this.templatePath = undefined;
|
|
559
580
|
this.baseOid = undefined;
|
|
581
|
+
this.sourceLinksHash = undefined; this.sourceLinks = Object.create(null);
|
|
560
582
|
this.initializePromise = undefined;
|
|
561
583
|
this.artifacts.clear();
|
|
562
584
|
this.leases.clear();
|
|
@@ -575,6 +597,7 @@ export class WorkspaceManager {
|
|
|
575
597
|
this.workspaceTempRoot = undefined;
|
|
576
598
|
this.templatePath = undefined;
|
|
577
599
|
this.baseOid = undefined;
|
|
600
|
+
this.sourceLinksHash = undefined; this.sourceLinks = Object.create(null);
|
|
578
601
|
this.repoRoot = undefined;
|
|
579
602
|
this.initializePromise = undefined;
|
|
580
603
|
throw error;
|
|
@@ -631,9 +654,17 @@ export class WorkspaceManager {
|
|
|
631
654
|
if (copyTreeOid(before) !== copyTreeOid(after)) throw new Error("Parent workspace changed during child Git capture");
|
|
632
655
|
this.copyWithPrivateGit = { ownerDirectory, snapshotRepository: join(history, "repository.git") };
|
|
633
656
|
}
|
|
634
|
-
const
|
|
657
|
+
const links: Record<string, string> = Object.create(null);
|
|
658
|
+
const tree = await scanCopyTree(this.repoRoot, true, true, true, undefined, undefined, links);
|
|
635
659
|
await materializeCopyTree(this.repoRoot, this.templatePath, tree);
|
|
636
|
-
|
|
660
|
+
const afterLinks: Record<string, string> = Object.create(null);
|
|
661
|
+
if (copyTreeOid(await scanCopyTree(this.repoRoot, true, true, true, undefined, undefined, afterLinks)) !== copyTreeOid(tree)
|
|
662
|
+
|| JSON.stringify(links) !== JSON.stringify(afterLinks)) throw new Error("Copy workspace changed during snapshot");
|
|
663
|
+
if (Object.keys(links).length) {
|
|
664
|
+
const json = JSON.stringify(links);
|
|
665
|
+
await writeFile(join(this.batchRoot!, "source-links.json"), json, { flag: "wx", mode: 0o600 });
|
|
666
|
+
this.sourceLinks = links; this.sourceLinksHash = createHash("sha256").update(json).digest("hex");
|
|
667
|
+
}
|
|
637
668
|
this.baseOid = copyTreeOid(tree);
|
|
638
669
|
return;
|
|
639
670
|
}
|
|
@@ -15,6 +15,8 @@ export interface WorkspaceLease {
|
|
|
15
15
|
repoPath?: string;
|
|
16
16
|
baseOid?: string;
|
|
17
17
|
batchPath?: string;
|
|
18
|
+
/** Host-owned raw source-link baseline, outside every writable clone. */
|
|
19
|
+
sourceLinksHash?: string;
|
|
18
20
|
/** Host-created private metadata, excluded from delivered file artifacts. */
|
|
19
21
|
privateGit?: PrivateGitBinding;
|
|
20
22
|
}
|