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
| 1 | import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts"; |
| 2 | import * as Cause from "effect/Cause"; |
| 3 | import * as Deferred from "effect/Deferred"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Fiber from "effect/Fiber"; |
| 6 | import * as Ref from "effect/Ref"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import * as EffectAcpErrors from "effect-acp/errors"; |
| 9 | import type * as EffectAcpSchema from "effect-acp/compat"; |
| 10 | |
| 11 | import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; |
| 12 | import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel"; |
| 13 | |
| 14 | export const xAiRateLimitedErrorCode = -32003; |
| 15 | const completedXAiPromptIdLimit = 128; |
| 16 | |
| 17 | const XAiPromptCompleteNotification = Schema.Struct({ |
| 18 | sessionId: Schema.String, |
| 19 | promptId: Schema.optional(Schema.String), |
| 20 | stopReason: Schema.optional(Schema.String), |
| 21 | agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)), |
| 22 | }); |
| 23 | |
| 24 | type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type; |
| 25 | |
| 26 | const XAiSessionUpdateNotification = Schema.Struct({ |
| 27 | sessionId: Schema.String, |
| 28 | update: Schema.Struct({ |
| 29 | sessionUpdate: Schema.String, |
| 30 | prompt_id: Schema.optional(Schema.String), |
| 31 | promptId: Schema.optional(Schema.String), |
| 32 | stop_reason: Schema.optional(Schema.String), |
| 33 | stopReason: Schema.optional(Schema.String), |
| 34 | agent_result: Schema.optional(Schema.NullOr(Schema.Unknown)), |
| 35 | child_session_id: Schema.optional(Schema.String), |
| 36 | status: Schema.optional(Schema.String), |
| 37 | output: Schema.optional(Schema.NullOr(Schema.String)), |
| 38 | error: Schema.optional(Schema.NullOr(Schema.String)), |
| 39 | }), |
| 40 | _meta: Schema.optional(Schema.Unknown), |
| 41 | }); |
| 42 | |
| 43 | type XAiSessionUpdateNotification = typeof XAiSessionUpdateNotification.Type; |
| 44 | |
| 45 | const decodeXAiSessionUpdateNotification = Schema.decodeUnknownEffect(XAiSessionUpdateNotification); |
| 46 | |
| 47 | const xAiSessionNotificationMethods = [ |
| 48 | "x.ai/session_notification", |
| 49 | "_x.ai/session_notification", |
| 50 | "_x.ai/session/update", |
| 51 | ] as const; |
| 52 | |
| 53 | const XAI_TASK_COMPLETED_PROMPT_ID_PREFIX = "task-completed-"; |
| 54 | |
| 55 | export function xAiPromptCompleteFromSessionUpdate( |
| 56 | notification: XAiSessionUpdateNotification, |
| 57 | ): XAiPromptCompleteNotification | null { |
| 58 | const update = notification.update; |
| 59 | if (update.sessionUpdate !== "turn_completed") { |
| 60 | return null; |
| 61 | } |
| 62 | const promptId = nonEmptyString(update.prompt_id) ?? nonEmptyString(update.promptId); |
| 63 | // Require prompt identity to avoid matching background completions or unrelated turns. |
| 64 | if (promptId === undefined || promptId.startsWith(XAI_TASK_COMPLETED_PROMPT_ID_PREFIX)) { |
| 65 | return null; |
| 66 | } |
| 67 | const stopReason = nonEmptyString(update.stop_reason) ?? nonEmptyString(update.stopReason); |
| 68 | return { |
| 69 | sessionId: notification.sessionId, |
| 70 | promptId, |
| 71 | ...(stopReason === undefined ? {} : { stopReason }), |
| 72 | ...(update.agent_result === undefined ? {} : { agentResult: update.agent_result }), |
| 73 | }; |
| 74 | } |
| 75 | |
| 76 | /** Background command wakes use their own task-completed-* prompt IDs. */ |
| 77 | export function isXAiTaskCompletedWakeNotification( |
| 78 | notification: EffectAcpSchema.SessionNotification, |
| 79 | ): boolean { |
| 80 | const promptId = notification._meta?.promptId; |
| 81 | return typeof promptId === "string" && promptId.startsWith(XAI_TASK_COMPLETED_PROMPT_ID_PREFIX); |
| 82 | } |
| 83 | |
| 84 | interface PendingXAiPromptCompletion { |
| 85 | readonly sessionId: string; |
| 86 | readonly promptId: string; |
| 87 | readonly deferred: Deferred.Deferred< |
| 88 | EffectAcpSchema.PromptResponse, |
| 89 | EffectAcpErrors.AcpRequestError |
| 90 | >; |
| 91 | } |
| 92 | |
| 93 | export interface XAiAcpSubagentUpdate { |
| 94 | readonly nativeTaskId: string; |
| 95 | readonly prompt: string; |
| 96 | readonly title: string | null; |
| 97 | readonly model: string | null; |
| 98 | readonly status: "running" | "completed" | "failed"; |
| 99 | readonly childSessionId: string | null; |
| 100 | readonly result: string | null; |
| 101 | /** Defaults to true; false also projects a normal tool item for hydration. */ |
| 102 | readonly suppressNormalTool?: boolean; |
| 103 | } |
| 104 | |
| 105 | export interface XAiAcpBackgroundToolMutation { |
| 106 | readonly taskId: string; |
| 107 | readonly status: "running" | "completed" | "failed"; |
| 108 | readonly appendOutput: string; |
| 109 | } |
| 110 | |
| 111 | export interface XAiAcpSubagentEndNotice { |
| 112 | readonly childSessionId: string; |
| 113 | readonly status: "completed" | "failed"; |
| 114 | } |
| 115 | |
| 116 | const XAI_UUID_RE = "[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}"; |
| 117 | |
| 118 | function unknownRecord(value: unknown): Record<string, unknown> | undefined { |
| 119 | return typeof value === "object" && value !== null && !Array.isArray(value) |
| 120 | ? (value as Record<string, unknown>) |
| 121 | : undefined; |
| 122 | } |
| 123 | |
| 124 | function nonEmptyString(value: unknown): string | undefined { |
| 125 | return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; |
| 126 | } |
| 127 | |
| 128 | function titleKey(toolCall: AcpToolCallState): string { |
| 129 | return (toolCall.title ?? "").trim().toLowerCase(); |
| 130 | } |
| 131 | |
| 132 | function decodeByteText(value: unknown): string | undefined { |
| 133 | if (typeof value === "string") return nonEmptyString(value); |
| 134 | if (!Array.isArray(value)) return undefined; |
| 135 | if (value.length === 0) return undefined; |
| 136 | if (!value.every((entry) => typeof entry === "number")) return undefined; |
| 137 | try { |
| 138 | return nonEmptyString(new TextDecoder().decode(Uint8Array.from(value as number[]))); |
| 139 | } catch { |
| 140 | return undefined; |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | function xAiToolOutputText(toolCall: AcpToolCallState): string | undefined { |
| 145 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 146 | if (rawOutput !== undefined) { |
| 147 | const direct = |
| 148 | nonEmptyString(rawOutput.text) ?? |
| 149 | nonEmptyString(rawOutput.output_for_prompt) ?? |
| 150 | decodeByteText(rawOutput.output); |
| 151 | if (direct !== undefined) return direct; |
| 152 | const result = unknownRecord(rawOutput.Result) ?? unknownRecord(rawOutput.result); |
| 153 | if (result !== undefined) { |
| 154 | const nested = |
| 155 | nonEmptyString(result.output) ?? |
| 156 | nonEmptyString(result.text) ?? |
| 157 | decodeByteText(result.output); |
| 158 | if (nested !== undefined) return nested; |
| 159 | } |
| 160 | } |
| 161 | if (typeof toolCall.data.rawOutput === "string") { |
| 162 | return nonEmptyString(toolCall.data.rawOutput); |
| 163 | } |
| 164 | const content = toolCall.data.content; |
| 165 | if (!Array.isArray(content)) return undefined; |
| 166 | const text = content |
| 167 | .flatMap((entry) => { |
| 168 | const record = unknownRecord(entry); |
| 169 | const nested = unknownRecord(record?.content); |
| 170 | return nonEmptyString(nested?.text) ?? nonEmptyString(record?.text) ?? []; |
| 171 | }) |
| 172 | .join("\n") |
| 173 | .trim(); |
| 174 | return text.length > 0 ? text : undefined; |
| 175 | } |
| 176 | |
| 177 | function firstUuidMatch(text: string, pattern: RegExp): string | undefined { |
| 178 | const match = pattern.exec(text); |
| 179 | return match?.[1]; |
| 180 | } |
| 181 | |
| 182 | function extractXAiChildSessionId(output: string | undefined): string | null { |
| 183 | if (output === undefined) return null; |
| 184 | return ( |
| 185 | firstUuidMatch(output, new RegExp(`(?:^|\\n)\\s*Agent ID:\\s*(${XAI_UUID_RE})\\b`, "i")) ?? |
| 186 | firstUuidMatch(output, new RegExp(`(?:^|\\n)\\s*subagent_id:\\s*(${XAI_UUID_RE})\\b`, "i")) ?? |
| 187 | firstUuidMatch(output, new RegExp(`===\\s*Task\\s+(${XAI_UUID_RE})\\s*===`, "i")) ?? |
| 188 | null |
| 189 | ); |
| 190 | } |
| 191 | |
| 192 | function isXAiAsyncSpawnAck(output: string | undefined): boolean { |
| 193 | if (output === undefined) return false; |
| 194 | if (/subagent started in background/i.test(output)) return true; |
| 195 | return ( |
| 196 | new RegExp(`subagent_id:\\s*${XAI_UUID_RE}`, "i").test(output) && |
| 197 | /get_command_or_subagent_output/i.test(output) |
| 198 | ); |
| 199 | } |
| 200 | |
| 201 | function isXAiMonitorStartAck(output: string | undefined): boolean { |
| 202 | if (output === undefined) return false; |
| 203 | return /monitor started\s*\(\s*task\s+/i.test(output); |
| 204 | } |
| 205 | |
| 206 | function isXAiSpawnOrTaskTool( |
| 207 | toolCall: AcpToolCallState, |
| 208 | rawInput: Record<string, unknown> | undefined, |
| 209 | ): boolean { |
| 210 | const title = titleKey(toolCall); |
| 211 | if (title === "task" || title === "spawn_subagent" || title.includes("spawn subagent")) { |
| 212 | return true; |
| 213 | } |
| 214 | const variant = nonEmptyString(rawInput?.variant)?.toLowerCase(); |
| 215 | if (variant === "cursortask" || variant === "task" || variant === "spawn_subagent") { |
| 216 | return true; |
| 217 | } |
| 218 | if (nonEmptyString(rawInput?.subagent_type) !== undefined) return true; |
| 219 | if (nonEmptyString(rawInput?.subagentType) !== undefined) return true; |
| 220 | return false; |
| 221 | } |
| 222 | |
| 223 | function isXAiGetSubagentOutputTool( |
| 224 | toolCall: AcpToolCallState, |
| 225 | rawInput: Record<string, unknown> | undefined, |
| 226 | ): boolean { |
| 227 | const title = titleKey(toolCall); |
| 228 | if ( |
| 229 | title === "get_command_or_subagent_output" || |
| 230 | title.includes("get_command_or_subagent_output") || |
| 231 | title === "wait_commands_or_subagents" |
| 232 | ) { |
| 233 | return true; |
| 234 | } |
| 235 | const variant = nonEmptyString(rawInput?.variant)?.toLowerCase(); |
| 236 | if (variant === "taskoutput" || variant === "task_output") return true; |
| 237 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 238 | const outputType = nonEmptyString(rawOutput?.type)?.toLowerCase(); |
| 239 | if (outputType === "taskoutput" || outputType === "task_output") return true; |
| 240 | if (title.startsWith("[subagent:") && Array.isArray(rawInput?.task_ids)) return true; |
| 241 | return false; |
| 242 | } |
| 243 | |
| 244 | export function isXAiMonitorTool(toolCall: AcpToolCallState): boolean { |
| 245 | const title = titleKey(toolCall); |
| 246 | if (title === "monitor" || title.startsWith("monitor ")) return true; |
| 247 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 248 | const variant = nonEmptyString(rawInput?.variant)?.toLowerCase(); |
| 249 | if (variant === "monitor") return true; |
| 250 | // Start ACK titles can be generic; the structured Monitor envelope remains authoritative. |
| 251 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 252 | const outputType = nonEmptyString(rawOutput?.type)?.toLowerCase(); |
| 253 | if (outputType === "monitor") return true; |
| 254 | // Older clients send plain Text ACKs; these still identify the monitor after title rewrites. |
| 255 | return isXAiMonitorStartAck(xAiToolOutputText(toolCall)); |
| 256 | } |
| 257 | |
| 258 | /** |
| 259 | * BackgroundTaskStarted completes the tool call while the shell process still runs. |
| 260 | * The task ends on a completion notification or completed TaskOutput for its task id. |
| 261 | */ |
| 262 | export function xAiBackgroundShellTaskId(toolCall: AcpToolCallState): string | undefined { |
| 263 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 264 | return nonEmptyString(rawOutput?.type) === "BackgroundTaskStarted" |
| 265 | ? nonEmptyString(rawOutput?.task_id) |
| 266 | : undefined; |
| 267 | } |
| 268 | |
| 269 | export function extractXAiMonitorTaskId(toolCall: AcpToolCallState): string | undefined { |
| 270 | const backgroundShellTaskId = xAiBackgroundShellTaskId(toolCall); |
| 271 | if (backgroundShellTaskId !== undefined) return backgroundShellTaskId; |
| 272 | if (!isXAiMonitorTool(toolCall)) return undefined; |
| 273 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 274 | if (rawOutput !== undefined && nonEmptyString(rawOutput.type)?.toLowerCase() === "monitor") { |
| 275 | const structured = nonEmptyString(rawOutput.taskId) ?? nonEmptyString(rawOutput.task_id); |
| 276 | if (structured !== undefined) return structured; |
| 277 | } |
| 278 | const output = xAiToolOutputText(toolCall); |
| 279 | if (output !== undefined) { |
| 280 | const fromAck = firstUuidMatch( |
| 281 | output, |
| 282 | new RegExp(`monitor started\\s*\\(\\s*task\\s+(${XAI_UUID_RE})\\b`, "i"), |
| 283 | ); |
| 284 | if (fromAck !== undefined) return fromAck; |
| 285 | } |
| 286 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 287 | return ( |
| 288 | nonEmptyString(rawInput?.task_id) ?? |
| 289 | nonEmptyString(rawInput?.taskId) ?? |
| 290 | (Array.isArray(rawInput?.task_ids) ? nonEmptyString(rawInput.task_ids[0]) : undefined) |
| 291 | ); |
| 292 | } |
| 293 | |
| 294 | /** Persistent monitors must not hold root-turn deferred finalize. */ |
| 295 | export function isXAiPersistentMonitor(toolCall: AcpToolCallState): boolean { |
| 296 | if (!isXAiMonitorTool(toolCall)) return false; |
| 297 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 298 | if (rawOutput !== undefined && nonEmptyString(rawOutput.type)?.toLowerCase() === "monitor") { |
| 299 | return rawOutput.persistent === true; |
| 300 | } |
| 301 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 302 | return rawInput?.persistent === true; |
| 303 | } |
| 304 | |
| 305 | export function extractXAiBackgroundTaskCompletion(toolCall: AcpToolCallState): ReadonlyArray<{ |
| 306 | readonly taskId: string; |
| 307 | readonly status: "running" | "completed" | "failed"; |
| 308 | readonly appendOutput: string; |
| 309 | }> { |
| 310 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 311 | if (!isXAiGetSubagentOutputTool(toolCall, rawInput)) return []; |
| 312 | const text = xAiToolOutputText(toolCall); |
| 313 | const status = statusFromGetOutputTool(toolCall, text); |
| 314 | const appendOutput = resultFromGetOutputTool(toolCall, text) ?? ""; |
| 315 | // Prefer the completed identity from the result/header over the request list |
| 316 | // (one call can poll multiple task_ids). |
| 317 | // Command task ids can be `call-<uuid>-<index>`; subagent ids stay UUID-only. |
| 318 | const resultTaskId = |
| 319 | structuredTaskIdFromGetOutputTool(toolCall) ?? resultTaskIdFromGetOutputTool(toolCall, text); |
| 320 | if (resultTaskId !== undefined) { |
| 321 | return [{ taskId: resultTaskId, status, appendOutput }]; |
| 322 | } |
| 323 | const requestIds: string[] = []; |
| 324 | const push = (value: unknown) => { |
| 325 | const id = nonEmptyString(value); |
| 326 | if (id !== undefined && new RegExp(`^${XAI_UUID_RE}$`, "i").test(id)) { |
| 327 | requestIds.push(id); |
| 328 | } |
| 329 | }; |
| 330 | if (Array.isArray(rawInput?.task_ids)) { |
| 331 | for (const entry of rawInput.task_ids) push(entry); |
| 332 | } |
| 333 | push(rawInput?.task_id); |
| 334 | push(rawInput?.taskId); |
| 335 | const unique = [...new Set(requestIds)]; |
| 336 | return unique.map((taskId) => ({ taskId, status, appendOutput })); |
| 337 | } |
| 338 | |
| 339 | /** |
| 340 | * A finished kill_command_or_subagent call is the genuine end signal for every |
| 341 | * task id it names, even without a separate `x.ai/task_completed` notification. |
| 342 | * A failed kill is not proof the target stopped, so leave the existing |
| 343 | * task state unchanged until a genuine terminal signal arrives. |
| 344 | */ |
| 345 | export function extractXAiKilledBackgroundTasks(toolCall: AcpToolCallState): ReadonlyArray<{ |
| 346 | readonly taskId: string; |
| 347 | readonly status: "running" | "completed" | "failed"; |
| 348 | readonly appendOutput: string; |
| 349 | }> { |
| 350 | const title = titleKey(toolCall); |
| 351 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 352 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 353 | const variant = nonEmptyString(rawInput?.variant)?.toLowerCase(); |
| 354 | const legacy = title.includes("kill_command_or_subagent") || variant === "kill"; |
| 355 | if (!legacy && variant !== "killtask" && rawOutput?.type !== "KillTask") return []; |
| 356 | if (toolCall.status !== "completed") return []; |
| 357 | // Grok nests the outcome under Result; only a missing, killed or already_exited one ends the task. |
| 358 | const outcome = rawOutput?.outcome ?? unknownRecord(rawOutput?.Result)?.outcome; |
| 359 | if (!legacy && outcome !== undefined && outcome !== "killed" && outcome !== "already_exited") |
| 360 | return []; |
| 361 | const taskIds: string[] = []; |
| 362 | const push = (value: unknown) => { |
| 363 | const id = nonEmptyString(value); |
| 364 | if (id !== undefined) taskIds.push(id); |
| 365 | }; |
| 366 | if (Array.isArray(rawInput?.task_ids)) { |
| 367 | for (const entry of rawInput.task_ids) push(entry); |
| 368 | } |
| 369 | push(rawInput?.task_id); |
| 370 | push(rawInput?.taskId); |
| 371 | return [...new Set(taskIds)].map((taskId) => ({ |
| 372 | taskId, |
| 373 | status: "completed" as const, |
| 374 | appendOutput: "", |
| 375 | })); |
| 376 | } |
| 377 | |
| 378 | const XAiTaskLifecycleNotification = Schema.Struct({ |
| 379 | sessionId: Schema.String, |
| 380 | update: Schema.Struct({ |
| 381 | sessionUpdate: Schema.String, |
| 382 | task_id: Schema.optional(Schema.String), |
| 383 | tool_call_id: Schema.optional(Schema.String), |
| 384 | command: Schema.optional(Schema.String), |
| 385 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 386 | monitor_description: Schema.optional(Schema.NullOr(Schema.String)), |
| 387 | task_snapshot: Schema.optional( |
| 388 | Schema.Struct({ |
| 389 | task_id: Schema.optional(Schema.String), |
| 390 | output: Schema.optional(Schema.String), |
| 391 | exit_code: Schema.optional(Schema.NullOr(Schema.Number)), |
| 392 | command: Schema.optional(Schema.String), |
| 393 | display_command: Schema.optional(Schema.NullOr(Schema.String)), |
| 394 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 395 | kind: Schema.optional(Schema.String), |
| 396 | }), |
| 397 | ), |
| 398 | }), |
| 399 | _meta: Schema.optional(Schema.Unknown), |
| 400 | }); |
| 401 | |
| 402 | type XAiTaskLifecycleNotification = typeof XAiTaskLifecycleNotification.Type; |
| 403 | |
| 404 | export interface XAiBackgroundTaskLifecycleMutation { |
| 405 | readonly sessionId: string; |
| 406 | readonly taskId: string; |
| 407 | readonly status: "running" | "completed" | "failed"; |
| 408 | readonly output?: string; |
| 409 | readonly report?: |
| 410 | | { readonly kind: "command"; readonly label?: string; readonly exitCode?: number } |
| 411 | | { readonly kind: "monitor"; readonly label?: string }; |
| 412 | } |
| 413 | |
| 414 | function xAiBackgroundTaskReport( |
| 415 | update: XAiTaskLifecycleNotification["update"], |
| 416 | ): XAiBackgroundTaskLifecycleMutation["report"] { |
| 417 | const snapshot = update.task_snapshot; |
| 418 | const monitorDescription = nonEmptyString(update.monitor_description ?? undefined); |
| 419 | const displayCommand = nonEmptyString(snapshot?.display_command ?? undefined); |
| 420 | const isMonitor = |
| 421 | snapshot?.kind === "monitor" || |
| 422 | monitorDescription !== undefined || |
| 423 | displayCommand?.startsWith("[monitor]") === true; |
| 424 | const isCommand = |
| 425 | snapshot?.kind === "bash" || snapshot?.command !== undefined || update.command !== undefined; |
| 426 | if (!isMonitor && !isCommand) return undefined; |
| 427 | const label = |
| 428 | monitorDescription ?? |
| 429 | nonEmptyString(snapshot?.description ?? undefined) ?? |
| 430 | nonEmptyString(update.description ?? undefined) ?? |
| 431 | displayCommand?.replace(/^\[monitor\]\s*/, "") ?? |
| 432 | nonEmptyString(snapshot?.command) ?? |
| 433 | nonEmptyString(update.command); |
| 434 | const named = label === undefined ? {} : { label }; |
| 435 | if (isMonitor) return { kind: "monitor", ...named }; |
| 436 | const exitCode = snapshot?.exit_code; |
| 437 | return { kind: "command", ...named, ...(typeof exitCode === "number" ? { exitCode } : {}) }; |
| 438 | } |
| 439 | |
| 440 | export function xAiBackgroundTaskLifecycleMutation( |
| 441 | notification: XAiTaskLifecycleNotification, |
| 442 | status: "running" | "completed", |
| 443 | ): XAiBackgroundTaskLifecycleMutation | null { |
| 444 | const update = notification.update; |
| 445 | const taskId = |
| 446 | nonEmptyString(update.task_snapshot?.task_id) ?? |
| 447 | nonEmptyString(update.task_id) ?? |
| 448 | nonEmptyString(update.tool_call_id); |
| 449 | if (taskId === undefined) return null; |
| 450 | const exitCode = update.task_snapshot?.exit_code; |
| 451 | const output = update.task_snapshot?.output; |
| 452 | const report = xAiBackgroundTaskReport(update); |
| 453 | return { |
| 454 | sessionId: notification.sessionId, |
| 455 | taskId, |
| 456 | status: |
| 457 | status === "completed" && typeof exitCode === "number" && exitCode !== 0 ? "failed" : status, |
| 458 | ...(output === undefined ? {} : { output }), |
| 459 | ...(report === undefined ? {} : { report }), |
| 460 | }; |
| 461 | } |
| 462 | |
| 463 | /** Track both x.ai/task_* and legacy _x.ai/task_*; background tasks can survive cancellation. */ |
| 464 | export const registerXAiBackgroundTaskTracking = ( |
| 465 | runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "handleExtNotification">, |
| 466 | apply: (mutation: XAiBackgroundTaskLifecycleMutation) => Effect.Effect<void>, |
| 467 | ): Effect.Effect<void, EffectAcpErrors.AcpError> => |
| 468 | Effect.forEach( |
| 469 | [ |
| 470 | ["x.ai/task_backgrounded", "running"], |
| 471 | ["_x.ai/task_backgrounded", "running"], |
| 472 | ["x.ai/task_completed", "completed"], |
| 473 | ["_x.ai/task_completed", "completed"], |
| 474 | ] as const, |
| 475 | ([method, status]) => |
| 476 | runtime.handleExtNotification(method, XAiTaskLifecycleNotification, (notification) => { |
| 477 | const mutation = xAiBackgroundTaskLifecycleMutation(notification, status); |
| 478 | return mutation === null ? Effect.void : apply(mutation); |
| 479 | }), |
| 480 | { discard: true }, |
| 481 | ); |
| 482 | |
| 483 | /** Sent on the parent session; will_wake means a subagent-completed-<id> turn follows. */ |
| 484 | export interface XAiSubagentFinishedNotice { |
| 485 | readonly sessionId: string; |
| 486 | readonly childSessionId: string; |
| 487 | readonly status: "completed" | "failed" | "cancelled"; |
| 488 | readonly result: string | null; |
| 489 | } |
| 490 | |
| 491 | export function xAiSubagentFinishedNotice( |
| 492 | notification: XAiSessionUpdateNotification, |
| 493 | ): XAiSubagentFinishedNotice | null { |
| 494 | const update = notification.update; |
| 495 | const childSessionId = nonEmptyString(update.child_session_id); |
| 496 | if (update.sessionUpdate !== "subagent_finished" || childSessionId === undefined) return null; |
| 497 | const status = update.status; |
| 498 | if (status !== "completed" && status !== "failed" && status !== "cancelled") return null; |
| 499 | const text = status === "completed" ? update.output : update.error; |
| 500 | return { |
| 501 | sessionId: notification.sessionId, |
| 502 | childSessionId, |
| 503 | status, |
| 504 | result: nonEmptyString(text ?? undefined) ?? null, |
| 505 | }; |
| 506 | } |
| 507 | |
| 508 | export const registerXAiSubagentFinished = ( |
| 509 | runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "handleExtNotification">, |
| 510 | finish: (notice: XAiSubagentFinishedNotice) => Effect.Effect<void>, |
| 511 | ): Effect.Effect<void> => |
| 512 | Effect.forEach( |
| 513 | xAiSessionNotificationMethods, |
| 514 | (method) => |
| 515 | runtime.handleExtNotification(method, XAiSessionUpdateNotification, (notification) => { |
| 516 | const notice = xAiSubagentFinishedNotice(notification); |
| 517 | return notice === null ? Effect.void : finish(notice); |
| 518 | }), |
| 519 | { discard: true }, |
| 520 | ); |
| 521 | |
| 522 | function isGenericAcpToolTitle(title: string | undefined): boolean { |
| 523 | const key = (title ?? "").trim().toLowerCase(); |
| 524 | return key.length === 0 || key === "tool" || key === "tool call" || key === "terminal"; |
| 525 | } |
| 526 | |
| 527 | function resolveXAiAcpToolTitle(toolCall: AcpToolCallState): string | undefined { |
| 528 | if (!isGenericAcpToolTitle(toolCall.title)) { |
| 529 | return nonEmptyString(toolCall.title); |
| 530 | } |
| 531 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 532 | const description = nonEmptyString(rawInput?.description); |
| 533 | const variant = nonEmptyString(rawInput?.variant)?.toLowerCase(); |
| 534 | if (description !== undefined) { |
| 535 | if (variant === "monitor" && !description.toLowerCase().startsWith("monitor")) { |
| 536 | return `Monitor: ${description}`; |
| 537 | } |
| 538 | return description; |
| 539 | } |
| 540 | if (variant === "monitor") return "Monitor"; |
| 541 | if (variant === "task" || variant === "cursortask" || variant === "spawn_subagent") { |
| 542 | return "Task"; |
| 543 | } |
| 544 | if (variant === "taskoutput" || variant === "task_output") return "Task output"; |
| 545 | if (variant !== undefined) { |
| 546 | return variant; |
| 547 | } |
| 548 | const command = |
| 549 | nonEmptyString(rawInput?.command) ?? |
| 550 | nonEmptyString(unknownRecord(toolCall.data.rawOutput)?.command); |
| 551 | if (command !== undefined) { |
| 552 | if (command.length <= 80) return command; |
| 553 | const splitsPair = |
| 554 | /[\uD800-\uDBFF]/.test(command.charAt(76)) && /[\uDC00-\uDFFF]/.test(command.charAt(77)); |
| 555 | return `${command.slice(0, splitsPair ? 76 : 77)}...`; |
| 556 | } |
| 557 | return nonEmptyString(toolCall.title); |
| 558 | } |
| 559 | |
| 560 | /** Grok 1.0.41 monitor ticks report exit_code 0 before ending via _x.ai/task_completed. */ |
| 561 | // Grok calls MCP tools through its `use_tool` built-in as "<server>__<tool>" and wraps results as |
| 562 | // { type: "MCP", output: { OkayOutput } | { Error } }; rewrite both into the generic ACP MCP shapes. |
| 563 | function normalizeXAiMcpToolCall(toolCall: AcpToolCallState): AcpToolCallState { |
| 564 | const meta = unknownRecord(toolCall.data.meta); |
| 565 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 566 | const toolName = nonEmptyString(rawInput?.tool_name) ?? ""; |
| 567 | const separator = toolName.indexOf("__"); |
| 568 | const isUseTool = |
| 569 | unknownRecord(meta?.["x.ai/tool"])?.name === "use_tool" && |
| 570 | separator > 0 && |
| 571 | separator + 2 < toolName.length; |
| 572 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 573 | const result = rawOutput?.type === "MCP" ? unknownRecord(rawOutput.output) : undefined; |
| 574 | const text = |
| 575 | typeof result?.Error === "string" |
| 576 | ? result.Error |
| 577 | : typeof result?.OkayOutput === "string" |
| 578 | ? result.OkayOutput |
| 579 | : undefined; |
| 580 | if (!isUseTool && text === undefined) return toolCall; |
| 581 | return { |
| 582 | ...toolCall, |
| 583 | data: { |
| 584 | ...toolCall.data, |
| 585 | ...(isUseTool |
| 586 | ? { |
| 587 | meta: { ...meta, is_mcp_tool_call: true }, |
| 588 | rawInput: { |
| 589 | server: toolName.slice(0, separator), |
| 590 | tool: toolName.slice(separator + 2), |
| 591 | arguments: unknownRecord(rawInput?.tool_input) ?? {}, |
| 592 | }, |
| 593 | } |
| 594 | : {}), |
| 595 | ...(text === undefined |
| 596 | ? {} |
| 597 | : { |
| 598 | rawOutput: { |
| 599 | ...(typeof result?.Error === "string" ? { isError: true } : {}), |
| 600 | content: [{ type: "text", text }], |
| 601 | }, |
| 602 | }), |
| 603 | }, |
| 604 | }; |
| 605 | } |
| 606 | |
| 607 | export function normalizeXAiAcpToolCallState(incoming: AcpToolCallState): AcpToolCallState { |
| 608 | const toolCall = normalizeXAiMcpToolCall(incoming); |
| 609 | const resolvedTitle = resolveXAiAcpToolTitle(toolCall); |
| 610 | const withTitle = |
| 611 | resolvedTitle !== undefined && resolvedTitle !== toolCall.title |
| 612 | ? { ...toolCall, title: resolvedTitle } |
| 613 | : toolCall; |
| 614 | |
| 615 | const rawOutput = unknownRecord(withTitle.data.rawOutput); |
| 616 | const outputType = nonEmptyString(rawOutput?.type)?.toLowerCase(); |
| 617 | const reportedRunning = withTitle.status === "inProgress" || withTitle.status === "pending"; |
| 618 | if (outputType === "bash" && !reportedRunning) { |
| 619 | // Keep exit-code keys aligned with adapter commandExitCode. |
| 620 | const exitCode = ["exit_code", "exitCode", "code"] |
| 621 | .map((key) => rawOutput?.[key]) |
| 622 | .find((value) => typeof value === "number" && Number.isInteger(value)); |
| 623 | if (typeof exitCode === "number") { |
| 624 | if (exitCode === 0 && (xAiToolOutputText(withTitle)?.trim().length ?? 0) === 0) { |
| 625 | return { ...withTitle, status: "inProgress" }; |
| 626 | } |
| 627 | return { |
| 628 | ...withTitle, |
| 629 | status: exitCode === 0 ? "completed" : "failed", |
| 630 | }; |
| 631 | } |
| 632 | } |
| 633 | if (xAiBackgroundShellTaskId(withTitle) !== undefined) { |
| 634 | return { ...withTitle, status: "inProgress" }; |
| 635 | } |
| 636 | if (!isXAiMonitorTool(withTitle)) { |
| 637 | return withTitle; |
| 638 | } |
| 639 | if (outputType === "monitor") { |
| 640 | return { ...withTitle, status: "inProgress" }; |
| 641 | } |
| 642 | const output = xAiToolOutputText(withTitle); |
| 643 | if (withTitle.status === "completed" && isXAiMonitorStartAck(output)) { |
| 644 | return { ...withTitle, status: "inProgress" }; |
| 645 | } |
| 646 | return withTitle; |
| 647 | } |
| 648 | |
| 649 | export function extractXAiAcpBackgroundToolMutation( |
| 650 | text: string, |
| 651 | ): ReadonlyArray<XAiAcpBackgroundToolMutation> { |
| 652 | const mutations: XAiAcpBackgroundToolMutation[] = []; |
| 653 | |
| 654 | const eventRe = new RegExp( |
| 655 | `<monitor-event\\s+task_id=["']?(${XAI_UUID_RE})["']?\\s*>\\s*([\\s\\S]*?)\\s*</monitor-event>`, |
| 656 | "gi", |
| 657 | ); |
| 658 | for (const eventMatch of text.matchAll(eventRe)) { |
| 659 | if (eventMatch[1] === undefined) continue; |
| 660 | const line = (eventMatch[2] ?? "").trim(); |
| 661 | mutations.push({ |
| 662 | taskId: eventMatch[1], |
| 663 | status: "running", |
| 664 | appendOutput: line.length > 0 ? `${line}\n` : "", |
| 665 | }); |
| 666 | } |
| 667 | |
| 668 | const batchedRe = new RegExp( |
| 669 | `<monitor\\s[^>]*task_id=["']?(${XAI_UUID_RE})["']?[^>]*>\\s*([\\s\\S]*?)\\s*</monitor>`, |
| 670 | "gi", |
| 671 | ); |
| 672 | for (const batchedMatch of text.matchAll(batchedRe)) { |
| 673 | if (batchedMatch[1] === undefined) continue; |
| 674 | const lines = (batchedMatch[2] ?? "").trim(); |
| 675 | mutations.push({ |
| 676 | taskId: batchedMatch[1], |
| 677 | status: "running", |
| 678 | appendOutput: lines.length > 0 ? `${lines}\n` : "", |
| 679 | }); |
| 680 | } |
| 681 | |
| 682 | const endedRe = new RegExp(`Monitor\\s+["']?(${XAI_UUID_RE})["']?\\s+ended`, "gi"); |
| 683 | for (const endedMatch of text.matchAll(endedRe)) { |
| 684 | if (endedMatch[1] === undefined) continue; |
| 685 | // Only the monitor header describes outcome; output can contain error words without failure. |
| 686 | const outcomeClause = (endedMatch[0] ?? "").trim(); |
| 687 | const afterHeader = text.slice((endedMatch.index ?? 0) + endedMatch[0].length); |
| 688 | const outcomeTail = afterHeader.split(/\n/)[0] ?? ""; |
| 689 | const outcome = `${outcomeClause}${outcomeTail}`; |
| 690 | const summary = text.replace(/<\/?system-reminder>/gi, "").trim(); |
| 691 | mutations.push({ |
| 692 | taskId: endedMatch[1], |
| 693 | status: |
| 694 | /exited\s*\(\s*code\s*0\s*\)/i.test(outcome) || /ended cleanly/i.test(outcome) |
| 695 | ? "completed" |
| 696 | : /exited|failed|error|signal/i.test(outcome) |
| 697 | ? "failed" |
| 698 | : "completed", |
| 699 | appendOutput: summary.length > 0 ? `${summary}\n` : "Monitor ended.\n", |
| 700 | }); |
| 701 | } |
| 702 | |
| 703 | return mutations; |
| 704 | } |
| 705 | |
| 706 | function stripLeadingBalancedParenGroup(text: string): string { |
| 707 | const trimmed = text.replace(/^\s+/, ""); |
| 708 | if (!trimmed.startsWith("(")) return trimmed; |
| 709 | let depth = 0; |
| 710 | for (let index = 0; index < trimmed.length; index += 1) { |
| 711 | const char = trimmed[index]; |
| 712 | if (char === "(") depth += 1; |
| 713 | else if (char === ")") { |
| 714 | depth -= 1; |
| 715 | if (depth === 0) return trimmed.slice(index + 1).replace(/^\s+/, ""); |
| 716 | } |
| 717 | } |
| 718 | return trimmed; |
| 719 | } |
| 720 | |
| 721 | export function extractXAiAcpSubagentEndNotice(text: string): XAiAcpSubagentEndNotice | undefined { |
| 722 | const match = text.match(new RegExp(`Background subagent\\s+["']?(${XAI_UUID_RE})["']?`, "i")); |
| 723 | if (match?.[1] === undefined) return undefined; |
| 724 | // Skip balanced descriptor parentheses so nested titles cannot supply false outcome verbs. |
| 725 | const tail = stripLeadingBalancedParenGroup(text.slice((match.index ?? 0) + match[0].length)); |
| 726 | if (/completed successfully/i.test(tail)) { |
| 727 | return { childSessionId: match[1], status: "completed" }; |
| 728 | } |
| 729 | if (/\b(failed|errored|error|crashed|cancelled|canceled|interrupted|timed out)\b/i.test(tail)) { |
| 730 | return { childSessionId: match[1], status: "failed" }; |
| 731 | } |
| 732 | if (/\b(completed|finished|ended)\b/i.test(tail)) { |
| 733 | return { childSessionId: match[1], status: "completed" }; |
| 734 | } |
| 735 | return undefined; |
| 736 | } |
| 737 | |
| 738 | function taskIdsFromGetOutputTool( |
| 739 | toolCall: AcpToolCallState, |
| 740 | rawInput: Record<string, unknown> | undefined, |
| 741 | ): ReadonlyArray<string> { |
| 742 | const ids: string[] = []; |
| 743 | const push = (value: unknown) => { |
| 744 | const text = nonEmptyString(value); |
| 745 | if (text !== undefined && new RegExp(`^${XAI_UUID_RE}$`, "i").test(text)) { |
| 746 | ids.push(text); |
| 747 | } |
| 748 | }; |
| 749 | if (Array.isArray(rawInput?.task_ids)) { |
| 750 | for (const entry of rawInput.task_ids) push(entry); |
| 751 | } |
| 752 | push(rawInput?.task_id); |
| 753 | push(rawInput?.taskId); |
| 754 | const resultId = resultTaskIdFromGetOutputTool(toolCall, xAiToolOutputText(toolCall)); |
| 755 | if (resultId !== undefined) ids.push(resultId); |
| 756 | return [...new Set(ids)]; |
| 757 | } |
| 758 | |
| 759 | function structuredTaskIdFromGetOutputTool(toolCall: AcpToolCallState): string | undefined { |
| 760 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 761 | const result = unknownRecord(rawOutput?.Result) ?? unknownRecord(rawOutput?.result); |
| 762 | return ( |
| 763 | nonEmptyString(result?.task_id) ?? |
| 764 | nonEmptyString(result?.taskId) ?? |
| 765 | nonEmptyString(rawOutput?.task_id) ?? |
| 766 | nonEmptyString(rawOutput?.taskId) |
| 767 | ); |
| 768 | } |
| 769 | |
| 770 | function resultTaskIdFromGetOutputTool( |
| 771 | toolCall: AcpToolCallState, |
| 772 | output: string | undefined, |
| 773 | ): string | undefined { |
| 774 | const structured = structuredTaskIdFromGetOutputTool(toolCall); |
| 775 | if (structured !== undefined && new RegExp(`^${XAI_UUID_RE}$`, "i").test(structured)) { |
| 776 | return structured; |
| 777 | } |
| 778 | if (output === undefined) return undefined; |
| 779 | const taskHeader = firstUuidMatch( |
| 780 | output, |
| 781 | new RegExp(`===\\s*Task\\s+(${XAI_UUID_RE})\\s*===`, "i"), |
| 782 | ); |
| 783 | return taskHeader; |
| 784 | } |
| 785 | |
| 786 | function resultFromGetOutputTool( |
| 787 | toolCall: AcpToolCallState, |
| 788 | output: string | undefined, |
| 789 | ): string | null { |
| 790 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 791 | const result = unknownRecord(rawOutput?.Result) ?? unknownRecord(rawOutput?.result); |
| 792 | const structured = |
| 793 | nonEmptyString(result?.output) ?? |
| 794 | nonEmptyString(result?.text) ?? |
| 795 | decodeByteText(result?.output); |
| 796 | if (structured !== undefined) { |
| 797 | const cleaned = structured |
| 798 | .replace(/<subagent_meta>[\s\S]*?<\/subagent_meta>/gi, "") |
| 799 | .replace(/<subagent_result>[\s\S]*?<\/subagent_result>/gi, "") |
| 800 | .trim(); |
| 801 | if (cleaned.length > 0) return cleaned; |
| 802 | return null; |
| 803 | } |
| 804 | if (output === undefined) return null; |
| 805 | const marker = output.match(/=== Output ===\s*([\s\S]*)$/i); |
| 806 | const body = (marker?.[1] ?? output).trim(); |
| 807 | return body.length > 0 ? body : null; |
| 808 | } |
| 809 | |
| 810 | function statusFromGetOutputTool( |
| 811 | toolCall: AcpToolCallState, |
| 812 | output: string | undefined, |
| 813 | ): "running" | "completed" | "failed" { |
| 814 | if (toolCall.status === "failed") return "failed"; |
| 815 | const rawOutput = unknownRecord(toolCall.data.rawOutput); |
| 816 | const result = unknownRecord(rawOutput?.Result) ?? unknownRecord(rawOutput?.result); |
| 817 | const structuredStatus = nonEmptyString(result?.status)?.toLowerCase(); |
| 818 | if (structuredStatus === "completed" || structuredStatus === "success") return "completed"; |
| 819 | if (structuredStatus === "failed" || structuredStatus === "error") return "failed"; |
| 820 | if (structuredStatus === "running" || structuredStatus === "pending") return "running"; |
| 821 | if (typeof result?.exit_code === "number") { |
| 822 | return result.exit_code === 0 ? "completed" : "failed"; |
| 823 | } |
| 824 | if (output !== undefined) { |
| 825 | if (/Status:\s*failed/i.test(output) || /Exit Code:\s*-?(?!0\b)\d+/i.test(output)) { |
| 826 | return "failed"; |
| 827 | } |
| 828 | if (/Status:\s*completed/i.test(output) || /Status:\s*success/i.test(output)) { |
| 829 | return "completed"; |
| 830 | } |
| 831 | if (/Status:\s*running/i.test(output) || /Status:\s*pending/i.test(output)) { |
| 832 | return "running"; |
| 833 | } |
| 834 | } |
| 835 | // A completed poll RPC does not end its task without task-level status or exit code. |
| 836 | return "running"; |
| 837 | } |
| 838 | |
| 839 | /** Spawn ACKs return immediately; keep subagents running until a child or hydration terminal. */ |
| 840 | export function extractXAiAcpSubagentUpdate( |
| 841 | toolCall: AcpToolCallState, |
| 842 | ): XAiAcpSubagentUpdate | undefined { |
| 843 | const rawInput = unknownRecord(toolCall.data.rawInput); |
| 844 | const output = xAiToolOutputText(toolCall); |
| 845 | |
| 846 | if (isXAiGetSubagentOutputTool(toolCall, rawInput)) { |
| 847 | const structuredTaskId = structuredTaskIdFromGetOutputTool(toolCall); |
| 848 | if ( |
| 849 | structuredTaskId !== undefined && |
| 850 | !new RegExp(`^${XAI_UUID_RE}$`, "i").test(structuredTaskId) |
| 851 | ) { |
| 852 | return undefined; |
| 853 | } |
| 854 | const taskIds = taskIdsFromGetOutputTool(toolCall, rawInput); |
| 855 | const childSessionId = |
| 856 | resultTaskIdFromGetOutputTool(toolCall, output) ?? |
| 857 | taskIds[0] ?? |
| 858 | extractXAiChildSessionId(output); |
| 859 | if (childSessionId === null) return undefined; |
| 860 | return { |
| 861 | nativeTaskId: toolCall.toolCallId, |
| 862 | prompt: "", |
| 863 | title: null, |
| 864 | model: null, |
| 865 | status: statusFromGetOutputTool(toolCall, output), |
| 866 | childSessionId, |
| 867 | result: resultFromGetOutputTool(toolCall, output), |
| 868 | suppressNormalTool: true, |
| 869 | }; |
| 870 | } |
| 871 | |
| 872 | if (!isXAiSpawnOrTaskTool(toolCall, rawInput)) return undefined; |
| 873 | |
| 874 | const childSessionId = extractXAiChildSessionId(output); |
| 875 | const asyncSpawnAck = isXAiAsyncSpawnAck(output); |
| 876 | const legacyResult = |
| 877 | output |
| 878 | ?.replace(new RegExp(`(?:^|\\n)\\s*Agent ID:\\s*${XAI_UUID_RE}[^\\n]*(?:\\n|$)`, "gi"), "\n") |
| 879 | .replace( |
| 880 | new RegExp(`(?:^|\\n)\\s*subagent_id:\\s*${XAI_UUID_RE}[^\\n]*(?:\\n|$)`, "gi"), |
| 881 | "\n", |
| 882 | ) |
| 883 | .trim() || null; |
| 884 | |
| 885 | let status: "running" | "completed" | "failed"; |
| 886 | if (toolCall.status === "failed") { |
| 887 | status = "failed"; |
| 888 | } else if (asyncSpawnAck) { |
| 889 | status = "running"; |
| 890 | } else if (toolCall.status === "completed") { |
| 891 | status = "completed"; |
| 892 | } else { |
| 893 | status = "running"; |
| 894 | } |
| 895 | |
| 896 | return { |
| 897 | nativeTaskId: toolCall.toolCallId, |
| 898 | prompt: nonEmptyString(rawInput?.prompt) ?? "", |
| 899 | title: nonEmptyString(rawInput?.description) ?? null, |
| 900 | model: nonEmptyString(rawInput?.model) ?? null, |
| 901 | status, |
| 902 | childSessionId, |
| 903 | result: asyncSpawnAck ? null : legacyResult, |
| 904 | suppressNormalTool: true, |
| 905 | }; |
| 906 | } |
| 907 | |
| 908 | const XAiAskUserQuestionOption = Schema.Struct({ |
| 909 | label: Schema.String, |
| 910 | description: Schema.optional(Schema.String), |
| 911 | preview: Schema.optional(Schema.String), |
| 912 | id: Schema.optional(Schema.String), |
| 913 | }); |
| 914 | |
| 915 | const XAiAskUserQuestion = Schema.Struct({ |
| 916 | id: Schema.optional(Schema.String), |
| 917 | question: Schema.String, |
| 918 | options: Schema.Array(XAiAskUserQuestionOption), |
| 919 | multiSelect: Schema.optional(Schema.NullOr(Schema.Boolean)), |
| 920 | }); |
| 921 | |
| 922 | const XAiAskUserQuestionParams = Schema.Struct({ |
| 923 | sessionId: Schema.String, |
| 924 | toolCallId: Schema.String, |
| 925 | questions: Schema.Array(XAiAskUserQuestion), |
| 926 | mode: Schema.Literals(["default", "plan"]), |
| 927 | }); |
| 928 | |
| 929 | const XAiWrappedAskUserQuestionParams = Schema.Struct({ |
| 930 | method: Schema.Literals(["x.ai/ask_user_question", "_x.ai/ask_user_question"]), |
| 931 | params: XAiAskUserQuestionParams, |
| 932 | }); |
| 933 | |
| 934 | export const XAiAskUserQuestionRequest = Schema.Union([ |
| 935 | XAiAskUserQuestionParams, |
| 936 | XAiWrappedAskUserQuestionParams, |
| 937 | ]); |
| 938 | |
| 939 | type XAiAskUserQuestionRequestParams = typeof XAiAskUserQuestionParams.Type; |
| 940 | type XAiAskUserQuestionRequest = typeof XAiAskUserQuestionRequest.Type; |
| 941 | |
| 942 | const XAiExitPlanModeParams = Schema.Struct({ |
| 943 | sessionId: Schema.String, |
| 944 | toolCallId: Schema.String, |
| 945 | planContent: Schema.optional(Schema.NullOr(Schema.String)), |
| 946 | }); |
| 947 | |
| 948 | const XAiWrappedExitPlanModeParams = Schema.Struct({ |
| 949 | method: Schema.Literals(["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"]), |
| 950 | params: XAiExitPlanModeParams, |
| 951 | }); |
| 952 | |
| 953 | export const XAiExitPlanModeRequest = Schema.Union([ |
| 954 | XAiExitPlanModeParams, |
| 955 | XAiWrappedExitPlanModeParams, |
| 956 | ]); |
| 957 | |
| 958 | type XAiExitPlanModeRequestParams = typeof XAiExitPlanModeParams.Type; |
| 959 | type XAiExitPlanModeRequest = typeof XAiExitPlanModeRequest.Type; |
| 960 | |
| 961 | function unwrapExitPlanModeParams(params: XAiExitPlanModeRequest): XAiExitPlanModeRequestParams { |
| 962 | return "params" in params ? params.params : params; |
| 963 | } |
| 964 | |
| 965 | export const XAI_EMPTY_PLAN_MARKDOWN = |
| 966 | "# No plan written yet\n\n(The agent exited plan mode without writing a plan.)"; |
| 967 | |
| 968 | export function extractXAiExitPlanMarkdown( |
| 969 | params: XAiExitPlanModeRequest, |
| 970 | fallback?: string | null, |
| 971 | ): string { |
| 972 | const content = unwrapExitPlanModeParams(params).planContent; |
| 973 | const fromRequest = typeof content === "string" ? trimmed(content) : undefined; |
| 974 | if (fromRequest) { |
| 975 | return fromRequest; |
| 976 | } |
| 977 | const fromFallback = fallback?.trim(); |
| 978 | if (fromFallback && fromFallback.length > 0) { |
| 979 | return fromFallback; |
| 980 | } |
| 981 | return XAI_EMPTY_PLAN_MARKDOWN; |
| 982 | } |
| 983 | |
| 984 | export type XAiExitPlanModeOutcome = "approved" | "abandoned" | "request_changes"; |
| 985 | |
| 986 | export interface XAiExitPlanModeResponse { |
| 987 | readonly outcome: XAiExitPlanModeOutcome; |
| 988 | readonly feedback?: string; |
| 989 | } |
| 990 | |
| 991 | /** Abandon the native approval gate after T3 captures the plan; implementation uses T3 UI. */ |
| 992 | export function makeXAiExitPlanModeCapturedResponse(feedback?: string): XAiExitPlanModeResponse { |
| 993 | return { |
| 994 | outcome: "abandoned", |
| 995 | feedback: |
| 996 | feedback ?? |
| 997 | "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", |
| 998 | }; |
| 999 | } |
| 1000 | |
| 1001 | function normalizeFsPath(value: string): string { |
| 1002 | return value.trim().replace(/\\/g, "/").replace(/\/+$/, ""); |
| 1003 | } |
| 1004 | |
| 1005 | function pathHasTraversalSegment(normalized: string): boolean { |
| 1006 | return normalized.split("/").includes(".."); |
| 1007 | } |
| 1008 | |
| 1009 | function addGrokSessionPrefix( |
| 1010 | prefixes: Set<string>, |
| 1011 | homeOrRoot: string, |
| 1012 | nestedGrokDir: boolean, |
| 1013 | ): void { |
| 1014 | const root = normalizeFsPath(homeOrRoot); |
| 1015 | if (!root) { |
| 1016 | return; |
| 1017 | } |
| 1018 | prefixes.add(nestedGrokDir ? `${root}/.grok/sessions/` : `${root}/sessions/`); |
| 1019 | } |
| 1020 | |
| 1021 | export interface GrokPlanPathHost { |
| 1022 | readonly platform: NodeJS.Platform; |
| 1023 | readonly environment: NodeJS.ProcessEnv; |
| 1024 | readonly homeDirectory: string; |
| 1025 | } |
| 1026 | |
| 1027 | function grokPlanSessionPrefixes(host: GrokPlanPathHost): ReadonlySet<string> { |
| 1028 | const { environment } = host; |
| 1029 | const prefixes = new Set<string>(); |
| 1030 | addGrokSessionPrefix(prefixes, host.homeDirectory, true); |
| 1031 | addGrokSessionPrefix(prefixes, "~", true); |
| 1032 | addGrokSessionPrefix(prefixes, environment.HOME ?? "", true); |
| 1033 | addGrokSessionPrefix(prefixes, environment.USERPROFILE ?? "", true); |
| 1034 | // ACP mock and isolated Grok spawns use a HOME that is not the server process home. |
| 1035 | addGrokSessionPrefix(prefixes, "/tmp/mock-home", true); |
| 1036 | const grokHome = environment.GROK_HOME ?? ""; |
| 1037 | addGrokSessionPrefix(prefixes, grokHome, false); |
| 1038 | addGrokSessionPrefix(prefixes, grokHome, true); |
| 1039 | return prefixes; |
| 1040 | } |
| 1041 | |
| 1042 | const CANONICAL_HOME_GROK_SESSION_PATH = |
| 1043 | /^(?:\/home\/[^/]+|\/Users\/[^/]+|[a-zA-Z]:\/Users\/[^/]+)\/\.grok\/sessions\/(?:[^/]+\/)+plan\.md$/; |
| 1044 | const CASE_INSENSITIVE_CANONICAL_HOME_GROK_SESSION_PATH = new RegExp( |
| 1045 | CANONICAL_HOME_GROK_SESSION_PATH.source, |
| 1046 | "i", |
| 1047 | ); |
| 1048 | |
| 1049 | export function isGrokPlanMarkdownPath( |
| 1050 | path: string | undefined | null, |
| 1051 | host: GrokPlanPathHost, |
| 1052 | ): boolean { |
| 1053 | if (typeof path !== "string") { |
| 1054 | return false; |
| 1055 | } |
| 1056 | const normalized = path.trim().replace(/\\/g, "/"); |
| 1057 | const win32 = host.platform === "win32"; |
| 1058 | const haystack = win32 ? normalized.toLowerCase() : normalized; |
| 1059 | if ( |
| 1060 | normalized.length === 0 || |
| 1061 | !haystack.endsWith("/plan.md") || |
| 1062 | pathHasTraversalSegment(normalized) |
| 1063 | ) { |
| 1064 | return false; |
| 1065 | } |
| 1066 | for (const prefix of grokPlanSessionPrefixes(host)) { |
| 1067 | const needle = win32 ? prefix.toLowerCase() : prefix; |
| 1068 | if (!haystack.startsWith(needle)) { |
| 1069 | continue; |
| 1070 | } |
| 1071 | const rest = haystack.slice(needle.length); |
| 1072 | if (rest !== "plan.md" && rest.endsWith("plan.md")) { |
| 1073 | return true; |
| 1074 | } |
| 1075 | } |
| 1076 | return ( |
| 1077 | win32 ? CASE_INSENSITIVE_CANONICAL_HOME_GROK_SESSION_PATH : CANONICAL_HOME_GROK_SESSION_PATH |
| 1078 | ).test(haystack); |
| 1079 | } |
| 1080 | |
| 1081 | export function extractGrokPlanMarkdownFromToolCallData( |
| 1082 | data: Record<string, unknown> | undefined, |
| 1083 | host: GrokPlanPathHost, |
| 1084 | ): string | undefined { |
| 1085 | if (!data) { |
| 1086 | return undefined; |
| 1087 | } |
| 1088 | |
| 1089 | let sawPlanWrite = false; |
| 1090 | const takePlanText = ( |
| 1091 | value: string | undefined, |
| 1092 | filePath: string | undefined, |
| 1093 | ): string | undefined => { |
| 1094 | if (!isGrokPlanMarkdownPath(filePath, host) || value === undefined) { |
| 1095 | return undefined; |
| 1096 | } |
| 1097 | sawPlanWrite = true; |
| 1098 | const trimmed = value.trim(); |
| 1099 | return trimmed.length > 0 ? trimmed : undefined; |
| 1100 | }; |
| 1101 | |
| 1102 | const rawInput = data.rawInput; |
| 1103 | if (isRecord(rawInput)) { |
| 1104 | const filePath = |
| 1105 | (typeof rawInput.file_path === "string" ? rawInput.file_path : undefined) ?? |
| 1106 | (typeof rawInput.path === "string" ? rawInput.path : undefined); |
| 1107 | const content = typeof rawInput.content === "string" ? rawInput.content : undefined; |
| 1108 | const fromRaw = takePlanText(content, filePath); |
| 1109 | if (fromRaw !== undefined) { |
| 1110 | return fromRaw; |
| 1111 | } |
| 1112 | } |
| 1113 | |
| 1114 | const content = data.content; |
| 1115 | if (Array.isArray(content)) { |
| 1116 | for (const block of content) { |
| 1117 | if (!isRecord(block) || block.type !== "diff") { |
| 1118 | continue; |
| 1119 | } |
| 1120 | const path = typeof block.path === "string" ? block.path : undefined; |
| 1121 | const newText = typeof block.newText === "string" ? block.newText : undefined; |
| 1122 | const fromDiff = takePlanText(newText, path); |
| 1123 | if (fromDiff !== undefined) { |
| 1124 | return fromDiff; |
| 1125 | } |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | return sawPlanWrite ? "" : undefined; |
| 1130 | } |
| 1131 | |
| 1132 | function isRecord(value: unknown): value is Record<string, unknown> { |
| 1133 | return typeof value === "object" && value !== null && !Array.isArray(value); |
| 1134 | } |
| 1135 | |
| 1136 | function trimmed(value: string | undefined): string | undefined { |
| 1137 | const text = value?.trim(); |
| 1138 | return text && text.length > 0 ? text : undefined; |
| 1139 | } |
| 1140 | |
| 1141 | function unwrapAskUserQuestionParams( |
| 1142 | params: XAiAskUserQuestionRequest, |
| 1143 | ): XAiAskUserQuestionRequestParams { |
| 1144 | return "params" in params ? params.params : params; |
| 1145 | } |
| 1146 | |
| 1147 | export function extractXAiAskUserQuestions( |
| 1148 | params: XAiAskUserQuestionRequest, |
| 1149 | ): ReadonlyArray<UserInputQuestion> { |
| 1150 | return unwrapAskUserQuestionParams(params).questions.map((question) => ({ |
| 1151 | id: question.id ?? question.question, |
| 1152 | header: "Question", |
| 1153 | question: question.question, |
| 1154 | multiSelect: question.multiSelect === true, |
| 1155 | options: |
| 1156 | question.options.length > 0 |
| 1157 | ? question.options.map((option) => ({ |
| 1158 | label: option.label, |
| 1159 | description: option.description ?? option.label, |
| 1160 | })) |
| 1161 | : [{ label: "OK", description: "Continue" }], |
| 1162 | })); |
| 1163 | } |
| 1164 | |
| 1165 | export function extractXAiAskUserQuestionIdentity(params: XAiAskUserQuestionRequest): { |
| 1166 | readonly sessionId: string; |
| 1167 | readonly toolCallId: string; |
| 1168 | } { |
| 1169 | const unwrapped = unwrapAskUserQuestionParams(params); |
| 1170 | return { |
| 1171 | sessionId: unwrapped.sessionId, |
| 1172 | toolCallId: unwrapped.toolCallId, |
| 1173 | }; |
| 1174 | } |
| 1175 | |
| 1176 | interface XAiAskUserQuestionAnnotation { |
| 1177 | readonly preview?: string; |
| 1178 | readonly notes?: string; |
| 1179 | } |
| 1180 | |
| 1181 | interface XAiAskUserQuestionAcceptedResponse { |
| 1182 | readonly outcome: "accepted"; |
| 1183 | readonly answers: Record<string, ReadonlyArray<string>>; |
| 1184 | readonly annotations?: Record<string, XAiAskUserQuestionAnnotation>; |
| 1185 | } |
| 1186 | |
| 1187 | interface XAiAskUserQuestionCancelledResponse { |
| 1188 | readonly outcome: "cancelled"; |
| 1189 | } |
| 1190 | |
| 1191 | interface NormalizedXAiAnswer { |
| 1192 | readonly questionText: string; |
| 1193 | readonly selectedLabels: ReadonlyArray<string>; |
| 1194 | readonly annotation?: XAiAskUserQuestionAnnotation; |
| 1195 | } |
| 1196 | |
| 1197 | function answerValues(answer: unknown): ReadonlyArray<string> { |
| 1198 | if (Array.isArray(answer)) { |
| 1199 | return answer.flatMap((entry) => { |
| 1200 | const text = typeof entry === "string" ? trimmed(entry) : undefined; |
| 1201 | return text ? [text] : []; |
| 1202 | }); |
| 1203 | } |
| 1204 | const text = typeof answer === "string" ? trimmed(answer) : undefined; |
| 1205 | return text ? [text] : []; |
| 1206 | } |
| 1207 | |
| 1208 | function normalizeAnswerForXAi( |
| 1209 | question: XAiAskUserQuestionRequestParams["questions"][number], |
| 1210 | answer: unknown, |
| 1211 | ): NormalizedXAiAnswer | undefined { |
| 1212 | const values = answerValues(answer); |
| 1213 | if (values.length === 0) { |
| 1214 | return undefined; |
| 1215 | } |
| 1216 | |
| 1217 | const optionByLabel = new Map(question.options.map((option) => [option.label, option])); |
| 1218 | const resolvedValues = values.map((value) => ({ |
| 1219 | value, |
| 1220 | option: optionByLabel.get(value), |
| 1221 | })); |
| 1222 | const selectedLabels = resolvedValues.flatMap(({ option }) => (option ? [option.label] : [])); |
| 1223 | const notes = resolvedValues.flatMap(({ option, value }) => (option ? [] : [value])); |
| 1224 | const preview = |
| 1225 | question.multiSelect === true |
| 1226 | ? undefined |
| 1227 | : resolvedValues.map(({ option }) => trimmed(option?.preview)).find((value) => value); |
| 1228 | |
| 1229 | const annotation = |
| 1230 | preview || notes.length > 0 |
| 1231 | ? { |
| 1232 | ...(preview ? { preview } : {}), |
| 1233 | ...(notes.length > 0 ? { notes: notes.join("\n") } : {}), |
| 1234 | } |
| 1235 | : undefined; |
| 1236 | |
| 1237 | return { |
| 1238 | questionText: question.question, |
| 1239 | selectedLabels: selectedLabels.length > 0 ? selectedLabels : ["Other"], |
| 1240 | ...(annotation ? { annotation } : {}), |
| 1241 | }; |
| 1242 | } |
| 1243 | |
| 1244 | function findQuestionAnswer( |
| 1245 | answers: ProviderUserInputAnswers, |
| 1246 | question: XAiAskUserQuestionRequestParams["questions"][number], |
| 1247 | ): unknown { |
| 1248 | const key = question.id ?? question.question; |
| 1249 | return answers[key] ?? answers[question.question]; |
| 1250 | } |
| 1251 | |
| 1252 | export function makeXAiAskUserQuestionResponse( |
| 1253 | params: XAiAskUserQuestionRequest, |
| 1254 | answers: ProviderUserInputAnswers, |
| 1255 | ): XAiAskUserQuestionAcceptedResponse { |
| 1256 | const questions = unwrapAskUserQuestionParams(params).questions; |
| 1257 | const normalized = questions.flatMap((question) => { |
| 1258 | const entry = normalizeAnswerForXAi(question, findQuestionAnswer(answers, question)); |
| 1259 | return entry ? [entry] : []; |
| 1260 | }); |
| 1261 | const annotations = Object.fromEntries( |
| 1262 | normalized.flatMap((entry) => |
| 1263 | entry.annotation ? [[entry.questionText, entry.annotation] as const] : [], |
| 1264 | ), |
| 1265 | ); |
| 1266 | |
| 1267 | return { |
| 1268 | outcome: "accepted", |
| 1269 | answers: Object.fromEntries( |
| 1270 | normalized.map((entry) => [entry.questionText, entry.selectedLabels]), |
| 1271 | ), |
| 1272 | ...(Object.keys(annotations).length > 0 ? { annotations } : {}), |
| 1273 | }; |
| 1274 | } |
| 1275 | |
| 1276 | export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse { |
| 1277 | return { outcome: "cancelled" }; |
| 1278 | } |
| 1279 | |
| 1280 | function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined { |
| 1281 | const meta = response._meta; |
| 1282 | if (meta === null || typeof meta !== "object") { |
| 1283 | return undefined; |
| 1284 | } |
| 1285 | const promptId = meta.promptId ?? meta.requestId; |
| 1286 | return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined; |
| 1287 | } |
| 1288 | |
| 1289 | function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason { |
| 1290 | switch (value) { |
| 1291 | case "cancelled": |
| 1292 | case "end_turn": |
| 1293 | case "max_tokens": |
| 1294 | case "max_turn_requests": |
| 1295 | case "refusal": |
| 1296 | return value; |
| 1297 | default: |
| 1298 | return "end_turn"; |
| 1299 | } |
| 1300 | } |
| 1301 | |
| 1302 | function promptResponseFromXAi( |
| 1303 | notification: XAiPromptCompleteNotification, |
| 1304 | ): EffectAcpSchema.PromptResponse { |
| 1305 | const stopReason = normalizeXAiStopReason(notification.stopReason); |
| 1306 | const meta: Record<string, Schema.Json> = { |
| 1307 | sessionId: notification.sessionId, |
| 1308 | }; |
| 1309 | if (notification.promptId !== undefined) { |
| 1310 | meta.promptId = notification.promptId; |
| 1311 | meta.requestId = notification.promptId; |
| 1312 | } |
| 1313 | if (notification.agentResult !== undefined) { |
| 1314 | meta.agentResult = notification.agentResult as Schema.Json; |
| 1315 | } |
| 1316 | return { |
| 1317 | stopReason, |
| 1318 | _meta: meta, |
| 1319 | }; |
| 1320 | } |
| 1321 | |
| 1322 | // Grok completion can beat the prompt RPC error; carry its agentResult failure. |
| 1323 | function xAiPromptFailure( |
| 1324 | notification: XAiPromptCompleteNotification, |
| 1325 | ): EffectAcpErrors.AcpRequestError | null { |
| 1326 | if (notification.stopReason === "rate_limit") { |
| 1327 | return new EffectAcpErrors.AcpRequestError({ |
| 1328 | code: xAiRateLimitedErrorCode, |
| 1329 | errorMessage: "Grok usage limit reached. Try again later.", |
| 1330 | }); |
| 1331 | } |
| 1332 | if (notification.stopReason === "error") { |
| 1333 | const agentResult = nonEmptyString(notification.agentResult); |
| 1334 | return new EffectAcpErrors.AcpRequestError({ |
| 1335 | code: -32603, |
| 1336 | errorMessage: "Grok ended the turn with an error.", |
| 1337 | operation: "receive-response", |
| 1338 | ...(agentResult === undefined |
| 1339 | ? {} |
| 1340 | : { cause: new XAiPromptFailureText({ message: agentResult }) }), |
| 1341 | }); |
| 1342 | } |
| 1343 | return null; |
| 1344 | } |
| 1345 | |
| 1346 | /** Keep unbounded provider text out of structured attributes; read only at presentation. */ |
| 1347 | export class XAiPromptFailureText extends Schema.TaggedError<XAiPromptFailureText>()( |
| 1348 | "XAiPromptFailureText", |
| 1349 | { message: Schema.String }, |
| 1350 | ) {} |
| 1351 | |
| 1352 | const registerXAiPromptCompletionFallback = ( |
| 1353 | pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>, |
| 1354 | sessionId: string, |
| 1355 | promptId: string, |
| 1356 | ) => |
| 1357 | Deferred.make<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>().pipe( |
| 1358 | Effect.tap((deferred) => |
| 1359 | Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]), |
| 1360 | ), |
| 1361 | Effect.map((deferred) => ({ deferred, promptId })), |
| 1362 | ); |
| 1363 | |
| 1364 | const unregisterXAiPromptCompletionFallback = ( |
| 1365 | pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>, |
| 1366 | deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>, |
| 1367 | ) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred)); |
| 1368 | |
| 1369 | const abortPendingPromptCompletions = ( |
| 1370 | pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>, |
| 1371 | sessionId?: string, |
| 1372 | ) => |
| 1373 | Ref.modify(pendingRef, (pending) => { |
| 1374 | const [toAbort, remaining] = pending.reduce< |
| 1375 | [ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>] |
| 1376 | >( |
| 1377 | ([aborting, kept], entry) => |
| 1378 | sessionId === undefined || entry.sessionId === sessionId |
| 1379 | ? [[...aborting, entry], kept] |
| 1380 | : [aborting, [...kept, entry]], |
| 1381 | [[], []], |
| 1382 | ); |
| 1383 | if (toAbort.length === 0) { |
| 1384 | return [Effect.void, pending] as const; |
| 1385 | } |
| 1386 | return [ |
| 1387 | Effect.forEach( |
| 1388 | toAbort, |
| 1389 | (entry) => |
| 1390 | Deferred.succeed( |
| 1391 | entry.deferred, |
| 1392 | promptResponseFromXAi({ |
| 1393 | sessionId: entry.sessionId, |
| 1394 | promptId: entry.promptId, |
| 1395 | stopReason: "cancelled", |
| 1396 | agentResult: null, |
| 1397 | }), |
| 1398 | ), |
| 1399 | { concurrency: "unbounded" }, |
| 1400 | ).pipe(Effect.asVoid), |
| 1401 | remaining, |
| 1402 | ] as const; |
| 1403 | }).pipe(Effect.flatten); |
| 1404 | |
| 1405 | const resolveXAiPromptCompletionFallback = ({ |
| 1406 | pendingRef, |
| 1407 | completedPromptIdsRef, |
| 1408 | notification, |
| 1409 | }: { |
| 1410 | readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>; |
| 1411 | readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>; |
| 1412 | readonly notification: XAiPromptCompleteNotification; |
| 1413 | }) => |
| 1414 | Ref.get(completedPromptIdsRef).pipe( |
| 1415 | Effect.flatMap((completedPromptIds) => { |
| 1416 | if ( |
| 1417 | notification.promptId !== undefined && |
| 1418 | completedPromptIds.includes(notification.promptId) |
| 1419 | ) { |
| 1420 | return Effect.void; |
| 1421 | } |
| 1422 | return Ref.modify(pendingRef, (pending) => { |
| 1423 | const index = |
| 1424 | notification.promptId !== undefined |
| 1425 | ? pending.findIndex( |
| 1426 | (entry) => |
| 1427 | entry.sessionId === notification.sessionId && |
| 1428 | entry.promptId === notification.promptId, |
| 1429 | ) |
| 1430 | : (() => { |
| 1431 | const sessionPendingIndexes = pending.flatMap((entry, entryIndex) => |
| 1432 | entry.sessionId === notification.sessionId ? [entryIndex] : [], |
| 1433 | ); |
| 1434 | if (sessionPendingIndexes.length !== 1) { |
| 1435 | return -1; |
| 1436 | } |
| 1437 | return sessionPendingIndexes[0] ?? -1; |
| 1438 | })(); |
| 1439 | if (index < 0) { |
| 1440 | return [Effect.void, pending] as const; |
| 1441 | } |
| 1442 | const entry = pending[index]; |
| 1443 | if (!entry) { |
| 1444 | return [Effect.void, pending] as const; |
| 1445 | } |
| 1446 | const failure = xAiPromptFailure(notification); |
| 1447 | const settle = |
| 1448 | failure !== null |
| 1449 | ? Deferred.fail(entry.deferred, failure).pipe(Effect.asVoid) |
| 1450 | : Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe( |
| 1451 | Effect.asVoid, |
| 1452 | ); |
| 1453 | return [settle, [...pending.slice(0, index), ...pending.slice(index + 1)]] as const; |
| 1454 | }).pipe(Effect.flatten); |
| 1455 | }), |
| 1456 | ); |
| 1457 | |
| 1458 | const rememberCompletedXAiPromptId = ( |
| 1459 | completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>, |
| 1460 | response: EffectAcpSchema.PromptResponse, |
| 1461 | fallbackPromptId: string, |
| 1462 | ) => { |
| 1463 | const promptId = promptIdFromResponse(response) ?? fallbackPromptId; |
| 1464 | if (promptId.length === 0) { |
| 1465 | return Effect.void; |
| 1466 | } |
| 1467 | return Ref.update(completedPromptIdsRef, (completedPromptIds) => { |
| 1468 | if (completedPromptIds.includes(promptId)) { |
| 1469 | return completedPromptIds; |
| 1470 | } |
| 1471 | return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit); |
| 1472 | }); |
| 1473 | }; |
| 1474 | |
| 1475 | export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")( |
| 1476 | function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) { |
| 1477 | // Grok multiplexes session updates on extension methods that permit only one handler. |
| 1478 | const sessionNotificationHandlers = new Map< |
| 1479 | string, |
| 1480 | (params: unknown) => Effect.Effect<void, EffectAcpErrors.AcpError> |
| 1481 | >(); |
| 1482 | let nextPromptFallbackId = 0; |
| 1483 | const allocatePromptFallbackId = Effect.sync(() => { |
| 1484 | nextPromptFallbackId += 1; |
| 1485 | return `t3-xai-prompt-${nextPromptFallbackId}`; |
| 1486 | }); |
| 1487 | const pendingXAiPromptCompletionsRef = yield* Ref.make< |
| 1488 | ReadonlyArray<PendingXAiPromptCompletion> |
| 1489 | >([]); |
| 1490 | const completedXAiPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]); |
| 1491 | |
| 1492 | const settleFromPromptComplete = (notification: XAiPromptCompleteNotification) => |
| 1493 | resolveXAiPromptCompletionFallback({ |
| 1494 | pendingRef: pendingXAiPromptCompletionsRef, |
| 1495 | completedPromptIdsRef: completedXAiPromptIdsRef, |
| 1496 | notification, |
| 1497 | }).pipe(Effect.ignore); |
| 1498 | |
| 1499 | yield* Effect.forEach( |
| 1500 | ["x.ai/session/prompt_complete", "_x.ai/session/prompt_complete"] as const, |
| 1501 | (method) => |
| 1502 | runtime.handleExtNotification( |
| 1503 | method, |
| 1504 | XAiPromptCompleteNotification, |
| 1505 | settleFromPromptComplete, |
| 1506 | ), |
| 1507 | { discard: true }, |
| 1508 | ); |
| 1509 | |
| 1510 | yield* Effect.forEach( |
| 1511 | xAiSessionNotificationMethods, |
| 1512 | (method) => |
| 1513 | runtime.handleExtNotification(method, Schema.Unknown, (params) => |
| 1514 | decodeXAiSessionUpdateNotification(params).pipe( |
| 1515 | Effect.flatMap((notification) => { |
| 1516 | const complete = xAiPromptCompleteFromSessionUpdate(notification); |
| 1517 | return complete === null ? Effect.void : settleFromPromptComplete(complete); |
| 1518 | }), |
| 1519 | Effect.ignore, |
| 1520 | Effect.andThen( |
| 1521 | Effect.suspend( |
| 1522 | () => sessionNotificationHandlers.get(method)?.(params) ?? Effect.void, |
| 1523 | ), |
| 1524 | ), |
| 1525 | ), |
| 1526 | ), |
| 1527 | { discard: true }, |
| 1528 | ); |
| 1529 | |
| 1530 | return { |
| 1531 | ...runtime, |
| 1532 | handleExtNotification: (method, payload, handler) => |
| 1533 | xAiSessionNotificationMethods.some((owned) => owned === method) |
| 1534 | ? Effect.sync(() => { |
| 1535 | sessionNotificationHandlers.set(method, (params) => |
| 1536 | Schema.decodeUnknownEffect(payload)(params).pipe( |
| 1537 | Effect.mapError((error) => |
| 1538 | EffectAcpErrors.AcpProtocolParseError.fromSchemaError( |
| 1539 | "decode-notification-payload", |
| 1540 | method, |
| 1541 | error, |
| 1542 | ), |
| 1543 | ), |
| 1544 | Effect.flatMap(handler), |
| 1545 | ), |
| 1546 | ); |
| 1547 | }) |
| 1548 | : runtime.handleExtNotification(method, payload, handler), |
| 1549 | prompt: Effect.fn("xaiAcpExtension.prompt")(function* (payload, promptOptions?) { |
| 1550 | const started = yield* runtime.start(); |
| 1551 | const promptId = yield* allocatePromptFallbackId; |
| 1552 | const fallback = yield* registerXAiPromptCompletionFallback( |
| 1553 | pendingXAiPromptCompletionsRef, |
| 1554 | started.sessionId, |
| 1555 | promptId, |
| 1556 | ); |
| 1557 | const cancelledResponse = promptResponseFromXAi({ |
| 1558 | sessionId: started.sessionId, |
| 1559 | promptId: fallback.promptId, |
| 1560 | stopReason: "cancelled", |
| 1561 | agentResult: null, |
| 1562 | }); |
| 1563 | const promptRpcFiber = yield* runtime |
| 1564 | .prompt( |
| 1565 | { |
| 1566 | ...payload, |
| 1567 | _meta: { |
| 1568 | ...payload._meta, |
| 1569 | promptId: fallback.promptId, |
| 1570 | requestId: fallback.promptId, |
| 1571 | }, |
| 1572 | }, |
| 1573 | promptOptions, |
| 1574 | ) |
| 1575 | .pipe(Effect.forkChild); |
| 1576 | return yield* Effect.raceFirst( |
| 1577 | Fiber.join(promptRpcFiber).pipe( |
| 1578 | Effect.catchCauseIf( |
| 1579 | (cause) => Cause.hasInterruptsOnly(cause), |
| 1580 | (_cause) => Effect.succeed(cancelledResponse), |
| 1581 | ), |
| 1582 | ), |
| 1583 | Deferred.await(fallback.deferred), |
| 1584 | ).pipe( |
| 1585 | Effect.tap((response) => |
| 1586 | rememberCompletedXAiPromptId(completedXAiPromptIdsRef, response, fallback.promptId), |
| 1587 | ), |
| 1588 | Effect.ensuring( |
| 1589 | Effect.gen(function* () { |
| 1590 | yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore); |
| 1591 | yield* unregisterXAiPromptCompletionFallback( |
| 1592 | pendingXAiPromptCompletionsRef, |
| 1593 | fallback.deferred, |
| 1594 | ); |
| 1595 | }), |
| 1596 | ), |
| 1597 | ); |
| 1598 | }), |
| 1599 | cancel: Effect.gen(function* () { |
| 1600 | // Cancellation must bypass start so it can reach a stalled runtime. |
| 1601 | yield* abortPendingPromptCompletions(pendingXAiPromptCompletionsRef); |
| 1602 | yield* runtime.cancel; |
| 1603 | }), |
| 1604 | } satisfies AcpSessionRuntime.AcpSessionRuntime["Service"]; |
| 1605 | }, |
| 1606 | ); |