Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFS from "node:fs";
4
5import * as Effect from "effect/Effect";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
9
10import * as EffectAcpAgent from "effect-acp/agent";
11import * as AcpError from "effect-acp/errors";
12import type * as AcpSchema from "effect-acp/schema";
13
14const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
15const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
16const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
17const emitInterleavedAssistantToolCalls =
18 process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
19const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
20const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
21const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
22const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
23const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
24const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
25const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
26const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
27const omitXAiPromptCompleteStopReason =
28 process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
29const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
30const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
31const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
32const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
33const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
34const emitStaleXAiPromptCompleteBeforeSecondHang =
35 process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
36const emitOverlappingXAiPromptCompleteOutOfOrder =
37 process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
38const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
39const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
40const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
41const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
42const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
43const permissionOptionIds = {
44 allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
45 allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
46 rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
47};
48const sessionId = "mock-session-1";
49
50let currentModeId = "ask";
51let currentModelId = "default";
52let parameterizedModelPicker = false;
53let currentReasoning = "medium";
54let currentContext = "272k";
55let currentFast = false;
56let promptCount = 0;
57let overlappingFirstPromptId: string | undefined;
58const cancelledSessions = new Set<string>();
59
60function promptIdFromRequestMeta(
61 request: Pick<AcpSchema.PromptRequest, "_meta">,
62): string | undefined {
63 const meta = request._meta;
64 if (meta === null || typeof meta !== "object") {
65 return undefined;
66 }
67 const promptId = meta.promptId ?? meta.requestId;
68 return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
69}
70
71function logExit(reason: string): void {
72 if (!exitLogPath) {
73 return;
74 }
75 NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
76}
77
78function writeJsonRpcNotification(method: string, params: unknown): void {
79 process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
80}
81
82process.once("SIGTERM", () => {
83 logExit("SIGTERM");
84 process.exit(0);
85});
86
87process.once("SIGINT", () => {
88 logExit("SIGINT");
89 process.exit(0);
90});
91
92process.once("exit", (code) => {
93 logExit(`exit:${code}`);
94});
95
96function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
97 if (parameterizedModelPicker) {
98 const baseOptions: Array<AcpSchema.SessionConfigOption> = [
99 {
100 id: "mode",
101 name: "Mode",
102 category: "mode",
103 type: "select",
104 currentValue: currentModeId,
105 options: availableModes.map((mode) => ({
106 value: mode.id,
107 name: mode.name,
108 ...(mode.description ? { description: mode.description } : {}),
109 })),
110 },
111 {
112 id: "model",
113 name: "Model",
114 category: "model",
115 type: "select",
116 currentValue: currentModelId,
117 options: [
118 { value: "default", name: "Auto" },
119 { value: "composer-2", name: "Composer 2" },
120 { value: "gpt-5.4", name: "GPT-5.4" },
121 { value: "claude-opus-4-6", name: "Opus 4.6" },
122 ],
123 },
124 ];
125
126 switch (currentModelId) {
127 case "gpt-5.4":
128 return [
129 ...baseOptions,
130 {
131 id: "reasoning",
132 name: "Reasoning",
133 category: "thought_level",
134 type: "select",
135 currentValue: currentReasoning,
136 options: [
137 { value: "none", name: "None" },
138 { value: "low", name: "Low" },
139 { value: "medium", name: "Medium" },
140 { value: "high", name: "High" },
141 { value: "extra-high", name: "Extra High" },
142 ],
143 },
144 {
145 id: "context",
146 name: "Context",
147 category: "model_config",
148 type: "select",
149 currentValue: currentContext,
150 options: [
151 { value: "272k", name: "272K" },
152 { value: "1m", name: "1M" },
153 ],
154 },
155 {
156 id: "fast",
157 name: "Fast",
158 category: "model_config",
159 type: "select",
160 currentValue: String(currentFast),
161 options: [
162 { value: "false", name: "Off" },
163 { value: "true", name: "Fast" },
164 ],
165 },
166 ];
167 case "composer-2":
168 return [
169 ...baseOptions,
170 {
171 id: "fast",
172 name: "Fast",
173 category: "model_config",
174 type: "select",
175 currentValue: String(currentFast),
176 options: [
177 { value: "false", name: "Off" },
178 { value: "true", name: "Fast" },
179 ],
180 },
181 ];
182 case "claude-opus-4-6":
183 return [
184 ...baseOptions,
185 {
186 id: "reasoning",
187 name: "Reasoning",
188 category: "thought_level",
189 type: "select",
190 currentValue: currentReasoning,
191 options: [
192 { value: "low", name: "Low" },
193 { value: "medium", name: "Medium" },
194 { value: "high", name: "High" },
195 ],
196 },
197 {
198 id: "thinking",
199 name: "Thinking",
200 category: "model_config",
201 type: "boolean",
202 currentValue: true,
203 },
204 ];
205 default:
206 return baseOptions;
207 }
208 }
209
210 return [
211 {
212 id: "model",
213 name: "Model",
214 category: "model",
215 type: "select" as const,
216 currentValue: currentModelId,
217 options: [
218 { value: "default", name: "Auto" },
219 { value: "composer-2", name: "Composer 2" },
220 { value: "composer-2[fast=true]", name: "Composer 2 Fast" },
221 { value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
222 ],
223 },
224 ];
225}
226
227function modelConfigOptionsFor(modelId: string): ReadonlyArray<AcpSchema.SessionConfigOption> {
228 const previousModelId = currentModelId;
229 try {
230 currentModelId = modelId;
231 return configOptions().filter(
232 (option) => option.category !== "mode" && option.category !== "model",
233 );
234 } finally {
235 currentModelId = previousModelId;
236 }
237}
238
239function availableModels(): ReadonlyArray<{
240 readonly value: string;
241 readonly name: string;
242 readonly configOptions: ReadonlyArray<AcpSchema.SessionConfigOption>;
243}> {
244 return [
245 { value: "default", name: "Auto" },
246 { value: "composer-2", name: "Composer 2" },
247 { value: "gpt-5.4", name: "GPT-5.4" },
248 { value: "claude-opus-4-6", name: "Opus 4.6" },
249 ].map((model) => ({
250 value: model.value,
251 name: model.name,
252 configOptions: modelConfigOptionsFor(model.value),
253 }));
254}
255
256const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
257 {
258 id: "ask",
259 name: "Ask",
260 description: "Request permission before making any changes",
261 },
262 {
263 id: "architect",
264 name: "Architect",
265 description: "Design and plan software systems without implementation",
266 },
267 {
268 id: "code",
269 name: "Code",
270 description: "Write and modify code with full tool access",
271 },
272];
273
274function modeState(): AcpSchema.SessionModeState {
275 return {
276 currentModeId,
277 availableModes,
278 };
279}
280
281const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
282 { modelId: "grok-build", name: "Grok Build" },
283 { modelId: "grok-mock-alt", name: "Grok Mock Alt" },
284];
285
286function modelState(): AcpSchema.SessionModelState {
287 const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
288 ? currentModelId
289 : "grok-build";
290 return {
291 currentModelId: modelId,
292 availableModels: grokAcpModels,
293 };
294}
295
296const program = Effect.gen(function* () {
297 const agent = yield* EffectAcpAgent.AcpAgent;
298
299 yield* agent.handleInitialize((request) =>
300 Effect.sync(() => {
301 parameterizedModelPicker =
302 request.clientCapabilities?._meta?.parameterizedModelPicker === true;
303 return {
304 protocolVersion: 1,
305 agentCapabilities: { loadSession: true },
306 };
307 }),
308 );
309
310 yield* agent.handleAuthenticate(() => Effect.succeed({}));
311
312 yield* agent.handleCreateSession(() =>
313 Effect.succeed({
314 sessionId,
315 modes: modeState(),
316 models: modelState(),
317 configOptions: configOptions(),
318 }),
319 );
320
321 const emitLoadReplayNotifications = (requestedSessionId: string) => {
322 writeJsonRpcNotification("session/update", {
323 _meta: { isReplay: true },
324 sessionId: requestedSessionId,
325 update: {
326 sessionUpdate: "tool_call",
327 toolCallId: "replay-tool-1",
328 title: "Replay tool",
329 kind: "search",
330 status: "completed",
331 },
332 });
333 writeJsonRpcNotification("session/update", {
334 _meta: { isReplay: true },
335 sessionId: requestedSessionId,
336 update: {
337 sessionUpdate: "agent_message_chunk",
338 content: { type: "text", text: "replayed assistant text" },
339 },
340 });
341 };
342
343 yield* agent.handleLoadSession((request) =>
344 Effect.gen(function* () {
345 const requestedSessionId = String(request.sessionId ?? sessionId);
346 if (failLoadSession) {
347 return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
348 }
349 if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
350 emitLoadReplayNotifications(requestedSessionId);
351 yield* agent.client.sessionUpdate({
352 sessionId: requestedSessionId,
353 update: {
354 sessionUpdate: "user_message_chunk",
355 content: { type: "text", text: "replay-tail" },
356 },
357 });
358 yield* Effect.sleep(loadSessionDelayMs);
359 return {
360 modes: modeState(),
361 models: modelState(),
362 configOptions: configOptions(),
363 };
364 }
365 if (emitLoadReplay) {
366 emitLoadReplayNotifications(requestedSessionId);
367 }
368 yield* agent.client.sessionUpdate({
369 sessionId: requestedSessionId,
370 update: {
371 sessionUpdate: "user_message_chunk",
372 content: { type: "text", text: "replay" },
373 },
374 });
375 return {
376 modes: modeState(),
377 models: modelState(),
378 configOptions: configOptions(),
379 };
380 }),
381 );
382
383 yield* agent.handleSetSessionModel((request) =>
384 Effect.gen(function* () {
385 if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
386 return yield* AcpError.AcpRequestError.invalidParams(
387 `Unknown mock model id: ${request.modelId}`,
388 {
389 method: "session/set_model",
390 params: request,
391 },
392 );
393 }
394 currentModelId = request.modelId;
395 return {};
396 }),
397 );
398
399 yield* agent.handleSetSessionConfigOption((request) =>
400 Effect.gen(function* () {
401 if (exitOnSetConfigOption) {
402 return yield* Effect.sync(() => {
403 process.exit(7);
404 });
405 }
406 if (failSetConfigOption) {
407 return yield* AcpError.AcpRequestError.invalidParams(
408 "Mock invalid params for session/set_config_option",
409 {
410 method: "session/set_config_option",
411 params: request,
412 },
413 );
414 }
415 if (request.configId === "mode" && typeof request.value === "string") {
416 currentModeId = request.value;
417 }
418 if (request.configId === "model" && typeof request.value === "string") {
419 currentModelId = request.value;
420 }
421 if (request.configId === "reasoning" && typeof request.value === "string") {
422 currentReasoning = request.value;
423 }
424 if (request.configId === "context" && typeof request.value === "string") {
425 currentContext = request.value;
426 }
427 if (request.configId === "fast") {
428 currentFast = request.value === true || request.value === "true";
429 }
430 return {
431 configOptions: configOptions(),
432 };
433 }),
434 );
435
436 yield* agent.handleCancel(({ sessionId }) =>
437 Effect.gen(function* () {
438 const cancelledSessionId = String(sessionId ?? "mock-session-1");
439 cancelledSessions.add(cancelledSessionId);
440 if (emitLateUpdateAfterCancel) {
441 yield* Effect.sleep("50 millis");
442 yield* Effect.sync(() => {
443 writeJsonRpcNotification("session/update", {
444 sessionId: cancelledSessionId,
445 update: {
446 sessionUpdate: "agent_message_chunk",
447 content: { type: "text", text: "late after cancel" },
448 },
449 });
450 });
451 }
452 }),
453 );
454
455 yield* agent.handlePrompt((request) =>
456 Effect.gen(function* () {
457 const requestedSessionId = String(request.sessionId ?? sessionId);
458 promptCount += 1;
459
460 if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
461 yield* Effect.sleep(`${promptDelayMs} millis`);
462 }
463
464 if (failPrompt) {
465 return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
466 }
467
468 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
469 return {
470 stopReason: "end_turn",
471 _meta: {
472 promptId: "mock-stale-xai-prompt-1",
473 requestId: "mock-stale-xai-prompt-1",
474 },
475 };
476 }
477
478 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
479 const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
480 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
481 sessionId: requestedSessionId,
482 promptId: "mock-stale-xai-prompt-1",
483 stopReason: "end_turn",
484 agentResult: null,
485 });
486
487 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
488 sessionId: requestedSessionId,
489 promptId: currentPromptId,
490 stopReason: "end_turn",
491 agentResult: null,
492 });
493
494 return yield* Effect.never;
495 }
496
497 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
498 overlappingFirstPromptId = promptIdFromRequestMeta(request);
499 return yield* Effect.never;
500 }
501
502 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
503 const secondPromptId = promptIdFromRequestMeta(request);
504 if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
505 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
506 sessionId: requestedSessionId,
507 promptId: secondPromptId,
508 stopReason: "end_turn",
509 agentResult: null,
510 });
511 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
512 sessionId: requestedSessionId,
513 promptId: overlappingFirstPromptId,
514 stopReason: "end_turn",
515 agentResult: null,
516 });
517 }
518 return yield* Effect.never;
519 }
520
521 if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
522 return yield* Effect.never;
523 }
524
525 if (emitXAiPromptCompleteThenHang) {
526 writeJsonRpcNotification("session/update", {
527 sessionId: requestedSessionId,
528 update: {
529 sessionUpdate: "agent_message_chunk",
530 content: { type: "text", text: "hello from " },
531 },
532 });
533
534 if (emitForeignSessionUpdates) {
535 writeJsonRpcNotification("session/update", {
536 sessionId: "mock-child-session-1",
537 update: {
538 sessionUpdate: "agent_message_chunk",
539 content: { type: "text", text: "child before completion" },
540 },
541 });
542 }
543
544 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
545 sessionId: requestedSessionId,
546 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
547 ...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
548 agentResult: null,
549 });
550
551 if (emitForeignSessionUpdates) {
552 writeJsonRpcNotification("session/update", {
553 sessionId: "mock-child-session-1",
554 update: {
555 sessionUpdate: "tool_call",
556 toolCallId: "child-tool-call-1",
557 title: "Child-only tool",
558 kind: "other",
559 status: "pending",
560 rawInput: {},
561 },
562 });
563 writeJsonRpcNotification("session/update", {
564 sessionId: "mock-child-session-1",
565 update: {
566 sessionUpdate: "agent_message_chunk",
567 content: { type: "text", text: "child after completion" },
568 },
569 });
570 }
571
572 writeJsonRpcNotification("session/update", {
573 sessionId: requestedSessionId,
574 update: {
575 sessionUpdate: "agent_message_chunk",
576 content: { type: "text", text: "mock" },
577 },
578 });
579
580 return yield* Effect.never;
581 }
582
583 if (emitInterleavedAssistantToolCalls) {
584 const toolCallId = "tool-call-1";
585
586 yield* agent.client.sessionUpdate({
587 sessionId: requestedSessionId,
588 update: {
589 sessionUpdate: "agent_message_chunk",
590 content: { type: "text", text: "before tool" },
591 },
592 });
593
594 yield* agent.client.sessionUpdate({
595 sessionId: requestedSessionId,
596 update: {
597 sessionUpdate: "tool_call",
598 toolCallId,
599 title: "Terminal",
600 kind: "execute",
601 status: "pending",
602 rawInput: {
603 command: ["echo", "hello"],
604 },
605 },
606 });
607
608 yield* agent.client.sessionUpdate({
609 sessionId: requestedSessionId,
610 update: {
611 sessionUpdate: "tool_call_update",
612 toolCallId,
613 status: "completed",
614 rawOutput: {
615 exitCode: 0,
616 stdout: "hello",
617 stderr: "",
618 },
619 },
620 });
621
622 yield* agent.client.sessionUpdate({
623 sessionId: requestedSessionId,
624 update: {
625 sessionUpdate: "agent_message_chunk",
626 content: { type: "text", text: "after tool" },
627 },
628 });
629
630 return { stopReason: "end_turn" };
631 }
632
633 if (emitToolCalls) {
634 const toolCallId = "tool-call-1";
635
636 yield* agent.client.sessionUpdate({
637 sessionId: requestedSessionId,
638 update: {
639 sessionUpdate: "tool_call",
640 toolCallId,
641 title: "Terminal",
642 kind: "execute",
643 status: "pending",
644 rawInput: {
645 command: ["cat", "server/package.json"],
646 },
647 },
648 });
649
650 yield* agent.client.sessionUpdate({
651 sessionId: requestedSessionId,
652 update: {
653 sessionUpdate: "tool_call_update",
654 toolCallId,
655 status: "in_progress",
656 },
657 });
658
659 const permission = yield* agent.client.requestPermission({
660 sessionId: requestedSessionId,
661 toolCall: {
662 toolCallId,
663 title: "`cat server/package.json`",
664 kind: "execute",
665 status: "pending",
666 content: [
667 {
668 type: "content",
669 content: {
670 type: "text",
671 text: "Not in allowlist: cat server/package.json",
672 },
673 },
674 ],
675 },
676 options: [
677 { optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
678 {
679 optionId: permissionOptionIds.allowAlways,
680 name: "Allow always",
681 kind: "allow_always",
682 },
683 { optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
684 ],
685 });
686
687 const cancelled =
688 cancelledSessions.delete(requestedSessionId) ||
689 permission.outcome.outcome === "cancelled";
690
691 yield* agent.client.sessionUpdate({
692 sessionId: requestedSessionId,
693 update: {
694 sessionUpdate: "tool_call_update",
695 toolCallId,
696 title: "Terminal",
697 kind: "execute",
698 status: "completed",
699 rawOutput: {
700 exitCode: 0,
701 stdout: '{ "name": "t3" }',
702 stderr: "",
703 },
704 },
705 });
706
707 yield* agent.client.sessionUpdate({
708 sessionId: requestedSessionId,
709 update: {
710 sessionUpdate: "agent_message_chunk",
711 content: { type: "text", text: "hello from mock" },
712 },
713 });
714
715 return { stopReason: cancelled ? "cancelled" : "end_turn" };
716 }
717
718 if (emitGenericToolPlaceholders) {
719 const toolCallId = "tool-call-generic-1";
720
721 yield* agent.client.sessionUpdate({
722 sessionId: requestedSessionId,
723 update: {
724 sessionUpdate: "tool_call",
725 toolCallId,
726 title: "Read File",
727 kind: "read",
728 status: "pending",
729 rawInput: {},
730 },
731 });
732
733 yield* agent.client.sessionUpdate({
734 sessionId: requestedSessionId,
735 update: {
736 sessionUpdate: "tool_call_update",
737 toolCallId,
738 status: "in_progress",
739 },
740 });
741
742 yield* agent.client.sessionUpdate({
743 sessionId: requestedSessionId,
744 update: {
745 sessionUpdate: "tool_call_update",
746 toolCallId,
747 status: "completed",
748 rawOutput: {
749 content: "package.json\n",
750 },
751 },
752 });
753
754 return { stopReason: "end_turn" };
755 }
756
757 if (emitAskQuestion) {
758 yield* agent.client.extRequest("cursor/ask_question", {
759 toolCallId: "ask-question-tool-call-1",
760 title: "Question",
761 questions: [
762 {
763 id: "scope",
764 prompt: "Which scope?",
765 options: [
766 { id: "workspace", label: "Workspace" },
767 { id: "session", label: "Session" },
768 ],
769 },
770 ],
771 });
772
773 return { stopReason: "end_turn" };
774 }
775
776 if (emitXAiAskUserQuestion) {
777 const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
778 method: "x.ai/ask_user_question",
779 params: {
780 sessionId: requestedSessionId,
781 toolCallId: "ask-user-question-tool-call-1",
782 questions: [
783 {
784 question: "Which scope should Grok use?",
785 multiSelect: null,
786 options: [
787 { label: "Workspace", description: "Use the current workspace" },
788 { label: "Session", description: "Only use this session" },
789 ],
790 },
791 ],
792 mode: "default",
793 },
794 });
795 if (typeof result !== "object" || result === null || !("outcome" in result)) {
796 throw new Error("Expected _x.ai/ask_user_question response outcome.");
797 }
798 if (result.outcome === "cancelled") {
799 return { stopReason: "end_turn" };
800 }
801 if (
802 result.outcome !== "accepted" ||
803 !("answers" in result) ||
804 typeof result.answers !== "object" ||
805 result.answers === null
806 ) {
807 throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
808 }
809
810 return { stopReason: "end_turn" };
811 }
812
813 if (emitForeignSessionUpdates) {
814 yield* agent.client.sessionUpdate({
815 sessionId: requestedSessionId,
816 update: {
817 sessionUpdate: "agent_message_chunk",
818 content: { type: "text", text: "root before child" },
819 },
820 });
821 yield* agent.client.sessionUpdate({
822 sessionId: "mock-child-session-1",
823 update: {
824 sessionUpdate: "agent_message_chunk",
825 content: { type: "text", text: "child content" },
826 },
827 });
828 yield* agent.client.sessionUpdate({
829 sessionId: "mock-child-session-1",
830 update: {
831 sessionUpdate: "tool_call",
832 toolCallId: "child-tool-call-1",
833 title: "Child-only tool",
834 kind: "other",
835 status: "pending",
836 rawInput: {},
837 },
838 });
839 yield* agent.client.sessionUpdate({
840 sessionId: requestedSessionId,
841 update: {
842 sessionUpdate: "agent_message_chunk",
843 content: { type: "text", text: " root after child" },
844 },
845 });
846 return { stopReason: "end_turn" };
847 }
848
849 yield* agent.client.sessionUpdate({
850 sessionId: requestedSessionId,
851 update: {
852 sessionUpdate: "plan",
853 entries: [
854 {
855 content: "Inspect mock ACP state",
856 priority: "high",
857 status: "completed",
858 },
859 {
860 content: "Implement the requested change",
861 priority: "high",
862 status: "in_progress",
863 },
864 ],
865 },
866 });
867
868 yield* agent.client.sessionUpdate({
869 sessionId: requestedSessionId,
870 update: {
871 sessionUpdate: "agent_message_chunk",
872 content: { type: "text", text: promptResponseText ?? "hello from mock" },
873 },
874 });
875
876 return { stopReason: "end_turn" };
877 }),
878 );
879
880 yield* agent.handleUnknownExtRequest((method, params) => {
881 if (method === "cursor/list_available_models") {
882 return Effect.succeed({
883 models: availableModels(),
884 });
885 }
886
887 if (method !== "session/mode/set") {
888 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
889 }
890
891 const nextModeId =
892 typeof params === "object" &&
893 params !== null &&
894 "modeId" in params &&
895 typeof params.modeId === "string"
896 ? params.modeId
897 : typeof params === "object" &&
898 params !== null &&
899 "mode" in params &&
900 typeof params.mode === "string"
901 ? params.mode
902 : undefined;
903 const requestedSessionId =
904 typeof params === "object" &&
905 params !== null &&
906 "sessionId" in params &&
907 typeof params.sessionId === "string"
908 ? params.sessionId
909 : sessionId;
910
911 if (typeof nextModeId === "string" && nextModeId.trim()) {
912 currentModeId = nextModeId.trim();
913 return agent.client
914 .sessionUpdate({
915 sessionId: requestedSessionId,
916 update: {
917 sessionUpdate: "current_mode_update",
918 currentModeId,
919 },
920 })
921 .pipe(Effect.as({}));
922 }
923
924 return Effect.succeed({});
925 });
926
927 return yield* Effect.never;
928}).pipe(
929 Effect.provide(
930 EffectAcpAgent.layerStdio(
931 requestLogPath
932 ? {
933 logIncoming: true,
934 logger: (event) => {
935 if (event.direction !== "incoming" || event.stage !== "raw") {
936 return Effect.void;
937 }
938 if (typeof event.payload !== "string") {
939 return Effect.void;
940 }
941 const payload = event.payload;
942 return Effect.sync(() => {
943 NodeFS.appendFileSync(
944 requestLogPath,
945 payload.endsWith("\n") ? payload : `${payload}\n`,
946 "utf8",
947 );
948 });
949 },
950 }
951 : {},
952 ),
953 ),
954 Effect.scoped,
955 Effect.provide(NodeServices.layer),
956);
957
958NodeRuntime.runMain(program);