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