zapagent 1.14.13 → 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/buildAgentRuntime.ts +6 -1
- package/src/agent/goalPresentation.ts +43 -0
- package/src/agent/promptDiagnostics.ts +8 -1
- package/src/commands/dispatcher.ts +9 -3
- package/src/commands/status.ts +7 -32
- package/src/config.ts +7 -2
- 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/headless/runHeadless.ts +6 -2
- package/src/hooks/useAgentRunner.ts +48 -1
- package/src/hooks/useTurnDispatcher.ts +8 -0
- package/src/index.tsx +19 -3
- package/src/prompts/context.ts +4 -3
- package/src/prompts/registry.ts +4 -3
- package/src/prompts/required-sections.ts +26 -0
- package/src/prompts/sections/agents-md.ts +24 -11
- package/src/prompts/sections/concise.ts +2 -2
- package/src/prompts/sections/file-reading.ts +2 -2
- package/src/prompts/sections/identity.ts +2 -2
- package/src/prompts/sections/plan-discipline.ts +2 -2
- package/src/prompts/sections/safety.ts +1 -1
- package/src/prompts/sections/skills.ts +4 -3
- package/src/prompts/sections/system.ts +4 -3
- package/src/prompts/sections/tasks.ts +1 -1
- package/src/ui/slash-palette.tsx +1 -1
- package/zapsdk/agent/events.ts +3 -0
- package/zapsdk/agent/loop.ts +33 -62
- package/zapsdk/agent/output-text.ts +34 -0
- package/zapsdk/agent/prompt-output-guard.ts +138 -0
- package/zapsdk/agent/streaming-tool-executor.ts +16 -8
- package/zapsdk/agent/subagent-assembly.ts +1 -0
- package/zapsdk/builtin-tools/subagent.ts +4 -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
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) ──
|
|
@@ -18,6 +18,7 @@ import { getActiveMaxOutputTokens, getActiveProvider, setVisionSupport } from ".
|
|
|
18
18
|
import type { AppConfig } from "../config.js"
|
|
19
19
|
import type { AgentObjects } from "./types.js"
|
|
20
20
|
import { resolveActiveContextLimits } from "../context-budget.js"
|
|
21
|
+
import { buildInheritedPromptInstructions } from "../prompts/required-sections.js"
|
|
21
22
|
import {
|
|
22
23
|
createProjectRuntimeEventStore,
|
|
23
24
|
createProjectRuntimeStateStore,
|
|
@@ -30,6 +31,7 @@ export interface BuildAgentRuntimeDeps extends Pick<AgentObjects, "provider" | "
|
|
|
30
31
|
completionEvidence?: CompletionEvidenceProvider
|
|
31
32
|
conversation: ConversationManager
|
|
32
33
|
fullSystemPrompt: string
|
|
34
|
+
publicPromptSections?: readonly string[]
|
|
33
35
|
/** Explicit host instructions for descendants; excludes generated workflow sections. */
|
|
34
36
|
inheritedInstructions?: string
|
|
35
37
|
/** AutoCompact char threshold (≈ 80% context window × 4 chars/token). */
|
|
@@ -51,6 +53,7 @@ export interface BuildAgentRuntimeDeps extends Pick<AgentObjects, "provider" | "
|
|
|
51
53
|
* config, checkpoint and devtools integration. */
|
|
52
54
|
export function buildAgentRuntime(deps: BuildAgentRuntimeDeps): AgentRuntime {
|
|
53
55
|
const contextLimits = resolveActiveContextLimits(deps.config)
|
|
56
|
+
const inherited = buildInheritedPromptInstructions(deps.cwd, [deps.config.customSystemPrompt, deps.inheritedInstructions])
|
|
54
57
|
const runtime = createAgentRuntime({
|
|
55
58
|
threadId: deps.currentSessionId,
|
|
56
59
|
observer: watchObserver(),
|
|
@@ -76,6 +79,7 @@ export function buildAgentRuntime(deps: BuildAgentRuntimeDeps): AgentRuntime {
|
|
|
76
79
|
executor: deps.executor,
|
|
77
80
|
conversation: deps.conversation,
|
|
78
81
|
systemPrompt: deps.fullSystemPrompt,
|
|
82
|
+
publicPromptSections: deps.publicPromptSections ?? inherited.publicPromptSections,
|
|
79
83
|
promptProfile: deps.config.promptProfile ?? "standard",
|
|
80
84
|
maxSteps: deps.config.maxSteps,
|
|
81
85
|
reserveSteps: 2,
|
|
@@ -107,7 +111,8 @@ export function buildAgentRuntime(deps: BuildAgentRuntimeDeps): AgentRuntime {
|
|
|
107
111
|
}
|
|
108
112
|
},
|
|
109
113
|
subagent: {
|
|
110
|
-
inheritedInstructions:
|
|
114
|
+
inheritedInstructions: inherited.instructions,
|
|
115
|
+
publicPromptSections: inherited.publicPromptSections,
|
|
111
116
|
onEvent: deps.subAgentEventHandler,
|
|
112
117
|
todoStore: deps.todoStore,
|
|
113
118
|
createRegistryForCwd: deps.createRegistryForCwd,
|
|
@@ -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
|
+
}
|
|
@@ -16,12 +16,19 @@ export interface PromptSectionDiagnostics extends PromptSegmentDiagnostics {
|
|
|
16
16
|
|
|
17
17
|
export function createPromptSectionDiagnostics(): {
|
|
18
18
|
sections: PromptSectionDiagnostics[]
|
|
19
|
+
publicPromptSections: string[]
|
|
19
20
|
record: NonNullable<PromptContext["onSection"]>
|
|
20
21
|
} {
|
|
21
22
|
const sections: PromptSectionDiagnostics[] = []
|
|
23
|
+
const publicPromptSections: string[] = []
|
|
22
24
|
return {
|
|
23
25
|
sections,
|
|
24
|
-
|
|
26
|
+
publicPromptSections,
|
|
27
|
+
record: (name, purpose, dynamic, text, sourceText) => {
|
|
28
|
+
if (purpose === "project") {
|
|
29
|
+
publicPromptSections.push(text)
|
|
30
|
+
if (sourceText && sourceText !== text) publicPromptSections.push(sourceText)
|
|
31
|
+
}
|
|
25
32
|
sections.push({ name, purpose, dynamic, ...segmentDiagnostics(text) })
|
|
26
33
|
},
|
|
27
34
|
}
|
|
@@ -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/commands/status.ts
CHANGED
|
@@ -9,14 +9,15 @@
|
|
|
9
9
|
* zap's bring-your-own-key model.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
12
|
+
import { realpathSync } from "node:fs"
|
|
13
|
+
import { relative } from "node:path"
|
|
14
14
|
import { homedir } from "node:os"
|
|
15
15
|
import { computeCacheUsageStats } from "../../zapsdk/agent/cache-metrics.js"
|
|
16
16
|
import type { ContextDiagnostics, ContextSegmentDiagnostics } from "../../zapsdk/agent/events.js"
|
|
17
17
|
import type { ToolSchemaDiagnostics } from "../agent/toolDiagnostics.js"
|
|
18
18
|
import type { PromptCacheDiagnostics } from "../agent/promptDiagnostics.js"
|
|
19
19
|
import type { CacheMemoryAuditEntry } from "../agent/cacheMemoryAudit.js"
|
|
20
|
+
import { readProjectGuidelines } from "../prompts/sections/agents-md.js"
|
|
20
21
|
import {
|
|
21
22
|
makePromptCacheScope,
|
|
22
23
|
samePromptCacheScope,
|
|
@@ -122,43 +123,17 @@ export interface StatusDiagnostics {
|
|
|
122
123
|
}
|
|
123
124
|
}
|
|
124
125
|
|
|
125
|
-
/** Surface
|
|
126
|
-
* The prompt section resolves AGENTS.md from the git root when available,
|
|
127
|
-
* so /status must do the same; otherwise a session started from a subdir
|
|
128
|
-
* misleadingly reports "(none detected)" while project rules are active. */
|
|
126
|
+
/** Surface every project document loaded for the current directory scope. */
|
|
129
127
|
function detectAgentsDoc(cwd: string): string | null {
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
if (!existsSync(path)) return null
|
|
133
|
-
return root === cwd ? "AGENTS.md" : shortRelativePath(cwd, path)
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
function resolveProjectRoot(cwd: string): string {
|
|
137
|
-
let current = cwd
|
|
138
|
-
const { root } = parse(cwd)
|
|
139
|
-
for (;;) {
|
|
140
|
-
if (hasGitMarker(current)) return current
|
|
141
|
-
if (current === root) return cwd
|
|
142
|
-
const parent = dirname(current)
|
|
143
|
-
if (parent === current) return cwd
|
|
144
|
-
current = parent
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function hasGitMarker(path: string): boolean {
|
|
149
|
-
try {
|
|
150
|
-
const stat = statSync(join(path, ".git"))
|
|
151
|
-
return stat.isDirectory() || stat.isFile()
|
|
152
|
-
} catch {
|
|
153
|
-
return false
|
|
154
|
-
}
|
|
128
|
+
const documents = readProjectGuidelines(cwd)
|
|
129
|
+
return documents.length ? documents.map(document => shortRelativePath(cwd, document.path)).join(", ") : null
|
|
155
130
|
}
|
|
156
131
|
|
|
157
132
|
function shortRelativePath(cwd: string, path: string): string {
|
|
158
133
|
const from = realPathBestEffort(cwd)
|
|
159
134
|
const to = realPathBestEffort(path)
|
|
160
135
|
const r = relative(from, to)
|
|
161
|
-
if (!r) return "AGENTS.md"
|
|
136
|
+
if (!r || r === "AGENTS.md") return "AGENTS.md"
|
|
162
137
|
return r.startsWith(".") ? r : `./${r}`
|
|
163
138
|
}
|
|
164
139
|
|
package/src/config.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { resolvePromptProfile, type PromptProfile } from "../zapsdk/agent/prompt
|
|
|
12
12
|
import { concisePlanSection } from "./prompts/sections/concise.js"
|
|
13
13
|
import { recordPromptSection } from "./prompts/registry.js"
|
|
14
14
|
import { localExecutionShell } from "../zapsdk/execution/shell.js"
|
|
15
|
+
import { REQUIRED_SECTIONS } from "./prompts/required-sections.js"
|
|
15
16
|
|
|
16
17
|
/** A built-in provider template. Templates are catalog-only: they seed the
|
|
17
18
|
* "Add Provider" wizard with sensible defaults, but never store runtime
|
|
@@ -1015,7 +1016,7 @@ export function buildSystemPrompt(
|
|
|
1015
1016
|
enabledTools: enabledTools ?? new Set(),
|
|
1016
1017
|
toolPromptsRaw: toolPrompts,
|
|
1017
1018
|
model: config.active.model,
|
|
1018
|
-
customSystemPrompt:
|
|
1019
|
+
customSystemPrompt: config.customSystemPrompt,
|
|
1019
1020
|
promptProfile: resolvePromptProfile(config.promptProfile),
|
|
1020
1021
|
onSection,
|
|
1021
1022
|
availableSkills,
|
|
@@ -1038,17 +1039,19 @@ export function buildCustomSystemPrompt(
|
|
|
1038
1039
|
dynamicLines: string[] = [],
|
|
1039
1040
|
): string {
|
|
1040
1041
|
const cacheableSupportSections = [
|
|
1042
|
+
...REQUIRED_SECTIONS,
|
|
1041
1043
|
toolPromptsSection,
|
|
1042
1044
|
skillsSection,
|
|
1043
1045
|
ctx.promptProfile === "concise" ? concisePlanSection : planDisciplineSection,
|
|
1044
1046
|
].flatMap((section) => {
|
|
1045
1047
|
const value = section.compute(ctx)
|
|
1046
1048
|
const trimmed = value ? escapeDynamicBoundaryText(value).trim() : ""
|
|
1047
|
-
if (trimmed) recordPromptSection(ctx, section, trimmed)
|
|
1049
|
+
if (trimmed) recordPromptSection(ctx, section, trimmed, value ?? undefined)
|
|
1048
1050
|
return trimmed ? [trimmed] : []
|
|
1049
1051
|
})
|
|
1050
1052
|
const dynamic = [
|
|
1051
1053
|
...dynamicLines,
|
|
1054
|
+
...(ctx.model ? [`Model: ${ctx.model}`] : []),
|
|
1052
1055
|
`Shell: ${ctx.executionFacts?.shell ?? localExecutionShell().executable}`,
|
|
1053
1056
|
...(ctx.executionFacts ? [`Process environment facts: ${JSON.stringify(ctx.executionFacts)}`] : []),
|
|
1054
1057
|
...sandboxTemporaryDirectoryDescription(ctx.executionFacts),
|
|
@@ -1058,6 +1061,8 @@ export function buildCustomSystemPrompt(
|
|
|
1058
1061
|
recordPromptSection(ctx, { name: "custom-environment", purpose: "environment", dynamic: true, compute: () => null }, dynamic.join("\n"))
|
|
1059
1062
|
return [
|
|
1060
1063
|
escapeDynamicBoundaryText(customPrompt).trim(),
|
|
1064
|
+
...(ctx.customSystemPrompt?.trim() && ctx.customSystemPrompt.trim() !== customPrompt.trim()
|
|
1065
|
+
? [escapeDynamicBoundaryText(ctx.customSystemPrompt).trim()] : []),
|
|
1061
1066
|
...cacheableSupportSections,
|
|
1062
1067
|
...(dynamic.length > 0 ? [DYNAMIC_BOUNDARY, ...dynamic] : []),
|
|
1063
1068
|
].filter(Boolean).join("\n")
|
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
|
+
}
|