Open History to see the last commit
1// Stores agent feedback reports and shows the cards of requested ones. A card is answered from
2// what it recorded, so it stays answerable after its turn ends and after a restart.
3import {
4 type AgentFeedbackAnswerInput,
5 type AgentFeedbackMode,
6 type AgentFeedbackPreview,
7 type AgentFeedbackRequestStatus,
8 AgentFeedbackRequestError,
9 type AgentFeedbackTrace,
10 CommandId,
11 type NodeId,
12 type RunId,
13 type ThreadId,
14 TurnItemId,
15} from "@t3tools/contracts";
16import * as Context from "effect/Context";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Schema from "effect/Schema";
21import * as Semaphore from "effect/Semaphore";
22import * as SqlClient from "effect/sql/SqlClient";
23
24import * as Threads from "../orchestration-v2/ThreadManagementService.ts";
25import * as Providers from "../provider/ProviderRegistry.ts";
26import * as Settings from "../serverSettings.ts";
27import * as Analytics from "../telemetry/AnalyticsService.ts";
28import { type ProviderDimensions, providerDimensions } from "../telemetry/ProviderDimensions.ts";
29import {
30 FeedbackLimitError,
31 FeedbackNotRequestedError,
32 MAX_REPORTS_OUTSIDE_TURNS_PER_HOUR,
33 MAX_REPORTS_PER_TURN,
34 REPEAT_REPORT_WINDOW_HOURS,
35 FeedbackOffError,
36 type FeedbackReport,
37 FeedbackStorageError,
38 FeedbackTrace,
39 type FeedbackSource,
40} from "./FeedbackReport.ts";
41
42const CARD_PREFIX = "turn-item:feedback-request:";
43
44/** A requested report waiting for the user's answer, shown in its run. */
45export interface FeedbackCard {
46 readonly reportId: string;
47 readonly threadId: ThreadId;
48 readonly runId: RunId;
49 readonly nodeId: NodeId;
50 readonly preview: AgentFeedbackPreview;
51 readonly conversationTrace: AgentFeedbackTrace | null;
52}
53
54export interface UnpromptedReport {
55 readonly id: string;
56 readonly preview: AgentFeedbackPreview;
57 readonly source: FeedbackSource;
58 readonly threadId: ThreadId | null;
59 readonly runId: RunId | null;
60 /** The closed code of the subject tool's latest failed call in this thread, when it has one. */
61 readonly errorCode: string | undefined;
62 readonly dimensions: Partial<ProviderDimensions>;
63}
64
65export class FeedbackStore extends Context.Service<
66 FeedbackStore,
67 {
68 /** Stores and sends a report nobody has to approve. */
69 readonly store: (
70 report: UnpromptedReport,
71 ) => Effect.Effect<
72 FeedbackReport,
73 FeedbackLimitError | FeedbackOffError | FeedbackNotRequestedError | FeedbackStorageError
74 >;
75 /** Shows a requested report's card. Nothing is stored or sent until the user answers it. */
76 readonly showCard: (
77 card: FeedbackCard,
78 ) => Effect.Effect<void, FeedbackLimitError | FeedbackStorageError>;
79 /** Send stores and sends what the card shows; either answer closes it, once. */
80 readonly answer: (
81 input: AgentFeedbackAnswerInput,
82 ) => Effect.Effect<void, AgentFeedbackRequestError>;
83 }
84>()("t3/feedback/FeedbackStore") {}
85
86const storageError = (cause: unknown) => new FeedbackStorageError({ cause });
87const TraceJson = Schema.NullOr(Schema.fromJsonString(FeedbackTrace));
88const encodeTrace = Schema.encodeEffect(TraceJson);
89const decodeTrace = Schema.decodeUnknownEffect(TraceJson);
90
91/** The mode rule: nothing while Off, and only approved reports while When I ask. */
92export const allowedBy = (
93 mode: AgentFeedbackMode,
94 userRequested: boolean,
95 source: FeedbackSource,
96): Effect.Effect<void, FeedbackOffError | FeedbackNotRequestedError> =>
97 mode === "off"
98 ? Effect.fail(new FeedbackOffError({}))
99 : mode === "on-request" && !userRequested
100 ? Effect.fail(new FeedbackNotRequestedError({ source }))
101 : Effect.void;
102
103const make = Effect.gen(function* () {
104 const sql = yield* SqlClient.SqlClient;
105 const threads = yield* Threads.ThreadManagementService;
106 const settings = yield* Settings.ServerSettingsService;
107 const analytics = yield* Analytics.AnalyticsService;
108 const providers = yield* Providers.ProviderRegistry;
109 // Serializes the limit checks with their writes. Held only after any settings wait, so an answer
110 // stalled on the settings lock never holds up a card or an unprompted report.
111 const lock = yield* Semaphore.make(1);
112 // Serializes answers, each from its claim through settling its card. Order: answers, settings,
113 // SQL. Nothing that holds the settings lock or `lock` takes this one.
114 const answering = yield* Semaphore.make(1);
115
116 const record = (
117 card: Omit<FeedbackCard, "conversationTrace">,
118 feedbackStatus: AgentFeedbackRequestStatus,
119 conversationTrace?: AgentFeedbackTrace,
120 ) =>
121 threads
122 .dispatch({
123 type: "feedback_request.record",
124 commandId: CommandId.make(`feedback-request:${card.reportId}:${feedbackStatus}`),
125 threadId: card.threadId,
126 runId: card.runId,
127 nodeId: card.nodeId,
128 turnItemId: TurnItemId.make(`${CARD_PREFIX}${card.reportId}`),
129 preview: card.preview,
130 ...(conversationTrace === undefined ? {} : { conversationTrace }),
131 feedbackStatus,
132 })
133 .pipe(Effect.mapError(storageError));
134
135 /** The unprompted report the next one would pass the limit of, or undefined. */
136 const overLimit = Effect.fn("FeedbackStore.overLimit")(function* (runId: RunId | null) {
137 if (runId !== null) {
138 const [row] = yield* sql<{ readonly count: number }>`
139 SELECT COUNT(*) AS count FROM agent_feedback
140 WHERE run_id = ${runId} AND user_requested = 0`;
141 return (row?.count ?? 0) >= MAX_REPORTS_PER_TURN ? ("turn" as const) : undefined;
142 }
143 const since = DateTime.formatIso(DateTime.subtract(yield* DateTime.now, { hours: 1 }));
144 const [row] = yield* sql<{ readonly count: number }>`
145 SELECT COUNT(*) AS count FROM agent_feedback
146 WHERE run_id IS NULL AND created_at > ${since}`;
147 return (row?.count ?? 0) >= MAX_REPORTS_OUTSIDE_TURNS_PER_HOUR ? ("hour" as const) : undefined;
148 });
149
150 /** Whether this machine already sent an unprompted report of this problem in the window. */
151 const alreadySent = Effect.fn("FeedbackStore.alreadySent")(function* (
152 subject: string,
153 errorCode: string | null,
154 ) {
155 const since = DateTime.formatIso(
156 DateTime.subtract(yield* DateTime.now, { hours: REPEAT_REPORT_WINDOW_HOURS }),
157 );
158 const [row] = yield* sql<{ readonly found: number }>`
159 SELECT 1 AS found FROM agent_feedback
160 WHERE subject = ${subject} AND error_code IS ${errorCode}
161 AND user_requested = 0 AND sent = 1 AND created_at > ${since}
162 LIMIT 1`;
163 return row !== undefined;
164 });
165
166 /**
167 * Inserts a report under the settings lock, so a switch to Off is wholly before or after it: a
168 * read cannot return the mode an update is replacing. An unprompted report takes `lock` inside
169 * it for its limit; a requested one is called under `answering`. Answers whether to send it:
170 * false for an unprompted repeat, which is stored as not sent.
171 */
172 const insert = Effect.fn("FeedbackStore.insert")(function* (
173 report: Omit<FeedbackReport, "sent">,
174 runId: RunId | null,
175 errorCode: string | null = null,
176 ) {
177 const traceJson = yield* encodeTrace(report.trace).pipe(Effect.mapError(storageError));
178 const write = (mode: AgentFeedbackMode) =>
179 sql.withTransaction(
180 Effect.gen(function* () {
181 if (!report.userRequested) {
182 const limited = yield* overLimit(runId);
183 if (limited !== undefined) return yield* new FeedbackLimitError({ scope: limited });
184 }
185 // Last before the insert: the mode can change while a card waits.
186 yield* allowedBy(mode, report.userRequested, report.source);
187 const send = report.userRequested || !(yield* alreadySent(report.subject, errorCode));
188 yield* sql`INSERT INTO agent_feedback ${sql.insert({
189 id: report.id,
190 thread_id: report.threadId,
191 run_id: runId,
192 created_at: report.createdAt,
193 kind: report.kind,
194 subject: report.subject,
195 expected: report.expected,
196 actual: report.actual,
197 workaround: report.workaround,
198 user_requested: report.userRequested ? 1 : 0,
199 trace: traceJson,
200 source: report.source,
201 error_code: errorCode,
202 // Marked sent before the hand-off and cleared only on a refusal, so a delivery cut
203 // short reads as sent.
204 sent: send ? 1 : 0,
205 })}`;
206 return send;
207 }),
208 );
209 return yield* settings
210 .withSettingsSnapshot(({ agentFeedback: { mode } }) =>
211 report.userRequested ? write(mode) : lock.withPermit(write(mode)),
212 )
213 .pipe(
214 Effect.mapError((error) =>
215 error._tag === "FeedbackLimitError" ||
216 error._tag === "FeedbackOffError" ||
217 error._tag === "FeedbackNotRequestedError"
218 ? error
219 : storageError(error),
220 ),
221 );
222 });
223
224 /** Sends a stored report as the `agent.feedback` event; false when telemetry refuses it. */
225 const deliver = Effect.fn("FeedbackStore.deliver")(function* (
226 report: Omit<FeedbackReport, "sent">,
227 dimensions: Partial<ProviderDimensions>,
228 errorCode?: string,
229 ) {
230 const { kind, subject, expected, actual, workaround, trace, userRequested, source } = report;
231 // A report links to no install. One that left without the user seeing it carries only its
232 // categories and the failed call's code; the agent's text stays in the local copy.
233 const sent = yield* analytics.record(
234 "agent.feedback",
235 {
236 kind,
237 subject,
238 ...(userRequested ? { expected, actual, workaround } : {}),
239 ...(errorCode === undefined ? {} : { errorCode }),
240 trace,
241 userRequested,
242 source,
243 ...dimensions,
244 },
245 { anonymous: true },
246 );
247 if (!sent) {
248 // A failed clear leaves the report reading as sent, on purpose: uncertain reads as sent.
249 yield* sql`UPDATE agent_feedback SET sent = 0 WHERE id = ${report.id}`.pipe(
250 Effect.mapError(storageError),
251 );
252 }
253 return sent;
254 });
255
256 const store = Effect.fn("FeedbackStore.store")(function* ({
257 preview,
258 id,
259 source,
260 threadId,
261 runId,
262 errorCode,
263 dimensions,
264 }: UnpromptedReport) {
265 const report = {
266 ...preview,
267 userRequested: false,
268 source,
269 id,
270 threadId,
271 createdAt: DateTime.formatIso(yield* DateTime.now),
272 };
273 const send = yield* insert(report, runId, errorCode ?? null);
274 return { ...report, sent: send && (yield* deliver(report, dimensions, errorCode)) };
275 });
276
277 const showCard = Effect.fn("FeedbackStore.showCard")(function* (card: FeedbackCard) {
278 yield* lock.withPermit(
279 Effect.gen(function* () {
280 const [shown] = yield* sql<{ readonly count: number }>`
281 SELECT COUNT(*) AS count FROM orchestration_v2_projection_turn_items
282 WHERE thread_id = ${card.threadId} AND run_id = ${card.runId}
283 AND type = 'feedback_request'`.pipe(Effect.mapError(storageError));
284 if ((shown?.count ?? 0) >= MAX_REPORTS_PER_TURN) {
285 return yield* new FeedbackLimitError({ scope: "cards" });
286 }
287 yield* record(card, "pending", card.conversationTrace ?? undefined);
288 }),
289 );
290 });
291
292 const answer = Effect.fn("FeedbackStore.answer")(function* (input: AgentFeedbackAnswerInput) {
293 yield* Effect.annotateCurrentSpan({
294 "orchestration_v2.thread_id": input.threadId,
295 "agent_feedback.answer": input.answer,
296 });
297 const fail = (reason: AgentFeedbackRequestError["reason"]) =>
298 Effect.fail(new AgentFeedbackRequestError({ reason }));
299 const recordFailed = (cause: unknown) =>
300 new AgentFeedbackRequestError({ reason: "record_failed", cause });
301 const { turnItems } = yield* threads
302 .getThreadRecords(input.threadId, ["turnItems"], {
303 turnItemTypes: ["feedback_request"],
304 messageRoles: [],
305 })
306 .pipe(
307 Effect.mapError((cause) => new AgentFeedbackRequestError({ reason: "load_failed", cause })),
308 );
309 const item = turnItems.find((candidate) => candidate.id === input.turnItemId);
310 // A fork lists the cards it inherited; only the thread that asked answers one.
311 if (
312 item?.type !== "feedback_request" ||
313 item.threadId !== input.threadId ||
314 item.runId === null ||
315 item.nodeId === null ||
316 !item.id.startsWith(CARD_PREFIX)
317 ) {
318 return yield* fail("not_found");
319 }
320 if (item.feedbackStatus !== "pending") return yield* fail("already_answered");
321 const card = {
322 reportId: item.id.slice(CARD_PREFIX.length),
323 threadId: input.threadId,
324 runId: item.runId,
325 nodeId: item.nodeId,
326 };
327 // Settles the card with the trace it sent. Without one, it keeps only the outline.
328 const settle = (status: AgentFeedbackRequestStatus, trace = item.preview.trace) =>
329 record({ ...card, preview: { ...item.preview, trace } }, status);
330 const { runs } = yield* threads
331 .getThreadRecords(input.threadId, ["runs"], { runIds: [card.runId] })
332 .pipe(
333 Effect.mapError((cause) => new AgentFeedbackRequestError({ reason: "load_failed", cause })),
334 );
335 const run = runs.find((candidate) => candidate.id === card.runId);
336 const providerList = yield* providers.getProviders;
337
338 // One answer at a time, from the claim through settling the card, so no other answer can
339 // settle it differently in between.
340 yield* answering
341 .withPermit(
342 Effect.gen(function* () {
343 const [waiting] = yield* sql<{ readonly waiting: number }>`
344 SELECT 1 AS waiting FROM orchestration_v2_projection_turn_items
345 WHERE turn_item_id = ${item.id} AND status = 'waiting'`;
346 if (waiting === undefined) return yield* fail("already_answered");
347 // Stored before its card was settled, by a crash or a failed record: settle it now. A
348 // report not known to be refused reads as sent.
349 const [stored] = yield* sql<{ readonly sent: number; readonly trace: string | null }>`
350 SELECT sent, trace FROM agent_feedback WHERE id = ${card.reportId}`;
351 if (stored !== undefined) {
352 if (stored.sent !== 1) return yield* settle("cancelled");
353 return yield* settle("sent", yield* decodeTrace(stored.trace));
354 }
355 if (input.answer === "decline") return yield* settle("declined");
356
357 const trace =
358 input.includeConversation === true && item.conversationTrace !== undefined
359 ? item.conversationTrace
360 : item.preview.trace;
361 const report = {
362 ...item.preview,
363 trace,
364 userRequested: true,
365 source: "mcp" as const,
366 id: card.reportId,
367 threadId: input.threadId,
368 createdAt: DateTime.formatIso(yield* DateTime.now),
369 };
370 const off = yield* insert(report, card.runId).pipe(
371 Effect.as(false),
372 Effect.catchTags({ FeedbackOffError: () => Effect.succeed(true) }),
373 );
374 if (off) {
375 yield* settle("cancelled");
376 return yield* fail("feedback_off");
377 }
378 const sent = yield* deliver(
379 report,
380 run === undefined ? {} : providerDimensions(providerList, run.modelSelection),
381 );
382 // Telemetry off keeps the report on this machine, so the card says not sent.
383 yield* sent ? settle("sent", trace) : settle("cancelled");
384 }),
385 )
386 .pipe(
387 Effect.catchTags({
388 // A failed record leaves the card open; the next answer settles it from the report.
389 FeedbackStorageError: (error) => Effect.fail(recordFailed(error)),
390 SqlError: (error) => Effect.fail(recordFailed(error)),
391 SchemaError: (error) => Effect.fail(recordFailed(error)),
392 // A requested report is never over a limit or refused by When I ask.
393 FeedbackLimitError: Effect.die,
394 FeedbackNotRequestedError: Effect.die,
395 }),
396 );
397 });
398
399 return FeedbackStore.of({ store, showCard, answer });
400});
401
402export const layer = Layer.effect(FeedbackStore, make);