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

SecretRequests.ts

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