Open History to see the last commit
1import type {
2 EnvironmentId,
3 ThreadId,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2RuntimeRequest,
6 OrchestrationV2UserInputQuestion,
7 ProviderApprovalFullAccessOverride,
8 ProviderApprovalOption,
9 ProviderApprovalDecision,
10 ProviderRequestKind,
11 RuntimeRequestId,
12} from "@t3tools/contracts";
13import * as DateTime from "effect/DateTime";
14import type { AtomCommandResult } from "./runtime.ts";
15import type { ThreadStructure, ThreadStructureVisibleTurnItem } from "./models.ts";
16
17export type ApprovalResponder = (
18 requestId: RuntimeRequestId,
19 decision: ProviderApprovalDecision,
20 feedback?: string,
21) => Promise<AtomCommandResult<unknown, unknown> | undefined>;
22
23/** Feedback belongs to the displayed request, which may be a native child's tool call. */
24export async function sendApprovalFeedback(
25 approval: ThreadPendingApproval,
26 feedback: string,
27 respond: ApprovalResponder,
28): Promise<boolean> {
29 if (!approval.supportsFeedback || approval.responseCapability !== "live" || !feedback.trim())
30 return false;
31 return (await respond(approval.requestId, "decline", feedback.trim()))?._tag === "Success";
32}
33
34/** Declines every approval a redirect replaces; any one still pending would block the agent. */
35export async function declinePendingApprovals(
36 approvals: ReadonlyArray<ThreadPendingApproval>,
37 respond: ApprovalResponder,
38): Promise<boolean> {
39 for (const approval of approvals) {
40 // A request the provider can no longer answer has nothing to decline.
41 if (approval.responseCapability !== "live") continue;
42 if ((await respond(approval.requestId, "decline"))?._tag !== "Success") return false;
43 }
44 return true;
45}
46
47export interface ThreadPendingApproval {
48 readonly requestId: RuntimeRequestId;
49 readonly requestKind: ProviderRequestKind;
50 readonly createdAt: string;
51 readonly detail?: string;
52 readonly reason?: string;
53 readonly fullAccessOverride?: ProviderApprovalFullAccessOverride;
54 readonly appName?: string;
55 readonly options?: ReadonlyArray<ProviderApprovalOption>;
56 readonly responseCapability: "live" | "not_resumable";
57 readonly supportsFeedback?: boolean;
58}
59
60export const FULL_ACCESS_OVERRIDE_QUESTION = "Why am I being asked this?";
61
62export function fullAccessOverrideExplanation(
63 override: ProviderApprovalFullAccessOverride,
64): string {
65 return override === "ask_rule"
66 ? "Full access skips approvals, but an ask rule in the agent's own settings matches this action, so it still asks. Remove or narrow that rule to stop these prompts."
67 : "Full access skips approvals, but the agent still stops for a few safety checks of its own that no setting can skip, such as a delete whose path it can't verify. T3 Code can't turn these off, so check the request and approve it if it's what you expect.";
68}
69
70export interface ThreadUserInputQuestion extends Omit<
71 OrchestrationV2UserInputQuestion,
72 "multiSelect"
73> {
74 readonly multiSelect: boolean;
75}
76
77export interface ThreadPendingUserInput {
78 readonly requestId: RuntimeRequestId;
79 readonly createdAt: string;
80 readonly questions: ReadonlyArray<ThreadUserInputQuestion>;
81 readonly responseCapability: OrchestrationV2RuntimeRequest["responseCapability"]["type"];
82 readonly responseMode?: "message";
83 readonly dismissible: boolean;
84}
85
86export interface PendingThreadRequests {
87 readonly approvals: ReadonlyArray<ThreadPendingApproval>;
88 readonly userInputs: ReadonlyArray<ThreadPendingUserInput>;
89}
90
91export function seedUserInputDraftAnswers<Draft extends { readonly customAnswer?: string }>(
92 questions: ReadonlyArray<
93 Pick<OrchestrationV2UserInputQuestion, "id" | "allowCustomAnswer" | "initialAnswer">
94 >,
95 drafts: Record<string, Draft>,
96): Record<string, Draft | { customAnswer: string }> {
97 let seeded: Record<string, Draft | { customAnswer: string }> = drafts;
98 for (const question of questions) {
99 if (
100 question.initialAnswer === undefined ||
101 question.allowCustomAnswer === false ||
102 seeded[question.id] !== undefined
103 )
104 continue;
105 if (seeded === drafts) seeded = { ...drafts };
106 seeded[question.id] = { customAnswer: question.initialAnswer };
107 }
108 return seeded;
109}
110
111/** Keys a user-input draft by thread so a thread's resolved requests can be pruned together. */
112export function userInputDraftKey(
113 environmentId: string,
114 threadId: string | null,
115 requestId: string | undefined,
116): string {
117 return JSON.stringify([environmentId, threadId, requestId]);
118}
119
120/**
121 * Drops the thread's drafts for requests outside `pendingRequestIds`, leaving
122 * other threads alone. Returns the input itself when nothing is dropped.
123 */
124export function pruneResolvedUserInputDrafts<T>(
125 draftsByRequestKey: Record<string, T>,
126 environmentId: string,
127 threadId: string,
128 pendingRequestIds: ReadonlyArray<string>,
129): Record<string, T> {
130 const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
131 const pendingKeys = new Set(
132 pendingRequestIds.map((requestId) => userInputDraftKey(environmentId, threadId, requestId)),
133 );
134 const retained = Object.entries(draftsByRequestKey).filter(
135 ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
136 );
137 return retained.length === Object.keys(draftsByRequestKey).length
138 ? draftsByRequestKey
139 : Object.fromEntries(retained);
140}
141
142/**
143 * Question attachment drafts are keyed `<thread prefix><encoded [requestId, questionId]>`.
144 * Returns the keys under `threadPrefix` whose request is outside `pendingRequestIds`.
145 */
146export function resolvedQuestionDraftKeys(
147 keys: Iterable<string>,
148 threadPrefix: string,
149 pendingRequestIds: ReadonlyArray<string>,
150): string[] {
151 // encodeURIComponent is per character, so an encoded JSON prefix prefixes the encoded key.
152 const pendingPrefixes = pendingRequestIds.map(
153 (requestId) =>
154 `${threadPrefix}${encodeURIComponent(`${JSON.stringify([requestId]).slice(0, -1)},`)}`,
155 );
156 const resolved: string[] = [];
157 for (const key of keys) {
158 if (key.startsWith(threadPrefix) && !pendingPrefixes.some((prefix) => key.startsWith(prefix)))
159 resolved.push(key);
160 }
161 return resolved;
162}
163
164export interface ThreadRequestsResolved {
165 readonly environmentId: EnvironmentId;
166 readonly threadId: ThreadId;
167 /** Every request the thread still waits on; drafts for any other request are stale. */
168 readonly pendingRequestIds: ReadonlyArray<RuntimeRequestId>;
169}
170
171const threadRequestsResolvedListeners = new Set<(event: ThreadRequestsResolved) => void>();
172
173/**
174 * Clients register draft pruners once at module level. Thread state announces
175 * when its synchronized projection first lands and whenever a request leaves
176 * pending, wherever the resolution came from (another device, interrupt, turn end).
177 */
178export function onThreadRequestsResolved(
179 listener: (event: ThreadRequestsResolved) => void,
180): () => void {
181 threadRequestsResolvedListeners.add(listener);
182 return () => threadRequestsResolvedListeners.delete(listener);
183}
184
185function notifyThreadRequestsResolved(event: ThreadRequestsResolved): void {
186 for (const listener of threadRequestsResolvedListeners) {
187 try {
188 listener(event);
189 } catch (error) {
190 // A failing pruner must neither stop the others nor break thread sync.
191 queueMicrotask(() => {
192 throw error;
193 });
194 }
195 }
196}
197
198/**
199 * Tracks one thread's announced pending requests. Feed it the pending ids of
200 * each authoritative projection; it notifies on the first one and whenever an
201 * announced request is no longer pending. New requests alone stay quiet.
202 */
203export function makeThreadRequestsResolvedAnnouncer(
204 environmentId: EnvironmentId,
205 threadId: ThreadId,
206) {
207 let announced: ReadonlySet<RuntimeRequestId> | null = null;
208 return (pendingRequestIds: ReadonlyArray<RuntimeRequestId>) => {
209 const pending = new Set(pendingRequestIds);
210 const resolvedSome = announced === null || [...announced].some((id) => !pending.has(id));
211 announced = pending;
212 if (resolvedSome) notifyThreadRequestsResolved({ environmentId, threadId, pendingRequestIds });
213 };
214}
215
216export function pendingRuntimeRequestIds(
217 projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,
218): RuntimeRequestId[] {
219 return projection.runtimeRequests.flatMap((request) =>
220 request.status === "pending" ? [request.id] : [],
221 );
222}
223
224export function derivePendingThreadRequests(
225 projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,
226): PendingThreadRequests {
227 const approvals: ThreadPendingApproval[] = [];
228 const userInputs: ThreadPendingUserInput[] = [];
229
230 for (const request of projection.runtimeRequests) {
231 if (request.status !== "pending") continue;
232 const responseCapability = request.responseCapability.type;
233 if (request.kind === "user_input") {
234 const item = projection.turnItems.findLast(
235 (candidate) =>
236 candidate.type === "user_input_request" && candidate.requestId === request.id,
237 );
238 if (item === undefined || item.type !== "user_input_request") continue;
239 userInputs.push({
240 requestId: request.id,
241 createdAt: DateTime.formatIso(request.createdAt),
242 questions: item.questions.map((question) => ({
243 ...question,
244 multiSelect: question.multiSelect ?? false,
245 })),
246 responseCapability,
247 dismissible: item.responseMode === "message" || responseCapability === "message",
248 ...(item.responseMode === "message" || responseCapability === "message"
249 ? { responseMode: "message" as const }
250 : {}),
251 });
252 continue;
253 }
254
255 if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue;
256 const item = projection.turnItems.findLast(
257 (candidate) => candidate.type === "approval_request" && candidate.requestId === request.id,
258 );
259 approvals.push({
260 requestId: request.id,
261 requestKind: request.kind,
262 createdAt: DateTime.formatIso(request.createdAt),
263 ...(item?.type === "approval_request" && item.prompt ? { detail: item.prompt } : {}),
264 ...(item?.type === "approval_request" && item.reason ? { reason: item.reason } : {}),
265 ...(item?.type === "approval_request" && item.fullAccessOverride
266 ? { fullAccessOverride: item.fullAccessOverride }
267 : {}),
268 ...(item?.type === "approval_request" && item.appName ? { appName: item.appName } : {}),
269 ...(item?.type === "approval_request" && item.options !== undefined
270 ? { options: item.options }
271 : {}),
272 responseCapability: responseCapability === "live" ? "live" : "not_resumable",
273 ...(request.responseCapability.type === "live" && request.responseCapability.supportsFeedback
274 ? { supportsFeedback: true }
275 : {}),
276 });
277 }
278
279 return { approvals, userInputs };
280}
281
282export function createQuestionHistoryProjector<
283 Row extends ThreadStructureVisibleTurnItem =
284 OrchestrationV2ThreadProjection["visibleTurnItems"][number],
285>() {
286 type Rows = ReadonlyArray<Row>;
287 type Requests = OrchestrationV2ThreadProjection["runtimeRequests"];
288 let previousRows: Rows | undefined;
289 let previousRequests: Requests | undefined;
290 let previousResult: Rows | undefined;
291 const cache = new WeakMap<Row, { request: Requests[number]; row: Row }>();
292 return (projection: {
293 readonly visibleTurnItems: Rows;
294 readonly runtimeRequests: Requests;
295 }): Rows => {
296 const { visibleTurnItems: rows, runtimeRequests: requests } = projection;
297 if (rows === previousRows && requests === previousRequests && previousResult)
298 return previousResult;
299 const byId = new Map(requests.map((request) => [request.id, request]));
300 let result: Row[] | undefined;
301 for (const [index, row] of rows.entries()) {
302 const item = row.item;
303 const request =
304 item.type === "user_input_request" && !item.questionAnswer
305 ? byId.get(item.requestId)
306 : undefined;
307 let next = row;
308 if (
309 item.type === "user_input_request" &&
310 request?.status === "resolved" &&
311 request.answers !== undefined
312 ) {
313 const cached = cache.get(row);
314 next =
315 cached?.request === request
316 ? cached.row
317 : {
318 ...row,
319 item: {
320 ...item,
321 questionAnswer: {
322 requestId: request.id,
323 answers: request.answers,
324 attachmentsByQuestionId: {},
325 questionTextById: Object.fromEntries(
326 item.questions.map((question) => [question.id, question.question]),
327 ),
328 },
329 },
330 };
331 cache.set(row, { request, row: next });
332 }
333 if (next !== row) result ??= rows.slice(0, index);
334 result?.push(next);
335 }
336 previousRows = rows;
337 previousRequests = requests;
338 previousResult = result ?? rows;
339 return previousResult;
340 };
341}