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

acp-mock-agent.ts

1,374 lines44.0 KB

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