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
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import type { GoalCandidate, GoalHost, GoalOperationContext, GoalPhase, GoalPlanProposal, GoalReceipt, GoalRecord, GoalTask } from "./contracts.js";
|
|
3
|
+
import { GoalStore } from "./store.js";
|
|
4
|
+
import { driveGoalSchedule, nextGoalAction } from "./scheduler.js";
|
|
5
|
+
|
|
6
|
+
function validatePlan(proposal: GoalPlanProposal): GoalTask[] {
|
|
7
|
+
if (!proposal || !Array.isArray(proposal.tasks) || !proposal.tasks.length || proposal.tasks.length > 64) throw new Error("INVALID_GOAL_PLAN");
|
|
8
|
+
const ids = new Set<string>();
|
|
9
|
+
const tasks: GoalTask[] = proposal.tasks.map(item => {
|
|
10
|
+
if (!item || typeof item.id !== "string" || !/^[a-zA-Z0-9_-]{1,80}$/.test(item.id) || ids.has(item.id)
|
|
11
|
+
|| typeof item.description !== "string" || !item.description.trim() || typeof item.acceptance !== "string" || !item.acceptance.trim()
|
|
12
|
+
|| (item.dependencies !== undefined && (!Array.isArray(item.dependencies) || item.dependencies.some(v => typeof v !== "string")))) throw new Error("INVALID_GOAL_PLAN");
|
|
13
|
+
ids.add(item.id);
|
|
14
|
+
return { id: item.id, description: item.description, acceptance: item.acceptance, dependencies: [...(item.dependencies ?? [])], revision: 1, status: "pending", attempt: 0 };
|
|
15
|
+
});
|
|
16
|
+
const visited = new Set<string>(), visiting = new Set<string>();
|
|
17
|
+
function visit(id: string): void {
|
|
18
|
+
if (visiting.has(id)) throw new Error("CYCLIC_GOAL_PLAN");
|
|
19
|
+
if (visited.has(id)) return;
|
|
20
|
+
const task = tasks.find(t => t.id === id); if (!task) throw new Error("MISSING_GOAL_DEPENDENCY");
|
|
21
|
+
visiting.add(id); for (const dep of task.dependencies) visit(dep); visiting.delete(id); visited.add(id);
|
|
22
|
+
}
|
|
23
|
+
tasks.forEach(task => visit(task.id));
|
|
24
|
+
return tasks;
|
|
25
|
+
}
|
|
26
|
+
function checkCandidate(candidate: GoalCandidate): void {
|
|
27
|
+
if (!candidate || !candidate.candidateId || !candidate.snapshotId || !candidate.specDigest) throw new Error("INVALID_GOAL_CANDIDATE");
|
|
28
|
+
}
|
|
29
|
+
function checkReceipt(receipt: GoalReceipt, candidate: GoalCandidate, task: GoalTask): void {
|
|
30
|
+
if (!receipt || !["passed", "failed", "unverified", "error"].includes(receipt.status) || receipt.candidateId !== candidate.candidateId
|
|
31
|
+
|| receipt.snapshotId !== candidate.snapshotId || receipt.specDigest !== candidate.specDigest || receipt.taskId !== task.id
|
|
32
|
+
|| receipt.attempt !== task.attempt || receipt.evidence == null) throw new Error("INVALID_GOAL_ACCEPTANCE_RECEIPT");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Host-only coordinator: every effect has a persisted intent; unknown outcomes block recovery. */
|
|
36
|
+
export class GoalController {
|
|
37
|
+
private readonly instanceId = randomUUID();
|
|
38
|
+
private readonly abort = new AbortController();
|
|
39
|
+
private epoch = 0;
|
|
40
|
+
private timer?: ReturnType<typeof setInterval>;
|
|
41
|
+
private control?: "pause" | "cancel" | "deadline";
|
|
42
|
+
constructor(private readonly store: GoalStore, private readonly host: GoalHost, private readonly goalId: string, private readonly maxRepairs = Infinity) {}
|
|
43
|
+
private get(): GoalRecord { const goal = this.store.get(this.goalId); if (!goal) throw new Error("GOAL_NOT_FOUND"); return goal; }
|
|
44
|
+
private update(fn: (goal: GoalRecord) => void): GoalRecord { return this.store.update(this.goalId, this.epoch, this.instanceId, fn); }
|
|
45
|
+
private check(): void {
|
|
46
|
+
const goal = this.get();
|
|
47
|
+
if (goal.ownerEpoch !== this.epoch || goal.owner?.instanceId !== this.instanceId) throw new Error("GOAL_STALE_OWNER");
|
|
48
|
+
if (goal.control || goal.deadlineAt !== undefined && Date.now() >= goal.deadlineAt) {
|
|
49
|
+
this.control = goal.control ?? "deadline"; this.abort.abort(); throw new Error("GOAL_STOP_REQUESTED");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
private begin(phase: GoalPhase, taskId?: string): GoalOperationContext {
|
|
53
|
+
this.check();
|
|
54
|
+
const operationId = randomUUID();
|
|
55
|
+
const opaqueBefore = this.host.recoveryMarker?.();
|
|
56
|
+
const goal = this.update(value => { value.phase = phase; value.inFlight = { phase, operationId, ...(taskId ? { taskId } : {}), ...(opaqueBefore === undefined ? {} : { opaqueBefore }) }; });
|
|
57
|
+
return { goal, operationId, signal: this.abort.signal };
|
|
58
|
+
}
|
|
59
|
+
private finish(context: GoalOperationContext, apply: (goal: GoalRecord) => void): GoalRecord {
|
|
60
|
+
this.check();
|
|
61
|
+
return this.update(goal => {
|
|
62
|
+
if (goal.inFlight?.operationId !== context.operationId) throw new Error("GOAL_OPERATION_CONFLICT");
|
|
63
|
+
apply(goal); goal.inFlight = undefined;
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Reconcile persisted intent before any new work. The Host must prove
|
|
67
|
+
* absence of live writers and opaque effects; no unsafe replay fallback. */
|
|
68
|
+
async recover(): Promise<GoalRecord> {
|
|
69
|
+
const before = this.get();
|
|
70
|
+
if (!before.inFlight) return before;
|
|
71
|
+
const claimed = this.store.claim(this.goalId, this.instanceId, process.pid, true); this.epoch = claimed.ownerEpoch;
|
|
72
|
+
try {
|
|
73
|
+
await this.host.onClaim?.(claimed, before.ownerEpoch);
|
|
74
|
+
const resolution = await this.host.reconcile?.(claimed) ?? { kind: "blocked" as const, reason: "NO_RECONCILIATION_ADAPTER" };
|
|
75
|
+
if (resolution.kind === "blocked") return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", resolution.reason ?? "RECONCILIATION_REQUIRED");
|
|
76
|
+
this.update(goal => {
|
|
77
|
+
const flight = goal.inFlight; if (!flight || flight.operationId !== claimed.inFlight?.operationId) throw new Error("GOAL_OPERATION_CONFLICT");
|
|
78
|
+
if (flight.phase === "executing" || flight.phase === "repairing") {
|
|
79
|
+
const task = goal.tasks.find(item => item.id === flight.taskId); if (!task) throw new Error("GOAL_TASK_MISSING");
|
|
80
|
+
task.status = flight.phase === "repairing" ? "repairing" : "pending";
|
|
81
|
+
}
|
|
82
|
+
if (resolution.kind === "verified") {
|
|
83
|
+
const task = goal.tasks.find(item => item.id === flight.taskId); if (!task || !task.candidate || !resolution.receipt) throw new Error("GOAL_RECOVERY_RECEIPT_MISSING");
|
|
84
|
+
checkReceipt(resolution.receipt, task.candidate as GoalCandidate, task);
|
|
85
|
+
task.receipt = resolution.receipt;
|
|
86
|
+
task.status = resolution.receipt.status === "passed" ? "verifying" : resolution.receipt.status === "failed" ? "repairing" : "blocked";
|
|
87
|
+
}
|
|
88
|
+
goal.inFlight = undefined;
|
|
89
|
+
});
|
|
90
|
+
return this.store.release(this.goalId, this.epoch, this.instanceId, "paused", "RECONCILED_SAFE_TO_RESUME");
|
|
91
|
+
} catch (error) {
|
|
92
|
+
return this.store.release(this.goalId, this.epoch, this.instanceId, "blocked", `RECONCILIATION_FAILED: ${error instanceof Error ? error.message : String(error)}`);
|
|
93
|
+
}
|
|
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> {
|
|
205
|
+
const before = this.get();
|
|
206
|
+
const claimed = this.store.claim(this.goalId, this.instanceId, process.pid, false, options.automatic); this.epoch = claimed.ownerEpoch;
|
|
207
|
+
this.timer = setInterval(() => {
|
|
208
|
+
try { const value = this.get(); if (value.control || value.deadlineAt !== undefined && Date.now() >= value.deadlineAt) { this.control = value.control ?? "deadline"; this.abort.abort(); } }
|
|
209
|
+
catch { this.abort.abort(); }
|
|
210
|
+
}, 200);
|
|
211
|
+
try {
|
|
212
|
+
await this.host.onClaim?.(claimed, before.ownerEpoch);
|
|
213
|
+
return await driveGoalSchedule(() => this.step());
|
|
214
|
+
} catch (error) {
|
|
215
|
+
const goal = this.get();
|
|
216
|
+
if (this.control) {
|
|
217
|
+
if (error instanceof Error && error.message.includes("GOAL_SEAL_UNCONFIRMED")) throw error;
|
|
218
|
+
try {
|
|
219
|
+
if (!this.host.seal && goal.inFlight) throw new Error("GOAL_SEAL_UNAVAILABLE");
|
|
220
|
+
await this.host.seal?.(goal);
|
|
221
|
+
this.update(value => { value.phase = "sealing"; value.control = undefined; });
|
|
222
|
+
return this.store.release(this.goalId, this.epoch, this.instanceId, this.control === "cancel" ? "cancelled" : "paused", this.control === "deadline" ? "DEADLINE_EXCEEDED" : `USER_${this.control.toUpperCase()}`);
|
|
223
|
+
} catch { throw new Error("GOAL_SEAL_UNCONFIRMED"); }
|
|
224
|
+
}
|
|
225
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
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);
|
|
231
|
+
} finally { if (this.timer) clearInterval(this.timer); }
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
export const goalControllerTesting = { validatePlan, checkReceipt };
|
|
@@ -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,210 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { closeSync, existsSync, openSync, statSync } from "node:fs";
|
|
3
|
+
import { cp, lstat, mkdir, readdir, realpath, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
5
|
+
import { withPersistentGitOperation } from "./git-operation-owner.js";
|
|
6
|
+
import type { PrivateGitBinding } from "../workspace/types.js";
|
|
7
|
+
|
|
8
|
+
/** macOS-only primitive for preparing a private Git object store. It is not a
|
|
9
|
+
* Goal workspace backend: callers must still provide worktree snapshotting,
|
|
10
|
+
* merge/delivery and durable ownership before exposing Git execution. */
|
|
11
|
+
const binaries = ["/Applications/Xcode.app/Contents/Developer/usr/bin/git", "/Library/Developer/CommandLineTools/usr/bin/git"];
|
|
12
|
+
const environment = { HOME: "/nonexistent", PATH: "/usr/bin:/bin", LC_ALL: "C", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_NO_REPLACE_OBJECTS: "1", GIT_TERMINAL_PROMPT: "0" };
|
|
13
|
+
const oid = /^[0-9a-f]{40}$/;
|
|
14
|
+
|
|
15
|
+
async function trustedGit(): Promise<string | undefined> {
|
|
16
|
+
for (const binary of binaries) {
|
|
17
|
+
if (!existsSync(binary)) continue;
|
|
18
|
+
let path = binary;
|
|
19
|
+
let valid = true;
|
|
20
|
+
while (path !== "/") {
|
|
21
|
+
const info = await lstat(path);
|
|
22
|
+
if (info.isSymbolicLink() || info.uid !== 0 || (info.mode & 0o022) !== 0) { valid = false; break; }
|
|
23
|
+
path = dirname(path);
|
|
24
|
+
}
|
|
25
|
+
if (valid) return binary;
|
|
26
|
+
}
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function quote(path: string): string {
|
|
31
|
+
if (!isAbsolute(path) || /[\x00-\x1f]/.test(path)) throw new Error("Unsafe sandbox path");
|
|
32
|
+
return JSON.stringify(path);
|
|
33
|
+
}
|
|
34
|
+
function profile(readRoot: string, git: string, writeRoot: string): string {
|
|
35
|
+
return `(version 1)(allow default)(deny file-read-data (require-all (vnode-type REGULAR-FILE) (require-not (require-any (literal ${quote(git)}) (subpath ${quote(readRoot)})))))(deny file-write* (require-not (require-any (subpath ${quote(writeRoot)}) (subpath "/dev"))))(deny process-fork)(deny network*)`;
|
|
36
|
+
}
|
|
37
|
+
function execute(git: string, root: string, args: string[], signal: AbortSignal, input?: string, outputFile?: string, maxBytes = 512 * 1024 * 1024, writeRoot = "/dev"): Promise<string> {
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
if (signal.aborted) { reject(new Error("Git history capture cancelled or timed out")); return; }
|
|
40
|
+
let fd: number | undefined;
|
|
41
|
+
try { if (outputFile) fd = openSync(outputFile, "wx", 0o600); }
|
|
42
|
+
catch (error) { reject(error); return; }
|
|
43
|
+
const child = spawn("/usr/bin/sandbox-exec", ["-p", profile(root, git, writeRoot), git, "-c", "core.precomposeunicode=false", ...args], {
|
|
44
|
+
cwd: root, env: environment, stdio: ["pipe", fd === undefined ? "pipe" : fd, "pipe"],
|
|
45
|
+
});
|
|
46
|
+
if (fd !== undefined) closeSync(fd);
|
|
47
|
+
let overflow = false;
|
|
48
|
+
const abort = () => { child.kill("SIGKILL"); };
|
|
49
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
50
|
+
if (signal.aborted) abort();
|
|
51
|
+
const sizeTimer = outputFile ? setInterval(() => {
|
|
52
|
+
try { if (statSync(outputFile).size > maxBytes) { overflow = true; abort(); } } catch { overflow = true; abort(); }
|
|
53
|
+
}, 50) : undefined;
|
|
54
|
+
const out: Buffer[] = [], errors: Buffer[] = [];
|
|
55
|
+
let size = 0;
|
|
56
|
+
child.stdout?.on("data", chunk => { size += chunk.length; if (size > 8 * 1024 * 1024) child.kill(); else out.push(chunk); });
|
|
57
|
+
child.stderr?.on("data", chunk => { if (Buffer.concat(errors).length < 65536) errors.push(chunk); });
|
|
58
|
+
child.on("error", reject);
|
|
59
|
+
child.on("close", code => {
|
|
60
|
+
signal.removeEventListener("abort", abort);
|
|
61
|
+
if (sizeTimer) clearInterval(sizeTimer);
|
|
62
|
+
if (outputFile) { try { overflow ||= statSync(outputFile).size > maxBytes; } catch { overflow = true; } }
|
|
63
|
+
if (signal.aborted) reject(new Error("Git history capture cancelled or timed out"));
|
|
64
|
+
else if (overflow) reject(new Error("Git history pack exceeds resource limit"));
|
|
65
|
+
else if (code === 0 && size <= 8 * 1024 * 1024) resolve(Buffer.concat(out).toString("utf8"));
|
|
66
|
+
else reject(new Error(`Restricted Git command failed (${code}): ${Buffer.concat(errors).toString("utf8").slice(0, 1000)}`));
|
|
67
|
+
});
|
|
68
|
+
child.stdin?.on("error", () => {});
|
|
69
|
+
child.stdin?.end(input);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function inside(parent: string, child: string): boolean {
|
|
73
|
+
const rel = relative(parent, child);
|
|
74
|
+
return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
|
|
75
|
+
}
|
|
76
|
+
async function assertOrdinaryRepo(root: string): Promise<void> {
|
|
77
|
+
const dotGit = await lstat(join(root, ".git"));
|
|
78
|
+
if (!dotGit.isDirectory() || dotGit.isSymbolicLink()) throw new Error("Linked worktrees and symlinked Git directories are unsupported");
|
|
79
|
+
for (const file of ["objects/info/alternates", "objects/info/http-alternates", "commondir", "shallow"]) {
|
|
80
|
+
const entry = await lstat(join(root, ".git", file)).catch((error: NodeJS.ErrnoException) => {
|
|
81
|
+
if (error.code === "ENOENT") return undefined;
|
|
82
|
+
throw error;
|
|
83
|
+
});
|
|
84
|
+
if (entry) throw new Error(`Unsupported Git repository metadata: ${file}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Reconstruct reachable SHA-1 history in a new private bare repository.
|
|
89
|
+
* Refs are pinned before packing and checked again afterward; Git's strict
|
|
90
|
+
* index-pack validates the packed object hashes and connectivity. Callers must
|
|
91
|
+
* separately validate a consistent source working-tree snapshot. */
|
|
92
|
+
export async function capturePrivateGitHistory(source: string, destination: string, options: { signal?: AbortSignal; timeoutMs?: number; maxPackBytes?: number; afterRefsCaptured?: () => Promise<void> } = {}): Promise<void> {
|
|
93
|
+
if (process.platform !== "darwin") throw new Error("Restricted Git history capture requires macOS Seatbelt");
|
|
94
|
+
if (!isAbsolute(destination) || ["", ".", ".."].includes(basename(destination))) throw new Error("Invalid Git destination");
|
|
95
|
+
const git = await trustedGit();
|
|
96
|
+
if (!git || !existsSync("/usr/bin/sandbox-exec")) throw new Error("Trusted Git or Seatbelt is unavailable");
|
|
97
|
+
const sourceRoot = await realpath(source);
|
|
98
|
+
const destParent = await realpath(dirname(destination));
|
|
99
|
+
const parentInfo = await lstat(destParent);
|
|
100
|
+
if (!parentInfo.isDirectory() || parentInfo.isSymbolicLink() || (process.getuid && (parentInfo.uid !== process.getuid() || (parentInfo.mode & 0o077) !== 0))) throw new Error("Git destination parent must be a private owned directory");
|
|
101
|
+
const timeoutMs = options.timeoutMs ?? 120_000, maxPackBytes = options.maxPackBytes ?? 512 * 1024 * 1024;
|
|
102
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000 || !Number.isSafeInteger(maxPackBytes) || maxPackBytes < 1 || maxPackBytes > 512 * 1024 * 1024) throw new Error("Invalid Git capture resource limits");
|
|
103
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
|
|
104
|
+
const target = join(destParent, basename(destination));
|
|
105
|
+
if (inside(sourceRoot, target) || inside(target, sourceRoot)) throw new Error("Private Git destination must be separate from the source");
|
|
106
|
+
await assertOrdinaryRepo(sourceRoot);
|
|
107
|
+
if ((await execute(git, sourceRoot, ["-C", sourceRoot, "rev-parse", "--show-object-format"], signal)).trim() !== "sha1") throw new Error("SHA-256 Git repositories are not supported");
|
|
108
|
+
const refsArgs = ["-C", sourceRoot, "for-each-ref", "--format=%(refname)%00%(objectname)%00%(symref)"];
|
|
109
|
+
const refs = await execute(git, sourceRoot, refsArgs, signal);
|
|
110
|
+
const records = refs.trimEnd() ? refs.trimEnd().split("\n").map(line => line.split("\0")) : [];
|
|
111
|
+
if (records.some(record => record.length !== 3 || !record[0]!.startsWith("refs/") || !oid.test(record[1]!) || (record[2] && !record[2]!.startsWith("refs/")))) throw new Error("Invalid Git refs");
|
|
112
|
+
let head: string;
|
|
113
|
+
try { head = (await execute(git, sourceRoot, ["-C", sourceRoot, "rev-parse", "--verify", "HEAD"], signal)).trim(); }
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (signal.aborted) throw error;
|
|
116
|
+
throw new Error("Git HEAD is unborn or unavailable; Goal requires an existing commit");
|
|
117
|
+
}
|
|
118
|
+
if (!oid.test(head)) throw new Error("Invalid Git HEAD");
|
|
119
|
+
const headName = (await execute(git, sourceRoot, ["-C", sourceRoot, "rev-parse", "--symbolic-full-name", "HEAD"], signal)).trim();
|
|
120
|
+
if (headName !== "HEAD") {
|
|
121
|
+
if (!headName.startsWith("refs/heads/")) throw new Error("Unsupported Git HEAD");
|
|
122
|
+
await execute(git, sourceRoot, ["check-ref-format", headName], signal);
|
|
123
|
+
}
|
|
124
|
+
await options.afterRefsCaptured?.();
|
|
125
|
+
await mkdir(target, { mode: 0o700 });
|
|
126
|
+
const pack = join(target, "source.pack");
|
|
127
|
+
try {
|
|
128
|
+
await execute(git, sourceRoot, ["-C", sourceRoot, "pack-objects", "--revs", "--stdout"], signal, [...new Set([head, ...records.map(record => record[1]!)])].join("\n") + "\n", pack, maxPackBytes, target);
|
|
129
|
+
if (await execute(git, sourceRoot, refsArgs, signal) !== refs || (await execute(git, sourceRoot, ["-C", sourceRoot, "rev-parse", "--verify", "HEAD"], signal)).trim() !== head
|
|
130
|
+
|| (await execute(git, sourceRoot, ["-C", sourceRoot, "rev-parse", "--symbolic-full-name", "HEAD"], signal)).trim() !== headName) throw new Error("Git source changed during history capture");
|
|
131
|
+
await assertOrdinaryRepo(sourceRoot);
|
|
132
|
+
const repo = join(target, "repository.git");
|
|
133
|
+
await execute(git, target, ["init", "--bare", "--template=/nonexistent", "--object-format=sha1", repo], signal, undefined, undefined, undefined, target);
|
|
134
|
+
// The temporary pack was created exclusively by the Host and stays outside
|
|
135
|
+
// the source workspace. index-pack reads it by stdin to avoid path escape.
|
|
136
|
+
const packFd = openSync(pack, "r");
|
|
137
|
+
await new Promise<void>((resolve, reject) => {
|
|
138
|
+
const child = spawn("/usr/bin/sandbox-exec", ["-p", profile(target, git, target), git, "-c", "core.precomposeunicode=false", `--git-dir=${repo}`, "index-pack", "--strict", "--stdin"], { cwd: target, env: environment, stdio: [packFd, "ignore", "pipe"] });
|
|
139
|
+
closeSync(packFd);
|
|
140
|
+
const abort = () => { child.kill("SIGKILL"); };
|
|
141
|
+
signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort();
|
|
142
|
+
let errors = ""; child.stderr?.on("data", chunk => { errors += chunk.toString().slice(0, 1000); });
|
|
143
|
+
child.on("error", reject); child.on("close", code => { signal.removeEventListener("abort", abort); if (signal.aborted) reject(new Error("Git history capture cancelled or timed out")); else if (code === 0) resolve(); else reject(new Error(`Git index-pack failed (${code}): ${errors.slice(0, 1000)}`)); });
|
|
144
|
+
});
|
|
145
|
+
for (const [name, value, symref] of records) {
|
|
146
|
+
if (!symref) await execute(git, target, [`--git-dir=${repo}`, "update-ref", name!, value!], signal, undefined, undefined, undefined, target);
|
|
147
|
+
}
|
|
148
|
+
for (const [name, , symref] of records) if (symref) await execute(git, target, [`--git-dir=${repo}`, "symbolic-ref", name!, symref], signal, undefined, undefined, undefined, target);
|
|
149
|
+
if (headName !== "HEAD") await execute(git, target, [`--git-dir=${repo}`, "symbolic-ref", "HEAD", headName], signal, undefined, undefined, undefined, target);
|
|
150
|
+
else await execute(git, target, [`--git-dir=${repo}`, "update-ref", "--no-deref", "HEAD", head], signal, undefined, undefined, undefined, target);
|
|
151
|
+
await execute(git, target, [`--git-dir=${repo}`, "rev-list", "--objects", "--all", "--missing=error"], signal);
|
|
152
|
+
await rm(pack);
|
|
153
|
+
} catch (error) { await rm(target, { recursive: true, force: true }); throw error; }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Caller must hold a durable Git-operation marker. Compare source refs and
|
|
157
|
+
* HEAD again after file snapshotting so a changed branch cannot silently bind
|
|
158
|
+
* a worktree to an older captured history. */
|
|
159
|
+
export async function assertPrivateGitHistoryMatches(source: string, repository: string): Promise<void> {
|
|
160
|
+
const git = await trustedGit();
|
|
161
|
+
if (process.platform !== "darwin" || !git) throw new Error("Restricted Git history verification is unavailable");
|
|
162
|
+
const root = await realpath(source), repo = await realpath(repository), signal = AbortSignal.timeout(120_000);
|
|
163
|
+
await assertOrdinaryRepo(root);
|
|
164
|
+
const format = "--format=%(refname)%00%(objectname)%00%(symref)";
|
|
165
|
+
const sourceRefs = await execute(git, root, ["-C", root, "for-each-ref", format], signal);
|
|
166
|
+
const savedRefs = await execute(git, repo, [`--git-dir=${repo}`, "for-each-ref", format], signal);
|
|
167
|
+
const sourceHead = await execute(git, root, ["-C", root, "rev-parse", "--verify", "HEAD"], signal);
|
|
168
|
+
const savedHead = await execute(git, repo, [`--git-dir=${repo}`, "rev-parse", "--verify", "HEAD"], signal);
|
|
169
|
+
const sourceName = await execute(git, root, ["-C", root, "rev-parse", "--symbolic-full-name", "HEAD"], signal);
|
|
170
|
+
const savedName = await execute(git, repo, [`--git-dir=${repo}`, "rev-parse", "--symbolic-full-name", "HEAD"], signal);
|
|
171
|
+
if (sourceRefs !== savedRefs || sourceHead !== savedHead || sourceName !== savedName) throw new Error("Git source changed after history capture");
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Host-only metadata preparation for an already isolated, idle workspace.
|
|
175
|
+
* The captured bare store and workspace must both live under the private Goal
|
|
176
|
+
* owner directory. The caller must keep all model tools stopped until this
|
|
177
|
+
* operation returns, persist its binding, and never apply child commits to the
|
|
178
|
+
* user's original repository. */
|
|
179
|
+
export async function materializePrivateGitMetadata(repository: string, workspace: string, owner: string, signal?: AbortSignal): Promise<PrivateGitBinding> {
|
|
180
|
+
if (process.platform !== "darwin") throw new Error("Private Git metadata requires macOS Seatbelt");
|
|
181
|
+
const ownerRoot = await realpath(owner), repo = await realpath(repository), work = await realpath(workspace);
|
|
182
|
+
const info = await lstat(ownerRoot);
|
|
183
|
+
if (!info.isDirectory() || info.isSymbolicLink() || (process.getuid && (info.uid !== process.getuid() || (info.mode & 0o077) !== 0))) {
|
|
184
|
+
throw new Error("Private Git owner directory must be private and owned");
|
|
185
|
+
}
|
|
186
|
+
if (!inside(ownerRoot, repo) || !inside(ownerRoot, work) || inside(repo, work) || inside(work, repo)) {
|
|
187
|
+
throw new Error("Private Git paths must be separate and owned by the Goal");
|
|
188
|
+
}
|
|
189
|
+
const git = await trustedGit();
|
|
190
|
+
if (!git) throw new Error("Trusted Git is unavailable");
|
|
191
|
+
const deadline = signal ? AbortSignal.any([signal, AbortSignal.timeout(120_000)]) : AbortSignal.timeout(120_000);
|
|
192
|
+
async function validate(path: string): Promise<void> {
|
|
193
|
+
const entry = await lstat(path);
|
|
194
|
+
if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) throw new Error("Private Git snapshot contains unsafe entries");
|
|
195
|
+
if (entry.isDirectory()) for (const name of await readdir(path)) await validate(join(path, name));
|
|
196
|
+
}
|
|
197
|
+
const directory = join(work, ".git");
|
|
198
|
+
return withPersistentGitOperation(ownerRoot, async () => {
|
|
199
|
+
await validate(repo);
|
|
200
|
+
await mkdir(directory, { mode: 0o700 }); // exclusive: never replace a user's .git
|
|
201
|
+
try {
|
|
202
|
+
await cp(repo, directory, { recursive: true, force: false, errorOnExist: true, verbatimSymlinks: true });
|
|
203
|
+
await validate(directory);
|
|
204
|
+
await writeFile(join(directory, "config"), "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n", { mode: 0o600 });
|
|
205
|
+
await execute(git, directory, [`--git-dir=${directory}`, "read-tree", "HEAD"], deadline, undefined, undefined, undefined, directory);
|
|
206
|
+
const entry = await lstat(directory, { bigint: true });
|
|
207
|
+
return { directory, device: entry.dev.toString(), inode: entry.ino.toString() };
|
|
208
|
+
} catch (error) { await rm(directory, { recursive: true, force: true }); throw error; }
|
|
209
|
+
});
|
|
210
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
|
+
|
|
6
|
+
const MARKER = "git-operation.json";
|
|
7
|
+
const tails = new Map<string, Promise<void>>();
|
|
8
|
+
const activeOwner = new AsyncLocalStorage<string>();
|
|
9
|
+
|
|
10
|
+
function ownerDirectory(directory: string): string {
|
|
11
|
+
if (!isAbsolute(directory)) throw new Error("Goal Git owner directory must be absolute");
|
|
12
|
+
const path = realpathSync(directory);
|
|
13
|
+
const stat = lstatSync(path);
|
|
14
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || (process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0))) {
|
|
15
|
+
throw new Error("Goal Git owner directory must be private and owned");
|
|
16
|
+
}
|
|
17
|
+
return path;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function syncDirectory(directory: string): void {
|
|
21
|
+
const fd = openSync(directory, constants.O_RDONLY);
|
|
22
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A leftover marker is deliberately never inferred safe from a PID or timeout. */
|
|
26
|
+
export function assertNoUnresolvedGitOperation(directory: string): void {
|
|
27
|
+
const path = join(ownerDirectory(directory), MARKER);
|
|
28
|
+
try { lstatSync(path); }
|
|
29
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
|
|
30
|
+
throw new Error("GOAL_GIT_OPERATION_UNCONFIRMED");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Mark ownership *before* starting any Git process. Only a successful action
|
|
34
|
+
* whose subprocesses were awaited may retire the marker. A failure, abort, or
|
|
35
|
+
* process death remains blocked until explicit reconciliation is available. */
|
|
36
|
+
export async function withPersistentGitOperation<T>(directory: string, action: () => Promise<T>): Promise<T> {
|
|
37
|
+
const root = ownerDirectory(directory);
|
|
38
|
+
if (activeOwner.getStore() === root) throw new Error("GOAL_GIT_OPERATION_REENTRANT");
|
|
39
|
+
const previous = tails.get(root) ?? Promise.resolve();
|
|
40
|
+
let release!: () => void;
|
|
41
|
+
const tail = new Promise<void>(resolve => { release = resolve; });
|
|
42
|
+
tails.set(root, tail);
|
|
43
|
+
await previous;
|
|
44
|
+
try { return await activeOwner.run(root, () => executeOwned(root, action)); }
|
|
45
|
+
finally { if (tails.get(root) === tail) tails.delete(root); release(); }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function executeOwned<T>(root: string, action: () => Promise<T>): Promise<T> {
|
|
49
|
+
const path = join(root, MARKER), id = randomUUID();
|
|
50
|
+
const marker = JSON.stringify({ version: 1, id, pid: process.pid, startedAt: Date.now() });
|
|
51
|
+
let fd: number;
|
|
52
|
+
try { fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
|
53
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new Error("GOAL_GIT_OPERATION_UNCONFIRMED"); throw error; }
|
|
54
|
+
try { writeFileSync(fd, marker); fsyncSync(fd); } finally { closeSync(fd); }
|
|
55
|
+
syncDirectory(root);
|
|
56
|
+
const value = await action();
|
|
57
|
+
// Refuse to retire a marker which was removed or replaced during the action.
|
|
58
|
+
const readFd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
59
|
+
try { if (readFileSync(readFd, "utf8") !== marker) throw new Error("GOAL_GIT_OPERATION_OWNER_CHANGED"); }
|
|
60
|
+
finally { closeSync(readFd); }
|
|
61
|
+
unlinkSync(path);
|
|
62
|
+
syncDirectory(root);
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { estimateRequestTokens } from "../agent/call-budget.js";
|
|
3
|
+
import { TokenCounter } from "../context/token-counter.js";
|
|
4
|
+
import type { LLMCallOptions, LLMProvider } from "../core/llm.js";
|
|
5
|
+
import type { LLMChunk, Message, TokenUsage } from "../core/types.js";
|
|
6
|
+
import type { ToolDefinition } from "../tools/types.js";
|
|
7
|
+
|
|
8
|
+
export type GoalMeterRole = "planner" | "worker" | "verifier" | "repair" | "maintenance" | "finalization";
|
|
9
|
+
|
|
10
|
+
/** Synchronous host-owned ledger; never exposed to a model or a tool. */
|
|
11
|
+
export interface GoalProviderLedger {
|
|
12
|
+
reserve(goalId: string, epoch: number, input: { operationId: string; logicalCallId: string; role: GoalMeterRole; estimatedTokens: number; estimatedCostMicro: number | null; scope?: { providerId: string; modelId: string; priceRevision?: string; currency?: string } }): { ok: true; operationId: string } | { ok: false; reason: string };
|
|
13
|
+
dispatch(goalId: string, epoch: number, operationId: string): { ok: true; operationId: string } | { ok: false; reason: string };
|
|
14
|
+
settle(goalId: string, operationId: string, usage: { freshInputTokens: number; cacheReadTokens: number; cacheCreationTokens: number; outputTokens: number; costMicro: number | null; usageIncomplete?: boolean }): void;
|
|
15
|
+
markUncertain(goalId: string, operationId: string): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class GoalProviderBudgetError extends Error {
|
|
19
|
+
constructor(readonly reason: string) { super(`Goal provider admission denied: ${reason}`); this.name = "GoalProviderBudgetError"; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Wrap the provider inside RetryProvider, so each actual attempt reserves its
|
|
23
|
+
* own budget. A missing usage record or abandoned stream is uncertain, never
|
|
24
|
+
* silently charged as zero. Cost is unknown unless a trusted host supplies it. */
|
|
25
|
+
export function meterGoalProvider(inner: LLMProvider, ledger: GoalProviderLedger, context: {
|
|
26
|
+
goalId: string; epoch: number; role: GoalMeterRole;
|
|
27
|
+
scope?: { providerId: string; modelId: string; priceRevision?: string; currency?: string };
|
|
28
|
+
estimateCost?: (usage: TokenUsage, options?: LLMCallOptions) => number | null;
|
|
29
|
+
estimateRequestCost?: (tokens: number, options?: LLMCallOptions) => number | null;
|
|
30
|
+
}): LLMProvider {
|
|
31
|
+
function start(messages: Message[], tools?: ToolDefinition[], options?: LLMCallOptions): string {
|
|
32
|
+
options?.signal?.throwIfAborted();
|
|
33
|
+
const operationId = randomUUID();
|
|
34
|
+
const counter = new TokenCounter(inner.getImageTokenContext?.(options));
|
|
35
|
+
const estimatedTokens = estimateRequestTokens(messages, tools ?? [], counter) + Math.max(0, options?.maxOutputTokens ?? 4096);
|
|
36
|
+
const result = ledger.reserve(context.goalId, context.epoch, {
|
|
37
|
+
operationId, logicalCallId: options?.requestId ?? operationId, role: context.role, estimatedTokens,
|
|
38
|
+
estimatedCostMicro: context.estimateRequestCost?.(estimatedTokens, options) ?? null,
|
|
39
|
+
...(context.scope ? { scope: { ...context.scope, modelId: options?.model ?? context.scope.modelId } } : {}),
|
|
40
|
+
});
|
|
41
|
+
if (!result.ok) throw new GoalProviderBudgetError(result.reason);
|
|
42
|
+
// Persist dispatched before entering the provider. If this throws no I/O is attempted.
|
|
43
|
+
const dispatched = ledger.dispatch(context.goalId, context.epoch, operationId);
|
|
44
|
+
if (!dispatched.ok) throw new GoalProviderBudgetError(dispatched.reason);
|
|
45
|
+
return operationId;
|
|
46
|
+
}
|
|
47
|
+
function finish(operationId: string, usage: TokenUsage | undefined, options?: LLMCallOptions): void {
|
|
48
|
+
if (!usage || usage.providerUsageReported === false) { ledger.markUncertain(context.goalId, operationId); return; }
|
|
49
|
+
ledger.settle(context.goalId, operationId, {
|
|
50
|
+
freshInputTokens: usage.inputTokens, cacheReadTokens: usage.cacheReadInputTokens ?? 0,
|
|
51
|
+
cacheCreationTokens: usage.cacheCreationInputTokens ?? 0, outputTokens: usage.outputTokens,
|
|
52
|
+
costMicro: context.estimateCost?.(usage, options) ?? null,
|
|
53
|
+
...(usage.usageIncomplete ? { usageIncomplete: true } : {}),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
const wrapped: LLMProvider = {
|
|
57
|
+
getImageTokenContext: options => inner.getImageTokenContext?.(options) ?? { model: options?.model },
|
|
58
|
+
async call(messages, tools, options) {
|
|
59
|
+
const id = start(messages, tools, options);
|
|
60
|
+
let finished = false;
|
|
61
|
+
try {
|
|
62
|
+
const response = await inner.call(messages, tools, options);
|
|
63
|
+
finish(id, response.usage, options); finished = true;
|
|
64
|
+
return response;
|
|
65
|
+
} finally { if (!finished) ledger.markUncertain(context.goalId, id); }
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
if (inner.stream) wrapped.stream = async function* (messages: Message[], tools?: ToolDefinition[], options?: LLMCallOptions): AsyncIterable<LLMChunk> {
|
|
69
|
+
const id = start(messages, tools, options);
|
|
70
|
+
let finished = false;
|
|
71
|
+
try {
|
|
72
|
+
for await (const chunk of inner.stream!(messages, tools, options)) {
|
|
73
|
+
if (chunk.type === "done") { finish(id, chunk.usage, options); finished = true; }
|
|
74
|
+
yield chunk;
|
|
75
|
+
}
|
|
76
|
+
} finally { if (!finished) ledger.markUncertain(context.goalId, id); }
|
|
77
|
+
};
|
|
78
|
+
if (inner.setVisionSupported) wrapped.setVisionSupported = supported => inner.setVisionSupported!(supported);
|
|
79
|
+
return wrapped;
|
|
80
|
+
}
|