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

XAiAcpExtension.ts

432 lines14.0 KB

1import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Ref from "effect/Ref";
5import * as Schema from "effect/Schema";
6import type * as EffectAcpSchema from "effect-acp/schema";
7​
8import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
9​
10const XAiPromptCompleteNotification = Schema.Struct({
11 sessionId: Schema.String,
12 promptId: Schema.optional(Schema.String),
13 stopReason: Schema.optional(Schema.String),
14 agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
15});
16​
17type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
18​
19interface PendingXAiPromptCompletion {
20 readonly sessionId: string;
21 readonly promptId: string;
22 readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
24​
25const completedXAiPromptIdLimit = 128;
26const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
27​
28const XAiAskUserQuestionOption = Schema.Struct({
29 label: Schema.String,
30 description: Schema.optional(Schema.String),
31 preview: Schema.optional(Schema.String),
32 id: Schema.optional(Schema.String),
33});
34​
35const XAiAskUserQuestion = Schema.Struct({
36 id: Schema.optional(Schema.String),
37 question: Schema.String,
38 options: Schema.Array(XAiAskUserQuestionOption),
39 multiSelect: Schema.optional(Schema.NullOr(Schema.Boolean)),
40});
41​
42const XAiAskUserQuestionParams = Schema.Struct({
43 sessionId: Schema.String,
44 toolCallId: Schema.String,
45 questions: Schema.Array(XAiAskUserQuestion),
46 mode: Schema.Literals(["default", "plan"]),
47});
48​
49const XAiWrappedAskUserQuestionParams = Schema.Struct({
50 method: Schema.Literals(["x.ai/ask_user_question", "_x.ai/ask_user_question"]),
51 params: XAiAskUserQuestionParams,
52});
53​
54export const XAiAskUserQuestionRequest = Schema.Union([
55 XAiAskUserQuestionParams,
56 XAiWrappedAskUserQuestionParams,
57]);
58​
59type XAiAskUserQuestionRequestParams = typeof XAiAskUserQuestionParams.Type;
60type XAiAskUserQuestionRequest = typeof XAiAskUserQuestionRequest.Type;
61​
62function trimmed(value: string | undefined): string | undefined {
63 const text = value?.trim();
64 return text && text.length > 0 ? text : undefined;
66​
67function unwrapAskUserQuestionParams(
68 params: XAiAskUserQuestionRequest,
69): XAiAskUserQuestionRequestParams {
70 return "params" in params ? params.params : params;
72​
73export function extractXAiAskUserQuestions(
74 params: XAiAskUserQuestionRequest,
75): ReadonlyArray<UserInputQuestion> {
76 return unwrapAskUserQuestionParams(params).questions.map((question) => ({
77 id: question.id ?? question.question,
78 header: "Question",
79 question: question.question,
80 multiSelect: question.multiSelect === true,
81 options:
82 question.options.length > 0
83 ? question.options.map((option) => ({
84 label: option.label,
85 description: option.description ?? option.label,
86 }))
87 : [{ label: "OK", description: "Continue" }],
88 }));
90​
91interface XAiAskUserQuestionAnnotation {
92 readonly preview?: string;
93 readonly notes?: string;
95​
96interface XAiAskUserQuestionAcceptedResponse {
97 readonly outcome: "accepted";
98 readonly answers: Record<string, ReadonlyArray<string>>;
99 readonly annotations?: Record<string, XAiAskUserQuestionAnnotation>;
101​
102interface XAiAskUserQuestionCancelledResponse {
103 readonly outcome: "cancelled";
105​
106export type XAiAskUserQuestionResponse =
107 | XAiAskUserQuestionAcceptedResponse
108 | XAiAskUserQuestionCancelledResponse;
109​
110interface NormalizedXAiAnswer {
111 readonly questionText: string;
112 readonly selectedLabels: ReadonlyArray<string>;
113 readonly annotation?: XAiAskUserQuestionAnnotation;
115​
116function answerValues(answer: unknown): ReadonlyArray<string> {
117 if (Array.isArray(answer)) {
118 return answer.flatMap((entry) => {
119 const text = typeof entry === "string" ? trimmed(entry) : undefined;
120 return text ? [text] : [];
121 });
122 }
123 const text = typeof answer === "string" ? trimmed(answer) : undefined;
124 return text ? [text] : [];
126​
127function normalizeAnswerForXAi(
128 question: XAiAskUserQuestionRequestParams["questions"][number],
129 answer: unknown,
130): NormalizedXAiAnswer | undefined {
131 const values = answerValues(answer);
132 if (values.length === 0) {
133 return undefined;
134 }
135​
136 const optionByLabel = new Map(question.options.map((option) => [option.label, option]));
137 const resolvedValues = values.map((value) => ({
138 value,
139 option: optionByLabel.get(value),
140 }));
141 const selectedLabels = resolvedValues.flatMap(({ option }) => (option ? [option.label] : []));
142 const notes = resolvedValues.flatMap(({ option, value }) => (option ? [] : [value]));
143 const preview =
144 question.multiSelect === true
145 ? undefined
146 : resolvedValues.map(({ option }) => trimmed(option?.preview)).find((value) => value);
147​
148 const annotation =
149 preview || notes.length > 0
150 ? {
151 ...(preview ? { preview } : {}),
152 ...(notes.length > 0 ? { notes: notes.join("\n") } : {}),
153 }
154 : undefined;
155​
156 return {
157 questionText: question.question,
158 selectedLabels: selectedLabels.length > 0 ? selectedLabels : ["Other"],
159 ...(annotation ? { annotation } : {}),
160 };
162​
163function findQuestionAnswer(
164 answers: ProviderUserInputAnswers,
165 question: XAiAskUserQuestionRequestParams["questions"][number],
166): unknown {
167 const key = question.id ?? question.question;
168 return answers[key] ?? answers[question.question];
170​
171export function makeXAiAskUserQuestionResponse(
172 params: XAiAskUserQuestionRequest,
173 answers: ProviderUserInputAnswers,
174): XAiAskUserQuestionAcceptedResponse {
175 const questions = unwrapAskUserQuestionParams(params).questions;
176 const normalized = questions.flatMap((question) => {
177 const entry = normalizeAnswerForXAi(question, findQuestionAnswer(answers, question));
178 return entry ? [entry] : [];
179 });
180 const annotations = Object.fromEntries(
181 normalized.flatMap((entry) =>
182 entry.annotation ? [[entry.questionText, entry.annotation] as const] : [],
183 ),
184 );
185​
186 return {
187 outcome: "accepted",
188 answers: Object.fromEntries(
189 normalized.map((entry) => [entry.questionText, entry.selectedLabels]),
190 ),
191 ...(Object.keys(annotations).length > 0 ? { annotations } : {}),
192 };
194​
195export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
196 return { outcome: "cancelled" };
198​
199/**
200 * Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
201 * The underlying runtime remains unaware of xAI methods and metadata.
202 */
203export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
204 function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
205 const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
206 const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
207 const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
208 let nextPromptFallbackId = 0;
209 const allocatePromptFallbackId = Effect.sync(() => {
210 nextPromptFallbackId += 1;
211 return `t3-xai-prompt-${nextPromptFallbackId}`;
212 });
213​
214 yield* runtime.handleExtNotification(
215 "_x.ai/session/prompt_complete",
216 XAiPromptCompleteNotification,
217 (notification) =>
218 resolveXAiPromptCompletionFallback({
219 pendingRef,
220 completedPromptIdsRef,
221 notification,
222 }),
223 );
224​
225 return {
226 ...runtime,
227 start: () =>
228 runtime
229 .start()
230 .pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
231 prompt: (payload) =>
232 Effect.gen(function* () {
233 const sessionId = yield* Ref.get(activeSessionIdRef);
234 if (sessionId === undefined) {
235 return yield* runtime.prompt(payload);
236 }
237​
238 const promptId = yield* allocatePromptFallbackId;
239 const fallback = yield* registerXAiPromptCompletionFallback(
240 pendingRef,
241 sessionId,
242 promptId,
243 );
244 const requestPayload = {
245 ...payload,
246 _meta: {
247 ...payload._meta,
248 promptId: fallback.promptId,
249 requestId: fallback.promptId,
250 },
251 } satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
252​
253 return yield* Effect.raceFirst(
254 runtime.prompt(requestPayload),
255 Deferred.await(fallback.deferred),
256 ).pipe(
257 Effect.tap((response) =>
258 rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
259 ),
260 Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
261 );
262 }),
263 cancel: Ref.get(activeSessionIdRef).pipe(
264 Effect.flatMap((sessionId) =>
265 sessionId === undefined
266 ? runtime.cancel
267 : abortPendingPromptCompletions(pendingRef, sessionId).pipe(
268 Effect.andThen(runtime.cancel),
269 ),
270 ),
271 ),
272 } satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
273 },
274);
275​
276const registerXAiPromptCompletionFallback = (
277 pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
278 sessionId: string,
279 promptId: string,
280) =>
281 Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
282 Effect.tap((deferred) =>
283 Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
284 ),
285 Effect.map((deferred) => ({ deferred, promptId })),
286 );
287​
288const unregisterXAiPromptCompletionFallback = (
289 pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
290 deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
291) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
292​
293const abortPendingPromptCompletions = (
294 pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
295 sessionId: string,
296) =>
297 Ref.modify(pendingRef, (pending) => {
298 const [toAbort, remaining] = pending.reduce<
299 [ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
300 >(
301 ([aborting, kept], entry) =>
302 entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
303 [[], []],
304 );
305 if (toAbort.length === 0) {
306 return [Effect.void, pending] as const;
307 }
308 return [
309 Effect.forEach(
310 toAbort,
311 (entry) =>
312 Deferred.succeed(
313 entry.deferred,
314 promptResponseFromXAi({
315 sessionId: entry.sessionId,
316 promptId: entry.promptId,
317 stopReason: "cancelled",
318 agentResult: null,
319 }),
320 ),
321 { concurrency: "unbounded" },
322 ).pipe(Effect.asVoid),
323 remaining,
324 ] as const;
325 }).pipe(Effect.flatten);
326​
327const resolveXAiPromptCompletionFallback = ({
328 pendingRef,
329 completedPromptIdsRef,
330 notification,
331}: {
332 readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
333 readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
334 readonly notification: XAiPromptCompleteNotification;
335}) =>
336 Ref.get(completedPromptIdsRef).pipe(
337 Effect.flatMap((completedPromptIds) => {
338 if (
339 notification.promptId !== undefined &&
340 completedPromptIds.includes(notification.promptId)
341 ) {
342 return Effect.void;
343 }
344 return Ref.modify(pendingRef, (pending) => {
345 const index =
346 notification.promptId !== undefined
347 ? pending.findIndex(
348 (entry) =>
349 entry.sessionId === notification.sessionId &&
350 entry.promptId === notification.promptId,
351 )
352 : pending.findIndex((entry) => entry.sessionId === notification.sessionId);
353 if (index < 0) {
354 return [Effect.void, pending] as const;
355 }
356 const entry = pending[index];
357 if (!entry) {
358 return [Effect.void, pending] as const;
359 }
360 return [
361 Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
362 [...pending.slice(0, index), ...pending.slice(index + 1)],
363 ] as const;
364 }).pipe(Effect.flatten);
365 }),
366 );
367​
368const rememberCompletedXAiPromptId = (
369 completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
370 response: EffectAcpSchema.PromptResponse,
371 fallbackPromptId: string,
372) => {
373 const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
374 return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
375 if (completedPromptIds.includes(promptId)) {
376 return completedPromptIds;
377 }
378 return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
379 });
380};
381​
382function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
383 const meta = response._meta;
384 if (meta === null || typeof meta !== "object") {
385 return undefined;
386 }
387 const promptId = meta.promptId ?? meta.requestId;
388 return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
390​
391export function promptResponseHasMissingXAiStopReason(
392 response: EffectAcpSchema.PromptResponse,
393): boolean {
394 const meta = response._meta;
395 return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
397​
398function promptResponseFromXAi(
399 notification: XAiPromptCompleteNotification,
400): EffectAcpSchema.PromptResponse {
401 const stopReason = normalizeXAiStopReason(notification.stopReason);
402 const meta: Record<string, unknown> = {
403 sessionId: notification.sessionId,
404 };
405 if (notification.stopReason === undefined) {
406 meta[xAiStopReasonMissingMetaKey] = true;
407 }
408 if (notification.promptId !== undefined) {
409 meta.promptId = notification.promptId;
410 meta.requestId = notification.promptId;
411 }
412 if (notification.agentResult !== undefined) {
413 meta.agentResult = notification.agentResult;
414 }
415 return {
416 stopReason,
417 _meta: meta,
418 };
420​
421function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
422 switch (value) {
423 case "cancelled":
424 case "end_turn":
425 case "max_tokens":
426 case "max_turn_requests":
427 case "refusal":
428 return value;
429 default:
430 return "end_turn";
431 }