Open History to see the last commit
1/**
2 * SecretRequests - secrets an agent asks the user for.
3 *
4 * The user's answer goes straight to the server's secret store under a
5 * one-use SecretRef; orchestration only records the request and its status.
6 * A tool that needs the value takes the ref and consumes it, so the value
7 * never reaches the transcript, projections, clients, or model context.
8 *
9 * @module SecretRequests
10 */
11import {
12 CommandId,
13 SecretRef,
14 SecretRequestError,
15 type ProjectId,
16 type SecretRequestAnswerInput,
17 type ThreadId,
18} from "@t3tools/contracts";
19import * as NodeCrypto from "node:crypto";
20
21import * as Clock from "effect/Clock";
22import * as Context from "effect/Context";
23import * as Effect from "effect/Effect";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Schedule from "effect/Schedule";
28import * as Schema from "effect/Schema";
29import * as Semaphore from "effect/Semaphore";
30
31import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
32import * as Metrics from "../observability/Metrics.ts";
33import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
34
35const SECRET_REF_PREFIX = "secret-ref:";
36/** Store name for a ref's value; refs are fixed-length hex, so names stay short and safe. */
37const storeName = (ref: SecretRef) => `secret-request-${ref.slice(SECRET_REF_PREFIX.length)}`;
38const REF_PATTERN = /^secret-ref:[0-9a-f]{32}$/;
39/** A value nobody used within this long is dropped; the agent can ask again. */
40const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;
41const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;
42
43/**
44 * Each request has exactly one ref, derived from where it was asked. Its
45 * length never depends on the thread id, so the store's file names stay
46 * within filesystem limits, and the requesting tool finds it without a
47 * second record. Unguessable without the server's own salt.
48 */
49const refFor = (salt: string, threadId: ThreadId, turnItemId: string) =>
50 SecretRef.make(
51 `${SECRET_REF_PREFIX}${NodeCrypto.createHmac("sha256", salt)
52 .update(`${threadId}\u0000${turnItemId}`)
53 .digest("hex")
54 .slice(0, 32)}`,
55 );
56
57/** A ref's value, the project it was entered for, and when it was saved. */
58const StoredSecret = Schema.fromJsonString(
59 Schema.Struct({ projectId: Schema.String, value: Schema.String, savedAt: Schema.Number }),
60);
61const encodeStored = Schema.encodeEffect(StoredSecret);
62const decodeStored = Schema.decodeUnknownOption(StoredSecret);
63
64export class SecretRequests extends Context.Service<
65 SecretRequests,
66 {
67 /**
68 * Answers a pending request in a thread. Saving stores the value under a
69 * new ref that the requesting tool reads from the request's status.
70 */
71 readonly answer: (input: SecretRequestAnswerInput) => Effect.Effect<void, SecretRequestError>;
72 /** The ref minted when this request was saved, for the tool that asked. */
73 readonly savedRef: (input: {
74 readonly threadId: ThreadId;
75 readonly turnItemId: string;
76 }) => Effect.Effect<Option.Option<SecretRef>>;
77 /**
78 * Reads and deletes a ref's value. Fails for unknown or used refs, and
79 * for refs entered in another project.
80 */
81 readonly consume: (input: {
82 readonly ref: SecretRef;
83 readonly projectId: ProjectId;
84 }) => Effect.Effect<string, SecretRequestError>;
85 }
86>()("t3/secrets/SecretRequests") {}
87
88const make = Effect.gen(function* () {
89 const store = yield* ServerSecretStore.ServerSecretStore;
90 const fileSystem = yield* FileSystem.FileSystem;
91 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
92
93 const salt = Buffer.from(
94 yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),
95 ).toString("hex");
96
97 const answer: SecretRequests["Service"]["answer"] = (input) =>
98 Effect.gen(function* () {
99 yield* Effect.annotateCurrentSpan({
100 "orchestration_v2.thread_id": input.threadId,
101 "secret_request.answer": input.answer.type,
102 });
103 const records = yield* threadManagement
104 .getThreadRecords(input.threadId, ["runs", "turnItems"], {
105 turnItemTypes: ["secret_request"],
106 messageRoles: [],
107 })
108 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })));
109 const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);
110 if (item?.type !== "secret_request" || item.runId === null || item.nodeId === null) {
111 return yield* new SecretRequestError({ reason: "not_found" });
112 }
113 if (item.secretStatus !== "pending") {
114 return yield* new SecretRequestError({ reason: "already_answered" });
115 }
116 // The agent is waiting inside the run that asked; once it has ended,
117 // nobody will ever receive the ref, so a value saved now would be lost.
118 const run = records.runs.find((candidate) => candidate.id === item.runId);
119 if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) {
120 return yield* new SecretRequestError({ reason: "agent_stopped" });
121 }
122 // Store first: the card only says saved once the value is kept. Create,
123 // not set: a second answer racing this one must not replace the value.
124 // A value already there on a card still pending is an earlier save whose
125 // record failed and could not be cleaned up; recording it finishes that save.
126 if (input.answer.type === "save") {
127 const encoded = yield* encodeStored({
128 projectId: records.thread.projectId,
129 value: input.answer.secret,
130 savedAt: yield* Clock.currentTimeMillis,
131 }).pipe(Effect.orDie);
132 yield* store
133 .create(
134 storeName(refFor(salt, input.threadId, item.id)),
135 new TextEncoder().encode(encoded),
136 )
137 .pipe(
138 Effect.catchIf(ServerSecretStore.isSecretAlreadyExistsError, () => Effect.void),
139 Effect.mapError(
140 (error) => new SecretRequestError({ reason: "store_failed", cause: error }),
141 ),
142 );
143 }
144 const secretStatus = input.answer.type === "save" ? "saved" : "declined";
145 yield* threadManagement
146 .dispatch({
147 type: "secret_request.record",
148 commandId: CommandId.make(`secret-request:${item.id}:${secretStatus}`),
149 threadId: input.threadId,
150 runId: item.runId,
151 nodeId: item.nodeId,
152 turnItemId: item.id,
153 label: item.label,
154 reason: item.reason,
155 ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),
156 secretStatus,
157 })
158 .pipe(
159 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
160 // The card still says pending, so the user can save again; the value
161 // stored above would make that retry look already answered.
162 Effect.tapError(() =>
163 input.answer.type === "save"
164 ? removeLogged(storeName(refFor(salt, input.threadId, item.id)))
165 : Effect.void,
166 ),
167 );
168 if (input.answer.type !== "save") return;
169 // A request is answered once: if the agent's wait closed the card between
170 // the checks above and this record, the record changed nothing. Nobody
171 // will receive the ref, so the value is deleted rather than left to expire.
172 const recorded = yield* threadManagement
173 .getThreadRecords(input.threadId, ["turnItems"], {
174 turnItemTypes: ["secret_request"],
175 messageRoles: [],
176 })
177 .pipe(
178 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
179 );
180 const card = recorded.turnItems.find((candidate) => candidate.id === item.id);
181 if (card?.type === "secret_request" && card.secretStatus !== "saved") {
182 yield* removeLogged(storeName(refFor(salt, input.threadId, item.id)));
183 return yield* new SecretRequestError({ reason: "agent_stopped" });
184 }
185 }).pipe(Effect.withSpan("SecretRequests.answer"));
186
187 const savedRef: SecretRequests["Service"]["savedRef"] = (input) =>
188 Effect.gen(function* () {
189 const ref = refFor(salt, input.threadId, input.turnItemId);
190 const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));
191 return Option.map(stored, () => ref);
192 });
193
194 /** Removes a stored value; a failure is logged, since the value is still on disk. */
195 const removeLogged = (name: string) =>
196 store.remove(name).pipe(
197 Effect.as(true),
198 Effect.catch((error) =>
199 Effect.logWarning("Could not delete a secret request value", {
200 errorTag: error._tag,
201 }).pipe(Effect.as(false)),
202 ),
203 );
204
205 // get and remove are separate store calls; one consumer at a time keeps two
206 // concurrent calls from both reading a ref before either deletes it.
207 const consumeLock = yield* Semaphore.make(1);
208 const consume: SecretRequests["Service"]["consume"] = (input) =>
209 consumeRef(input).pipe(
210 consumeLock.withPermits(1),
211 Effect.tap(() => Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "used" })),
212 Effect.tapError(() =>
213 Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "rejected" }),
214 ),
215 Effect.withSpan("SecretRequests.consume"),
216 );
217
218 const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) =>
219 Effect.gen(function* () {
220 if (!REF_PATTERN.test(input.ref))
221 return yield* new SecretRequestError({ reason: "invalid_ref" });
222 const stored = yield* store
223 .get(storeName(input.ref))
224 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));
225 const decoded = Option.flatMap(stored, (bytes) =>
226 decodeStored(new TextDecoder().decode(bytes)),
227 );
228 if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {
229 return yield* new SecretRequestError({ reason: "ref_unavailable" });
230 }
231 if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {
232 // The hourly sweep retries a removal that fails here.
233 yield* removeLogged(storeName(input.ref));
234 return yield* new SecretRequestError({ reason: "ref_expired" });
235 }
236 // One use: the value moves into whatever consumed it. If it cannot be
237 // deleted, it is not handed out, so a ref is never used twice.
238 if (!(yield* removeLogged(storeName(input.ref)))) {
239 return yield* new SecretRequestError({ reason: "consume_failed" });
240 }
241 return decoded.value.value;
242 });
243
244 /**
245 * Drops values nobody used before they expired, so an agent that never
246 * consumed its ref does not leave the user's secret on disk.
247 */
248 const sweepExpired = Effect.gen(function* () {
249 if (store.directory === undefined) return;
250 const now = yield* Clock.currentTimeMillis;
251 const names = (yield* fileSystem.readDirectory(store.directory)).flatMap((file) => {
252 const match = STORE_NAME_PATTERN.exec(file);
253 return match?.[1] === undefined ? [] : [match[1]];
254 });
255 let removed = 0;
256 for (const name of names) {
257 const stored = yield* store.get(name).pipe(Effect.orElseSucceed(Option.none));
258 const decoded = Option.flatMap(stored, (bytes) =>
259 decodeStored(new TextDecoder().decode(bytes)),
260 );
261 if (Option.isSome(decoded) && now - decoded.value.savedAt <= SECRET_REF_TTL_MS) continue;
262 if (yield* removeLogged(name)) removed += 1;
263 }
264 yield* Effect.annotateCurrentSpan({ "secret_request.expired_removed": removed });
265 }).pipe(
266 Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret refs", cause)),
267 Effect.withSpan("SecretRequests.sweepExpired"),
268 );
269 // Once at startup, then hourly; a value lingers at most an hour past expiry.
270 yield* sweepExpired;
271 yield* sweepExpired.pipe(
272 Effect.delay("1 hour"),
273 Effect.repeat(Schedule.spaced("1 hour")),
274 Effect.forkScoped,
275 );
276
277 return SecretRequests.of({ answer, savedRef, consume });
278});
279
280export const layer = Layer.effect(SecretRequests, make);