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