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";
6import * as Deferred from "effect/Deferred";
7
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10
11import * as EffectAcpAgent from "effect-acp/agent";
12import * as AcpError from "effect-acp/errors";
13import type * as AcpSchema from "effect-acp/schema";
14
15const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
16const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
17const antigravityProfile = process.env.T3_ACP_ANTIGRAVITY === "1";
18const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
19const emitInterleavedAssistantToolCalls =
20 process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
21const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
22const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
23const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
24const emitXAiExitPlanMode = process.env.T3_ACP_EMIT_XAI_EXIT_PLAN_MODE === "1";
25const emitXAiPlanMdWrite = process.env.T3_ACP_EMIT_XAI_PLAN_MD_WRITE === "1";
26const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
27const emitXAiRateLimitThenHang = process.env.T3_ACP_EMIT_XAI_RATE_LIMIT_THEN_HANG === "1";
28const emitXAiAskUserQuestionThenHang =
29 process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION_THEN_HANG === "1";
30const emitContentThenHang = process.env.T3_ACP_EMIT_CONTENT_THEN_HANG === "1";
31const emitPlanThenHang = process.env.T3_ACP_EMIT_PLAN_THEN_HANG === "1";
32const emitActiveToolThenHang = process.env.T3_ACP_EMIT_ACTIVE_TOOL_THEN_HANG === "1";
33const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
34const waitForResumeRelease = process.env.T3_ACP_WAIT_FOR_RESUME_RELEASE === "1";
35const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1";
36const floodStderr = process.env.T3_ACP_FLOOD_STDERR === "1";
37const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
38const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
39const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
40const omitXAiPromptCompleteStopReason =
41 process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
42const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
43const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
44const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
45const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
46const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
47const emitStaleXAiPromptCompleteBeforeSecondHang =
48 process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
49const emitOverlappingXAiPromptCompleteOutOfOrder =
50 process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
51const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
52const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
53const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
54const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
55const initialGrokReasoningEffort =
56 process.env.T3_ACP_INITIAL_GROK_REASONING_EFFORT?.trim() || undefined;
57const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
58const permissionOptionIds = {
59 allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
60 allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
61 rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
62};
63const omitAllowAlways = process.env.T3_ACP_OMIT_ALLOW_ALWAYS === "1";
64const permissionRequestCount = Math.max(
65 1,
66 Number(process.env.T3_ACP_PERMISSION_REQUEST_COUNT ?? "1") || 1,
67);
68const sessionId = "mock-session-1";
69
70let currentModeId = antigravityProfile ? "default" : "ask";
71let currentModelId = antigravityProfile ? "gemini-test-low" : "default";
72let parameterizedModelPicker = false;
73let currentReasoning = "medium";
74let currentContext = "272k";
75let currentFast = false;
76let promptCount = 0;
77let overlappingFirstPromptId: string | undefined;
78const cancelledSessions = new Set<string>();
79
80function promptIdFromRequestMeta(
81 request: Pick<AcpSchema.PromptRequest, "_meta">,
82): string | undefined {
83 const meta = request._meta;
84 if (meta === null || typeof meta !== "object") {
85 return undefined;
86 }
87 const promptId = meta.promptId ?? meta.requestId;
88 return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
89}
90
91function logExit(reason: string): void {
92 if (!exitLogPath) {
93 return;
94 }
95 NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
96}
97
98function writeJsonRpcNotification(method: string, params: unknown): void {
99 process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
100}
101
102process.once("SIGTERM", () => {
103 logExit("SIGTERM");
104 process.exit(0);
105});
106
107process.once("SIGINT", () => {
108 logExit("SIGINT");
109 process.exit(0);
110});
111
112process.once("exit", (code) => {
113 logExit(`exit:${code}`);
114});
115
116function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
117 if (antigravityProfile) {
118 return [
119 {
120 id: "model",
121 name: "Model",
122 category: "model",
123 type: "select",
124 currentValue: currentModelId,
125 options: antigravityModels.map((model) => ({ value: model.modelId, name: model.name })),
126 },
127 {
128 id: "mode",
129 name: "Mode",
130 category: "mode",
131 type: "select",
132 currentValue: currentModeId,
133 options: availableModes.map((mode) => ({ value: mode.id, name: mode.name })),
134 },
135 ];
136 }
137 if (parameterizedModelPicker) {
138 const baseOptions: Array<AcpSchema.SessionConfigOption> = [
139 {
140 id: "mode",
141 name: "Mode",
142 category: "mode",
143 type: "select",
144 currentValue: currentModeId,
145 options: availableModes.map((mode) => ({
146 value: mode.id,
147 name: mode.name,
148 ...(mode.description ? { description: mode.description } : {}),
149 })),
150 },
151 {
152 id: "model",
153 name: "Model",
154 category: "model",
155 type: "select",
156 currentValue: currentModelId,
157 options: [
158 { value: "default", name: "Auto" },
159 { value: "composer-2", name: "Composer 2" },
160 { value: "gpt-5.4", name: "GPT-5.4" },
161 { value: "claude-opus-4-6", name: "Opus 4.6" },
162 ],
163 },
164 ];
165
166 switch (currentModelId) {
167 case "gpt-5.4":
168 return [
169 ...baseOptions,
170 {
171 id: "reasoning",
172 name: "Reasoning",
173 category: "thought_level",
174 type: "select",
175 currentValue: currentReasoning,
176 options: [
177 { value: "none", name: "None" },
178 { value: "low", name: "Low" },
179 { value: "medium", name: "Medium" },
180 { value: "high", name: "High" },
181 { value: "extra-high", name: "Extra High" },
182 ],
183 },
184 {
185 id: "context",
186 name: "Context",
187 category: "model_config",
188 type: "select",
189 currentValue: currentContext,
190 options: [
191 { value: "272k", name: "272K" },
192 { value: "1m", name: "1M" },
193 ],
194 },
195 {
196 id: "fast",
197 name: "Fast",
198 category: "model_config",
199 type: "select",
200 currentValue: String(currentFast),
201 options: [
202 { value: "false", name: "Off" },
203 { value: "true", name: "Fast" },
204 ],
205 },
206 ];
207 case "composer-2":
208 return [
209 ...baseOptions,
210 {
211 id: "fast",
212 name: "Fast",
213 category: "model_config",
214 type: "select",
215 currentValue: String(currentFast),
216 options: [
217 { value: "false", name: "Off" },
218 { value: "true", name: "Fast" },
219 ],
220 },
221 ];
222 case "claude-opus-4-6":
223 return [
224 ...baseOptions,
225 {
226 id: "reasoning",
227 name: "Reasoning",
228 category: "thought_level",
229 type: "select",
230 currentValue: currentReasoning,
231 options: [
232 { value: "low", name: "Low" },
233 { value: "medium", name: "Medium" },
234 { value: "high", name: "High" },
235 ],
236 },
237 {
238 id: "thinking",
239 name: "Thinking",
240 category: "model_config",
241 type: "boolean",
242 currentValue: true,
243 },
244 ];
245 default:
246 return baseOptions;
247 }
248 }
249
250 return [
251 {
252 id: "model",
253 name: "Model",
254 category: "model",
255 type: "select" as const,
256 currentValue: currentModelId,
257 options: [
258 { value: "default", name: "Auto" },
259 { value: "composer-2", name: "Composer 2" },
260 { value: "composer-2[fast=true]", name: "Composer 2 Fast" },
261 { value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
262 ],
263 },
264 ];
265}
266
267function modelConfigOptionsFor(modelId: string): ReadonlyArray<AcpSchema.SessionConfigOption> {
268 const previousModelId = currentModelId;
269 try {
270 currentModelId = modelId;
271 return configOptions().filter(
272 (option) => option.category !== "mode" && option.category !== "model",
273 );
274 } finally {
275 currentModelId = previousModelId;
276 }
277}
278
279function availableModels(): ReadonlyArray<{
280 readonly value: string;
281 readonly name: string;
282 readonly configOptions: ReadonlyArray<AcpSchema.SessionConfigOption>;
283}> {
284 return [
285 { value: "default", name: "Auto" },
286 { value: "composer-2", name: "Composer 2" },
287 { value: "gpt-5.4", name: "GPT-5.4" },
288 { value: "claude-opus-4-6", name: "Opus 4.6" },
289 ].map((model) => ({
290 value: model.value,
291 name: model.name,
292 configOptions: modelConfigOptionsFor(model.value),
293 }));
294}
295
296const antigravityModels = [
297 { modelId: "gemini-test-low", name: "Gemini Test Low" },
298 { modelId: "gemini-test-high", name: "Gemini Test High" },
299] satisfies ReadonlyArray<AcpSchema.ModelInfo>;
300
301const availableModes: ReadonlyArray<AcpSchema.SessionMode> = antigravityProfile
302 ? [
303 { id: "default", name: "Default" },
304 { id: "auto_edit", name: "Auto edit" },
305 { id: "yolo", name: "YOLO" },
306 ]
307 : [
308 {
309 id: "ask",
310 name: "Ask",
311 description: "Request permission before making any changes",
312 },
313 {
314 id: "architect",
315 name: "Architect",
316 description: "Design and plan software systems without implementation",
317 },
318 {
319 id: "code",
320 name: "Code",
321 description: "Write and modify code with full tool access",
322 },
323 ];
324
325function modeState(): AcpSchema.SessionModeState {
326 return {
327 currentModeId,
328 availableModes,
329 };
330}
331
332// Mirrors the real Grok ACP: it advertises versioned model ids, never the CLI's own
333// "grok-build" product name, and it rejects unknown ids in session/set_model.
334const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
335 {
336 modelId: "grok-4.6",
337 name: "Grok 4.6",
338 _meta: {
339 totalContextTokens: 500_000,
340 supportsReasoningEffort: true,
341 reasoningEffort: initialGrokReasoningEffort ?? "high",
342 reasoningEfforts: [
343 { id: "xhigh", value: "xhigh", label: "Extra High Effort", default: false },
344 { id: "high", value: "high", label: "High Effort", default: true },
345 { id: "low", value: "low", label: "Low Effort", default: false },
346 ],
347 },
348 },
349 { modelId: "grok-mock-alt", name: "Grok Mock Alt" },
350];
351
352function modelState(): AcpSchema.SessionModelState {
353 if (process.env.T3_ACP_CURSOR_MODELS_ERROR === "missing") {
354 return {
355 currentModelId: " grok-4.6 ",
356 availableModels: [
357 { modelId: " grok-4.6 ", name: " Grok 4.6 " },
358 { modelId: "grok-mock-alt", name: " Grok Mock Alt " },
359 { modelId: "blank-name", name: " " },
360 { modelId: " ", name: "Invalid" },
361 ],
362 };
363 }
364 if (antigravityProfile) {
365 return { currentModelId, availableModels: antigravityModels };
366 }
367 const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
368 ? currentModelId
369 : "grok-4.6";
370 return {
371 currentModelId: modelId,
372 availableModels: grokAcpModels,
373 };
374}
375
376const program = Effect.gen(function* () {
377 const agent = yield* EffectAcpAgent.AcpAgent;
378 const resumeRelease = yield* Deferred.make<void>();
379 const nativeCancelRequested = yield* Deferred.make<void>();
380 const nativeCancelRelease = yield* Deferred.make<void>();
381 const publishAntigravityCommands = (targetSessionId: string) =>
382 agent.client.sessionUpdate({
383 sessionId: targetSessionId,
384 update: {
385 sessionUpdate: "available_commands_update",
386 availableCommands: [
387 { name: "plan", description: "Plan a task", input: { hint: "task" } },
388 { name: "logout", description: "Sign out" },
389 ],
390 },
391 });
392
393 yield* agent.handleInitialize((request) =>
394 Effect.gen(function* () {
395 if (floodStderr) {
396 yield* Effect.promise(
397 () =>
398 new Promise<void>((resolve) => {
399 process.stderr.write("stderr".repeat(350_000), () => resolve());
400 }),
401 );
402 }
403 parameterizedModelPicker =
404 request.clientCapabilities?._meta?.parameterizedModelPicker === true;
405 if (antigravityProfile) {
406 return {
407 protocolVersion: 1,
408 agentInfo: { name: "antigravity-acp", version: "mock" },
409 agentCapabilities: {
410 loadSession: true,
411 sessionCapabilities: { resume: {} },
412 auth: { logout: {} },
413 promptCapabilities: { image: true, embeddedContext: true },
414 },
415 authMethods: [{ id: "oauth-personal", name: "Sign in with Google" }],
416 };
417 }
418 return {
419 protocolVersion: 1,
420 agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } },
421 // Grok advertises model state before any session exists; the provider
422 // health check reads it from here without authenticating.
423 _meta: { modelState: modelState() },
424 };
425 }),
426 );
427
428 // Mirrors the real agent: the API key method reads GEMINI_API_KEY from the
429 // process environment and rejects when it is missing.
430 yield* agent.handleAuthenticate((request) =>
431 !antigravityProfile || request.methodId === "oauth-personal"
432 ? Effect.succeed({})
433 : request.methodId === "gemini-api-key" && process.env.GEMINI_API_KEY
434 ? Effect.succeed({})
435 : Effect.fail(
436 AcpError.AcpRequestError.invalidParams(
437 `Mock Antigravity rejected auth method ${request.methodId}.`,
438 ),
439 ),
440 );
441 if (antigravityProfile) {
442 yield* agent.handleLogout(() => Effect.succeed({}));
443 }
444
445 yield* agent.handleCreateSession(() =>
446 Effect.gen(function* () {
447 if (antigravityProfile) {
448 yield* publishAntigravityCommands(sessionId);
449 }
450 return {
451 sessionId,
452 modes: modeState(),
453 models: modelState(),
454 configOptions: configOptions(),
455 };
456 }),
457 );
458
459 yield* agent.handleResumeSession((request) =>
460 Effect.gen(function* () {
461 yield* agent.client.sessionUpdate({
462 sessionId: request.sessionId,
463 update: {
464 sessionUpdate: "user_message_chunk",
465 content: { type: "text", text: "native-resume-started" },
466 },
467 });
468 if (waitForResumeRelease) {
469 yield* Deferred.await(resumeRelease);
470 }
471 if (antigravityProfile) {
472 yield* publishAntigravityCommands(request.sessionId);
473 }
474 return {
475 modes: modeState(),
476 models: modelState(),
477 configOptions: configOptions(),
478 _meta: { nativeResume: true },
479 };
480 }),
481 );
482
483 const emitLoadReplayNotifications = (requestedSessionId: string) => {
484 writeJsonRpcNotification("session/update", {
485 _meta: { isReplay: true },
486 sessionId: requestedSessionId,
487 update: {
488 sessionUpdate: "tool_call",
489 toolCallId: "replay-tool-1",
490 title: "Replay tool",
491 kind: "search",
492 status: "completed",
493 },
494 });
495 writeJsonRpcNotification("session/update", {
496 _meta: { isReplay: true },
497 sessionId: requestedSessionId,
498 update: {
499 sessionUpdate: "agent_message_chunk",
500 content: { type: "text", text: "replayed assistant text" },
501 },
502 });
503 };
504
505 yield* agent.handleLoadSession((request) =>
506 Effect.gen(function* () {
507 const requestedSessionId = String(request.sessionId ?? sessionId);
508 if (failLoadSession) {
509 return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
510 }
511 if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
512 emitLoadReplayNotifications(requestedSessionId);
513 yield* agent.client.sessionUpdate({
514 sessionId: requestedSessionId,
515 update: {
516 sessionUpdate: "user_message_chunk",
517 content: { type: "text", text: "replay-tail" },
518 },
519 });
520 yield* Effect.sleep(loadSessionDelayMs);
521 return {
522 modes: modeState(),
523 models: modelState(),
524 configOptions: configOptions(),
525 };
526 }
527 if (emitLoadReplay) {
528 emitLoadReplayNotifications(requestedSessionId);
529 }
530 yield* agent.client.sessionUpdate({
531 sessionId: requestedSessionId,
532 update: {
533 sessionUpdate: "user_message_chunk",
534 content: { type: "text", text: "replay" },
535 },
536 });
537 return {
538 modes: modeState(),
539 models: modelState(),
540 configOptions: configOptions(),
541 };
542 }),
543 );
544
545 yield* agent.handleSetSessionModel((request) =>
546 Effect.gen(function* () {
547 if (!modelState().availableModels.some((model) => model.modelId === request.modelId)) {
548 return yield* AcpError.AcpRequestError.invalidParams(
549 `Unknown mock model id: ${request.modelId}`,
550 {
551 method: "session/set_model",
552 params: request,
553 },
554 );
555 }
556 currentModelId = request.modelId;
557 return {};
558 }),
559 );
560
561 yield* agent.handleSetSessionConfigOption((request) =>
562 Effect.gen(function* () {
563 if (exitOnSetConfigOption) {
564 return yield* Effect.sync(() => {
565 process.exit(7);
566 });
567 }
568 if (failSetConfigOption) {
569 return yield* AcpError.AcpRequestError.invalidParams(
570 "Mock invalid params for session/set_config_option",
571 {
572 method: "session/set_config_option",
573 params: request,
574 },
575 );
576 }
577 if (request.configId === "mode" && typeof request.value === "string") {
578 currentModeId = request.value;
579 }
580 if (request.configId === "model" && typeof request.value === "string") {
581 currentModelId = request.value;
582 }
583 if (request.configId === "reasoning" && typeof request.value === "string") {
584 currentReasoning = request.value;
585 }
586 if (request.configId === "context" && typeof request.value === "string") {
587 currentContext = request.value;
588 }
589 if (request.configId === "fast") {
590 currentFast = request.value === true || request.value === "true";
591 }
592 return {
593 configOptions: configOptions(),
594 };
595 }),
596 );
597
598 yield* agent.handleCancel(({ sessionId }) =>
599 Effect.gen(function* () {
600 const cancelledSessionId = String(sessionId ?? "mock-session-1");
601 cancelledSessions.add(cancelledSessionId);
602 if (completeFirstPromptOnCancel) {
603 yield* Deferred.succeed(nativeCancelRequested, undefined);
604 yield* agent.client.sessionUpdate({
605 sessionId: cancelledSessionId,
606 update: {
607 sessionUpdate: "agent_thought_chunk",
608 content: { type: "text", text: "native-cancel-received" },
609 },
610 });
611 }
612 if (emitLateUpdateAfterCancel) {
613 yield* Effect.sleep("50 millis");
614 yield* Effect.sync(() => {
615 writeJsonRpcNotification("session/update", {
616 sessionId: cancelledSessionId,
617 update: {
618 sessionUpdate: "agent_message_chunk",
619 content: { type: "text", text: "late after cancel" },
620 },
621 });
622 });
623 }
624 }),
625 );
626
627 yield* agent.handlePrompt((request) =>
628 Effect.gen(function* () {
629 const requestedSessionId = String(request.sessionId ?? sessionId);
630 promptCount += 1;
631
632 if (completeFirstPromptOnCancel && promptCount === 1) {
633 yield* agent.client.sessionUpdate({
634 sessionId: requestedSessionId,
635 update: {
636 sessionUpdate: "tool_call",
637 toolCallId: "native-cancel-tool",
638 title: "Long command",
639 kind: "execute",
640 status: "in_progress",
641 },
642 });
643 yield* Deferred.await(nativeCancelRequested);
644 yield* Deferred.await(nativeCancelRelease);
645 yield* agent.client.sessionUpdate({
646 sessionId: requestedSessionId,
647 update: {
648 sessionUpdate: "tool_call_update",
649 toolCallId: "native-cancel-tool",
650 status: "failed",
651 content: [{ type: "content", content: { type: "text", text: "Cancelled." } }],
652 },
653 });
654 yield* agent.client.sessionUpdate({
655 sessionId: requestedSessionId,
656 update: {
657 sessionUpdate: "agent_message_chunk",
658 content: { type: "text", text: "Request cancelled." },
659 },
660 });
661 return { stopReason: "cancelled", _meta: { nativeCancel: true } };
662 }
663
664 if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
665 yield* Effect.sleep(`${promptDelayMs} millis`);
666 }
667
668 if (failPrompt) {
669 return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
670 }
671
672 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
673 return {
674 stopReason: "end_turn",
675 _meta: {
676 promptId: "mock-stale-xai-prompt-1",
677 requestId: "mock-stale-xai-prompt-1",
678 },
679 };
680 }
681
682 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
683 const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
684 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
685 sessionId: requestedSessionId,
686 promptId: "mock-stale-xai-prompt-1",
687 stopReason: "end_turn",
688 agentResult: null,
689 });
690
691 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
692 sessionId: requestedSessionId,
693 promptId: currentPromptId,
694 stopReason: "end_turn",
695 agentResult: null,
696 });
697
698 return yield* Effect.never;
699 }
700
701 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
702 overlappingFirstPromptId = promptIdFromRequestMeta(request);
703 return yield* Effect.never;
704 }
705
706 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
707 const secondPromptId = promptIdFromRequestMeta(request);
708 if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
709 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
710 sessionId: requestedSessionId,
711 promptId: secondPromptId,
712 stopReason: "end_turn",
713 agentResult: null,
714 });
715 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
716 sessionId: requestedSessionId,
717 promptId: overlappingFirstPromptId,
718 stopReason: "end_turn",
719 agentResult: null,
720 });
721 }
722 return yield* Effect.never;
723 }
724
725 if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
726 return yield* Effect.never;
727 }
728
729 if (emitXAiRateLimitThenHang) {
730 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
731 sessionId: requestedSessionId,
732 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-rate-limit-prompt-1",
733 stopReason: "rate_limit",
734 agentResult: null,
735 });
736 return yield* Effect.never;
737 }
738
739 if (emitContentThenHang) {
740 yield* agent.client.sessionUpdate({
741 sessionId: requestedSessionId,
742 update: {
743 sessionUpdate: "agent_message_chunk",
744 content: { type: "text", text: "partial before stall" },
745 },
746 });
747 return yield* Effect.never;
748 }
749
750 if (emitPlanThenHang) {
751 yield* agent.client.sessionUpdate({
752 sessionId: requestedSessionId,
753 update: {
754 sessionUpdate: "plan",
755 entries: [
756 {
757 content: "Wait for more ACP progress",
758 priority: "high",
759 status: "in_progress",
760 },
761 ],
762 },
763 });
764 return yield* Effect.never;
765 }
766
767 if (emitActiveToolThenHang) {
768 const toolCallId = "tool-call-long-running-1";
769 yield* agent.client.sessionUpdate({
770 sessionId: requestedSessionId,
771 update: {
772 sessionUpdate: "tool_call",
773 toolCallId,
774 title: "Long-running tool",
775 kind: "execute",
776 status: "pending",
777 rawInput: { command: ["long-running-tool"] },
778 },
779 });
780 yield* agent.client.sessionUpdate({
781 sessionId: requestedSessionId,
782 update: {
783 sessionUpdate: "tool_call_update",
784 toolCallId,
785 status: "in_progress",
786 },
787 });
788 return yield* Effect.never;
789 }
790
791 if (emitXAiPromptCompleteThenHang) {
792 writeJsonRpcNotification("session/update", {
793 sessionId: requestedSessionId,
794 update: {
795 sessionUpdate: "agent_message_chunk",
796 content: { type: "text", text: "hello from " },
797 },
798 });
799
800 if (emitForeignSessionUpdates) {
801 writeJsonRpcNotification("session/update", {
802 sessionId: "mock-child-session-1",
803 update: {
804 sessionUpdate: "agent_message_chunk",
805 content: { type: "text", text: "child before completion" },
806 },
807 });
808 }
809
810 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
811 sessionId: requestedSessionId,
812 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
813 ...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
814 agentResult: null,
815 });
816
817 if (emitForeignSessionUpdates) {
818 writeJsonRpcNotification("session/update", {
819 sessionId: "mock-child-session-1",
820 update: {
821 sessionUpdate: "tool_call",
822 toolCallId: "child-tool-call-1",
823 title: "Child-only tool",
824 kind: "other",
825 status: "pending",
826 rawInput: {},
827 },
828 });
829 writeJsonRpcNotification("session/update", {
830 sessionId: "mock-child-session-1",
831 update: {
832 sessionUpdate: "agent_message_chunk",
833 content: { type: "text", text: "child after completion" },
834 },
835 });
836 }
837
838 writeJsonRpcNotification("session/update", {
839 sessionId: requestedSessionId,
840 update: {
841 sessionUpdate: "agent_message_chunk",
842 content: { type: "text", text: "mock" },
843 },
844 });
845
846 return yield* Effect.never;
847 }
848
849 if (emitInterleavedAssistantToolCalls) {
850 const toolCallId = "tool-call-1";
851
852 yield* agent.client.sessionUpdate({
853 sessionId: requestedSessionId,
854 update: {
855 sessionUpdate: "agent_message_chunk",
856 content: { type: "text", text: "before tool" },
857 },
858 });
859
860 yield* agent.client.sessionUpdate({
861 sessionId: requestedSessionId,
862 update: {
863 sessionUpdate: "tool_call",
864 toolCallId,
865 title: "Terminal",
866 kind: "execute",
867 status: "pending",
868 rawInput: {
869 command: ["echo", "hello"],
870 },
871 },
872 });
873
874 yield* agent.client.sessionUpdate({
875 sessionId: requestedSessionId,
876 update: {
877 sessionUpdate: "tool_call_update",
878 toolCallId,
879 status: "completed",
880 rawOutput: {
881 exitCode: 0,
882 stdout: "hello",
883 stderr: "",
884 },
885 },
886 });
887
888 yield* agent.client.sessionUpdate({
889 sessionId: requestedSessionId,
890 update: {
891 sessionUpdate: "agent_message_chunk",
892 content: { type: "text", text: "after tool" },
893 },
894 });
895
896 return { stopReason: "end_turn" };
897 }
898
899 if (emitToolCalls) {
900 const toolCallId = "tool-call-1";
901
902 yield* agent.client.sessionUpdate({
903 sessionId: requestedSessionId,
904 update: {
905 sessionUpdate: "tool_call",
906 toolCallId,
907 title: "Terminal",
908 kind: "execute",
909 status: "pending",
910 rawInput: {
911 command: ["cat", "server/package.json"],
912 },
913 },
914 });
915
916 yield* agent.client.sessionUpdate({
917 sessionId: requestedSessionId,
918 update: {
919 sessionUpdate: "tool_call_update",
920 toolCallId,
921 status: "in_progress",
922 },
923 });
924
925 const permissionOptions: Array<AcpSchema.PermissionOption> = [
926 { optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
927 ...(omitAllowAlways
928 ? []
929 : [
930 {
931 optionId: permissionOptionIds.allowAlways,
932 name: "Allow always",
933 kind: "allow_always" as const,
934 },
935 ]),
936 { optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
937 ];
938
939 let cancelled = cancelledSessions.delete(requestedSessionId);
940 for (let index = 0; index < permissionRequestCount; index++) {
941 const command =
942 index > 0
943 ? (process.env.T3_ACP_SECOND_PERMISSION_COMMAND ?? "cat server/package.json")
944 : "cat server/package.json";
945 const permission = yield* agent.client.requestPermission({
946 sessionId: requestedSessionId,
947 toolCall: {
948 toolCallId: index === 0 ? toolCallId : `${toolCallId}-${index + 1}`,
949 title: process.env.T3_ACP_PERMISSION_TITLE ?? `\`${command}\``,
950 kind: "execute",
951 status: "pending",
952 rawInput: {
953 variant: "Bash",
954 command,
955 description: index === 0 ? "Read package metadata" : "Read it again",
956 },
957 content: [
958 {
959 type: "content",
960 content: {
961 type: "text",
962 text: `Not in allowlist: ${command}`,
963 },
964 },
965 ],
966 },
967 options: permissionOptions,
968 });
969 cancelled =
970 cancelled ||
971 cancelledSessions.delete(requestedSessionId) ||
972 permission.outcome.outcome === "cancelled";
973 if (cancelled) {
974 break;
975 }
976 }
977
978 yield* agent.client.sessionUpdate({
979 sessionId: requestedSessionId,
980 update: {
981 sessionUpdate: "tool_call_update",
982 toolCallId,
983 title: "Terminal",
984 kind: "execute",
985 status: "completed",
986 rawOutput: {
987 exitCode: 0,
988 stdout: '{ "name": "t3" }',
989 stderr: "",
990 },
991 },
992 });
993
994 yield* agent.client.sessionUpdate({
995 sessionId: requestedSessionId,
996 update: {
997 sessionUpdate: "agent_message_chunk",
998 content: { type: "text", text: "hello from mock" },
999 },
1000 });
1001
1002 return { stopReason: cancelled ? "cancelled" : "end_turn" };
1003 }
1004
1005 if (emitGenericToolPlaceholders) {
1006 const toolCallId = "tool-call-generic-1";
1007
1008 yield* agent.client.sessionUpdate({
1009 sessionId: requestedSessionId,
1010 update: {
1011 sessionUpdate: "tool_call",
1012 toolCallId,
1013 title: "Read File",
1014 kind: "read",
1015 status: "pending",
1016 rawInput: {},
1017 },
1018 });
1019
1020 yield* agent.client.sessionUpdate({
1021 sessionId: requestedSessionId,
1022 update: {
1023 sessionUpdate: "tool_call_update",
1024 toolCallId,
1025 status: "in_progress",
1026 },
1027 });
1028
1029 yield* agent.client.sessionUpdate({
1030 sessionId: requestedSessionId,
1031 update: {
1032 sessionUpdate: "tool_call_update",
1033 toolCallId,
1034 status: "completed",
1035 rawOutput: {
1036 content: "package.json\n",
1037 },
1038 },
1039 });
1040
1041 return { stopReason: "end_turn" };
1042 }
1043
1044 if (emitAskQuestion) {
1045 yield* agent.client.extRequest("cursor/ask_question", {
1046 toolCallId: "ask-question-tool-call-1",
1047 title: "Question",
1048 questions: [
1049 {
1050 id: "scope",
1051 prompt: "Which scope?",
1052 options: [
1053 { id: "workspace", label: "Workspace" },
1054 { id: "session", label: "Session" },
1055 ],
1056 },
1057 ],
1058 });
1059
1060 return { stopReason: "end_turn" };
1061 }
1062
1063 if (emitXAiAskUserQuestion || emitXAiAskUserQuestionThenHang) {
1064 const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
1065 method: "x.ai/ask_user_question",
1066 params: {
1067 sessionId: requestedSessionId,
1068 toolCallId: "ask-user-question-tool-call-1",
1069 questions: [
1070 {
1071 question: "Which scope should Grok use?",
1072 multiSelect: null,
1073 options: [
1074 { label: "Workspace", description: "Use the current workspace" },
1075 { label: "Session", description: "Only use this session" },
1076 ],
1077 },
1078 ],
1079 mode: "default",
1080 },
1081 });
1082 if (typeof result !== "object" || result === null || !("outcome" in result)) {
1083 throw new Error("Expected _x.ai/ask_user_question response outcome.");
1084 }
1085 if (result.outcome === "cancelled") {
1086 return { stopReason: "end_turn" };
1087 }
1088 if (
1089 result.outcome !== "accepted" ||
1090 !("answers" in result) ||
1091 typeof result.answers !== "object" ||
1092 result.answers === null
1093 ) {
1094 throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
1095 }
1096
1097 if (emitXAiAskUserQuestionThenHang) {
1098 return yield* Effect.never;
1099 }
1100
1101 return { stopReason: "end_turn" };
1102 }
1103
1104 if (emitXAiPlanMdWrite) {
1105 // Match Grok's real session layout so isGrokPlanMarkdownPath accepts it.
1106 const planRoot = process.env.T3_ACP_PLAN_ROOT ?? "/tmp/mock-home/.grok";
1107 const planPath = `${planRoot}/sessions/${requestedSessionId}/plan.md`;
1108 const planBody = "# Mock plan\n\n- Write the feature\n- Add a test\n- Ship it\n";
1109 // enter_plan_mode first so the adapter arms planModeActive.
1110 yield* agent.client.sessionUpdate({
1111 sessionId: requestedSessionId,
1112 update: {
1113 sessionUpdate: "tool_call",
1114 toolCallId: "enter-plan-mode-1",
1115 title: "enter_plan_mode",
1116 kind: "other",
1117 status: "completed",
1118 rawInput: { variant: "EnterPlanMode" },
1119 },
1120 });
1121 yield* agent.client.sessionUpdate({
1122 sessionId: requestedSessionId,
1123 update: {
1124 sessionUpdate: "tool_call",
1125 toolCallId: "plan-md-write-1",
1126 title: "write",
1127 kind: "edit",
1128 status: "pending",
1129 rawInput: { file_path: planPath, content: planBody },
1130 },
1131 });
1132 yield* agent.client.sessionUpdate({
1133 sessionId: requestedSessionId,
1134 update: {
1135 sessionUpdate: "tool_call_update",
1136 toolCallId: "plan-md-write-1",
1137 kind: "edit",
1138 status: "completed",
1139 title: `Write \`${planPath}\``,
1140 rawInput: { file_path: planPath, content: planBody },
1141 content: [
1142 {
1143 type: "diff",
1144 path: planPath,
1145 oldText: "",
1146 newText: planBody,
1147 },
1148 ],
1149 },
1150 });
1151 return { stopReason: "end_turn" };
1152 }
1153
1154 if (emitXAiExitPlanMode) {
1155 const result = yield* agent.client.extRequest("_x.ai/exit_plan_mode", {
1156 method: "x.ai/exit_plan_mode",
1157 params: {
1158 sessionId: requestedSessionId,
1159 toolCallId: "exit-plan-mode-tool-call-1",
1160 planContent: "# Exit plan\n\n- Step one\n- Step two\n",
1161 },
1162 });
1163 if (typeof result !== "object" || result === null || !("outcome" in result)) {
1164 throw new Error("Expected _x.ai/exit_plan_mode response outcome.");
1165 }
1166 if (
1167 result.outcome !== "abandoned" &&
1168 result.outcome !== "approved" &&
1169 result.outcome !== "request_changes"
1170 ) {
1171 throw new Error(
1172 `Expected exit_plan_mode outcome abandoned|approved|request_changes, got ${String(result.outcome)}`,
1173 );
1174 }
1175 return { stopReason: "end_turn" };
1176 }
1177
1178 if (emitForeignSessionUpdates) {
1179 yield* agent.client.sessionUpdate({
1180 sessionId: requestedSessionId,
1181 update: {
1182 sessionUpdate: "agent_message_chunk",
1183 content: { type: "text", text: "root before child" },
1184 },
1185 });
1186 yield* agent.client.sessionUpdate({
1187 sessionId: "mock-child-session-1",
1188 update: {
1189 sessionUpdate: "agent_message_chunk",
1190 content: { type: "text", text: "child content" },
1191 },
1192 });
1193 yield* agent.client.sessionUpdate({
1194 sessionId: "mock-child-session-1",
1195 update: {
1196 sessionUpdate: "tool_call",
1197 toolCallId: "child-tool-call-1",
1198 title: "Child-only tool",
1199 kind: "other",
1200 status: "pending",
1201 rawInput: {},
1202 },
1203 });
1204 yield* agent.client.sessionUpdate({
1205 sessionId: requestedSessionId,
1206 update: {
1207 sessionUpdate: "agent_message_chunk",
1208 content: { type: "text", text: " root after child" },
1209 },
1210 });
1211 return { stopReason: "end_turn" };
1212 }
1213
1214 yield* agent.client.sessionUpdate({
1215 sessionId: requestedSessionId,
1216 update: {
1217 sessionUpdate: "plan",
1218 entries: [
1219 {
1220 content: "Inspect mock ACP state",
1221 priority: "high",
1222 status: "completed",
1223 },
1224 {
1225 content: "Implement the requested change",
1226 priority: "high",
1227 status: "in_progress",
1228 },
1229 ],
1230 },
1231 });
1232
1233 yield* agent.client.sessionUpdate({
1234 sessionId: requestedSessionId,
1235 update: {
1236 sessionUpdate: "agent_message_chunk",
1237 content: { type: "text", text: promptResponseText ?? "hello from mock" },
1238 },
1239 });
1240
1241 return { stopReason: "end_turn" };
1242 }),
1243 );
1244
1245 yield* agent.handleUnknownExtRequest((method, params) => {
1246 if (method === "_test/environment") {
1247 return Effect.succeed({
1248 inherited: process.env.T3_ACP_RUNTIME_AMBIENT === "sentinel",
1249 explicit: process.env.T3_ACP_RUNTIME_EXPLICIT === "kept",
1250 });
1251 }
1252 if (method === "_test/release-resume") {
1253 return Deferred.succeed(resumeRelease, undefined).pipe(Effect.as({}));
1254 }
1255 if (method === "_test/finish-cancel") {
1256 return Deferred.succeed(nativeCancelRelease, undefined).pipe(Effect.as({}));
1257 }
1258 if (method === "_test/startup-metadata") {
1259 return Effect.gen(function* () {
1260 for (const [metadataSessionId, commandName, modeId] of [
1261 [sessionId, "plan", "code"],
1262 ["child-session", "foreign-command", "ask"],
1263 ] as const) {
1264 yield* agent.client.sessionUpdate({
1265 sessionId: metadataSessionId,
1266 update: {
1267 sessionUpdate: "available_commands_update",
1268 availableCommands: [{ name: commandName, description: "Native command" }],
1269 },
1270 });
1271 yield* agent.client.sessionUpdate({
1272 sessionId: metadataSessionId,
1273 update: { sessionUpdate: "current_mode_update", currentModeId: modeId },
1274 });
1275 yield* agent.client.sessionUpdate({
1276 sessionId: metadataSessionId,
1277 update: {
1278 sessionUpdate: "config_option_update",
1279 configOptions: configOptions().map((option) =>
1280 option.type === "select" && option.category === "model"
1281 ? {
1282 ...option,
1283 currentValue: metadataSessionId === sessionId ? "gpt-5.4" : "default",
1284 }
1285 : option,
1286 ),
1287 },
1288 });
1289 yield* agent.client.sessionUpdate({
1290 sessionId: metadataSessionId,
1291 update: {
1292 sessionUpdate: "agent_message_chunk",
1293 content: { type: "text", text: "Startup transcript must not replay." },
1294 },
1295 });
1296 }
1297 return {};
1298 });
1299 }
1300 if (method === "cursor/list_available_models") {
1301 if (process.env.T3_ACP_CURSOR_MODELS_ERROR === "missing") {
1302 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
1303 }
1304 if (process.env.T3_ACP_CURSOR_MODELS_ERROR === "internal") {
1305 return Effect.fail(AcpError.AcpRequestError.internalError("Mock model discovery failure"));
1306 }
1307 return Effect.succeed({
1308 models: availableModels(),
1309 });
1310 }
1311
1312 if (method !== "session/mode/set") {
1313 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
1314 }
1315
1316 const nextModeId =
1317 typeof params === "object" &&
1318 params !== null &&
1319 "modeId" in params &&
1320 typeof params.modeId === "string"
1321 ? params.modeId
1322 : typeof params === "object" &&
1323 params !== null &&
1324 "mode" in params &&
1325 typeof params.mode === "string"
1326 ? params.mode
1327 : undefined;
1328 const requestedSessionId =
1329 typeof params === "object" &&
1330 params !== null &&
1331 "sessionId" in params &&
1332 typeof params.sessionId === "string"
1333 ? params.sessionId
1334 : sessionId;
1335
1336 if (typeof nextModeId === "string" && nextModeId.trim()) {
1337 currentModeId = nextModeId.trim();
1338 return agent.client
1339 .sessionUpdate({
1340 sessionId: requestedSessionId,
1341 update: {
1342 sessionUpdate: "current_mode_update",
1343 currentModeId,
1344 },
1345 })
1346 .pipe(Effect.as({}));
1347 }
1348
1349 return Effect.succeed({});
1350 });
1351
1352 yield* agent.handleUnknownExtNotification((method) =>
1353 method === "_test/exit" ? Effect.sync(() => process.exit(19)) : Effect.void,
1354 );
1355
1356 return yield* Effect.never;
1357}).pipe(
1358 Effect.provide(
1359 EffectAcpAgent.layerStdio(
1360 requestLogPath
1361 ? {
1362 logIncoming: true,
1363 logger: (event) => {
1364 if (event.direction !== "incoming" || event.stage !== "raw") {
1365 return Effect.void;
1366 }
1367 if (typeof event.payload !== "string") {
1368 return Effect.void;
1369 }
1370 const payload = event.payload;
1371 return Effect.sync(() => {
1372 NodeFS.appendFileSync(
1373 requestLogPath,
1374 payload.endsWith("\n") ? payload : `${payload}\n`,
1375 "utf8",
1376 );
1377 });
1378 },
1379 }
1380 : {},
1381 ),
1382 ),
1383 Effect.scoped,
1384 Effect.provide(NodeServices.layer),
1385);
1386
1387NodeRuntime.runMain(program);