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

SecretRequests.ts

250 lines10.6 KB

1/**
2 * The user's answer goes straight to the server's secret store under a
3 * one-use SecretRef; orchestration only records the request and its status.
4 * A tool that needs the value takes the ref and consumes it, so the value
5 * never reaches the transcript, projections, clients, or model context.
6 */
7import {
8 CommandId,
9 SecretRef,
10 SecretRequestError,
11 type ProjectId,
12 type SecretRequestAnswerInput,
13 type ThreadId,
14} from "@t3tools/contracts";
15// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac.
16import * as NodeCrypto from "node:crypto";
17​
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Schedule from "effect/Schedule";
25import * as Schema from "effect/Schema";
26import * as Semaphore from "effect/Semaphore";
27​
28import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
29import * as Metrics from "../observability/Metrics.ts";
30import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
31​
32const SECRET_REF_PREFIX = "secret-ref:";
33const storeName = (ref: SecretRef) => `secret-request-${ref.slice(SECRET_REF_PREFIX.length)}`;
34const REF_PATTERN = /^secret-ref:[0-9a-f]{32}$/;
35const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000;
36const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/;
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 }
65>()("t3/secrets/SecretRequests") {}
66​
67const make = Effect.gen(function* () {
68 const store = yield* ServerSecretStore.ServerSecretStore;
69 const fileSystem = yield* FileSystem.FileSystem;
70 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
71​
72 const salt = Buffer.from(
73 yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),
74 ).toString("hex");
75​
76 const answer: SecretRequests["Service"]["answer"] = (input) =>
77 Effect.gen(function* () {
78 yield* Effect.annotateCurrentSpan({
79 "orchestration_v2.thread_id": input.threadId,
80 "secret_request.answer": input.answer.type,
81 });
82 const records = yield* threadManagement
83 .getThreadRecords(input.threadId, ["runs", "turnItems"], {
84 turnItemTypes: ["secret_request"],
85 messageRoles: [],
86 })
87 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause })));
88 const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId);
89 if (item?.type !== "secret_request" || item.runId === null || item.nodeId === null) {
90 return yield* new SecretRequestError({ reason: "not_found" });
91 }
92 if (item.secretStatus !== "pending") {
93 return yield* new SecretRequestError({ reason: "already_answered" });
94 }
95 const run = records.runs.find((candidate) => candidate.id === item.runId);
96 if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) {
97 return yield* new SecretRequestError({ reason: "agent_stopped" });
98 }
99 // Store first: the card only says saved once the value is kept. Create,
100 // not set: a second answer racing this one must not replace the value.
101 // A value already there on a card still pending is an earlier save whose
102 // record failed and could not be cleaned up; recording it finishes that save.
103 if (input.answer.type === "save") {
104 const encoded = yield* encodeStored({
105 projectId: records.thread.projectId,
106 value: input.answer.secret,
107 savedAt: yield* Clock.currentTimeMillis,
108 }).pipe(Effect.orDie);
109 yield* store
110 .create(
111 storeName(refFor(salt, input.threadId, item.id)),
112 new TextEncoder().encode(encoded),
113 )
114 .pipe(
115 Effect.catchIf(ServerSecretStore.isSecretAlreadyExistsError, () => Effect.void),
116 Effect.mapError(
117 (error) => new SecretRequestError({ reason: "store_failed", cause: error }),
118 ),
119 );
120 }
121 const secretStatus = input.answer.type === "save" ? "saved" : "declined";
122 yield* threadManagement
123 .dispatch({
124 type: "secret_request.record",
125 commandId: CommandId.make(`secret-request:${item.id}:${secretStatus}`),
126 threadId: input.threadId,
127 runId: item.runId,
128 nodeId: item.nodeId,
129 turnItemId: item.id,
130 label: item.label,
131 reason: item.reason,
132 ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }),
133 secretStatus,
134 })
135 .pipe(
136 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
137 // The card still says pending, so the user can save again; the value
138 // stored above would make that retry look already answered.
139 Effect.tapError(() =>
140 input.answer.type === "save"
141 ? removeLogged(storeName(refFor(salt, input.threadId, item.id)))
142 : Effect.void,
143 ),
144 );
145 if (input.answer.type !== "save") return;
146 // A request is answered once: if the agent's wait closed the card between
147 // the checks above and this record, the record changed nothing. Nobody
148 // will receive the ref, so the value is deleted rather than left to expire.
149 const recorded = yield* threadManagement
150 .getThreadRecords(input.threadId, ["turnItems"], {
151 turnItemTypes: ["secret_request"],
152 messageRoles: [],
153 })
154 .pipe(
155 Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })),
156 );
157 const card = recorded.turnItems.find((candidate) => candidate.id === item.id);
158 if (card?.type === "secret_request" && card.secretStatus !== "saved") {
159 yield* removeLogged(storeName(refFor(salt, input.threadId, item.id)));
160 return yield* new SecretRequestError({ reason: "agent_stopped" });
161 }
162 }).pipe(Effect.withSpan("SecretRequests.answer"));
163​
164 const savedRef: SecretRequests["Service"]["savedRef"] = (input) =>
165 Effect.gen(function* () {
166 const ref = refFor(salt, input.threadId, input.turnItemId);
167 const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));
168 return Option.map(stored, () => ref);
169 });
170​
171 const removeLogged = (name: string) =>
172 store.remove(name).pipe(
173 Effect.as(true),
174 Effect.catch((error) =>
175 Effect.logWarning("Could not delete a secret request value", {
176 errorTag: error._tag,
177 }).pipe(Effect.as(false)),
178 ),
179 );
180​
181 // get and remove are separate store calls; one consumer at a time keeps two
182 // concurrent calls from both reading a ref before either deletes it.
183 const consumeLock = yield* Semaphore.make(1);
184 const consume: SecretRequests["Service"]["consume"] = (input) =>
185 consumeRef(input).pipe(
186 consumeLock.withPermits(1),
187 Effect.tap(() => Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "used" })),
188 Effect.tapError(() =>
189 Metrics.increment(Metrics.secretRefsConsumedTotal, { result: "rejected" }),
190 ),
191 Effect.withSpan("SecretRequests.consume"),
192 );
193​
194 const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) =>
195 Effect.gen(function* () {
196 if (!REF_PATTERN.test(input.ref))
197 return yield* new SecretRequestError({ reason: "invalid_ref" });
198 const stored = yield* store
199 .get(storeName(input.ref))
200 .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));
201 const decoded = Option.flatMap(stored, (bytes) =>
202 decodeStored(new TextDecoder().decode(bytes)),
203 );
204 if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {
205 return yield* new SecretRequestError({ reason: "ref_unavailable" });
206 }
207 if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {
208 yield* removeLogged(storeName(input.ref));
209 return yield* new SecretRequestError({ reason: "ref_expired" });
210 }
211 // One use: the value moves into whatever consumed it. If it cannot be
212 // deleted, it is not handed out, so a ref is never used twice.
213 if (!(yield* removeLogged(storeName(input.ref)))) {
214 return yield* new SecretRequestError({ reason: "consume_failed" });
215 }
216 return decoded.value.value;
217 });
218​
219 const sweepExpired = Effect.gen(function* () {
220 if (store.directory === undefined) return;
221 const now = yield* Clock.currentTimeMillis;
222 const names = (yield* fileSystem.readDirectory(store.directory)).flatMap((file) => {
223 const match = STORE_NAME_PATTERN.exec(file);
224 return match?.[1] === undefined ? [] : [match[1]];
225 });
226 let removed = 0;
227 for (const name of names) {
228 const stored = yield* store.get(name).pipe(Effect.orElseSucceed(Option.none));
229 const decoded = Option.flatMap(stored, (bytes) =>
230 decodeStored(new TextDecoder().decode(bytes)),
231 );
232 if (Option.isSome(decoded) && now - decoded.value.savedAt <= SECRET_REF_TTL_MS) continue;
233 if (yield* removeLogged(name)) removed += 1;
234 }
235 yield* Effect.annotateCurrentSpan({ "secret_request.expired_removed": removed });
236 }).pipe(
237 Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret refs", cause)),
238 Effect.withSpan("SecretRequests.sweepExpired"),
239 );
240 yield* sweepExpired;
241 yield* sweepExpired.pipe(
242 Effect.delay("1 hour"),
243 Effect.repeat(Schedule.spaced("1 hour")),
244 Effect.forkScoped,
245 );
246​
247 return SecretRequests.of({ answer, savedRef, consume });
248});
249​
250export const layer = Layer.effect(SecretRequests, make);