Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pendingRequests.ts

196 lines7.0 KB

1import {
2 ApprovalRequestId,
3 type OrchestrationThreadActivity,
4 ProviderApprovalOption,
5 ProviderRequestKind,
6 UserInputQuestion,
7} from "@t3tools/contracts";
8import * as Option from "effect/Option";
9import * as Predicate from "effect/Predicate";
10import * as Schema from "effect/Schema";
11​
12export interface PendingApproval {
13 readonly requestId: ApprovalRequestId;
14 readonly requestKind: ProviderRequestKind;
15 readonly createdAt: string;
16 readonly detail?: string;
17 readonly appName?: string;
18 readonly options?: ReadonlyArray<ProviderApprovalOption>;
20​
21export interface PendingUserInput {
22 readonly requestId: ApprovalRequestId;
23 readonly createdAt: string;
24 readonly questions: ReadonlyArray<UserInputQuestion>;
25 /** Async questions can be dismissed without a reply; native callbacks cannot. */
26 readonly dismissible: boolean;
28​
29const isRequestId = Schema.is(ApprovalRequestId);
30const isProviderRequestKind = Schema.is(ProviderRequestKind);
31const isProviderApprovalOption = Schema.is(ProviderApprovalOption);
32const QuestionOption = Schema.Struct({
33 ...UserInputQuestion.fields.options.value.fields,
34 label: Schema.String,
35});
36const isQuestionOption = Schema.is(QuestionOption);
37// Native question IDs and option labels can be answer keys. Do not trim them.
38const decodeQuestion = Schema.decodeUnknownOption(
39 Schema.Struct({
40 ...UserInputQuestion.fields,
41 id: Schema.String,
42 header: Schema.String,
43 question: Schema.String,
44 options: Schema.Array(QuestionOption),
45 }),
46);
47​
48/** Older activities use native request types instead of a request kind. */
49export function requestKindFromRequestType(requestType: unknown): ProviderRequestKind | null {
50 switch (requestType) {
51 case "command_execution_approval":
52 case "exec_command_approval":
53 case "dynamic_tool_call":
54 return "command";
55 case "file_read_approval":
56 return "file-read";
57 case "file_change_approval":
58 case "apply_patch_approval":
59 return "file-change";
60 case "mcp_elicitation_approval":
61 return "mcp-elicitation";
62 default:
63 return null;
64 }
66​
67function parseQuestions(value: unknown): UserInputQuestion[] {
68 if (!Array.isArray(value)) return [];
69 return value.flatMap((question) => {
70 if (!Predicate.isObject(question) || !Array.isArray(question.options)) return [];
71 const options = question.options.filter(isQuestionOption);
72 if (options.length === 0 && question.allowCustomAnswer === false) return [];
73 const parsed = decodeQuestion({
74 id: question.id,
75 header: question.header,
76 question: question.question,
77 options,
78 multiSelect: question.multiSelect === true,
79 ...(typeof question.allowCustomAnswer === "boolean"
80 ? { allowCustomAnswer: question.allowCustomAnswer }
81 : {}),
82 });
83 return Option.isSome(parsed) ? [parsed.value] : [];
84 });
86​
87const requestActivityKinds = new Set([
88 "approval.requested",
89 "approval.resolved",
90 "provider.approval.respond.failed",
91 "user-input.requested",
92 "user-input.resolved",
93 "provider.user-input.respond.failed",
94]);
95​
96// The server reports a stale or unknown request through the failure text.
97// A failed reply with any other text stays open so the user can retry.
98const staleRequestFailureDetails = {
99 "provider.approval.respond.failed": [
100 "stale pending approval request",
101 "unknown pending approval request",
102 "unknown pending permission request",
103 "unknown pending codex approval request",
104 ],
105 "provider.user-input.respond.failed": [
106 "stale pending user-input request",
107 "unknown pending user-input request",
108 "unknown pending user input request",
109 "unknown pending codex user input request",
110 ],
111} as const;
112​
113function isStaleRequestFailure(
114 kind: keyof typeof staleRequestFailureDetails,
115 payload: Record<string, unknown>,
116): boolean {
117 const detail = typeof payload.detail === "string" ? payload.detail.toLowerCase() : "";
118 return staleRequestFailureDetails[kind].some((fragment) => detail.includes(fragment));
120​
121/** Reduces request state once for web, desktop, and mobile. Layout stays with each client. */
122export function derivePendingRequests(activities: ReadonlyArray<OrchestrationThreadActivity>) {
123 const approvals = new Map<ApprovalRequestId, PendingApproval>();
124 const userInputs = new Map<ApprovalRequestId, PendingUserInput>();
125 const closedApprovals = new Set<ApprovalRequestId>();
126 const closedUserInputs = new Set<ApprovalRequestId>();
127​
128 // Request IDs are unique. A terminal event stays final even when provider
129 // sequences and server-generated activities arrive in a different order.
130 for (const activity of activities) {
131 if (!requestActivityKinds.has(activity.kind)) continue;
132 const payload = Predicate.isObject(activity.payload) ? activity.payload : undefined;
133 if (!payload || !isRequestId(payload.requestId)) continue;
134 const requestId = payload.requestId;
135​
136 if (activity.kind === "approval.requested") {
137 if (
138 closedApprovals.has(requestId) ||
139 payload.requestType === "tool_user_input" ||
140 payload.requestType === "auth_tokens_refresh"
141 ) {
142 continue;
143 }
144 const requestKind = isProviderRequestKind(payload.requestKind)
145 ? payload.requestKind
146 : requestKindFromRequestType(payload.requestType);
147 const options = Array.isArray(payload.options)
148 ? payload.options.filter(isProviderApprovalOption)
149 : [];
150 approvals.set(requestId, {
151 requestId,
152 // Older OpenCode approvals do not always include a recognized kind.
153 requestKind: requestKind ?? "command",
154 createdAt: activity.createdAt,
155 ...(typeof payload.detail === "string" && payload.detail ? { detail: payload.detail } : {}),
156 ...(typeof payload.appName === "string" && payload.appName
157 ? { appName: payload.appName }
158 : {}),
159 ...(options.length > 0 ? { options } : {}),
160 });
161 } else if (activity.kind === "user-input.requested") {
162 if (closedUserInputs.has(requestId)) continue;
163 const questions = parseQuestions(payload.questions);
164 if (questions.length === 0) continue;
165 userInputs.set(requestId, {
166 requestId,
167 createdAt: activity.createdAt,
168 questions,
169 dismissible: payload.responseMode === "message",
170 });
171 } else if (
172 activity.kind === "approval.resolved" ||
173 (activity.kind === "provider.approval.respond.failed" &&
174 isStaleRequestFailure(activity.kind, payload))
175 ) {
176 closedApprovals.add(requestId);
177 approvals.delete(requestId);
178 } else if (
179 activity.kind === "user-input.resolved" ||
180 (activity.kind === "provider.user-input.respond.failed" &&
181 isStaleRequestFailure(activity.kind, payload))
182 ) {
183 closedUserInputs.add(requestId);
184 userInputs.delete(requestId);
185 }
186 }
187​
188 const byCreatedAt = (
189 left: { readonly createdAt: string },
190 right: { readonly createdAt: string },
191 ) => left.createdAt.localeCompare(right.createdAt);
192 return {
193 approvals: [...approvals.values()].sort(byCreatedAt),
194 userInputs: [...userInputs.values()].sort(byCreatedAt),
195 };