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