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