File size: 6,583 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
import { collections } from "$lib/server/database";
import type { Workspace, WorkspaceSandbox } from "$lib/types/Workspace";

export interface AgentPromptRecovery {
	sandboxId: string;
	sandboxGeneration: string;
	seededMessage: string;
}

export type DetachedAgentPromptPreparation = "ready" | "busy" | "unrecoverable" | "gone";

/**
 * A prompt assembled for an existing pi session must be replaced with its
 * transcript-seeded form when provisioning returns a different sandbox. The
 * CAS only succeeds before any relay has claimed or dispatched the command.
 */
export async function reseedAgentPromptForReplacement(options: {
	generationId: string;
	conversationId: Workspace["conversationId"];
	workspaceId: Workspace["_id"];
	prompt: { id: string; message: string };
	recovery?: AgentPromptRecovery;
	sandbox: Pick<WorkspaceSandbox, "id" | "generation">;
	producerOwner?: string;
}): Promise<string> {
	const { recovery } = options;
	if (
		!recovery ||
		(options.sandbox.id === recovery.sandboxId &&
			options.sandbox.generation === recovery.sandboxGeneration)
	) {
		return options.prompt.message;
	}
	if (!options.sandbox.id || !options.sandbox.generation) {
		throw new Error("Replacement Agent sandbox has no durable incarnation");
	}

	const reseeded = await collections.generations.updateOne(
		{
			generationId: options.generationId,
			conversationId: options.conversationId,
			workspaceId: options.workspaceId,
			mode: "agent",
			status: "running",
			"agent.prompt.id": options.prompt.id,
			"agent.prompt.message": options.prompt.message,
			"agent.relay": { $exists: false },
			"agent.sandboxId": recovery.sandboxId,
			"agent.sandboxGeneration": recovery.sandboxGeneration,
			...(options.producerOwner
				? {
						"agent.producer.owner": options.producerOwner,
						"agent.producer.expiresAt": { $gt: new Date() },
					}
				: {
						$or: [
							{ "agent.producer": { $exists: false } },
							{ "agent.producer.expiresAt": { $lte: new Date() } },
						],
					}),
		},
		{
			$set: {
				"agent.prompt.message": recovery.seededMessage,
				"agent.sandboxId": options.sandbox.id,
				"agent.sandboxGeneration": options.sandbox.generation,
			},
			$unset: { "agent.prompt.recovery": "" },
		}
	);
	if (reseeded.matchedCount !== 1) {
		const current = await collections.generations.findOne(
			{
				generationId: options.generationId,
				conversationId: options.conversationId,
				workspaceId: options.workspaceId,
				mode: "agent",
				status: "running",
			},
			{
				projection: {
					"agent.prompt.id": 1,
					"agent.prompt.message": 1,
					"agent.sandboxId": 1,
					"agent.sandboxGeneration": 1,
				},
			}
		);
		if (
			current?.agent?.prompt?.id === options.prompt.id &&
			current.agent.prompt.message === recovery.seededMessage &&
			current.agent.sandboxId === options.sandbox.id &&
			current.agent.sandboxGeneration === options.sandbox.generation
		) {
			return recovery.seededMessage;
		}
		throw new Error("Agent prompt changed before replacement context was restored");
	}
	return recovery.seededMessage;
}

/**
 * Recover a replacement-bound prompt after its originating producer died.
 * The durable one-shot fallback means a detached relay never dispatches a
 * resume prompt into the wrong pi-session incarnation.
 */
export async function prepareDetachedAgentPromptForSandbox(options: {
	generationId: string;
	workspaceId: Workspace["_id"];
	sandbox: Pick<WorkspaceSandbox, "id" | "generation">;
	now?: Date;
}): Promise<DetachedAgentPromptPreparation> {
	const { id: sandboxId, generation: sandboxGeneration } = options.sandbox;
	if (!sandboxId || !sandboxGeneration) return "unrecoverable";
	const now = options.now ?? new Date();
	const generation = await collections.generations.findOne(
		{
			generationId: options.generationId,
			workspaceId: options.workspaceId,
			mode: "agent",
		},
		{
			projection: {
				status: 1,
				"agent.sandboxId": 1,
				"agent.sandboxGeneration": 1,
				"agent.prompt": 1,
				"agent.producer": 1,
				"agent.relay": 1,
			},
		}
	);
	if (!generation || generation.status !== "running") return "gone";

	const agent = generation.agent;
	const boundId = agent?.sandboxId;
	const boundGeneration = agent?.sandboxGeneration;
	if (
		(boundId === undefined && boundGeneration === undefined) ||
		(boundId === sandboxId && boundGeneration === sandboxGeneration)
	) {
		return "ready";
	}
	const producer = agent?.producer;
	if (producer && producer.expiresAt > now) return "busy";
	const prompt = agent?.prompt;
	const recovery = prompt?.recovery;
	if (
		!prompt ||
		!recovery ||
		agent?.relay ||
		recovery.sandboxId !== boundId ||
		recovery.sandboxGeneration !== boundGeneration
	) {
		return "unrecoverable";
	}

	const reseeded = await collections.generations.updateOne(
		{
			generationId: options.generationId,
			workspaceId: options.workspaceId,
			mode: "agent",
			status: "running",
			"agent.prompt.id": prompt.id,
			"agent.prompt.message": prompt.message,
			"agent.prompt.recovery.sandboxId": recovery.sandboxId,
			"agent.prompt.recovery.sandboxGeneration": recovery.sandboxGeneration,
			"agent.prompt.recovery.seededMessage": recovery.seededMessage,
			"agent.sandboxId": boundId,
			"agent.sandboxGeneration": boundGeneration,
			"agent.relay": { $exists: false },
			$or: [
				{ "agent.producer": { $exists: false } },
				{ "agent.producer.expiresAt": { $lte: now } },
			],
		},
		{
			$set: {
				"agent.prompt.message": recovery.seededMessage,
				"agent.sandboxId": sandboxId,
				"agent.sandboxGeneration": sandboxGeneration,
			},
			// Completing takeover recovery fences the expired producer. Its delayed
			// heartbeat must not resurrect the pre-dispatch lease between this CAS
			// and detached relay acquisition.
			$unset: { "agent.prompt.recovery": "", "agent.producer": "" },
		}
	);
	if (reseeded.matchedCount === 1) return "ready";

	const current = await collections.generations.findOne(
		{
			generationId: options.generationId,
			workspaceId: options.workspaceId,
			mode: "agent",
		},
		{
			projection: {
				status: 1,
				"agent.sandboxId": 1,
				"agent.sandboxGeneration": 1,
				"agent.prompt.message": 1,
				"agent.producer": 1,
			},
		}
	);
	if (!current || current.status !== "running") return "gone";
	if (
		current.agent?.sandboxId === sandboxId &&
		current.agent?.sandboxGeneration === sandboxGeneration &&
		current.agent?.prompt?.message === recovery.seededMessage
	) {
		return "ready";
	}
	if (current.agent?.producer && current.agent.producer.expiresAt > now) return "busy";
	return "unrecoverable";
}