zapagent 1.14.11 → 1.14.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled-dependencies.json +201 -201
- package/package.json +1 -1
- package/src/agent-factory.ts +6 -3
- package/src/commands/dispatcher.ts +10 -0
- package/src/commands.ts +4 -0
- package/src/execution-environment.ts +1 -1
- package/src/goal-command.ts +173 -0
- package/src/goal-host.ts +408 -0
- package/src/goal-runner.ts +31 -0
- package/src/headless/goal-npm-install.ts +96 -0
- package/src/headless/goalPhase.ts +380 -0
- package/src/headless/runHeadless.ts +56 -4
- package/src/hooks/useTurnDispatcher.ts +3 -0
- package/src/index.tsx +17 -0
- package/src/ui/slash-palette.tsx +1 -0
- package/zapsdk/agent/loop.ts +13 -2
- package/zapsdk/agent/subagent-assembly.ts +5 -0
- package/zapsdk/agent/tool-execution-guards.ts +30 -17
- package/zapsdk/builtin-tools/command.ts +11 -0
- package/zapsdk/builtin-tools/subagent.ts +10 -3
- package/zapsdk/core/llm.ts +2 -0
- package/zapsdk/core/retry.ts +3 -0
- package/zapsdk/execution/broker.ts +18 -1
- package/zapsdk/execution/goal-workspace-gate.ts +95 -0
- package/zapsdk/execution/required-process-seal.ts +35 -0
- package/zapsdk/execution/types.ts +8 -0
- package/zapsdk/execution/workspace-runtime.ts +6 -0
- package/zapsdk/execution/zapvm.ts +117 -15
- package/zapsdk/goal/acceptance.ts +139 -0
- package/zapsdk/goal/budget.ts +406 -0
- package/zapsdk/goal/contracts.ts +93 -0
- package/zapsdk/goal/controller.ts +234 -0
- package/zapsdk/goal/errors.ts +17 -0
- package/zapsdk/goal/git-history-snapshot.ts +210 -0
- package/zapsdk/goal/git-operation-owner.ts +64 -0
- package/zapsdk/goal/metered-provider.ts +80 -0
- package/zapsdk/goal/npm-installer.ts +362 -0
- package/zapsdk/goal/scheduler.ts +34 -0
- package/zapsdk/goal/store.ts +173 -0
- package/zapsdk/goal/structured-output.ts +84 -0
- package/zapsdk/goal/workspace-broker.ts +11 -0
- package/zapsdk/goal/workspace.ts +425 -0
- package/zapsdk/policy/types.ts +4 -0
- package/zapsdk/runtime/factory.ts +7 -0
- package/zapsdk/scheduler/batch-scheduler.ts +2 -2
- package/zapsdk/tools/executor.ts +79 -6
- package/zapsdk/tools/types.ts +2 -0
- package/zapsdk/workspace/context.ts +8 -4
- package/zapsdk/workspace/copy.ts +14 -1
- package/zapsdk/workspace/manager.ts +67 -3
- package/zapsdk/workspace/types.ts +11 -0
package/package.json
CHANGED
package/src/agent-factory.ts
CHANGED
|
@@ -29,6 +29,7 @@ import type { AgentEventHandler } from "../zapsdk/agent/events.js"
|
|
|
29
29
|
import { autoMemory, cronHandle, monitorHandle, taskStore, mdStore, globalMdStore, globalMemoryDir, delegateProviders, delegateEventBridge } from "./singletons.js"
|
|
30
30
|
import { memorySaveTool } from "../zapsdk/builtin-tools/memory.js"
|
|
31
31
|
import type { AgentObjects } from "./agent/types.js"
|
|
32
|
+
import type { LLMProvider } from "../zapsdk/core/llm.js"
|
|
32
33
|
import { createMemoryReadPostProcess } from "./agent/memoryReadPostProcess.js"
|
|
33
34
|
import { createExecutionEnvironment, resolveExecutionBackend, type ExecutionEnvironment } from "./execution-environment.js"
|
|
34
35
|
|
|
@@ -61,6 +62,7 @@ export function buildAgentObjects(
|
|
|
61
62
|
delegateOnEvent?: AgentEventHandler,
|
|
62
63
|
/** Interactive UI only: registers `ask_user_question`. Headless leaves it out. */
|
|
63
64
|
askUserCallbacks?: AskUserCallbacks,
|
|
65
|
+
providerAdapter?: (provider: LLMProvider) => LLMProvider,
|
|
64
66
|
): AgentObjects {
|
|
65
67
|
const effectiveCwd = cwdOverride ?? process.cwd()
|
|
66
68
|
const environment = executionEnvironment ?? createExecutionEnvironment(effectiveCwd, sandboxMode, resolveExecutionBackend(config.executionBackend), config.allowUnsandboxedCommands !== false, config.sandboxNetwork, config.sandboxExcludedCommands)
|
|
@@ -116,8 +118,7 @@ export function buildAgentObjects(
|
|
|
116
118
|
"x-stainless-runtime-version": null,
|
|
117
119
|
} as unknown as Record<string, string>
|
|
118
120
|
: undefined
|
|
119
|
-
const
|
|
120
|
-
isAnthropic
|
|
121
|
+
const rawProvider = isAnthropic
|
|
121
122
|
? new AnthropicProvider({
|
|
122
123
|
maxRequestBytes: active?.maxRequestBytes,
|
|
123
124
|
canonicalModelIds: modelCanonicalIds(active),
|
|
@@ -139,7 +140,9 @@ export function buildAgentObjects(
|
|
|
139
140
|
// models.dev modalities and positive name hints. Unknown preserves
|
|
140
141
|
// images until an actual rejection triggers bounded runtime fallback.
|
|
141
142
|
supportsVision: resolveVisionSupport(active, model),
|
|
142
|
-
})
|
|
143
|
+
})
|
|
144
|
+
const provider = new RetryProvider(
|
|
145
|
+
providerAdapter ? providerAdapter(rawProvider) : rawProvider,
|
|
143
146
|
{ maxRetries: 2, initialDelayMs: 1000 }
|
|
144
147
|
)
|
|
145
148
|
|
|
@@ -17,6 +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
21
|
import {
|
|
21
22
|
getCurrentSessionId,
|
|
22
23
|
lastOutputPath,
|
|
@@ -608,6 +609,15 @@ export function dispatchSlashCommand(
|
|
|
608
609
|
return dispatchAgentTurn("Analyze this project and write AGENTS.md.", INIT_PROJECT_PROMPT)
|
|
609
610
|
}
|
|
610
611
|
|
|
612
|
+
case "goal": {
|
|
613
|
+
const raw = cmd.value?.trim() ?? ""
|
|
614
|
+
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())) }
|
|
617
|
+
catch (error) { deps.addLog("error", error instanceof Error ? error.message : String(error)) }
|
|
618
|
+
return true
|
|
619
|
+
}
|
|
620
|
+
|
|
611
621
|
case "supertask": {
|
|
612
622
|
if (!precheckProvider(deps)) return true
|
|
613
623
|
const cwd = process.cwd()
|
package/src/commands.ts
CHANGED
|
@@ -22,6 +22,7 @@ export interface CommandResult {
|
|
|
22
22
|
| "init_project"
|
|
23
23
|
| "review"
|
|
24
24
|
| "commit"
|
|
25
|
+
| "goal"
|
|
25
26
|
| "supertask"
|
|
26
27
|
| "supertask_resume"
|
|
27
28
|
| "supertask_abort"
|
|
@@ -93,6 +94,7 @@ export function parseCommand(input: string): CommandResult | null {
|
|
|
93
94
|
" /review [path] — Review code for bugs & security",
|
|
94
95
|
" /commit — Stage changes and create a commit",
|
|
95
96
|
" /init — Analyze project and generate AGENTS.md",
|
|
97
|
+
" /goal <objective> — Start a Goal; /goal help for controls",
|
|
96
98
|
" /supertask <desc> [--max-turns N] [--max-iter N]",
|
|
97
99
|
" — Long-horizon orchestrated task (defaults: 80 turns, 30 iters)",
|
|
98
100
|
" /supertask resume — Continue the most recent unfinished supertask",
|
|
@@ -221,6 +223,8 @@ export function parseCommand(input: string): CommandResult | null {
|
|
|
221
223
|
case "init":
|
|
222
224
|
return { type: "init_project" }
|
|
223
225
|
|
|
226
|
+
case "goal": return { type: "goal", value: rest.trim() }
|
|
227
|
+
|
|
224
228
|
case "supertask": {
|
|
225
229
|
const trimmed = rest.trim()
|
|
226
230
|
if (trimmed === "resume") return { type: "supertask_resume" }
|
|
@@ -22,7 +22,7 @@ export interface ExecutionEnvironment {
|
|
|
22
22
|
capacity?: ExecutionCapacityFacts
|
|
23
23
|
// No prompt, model, retry, budget or completion policy is accepted here.
|
|
24
24
|
commandOptions: Pick<ExecuteCommandOptions,
|
|
25
|
-
"disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands" | "sandboxGitIntegration">
|
|
25
|
+
"disableBackgroundTasks" | "restrictedNetwork" | "preserveEnvironment" | "allowUnsandboxed" | "sandboxNetwork" | "sandboxExcludedCommands" | "sandboxGitIntegration" | "workspaceOnly">
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export type ExecutionBackend = "local" | "vm"
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { openSync, closeSync, mkdirSync, existsSync, readFileSync } from "node:fs"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import { fileURLToPath } from "node:url"
|
|
5
|
+
import { spawn } from "node:child_process"
|
|
6
|
+
import { getAppDataDir } from "../zapsdk/utils/platform.js"
|
|
7
|
+
import { GoalStore } from "../zapsdk/goal/store.js"
|
|
8
|
+
import { GoalBudgetLedger, type GoalBudgetLimits } from "../zapsdk/goal/budget.js"
|
|
9
|
+
import type { GoalRecord } from "../zapsdk/goal/contracts.js"
|
|
10
|
+
import { loadAppConfig } from "./config.js"
|
|
11
|
+
import { createExecutionEnvironment, resolveExecutionBackend } from "./execution-environment.js"
|
|
12
|
+
|
|
13
|
+
function machineCheckSupported(cwd: string): boolean {
|
|
14
|
+
const config = loadAppConfig(join(getAppDataDir(), "config.json"))
|
|
15
|
+
const environment = createExecutionEnvironment(cwd, "required", resolveExecutionBackend(config.executionBackend), false, config.sandboxNetwork, [])
|
|
16
|
+
return environment.broker.supportsProcessSeal?.({ name: "bash", executionLocation: "workspace" }) === true
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function goalDatabasePath(): string { return join(getAppDataDir(), "goal", "goals.sqlite") }
|
|
20
|
+
export function goalHome(goalId: string): string {
|
|
21
|
+
return join(getAppDataDir(), "goal", "runs", createHash("sha256").update(goalId).digest("hex"))
|
|
22
|
+
}
|
|
23
|
+
function selectGoal(store: GoalStore, cwd: string, id?: string, sessionId?: string): GoalRecord {
|
|
24
|
+
const goals = store.list(cwd)
|
|
25
|
+
const value = id ? store.get(id) : sessionId ? goals.find(goal => goal.sessionId === sessionId) ?? goals.find(goal => !goal.sessionId) : goals[0]
|
|
26
|
+
if (!value || value.cwd !== cwd) throw new Error("No matching Goal in this workspace")
|
|
27
|
+
return value
|
|
28
|
+
}
|
|
29
|
+
/** No state is created just by sending an ordinary chat message. */
|
|
30
|
+
export function pauseGoalsForUserInput(cwd: string, sessionId: string, text: string): string[] {
|
|
31
|
+
if (/^\/goal(?:\s|$)/.test(text.trim()) || !existsSync(goalDatabasePath())) return []
|
|
32
|
+
const store = new GoalStore(goalDatabasePath())
|
|
33
|
+
try { return store.pauseForInput(cwd, sessionId) } finally { store.close() }
|
|
34
|
+
}
|
|
35
|
+
function definitelyGone(pid: number, group: boolean): boolean {
|
|
36
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || (group && process.platform === "win32")) return false
|
|
37
|
+
try { process.kill(group ? -pid : pid, 0); return false }
|
|
38
|
+
catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH" }
|
|
39
|
+
}
|
|
40
|
+
/** An absent PID alone does not establish that the detached phase is gone. */
|
|
41
|
+
function recoverStoppedOwner(store: GoalStore, goal: GoalRecord): GoalRecord {
|
|
42
|
+
if (!goal.owner) return goal
|
|
43
|
+
if (!definitelyGone(goal.owner.pid, false)) throw new Error("Goal owner is active or its identity is unresolved")
|
|
44
|
+
const path = join(goalHome(goal.id), "workspace.json")
|
|
45
|
+
if (existsSync(path)) {
|
|
46
|
+
const meta = JSON.parse(readFileSync(path, "utf8")) as { goalId?: string; phaseProcess?: { pid?: number } }
|
|
47
|
+
if (meta.goalId !== goal.id) throw new Error("Goal workspace identity mismatch")
|
|
48
|
+
if (meta.phaseProcess && (!meta.phaseProcess.pid || !definitelyGone(meta.phaseProcess.pid, true))) {
|
|
49
|
+
throw new Error("Goal phase process is still active or cannot be verified stopped")
|
|
50
|
+
}
|
|
51
|
+
} else if (goal.inFlight) throw new Error("Missing Goal process evidence; manual reconciliation required")
|
|
52
|
+
return store.recoverOwner(goal.id, goal.owner.instanceId, true)
|
|
53
|
+
}
|
|
54
|
+
function startRunner(goal: GoalRecord): void {
|
|
55
|
+
if (goal.owner) throw new Error("Goal already has an active or unresolved owner")
|
|
56
|
+
if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error(`Goal is ${goal.status}`)
|
|
57
|
+
const directory = goalHome(goal.id)
|
|
58
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 })
|
|
59
|
+
const log = openSync(join(directory, "runner.log"), "a", 0o600)
|
|
60
|
+
try {
|
|
61
|
+
const isBun = /(?:^|[\\/])bun(?:\.exe)?$/i.test(process.execPath)
|
|
62
|
+
const argv = isBun ? [fileURLToPath(new URL("./index.tsx", import.meta.url)), "--goal-runner", goal.id] : ["--goal-runner", goal.id]
|
|
63
|
+
const child = spawn(process.execPath, argv, { cwd: goal.cwd, detached: true, stdio: ["ignore", log, log], env: { ...process.env, ZAPCODE_DEVTOOLS_PORT: "", ZAPCODE_HOST_PROTOCOL_PORT: "" } })
|
|
64
|
+
if (!child.pid) throw new Error("Failed to launch Goal runner")
|
|
65
|
+
child.unref()
|
|
66
|
+
} finally { closeSync(log) }
|
|
67
|
+
}
|
|
68
|
+
|
|
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 {
|
|
71
|
+
const action = args[0] ?? ""
|
|
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",
|
|
74
|
+
"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.",
|
|
80
|
+
"--accept-edits authorizes file edits but does not authorize shell commands or artifact merges requiring confirmation.",
|
|
81
|
+
].join("\n")
|
|
82
|
+
const control = ["list", "status", "watch", "pause", "cancel", "resume", "budget"].includes(action)
|
|
83
|
+
if (platform === "win32" && (action === "resume" || !control)) throw new Error("Goal execution is not yet supported on Windows: process-tree sealing cannot be verified.")
|
|
84
|
+
const checkArgs = args.filter(arg => arg === "--check" || arg.startsWith("--check="))
|
|
85
|
+
const installArgs = args.filter(arg => arg === "--install" || arg.startsWith("--install="))
|
|
86
|
+
const modeArgs = args.filter(arg => arg === "--permission-mode" || arg.startsWith("--permission-mode="))
|
|
87
|
+
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
|
+
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.")
|
|
91
|
+
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")
|
|
92
|
+
const limits: GoalBudgetLimits = { strict: args.includes("--strict") }
|
|
93
|
+
const limitKeys = { tokens: "maxTokens", "model-calls": "maxModelCalls", "provider-attempts": "maxProviderAttempts", "tool-calls": "maxToolCalls", minutes: "deadlineAt" } as const
|
|
94
|
+
const limitArgs = !control ? args.filter(arg => /^--(?:tokens|model-calls|provider-attempts|tool-calls|minutes)(?:=|$)/.test(arg)) : []
|
|
95
|
+
const seen = new Set<string>()
|
|
96
|
+
for (const arg of limitArgs) {
|
|
97
|
+
const match = /^--(tokens|model-calls|provider-attempts|tool-calls|minutes)=([1-9]\d*)$/.exec(arg)
|
|
98
|
+
if (!match || seen.has(match[1]!)) throw new Error("Invalid explicit Goal limit")
|
|
99
|
+
seen.add(match[1]!)
|
|
100
|
+
const value = Number(match[2]), key = limitKeys[match[1] as keyof typeof limitKeys]
|
|
101
|
+
const limit = key === "deadlineAt" ? Date.now() + value * 60_000 : value
|
|
102
|
+
if (!Number.isSafeInteger(value) || !Number.isSafeInteger(limit)) throw new Error("Invalid explicit Goal limit")
|
|
103
|
+
limits[key] = limit
|
|
104
|
+
}
|
|
105
|
+
if (limits.maxTokens !== undefined) limits.reservedTokens = Math.min(50_000, Math.floor(limits.maxTokens * 0.05))
|
|
106
|
+
const store = new GoalStore(goalDatabasePath(), { requireLedger: true })
|
|
107
|
+
try {
|
|
108
|
+
if (action === "list") {
|
|
109
|
+
const list = store.list(cwd)
|
|
110
|
+
return list.length ? list.map(g => `${g.id} · ${g.status} · ${g.objective}`).join("\n") : "No Goals in this workspace."
|
|
111
|
+
}
|
|
112
|
+
if (["status", "watch"].includes(action)) {
|
|
113
|
+
const goal = selectGoal(store, cwd, args[1], sessionId)
|
|
114
|
+
const ledger = new GoalBudgetLedger(goalDatabasePath())
|
|
115
|
+
try {
|
|
116
|
+
const budget = ledger.snapshot(goal.id)
|
|
117
|
+
return [
|
|
118
|
+
`${goal.id} · ${goal.status}${goal.phase ? ` / ${goal.phase}` : ""}`,
|
|
119
|
+
goal.objective,
|
|
120
|
+
...(goal.stopReason ? [`Reason: ${goal.stopReason}`] : []),
|
|
121
|
+
...(goal.failure ? [`Failure: ${JSON.stringify(goal.failure)}`] : []),
|
|
122
|
+
...(goal.progress ? [`Progress: ${JSON.stringify(goal.progress)}`] : []),
|
|
123
|
+
`Tasks: ${goal.tasks.filter(task => task.status === "passed").length}/${goal.tasks.length}`,
|
|
124
|
+
...(goal.dependencyInstall ? ["Dependencies: npm (official registry, package-lock v3, scripts disabled)"] : []),
|
|
125
|
+
`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
|
+
...(goal.delivery ? [`Artifact: ${JSON.stringify(goal.delivery)}`] : []),
|
|
127
|
+
`Log: ${join(goalHome(goal.id), "runner.log")}`,
|
|
128
|
+
].join("\n")
|
|
129
|
+
} finally { ledger.close() }
|
|
130
|
+
}
|
|
131
|
+
if (action === "budget" && args[1] === "extend") {
|
|
132
|
+
const id = args[2]?.startsWith("--") ? undefined : args[2]
|
|
133
|
+
const goal = selectGoal(store, cwd, id, sessionId)
|
|
134
|
+
const delta: { tokens?: number; modelCalls?: number; providerAttempts?: number; toolCalls?: number; minutes?: number } = {}
|
|
135
|
+
for (const arg of args.slice(id ? 3 : 2)) {
|
|
136
|
+
const match = /^--(tokens|model-calls|provider-attempts|tool-calls|minutes)=(\d+)$/.exec(arg)
|
|
137
|
+
if (!match) throw new Error(`Invalid budget extension: ${arg}`)
|
|
138
|
+
const key = ({ tokens: "tokens", "model-calls": "modelCalls", "provider-attempts": "providerAttempts", "tool-calls": "toolCalls", minutes: "minutes" } as const)[match[1] as "tokens" | "model-calls" | "provider-attempts" | "tool-calls" | "minutes"]
|
|
139
|
+
delta[key] = Number(match[2])
|
|
140
|
+
}
|
|
141
|
+
const updated = store.extendBudget(goal.id, delta)
|
|
142
|
+
return `Goal ${updated.id} budget extended; resume to continue.`
|
|
143
|
+
}
|
|
144
|
+
if (action === "pause" || action === "cancel") {
|
|
145
|
+
const goal = selectGoal(store, cwd, args[1], sessionId); const next = store.requestControl(goal.id, action)
|
|
146
|
+
return `${next.id}: ${next.owner ? `${action} requested; waiting for sealing` : next.status}`
|
|
147
|
+
}
|
|
148
|
+
if (action === "resume") {
|
|
149
|
+
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.")
|
|
151
|
+
const stopped = recoverStoppedOwner(store, goal)
|
|
152
|
+
if (sessionId && stopped.sessionId === sessionId) store.pauseForInput(cwd, sessionId)
|
|
153
|
+
startRunner(store.prepareResume(stopped.id))
|
|
154
|
+
return `Goal ${goal.id} resumed; budget and task state retained.`
|
|
155
|
+
}
|
|
156
|
+
const permissionMode = args.includes("--accept-edits") ? "acceptEdits" : modeArgs.length ? modeArgs[0]!.slice("--permission-mode=".length) as import("./config.js").PermissionMode : currentMode
|
|
157
|
+
const strict = args.includes("--strict")
|
|
158
|
+
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()
|
|
160
|
+
if (!objective) throw new Error("Goal objective is required")
|
|
161
|
+
const machineCheck = checkArgs[0]?.slice("--check=".length) as "bun" | "npm" | "pytest" | "go" | undefined
|
|
162
|
+
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 })
|
|
164
|
+
const ledger = new GoalBudgetLedger(goalDatabasePath())
|
|
165
|
+
try {
|
|
166
|
+
// Usage remains durable and shared across all phases and children; no
|
|
167
|
+
// implicit cap may turn an unfinished objective into a stopped Goal.
|
|
168
|
+
ledger.create(goal.id, 0, limits)
|
|
169
|
+
} 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.`
|
|
172
|
+
} finally { store.close() }
|
|
173
|
+
}
|