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.
3import {
4 CommandId,
5 SecretRef,
6 SecretRequestError,
7 type ProjectId,
8 type SecretRequestAnswerInput,
9 type ThreadId,
10} from "@t3tools/contracts";
11// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.
12import * as NodeCrypto from "node:crypto";
13
14import * as Clock from "effect/Clock";
15import * as Context from "effect/Context";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Schedule from "effect/Schedule";
21import * as Schema from "effect/Schema";
22import * as Semaphore from "effect/Semaphore";
23
24import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
25import * as Metrics from "../observability/Metrics.ts";
26import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
27
28const SECRET_REF_PREFIX = "secret-ref:";
29const storeName = (ref: SecretRef) => `secret-request-${ref.slice(SECRET_REF_PREFIX.length)}`;
30const REF_PATTERN = /^secret-ref:[0-9a-f]{32}$/;
31const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;
32const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;
33
34const refFor = (salt: string, threadId: ThreadId, turnItemId: string) =>
35 SecretRef.make(
36 `${SECRET_REF_PREFIX}${NodeCrypto.createHmac("sha256", salt)
37 .update(`${threadId}\u0000${turnItemId}`)
38 .digest("hex")
39 .slice(0, 32)}`,
40 );
41
42const StoredSecret = Schema.fromJsonString(
43 Schema.Struct({ projectId: Schema.String, value: Schema.String, savedAt: Schema.Number }),
44);
45const encodeStored = Schema.encodeEffect(StoredSecret);
46const decodeStored = Schema.decodeUnknownOption(StoredSecret);
47
48export class SecretRequests extends Context.Service<
49 SecretRequests,
50 {
51 readonly answer: (input: SecretRequestAnswerInput) => Effect.Effect<void, SecretRequestError>;
52 readonly savedRef: (input: {
53 readonly threadId: ThreadId;
54 readonly turnItemId: string;
55 }) => Effect.Effect<Option.Option<SecretRef>>;
56 readonly consume: (input: {
57 readonly ref: SecretRef;
58 readonly projectId: ProjectId;
59 }) => Effect.Effect<string, SecretRequestError>;
60 }
61>()("t3/secrets/SecretRequests") {}
62
63const make = Effect.gen(function* () {
64 const store = yield* ServerSecretStore.ServerSecretStore;
65 const fileSystem = yield* FileSystem.FileSystem;
66 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
67
68 const salt = Buffer.from(
69 yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),
70 ).toString("hex");
71
72 const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")(
73 function* (input) {
74 yield* Effect.annotateCurrentSpan({
75 "orchestration_v2.thread_id": input.threadId,
76 "secret_request.answer": input.answer.type,
77 });
78 const records = yield* threadManagement
79 .getThreadRecords(input.threadId, ["runs", "turnItems"], {
80 turnItemTypes: ["secret_request"],
81 messageRoles: [],
82 })
83 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })));
84 const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);
85 if (item?.type !== "secret_request" || item.runId === null || item.nodeId === null) {
86 return yield* new SecretRequestError({ reason: "not_found" });
87 }
88 if (item.secretStatus !== "pending") {
89 return yield* new SecretRequestError({ reason: "already_answered" });
90 }
91 const run = records.runs.find((candidate) => candidate.id === item.runId);
92 if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) {
93 return yield* new SecretRequestError({ reason: "agent_stopped" });
94 }
95 // Create before recording so racing answers cannot overwrite values or show saved before storage.
96 // Existing values on pending cards finish earlier saves whose recording failed.
97 if (input.answer.type === "save") {
98 const encoded = yield* encodeStored({
99 projectId: records.thread.projectId,
100 value: input.answer.secret,
101 savedAt: yield* Clock.currentTimeMillis,
102 }).pipe(Effect.orDie);
103 yield* store
104 .create(
105 storeName(refFor(salt, input.threadId, item.id)),
106 new TextEncoder().encode(encoded),
107 )
108 .pipe(
109 Effect.catchIf(ServerSecretStore.isSecretAlreadyExistsError, () => Effect.void),
110 Effect.mapError(
111 (error) => new SecretRequestError({ reason: "store_failed", cause: error }),
112 ),
113 );
114 }
115 const secretStatus = input.answer.type === "save" ? "saved" : "declined";
116 yield* threadManagement
117 .dispatch({
118 type: "secret_request.record",
119 commandId: CommandId.make(`secret-request:${item.id}:${secretStatus}`),
120 threadId: input.threadId,
121 runId: item.runId,
122 nodeId: item.nodeId,
123 turnItemId: item.id,
124 label: item.label,
125 reason: item.reason,
126 ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),
127 secretStatus,
128 })
129 .pipe(
130 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
131 // Clear failed saves so the pending card can be answered again.
132 Effect.tapError(() =>
133 input.answer.type === "save"
134 ? removeLogged(storeName(refFor(salt, input.threadId, item.id)))
135 : Effect.void,
136 ),
137 );
138 if (input.answer.type !== "save") return;
139 // The wait may have closed the card; delete unrecorded answers because no one receives their refs.
140 const recorded = yield* threadManagement
141 .getThreadRecords(input.threadId, ["turnItems"], {
142 turnItemTypes: ["secret_request"],
143 messageRoles: [],
144 })
145 .pipe(
146 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
147 );
148 const card = recorded.turnItems.find((candidate) => candidate.id === item.id);
149 if (card?.type === "secret_request" && card.secretStatus !== "saved") {
150 yield* removeLogged(storeName(refFor(salt, input.threadId, item.id)));
151 return yield* new SecretRequestError({ reason: "agent_stopped" });
152 }
153 },
154 );
155
156 const savedRef: SecretRequests["Service"]["savedRef"] = Effect.fn("SecretRequests.savedRef")(
157 function* (input) {
158 const ref = refFor(salt, input.threadId, input.turnItemId);
159 const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));
160 return Option.map(stored, () => ref);
161 },
162 );
163
164 const removeLogged = (name: string) =>
165 store.remove(name).pipe(
166 Effect.as(true),
167 Effect.catch((error) =>
168 Effect.logWarning("Could not delete a secret request value", {
169 errorTag: error._tag,
170 }).pipe(Effect.as(false)),
171 ),
172 );
173
174 // Serialize get/remove so concurrent consumers cannot read the same one-use ref.
175 const consumeLock = yield* Semaphore.make(1);
176 const consume: SecretRequests["Service"]["consume"] = (input) =>
177 consumeRef(input).pipe(
178 consumeLock.withPermits(1),
179 Effect.tap(() => Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "used" })),
180 Effect.tapError(() =>
181 Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "rejected" }),
182 ),
183 Effect.withSpan("SecretRequests.consume"),
184 );
185
186 const consumeRef = Effect.fn("SecretRequests.consumeRef")(function* (input: {
187 readonly ref: SecretRef;
188 readonly projectId: ProjectId;
189 }) {
190 if (!REF_PATTERN.test(input.ref))
191 return yield* new SecretRequestError({ reason: "invalid_ref" });
192 const stored = yield* store
193 .get(storeName(input.ref))
194 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));
195 const decoded = Option.flatMap(stored, (bytes) =>
196 decodeStored(new TextDecoder().decode(bytes)),
197 );
198 if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {
199 return yield* new SecretRequestError({ reason: "ref_unavailable" });
200 }
201 if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {
202 yield* removeLogged(storeName(input.ref));
203 return yield* new SecretRequestError({ reason: "ref_expired" });
204 }
205 // One use: the value moves into whatever consumed it. If it cannot be
206 // deleted, it is not handed out, so a ref is never used twice.
207 if (!(yield* removeLogged(storeName(input.ref)))) {
208 return yield* new SecretRequestError({ reason: "consume_failed" });
209 }
210 return decoded.value.value;
211 });
212
213 const sweepExpired = Effect.gen(function* () {
214 if (store.directory === undefined) return;
215 const now = yield* Clock.currentTimeMillis;
216 const names = (yield* fileSystem.readDirectory(store.directory)).flatMap((file) => {
217 const match = STORE_NAME_PATTERN.exec(file);
218 return match?.[1] === undefined ? [] : [match[1]];
219 });
220 let removed = 0;
221 for (const name of names) {
222 const stored = yield* store.get(name).pipe(Effect.orElseSucceed(Option.none));
223 const decoded = Option.flatMap(stored, (bytes) =>
224 decodeStored(new TextDecoder().decode(bytes)),
225 );
226 if (Option.isSome(decoded) && now - decoded.value.savedAt <= SECRET_REF_TTL_MS) continue;
227 if (yield* removeLogged(name)) removed += 1;
228 }
229 yield* Effect.annotateCurrentSpan({ "secret_request.expired_removed": removed });
230 }).pipe(
231 Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret refs", cause)),
232 Effect.withSpan("SecretRequests.sweepExpired"),
233 );
234 yield* sweepExpired;
235 yield* sweepExpired.pipe(
236 Effect.delay("1 hour"),
237 Effect.repeat(Schedule.spaced("1 hour")),
238 Effect.forkScoped,
239 );
240
241 return SecretRequests.of({ answer, savedRef, consume });
242});
243
244export const layer = Layer.effect(SecretRequests, make);