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,139 @@
|
|
|
1
|
+
import { FileBytesSnapshotProvider } from "../runtime/file-acceptance.js";
|
|
2
|
+
import { InlineAcceptanceCoordinator, acceptanceSpecDigest, validateInlineAcceptanceRecord,
|
|
3
|
+
type InlineAcceptanceStore, type InlineHostVerifier } from "../runtime/inline-acceptance.js";
|
|
4
|
+
import type { AcceptanceSpec, AgentOutcomeV1 } from "../runtime/outcome.js";
|
|
5
|
+
import type { GoalWorkspaceCandidate, GoalVerifierWorkspace, GoalWorkspace } from "./workspace.js";
|
|
6
|
+
import { goalTreeHash } from "./workspace.js";
|
|
7
|
+
|
|
8
|
+
/** Store this binding in Host-owned Goal state. Agent-provided objects are not receipts. */
|
|
9
|
+
export interface GoalAcceptanceReceipt {
|
|
10
|
+
candidateId: string;
|
|
11
|
+
candidateHash: string;
|
|
12
|
+
integrationHash: string;
|
|
13
|
+
attemptId: string;
|
|
14
|
+
recordId: string;
|
|
15
|
+
specDigest: string;
|
|
16
|
+
snapshotId: string;
|
|
17
|
+
goalSpecRevision: number;
|
|
18
|
+
planRevision: number;
|
|
19
|
+
taskSpecRevision: number;
|
|
20
|
+
verifierVersion: string;
|
|
21
|
+
verificationId?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface GoalAcceptanceBinding {
|
|
24
|
+
goalSpecRevision: number;
|
|
25
|
+
planRevision: number;
|
|
26
|
+
taskSpecRevision: number;
|
|
27
|
+
verifierVersion: string;
|
|
28
|
+
verificationId?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Host-only: the supplied verifiers must execute independently under the
|
|
32
|
+
* Host's Broker policy. Directory copies alone do not enforce that policy. */
|
|
33
|
+
export async function verifyGoalCandidate(options: {
|
|
34
|
+
workspace: GoalWorkspace;
|
|
35
|
+
candidate: GoalWorkspaceCandidate;
|
|
36
|
+
verifierWorkspace: GoalVerifierWorkspace;
|
|
37
|
+
outcome: AgentOutcomeV1;
|
|
38
|
+
spec: AcceptanceSpec;
|
|
39
|
+
verifiers: InlineHostVerifier[];
|
|
40
|
+
store: InlineAcceptanceStore;
|
|
41
|
+
binding: GoalAcceptanceBinding;
|
|
42
|
+
timeoutMs: number;
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
}): Promise<{ status: "passed" | "failed" | "unverified" | "error"; receipt?: GoalAcceptanceReceipt; detail: string }> {
|
|
45
|
+
const { workspace, candidate, verifierWorkspace, outcome, spec, store, binding } = options;
|
|
46
|
+
if (outcome.attemptId !== candidate.attemptId) throw new Error("Acceptance attempt does not match the candidate");
|
|
47
|
+
if (![binding.goalSpecRevision, binding.planRevision, binding.taskSpecRevision].every(n => Number.isSafeInteger(n) && n > 0) || !binding.verifierVersion) {
|
|
48
|
+
throw new Error("Invalid Goal acceptance binding");
|
|
49
|
+
}
|
|
50
|
+
await workspace.assertVerifierUnchanged(candidate, verifierWorkspace);
|
|
51
|
+
const snapshotProvider = new FileBytesSnapshotProvider(candidate.snapshotPath);
|
|
52
|
+
const coordinator = new InlineAcceptanceCoordinator({ mode: "required", timing: "inline", spec, snapshotProvider,
|
|
53
|
+
verifiers: options.verifiers, store, timeoutMs: options.timeoutMs });
|
|
54
|
+
const record = await coordinator.evaluate(outcome, options.signal);
|
|
55
|
+
await workspace.assertVerifierUnchanged(candidate, verifierWorkspace);
|
|
56
|
+
if (record.report.status !== "passed" || record.workflow.status !== "ready" || !record.snapshot) {
|
|
57
|
+
return { status: record.report.status, detail: record.report.code };
|
|
58
|
+
}
|
|
59
|
+
const receipt: GoalAcceptanceReceipt = { candidateId: candidate.candidateId, candidateHash: candidate.treeHash,
|
|
60
|
+
integrationHash: candidate.integrationHash, attemptId: candidate.attemptId, recordId: record.id,
|
|
61
|
+
specDigest: record.specDigest, snapshotId: record.snapshot.id, ...binding };
|
|
62
|
+
await assertGoalAcceptance(candidate, receipt, store);
|
|
63
|
+
return { status: "passed", receipt, detail: record.report.code };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Re-read the current immutable bytes and the Host's persisted receipt at each
|
|
67
|
+
* merge boundary. The caller must read the binding from its trusted GoalStore. */
|
|
68
|
+
export async function assertGoalAcceptance(candidate: GoalWorkspaceCandidate, receipt: GoalAcceptanceReceipt, store: InlineAcceptanceStore): Promise<void> {
|
|
69
|
+
if (receipt.candidateId !== candidate.candidateId || receipt.candidateHash !== candidate.treeHash
|
|
70
|
+
|| receipt.integrationHash !== candidate.integrationHash || receipt.attemptId !== candidate.attemptId
|
|
71
|
+
|| !receipt.verifierVersion || ![receipt.goalSpecRevision, receipt.planRevision, receipt.taskSpecRevision].every(n => Number.isSafeInteger(n) && n > 0)) {
|
|
72
|
+
throw new Error("Acceptance receipt does not match the Goal candidate");
|
|
73
|
+
}
|
|
74
|
+
const record = await store.load(receipt.recordId);
|
|
75
|
+
validateInlineAcceptanceRecord(record);
|
|
76
|
+
if (record.id !== receipt.recordId || record.outcome.attemptId !== candidate.attemptId || record.report.status !== "passed"
|
|
77
|
+
|| record.workflow.status !== "ready" || record.specDigest !== receipt.specDigest
|
|
78
|
+
|| acceptanceSpecDigest(record.spec) !== receipt.specDigest || record.snapshot?.id !== receipt.snapshotId) {
|
|
79
|
+
throw new Error("Acceptance record is not a passing Host receipt");
|
|
80
|
+
}
|
|
81
|
+
if (await goalTreeHash(candidate.snapshotPath) !== candidate.treeHash) throw new Error("Candidate changed after acceptance");
|
|
82
|
+
const provider = new FileBytesSnapshotProvider(candidate.snapshotPath);
|
|
83
|
+
const signal = new AbortController().signal;
|
|
84
|
+
const current = await provider.capture({ outcome: record.outcome, spec: record.spec, signal });
|
|
85
|
+
if (!current || current.id !== receipt.snapshotId) throw new Error("Acceptance subject changed after verification");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface GoalFinalAcceptanceReceipt extends GoalAcceptanceBinding {
|
|
89
|
+
goalId: string;
|
|
90
|
+
snapshotId: string;
|
|
91
|
+
treeHash: string;
|
|
92
|
+
attemptId: string;
|
|
93
|
+
recordId: string;
|
|
94
|
+
specDigest: string;
|
|
95
|
+
acceptanceSnapshotId: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Final acceptance uses a fresh immutable integration snapshot and a separate
|
|
99
|
+
* verifier copy; a passed worker receipt is never an integration receipt. */
|
|
100
|
+
export async function verifyGoalFinalSnapshot(options: {
|
|
101
|
+
workspace: GoalWorkspace;
|
|
102
|
+
snapshot: import("./workspace.js").GoalFinalSnapshot;
|
|
103
|
+
verifierWorkspace: GoalVerifierWorkspace;
|
|
104
|
+
outcome: AgentOutcomeV1;
|
|
105
|
+
spec: AcceptanceSpec;
|
|
106
|
+
verifiers: InlineHostVerifier[];
|
|
107
|
+
store: InlineAcceptanceStore;
|
|
108
|
+
binding: GoalAcceptanceBinding;
|
|
109
|
+
timeoutMs: number;
|
|
110
|
+
signal?: AbortSignal;
|
|
111
|
+
}): Promise<{ status: "passed" | "failed" | "unverified" | "error"; receipt?: GoalFinalAcceptanceReceipt; detail: string }> {
|
|
112
|
+
const { workspace, snapshot, verifierWorkspace, outcome, spec, store, binding } = options;
|
|
113
|
+
if (![binding.goalSpecRevision, binding.planRevision, binding.taskSpecRevision].every(n => Number.isSafeInteger(n) && n > 0) || !binding.verifierVersion) throw new Error("Invalid Goal acceptance binding");
|
|
114
|
+
await workspace.assertFinalVerifierUnchanged(snapshot, verifierWorkspace);
|
|
115
|
+
const provider = new FileBytesSnapshotProvider(snapshot.path);
|
|
116
|
+
const coordinator = new InlineAcceptanceCoordinator({ mode: "required", timing: "inline", spec, snapshotProvider: provider,
|
|
117
|
+
verifiers: options.verifiers, store, timeoutMs: options.timeoutMs });
|
|
118
|
+
const record = await coordinator.evaluate(outcome, options.signal);
|
|
119
|
+
await workspace.assertFinalVerifierUnchanged(snapshot, verifierWorkspace);
|
|
120
|
+
if (record.report.status !== "passed" || record.workflow.status !== "ready" || !record.snapshot) return { status: record.report.status, detail: record.report.code };
|
|
121
|
+
const receipt: GoalFinalAcceptanceReceipt = { goalId: snapshot.goalId, snapshotId: snapshot.snapshotId, treeHash: snapshot.treeHash,
|
|
122
|
+
attemptId: outcome.attemptId, recordId: record.id, specDigest: record.specDigest, acceptanceSnapshotId: record.snapshot.id, ...binding };
|
|
123
|
+
await assertGoalFinalAcceptance(workspace, snapshot, receipt, store);
|
|
124
|
+
return { status: "passed", receipt, detail: record.report.code };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function assertGoalFinalAcceptance(workspace: GoalWorkspace, snapshot: import("./workspace.js").GoalFinalSnapshot,
|
|
128
|
+
receipt: GoalFinalAcceptanceReceipt, store: InlineAcceptanceStore): Promise<void> {
|
|
129
|
+
await workspace.assertFinalSnapshot(snapshot);
|
|
130
|
+
if (receipt.goalId !== snapshot.goalId || receipt.snapshotId !== snapshot.snapshotId || receipt.treeHash !== snapshot.treeHash
|
|
131
|
+
|| !receipt.verifierVersion || ![receipt.goalSpecRevision, receipt.planRevision, receipt.taskSpecRevision].every(n => Number.isSafeInteger(n) && n > 0)) throw new Error("Final acceptance binding is stale");
|
|
132
|
+
const record = await store.load(receipt.recordId);
|
|
133
|
+
validateInlineAcceptanceRecord(record);
|
|
134
|
+
if (record.outcome.attemptId !== receipt.attemptId || record.report.status !== "passed" || record.workflow.status !== "ready"
|
|
135
|
+
|| record.specDigest !== receipt.specDigest || record.snapshot?.id !== receipt.acceptanceSnapshotId) throw new Error("Final acceptance has no passing Host receipt");
|
|
136
|
+
const provider = new FileBytesSnapshotProvider(snapshot.path);
|
|
137
|
+
const current = await provider.capture({ outcome: record.outcome, spec: record.spec, signal: new AbortController().signal });
|
|
138
|
+
if (!current || current.id !== receipt.acceptanceSnapshotId) throw new Error("Final acceptance subjects changed");
|
|
139
|
+
}
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { chmodSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Durable admission and accounting for calls controlled by a Goal host.
|
|
6
|
+
* This ledger cannot measure calls made outside the host's instrumented
|
|
7
|
+
* transports (for example an opaque CLI launched by a shell). */
|
|
8
|
+
export type GoalBudgetRole = "planner" | "worker" | "verifier" | "repair" | "maintenance" | "finalization";
|
|
9
|
+
export type GoalBudgetDenial = "budget_exhausted" | "role_limit" | "usage_unknown" | "price_unknown" | "deadline" | "stale_epoch" | "operation_exists";
|
|
10
|
+
export type GoalBudgetResult = { ok: true; operationId: string } | { ok: false; reason: GoalBudgetDenial };
|
|
11
|
+
|
|
12
|
+
export interface GoalRoleLimits {
|
|
13
|
+
maxTokens?: number;
|
|
14
|
+
maxModelCalls?: number;
|
|
15
|
+
maxProviderAttempts?: number;
|
|
16
|
+
maxToolCalls?: number;
|
|
17
|
+
maxSpawns?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface GoalBudgetLimits extends GoalRoleLimits {
|
|
21
|
+
/** Absolute UTC deadline. It continues to pass while paused. */
|
|
22
|
+
deadlineAt?: number;
|
|
23
|
+
/** All prices must use the same host-defined currency and price snapshot. */
|
|
24
|
+
maxCostMicro?: number;
|
|
25
|
+
/** Reserve tokens for the verifier and finalization; other roles cannot consume them. */
|
|
26
|
+
reservedTokens?: number;
|
|
27
|
+
/** Strict is the default. When false, unknown usage is visible but does not block admission. */
|
|
28
|
+
strict?: boolean;
|
|
29
|
+
roles?: Partial<Record<GoalBudgetRole, GoalRoleLimits>>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface GoalBudgetRequest {
|
|
33
|
+
operationId: string;
|
|
34
|
+
/** Stable for all HTTP attempts belonging to one logical model invocation. */
|
|
35
|
+
logicalCallId: string;
|
|
36
|
+
role: GoalBudgetRole;
|
|
37
|
+
estimatedTokens: number;
|
|
38
|
+
/** null or absent denotes an unknown price, not a zero price. */
|
|
39
|
+
estimatedCostMicro?: number | null;
|
|
40
|
+
/** Public billing identity only; never include credentials or raw prompts. */
|
|
41
|
+
scope?: { providerId: string; modelId: string; priceRevision?: string; currency?: string };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface GoalBudgetUsage {
|
|
45
|
+
/** SDK inputTokens is already fresh input, not the total including caches. */
|
|
46
|
+
freshInputTokens: number;
|
|
47
|
+
cacheReadTokens: number;
|
|
48
|
+
cacheCreationTokens: number;
|
|
49
|
+
outputTokens: number;
|
|
50
|
+
costMicro: number | null;
|
|
51
|
+
usageIncomplete?: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface GoalBudgetReservation extends GoalBudgetRequest {
|
|
55
|
+
goalId: string;
|
|
56
|
+
epoch: number;
|
|
57
|
+
status: "reserved" | "dispatched" | "uncertain" | "settled" | "released";
|
|
58
|
+
estimatedCostMicro: number | null;
|
|
59
|
+
usage: GoalBudgetUsage | null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface GoalBudgetSnapshot {
|
|
63
|
+
goalId: string;
|
|
64
|
+
epoch: number;
|
|
65
|
+
limits: GoalBudgetLimits;
|
|
66
|
+
totals: {
|
|
67
|
+
modelCalls: number;
|
|
68
|
+
providerAttempts: number;
|
|
69
|
+
toolCalls: number;
|
|
70
|
+
spawns: number;
|
|
71
|
+
tokensUsed: number;
|
|
72
|
+
tokensReserved: number;
|
|
73
|
+
costMicroUsed: number;
|
|
74
|
+
costMicroReserved: number;
|
|
75
|
+
unknownUsage: number;
|
|
76
|
+
unknownPrice: number;
|
|
77
|
+
/** Number of admitted tools whose external spend cannot be observed. */
|
|
78
|
+
opaqueToolCalls: number;
|
|
79
|
+
};
|
|
80
|
+
reservations: GoalBudgetReservation[];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface AccountRow { epoch: number; limits_json: string }
|
|
84
|
+
interface ReservationRow {
|
|
85
|
+
goal_id: string; operation_id: string; logical_id: string; role: GoalBudgetRole; epoch: number;
|
|
86
|
+
status: GoalBudgetReservation["status"]; estimated_tokens: number; estimated_cost: number | null; usage_json: string | null; scope_json: string | null;
|
|
87
|
+
}
|
|
88
|
+
interface EventRow { operation_id: string; role: GoalBudgetRole; kind: "tool" | "spawn"; opaque: number }
|
|
89
|
+
|
|
90
|
+
const roles: readonly GoalBudgetRole[] = ["planner", "worker", "verifier", "repair", "maintenance", "finalization"];
|
|
91
|
+
const limitKeys = ["maxTokens", "maxModelCalls", "maxProviderAttempts", "maxToolCalls", "maxSpawns"] as const;
|
|
92
|
+
|
|
93
|
+
function identifier(value: string): void {
|
|
94
|
+
if (typeof value !== "string" || !value.trim() || value.length > 512) throw new Error("Invalid Goal budget identifier");
|
|
95
|
+
}
|
|
96
|
+
function integer(value: number, field: string): void {
|
|
97
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid Goal budget ${field}`);
|
|
98
|
+
}
|
|
99
|
+
function validateRole(role: GoalBudgetRole): void {
|
|
100
|
+
if (!roles.includes(role)) throw new Error("Invalid Goal budget role");
|
|
101
|
+
}
|
|
102
|
+
function validateLimits(limits: GoalBudgetLimits): void {
|
|
103
|
+
if (!limits || typeof limits !== "object" || Array.isArray(limits)) throw new Error("Invalid Goal budget limits");
|
|
104
|
+
const allowed = [...limitKeys, "maxCostMicro", "deadlineAt", "reservedTokens", "strict", "roles"];
|
|
105
|
+
if (Object.keys(limits).some(key => !allowed.includes(key as never))) throw new Error("Unknown Goal budget limit");
|
|
106
|
+
for (const key of [...limitKeys, "maxCostMicro", "deadlineAt", "reservedTokens"] as const) {
|
|
107
|
+
if (limits[key] !== undefined) integer(limits[key]!, key);
|
|
108
|
+
}
|
|
109
|
+
if (limits.strict !== undefined && typeof limits.strict !== "boolean") throw new Error("Invalid Goal budget strict mode");
|
|
110
|
+
if (limits.roles !== undefined) {
|
|
111
|
+
if (!limits.roles || typeof limits.roles !== "object" || Array.isArray(limits.roles)) throw new Error("Invalid Goal role limits");
|
|
112
|
+
for (const [role, item] of Object.entries(limits.roles)) {
|
|
113
|
+
validateRole(role as GoalBudgetRole);
|
|
114
|
+
if (!item || typeof item !== "object" || Array.isArray(item) || Object.keys(item).some(key => !limitKeys.includes(key as never))) throw new Error("Invalid Goal role limits");
|
|
115
|
+
for (const key of limitKeys) if (item[key] !== undefined) integer(item[key]!, key);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (limits.maxTokens !== undefined && (limits.reservedTokens ?? 0) > limits.maxTokens) throw new Error("Goal token reserve exceeds limit");
|
|
119
|
+
}
|
|
120
|
+
function validateUsage(usage: GoalBudgetUsage): void {
|
|
121
|
+
if (!usage || typeof usage !== "object" || Array.isArray(usage)) throw new Error("Invalid Goal usage");
|
|
122
|
+
for (const key of ["freshInputTokens", "cacheReadTokens", "cacheCreationTokens", "outputTokens"] as const) integer(usage[key], key);
|
|
123
|
+
if (usage.costMicro !== null) integer(usage.costMicro, "costMicro");
|
|
124
|
+
if (usage.usageIncomplete !== undefined && typeof usage.usageIncomplete !== "boolean") throw new Error("Invalid Goal usage completeness");
|
|
125
|
+
if (!Number.isSafeInteger(tokenTotal(usage))) throw new Error("Goal token total exceeds safe integer range");
|
|
126
|
+
}
|
|
127
|
+
function tokenTotal(usage: GoalBudgetUsage): number {
|
|
128
|
+
return usage.freshInputTokens + usage.cacheReadTokens + usage.cacheCreationTokens + usage.outputTokens;
|
|
129
|
+
}
|
|
130
|
+
function sameUsage(a: GoalBudgetUsage, b: GoalBudgetUsage): boolean {
|
|
131
|
+
return a.freshInputTokens === b.freshInputTokens && a.cacheReadTokens === b.cacheReadTokens &&
|
|
132
|
+
a.cacheCreationTokens === b.cacheCreationTokens && a.outputTokens === b.outputTokens &&
|
|
133
|
+
a.costMicro === b.costMicro && Boolean(a.usageIncomplete) === Boolean(b.usageIncomplete);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export class GoalBudgetLedger {
|
|
137
|
+
private readonly database: Database;
|
|
138
|
+
|
|
139
|
+
constructor(readonly filePath: string) {
|
|
140
|
+
if (filePath !== ":memory:") mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
|
141
|
+
this.database = new Database(filePath, { create: true, strict: true });
|
|
142
|
+
try {
|
|
143
|
+
if (filePath !== ":memory:") chmodSync(filePath, 0o600);
|
|
144
|
+
this.database.exec("PRAGMA busy_timeout = 5000");
|
|
145
|
+
this.database.exec("PRAGMA journal_mode = DELETE");
|
|
146
|
+
this.database.exec("PRAGMA synchronous = FULL");
|
|
147
|
+
this.database.exec(`CREATE TABLE IF NOT EXISTS goal_budget_accounts (
|
|
148
|
+
goal_id TEXT PRIMARY KEY, epoch INTEGER NOT NULL, limits_json TEXT NOT NULL
|
|
149
|
+
)`);
|
|
150
|
+
this.database.exec(`CREATE TABLE IF NOT EXISTS goal_budget_reservations (
|
|
151
|
+
goal_id TEXT NOT NULL, operation_id TEXT NOT NULL, logical_id TEXT NOT NULL,
|
|
152
|
+
role TEXT NOT NULL, epoch INTEGER NOT NULL, status TEXT NOT NULL,
|
|
153
|
+
estimated_tokens INTEGER NOT NULL, estimated_cost INTEGER, usage_json TEXT, scope_json TEXT,
|
|
154
|
+
PRIMARY KEY (goal_id, operation_id), FOREIGN KEY (goal_id) REFERENCES goal_budget_accounts(goal_id)
|
|
155
|
+
)`);
|
|
156
|
+
this.database.exec(`CREATE TABLE IF NOT EXISTS goal_budget_events (
|
|
157
|
+
goal_id TEXT NOT NULL, operation_id TEXT NOT NULL, role TEXT NOT NULL, kind TEXT NOT NULL,
|
|
158
|
+
opaque INTEGER NOT NULL DEFAULT 0,
|
|
159
|
+
PRIMARY KEY (goal_id, operation_id), FOREIGN KEY (goal_id) REFERENCES goal_budget_accounts(goal_id)
|
|
160
|
+
)`);
|
|
161
|
+
} catch (error) { this.database.close(); throw error; }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
close(): void { this.database.close(); }
|
|
165
|
+
|
|
166
|
+
private transaction<T>(fn: () => T): T {
|
|
167
|
+
this.database.exec("BEGIN IMMEDIATE");
|
|
168
|
+
try { const result = fn(); this.database.exec("COMMIT"); return result; }
|
|
169
|
+
catch (error) { this.database.exec("ROLLBACK"); throw error; }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private account(goalId: string): { epoch: number; limits: GoalBudgetLimits } {
|
|
173
|
+
identifier(goalId);
|
|
174
|
+
const row = this.database.query<AccountRow, [string]>("SELECT epoch, limits_json FROM goal_budget_accounts WHERE goal_id = ?").get(goalId);
|
|
175
|
+
if (!row) throw new Error("Goal budget account not found");
|
|
176
|
+
const limits = JSON.parse(row.limits_json) as GoalBudgetLimits;
|
|
177
|
+
validateLimits(limits);
|
|
178
|
+
return { epoch: row.epoch, limits };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
create(goalId: string, epoch: number, limits: GoalBudgetLimits): void {
|
|
182
|
+
identifier(goalId); integer(epoch, "epoch"); validateLimits(limits);
|
|
183
|
+
this.transaction(() => this.database.query("INSERT INTO goal_budget_accounts(goal_id, epoch, limits_json) VALUES (?, ?, ?)")
|
|
184
|
+
.run(goalId, epoch, JSON.stringify(limits)));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Host must first prove that the old owner's writers have stopped. */
|
|
188
|
+
advanceEpoch(goalId: string, expectedEpoch: number, nextEpoch: number): boolean {
|
|
189
|
+
integer(expectedEpoch, "expected epoch"); integer(nextEpoch, "next epoch");
|
|
190
|
+
if (nextEpoch <= expectedEpoch) throw new Error("Goal epoch must increase");
|
|
191
|
+
return this.transaction(() => {
|
|
192
|
+
this.account(goalId);
|
|
193
|
+
const result = this.database.query("UPDATE goal_budget_accounts SET epoch = ? WHERE goal_id = ? AND epoch = ?")
|
|
194
|
+
.run(nextEpoch, goalId, expectedEpoch) as { changes: number };
|
|
195
|
+
return result.changes === 1;
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Only explicitly authorized, monotonic limit extensions are accepted. */
|
|
200
|
+
extend(goalId: string, epoch: number, limits: GoalBudgetLimits): boolean {
|
|
201
|
+
validateLimits(limits);
|
|
202
|
+
return this.transaction(() => {
|
|
203
|
+
const account = this.account(goalId);
|
|
204
|
+
if (account.epoch !== epoch) return false;
|
|
205
|
+
const previous = account.limits;
|
|
206
|
+
for (const key of [...limitKeys, "maxCostMicro", "deadlineAt"] as const) {
|
|
207
|
+
if (previous[key] === undefined && limits[key] !== undefined ||
|
|
208
|
+
previous[key] !== undefined && limits[key] !== undefined && limits[key]! < previous[key]!) {
|
|
209
|
+
throw new Error(`Goal budget extension cannot restrict ${key}`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
for (const role of roles) for (const key of limitKeys) {
|
|
213
|
+
const before = previous.roles?.[role]?.[key], after = limits.roles?.[role]?.[key];
|
|
214
|
+
if (before === undefined && after !== undefined || before !== undefined && after !== undefined && after < before) throw new Error("Goal budget extension cannot restrict a role");
|
|
215
|
+
}
|
|
216
|
+
if (previous.strict !== false && limits.strict === false) throw new Error("Changing unknown-usage policy requires a separate explicit authorization");
|
|
217
|
+
if ((limits.reservedTokens ?? 0) > (previous.reservedTokens ?? 0)) throw new Error("Goal budget extension cannot increase withheld reserve");
|
|
218
|
+
this.database.query("UPDATE goal_budget_accounts SET limits_json = ? WHERE goal_id = ?").run(JSON.stringify(limits), goalId);
|
|
219
|
+
return true;
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private rows(goalId: string): { reservations: GoalBudgetReservation[]; events: EventRow[] } {
|
|
224
|
+
const rows = this.database.query<ReservationRow, [string]>("SELECT * FROM goal_budget_reservations WHERE goal_id = ? ORDER BY rowid").all(goalId);
|
|
225
|
+
const reservations = rows.map(row => ({
|
|
226
|
+
goalId: row.goal_id, operationId: row.operation_id, logicalCallId: row.logical_id, role: row.role,
|
|
227
|
+
epoch: row.epoch, status: row.status, estimatedTokens: row.estimated_tokens,
|
|
228
|
+
estimatedCostMicro: row.estimated_cost, usage: row.usage_json === null ? null : JSON.parse(row.usage_json) as GoalBudgetUsage,
|
|
229
|
+
...(row.scope_json === null ? {} : { scope: JSON.parse(row.scope_json) as GoalBudgetRequest["scope"] }),
|
|
230
|
+
}));
|
|
231
|
+
const events = this.database.query<EventRow, [string]>("SELECT operation_id, role, kind, opaque FROM goal_budget_events WHERE goal_id = ? ORDER BY rowid").all(goalId);
|
|
232
|
+
return { reservations, events };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
snapshot(goalId: string): GoalBudgetSnapshot {
|
|
236
|
+
return this.transaction(() => this.snapshotUnlocked(goalId));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private snapshotUnlocked(goalId: string): GoalBudgetSnapshot {
|
|
240
|
+
const account = this.account(goalId);
|
|
241
|
+
const { reservations, events } = this.rows(goalId);
|
|
242
|
+
const active = reservations.filter(item => item.status !== "released");
|
|
243
|
+
const outstanding = active.filter(item => item.status !== "settled");
|
|
244
|
+
return {
|
|
245
|
+
goalId, epoch: account.epoch, limits: account.limits, reservations,
|
|
246
|
+
totals: {
|
|
247
|
+
modelCalls: new Set(active.map(item => item.logicalCallId)).size,
|
|
248
|
+
providerAttempts: active.length,
|
|
249
|
+
toolCalls: events.filter(item => item.kind === "tool").length,
|
|
250
|
+
spawns: events.filter(item => item.kind === "spawn").length,
|
|
251
|
+
tokensUsed: active.reduce((n, item) => n + (item.usage ? tokenTotal(item.usage) : 0), 0),
|
|
252
|
+
tokensReserved: outstanding.reduce((n, item) => n + Math.max(0, item.estimatedTokens - (item.usage ? tokenTotal(item.usage) : 0)), 0),
|
|
253
|
+
costMicroUsed: active.reduce((n, item) => n + (item.usage?.costMicro ?? 0), 0),
|
|
254
|
+
costMicroReserved: outstanding.reduce((n, item) => n + Math.max(0, (item.estimatedCostMicro ?? 0) - (item.usage?.costMicro ?? 0)), 0),
|
|
255
|
+
unknownUsage: active.filter(item => item.status === "uncertain" || item.usage?.usageIncomplete).length,
|
|
256
|
+
unknownPrice: active.filter(item => item.usage ? item.usage.costMicro === null : item.estimatedCostMicro === null).length,
|
|
257
|
+
opaqueToolCalls: events.filter(item => item.opaque === 1).length,
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
reserve(goalId: string, epoch: number, request: GoalBudgetRequest): GoalBudgetResult {
|
|
263
|
+
identifier(request.operationId); identifier(request.logicalCallId); validateRole(request.role);
|
|
264
|
+
integer(epoch, "epoch"); integer(request.estimatedTokens, "estimatedTokens");
|
|
265
|
+
if (request.estimatedCostMicro != null) integer(request.estimatedCostMicro, "estimatedCostMicro");
|
|
266
|
+
if (request.scope !== undefined) {
|
|
267
|
+
if (!request.scope || typeof request.scope !== "object" || Object.keys(request.scope).some(key => !["providerId", "modelId", "priceRevision", "currency"].includes(key))) throw new Error("Invalid Goal budget scope");
|
|
268
|
+
identifier(request.scope.providerId); identifier(request.scope.modelId);
|
|
269
|
+
if (request.scope.priceRevision !== undefined) identifier(request.scope.priceRevision);
|
|
270
|
+
if (request.scope.currency !== undefined) identifier(request.scope.currency);
|
|
271
|
+
}
|
|
272
|
+
return this.transaction(() => {
|
|
273
|
+
const snap = this.snapshotUnlocked(goalId), { limits, totals, reservations } = snap;
|
|
274
|
+
if (snap.epoch !== epoch) return { ok: false, reason: "stale_epoch" };
|
|
275
|
+
const existing = reservations.find(item => item.operationId === request.operationId);
|
|
276
|
+
if (existing) {
|
|
277
|
+
if (existing.status === "reserved" && existing.epoch === epoch && existing.logicalCallId === request.logicalCallId && existing.role === request.role &&
|
|
278
|
+
existing.estimatedTokens === request.estimatedTokens && existing.estimatedCostMicro === (request.estimatedCostMicro ?? null) &&
|
|
279
|
+
JSON.stringify(existing.scope ?? null) === JSON.stringify(request.scope ?? null)) return { ok: true, operationId: request.operationId };
|
|
280
|
+
return { ok: false, reason: "operation_exists" };
|
|
281
|
+
}
|
|
282
|
+
if (limits.deadlineAt !== undefined && Date.now() >= limits.deadlineAt) return { ok: false, reason: "deadline" };
|
|
283
|
+
if (limits.maxTokens !== undefined && request.estimatedTokens === 0) throw new Error("Token-limited Goal requests require a positive reservation");
|
|
284
|
+
if (limits.strict !== false && totals.opaqueToolCalls > 0 && [limits.maxTokens, limits.maxCostMicro,
|
|
285
|
+
limits.maxModelCalls, limits.maxProviderAttempts, limits.maxSpawns].some(value => value !== undefined)) return { ok: false, reason: "usage_unknown" };
|
|
286
|
+
if (limits.strict !== false && limits.maxTokens !== undefined && totals.unknownUsage > 0) return { ok: false, reason: "usage_unknown" };
|
|
287
|
+
if (limits.strict !== false && limits.maxCostMicro !== undefined && (totals.unknownPrice > 0 || request.estimatedCostMicro == null)) return { ok: false, reason: "price_unknown" };
|
|
288
|
+
const sameLogical = reservations.filter(item => item.status !== "released" && item.logicalCallId === request.logicalCallId);
|
|
289
|
+
if (sameLogical.some(item => item.role !== request.role)) throw new Error("Logical Goal call cannot change roles");
|
|
290
|
+
const addsModelCall = sameLogical.length === 0 ? 1 : 0;
|
|
291
|
+
const protectedTokens = request.role === "verifier" || request.role === "finalization" ? 0 : (limits.reservedTokens ?? 0);
|
|
292
|
+
if (limits.maxModelCalls !== undefined && totals.modelCalls + addsModelCall > limits.maxModelCalls ||
|
|
293
|
+
limits.maxProviderAttempts !== undefined && totals.providerAttempts + 1 > limits.maxProviderAttempts ||
|
|
294
|
+
limits.maxTokens !== undefined && totals.tokensUsed + totals.tokensReserved + request.estimatedTokens > limits.maxTokens - protectedTokens ||
|
|
295
|
+
limits.maxCostMicro !== undefined && totals.costMicroUsed + totals.costMicroReserved + (request.estimatedCostMicro ?? 0) > limits.maxCostMicro) return { ok: false, reason: "budget_exhausted" };
|
|
296
|
+
const role = limits.roles?.[request.role];
|
|
297
|
+
const own = reservations.filter(item => item.role === request.role && item.status !== "released");
|
|
298
|
+
const ownCalls = new Set(own.map(item => item.logicalCallId)).size;
|
|
299
|
+
const ownTokens = own.reduce((n, item) => n + (item.usage ? tokenTotal(item.usage) : 0) + (item.status !== "settled" ? Math.max(0, item.estimatedTokens - (item.usage ? tokenTotal(item.usage) : 0)) : 0), 0);
|
|
300
|
+
if (role?.maxModelCalls !== undefined && ownCalls + addsModelCall > role.maxModelCalls ||
|
|
301
|
+
role?.maxProviderAttempts !== undefined && own.length + 1 > role.maxProviderAttempts ||
|
|
302
|
+
role?.maxTokens !== undefined && ownTokens + request.estimatedTokens > role.maxTokens) return { ok: false, reason: "role_limit" };
|
|
303
|
+
this.database.query(`INSERT INTO goal_budget_reservations
|
|
304
|
+
(goal_id, operation_id, logical_id, role, epoch, status, estimated_tokens, estimated_cost, usage_json, scope_json)
|
|
305
|
+
VALUES (?, ?, ?, ?, ?, 'reserved', ?, ?, NULL, ?)`)
|
|
306
|
+
.run(goalId, request.operationId, request.logicalCallId, request.role, epoch, request.estimatedTokens, request.estimatedCostMicro ?? null, request.scope ? JSON.stringify(request.scope) : null);
|
|
307
|
+
return { ok: true, operationId: request.operationId };
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** The committed transition must precede the actual transport call.
|
|
312
|
+
* A duplicate dispatch is refused: callers must never replay an ambiguous call. */
|
|
313
|
+
dispatch(goalId: string, epoch: number, operationId: string): GoalBudgetResult {
|
|
314
|
+
identifier(operationId); integer(epoch, "epoch");
|
|
315
|
+
return this.transaction(() => {
|
|
316
|
+
const account = this.account(goalId);
|
|
317
|
+
if (account.epoch !== epoch) return { ok: false, reason: "stale_epoch" };
|
|
318
|
+
if (account.limits.deadlineAt !== undefined && Date.now() >= account.limits.deadlineAt) return { ok: false, reason: "deadline" };
|
|
319
|
+
const result = this.database.query("UPDATE goal_budget_reservations SET status = 'dispatched' WHERE goal_id = ? AND operation_id = ? AND epoch = ? AND status = 'reserved'")
|
|
320
|
+
.run(goalId, operationId, epoch) as { changes: number };
|
|
321
|
+
return result.changes === 1 ? { ok: true, operationId } : { ok: false, reason: "operation_exists" };
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Settlement is a trusted host operation. A late report from an already
|
|
326
|
+
* dispatched attempt remains chargeable after a lease/epoch change. */
|
|
327
|
+
settle(goalId: string, operationId: string, usage: GoalBudgetUsage): void {
|
|
328
|
+
identifier(operationId); validateUsage(usage);
|
|
329
|
+
this.transaction(() => {
|
|
330
|
+
this.account(goalId);
|
|
331
|
+
const item = this.rows(goalId).reservations.find(row => row.operationId === operationId);
|
|
332
|
+
if (!item || !["dispatched", "uncertain", "settled"].includes(item.status)) throw new Error("Goal usage was not dispatched");
|
|
333
|
+
if (item.usage) {
|
|
334
|
+
if (sameUsage(item.usage, usage)) return;
|
|
335
|
+
const canResolve = (item.usage.usageIncomplete || item.usage.costMicro === null) &&
|
|
336
|
+
usage.freshInputTokens >= item.usage.freshInputTokens && usage.cacheReadTokens >= item.usage.cacheReadTokens &&
|
|
337
|
+
usage.cacheCreationTokens >= item.usage.cacheCreationTokens && usage.outputTokens >= item.usage.outputTokens &&
|
|
338
|
+
(item.usage.costMicro === null || usage.costMicro === item.usage.costMicro) &&
|
|
339
|
+
(!item.usage.usageIncomplete || !usage.usageIncomplete);
|
|
340
|
+
if (!canResolve) throw new Error("Conflicting Goal usage settlement");
|
|
341
|
+
}
|
|
342
|
+
this.database.query("UPDATE goal_budget_reservations SET status = ?, usage_json = ? WHERE goal_id = ? AND operation_id = ?")
|
|
343
|
+
.run(usage.usageIncomplete ? "uncertain" : "settled", JSON.stringify(usage), goalId, operationId);
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
markUncertain(goalId: string, operationId: string): void {
|
|
348
|
+
identifier(operationId);
|
|
349
|
+
this.transaction(() => {
|
|
350
|
+
this.account(goalId);
|
|
351
|
+
const item = this.rows(goalId).reservations.find(row => row.operationId === operationId);
|
|
352
|
+
if (!item || !["dispatched", "uncertain"].includes(item.status)) throw new Error("Only dispatched Goal requests can be uncertain");
|
|
353
|
+
if (item.status === "dispatched") this.database.query("UPDATE goal_budget_reservations SET status = 'uncertain' WHERE goal_id = ? AND operation_id = ?").run(goalId, operationId);
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** After the host has fenced and stopped older owners, record all of their
|
|
358
|
+
* dispatched requests as uncertain. Reserved entries are intentionally left
|
|
359
|
+
* untouched until the caller proves they never crossed dispatch. */
|
|
360
|
+
recoverDispatched(goalId: string, epoch: number): number {
|
|
361
|
+
integer(epoch, "epoch");
|
|
362
|
+
return this.transaction(() => {
|
|
363
|
+
if (this.account(goalId).epoch !== epoch) throw new Error("Stale Goal budget epoch");
|
|
364
|
+
const result = this.database.query("UPDATE goal_budget_reservations SET status = 'uncertain' WHERE goal_id = ? AND epoch < ? AND status = 'dispatched'")
|
|
365
|
+
.run(goalId, epoch) as { changes: number };
|
|
366
|
+
return result.changes;
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Caller must prove this operation never crossed the dispatch boundary. */
|
|
371
|
+
releaseUnsent(goalId: string, epoch: number, operationId: string): boolean {
|
|
372
|
+
identifier(operationId); integer(epoch, "epoch");
|
|
373
|
+
return this.transaction(() => {
|
|
374
|
+
if (this.account(goalId).epoch !== epoch) return false;
|
|
375
|
+
const result = this.database.query("UPDATE goal_budget_reservations SET status = 'released' WHERE goal_id = ? AND operation_id = ? AND status = 'reserved'").run(goalId, operationId) as { changes: number };
|
|
376
|
+
return result.changes === 1;
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Persists tool/spawn admission before invocation. Duplicate IDs never
|
|
381
|
+
* authorize replay, even if the caller did not receive the prior response. */
|
|
382
|
+
admit(goalId: string, epoch: number, event: { operationId: string; role: GoalBudgetRole; kind: "tool" | "spawn"; opaque?: boolean }): GoalBudgetResult {
|
|
383
|
+
identifier(event.operationId); integer(epoch, "epoch"); validateRole(event.role);
|
|
384
|
+
if (event.kind !== "tool" && event.kind !== "spawn") throw new Error("Invalid Goal budget event");
|
|
385
|
+
if (event.opaque !== undefined && typeof event.opaque !== "boolean") throw new Error("Invalid Goal opaque-tool flag");
|
|
386
|
+
return this.transaction(() => {
|
|
387
|
+
const snap = this.snapshotUnlocked(goalId);
|
|
388
|
+
if (snap.epoch !== epoch) return { ok: false, reason: "stale_epoch" };
|
|
389
|
+
if (snap.limits.deadlineAt !== undefined && Date.now() >= snap.limits.deadlineAt) return { ok: false, reason: "deadline" };
|
|
390
|
+
const { events } = this.rows(goalId);
|
|
391
|
+
if (events.some(item => item.operation_id === event.operationId)) return { ok: false, reason: "operation_exists" };
|
|
392
|
+
if (event.opaque && snap.limits.strict !== false &&
|
|
393
|
+
["maxTokens", "maxCostMicro", "maxModelCalls", "maxProviderAttempts", "maxSpawns"].some(key => snap.limits[key as keyof GoalBudgetLimits] !== undefined)) {
|
|
394
|
+
return { ok: false, reason: "usage_unknown" };
|
|
395
|
+
}
|
|
396
|
+
const kindKey = event.kind === "tool" ? "maxToolCalls" : "maxSpawns";
|
|
397
|
+
const count = event.kind === "tool" ? snap.totals.toolCalls : snap.totals.spawns;
|
|
398
|
+
const max = snap.limits[kindKey];
|
|
399
|
+
if (max !== undefined && count >= max) return { ok: false, reason: "budget_exhausted" };
|
|
400
|
+
const roleMax = snap.limits.roles?.[event.role]?.[kindKey];
|
|
401
|
+
if (roleMax !== undefined && events.filter(item => item.role === event.role && item.kind === event.kind).length >= roleMax) return { ok: false, reason: "role_limit" };
|
|
402
|
+
this.database.query("INSERT INTO goal_budget_events(goal_id, operation_id, role, kind, opaque) VALUES (?, ?, ?, ?, ?)").run(goalId, event.operationId, event.role, event.kind, event.opaque ? 1 : 0);
|
|
403
|
+
return { ok: true, operationId: event.operationId };
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** Goal control records are Host-owned. Agent output is a proposal, never a state transition. */
|
|
2
|
+
export type GoalStatus = "created" | "running" | "paused" | "blocked" | "awaiting_acceptance" | "budget_limited" | "ready_for_delivery" | "completed" | "cancelled" | "failed";
|
|
3
|
+
export type GoalPhase = "planning" | "executing" | "verifying" | "repairing" | "integrating" | "final_verifying" | "delivering" | "sealing";
|
|
4
|
+
export interface GoalTask {
|
|
5
|
+
id: string;
|
|
6
|
+
description: string;
|
|
7
|
+
acceptance: string;
|
|
8
|
+
dependencies: string[];
|
|
9
|
+
revision: number;
|
|
10
|
+
status: "pending" | "running" | "verifying" | "repairing" | "passed" | "blocked";
|
|
11
|
+
attempt: number;
|
|
12
|
+
candidate?: unknown;
|
|
13
|
+
receipt?: GoalReceipt;
|
|
14
|
+
}
|
|
15
|
+
export interface GoalReceipt {
|
|
16
|
+
status: "passed" | "failed" | "unverified" | "error";
|
|
17
|
+
candidateId: string;
|
|
18
|
+
snapshotId: string;
|
|
19
|
+
specDigest: string;
|
|
20
|
+
taskId: string;
|
|
21
|
+
attempt: number;
|
|
22
|
+
/** Immutable record returned by the host verifier; never the worker's claim. */
|
|
23
|
+
evidence: unknown;
|
|
24
|
+
detail?: string;
|
|
25
|
+
/** Stable failed-check identity, excluding model prose and timestamps. */
|
|
26
|
+
failureFingerprint?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface GoalRecord {
|
|
29
|
+
id: string;
|
|
30
|
+
objective: string;
|
|
31
|
+
deliveryPolicy: "artifact" | "workspace";
|
|
32
|
+
machineCheck?: "bun" | "npm" | "pytest" | "go";
|
|
33
|
+
/** User-authorized, host-managed dependency preparation. */
|
|
34
|
+
dependencyInstall?: "npm";
|
|
35
|
+
permissionMode: "default" | "acceptEdits" | "plan" | "bypassPermissions";
|
|
36
|
+
/** Present for TUI-created Goals; foreground input in another chat cannot pause it. */
|
|
37
|
+
sessionId?: string;
|
|
38
|
+
cwd: string;
|
|
39
|
+
stateRevision: number;
|
|
40
|
+
specRevision: number;
|
|
41
|
+
planRevision: number;
|
|
42
|
+
status: GoalStatus;
|
|
43
|
+
phase?: GoalPhase;
|
|
44
|
+
stopReason?: string;
|
|
45
|
+
createdAt: number;
|
|
46
|
+
updatedAt: number;
|
|
47
|
+
/** Optional user-imposed deadline; absent Goals run until accepted or interrupted. */
|
|
48
|
+
deadlineAt?: number;
|
|
49
|
+
ownerEpoch: number;
|
|
50
|
+
owner?: { instanceId: string; pid: number };
|
|
51
|
+
/** Intent persisted before external work. Recovery must reconcile before retry. */
|
|
52
|
+
inFlight?: { operationId: string; phase: GoalPhase; taskId?: string; opaqueBefore?: number };
|
|
53
|
+
control?: "pause" | "cancel";
|
|
54
|
+
/** Foreground input yields at a sealed phase boundary, without killing a live tool. */
|
|
55
|
+
yieldRequested?: boolean;
|
|
56
|
+
tasks: GoalTask[];
|
|
57
|
+
integration?: unknown;
|
|
58
|
+
finalCandidate?: GoalCandidate;
|
|
59
|
+
finalReceipt?: GoalReceipt;
|
|
60
|
+
/** Host-observed progress across failed attempts; persists across runner restarts. */
|
|
61
|
+
progress?: Record<string, { fingerprint: string; stalled: number; checks: number }>;
|
|
62
|
+
failure?: { code: string; phase?: GoalPhase; operationId?: string; taskId?: string; candidateId?: string; snapshotId?: string };
|
|
63
|
+
delivery?: unknown;
|
|
64
|
+
}
|
|
65
|
+
export interface GoalPlanProposal {
|
|
66
|
+
tasks: Array<{ id: string; description: string; acceptance: string; dependencies?: string[] }>;
|
|
67
|
+
}
|
|
68
|
+
export interface GoalCandidate {
|
|
69
|
+
candidateId: string;
|
|
70
|
+
snapshotId: string;
|
|
71
|
+
specDigest: string;
|
|
72
|
+
value: unknown;
|
|
73
|
+
activity?: { toolCalls: number; changed: boolean; fingerprint: string };
|
|
74
|
+
}
|
|
75
|
+
export interface GoalOperationContext {
|
|
76
|
+
goal: Readonly<GoalRecord>;
|
|
77
|
+
operationId: string;
|
|
78
|
+
signal: AbortSignal;
|
|
79
|
+
}
|
|
80
|
+
/** Concrete Host implementations provide real isolated runtimes and trusted verifier receipts. */
|
|
81
|
+
export interface GoalHost {
|
|
82
|
+
recoveryMarker?(): number;
|
|
83
|
+
reconcile?(goal: Readonly<GoalRecord>): Promise<{ kind: "retry" | "verified" | "blocked"; receipt?: GoalReceipt; reason?: string }>;
|
|
84
|
+
onClaim?(goal: Readonly<GoalRecord>, previousEpoch: number): Promise<void>;
|
|
85
|
+
plan(context: GoalOperationContext): Promise<GoalPlanProposal>;
|
|
86
|
+
execute(context: GoalOperationContext, task: Readonly<GoalTask>, previous?: GoalReceipt): Promise<GoalCandidate>;
|
|
87
|
+
verify(context: GoalOperationContext, task: Readonly<GoalTask>, candidate: GoalCandidate, final: boolean): Promise<GoalReceipt>;
|
|
88
|
+
integrate(context: GoalOperationContext, task: Readonly<GoalTask>, candidate: GoalCandidate, receipt: GoalReceipt): Promise<unknown>;
|
|
89
|
+
snapshotIntegration(context: GoalOperationContext): Promise<GoalCandidate>;
|
|
90
|
+
deliver(context: GoalOperationContext, integration: unknown, receipt: GoalReceipt): Promise<{ status: "delivered" | "needs_authorization"; value?: unknown }>;
|
|
91
|
+
/** Called during cancellation; must settle the process tree before resolving. */
|
|
92
|
+
seal?(goal: Readonly<GoalRecord>): Promise<void>;
|
|
93
|
+
}
|