Spaces:
Paused
Paused
File size: 10,541 Bytes
2df2e7e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | import { createHash } from "node:crypto";
import { MongoServerError, ObjectId } from "mongodb";
import { collections } from "$lib/server/database";
import type {
AgentConfigurationAction,
AgentConfigurationKey,
AgentConfigurationReceipt,
Workspace,
} from "$lib/types/Workspace";
export type AgentConfigurationPayload =
| { action: "set-model"; model: string }
| { action: "set-thinking"; level: string }
| { action: "set-policy"; policy: string };
export type AgentConfigurationReceiptState =
| { status: "missing" }
| { status: "pending"; receipt: AgentConfigurationReceipt }
| { status: "completed"; receipt: AgentConfigurationReceipt }
| { status: "conflict" }
| { status: "stale" };
/** Canonical hash which binds one stable client id to one exact setting. */
export function fingerprintAgentConfiguration(payload: AgentConfigurationPayload): string {
return createHash("sha256")
.update(
JSON.stringify({
action: payload.action,
value: configurationValue(payload),
})
)
.digest("hex");
}
/** Read-only preflight lets completed retries succeed without opening the sandbox. */
export async function inspectAgentConfiguration(options: {
workspaceId: Workspace["_id"];
controlId: string;
fingerprint: string;
}): Promise<AgentConfigurationReceiptState> {
const receipt = await collections.agentConfigurationReceipts.findOne({
workspaceId: options.workspaceId,
controlId: options.controlId,
});
return classifyReceipt(receipt, options.fingerprint);
}
/**
* Append a command to the durable per-workspace log and make it latest for its
* setting kind. Receipts are separate documents, so stable ids are never
* evicted and a hostile number of settings cannot grow the Workspace document.
*
* The placeholder's baseSequence closes both sides of the two-document crash
* window: a missing head update can be resumed, while a later request which
* advanced the same setting causes the older placeholder to be superseded.
*/
export async function registerAgentConfiguration(options: {
workspace: Workspace;
controlId: string;
payload: AgentConfigurationPayload;
now?: Date;
}): Promise<AgentConfigurationReceiptState> {
const fingerprint = fingerprintAgentConfiguration(options.payload);
const now = options.now ?? new Date();
const key = configurationKey(options.payload.action);
const sandbox = options.workspace.sandbox;
if (!sandbox.id || !sandbox.generation || !sandbox.nonce) return { status: "stale" };
await ensureLedger(options.workspace, now);
for (;;) {
const existing = await collections.agentConfigurationReceipts.findOne({
workspaceId: options.workspace._id,
controlId: options.controlId,
});
if (existing) {
return resumeReceipt({
workspace: options.workspace,
receipt: existing,
fingerprint,
key,
now,
});
}
const ledger = await collections.agentConfigurationLedgers.findOne({
_id: options.workspace._id,
});
if (!ledger) {
await ensureLedger(options.workspace, now);
continue;
}
const receipt: AgentConfigurationReceipt = {
_id: new ObjectId(),
workspaceId: options.workspace._id,
conversationId: options.workspace.conversationId,
controlId: options.controlId,
fingerprint,
action: options.payload.action,
value: configurationValue(options.payload),
baseSequence: ledger.nextSequence,
status: "pending",
requestedAt: now,
sandboxId: sandbox.id,
sandboxGeneration: sandbox.generation,
sandboxNonce: sandbox.nonce,
createdAt: now,
updatedAt: now,
};
try {
await collections.agentConfigurationReceipts.insertOne(receipt);
} catch (cause) {
if (cause instanceof MongoServerError && cause.code === 11000) continue;
throw cause;
}
return resumeReceipt({
workspace: options.workspace,
receipt,
fingerprint,
key,
now,
});
}
}
export async function completeAgentConfiguration(options: {
workspaceId: Workspace["_id"];
controlId: string;
fingerprint: string;
action: AgentConfigurationAction;
now?: Date;
}): Promise<boolean> {
const now = options.now ?? new Date();
const receipt = await collections.agentConfigurationReceipts.findOne({
workspaceId: options.workspaceId,
controlId: options.controlId,
});
const classified = classifyReceipt(receipt, options.fingerprint);
if (classified.status === "completed") return true;
if (classified.status !== "pending" || classified.receipt.sequence === undefined) return false;
const key = configurationKey(options.action);
const ledger = await collections.agentConfigurationLedgers.findOne({
_id: options.workspaceId,
});
const latest = ledger?.latest[key];
if (
!latest ||
latest.controlId !== options.controlId ||
latest.fingerprint !== options.fingerprint ||
latest.sequence !== classified.receipt.sequence
) {
if (latest && latest.sequence > classified.receipt.sequence) {
return markSuperseded(classified.receipt, options.fingerprint, now);
}
return false;
}
const completed = await collections.agentConfigurationReceipts.updateOne(
{
_id: classified.receipt._id,
fingerprint: options.fingerprint,
status: "pending",
sequence: classified.receipt.sequence,
},
{
$set: { status: "completed", completedAt: now, updatedAt: now },
}
);
if (completed.matchedCount === 1) return true;
const current = await inspectAgentConfiguration({
workspaceId: options.workspaceId,
controlId: options.controlId,
fingerprint: options.fingerprint,
});
return current.status === "completed";
}
async function ensureLedger(workspace: Workspace, now: Date): Promise<void> {
await collections.agentConfigurationLedgers.updateOne(
{ _id: workspace._id },
{
$setOnInsert: {
conversationId: workspace.conversationId,
nextSequence: 0,
latest: {},
createdAt: now,
updatedAt: now,
},
},
{ upsert: true }
);
}
async function resumeReceipt(options: {
workspace: Workspace;
receipt: AgentConfigurationReceipt;
fingerprint: string;
key: AgentConfigurationKey;
now: Date;
}): Promise<AgentConfigurationReceiptState> {
let receipt = options.receipt;
const classified = classifyReceipt(receipt, options.fingerprint);
if (classified.status !== "pending") return classified;
const sandbox = options.workspace.sandbox;
if (
receipt.sandboxId !== sandbox.id ||
receipt.sandboxGeneration !== sandbox.generation ||
receipt.sandboxNonce !== sandbox.nonce
) {
return { status: "stale" };
}
for (;;) {
const ledger = await collections.agentConfigurationLedgers.findOne({
_id: options.workspace._id,
});
if (!ledger) return { status: "stale" };
const latest = ledger.latest[options.key];
if (receipt.sequence !== undefined) {
if (latest && latest.sequence > receipt.sequence) {
await markSuperseded(receipt, options.fingerprint, options.now);
return inspectAgentConfiguration({
workspaceId: options.workspace._id,
controlId: receipt.controlId,
fingerprint: options.fingerprint,
});
}
if (
latest?.controlId === receipt.controlId &&
latest.fingerprint === options.fingerprint &&
latest.sequence === receipt.sequence
) {
return { status: "pending", receipt };
}
return { status: "stale" };
}
if (latest?.controlId === receipt.controlId && latest.fingerprint === options.fingerprint) {
const restored = await collections.agentConfigurationReceipts.findOneAndUpdate(
{ _id: receipt._id, fingerprint: options.fingerprint, sequence: { $exists: false } },
{ $set: { sequence: latest.sequence, updatedAt: options.now } },
{ returnDocument: "after", includeResultMetadata: false }
);
if (restored) return { status: "pending", receipt: restored };
const current = await collections.agentConfigurationReceipts.findOne({ _id: receipt._id });
if (!current) return { status: "stale" };
receipt = current;
continue;
}
if (latest && latest.sequence > receipt.baseSequence) {
await markSuperseded(receipt, options.fingerprint, options.now);
return inspectAgentConfiguration({
workspaceId: options.workspace._id,
controlId: receipt.controlId,
fingerprint: options.fingerprint,
});
}
const sequence = ledger.nextSequence + 1;
const advanced = await collections.agentConfigurationLedgers.updateOne(
{ _id: options.workspace._id, nextSequence: ledger.nextSequence },
{
$inc: { nextSequence: 1 },
$set: {
[`latest.${options.key}`]: {
controlId: receipt.controlId,
fingerprint: options.fingerprint,
sequence,
},
updatedAt: options.now,
},
}
);
if (advanced.matchedCount !== 1) continue;
const assigned = await collections.agentConfigurationReceipts.findOneAndUpdate(
{ _id: receipt._id, fingerprint: options.fingerprint, sequence: { $exists: false } },
{ $set: { sequence, updatedAt: options.now } },
{ returnDocument: "after", includeResultMetadata: false }
);
if (assigned) return { status: "pending", receipt: assigned };
const current = await collections.agentConfigurationReceipts.findOne({ _id: receipt._id });
if (!current) return { status: "stale" };
receipt = current;
}
}
async function markSuperseded(
receipt: AgentConfigurationReceipt,
fingerprint: string,
now: Date
): Promise<boolean> {
const superseded = await collections.agentConfigurationReceipts.updateOne(
{ _id: receipt._id, fingerprint, status: "pending" },
{ $set: { status: "superseded", completedAt: now, updatedAt: now } }
);
if (superseded.matchedCount === 1) return true;
const current = await collections.agentConfigurationReceipts.findOne({ _id: receipt._id });
return current?.fingerprint === fingerprint && current.status !== "pending";
}
function classifyReceipt(
receipt: AgentConfigurationReceipt | null | undefined,
fingerprint: string
): AgentConfigurationReceiptState {
if (!receipt) return { status: "missing" };
if (receipt.fingerprint !== fingerprint) return { status: "conflict" };
return receipt.status === "pending"
? { status: "pending", receipt }
: { status: "completed", receipt };
}
function configurationKey(action: AgentConfigurationAction): AgentConfigurationKey {
switch (action) {
case "set-model":
return "model";
case "set-thinking":
return "thinking";
case "set-policy":
return "policy";
}
}
function configurationValue(payload: AgentConfigurationPayload): string {
switch (payload.action) {
case "set-model":
return payload.model;
case "set-thinking":
return payload.level;
case "set-policy":
return payload.policy;
}
}
|