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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.14",
3
+ "version": "1.14.16",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
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 isAgentRunning = status !== "ready" && status !== "cancelled"
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 { goalCommand } from "../goal-command.js"
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
- try { deps.addLog("system", goalCommand(parts, process.cwd(), deps.configRef.current.permissionMode, process.platform, getCurrentSessionId())) }
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": {
@@ -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 startRunner(goal: GoalRecord): void {
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,16 +67,15 @@ 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, enforceSessionMode = false): 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
- "Goal execution is not yet supported on Windows; --check requires a VM backend with verified process sealing.",
76
- "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.",
77
- "Git commits remain private to the Goal; delivery changes files only, not the source index or refs. The private index starts from HEAD and does not preserve staged/unstaged grouping.",
78
- "--install=npm uses package-lock v3, official npm registry tarballs and an offline VM install with lifecycle scripts disabled.",
79
- "The lockfile must exist before starting; changing package.json or package-lock.json during the Goal blocks it. Existing node_modules is never overwritten. Verifier workspaces are read-only.",
76
+ "Goals use the current workspace and ordinary tool permissions. --artifact explicitly selects the legacy isolated-artifact workflow.",
77
+ "Goal execution is not yet supported on Windows.",
78
+ "--check runs the requested test command through normal tool permissions. --install=npm requests ordinary dependency installation; it does not grant shell permission.",
80
79
  "--accept-edits authorizes file edits but does not authorize shell commands or artifact merges requiring confirmation.",
81
80
  ].join("\n")
82
81
  const control = ["list", "status", "watch", "pause", "cancel", "resume", "budget"].includes(action)
@@ -86,9 +85,11 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
86
85
  const modeArgs = args.filter(arg => arg === "--permission-mode" || arg.startsWith("--permission-mode="))
87
86
  if (!control && (modeArgs.length > 1 || modeArgs.some(arg => !/^--permission-mode=(default|acceptEdits|bypassPermissions|plan)$/.test(arg)) || modeArgs.length > 0 && args.includes("--accept-edits"))) throw new Error("Invalid Goal permission mode")
88
87
  if (!control && (installArgs.length > 1 || installArgs.some(arg => arg !== "--install=npm"))) throw new Error("Invalid Goal dependency installation; use --install=npm")
