zapagent 1.14.12 → 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/commands/dispatcher.ts +1 -1
- package/src/goal-command.ts +44 -17
- package/src/goal-host.ts +71 -38
- package/src/goal-runner.ts +1 -1
- package/src/headless/goalPhase.ts +17 -8
- package/src/hooks/useTurnDispatcher.ts +3 -0
- package/src/ui/slash-palette.tsx +1 -0
- package/zapsdk/goal/acceptance.ts +2 -0
- package/zapsdk/goal/contracts.ts +14 -2
- package/zapsdk/goal/controller.ts +123 -66
- package/zapsdk/goal/errors.ts +17 -0
- package/zapsdk/goal/scheduler.ts +34 -0
- package/zapsdk/goal/store.ts +42 -6
- package/zapsdk/goal/structured-output.ts +84 -0
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import type { GoalCandidate, GoalHost, GoalOperationContext, GoalPhase, GoalPlanProposal, GoalReceipt, GoalRecord, GoalTask } from "./contracts.js";
|
|
3
3
|
import { GoalStore } from "./store.js";
|
|
4
|
+
import { driveGoalSchedule, nextGoalAction } from "./scheduler.js";
|
|
4
5
|
|
|
5
6
|
function validatePlan(proposal: GoalPlanProposal): GoalTask[] {
|
|
6
7
|
if (!proposal || !Array.isArray(proposal.tasks) || !proposal.tasks.length || proposal.tasks.length > 64) throw new Error("INVALID_GOAL_PLAN");
|
|
@@ -38,13 +39,13 @@ export class GoalController {
|
|
|
38
39
|
private epoch = 0;
|
|
39
40
|
private timer?: ReturnType<typeof setInterval>;
|
|
40
41
|
private control?: "pause" | "cancel" | "deadline";
|
|
41
|
-
constructor(private readonly store: GoalStore, private readonly host: GoalHost, private readonly goalId: string, private readonly maxRepairs =
|
|
42
|
+
constructor(private readonly store: GoalStore, private readonly host: GoalHost, private readonly goalId: string, private readonly maxRepairs = Infinity) {}
|
|
42
43
|
private get(): GoalRecord { const goal = this.store.get(this.goalId); if (!goal) throw new Error("GOAL_NOT_FOUND"); return goal; }
|
|
43
44
|
private update(fn: (goal: GoalRecord) => void): GoalRecord { return this.store.update(this.goalId, this.epoch, this.instanceId, fn); }
|
|
44
45
|
private check(): void {
|
|
45
46
|
const goal = this.get();
|
|
46
47
|
if (goal.ownerEpoch !== this.epoch || goal.owner?.instanceId !== this.instanceId) throw new Error("GOAL_STALE_OWNER");
|
|
47
|
-
if (goal.control || Date.now() >= goal.deadlineAt) {
|
|
48
|
+
if (goal.control || goal.deadlineAt !== undefined && Date.now() >= goal.deadlineAt) {
|
|
48
49
|
this.control = goal.control ?? "deadline"; this.abort.abort(); throw new Error("GOAL_STOP_REQUESTED");
|
|
49
50
|
}
|
|
50
51
|
}
|
|
@@ -84,80 +85,132 @@ export class GoalController {
|
|
|
84
85
|
task.receipt = resolution.receipt;
|
|
85
86
|
task.status = resolution.receipt.status === "passed" ? "verifying" : resolution.receipt.status === "failed" ? "repairing" : "blocked";
|
|
86
87
|
}
|
|
87
|
-
goal.inFlight = undefined;
|
|
88
|
+
goal.inFlight = undefined;
|
|
88
89
|
});
|
|
89
90
|
return this.store.release(this.goalId, this.epoch, this.instanceId, "paused", "RECONCILED_SAFE_TO_RESUME");
|
|
90
91
|
} catch (error) {
|
|
91
92
|
return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", `RECONCILIATION_FAILED: ${error instanceof Error ? error.message : String(error)}`);
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
|
-
|
|
95
|
+
private finalTask(): GoalTask {
|
|
96
|
+
const goal = this.get();
|
|
97
|
+
return { id: "$goal", description: goal.objective, acceptance: goal.objective, dependencies: [], revision: goal.specRevision, status: "verifying", attempt: 1 };
|
|
98
|
+
}
|
|
99
|
+
private recordAcceptanceIssue(goal: GoalRecord, context: GoalOperationContext, candidate: GoalCandidate, task: GoalTask, receipt: GoalReceipt): void {
|
|
100
|
+
if (receipt.status !== "error" && receipt.status !== "unverified") return;
|
|
101
|
+
const code = receipt.detail?.split(":")[0];
|
|
102
|
+
goal.failure = { code: code && /^[A-Z][A-Z_]+$/.test(code) ? code : "GOAL_ACCEPTANCE_UNVERIFIED",
|
|
103
|
+
phase: context.goal.phase, operationId: context.operationId, taskId: task.id, candidateId: candidate.candidateId, snapshotId: candidate.snapshotId };
|
|
104
|
+
}
|
|
105
|
+
private trackProgress(goal: GoalRecord, scope: string, candidate: GoalCandidate, receipt: GoalReceipt): boolean {
|
|
106
|
+
goal.progress ??= {};
|
|
107
|
+
if (receipt.status === "passed") { delete goal.progress[scope]; return false; }
|
|
108
|
+
if (receipt.status !== "failed") return false;
|
|
109
|
+
const fingerprint = createHash("sha256").update(JSON.stringify([candidate.activity?.fingerprint ?? candidate.snapshotId, receipt.failureFingerprint ?? receipt.detail ?? receipt.status])).digest("hex");
|
|
110
|
+
const previous = Object.hasOwn(goal.progress, scope) ? goal.progress[scope] : undefined;
|
|
111
|
+
const stalled = previous?.fingerprint === fingerprint ? previous.stalled + 1 : 0;
|
|
112
|
+
goal.progress = { ...goal.progress, [scope]: { fingerprint, stalled, checks: (previous?.checks ?? 0) + 1 } };
|
|
113
|
+
return stalled >= 3 || scope !== "$goal" && !!candidate.activity && candidate.activity.toolCalls === 0 && !candidate.activity.changed;
|
|
114
|
+
}
|
|
115
|
+
/** One scheduling turn. Every successful effect checkpoints its next safe
|
|
116
|
+
* action before the scheduler may start another phase. */
|
|
117
|
+
private async step(): Promise<GoalRecord> {
|
|
118
|
+
this.check();
|
|
119
|
+
const current = this.get();
|
|
120
|
+
if (current.yieldRequested) {
|
|
121
|
+
this.update(goal => { goal.yieldRequested = undefined; });
|
|
122
|
+
return this.store.release(this.goalId, this.epoch, this.instanceId, "paused", "USER_INPUT_PENDING");
|
|
123
|
+
}
|
|
124
|
+
const action = nextGoalAction(current);
|
|
125
|
+
if (action.kind === "stop") return this.store.release(this.goalId, this.epoch, this.instanceId, action.status, action.reason);
|
|
126
|
+
if (action.kind === "plan") {
|
|
127
|
+
const ctx = this.begin("planning");
|
|
128
|
+
const tasks = validatePlan(await this.host.plan(ctx));
|
|
129
|
+
return this.finish(ctx, goal => { goal.tasks = tasks; goal.planRevision = 1; });
|
|
130
|
+
}
|
|
131
|
+
if (action.kind === "execute") {
|
|
132
|
+
const task = action.task, previous = task.receipt;
|
|
133
|
+
if (task.status === "repairing" && (!previous || previous.status !== "failed" || task.attempt > this.maxRepairs)) {
|
|
134
|
+
return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", "REPAIR_LIMIT_OR_EVIDENCE_MISSING");
|
|
135
|
+
}
|
|
136
|
+
const ctx = this.begin(task.status === "repairing" ? "repairing" : "executing", task.id);
|
|
137
|
+
const running = this.update(goal => { const t = goal.tasks.find(x => x.id === task.id)!; t.attempt++; t.status = task.status === "repairing" ? "repairing" : "running"; });
|
|
138
|
+
const next = running.tasks.find(t => t.id === task.id)!;
|
|
139
|
+
const candidate = await this.host.execute({ ...ctx, goal: running }, next, previous);
|
|
140
|
+
checkCandidate(candidate);
|
|
141
|
+
return this.finish(ctx, goal => { const t = goal.tasks.find(x => x.id === task.id)!; t.candidate = candidate; t.receipt = undefined; t.status = "verifying"; });
|
|
142
|
+
}
|
|
143
|
+
if (action.kind === "verify" || action.kind === "integrate") {
|
|
144
|
+
const task = action.task, candidate = task.candidate as GoalCandidate | undefined;
|
|
145
|
+
if (!candidate) throw new Error("GOAL_CANDIDATE_MISSING");
|
|
146
|
+
checkCandidate(candidate);
|
|
147
|
+
if (action.kind === "integrate") {
|
|
148
|
+
if (!task.receipt) throw new Error("GOAL_ACCEPTANCE_MISSING");
|
|
149
|
+
checkReceipt(task.receipt, candidate, task);
|
|
150
|
+
const ctx = this.begin("integrating", task.id);
|
|
151
|
+
const integration = await this.host.integrate(ctx, task, candidate, task.receipt);
|
|
152
|
+
return this.finish(ctx, goal => {
|
|
153
|
+
goal.integration = integration; goal.tasks.find(t => t.id === task.id)!.status = "passed";
|
|
154
|
+
goal.finalCandidate = undefined; goal.finalReceipt = undefined;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
const ctx = this.begin("verifying", task.id);
|
|
158
|
+
const receipt = await this.host.verify(ctx, task, candidate, false); checkReceipt(receipt, candidate, task);
|
|
159
|
+
let stalled = false;
|
|
160
|
+
this.finish(ctx, goal => {
|
|
161
|
+
const t = goal.tasks.find(x => x.id === task.id)!;
|
|
162
|
+
t.receipt = receipt; t.status = receipt.status === "passed" ? "verifying" : receipt.status === "failed" ? "repairing" : "blocked";
|
|
163
|
+
this.recordAcceptanceIssue(goal, ctx, candidate, task, receipt);
|
|
164
|
+
stalled = this.trackProgress(goal, task.id, candidate, receipt);
|
|
165
|
+
});
|
|
166
|
+
if (stalled) return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", "GOAL_NO_PROGRESS: repeated failed evidence or no tool action; inspect the frozen candidate before resuming");
|
|
167
|
+
if (receipt.status !== "passed" && receipt.detail === "GOAL_BUDGET_LIMITED") return this.store.release(this.goalId, this.epoch, this.instanceId, "budget_limited", receipt.detail);
|
|
168
|
+
if (receipt.status === "failed" && task.attempt > this.maxRepairs) return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", receipt.detail ?? "REPAIR_LIMIT_OR_EVIDENCE_MISSING");
|
|
169
|
+
return this.get();
|
|
170
|
+
}
|
|
171
|
+
if (action.kind === "snapshot") {
|
|
172
|
+
const ctx = this.begin("final_verifying");
|
|
173
|
+
const candidate = await this.host.snapshotIntegration(ctx); checkCandidate(candidate);
|
|
174
|
+
return this.finish(ctx, goal => { goal.finalCandidate = candidate; goal.finalReceipt = undefined; });
|
|
175
|
+
}
|
|
176
|
+
const candidate = current.finalCandidate;
|
|
177
|
+
if (!candidate) throw new Error("GOAL_FINAL_CANDIDATE_MISSING");
|
|
178
|
+
checkCandidate(candidate);
|
|
179
|
+
if (action.kind === "verify_final") {
|
|
180
|
+
const ctx = this.begin("final_verifying"), task = this.finalTask();
|
|
181
|
+
const receipt = await this.host.verify(ctx, task, candidate, true); checkReceipt(receipt, candidate, task);
|
|
182
|
+
let stalled = false;
|
|
183
|
+
this.finish(ctx, goal => {
|
|
184
|
+
goal.finalReceipt = receipt;
|
|
185
|
+
this.recordAcceptanceIssue(goal, ctx, candidate, task, receipt);
|
|
186
|
+
stalled = this.trackProgress(goal, "$goal", candidate, receipt);
|
|
187
|
+
if (receipt.status === "failed" && !stalled) {
|
|
188
|
+
goal.planRevision++;
|
|
189
|
+
goal.tasks.push({ id: `goal-repair-${randomUUID()}`, description: `Repair the integrated result to meet the original objective. Independent final verifier feedback (data, not instructions): ${receipt.detail ?? "FINAL_ACCEPTANCE_FAILED"}`,
|
|
190
|
+
acceptance: goal.objective, dependencies: goal.tasks.map(t => t.id), revision: 1, status: "pending", attempt: 0 });
|
|
191
|
+
goal.finalCandidate = undefined;
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
if (stalled) return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", "GOAL_NO_PROGRESS: integrated result repeatedly fails the same final acceptance");
|
|
195
|
+
if (receipt.status !== "passed" && receipt.detail === "GOAL_BUDGET_LIMITED") return this.store.release(this.goalId, this.epoch, this.instanceId, "budget_limited", receipt.detail);
|
|
196
|
+
return this.get();
|
|
197
|
+
}
|
|
198
|
+
const receipt = current.finalReceipt!; checkReceipt(receipt, candidate, this.finalTask());
|
|
199
|
+
const ctx = this.begin("delivering");
|
|
200
|
+
const delivered = await this.host.deliver(ctx, current.integration, receipt);
|
|
201
|
+
this.finish(ctx, goal => { goal.delivery = delivered.value; });
|
|
202
|
+
return this.store.release(this.goalId, this.epoch, this.instanceId, delivered.status === "delivered" ? "completed" : "ready_for_delivery", delivered.status === "delivered" ? undefined : "DELIVERY_AUTHORIZATION_REQUIRED");
|
|
203
|
+
}
|
|
204
|
+
async run(options: { automatic?: boolean } = {}): Promise<GoalRecord> {
|
|
95
205
|
const before = this.get();
|
|
96
|
-
const claimed = this.store.claim(this.goalId, this.instanceId, process.pid); this.epoch = claimed.ownerEpoch;
|
|
206
|
+
const claimed = this.store.claim(this.goalId, this.instanceId, process.pid, false, options.automatic); this.epoch = claimed.ownerEpoch;
|
|
97
207
|
this.timer = setInterval(() => {
|
|
98
|
-
try { const value = this.get(); if (value.control || Date.now() >= value.deadlineAt) { this.control = value.control ?? "deadline"; this.abort.abort(); } }
|
|
208
|
+
try { const value = this.get(); if (value.control || value.deadlineAt !== undefined && Date.now() >= value.deadlineAt) { this.control = value.control ?? "deadline"; this.abort.abort(); } }
|
|
99
209
|
catch { this.abort.abort(); }
|
|
100
210
|
}, 200);
|
|
101
211
|
try {
|
|
102
212
|
await this.host.onClaim?.(claimed, before.ownerEpoch);
|
|
103
|
-
|
|
104
|
-
const ctx = this.begin("planning");
|
|
105
|
-
const proposal = validatePlan(await this.host.plan(ctx));
|
|
106
|
-
this.finish(ctx, goal => { goal.tasks = proposal; goal.planRevision = 1; });
|
|
107
|
-
}
|
|
108
|
-
while (true) {
|
|
109
|
-
this.check();
|
|
110
|
-
const current = this.get();
|
|
111
|
-
const task = current.tasks.find(t => t.status !== "passed" && t.dependencies.every(d => current.tasks.some(x => x.id === d && x.status === "passed")));
|
|
112
|
-
if (!task) {
|
|
113
|
-
if (current.tasks.some(t => t.status !== "passed")) throw new Error("GOAL_DEPENDENCY_BLOCKED");
|
|
114
|
-
break;
|
|
115
|
-
}
|
|
116
|
-
let currentTask = task;
|
|
117
|
-
let candidate = task.candidate as GoalCandidate | undefined;
|
|
118
|
-
let receipt = task.receipt;
|
|
119
|
-
if (task.status === "blocked") return this.store.release(this.goalId, this.epoch, this.instanceId, "awaiting_acceptance", receipt?.detail ?? "TASK_REQUIRES_ACCEPTANCE");
|
|
120
|
-
// Persisted candidate and receipt identify the next safe step. Never
|
|
121
|
-
// replay a worker merely because the owner died between operations.
|
|
122
|
-
if (task.status === "pending" || task.status === "repairing") {
|
|
123
|
-
if (task.status === "repairing" && (!receipt || receipt.status !== "failed" || task.attempt > this.maxRepairs)) {
|
|
124
|
-
return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", "REPAIR_LIMIT_OR_EVIDENCE_MISSING");
|
|
125
|
-
}
|
|
126
|
-
const ctx = this.begin(task.status === "repairing" ? "repairing" : "executing", task.id);
|
|
127
|
-
const running = this.update(goal => { const t = goal.tasks.find(x => x.id === task.id)!; t.attempt++; t.status = task.status === "repairing" ? "repairing" : "running"; });
|
|
128
|
-
currentTask = running.tasks.find(x => x.id === task.id)!;
|
|
129
|
-
candidate = await this.host.execute({ ...ctx, goal: running }, currentTask, receipt);
|
|
130
|
-
checkCandidate(candidate);
|
|
131
|
-
this.finish(ctx, goal => { const t = goal.tasks.find(x => x.id === task.id)!; t.candidate = candidate; t.receipt = undefined; t.status = "verifying"; });
|
|
132
|
-
receipt = undefined;
|
|
133
|
-
} else if (task.status !== "verifying") throw new Error("GOAL_TASK_RECOVERY_REQUIRED");
|
|
134
|
-
if (!candidate) throw new Error("GOAL_CANDIDATE_MISSING");
|
|
135
|
-
checkCandidate(candidate);
|
|
136
|
-
if (!receipt) {
|
|
137
|
-
const verification = this.begin("verifying", task.id);
|
|
138
|
-
receipt = await this.host.verify(verification, currentTask, candidate, false); checkReceipt(receipt, candidate, currentTask);
|
|
139
|
-
const checked = receipt;
|
|
140
|
-
this.finish(verification, goal => { const t = goal.tasks.find(x => x.id === task.id)!; t.receipt = checked; t.status = checked.status === "failed" ? "repairing" : checked.status === "passed" ? "verifying" : "blocked"; });
|
|
141
|
-
} else checkReceipt(receipt, candidate, currentTask);
|
|
142
|
-
if (receipt.status !== "passed") {
|
|
143
|
-
if (receipt.status === "failed" && currentTask.attempt <= this.maxRepairs) continue;
|
|
144
|
-
return this.store.release(this.goalId, this.epoch, this.instanceId, receipt.status === "failed" ? "blocked" : "awaiting_acceptance", receipt.detail ?? `VERIFICATION_${receipt.status.toUpperCase()}`);
|
|
145
|
-
}
|
|
146
|
-
const integration = this.begin("integrating", task.id);
|
|
147
|
-
const integrated = await this.host.integrate(integration, currentTask, candidate, receipt);
|
|
148
|
-
this.finish(integration, goal => { goal.integration = integrated; goal.tasks.find(x => x.id === task.id)!.status = "passed"; });
|
|
149
|
-
}
|
|
150
|
-
const snapshotOp = this.begin("final_verifying");
|
|
151
|
-
const finalCandidate = await this.host.snapshotIntegration(snapshotOp); checkCandidate(finalCandidate);
|
|
152
|
-
// The final snapshot and check share one persisted operation, so a crash cannot skip final verification.
|
|
153
|
-
const finalTask: GoalTask = { id: "$goal", description: this.get().objective, acceptance: this.get().objective, dependencies: [], revision: this.get().specRevision, status: "verifying", attempt: 1 };
|
|
154
|
-
const finalReceipt = await this.host.verify(snapshotOp, finalTask, finalCandidate, true); checkReceipt(finalReceipt, finalCandidate, finalTask);
|
|
155
|
-
this.finish(snapshotOp, goal => { goal.finalReceipt = finalReceipt; });
|
|
156
|
-
if (finalReceipt.status !== "passed") return this.store.release(this.goalId, this.epoch, this.instanceId, "awaiting_acceptance", finalReceipt.detail ?? "FINAL_ACCEPTANCE_NOT_PASSED");
|
|
157
|
-
const deliveryOp = this.begin("delivering");
|
|
158
|
-
const delivered = await this.host.deliver(deliveryOp, this.get().integration, finalReceipt);
|
|
159
|
-
this.finish(deliveryOp, goal => { goal.delivery = delivered.value; });
|
|
160
|
-
return this.store.release(this.goalId, this.epoch, this.instanceId, delivered.status === "delivered" ? "completed" : "ready_for_delivery", delivered.status === "delivered" ? undefined : "DELIVERY_AUTHORIZATION_REQUIRED");
|
|
213
|
+
return await driveGoalSchedule(() => this.step());
|
|
161
214
|
} catch (error) {
|
|
162
215
|
const goal = this.get();
|
|
163
216
|
if (this.control) {
|
|
@@ -170,7 +223,11 @@ export class GoalController {
|
|
|
170
223
|
} catch { throw new Error("GOAL_SEAL_UNCONFIRMED"); }
|
|
171
224
|
}
|
|
172
225
|
const reason = error instanceof Error ? error.message : String(error);
|
|
173
|
-
|
|
226
|
+
const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "GOAL_PHASE_FAILED";
|
|
227
|
+
const flight = goal.inFlight, task = goal.tasks.find(t => t.id === flight?.taskId);
|
|
228
|
+
const candidate = task?.candidate as GoalCandidate | undefined ?? goal.finalCandidate;
|
|
229
|
+
this.update(value => { value.failure = { code, ...(flight ? { phase: flight.phase, operationId: flight.operationId, taskId: flight.taskId } : {}), ...(candidate ? { candidateId: candidate.candidateId, snapshotId: candidate.snapshotId } : {}) }; });
|
|
230
|
+
return this.store.release(this.goalId, this.epoch, this.instanceId, code === "GOAL_BUDGET_LIMITED" ? "budget_limited" : "blocked", flight ? `OPERATION_REQUIRES_RECONCILIATION: ${reason}` : reason);
|
|
174
231
|
} finally { if (this.timer) clearInterval(this.timer); }
|
|
175
232
|
}
|
|
176
233
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { OutcomeProtocolError } from "../runtime/outcome.js";
|
|
2
|
+
|
|
3
|
+
export class GoalPhaseError extends OutcomeProtocolError {
|
|
4
|
+
constructor(code: string) {
|
|
5
|
+
const detail = code === "GOAL_NPM_EXISTING_MODULES_DIFFER" ? ": Existing node_modules differs from the sealed installation; refusing to replace it" : "";
|
|
6
|
+
super(code, `Goal phase stopped: ${code}${detail}`);
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Classify trusted runtime errors without persisting prompts or tool arguments. */
|
|
10
|
+
export function goalPhaseFailureCode(message: string): string {
|
|
11
|
+
if (/Goal (?:provider|tool|spawn|npm installation) admission denied: (?:budget_exhausted|role_limit|deadline|usage_unknown|price_unknown)/.test(message)) return "GOAL_BUDGET_LIMITED";
|
|
12
|
+
if (message.startsWith("Existing node_modules differs")) return "GOAL_NPM_EXISTING_MODULES_DIFFER";
|
|
13
|
+
if (message.startsWith("Goal npm offline install failed")) return "GOAL_NPM_INSTALL_FAILED";
|
|
14
|
+
if (message.startsWith("Goal npm installation disappeared")) return "GOAL_NPM_INSTALL_MISSING";
|
|
15
|
+
const code = /\bGOAL_[A-Z_]+\b/.exec(message)?.[0];
|
|
16
|
+
return code ?? "GOAL_PHASE_FAILED";
|
|
17
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { GoalRecord, GoalTask } from "./contracts.js";
|
|
2
|
+
|
|
3
|
+
export type GoalAction = { kind: "plan" | "snapshot" | "verify_final" | "deliver" }
|
|
4
|
+
| { kind: "execute" | "verify" | "integrate"; task: GoalTask }
|
|
5
|
+
| { kind: "stop"; status: "awaiting_acceptance" | "blocked" | "paused"; reason: string };
|
|
6
|
+
|
|
7
|
+
/** Pure scheduling policy. The controller alone owns effects and receipts. */
|
|
8
|
+
export function nextGoalAction(goal: Readonly<GoalRecord>): GoalAction {
|
|
9
|
+
if (!goal.planRevision) return { kind: "plan" };
|
|
10
|
+
if (goal.permissionMode === "plan") return { kind: "stop", status: "paused", reason: "GOAL_PLAN_REQUIRES_EXECUTION_AUTHORIZATION" };
|
|
11
|
+
const task = goal.tasks.find(t => t.status !== "passed" && t.dependencies.every(id => goal.tasks.some(dep => dep.id === id && dep.status === "passed")));
|
|
12
|
+
if (task) {
|
|
13
|
+
if (task.status === "blocked") return { kind: "stop", status: "awaiting_acceptance", reason: task.receipt?.detail ?? "TASK_REQUIRES_ACCEPTANCE" };
|
|
14
|
+
if (task.status === "pending" || task.status === "repairing") return { kind: "execute", task };
|
|
15
|
+
if (task.status !== "verifying") return { kind: "stop", status: "blocked", reason: "GOAL_TASK_RECOVERY_REQUIRED" };
|
|
16
|
+
if (task.receipt && task.receipt.status !== "passed") return { kind: "stop", status: "awaiting_acceptance", reason: task.receipt.detail ?? "TASK_REQUIRES_ACCEPTANCE" };
|
|
17
|
+
return { kind: task.receipt ? "integrate" : "verify", task };
|
|
18
|
+
}
|
|
19
|
+
if (goal.tasks.some(t => t.status !== "passed")) return { kind: "stop", status: "blocked", reason: "GOAL_DEPENDENCY_BLOCKED" };
|
|
20
|
+
if (!goal.finalCandidate) return { kind: "snapshot" };
|
|
21
|
+
if (!goal.finalReceipt) return { kind: "verify_final" };
|
|
22
|
+
if (goal.finalReceipt.status !== "passed") return { kind: "stop", status: "awaiting_acceptance", reason: goal.finalReceipt.detail ?? "FINAL_ACCEPTANCE_NOT_PASSED" };
|
|
23
|
+
return { kind: "deliver" };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Each completed phase emits the next scheduling opportunity. Yielding to
|
|
27
|
+
* the event loop lets queued user control win before starting new work. */
|
|
28
|
+
export async function driveGoalSchedule(step: () => Promise<GoalRecord>): Promise<GoalRecord> {
|
|
29
|
+
for (;;) {
|
|
30
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
31
|
+
const goal = await step();
|
|
32
|
+
if (goal.status !== "running") return goal;
|
|
33
|
+
}
|
|
34
|
+
}
|
package/zapsdk/goal/store.ts
CHANGED
|
@@ -16,10 +16,10 @@ export class GoalStore {
|
|
|
16
16
|
this.db.exec("CREATE TABLE IF NOT EXISTS goal_budget_extensions (id TEXT PRIMARY KEY, goal_id TEXT NOT NULL, at INTEGER NOT NULL, old_limits TEXT NOT NULL, new_limits TEXT NOT NULL)");
|
|
17
17
|
}
|
|
18
18
|
close(): void { this.db.close(); }
|
|
19
|
-
create(input: { objective: string; cwd: string; deadlineAt
|
|
20
|
-
if (!input.objective.trim() || !input.cwd || !Number.isSafeInteger(input.deadlineAt) || input.deadlineAt <= Date.now() || (input.dependencyInstall !== undefined && input.dependencyInstall !== "npm")) throw new Error("INVALID_GOAL");
|
|
19
|
+
create(input: { objective: string; cwd: string; sessionId?: string; deadlineAt?: number; deliveryPolicy?: "artifact" | "workspace"; machineCheck?: "bun" | "npm" | "pytest" | "go"; dependencyInstall?: "npm"; permissionMode?: "default" | "acceptEdits" | "plan" | "bypassPermissions" }): GoalRecord {
|
|
20
|
+
if (!input.objective.trim() || !input.cwd || (input.deadlineAt !== undefined && (!Number.isSafeInteger(input.deadlineAt) || input.deadlineAt <= Date.now())) || (input.dependencyInstall !== undefined && input.dependencyInstall !== "npm")) throw new Error("INVALID_GOAL");
|
|
21
21
|
const now = Date.now();
|
|
22
|
-
const value: GoalRecord = { id: `goal_${randomUUID()}`, objective: input.objective, deliveryPolicy: input.deliveryPolicy ?? "workspace", permissionMode: input.permissionMode ?? "default", ...(input.machineCheck ? { machineCheck: input.machineCheck } : {}), ...(input.dependencyInstall ? { dependencyInstall: input.dependencyInstall } : {}), cwd: input.cwd, stateRevision: 1, specRevision: 1, planRevision: 0, status: "created", createdAt: now, updatedAt: now, deadlineAt: input.deadlineAt, ownerEpoch: 0, tasks: [] };
|
|
22
|
+
const value: GoalRecord = { id: `goal_${randomUUID()}`, objective: input.objective, deliveryPolicy: input.deliveryPolicy ?? "workspace", permissionMode: input.permissionMode ?? "default", ...(input.machineCheck ? { machineCheck: input.machineCheck } : {}), ...(input.dependencyInstall ? { dependencyInstall: input.dependencyInstall } : {}), cwd: input.cwd, ...(input.sessionId ? { sessionId: input.sessionId } : {}), stateRevision: 1, specRevision: 1, planRevision: 0, status: "created", createdAt: now, updatedAt: now, ...(input.deadlineAt === undefined ? {} : { deadlineAt: input.deadlineAt }), ownerEpoch: 0, tasks: [] };
|
|
23
23
|
this.db.query("INSERT INTO goals(id,revision,record) VALUES(?,?,?)").run(value.id, value.stateRevision, JSON.stringify(value));
|
|
24
24
|
return value;
|
|
25
25
|
}
|
|
@@ -47,14 +47,15 @@ export class GoalStore {
|
|
|
47
47
|
if (changed !== 1) throw new Error("GOAL_REVISION_CONFLICT");
|
|
48
48
|
return structuredClone(next);
|
|
49
49
|
}
|
|
50
|
-
claim(id: string, instanceId: string, pid: number, forRecovery = false): GoalRecord {
|
|
50
|
+
claim(id: string, instanceId: string, pid: number, forRecovery = false, automatic = false): GoalRecord {
|
|
51
51
|
return this.transaction(() => {
|
|
52
52
|
const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
|
|
53
53
|
if (goal.owner) throw new Error("GOAL_OWNER_ACTIVE_OR_UNRESOLVED");
|
|
54
|
+
if (automatic && (goal.control || !(goal.status === "created" || goal.status === "paused" && goal.stopReason === "RECONCILED_SAFE_TO_RESUME"))) throw new Error("GOAL_AUTOMATIC_CONTINUATION_SUPPRESSED");
|
|
54
55
|
if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error("GOAL_TERMINAL");
|
|
55
56
|
if (goal.inFlight && !forRecovery) throw new Error("GOAL_RECOVERY_REQUIRED");
|
|
56
57
|
if (forRecovery && !goal.inFlight) throw new Error("GOAL_NO_RECOVERY_REQUIRED");
|
|
57
|
-
const next = structuredClone(goal); next.ownerEpoch++; next.owner = { instanceId, pid }; next.status = "running"; next.stopReason = undefined; next.control = undefined;
|
|
58
|
+
const next = structuredClone(goal); next.ownerEpoch++; next.owner = { instanceId, pid }; next.status = "running"; next.stopReason = undefined; next.failure = undefined; next.control = undefined;
|
|
58
59
|
// The Goal and its ledger reside in the same Host database. Advancing
|
|
59
60
|
// both epochs under this transaction prevents a crash or SQLite error
|
|
60
61
|
// from stranding a Goal at a revision its meter will never accept.
|
|
@@ -72,7 +73,7 @@ export class GoalStore {
|
|
|
72
73
|
const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
|
|
73
74
|
if (goal.ownerEpoch !== epoch || goal.owner?.instanceId !== instanceId) throw new Error("GOAL_STALE_OWNER");
|
|
74
75
|
const next = structuredClone(goal); fn(next);
|
|
75
|
-
if (next.id !== goal.id || next.ownerEpoch !== goal.ownerEpoch || next.owner?.instanceId !== goal.owner.instanceId || next.specRevision !== goal.specRevision || next.objective !== goal.objective || next.deliveryPolicy !== goal.deliveryPolicy || next.machineCheck !== goal.machineCheck || next.dependencyInstall !== goal.dependencyInstall || next.permissionMode !== goal.permissionMode || next.cwd !== goal.cwd || next.deadlineAt !== goal.deadlineAt) throw new Error("GOAL_IMMUTABLE_FIELD");
|
|
76
|
+
if (next.id !== goal.id || next.ownerEpoch !== goal.ownerEpoch || next.owner?.instanceId !== goal.owner.instanceId || next.specRevision !== goal.specRevision || next.objective !== goal.objective || next.deliveryPolicy !== goal.deliveryPolicy || next.machineCheck !== goal.machineCheck || next.dependencyInstall !== goal.dependencyInstall || next.permissionMode !== goal.permissionMode || next.cwd !== goal.cwd || next.sessionId !== goal.sessionId || next.deadlineAt !== goal.deadlineAt) throw new Error("GOAL_IMMUTABLE_FIELD");
|
|
76
77
|
return this.save(goal, next);
|
|
77
78
|
});
|
|
78
79
|
}
|
|
@@ -113,6 +114,41 @@ export class GoalStore {
|
|
|
113
114
|
return this.save(goal, next);
|
|
114
115
|
});
|
|
115
116
|
}
|
|
117
|
+
/** Foreground input may interrupt only Goals created by this chat. */
|
|
118
|
+
pauseForInput(cwd: string, sessionId: string): string[] {
|
|
119
|
+
return this.transaction(() => {
|
|
120
|
+
const ids: string[] = [];
|
|
121
|
+
for (const goal of this.list(cwd)) {
|
|
122
|
+
if (goal.sessionId !== sessionId || goal.control || !["created", "running"].includes(goal.status)) continue;
|
|
123
|
+
const next = structuredClone(goal); next.yieldRequested = true;
|
|
124
|
+
if (!next.owner && !next.inFlight) { next.status = "paused"; next.yieldRequested = undefined; next.stopReason = "USER_INPUT_PENDING"; }
|
|
125
|
+
this.save(goal, next); ids.push(goal.id);
|
|
126
|
+
}
|
|
127
|
+
return ids;
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
/** Explicit user resumption retries only indeterminate verification against
|
|
131
|
+
* the retained candidate; failed worker evidence stays available for repair. */
|
|
132
|
+
prepareResume(id: string): GoalRecord {
|
|
133
|
+
return this.transaction(() => {
|
|
134
|
+
const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
|
|
135
|
+
if (goal.owner) throw new Error("GOAL_OWNER_ACTIVE_OR_UNRESOLVED");
|
|
136
|
+
if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error("GOAL_TERMINAL");
|
|
137
|
+
const next = structuredClone(goal);
|
|
138
|
+
// Never erase unresolved effects or their evidence at this boundary.
|
|
139
|
+
if (!next.inFlight) {
|
|
140
|
+
for (const task of next.tasks) if (task.status === "blocked" && ["error", "unverified"].includes(task.receipt?.status ?? "")) {
|
|
141
|
+
task.status = "verifying"; task.receipt = undefined;
|
|
142
|
+
}
|
|
143
|
+
if (next.finalReceipt && next.finalReceipt.status !== "passed") {
|
|
144
|
+
next.finalReceipt = undefined;
|
|
145
|
+
}
|
|
146
|
+
next.progress = undefined;
|
|
147
|
+
}
|
|
148
|
+
next.status = "created"; next.stopReason = undefined; next.yieldRequested = undefined;
|
|
149
|
+
return this.save(goal, next);
|
|
150
|
+
});
|
|
151
|
+
}
|
|
116
152
|
/** User control requests are persisted separately from owner transitions. */
|
|
117
153
|
requestControl(id: string, control: "pause" | "cancel"): GoalRecord {
|
|
118
154
|
return this.transaction(() => {
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { OutcomeProtocolError } from "../runtime/outcome.js";
|
|
3
|
+
|
|
4
|
+
export class GoalStructuredOutputError extends OutcomeProtocolError {
|
|
5
|
+
constructor() { super("GOAL_STRUCTURED_OUTPUT_INVALID", "GOAL_STRUCTURED_OUTPUT_INVALID: result is missing, ambiguous or fails its schema"); }
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function parseUniqueKeys(text: string): unknown {
|
|
9
|
+
const stack: Set<string>[] = [];
|
|
10
|
+
let start = -1, escaped = false;
|
|
11
|
+
for (let i = 0; i < text.length; i++) {
|
|
12
|
+
const char = text[i];
|
|
13
|
+
if (start >= 0) {
|
|
14
|
+
if (escaped) { escaped = false; continue; }
|
|
15
|
+
if (char === "\\") { escaped = true; continue; }
|
|
16
|
+
if (char === '\"') {
|
|
17
|
+
let next = i + 1; while (/\s/.test(text[next] ?? "") && next < text.length) next++;
|
|
18
|
+
if (text[next] === ":") {
|
|
19
|
+
const key = JSON.parse(text.slice(start, i + 1)) as string, keys = stack.at(-1);
|
|
20
|
+
if (!keys || keys.has(key)) throw new GoalStructuredOutputError();
|
|
21
|
+
keys.add(key);
|
|
22
|
+
}
|
|
23
|
+
start = -1;
|
|
24
|
+
}
|
|
25
|
+
} else if (char === '\"') start = i;
|
|
26
|
+
else if (char === "{") stack.push(new Set());
|
|
27
|
+
else if (char === "}") stack.pop();
|
|
28
|
+
}
|
|
29
|
+
return JSON.parse(text);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Extract a single balanced object, ignoring braces inside JSON strings.
|
|
33
|
+
* Surrounding prose/fences are tolerated; multiple objects never select a winner. */
|
|
34
|
+
export function parseGoalObject<T>(text: string, schema: z.ZodType<T>): T {
|
|
35
|
+
if (text.length > 1024 * 1024) throw new GoalStructuredOutputError();
|
|
36
|
+
const objects: string[] = [];
|
|
37
|
+
let start = -1, depth = 0, quoted = false, escaped = false;
|
|
38
|
+
for (let i = 0; i < text.length; i++) {
|
|
39
|
+
const char = text[i];
|
|
40
|
+
if (start < 0) { if (char === "{") { start = i; depth = 1; } continue; }
|
|
41
|
+
if (quoted) {
|
|
42
|
+
if (escaped) escaped = false;
|
|
43
|
+
else if (char === "\\") escaped = true;
|
|
44
|
+
else if (char === '"') quoted = false;
|
|
45
|
+
} else if (char === '"') quoted = true;
|
|
46
|
+
else if (char === "{") depth++;
|
|
47
|
+
else if (char === "}" && --depth === 0) { objects.push(text.slice(start, i + 1)); start = -1; }
|
|
48
|
+
}
|
|
49
|
+
if (start >= 0 || objects.length !== 1) throw new GoalStructuredOutputError();
|
|
50
|
+
// A whole JSON value (e.g. an array containing an object) must not be
|
|
51
|
+
// reinterpreted as prose around an otherwise valid inner object.
|
|
52
|
+
const trimmed = text.trim();
|
|
53
|
+
if (trimmed.startsWith("[")) throw new GoalStructuredOutputError();
|
|
54
|
+
try { return schema.parse(parseUniqueKeys(objects[0]!)); }
|
|
55
|
+
catch { throw new GoalStructuredOutputError(); }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const goalPlanSchema = z.strictObject({ tasks: z.array(z.strictObject({
|
|
59
|
+
id: z.string().regex(/^[a-zA-Z0-9_-]{1,80}$/), description: z.string().trim().min(1),
|
|
60
|
+
acceptance: z.string().trim().min(1), dependencies: z.array(z.string()).optional(),
|
|
61
|
+
})).min(1).max(64) }).superRefine((plan, ctx) => {
|
|
62
|
+
const tasks = new Map(plan.tasks.map(task => [task.id, task]));
|
|
63
|
+
const done = new Set<string>(), visiting = new Set<string>();
|
|
64
|
+
const visit = (id: string): boolean => {
|
|
65
|
+
if (done.has(id)) return true;
|
|
66
|
+
const task = tasks.get(id);
|
|
67
|
+
if (!task || visiting.has(id)) return false;
|
|
68
|
+
visiting.add(id);
|
|
69
|
+
for (const dep of task.dependencies ?? []) if (!visit(dep)) return false;
|
|
70
|
+
visiting.delete(id); done.add(id); return true;
|
|
71
|
+
};
|
|
72
|
+
if (tasks.size !== plan.tasks.length || plan.tasks.some(task => !visit(task.id))) ctx.addIssue({ code: "custom", message: "Invalid task DAG" });
|
|
73
|
+
});
|
|
74
|
+
export const goalVerdictSchema = z.strictObject({ status: z.enum(["passed", "failed", "unverified"]), detail: z.string().trim().min(1).max(8000) });
|
|
75
|
+
|
|
76
|
+
/** Only schema failures are retried. The caller supplies a fresh sealed,
|
|
77
|
+
* metered read-only phase each time; execution/permission errors propagate. */
|
|
78
|
+
export async function readGoalStructuredResult<T>(run: (correction: string) => Promise<string>, schema: z.ZodType<T>): Promise<T> {
|
|
79
|
+
for (let attempt = 0; ; attempt++) {
|
|
80
|
+
const text = await run(attempt === 0 ? "" : "\n\nYour previous result failed the required JSON schema. Return exactly the requested JSON object, without commentary or examples. Do not perform development work.");
|
|
81
|
+
try { return parseGoalObject(text, schema); }
|
|
82
|
+
catch (error) { if (!(error instanceof GoalStructuredOutputError) || attempt >= 2) throw error; }
|
|
83
|
+
}
|
|
84
|
+
}
|