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