89
- if (!control && installArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --install=npm requires a VM backend with verified process sealing.")
90
- if (!control && checkArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --check machine verification is currently unavailable: process-tree sealing cannot be verified.")
88
+ if (!control && args.includes("--artifact") && installArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --install=npm requires a VM backend with verified process sealing.")
89
+ if (!control && args.includes("--artifact") && checkArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --check machine verification is currently unavailable: process-tree sealing cannot be verified.")
91
90
  if (!control && (checkArgs.length > 1 || checkArgs.some(arg => !/^--check=(bun|npm|pytest|go)$/.test(arg)))) throw new Error("Invalid Goal machine check; use --check=bun, npm, pytest or go")
91
+ const background = args.includes("--background")
92
+ if (args.filter(arg => arg === "--background").length > 1 || args.some(arg => arg.startsWith("--background="))) throw new Error("Invalid Goal background flag")
92
93
  const limits: GoalBudgetLimits = { strict: args.includes("--strict") }
93
94
  const limitKeys = { tokens: "maxTokens", "model-calls": "maxModelCalls", "provider-attempts": "maxProviderAttempts", "tool-calls": "maxToolCalls", minutes: "deadlineAt" } as const
94
95
  const limitArgs = !control ? args.filter(arg => /^--(?:tokens|model-calls|provider-attempts|tool-calls|minutes)(?:=|$)/.test(arg)) : []
@@ -103,6 +104,12 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
103
104
  limits[key] = limit
104
105
  }
105
106
  if (limits.maxTokens !== undefined) limits.reservedTokens = Math.min(50_000, Math.floor(limits.maxTokens * 0.05))
107
+ if ((!control || action === "resume") && !background && !onForeground) throw new Error("A foreground Goal launcher is required")
108
+ if (enforceSessionMode && !control && !background) {
109
+ const requested = args.includes("--accept-edits") ? "acceptEdits" : modeArgs[0]?.slice("--permission-mode=".length) ?? currentMode
110
+ if (requested !== currentMode) throw new Error("Goal uses the current session permission mode; change the session mode before starting a Goal")
111
+ }
112
+ const launch = (goal: GoalRecord) => background ? startGoalBackgroundRunner(goal) : onForeground!(goal)
106
113
  const store = new GoalStore(goalDatabasePath(), { requireLedger: true })
107
114
  try {
108
115
  if (action === "list") {
@@ -121,7 +128,7 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
121
128
  ...(goal.failure ? [`Failure: ${JSON.stringify(goal.failure)}`] : []),
122
129
  ...(goal.progress ? [`Progress: ${JSON.stringify(goal.progress)}`] : []),
123
130
  `Tasks: ${goal.tasks.filter(task => task.status === "passed").length}/${goal.tasks.length}`,
124
- ...(goal.dependencyInstall ? ["Dependencies: npm (official registry, package-lock v3, scripts disabled)"] : []),
131
+ ...(goal.dependencyInstall ? ["Dependencies: npm (normal tool permissions)"] : []),
125
132
  `Usage: ${budget.totals.modelCalls} model calls · ${budget.totals.toolCalls} tool calls · ${budget.totals.tokensUsed} tokens · ${budget.totals.unknownUsage} unknown usage · ${budget.totals.opaqueToolCalls} unmetered tool calls (${budget.limits.strict === false ? "observed" : "strict"})`,
126
133
  ...(goal.delivery ? [`Artifact: ${JSON.stringify(goal.delivery)}`] : []),
127
134
  `Log: ${join(goalHome(goal.id), "runner.log")}`,
@@ -147,27 +154,28 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
147
154
  }
148
155
  if (action === "resume") {
149
156
  const goal = selectGoal(store, cwd, args[1], sessionId)
150
- if ((goal.machineCheck || goal.dependencyInstall) && !machineCheckSupported(cwd)) throw new Error("Goal VM execution is currently unavailable: process-tree sealing cannot be verified.")
157
+ if (goal.executionMode !== "session" && (goal.machineCheck || goal.dependencyInstall) && !machineCheckSupported(cwd)) throw new Error("Goal VM execution is currently unavailable: process-tree sealing cannot be verified.")
158
+ if (enforceSessionMode && !background && goal.executionMode === "session" && goal.permissionMode !== currentMode) throw new Error("Goal permission mode differs from the current session; restore its mode before resuming")
151
159
  const stopped = recoverStoppedOwner(store, goal)
152
160
  if (sessionId && stopped.sessionId === sessionId) store.pauseForInput(cwd, sessionId)
153
- startRunner(store.prepareResume(stopped.id))
161
+ launch(store.prepareResume(stopped.id))
154
162
  return `Goal ${goal.id} resumed; budget and task state retained.`
155
163
  }
156
164
  const permissionMode = args.includes("--accept-edits") ? "acceptEdits" : modeArgs.length ? modeArgs[0]!.slice("--permission-mode=".length) as import("./config.js").PermissionMode : currentMode
157
165
  const strict = args.includes("--strict")
158
166
  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()
167
+ 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
168
  if (!objective) throw new Error("Goal objective is required")
161
169
  const machineCheck = checkArgs[0]?.slice("--check=".length) as "bun" | "npm" | "pytest" | "go" | undefined
162
170
  if (sessionId) store.pauseForInput(cwd, sessionId)
163
- const goal = store.create({ objective, cwd, sessionId, deadlineAt: limits.deadlineAt, deliveryPolicy, permissionMode, machineCheck, dependencyInstall: installArgs.length ? "npm" : undefined })
171
+ const goal = store.create({ executionMode: deliveryPolicy === "artifact" ? "isolated" : "session", objective, cwd, sessionId, deadlineAt: limits.deadlineAt, deliveryPolicy, permissionMode, machineCheck, dependencyInstall: installArgs.length ? "npm" : undefined })
164
172
  const ledger = new GoalBudgetLedger(goalDatabasePath())
165
173
  try {
166
174
  // Usage remains durable and shared across all phases and children; no
167
175
  // implicit cap may turn an unfinished objective into a stopped Goal.
168
176
  ledger.create(goal.id, 0, limits)
169
177
  } finally { ledger.close() }
170
- startRunner(goal)
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.`
178
+ launch(goal)
179
+ 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
180
  } finally { store.close() }
173
181
  }
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()
@@ -1,31 +1,64 @@
1
+ import { GoalTurnHost } from "./goal-turn-host.js"
2
+ import type { GoalTurnExecutor } from "./goal-turn.js"
1
3
  import { GoalController } from "../zapsdk/goal/controller.js"
2
4
  import { GoalStore } from "../zapsdk/goal/store.js"
3
5
  import { LocalGoalHost } from "./goal-host.js"
4
6
  import { goalDatabasePath } from "./goal-command.js"
5
7
 
6
- /** Invoked as a detached CLI child; it never treats a compiled executable as an interpreter. */
7
- export async function runGoalRunner(id: string): Promise<number> {
8
+ /** Shared controller entry for attached sessions and explicitly detached runners. */
9
+ export interface GoalRunnerObserver {
10
+ runTurn?: GoalTurnExecutor
11
+ signal?: AbortSignal
12
+ onEvent?: (event: import("../zapsdk/agent/events.js").AgentEvent, operationId: string) => void
13
+ onState?: (goal: import("../zapsdk/goal/contracts.js").GoalRecord) => void
14
+ onOutcome?: (goal: import("../zapsdk/goal/contracts.js").GoalRecord) => void
15
+ }
16
+ export async function runGoalRunner(id: string, observer: GoalRunnerObserver = {}): Promise<number> {
8
17
  if (process.platform === "win32") {
9
18
  process.stderr.write("Goal execution is not yet supported on Windows: process-tree sealing cannot be verified.\n")
10
19
  return 2
11
20
  }
12
21
  const store = new GoalStore(goalDatabasePath(), { requireLedger: true })
22
+ let revision = -1
23
+ const publish = () => {
24
+ const goal = store.get(id)
25
+ if (goal && goal.stateRevision !== revision) { revision = goal.stateRevision; observer.onState?.(goal) }
26
+ }
27
+ const pause = () => {
28
+ const goal = store.get(id)
29
+ if (goal && ["created", "running"].includes(goal.status)) store.requestControl(id, "pause")
30
+ }
31
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const
32
+ if (observer.onOutcome) for (const name of signals) process.on(name, pause)
33
+ observer.signal?.addEventListener("abort", pause, { once: true })
34
+ const timer = observer.onState ? setInterval(publish, 100) : undefined
13
35
  try {
14
36
  const goal = store.get(id)
15
37
  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)
38
+ const controller = new GoalController(store, (goal.executionMode === "session" ? new GoalTurnHost(id, observer.onEvent, observer.runTurn) : new LocalGoalHost(id, observer.onEvent)), id)
17
39
  if (goal.inFlight) {
18
40
  const reconciled = await controller.recover()
19
41
  if (reconciled.inFlight || reconciled.status === "blocked") {
20
- process.stderr.write(`Goal recovery blocked: ${reconciled.stopReason ?? "unknown effects"}\n`)
42
+ observer.onState?.(reconciled); observer.onOutcome?.(reconciled)
43
+ if (!observer.onOutcome) process.stderr.write(`Goal recovery blocked: ${reconciled.stopReason ?? "unknown effects"}\n`)
21
44
  return 1
22
45
  }
23
46
  }
47
+ publish()
48
+ if (observer.signal?.aborted) { pause(); const stopped = store.get(id)!; observer.onOutcome?.(stopped); return 1 }
24
49
  const outcome = await controller.run({ automatic: true })
25
- process.stdout.write(JSON.stringify({ id: outcome.id, status: outcome.status, phase: outcome.phase, reason: outcome.stopReason, delivery: outcome.delivery }) + "\n")
50
+ publish()
51
+ observer.onOutcome?.(outcome)
52
+ 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
53
  return outcome.status === "completed" || outcome.status === "ready_for_delivery" ? 0 : 1
27
54
  } catch (error) {
55
+ if (observer.onOutcome) throw error
28
56
  process.stderr.write(`Goal runner: ${error instanceof Error ? error.message : String(error)}\n`)
29
57
  return 1
30
- } finally { store.close() }
58
+ } finally {
59
+ if (timer) clearInterval(timer)
60
+ observer.signal?.removeEventListener("abort", pause)
61
+ if (observer.onOutcome) for (const name of signals) process.removeListener(name, pause)
62
+ store.close()
63
+ }
31
64
  }
@@ -0,0 +1,100 @@
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
+ runTurn?: import("./goal-turn.js").GoalTurnExecutor
9
+ permissionMode?: PermissionMode
10
+ sessionId?: string
11
+ signal?: AbortSignal
12
+ onStart?: (goal: GoalRecord) => void
13
+ onMessage: (text: string) => void
14
+ onState?: (goal: GoalRecord) => void
15
+ onEvent?: (event: AgentEvent, scope: string) => void
16
+ }
17
+ const attached = new Map<string, { id: string; background: () => void; pause: () => void; done: Promise<void> }>()
18
+ const sessionKey = (cwd: string, sessionId?: string) => JSON.stringify([goalDatabasePath(), cwd, sessionId])
19
+
20
+ /** Control commands bypass the ordinary turn queue while its Goal is active. */
21
+ export function isGoalSessionControl(text: string): boolean {
22
+ return /^\/goal\s+(?:status|watch|list|pause|cancel|background|budget)(?:\s|$)/.test(text.trim())
23
+ }
24
+
25
+ export async function executeGoalCommand(args: string[], cwd: string, options: GoalSessionOptions): Promise<number> {
26
+ const key = sessionKey(cwd, options.sessionId)
27
+ if (args[0] === "background") {
28
+ const detach = attached.get(key)
29
+ if (!detach || args.length > 2 || args[1] && args[1] !== detach.id) throw new Error("No foreground Goal in this session")
30
+ detach.background()
31
+ options.onMessage("Goal will switch to background at the next safe phase boundary.")
32
+ return 0
33
+ }
34
+ 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")
35
+ let foreground: GoalRecord | undefined
36
+ const message = goalCommand(args, cwd, options.permissionMode, process.platform, options.sessionId, goal => {
37
+ if (attached.has(key)) throw new Error("A foreground Goal is already running in this session")
38
+ foreground = goal
39
+ }, !!options.runTurn)
40
+ options.onMessage(message)
41
+ if (!foreground) return 0
42
+ const goal = foreground as GoalRecord
43
+ let backgroundRequested = false
44
+ let settle!: () => void
45
+ const done = new Promise<void>(resolve => { settle = resolve })
46
+ attached.set(key, { id: goal.id, done, pause: () => {
47
+ const store = new GoalStore(goalDatabasePath())
48
+ try { const current = store.get(goal.id); if (current && ["created", "running"].includes(current.status)) store.requestControl(goal.id, "pause") } finally { store.close() }
49
+ }, background: () => {
50
+ const store = new GoalStore(goalDatabasePath())
51
+ try {
52
+ const current = store.get(goal.id)
53
+ if (!current?.owner || current.control) throw new Error("Goal is already stopping")
54
+ store.update(goal.id, current.ownerEpoch, current.owner.instanceId, value => { value.yieldRequested = true })
55
+ backgroundRequested = true
56
+ } finally { store.close() }
57
+ } })
58
+ let outcome: GoalRecord | undefined
59
+ try {
60
+ options.onStart?.(goal)
61
+ const { runGoalRunner } = await import("./goal-runner.js")
62
+ const code = await runGoalRunner(goal.id, { runTurn: options.runTurn, signal: options.signal, onState: options.onState,
63
+ onEvent: (event, operationId) => options.onEvent?.(event, `${goal.id}:${operationId}`),
64
+ onOutcome: value => { outcome = value },
65
+ })
66
+ if (backgroundRequested && outcome?.status === "paused" && outcome.stopReason === "USER_INPUT_PENDING") {
67
+ options.onMessage(goalCommand(["resume", goal.id, "--background"], cwd, options.permissionMode, process.platform, options.sessionId))
68
+ options.onMessage(`Goal ${goal.id} is now running in background.`)
69
+ return 0
70
+ }
71
+ if (outcome) {
72
+ options.onMessage(`Goal ${outcome.id} · ${outcome.status}${outcome.stopReason ? ` · ${outcome.stopReason}` : ""}`)
73
+ if (outcome.delivery) options.onMessage(`Goal delivery: ${JSON.stringify(outcome.delivery)}`)
74
+ }
75
+ return code
76
+ } finally { attached.delete(key); settle() }
77
+ }
78
+
79
+ /** Separate process-local content/run identities across planning and workers. */
80
+ export function scopeGoalEvent(event: AgentEvent, scope: string): AgentEvent {
81
+ const value = { ...event } as unknown as Record<string, any>
82
+ for (const key of ["id", "subagentId", "requestId"]) if (typeof value[key] === "string") value[key] = `${scope}:${value[key]}`
83
+ if (value.path) value.path = value.path.map((id: string) => `${scope}:${id}`)
84
+ if (value.type === "content_final" && value.kind === "tool_result" && ["agent", "delegate_agent"].includes(value.toolName)
85
+ && typeof value.result?.meta?.subagentId === "string") {
86
+ value.result = { ...value.result, meta: { ...value.result.meta, subagentId: `${scope}:${value.result.meta.subagentId}` } }
87
+ }
88
+ if (value.run) {
89
+ value.run = { ...value.run }
90
+ for (const key of ["runId", "parentRunId", "toolCallId"]) if (value.run[key]) value.run[key] = `${scope}:${value.run[key]}`
91
+ }
92
+ return value as AgentEvent
93
+ }
94
+
95
+ /** Terminal shutdown waits for the owned phase to seal before process.exit. */
96
+ export async function closeForegroundGoals(): Promise<void> {
97
+ const sessions = [...attached.values()]
98
+ for (const session of sessions) session.pause()
99
+ await Promise.all(sessions.map(session => session.done))
100
+ }