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

XAiAcpExtension.ts

686 lines22.4 KB

1import * as NodeOS from "node:os";
2​
3import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Ref from "effect/Ref";
7import * as Schema from "effect/Schema";
8import * as EffectAcpErrors from "effect-acp/errors";
9import type * as EffectAcpSchema from "effect-acp/schema";
10​
11import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
12​
13const XAiPromptCompleteNotification = Schema.Struct({
14 sessionId: Schema.String,
15 promptId: Schema.optional(Schema.String),
16 stopReason: Schema.optional(Schema.String),
17 agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
18});
19​
20type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
21​
22interface PendingXAiPromptCompletion {
23 readonly sessionId: string;
24 readonly promptId: string;
25 readonly deferred: Deferred.Deferred<
26 EffectAcpSchema.PromptResponse,
27 EffectAcpErrors.AcpRequestError
28 >;
30​
31const completedXAiPromptIdLimit = 128;
32const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
33const xAiRateLimitedErrorCode = -32003;
34​
35const XAiAskUserQuestionOption = Schema.Struct({
36 label: Schema.String,
37 description: Schema.optional(Schema.String),
38 preview: Schema.optional(Schema.String),
39 id: Schema.optional(Schema.String),
40});
41​
42const XAiAskUserQuestion = Schema.Struct({
43 id: Schema.optional(Schema.String),
44 question: Schema.String,
45 options: Schema.Array(XAiAskUserQuestionOption),
46 multiSelect: Schema.optional(Schema.NullOr(Schema.Boolean)),
47});
48​
49const XAiAskUserQuestionParams = Schema.Struct({
50 sessionId: Schema.String,
51 toolCallId: Schema.String,
52 questions: Schema.Array(XAiAskUserQuestion),
53 mode: Schema.Literals(["default", "plan"]),
54});
55​
56const XAiWrappedAskUserQuestionParams = Schema.Struct({
57 method: Schema.Literals(["x.ai/ask_user_question", "_x.ai/ask_user_question"]),
58 params: XAiAskUserQuestionParams,
59});
60​
61export const XAiAskUserQuestionRequest = Schema.Union([
62 XAiAskUserQuestionParams,
63 XAiWrappedAskUserQuestionParams,
64]);
65​
66type XAiAskUserQuestionRequestParams = typeof XAiAskUserQuestionParams.Type;
67type XAiAskUserQuestionRequest = typeof XAiAskUserQuestionRequest.Type;
68​
69function trimmed(value: string | undefined): string | undefined {
70 const text = value?.trim();
71 return text && text.length > 0 ? text : undefined;
73​
74function unwrapAskUserQuestionParams(
75 params: XAiAskUserQuestionRequest,
76): XAiAskUserQuestionRequestParams {
77 return "params" in params ? params.params : params;
79​
80export function extractXAiAskUserQuestions(
81 params: XAiAskUserQuestionRequest,
82): ReadonlyArray<UserInputQuestion> {
83 return unwrapAskUserQuestionParams(params).questions.map((question) => ({
84 id: question.id ?? question.question,
85 header: "Question",
86 question: question.question,
87 multiSelect: question.multiSelect === true,
88 options:
89 question.options.length > 0
90 ? question.options.map((option) => ({
91 label: option.label,
92 description: option.description ?? option.label,
93 }))
94 : [{ label: "OK", description: "Continue" }],
95 }));
97​
98interface XAiAskUserQuestionAnnotation {
99 readonly preview?: string;
100 readonly notes?: string;
102​
103interface XAiAskUserQuestionAcceptedResponse {
104 readonly outcome: "accepted";
105 readonly answers: Record<string, ReadonlyArray<string>>;
106 readonly annotations?: Record<string, XAiAskUserQuestionAnnotation>;
108​
109interface XAiAskUserQuestionCancelledResponse {
110 readonly outcome: "cancelled";
112​
113export type XAiAskUserQuestionResponse =
114 | XAiAskUserQuestionAcceptedResponse
115 | XAiAskUserQuestionCancelledResponse;
116​
117interface NormalizedXAiAnswer {
118 readonly questionText: string;
119 readonly selectedLabels: ReadonlyArray<string>;
120 readonly annotation?: XAiAskUserQuestionAnnotation;
122​
123function answerValues(answer: unknown): ReadonlyArray<string> {
124 if (Array.isArray(answer)) {
125 return answer.flatMap((entry) => {
126 const text = typeof entry === "string" ? trimmed(entry) : undefined;
127 return text ? [text] : [];
128 });
129 }
130 const text = typeof answer === "string" ? trimmed(answer) : undefined;
131 return text ? [text] : [];
133​
134function normalizeAnswerForXAi(
135 question: XAiAskUserQuestionRequestParams["questions"][number],
136 answer: unknown,
137): NormalizedXAiAnswer | undefined {
138 const values = answerValues(answer);
139 if (values.length === 0) {
140 return undefined;
141 }
142​
143 const optionByLabel = new Map(question.options.map((option) => [option.label, option]));
144 const resolvedValues = values.map((value) => ({
145 value,
146 option: optionByLabel.get(value),
147 }));
148 const selectedLabels = resolvedValues.flatMap(({ option }) => (option ? [option.label] : []));
149 const notes = resolvedValues.flatMap(({ option, value }) => (option ? [] : [value]));
150 const preview =
151 question.multiSelect === true
152 ? undefined
153 : resolvedValues.map(({ option }) => trimmed(option?.preview)).find((value) => value);
154​
155 const annotation =
156 preview || notes.length > 0
157 ? {
158 ...(preview ? { preview } : {}),
159 ...(notes.length > 0 ? { notes: notes.join("\n") } : {}),
160 }
161 : undefined;
162​
163 return {
164 questionText: question.question,
165 selectedLabels: selectedLabels.length > 0 ? selectedLabels : ["Other"],
166 ...(annotation ? { annotation } : {}),
167 };
169​
170function findQuestionAnswer(
171 answers: ProviderUserInputAnswers,
172 question: XAiAskUserQuestionRequestParams["questions"][number],
173): unknown {
174 const key = question.id ?? question.question;
175 return answers[key] ?? answers[question.question];
177​
178export function makeXAiAskUserQuestionResponse(
179 params: XAiAskUserQuestionRequest,
180 answers: ProviderUserInputAnswers,
181): XAiAskUserQuestionAcceptedResponse {
182 const questions = unwrapAskUserQuestionParams(params).questions;
183 const normalized = questions.flatMap((question) => {
184 const entry = normalizeAnswerForXAi(question, findQuestionAnswer(answers, question));
185 return entry ? [entry] : [];
186 });
187 const annotations = Object.fromEntries(
188 normalized.flatMap((entry) =>
189 entry.annotation ? [[entry.questionText, entry.annotation] as const] : [],
190 ),
191 );
192​
193 return {
194 outcome: "accepted",
195 answers: Object.fromEntries(
196 normalized.map((entry) => [entry.questionText, entry.selectedLabels]),
197 ),
198 ...(Object.keys(annotations).length > 0 ? { annotations } : {}),
199 };
201​
202export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
203 return { outcome: "cancelled" };
205​
206// ---------------------------------------------------------------------------
207// x.ai/exit_plan_mode — plan approval gate (mirrors Grok Build TUI plan window)
208// ---------------------------------------------------------------------------
209​
210const XAiExitPlanModeParams = Schema.Struct({
211 sessionId: Schema.String,
212 toolCallId: Schema.String,
213 planContent: Schema.optional(Schema.NullOr(Schema.String)),
214});
215​
216const XAiWrappedExitPlanModeParams = Schema.Struct({
217 method: Schema.Literals(["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"]),
218 params: XAiExitPlanModeParams,
219});
220​
221export const XAiExitPlanModeRequest = Schema.Union([
222 XAiExitPlanModeParams,
223 XAiWrappedExitPlanModeParams,
224]);
225​
226type XAiExitPlanModeRequestParams = typeof XAiExitPlanModeParams.Type;
227type XAiExitPlanModeRequest = typeof XAiExitPlanModeRequest.Type;
228​
229function unwrapExitPlanModeParams(params: XAiExitPlanModeRequest): XAiExitPlanModeRequestParams {
230 return "params" in params ? params.params : params;
232​
233/** Empty-state copy when Grok exits plan mode without a plan file. */
234export const XAI_EMPTY_PLAN_MARKDOWN =
235 "# No plan written yet\n\n(The agent exited plan mode without writing a plan.)";
236​
237export function extractXAiExitPlanMarkdown(
238 params: XAiExitPlanModeRequest,
239 fallback?: string | null,
240): string {
241 const content = unwrapExitPlanModeParams(params).planContent;
242 const fromRequest = typeof content === "string" ? trimmed(content) : undefined;
243 if (fromRequest) {
244 return fromRequest;
245 }
246 const fromFallback = fallback?.trim();
247 if (fromFallback && fromFallback.length > 0) {
248 return fromFallback;
249 }
250 return XAI_EMPTY_PLAN_MARKDOWN;
252​
253export type XAiExitPlanModeOutcome = "approved" | "abandoned" | "request_changes";
254​
255export interface XAiExitPlanModeResponse {
256 readonly outcome: XAiExitPlanModeOutcome;
257 readonly feedback?: string;
259​
260/**
261 * Client captured the plan for T3's proposed-plan card. Abandon the native
262 * Grok plan-approval gate so the turn unblocks; the user implements via T3 UI.
263 */
264export function makeXAiExitPlanModeCapturedResponse(feedback?: string): XAiExitPlanModeResponse {
265 return {
266 outcome: "abandoned",
267 feedback:
268 feedback ??
269 "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
270 };
272​
273function normalizeFsPath(value: string): string {
274 return value.trim().replace(/\\/g, "/").replace(/\/+$/, "");
276​
277function pathHasTraversalSegment(normalized: string): boolean {
278 return normalized.split("/").includes("..");
280​
281function addGrokSessionPrefix(
282 prefixes: Set<string>,
283 homeOrRoot: string,
284 nestedGrokDir: boolean,
285): void {
286 const root = normalizeFsPath(homeOrRoot);
287 if (!root) {
288 return;
289 }
290 prefixes.add(nestedGrokDir ? `${root}/.grok/sessions/` : `${root}/sessions/`);
292​
293/** Injected host bits so these helpers stay off `process.platform` / `process.env`. */
294export interface GrokPlanPathHost {
295 readonly platform: NodeJS.Platform;
296 readonly environment: NodeJS.ProcessEnv;
298​
299function grokPlanSessionPrefixes(environment: NodeJS.ProcessEnv): ReadonlySet<string> {
300 const prefixes = new Set<string>();
301 addGrokSessionPrefix(prefixes, NodeOS.homedir(), true);
302 addGrokSessionPrefix(prefixes, "~", true);
303 addGrokSessionPrefix(prefixes, environment.HOME ?? "", true);
304 addGrokSessionPrefix(prefixes, environment.USERPROFILE ?? "", true);
305 // ACP mock and isolated Grok spawns use a HOME that is not the server process home.
306 addGrokSessionPrefix(prefixes, "/tmp/mock-home", true);
307 const grokHome = environment.GROK_HOME ?? "";
308 addGrokSessionPrefix(prefixes, grokHome, false);
309 addGrokSessionPrefix(prefixes, grokHome, true);
310 return prefixes;
312​
313const CANONICAL_HOME_GROK_SESSION_PATH =
314 /^(?:\/home\/[^/]+|\/Users\/[^/]+|[a-zA-Z]:\/Users\/[^/]+)\/\.grok\/sessions\/(?:[^/]+\/)+plan\.md$/;
315const CASE_INSENSITIVE_CANONICAL_HOME_GROK_SESSION_PATH = new RegExp(
316 CANONICAL_HOME_GROK_SESSION_PATH.source,
317 "i",
318);
319​
320/**
321 * True when a path is Grok's session plan file under a Grok home
322 * (`~/.grok/sessions/.../plan.md`, `$HOME/.grok/sessions/...`, or `$GROK_HOME/sessions/...`).
323 * Deliberately does not match workspace files named `plan.md` (e.g. docs/plan.md
324 * or a repo-local `.grok/sessions/.../plan.md`).
325 */
326export function isGrokPlanMarkdownPath(
327 path: string | undefined | null,
328 host: GrokPlanPathHost,
329): boolean {
330 if (typeof path !== "string") {
331 return false;
332 }
333 const normalized = path.trim().replace(/\\/g, "/");
334 const win32 = host.platform === "win32";
335 const haystack = win32 ? normalized.toLowerCase() : normalized;
336 if (
337 normalized.length === 0 ||
338 !haystack.endsWith("/plan.md") ||
339 pathHasTraversalSegment(normalized)
340 ) {
341 return false;
342 }
343 for (const prefix of grokPlanSessionPrefixes(host.environment)) {
344 const needle = win32 ? prefix.toLowerCase() : prefix;
345 if (!haystack.startsWith(needle)) {
346 continue;
347 }
348 const rest = haystack.slice(needle.length);
349 // Session layout: <home>/.grok/sessions/<encoded-cwd>/<session-id>/plan.md
350 if (rest !== "plan.md" && rest.endsWith("plan.md")) {
351 return true;
352 }
353 }
354 return (
355 win32 ? CASE_INSENSITIVE_CANONICAL_HOME_GROK_SESSION_PATH : CANONICAL_HOME_GROK_SESSION_PATH
356 ).test(haystack);
358​
359/**
360 * Extract plan markdown from a Grok write/edit tool call targeting plan.md.
361 * Used so T3 can show the plan while plan mode is still active (before exit).
362 */
363export function extractGrokPlanMarkdownFromToolCallData(
364 data: Record<string, unknown> | undefined,
365 host: GrokPlanPathHost,
366): string | undefined {
367 if (!data) {
368 return undefined;
369 }
370​
371 let sawPlanWrite = false;
372 const takePlanText = (
373 value: string | undefined,
374 filePath: string | undefined,
375 ): string | undefined => {
376 if (!isGrokPlanMarkdownPath(filePath, host) || value === undefined) {
377 return undefined;
378 }
379 sawPlanWrite = true;
380 const trimmed = value.trim();
381 return trimmed.length > 0 ? trimmed : undefined;
382 };
383​
384 const rawInput = data.rawInput;
385 if (isRecord(rawInput)) {
386 const filePath =
387 (typeof rawInput.file_path === "string" ? rawInput.file_path : undefined) ??
388 (typeof rawInput.path === "string" ? rawInput.path : undefined);
389 const content = typeof rawInput.content === "string" ? rawInput.content : undefined;
390 const fromRaw = takePlanText(content, filePath);
391 if (fromRaw !== undefined) {
392 return fromRaw;
393 }
394 }
395​
396 const content = data.content;
397 if (Array.isArray(content)) {
398 for (const block of content) {
399 if (!isRecord(block) || block.type !== "diff") {
400 continue;
401 }
402 const path = typeof block.path === "string" ? block.path : undefined;
403 const newText = typeof block.newText === "string" ? block.newText : undefined;
404 const fromDiff = takePlanText(newText, path);
405 if (fromDiff !== undefined) {
406 return fromDiff;
407 }
408 }
409 }
410​
411 return sawPlanWrite ? "" : undefined;
413​
414function isRecord(value: unknown): value is Record<string, unknown> {
415 return typeof value === "object" && value !== null && !Array.isArray(value);
417​
418/**
419 * Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
420 * The underlying runtime remains unaware of xAI methods and metadata.
421 */
422export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
423 function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
424 const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
425 const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
426 const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
427 let nextPromptFallbackId = 0;
428 const allocatePromptFallbackId = Effect.sync(() => {
429 nextPromptFallbackId += 1;
430 return `t3-xai-prompt-${nextPromptFallbackId}`;
431 });
432​
433 yield* runtime.handleExtNotification(
434 "_x.ai/session/prompt_complete",
435 XAiPromptCompleteNotification,
436 (notification) =>
437 resolveXAiPromptCompletionFallback({
438 pendingRef,
439 completedPromptIdsRef,
440 notification,
441 }),
442 );
443​
444 return {
445 ...runtime,
446 start: () =>
447 runtime
448 .start()
449 .pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
450 prompt: (payload, promptOptions?) =>
451 Effect.gen(function* () {
452 const sessionId = yield* Ref.get(activeSessionIdRef);
453 if (sessionId === undefined) {
454 return yield* runtime.prompt(payload, promptOptions);
455 }
456​
457 const promptId = yield* allocatePromptFallbackId;
458 const fallback = yield* registerXAiPromptCompletionFallback(
459 pendingRef,
460 sessionId,
461 promptId,
462 );
463 const requestPayload = {
464 ...payload,
465 _meta: {
466 ...payload._meta,
467 promptId: fallback.promptId,
468 requestId: fallback.promptId,
469 },
470 } satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
471​
472 return yield* Effect.raceFirst(
473 runtime.prompt(requestPayload, promptOptions),
474 Deferred.await(fallback.deferred),
475 ).pipe(
476 Effect.tap((response) =>
477 rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
478 ),
479 Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
480 );
481 }),
482 cancel: Ref.get(activeSessionIdRef).pipe(
483 Effect.flatMap((sessionId) =>
484 sessionId === undefined
485 ? runtime.cancel
486 : abortPendingPromptCompletions(pendingRef, sessionId).pipe(
487 Effect.andThen(runtime.cancel),
488 ),
489 ),
490 ),
491 } satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
492 },
493);
494​
495const registerXAiPromptCompletionFallback = (
496 pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
497 sessionId: string,
498 promptId: string,
499) =>
500 Deferred.make<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>().pipe(
501 Effect.tap((deferred) =>
502 Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
503 ),
504 Effect.map((deferred) => ({ deferred, promptId })),
505 );
506​
507const unregisterXAiPromptCompletionFallback = (
508 pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
509 deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>,
510) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
511​
512const abortPendingPromptCompletions = (
513 pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
514 sessionId: string,
515) =>
516 Ref.modify(pendingRef, (pending) => {
517 const [toAbort, remaining] = pending.reduce<
518 [ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
519 >(
520 ([aborting, kept], entry) =>
521 entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
522 [[], []],
523 );
524 if (toAbort.length === 0) {
525 return [Effect.void, pending] as const;
526 }
527 return [
528 Effect.forEach(
529 toAbort,
530 (entry) =>
531 Deferred.succeed(
532 entry.deferred,
533 promptResponseFromXAi({
534 sessionId: entry.sessionId,
535 promptId: entry.promptId,
536 stopReason: "cancelled",
537 agentResult: null,
538 }),
539 ),
540 { concurrency: "unbounded" },
541 ).pipe(Effect.asVoid),
542 remaining,
543 ] as const;
544 }).pipe(Effect.flatten);
545​
546const resolveXAiPromptCompletionFallback = ({
547 pendingRef,
548 completedPromptIdsRef,
549 notification,
550}: {
551 readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
552 readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
553 readonly notification: XAiPromptCompleteNotification;
554}) =>
555 Ref.get(completedPromptIdsRef).pipe(
556 Effect.flatMap((completedPromptIds) => {
557 if (
558 notification.promptId !== undefined &&
559 completedPromptIds.includes(notification.promptId)
560 ) {
561 return Effect.void;
562 }
563 return Ref.modify(pendingRef, (pending) => {
564 const index =
565 notification.promptId !== undefined
566 ? pending.findIndex(
567 (entry) =>
568 entry.sessionId === notification.sessionId &&
569 entry.promptId === notification.promptId,
570 )
571 : pending.findIndex((entry) => entry.sessionId === notification.sessionId);
572 if (index < 0) {
573 return [Effect.void, pending] as const;
574 }
575 const entry = pending[index];
576 if (!entry) {
577 return [Effect.void, pending] as const;
578 }
579 return [
580 settleXAiPromptCompletion(entry.deferred, notification),
581 [...pending.slice(0, index), ...pending.slice(index + 1)],
582 ] as const;
583 }).pipe(Effect.flatten);
584 }),
585 );
586​
587const settleXAiPromptCompletion = (
588 deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>,
589 notification: XAiPromptCompleteNotification,
590) => {
591 if (notification.stopReason === "rate_limit") {
592 return Deferred.fail(
593 deferred,
594 new EffectAcpErrors.AcpRequestError({
595 code: xAiRateLimitedErrorCode,
596 errorMessage: "Grok usage limit reached. Try again later.",
597 }),
598 ).pipe(Effect.asVoid);
599 }
600 if (notification.stopReason === "error") {
601 return Deferred.fail(
602 deferred,
603 EffectAcpErrors.AcpRequestError.internalError(
604 xAiAgentResultMessage(notification.agentResult) ?? "Grok prompt failed.",
605 ),
606 ).pipe(Effect.asVoid);
607 }
608 return Deferred.succeed(deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid);
609};
610​
611function xAiAgentResultMessage(value: unknown): string | undefined {
612 if (typeof value === "string") {
613 return trimmed(value);
614 }
615 if (value === null || typeof value !== "object") {
616 return undefined;
617 }
618 const message = "message" in value ? value.message : undefined;
619 return typeof message === "string" ? trimmed(message) : undefined;
621​
622const rememberCompletedXAiPromptId = (
623 completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
624 response: EffectAcpSchema.PromptResponse,
625 fallbackPromptId: string,
626) => {
627 const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
628 return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
629 if (completedPromptIds.includes(promptId)) {
630 return completedPromptIds;
631 }
632 return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
633 });
634};
635​
636function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
637 const meta = response._meta;
638 if (meta === null || typeof meta !== "object") {
639 return undefined;
640 }
641 const promptId = meta.promptId ?? meta.requestId;
642 return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
644​
645export function promptResponseHasMissingXAiStopReason(
646 response: EffectAcpSchema.PromptResponse,
647): boolean {
648 const meta = response._meta;
649 return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
651​
652function promptResponseFromXAi(
653 notification: XAiPromptCompleteNotification,
654): EffectAcpSchema.PromptResponse {
655 const stopReason = normalizeXAiStopReason(notification.stopReason);
656 const meta: Record<string, unknown> = {
657 sessionId: notification.sessionId,
658 };
659 if (notification.stopReason === undefined) {
660 meta[xAiStopReasonMissingMetaKey] = true;
661 }
662 if (notification.promptId !== undefined) {
663 meta.promptId = notification.promptId;
664 meta.requestId = notification.promptId;
665 }
666 if (notification.agentResult !== undefined) {
667 meta.agentResult = notification.agentResult;
668 }
669 return {
670 stopReason,
671 _meta: meta,
672 };
674​
675function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
676 switch (value) {
677 case "cancelled":
678 case "end_turn":
679 case "max_tokens":
680 case "max_turn_requests":
681 case "refusal":
682 return value;
683 default:
684 return "end_turn";
685 }