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 // Entries, not assignment, so an id such as `__proto__` becomes an own draft.
103 const seeds = questions.flatMap((question) =>
104 question.initialAnswer === undefined ||
105 question.allowCustomAnswer === false ||
106 Object.hasOwn(drafts, question.id)
107 ? []
108 : [[question.id, { customAnswer: question.initialAnswer }] as const],
109 );
110 return seeds.length === 0 ? drafts : { ...drafts, ...Object.fromEntries(seeds) };
111}
112
113/** Keys a user-input draft by thread so a thread's resolved requests can be pruned together. */
114export function userInputDraftKey(
115 environmentId: string,
116 threadId: string | null,
117 requestId: string | undefined,
118): string {
119 return JSON.stringify([environmentId, threadId, requestId]);
120}
121
122/**
123 * Drops the thread's drafts for requests outside `pendingRequestIds`, leaving
124 * other threads alone. Returns the input itself when nothing is dropped.
125 */
126export function pruneResolvedUserInputDrafts<T>(
127 draftsByRequestKey: Record<string, T>,
128 environmentId: string,
129 threadId: string,
130 pendingRequestIds: ReadonlyArray<string>,
131): Record<string, T> {
132 const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
133 const pendingKeys = new Set(
134 pendingRequestIds.map((requestId) => userInputDraftKey(environmentId, threadId, requestId)),
135 );
136 const retained = Object.entries(draftsByRequestKey).filter(
137 ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
138 );
139 return retained.length === Object.keys(draftsByRequestKey).length
140 ? draftsByRequestKey
141 : Object.fromEntries(retained);
142}
143
144/**
145 * Question attachment drafts are keyed `<thread prefix><encoded [requestId, questionId]>`.
146 * Returns the keys under `threadPrefix` whose request is outside `pendingRequestIds`.
147 */
148export function resolvedQuestionDraftKeys(
149 keys: Iterable<string>,
150 threadPrefix: string,
151 pendingRequestIds: ReadonlyArray<string>,
152): string[] {
153 // encodeURIComponent is per character, so an encoded JSON prefix prefixes the encoded key.
154 const pendingPrefixes = pendingRequestIds.map(
155 (requestId) =>
156 `${threadPrefix}${encodeURIComponent(`${JSON.stringify([requestId]).slice(0, -1)},`)}`,
157 );
158 const resolved: string[] = [];
159 for (const key of keys) {
160 if (key.startsWith(threadPrefix) && !pendingPrefixes.some((prefix) => key.startsWith(prefix)))
161 resolved.push(key);
162 }
163 return resolved;
164}
165
166export interface ThreadRequestsResolved {
167 readonly environmentId: EnvironmentId;
168 readonly threadId: ThreadId;
169 /** Every request the thread still waits on; drafts for any other request are stale. */
170 readonly pendingRequestIds: ReadonlyArray<RuntimeRequestId>;
171}
172
173const threadRequestsResolvedListeners = new Set<(event: ThreadRequestsResolved) => void>();
174
175/**
176 * Clients register draft pruners once at module level. Thread state announces
177 * when its synchronized projection first lands and whenever a request leaves
178 * pending, wherever the resolution came from (another device, interrupt, turn end).
179 */
180export function onThreadRequestsResolved(
181 listener: (event: ThreadRequestsResolved) => void,
182): () => void {
183 threadRequestsResolvedListeners.add(listener);
184 return () => threadRequestsResolvedListeners.delete(listener);
185}
186
187function notifyThreadRequestsResolved(event: ThreadRequestsResolved): void {
188 for (const listener of threadRequestsResolvedListeners) {
189 try {
190 listener(event);
191 } catch (error) {
192 // A failing pruner must neither stop the others nor break thread sync.
193 queueMicrotask(() => {
194 throw error;
195 });
196 }
197 }
198}
199
200/**
201 * Tracks one thread's announced pending requests. Feed it the pending ids of
202 * each authoritative projection; it notifies on the first one and whenever an
203 * announced request is no longer pending. New requests alone stay quiet.
204 */
205export function makeThreadRequestsResolvedAnnouncer(
206 environmentId: EnvironmentId,
207 threadId: ThreadId,
208) {
209 let announced: ReadonlySet<RuntimeRequestId> | null = null;
210 return (pendingRequestIds: ReadonlyArray<RuntimeRequestId>) => {
211 const pending = new Set(pendingRequestIds);
212 const resolvedSome = announced === null || [...announced].some((id) => !pending.has(id));
213 announced = pending;
214 if (resolvedSome) notifyThreadRequestsResolved({ environmentId, threadId, pendingRequestIds });
215 };
216}
217
218export function pendingRuntimeRequestIds(
219 projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,
220): RuntimeRequestId[] {
221 return projection.runtimeRequests.flatMap((request) =>
222 request.status === "pending" ? [request.id] : [],
223 );
224}
225
226export function derivePendingThreadRequests(
227 projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,
228): PendingThreadRequests {
229 const approvals: ThreadPendingApproval[] = [];
230 const userInputs: ThreadPendingUserInput[] = [];
231
232 for (const request of projection.runtimeRequests) {
233 if (request.status !== "pending") continue;
234 const responseCapability = request.responseCapability.type;
235 if (request.kind === "user_input") {
236 const item = projection.turnItems.findLast(
237 (candidate) =>
238 candidate.type === "user_input_request" && candidate.requestId === request.id,
239 );
240 if (item === undefined || item.type !== "user_input_request") continue;
241 userInputs.push({
242 requestId: request.id,
243 createdAt: DateTime.formatIso(request.createdAt),
244 questions: item.questions.map((question) => ({
245 ...question,
246 multiSelect: question.multiSelect ?? false,
247 })),
248 responseCapability,
249 dismissible: item.responseMode === "message" || responseCapability === "message",
250 ...(item.responseMode === "message" || responseCapability === "message"
251 ? { responseMode: "message" as const }
252 : {}),
253 });
254 continue;
255 }
256
257 if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue;
258 const item = projection.turnItems.findLast(
259 (candidate) => candidate.type === "approval_request" && candidate.requestId === request.id,
260 );
261 approvals.push({
262 requestId: request.id,
263 requestKind: request.kind,
264 createdAt: DateTime.formatIso(request.createdAt),
265 ...(item?.type === "approval_request" && item.prompt ? { detail: item.prompt } : {}),
266 ...(item?.type === "approval_request" && item.reason ? { reason: item.reason } : {}),
267 ...(item?.type === "approval_request" && item.fullAccessOverride
268 ? { fullAccessOverride: item.fullAccessOverride }
269 : {}),
270 ...(item?.type === "approval_request" && item.appName ? { appName: item.appName } : {}),
271 ...(item?.type === "approval_request" && item.options !== undefined
272 ? { options: item.options }
273 : {}),
274 responseCapability: responseCapability === "live" ? "live" : "not_resumable",
275 ...(request.responseCapability.type === "live" && request.responseCapability.supportsFeedback
276 ? { supportsFeedback: true }
277 : {}),
278 });
279 }
280
281 return { approvals, userInputs };
282}
283
284export function createQuestionHistoryProjector<
285 Row extends ThreadStructureVisibleTurnItem =
286 OrchestrationV2ThreadProjection["visibleTurnItems"][number],
287>() {
288 type Rows = ReadonlyArray<Row>;
289 type Requests = OrchestrationV2ThreadProjection["runtimeRequests"];
290 let previousRows: Rows | undefined;
291 let previousRequests: Requests | undefined;
292 let previousResult: Rows | undefined;
293 let byId = new Map<RuntimeRequestId, Requests[number]>();
294 const cache = new WeakMap<Row, { request: Requests[number]; row: Row }>();
295 const projectRow = (row: Row): Row => {
296 const item = row.item;
297 if (item.type !== "user_input_request" || item.questionAnswer) return row;
298 const request = byId.get(item.requestId);
299 if (request?.status !== "resolved" || request.answers === undefined) return row;
300 const cached = cache.get(row);
301 const next: Row =
302 cached?.request === request
303 ? cached.row
304 : {
305 ...row,
306 item: {
307 ...item,
308 questionAnswer: {
309 requestId: request.id,
310 answers: request.answers,
311 attachmentsByQuestionId: {},
312 questionTextById: Object.fromEntries(
313 item.questions.map((question) => [question.id, question.question]),
314 ),
315 },
316 },
317 };
318 cache.set(row, { request, row: next });
319 return next;
320 };
321 const projectRows = (rows: Rows): Rows => {
322 let result: Row[] | undefined;
323 for (const [index, row] of rows.entries()) {
324 const next = projectRow(row);
325 if (next !== row) result ??= rows.slice(0, index);
326 result?.push(next);
327 }
328 return result ?? rows;
329 };
330 return (projection: {
331 readonly visibleTurnItems: Rows;
332 readonly runtimeRequests: Requests;
333 }): Rows => {
334 const { visibleTurnItems: rows, runtimeRequests: requests } = projection;
335 const sameRequests = requests === previousRequests;
336 if (rows === previousRows && sameRequests && previousResult) return previousResult;
337 if (!sameRequests) byId = new Map(requests.map((request) => [request.id, request]));
338 // Nothing was overlaid and requests are unchanged, so only an exactly replaced row can differ.
339 const replacedIndex =
340 sameRequests && previousRows !== undefined && previousResult === previousRows
341 ? getProjectionArrayReplacementIndex(previousRows, rows)
342 : undefined;
343 const unchanged =
344 replacedIndex !== undefined && projectRow(rows[replacedIndex]!) === rows[replacedIndex];
345 previousRows = rows;
346 previousRequests = requests;
347 previousResult = unchanged ? rows : projectRows(rows);
348 return previousResult;
349 };
350}
351
352export interface ChildThreadApproval {
353 readonly thread: ScopedThreadRef;
354 readonly title: string;
355 readonly approval: ThreadPendingApproval;
356}
357
358export function createChildThreadApprovalsAtom(input: {
359 readonly childThreadInputsAtom: (
360 ref: ScopedThreadRef,
361 ) => Atom.Atom<ReadonlyArray<EnvironmentThreadShell>>;
362 readonly pendingRequestsAtom: (ref: ScopedThreadRef) => Atom.Atom<PendingThreadRequests | null>;
363}) {
364 const family = Atom.family((key: string) => {
365 let previous: ReadonlyArray<ChildThreadApproval> = [];
366 return Atom.make((get) => {
367 const next = get(input.childThreadInputsAtom(parseThreadKey(key))).flatMap((child) => {
368 if (!child.hasPendingApprovals) return [];
369 const thread = { environmentId: child.environmentId, threadId: child.id };
370 // Only children asking for approval need a detail subscription.
371 return (get(input.pendingRequestsAtom(thread))?.approvals ?? []).map((approval) => ({
372 thread,
373 title: child.title,
374 approval,
375 }));
376 });
377 if (
378 next.length === previous.length &&
379 next.every((entry, index) => {
380 const old = previous[index]!;
381 return (
382 old.approval === entry.approval &&
383 old.title === entry.title &&
384 threadKey(old.thread) === threadKey(entry.thread)
385 );
386 })
387 )
388 return previous;
389 previous = next;
390 return next;
391 });
392 });
393 const empty = Atom.make<ReadonlyArray<ChildThreadApproval>>([]);
394 return (ref: ScopedThreadRef | null) => (ref === null ? empty : family(threadKey(ref)));
395}