@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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