Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SecretRequests.ts

370 lines16.0 KB

1// Answers stay in the secret store behind one-use refs; orchestration records only request status.
2// Consuming tools keep values out of transcripts, projections, clients and model context.
3// A `file` request instead moves its value to an owner-only file for the agent's own shell.
4// A secret the user pasted in chat goes straight to such a file, with no card.
5import {
6 CommandId,
7 SecretRef,
8 SecretRequestError,
9 type ProjectId,
10 type SecretRequestAnswerInput,
11 type ThreadId,
12} from "@t3tools/contracts";
13​
14import * as Clock from "effect/Clock";
15import * as Context from "effect/Context";
16import * as Mac from "effect/crypto/Mac";
17import * as Effect from "effect/Effect";
18import * as Hex from "effect/encoding/Hex";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Path from "effect/Path";
23import * as Schedule from "effect/Schedule";
24import * as Schema from "effect/Schema";
25import * as Semaphore from "effect/Semaphore";
26​
27import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
28import * as Metrics from "../observability/Metrics.ts";
29import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
30​
31const SECRET_REF_PREFIX = "secret-ref:";
32const storeName = (ref: SecretRef) => `secret-request-${ref.slice(SECRET_REF_PREFIX.length)}`;
33const REF_PATTERN = /^secret-ref:[0-9a-f]{32}$/;
34const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;
35const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;
36const FILE_NAME_PATTERN = /^[0-9a-f]{32}(\.partial)?$/;
37​
38const StoredSecret = Schema.fromJsonString(
39 Schema.Struct({ projectId: Schema.String, value: Schema.String, savedAt: Schema.Number }),
40);
41const encodeStored = Schema.encodeEffect(StoredSecret);
42const decodeStored = Schema.decodeUnknownOption(StoredSecret);
43​
44export class SecretRequests extends Context.Service<
45 SecretRequests,
46 {
47 readonly answer: (input: SecretRequestAnswerInput) => Effect.Effect<void, SecretRequestError>;
48 readonly savedRef: (input: {
49 readonly threadId: ThreadId;
50 readonly turnItemId: string;
51 }) => Effect.Effect<Option.Option<SecretRef>>;
52 readonly consume: (input: {
53 readonly ref: SecretRef;
54 readonly projectId: ProjectId;
55 }) => Effect.Effect<string, SecretRequestError>;
56 /** Moves a saved `file` request's value to an owner-only file and returns its path. */
57 readonly saveToFile: (input: {
58 readonly threadId: ThreadId;
59 readonly turnItemId: string;
60 }) => Effect.Effect<string, SecretRequestError>;
61 /** Writes a secret the user pasted in chat to an owner-only file and returns its path. */
62 readonly savePasted: (input: {
63 readonly threadId: ThreadId;
64 /** The provider session's namespace, so two sessions' keys never share a file. */
65 readonly requestNamespace: string;
66 readonly requestKey: string;
67 readonly value: string;
68 }) => Effect.Effect<string, SecretRequestError>;
69 }
70>()("t3/secrets/SecretRequests") {}
71​
72const make = Effect.gen(function* () {
73 const store = yield* ServerSecretStore.ServerSecretStore;
74 const fileSystem = yield* FileSystem.FileSystem;
75 const path = yield* Path.Path;
76 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
77 // Beside the store's own files so the same owner-only directory and cleanup rules apply.
78 const filesDir = store.directory === undefined ? undefined : path.join(store.directory, "files");
79​
80 const mac = yield* Mac.Mac;
81 // Keyed by the salt's hex text, as refs saved by earlier versions were.
82 const refKey = yield* Mac.key(
83 Mac.hmacSha256,
84 new TextEncoder().encode(
85 Hex.encode(yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie)),
86 ),
87 ).pipe(Effect.orDie);
88 const refFor = (threadId: ThreadId, turnItemId: string) =>
89 mac.sign(refKey, new TextEncoder().encode(`${threadId}\u0000${turnItemId}`)).pipe(
90 Effect.orDie,
91 Effect.map((tag) => SecretRef.make(`${SECRET_REF_PREFIX}${Hex.encode(tag).slice(0, 32)}`)),
92 );
93​
94 const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")(
95 function* (input) {
96 yield* Effect.annotateCurrentSpan({
97 "orchestration_v2.thread_id": input.threadId,
98 "secret_request.answer": input.answer.type,
99 });
100 const records = yield* threadManagement
101 .getThreadRecords(input.threadId, ["runs", "turnItems"], {
102 turnItemTypes: ["secret_request"],
103 messageRoles: [],
104 })
105 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })));
106 const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);
107 if (item?.type !== "secret_request" || item.runId === null || item.nodeId === null) {
108 return yield* new SecretRequestError({ reason: "not_found" });
109 }
110 if (item.secretStatus !== "pending") {
111 return yield* new SecretRequestError({ reason: "already_answered" });
112 }
113 const run = records.runs.find((candidate) => candidate.id === item.runId);
114 if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) {
115 return yield* new SecretRequestError({ reason: "agent_stopped" });
116 }
117 // Create before recording so racing answers cannot overwrite values or show saved before storage.
118 // Existing values on pending cards finish earlier saves whose recording failed.
119 if (input.answer.type === "save") {
120 const encoded = yield* encodeStored({
121 projectId: records.thread.projectId,
122 value: input.answer.secret,
123 savedAt: yield* Clock.currentTimeMillis,
124 }).pipe(Effect.orDie);
125 yield* store
126 .create(
127 storeName(yield* refFor(input.threadId, item.id)),
128 new TextEncoder().encode(encoded),
129 )
130 .pipe(
131 Effect.catchIf(ServerSecretStore.isSecretAlreadyExistsError, () => Effect.void),
132 Effect.mapError(
133 (error) => new SecretRequestError({ reason: "store_failed", cause: error }),
134 ),
135 );
136 }
137 const secretStatus = input.answer.type === "save" ? "saved" : "declined";
138 yield* threadManagement
139 .dispatch({
140 type: "secret_request.record",
141 commandId: CommandId.make(`secret-request:${item.id}:${secretStatus}`),
142 threadId: input.threadId,
143 runId: item.runId,
144 nodeId: item.nodeId,
145 turnItemId: item.id,
146 label: item.label,
147 reason: item.reason,
148 ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),
149 ...(item.delivery === undefined ? {} : { delivery: item.delivery }),
150 secretStatus,
151 })
152 .pipe(
153 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
154 // Clear failed saves so the pending card can be answered again.
155 Effect.tapError(() =>
156 input.answer.type === "save"
157 ? refFor(input.threadId, item.id).pipe(
158 Effect.flatMap((ref) => removeLogged(storeName(ref))),
159 )
160 : Effect.void,
161 ),
162 );
163 if (input.answer.type !== "save") return;
164 // The wait may have closed the card; delete unrecorded answers because no one receives their refs.
165 const recorded = yield* threadManagement
166 .getThreadRecords(input.threadId, ["turnItems"], {
167 turnItemTypes: ["secret_request"],
168 messageRoles: [],
169 })
170 .pipe(
171 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
172 );
173 const card = recorded.turnItems.find((candidate) => candidate.id === item.id);
174 if (card?.type === "secret_request" && card.secretStatus !== "saved") {
175 yield* removeLogged(storeName(yield* refFor(input.threadId, item.id)));
176 return yield* new SecretRequestError({ reason: "agent_stopped" });
177 }
178 },
179 );
180​
181 const savedRef: SecretRequests["Service"]["savedRef"] = Effect.fn("SecretRequests.savedRef")(
182 function* (input) {
183 const ref = yield* refFor(input.threadId, input.turnItemId);
184 const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));
185 return Option.map(stored, () => ref);
186 },
187 );
188​
189 const removeLogged = (name: string) =>
190 store.remove(name).pipe(
191 Effect.as(true),
192 Effect.catch((error) =>
193 Effect.logWarning("Could not delete a secret request value", {
194 errorTag: error._tag,
195 }).pipe(Effect.as(false)),
196 ),
197 );
198​
199 // Serialize get/remove so concurrent consumers cannot read the same one-use ref.
200 const consumeLock = yield* Semaphore.make(1);
201 const consume: SecretRequests["Service"]["consume"] = (input) =>
202 consumeRef(input).pipe(
203 consumeLock.withPermits(1),
204 Effect.tap(() => Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "used" })),
205 Effect.tapError(() =>
206 Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "rejected" }),
207 ),
208 Effect.withSpan("SecretRequests.consume"),
209 );
210​
211 /** A live ref's value, left in the store. */
212 const readRef = Effect.fn("SecretRequests.readRef")(function* (input: {
213 readonly ref: SecretRef;
214 readonly projectId: ProjectId;
215 }) {
216 if (!REF_PATTERN.test(input.ref))
217 return yield* new SecretRequestError({ reason: "invalid_ref" });
218 const stored = yield* store
219 .get(storeName(input.ref))
220 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));
221 const decoded = Option.flatMap(stored, (bytes) =>
222 decodeStored(new TextDecoder().decode(bytes)),
223 );
224 if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {
225 return yield* new SecretRequestError({ reason: "ref_unavailable" });
226 }
227 if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {
228 yield* removeLogged(storeName(input.ref));
229 return yield* new SecretRequestError({ reason: "ref_expired" });
230 }
231 return decoded.value.value;
232 });
233​
234 const consumeRef = Effect.fn("SecretRequests.consumeRef")(function* (input: {
235 readonly ref: SecretRef;
236 readonly projectId: ProjectId;
237 }) {
238 const value = yield* readRef(input);
239 // One use: the value moves into whatever consumed it. If it cannot be
240 // deleted, it is not handed out, so a ref is never used twice.
241 if (!(yield* removeLogged(storeName(input.ref)))) {
242 return yield* new SecretRequestError({ reason: "consume_failed" });
243 }
244 return value;
245 });
246​
247 const writeSecretFile = (dir: string, file: string, value: string) => {
248 const partial = `${file}.partial`;
249 return fileSystem.makeDirectory(dir, { recursive: true, mode: 0o700 }).pipe(
250 Effect.andThen(fileSystem.chmod(dir, 0o700)),
251 Effect.andThen(fileSystem.remove(partial, { force: true })),
252 // `wx` never follows or replaces an existing path.
253 Effect.andThen(
254 fileSystem.writeFile(partial, new TextEncoder().encode(value), {
255 flag: "wx",
256 mode: 0o600,
257 }),
258 ),
259 Effect.andThen(fileSystem.rename(partial, file)),
260 Effect.mapError((cause) => new SecretRequestError({ reason: "store_failed", cause })),
261 );
262 };
263​
264 const saveToFile: SecretRequests["Service"]["saveToFile"] = Effect.fn(
265 "SecretRequests.saveToFile",
266 )(function* (input) {
267 const records = yield* threadManagement
268 .getThreadRecords(input.threadId, ["turnItems"], {
269 turnItemTypes: ["secret_request"],
270 messageRoles: [],
271 })
272 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })));
273 const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);
274 // Only a card that told the user the agent's commands can read the value may write it out.
275 if (
276 item?.type !== "secret_request" ||
277 item.secretStatus !== "saved" ||
278 item.delivery !== "file"
279 ) {
280 return yield* new SecretRequestError({ reason: "not_a_file_request" });
281 }
282 if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });
283 const ref = yield* refFor(input.threadId, item.id);
284 const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length));
285 return yield* Effect.gen(function* () {
286 // One use: the file counts as delivered only once the stored copy is gone. A retry with the
287 // same clientRequestId gets the file the first call wrote and finishes that removal.
288 const removeStored = removeLogged(storeName(ref)).pipe(
289 Effect.flatMap((removed) =>
290 removed ? Effect.succeed(file) : new SecretRequestError({ reason: "consume_failed" }),
291 ),
292 );
293 if (yield* fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))) {
294 return yield* removeStored;
295 }
296 // The stored value goes only after the file is complete, so a failed write can retry.
297 const value = yield* readRef({ ref, projectId: records.thread.projectId });
298 yield* writeSecretFile(filesDir, file, value);
299 return yield* removeStored;
300 }).pipe(consumeLock.withPermits(1));
301 });
302​
303 const savePasted: SecretRequests["Service"]["savePasted"] = Effect.fn(
304 "SecretRequests.savePasted",
305 )(function* (input) {
306 if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" });
307 const ref = yield* refFor(
308 input.threadId,
309 `pasted\u0000${input.requestNamespace}\u0000${input.requestKey}`,
310 );
311 const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length));
312 // A retry with the same clientRequestId gets the file the first call wrote, unchanged, so a
313 // command already holding that path never reads another value.
314 return yield* Effect.gen(function* () {
315 if (yield* fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))) return file;
316 yield* writeSecretFile(filesDir, file, input.value);
317 return file;
318 }).pipe(consumeLock.withPermits(1));
319 });
320​
321 const sweepExpired = Effect.gen(function* () {
322 if (store.directory === undefined) return;
323 const now = yield* Clock.currentTimeMillis;
324 const names = (yield* fileSystem.readDirectory(store.directory)).flatMap((file) => {
325 const match = STORE_NAME_PATTERN.exec(file);
326 return match?.[1] === undefined ? [] : [match[1]];
327 });
328 let removed = 0;
329 for (const name of names) {
330 const stored = yield* store.get(name).pipe(Effect.orElseSucceed(Option.none));
331 const decoded = Option.flatMap(stored, (bytes) =>
332 decodeStored(new TextDecoder().decode(bytes)),
333 );
334 if (Option.isSome(decoded) && now - decoded.value.savedAt <= SECRET_REF_TTL_MS) continue;
335 if (yield* removeLogged(name)) removed += 1;
336 }
337 yield* Effect.annotateCurrentSpan({ "secret_request.expired_removed": removed });
338 }).pipe(
339 Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret refs", cause)),
340 Effect.withSpan("SecretRequests.sweepExpired"),
341 );
342 const sweepExpiredFiles = Effect.gen(function* () {
343 if (filesDir === undefined || !(yield* fileSystem.exists(filesDir))) return;
344 const now = yield* Clock.currentTimeMillis;
345 let removed = 0;
346 for (const name of yield* fileSystem.readDirectory(filesDir)) {
347 if (!FILE_NAME_PATTERN.test(name)) continue;
348 const file = path.join(filesDir, name);
349 const { mtime } = yield* fileSystem.stat(file);
350 if (Option.exists(mtime, (time) => now - time.getTime() <= SECRET_REF_TTL_MS)) continue;
351 yield* fileSystem.remove(file);
352 removed += 1;
353 }
354 yield* Effect.annotateCurrentSpan({ "secret_request.expired_files_removed": removed });
355 }).pipe(
356 Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret files", cause)),
357 Effect.withSpan("SecretRequests.sweepExpiredFiles"),
358 );
359 const sweep = Effect.andThen(sweepExpired, sweepExpiredFiles);
360 yield* sweep;
361 yield* sweep.pipe(
362 Effect.delay("1 hour"),
363 Effect.repeat(Schedule.spaced("1 hour")),
364 Effect.forkScoped,
365 );
366​
367 return SecretRequests.of({ answer, savedRef, consume, saveToFile, savePasted });
368});
369​
370export const layer = Layer.effect(SecretRequests, make);