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

acp-mock-agent.ts

1,370 lines43.7 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 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;
90​
91function logExit(reason: string): void {
92 if (!exitLogPath) {
93 return;
94 }
95 NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
97​
98function writeJsonRpcNotification(method: string, params: unknown): void {
99 process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
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 ];
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 }
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 }));
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 };
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 (antigravityProfile) {
354 return { currentModelId, availableModels: antigravityModels };
355 }
356 const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
357 ? currentModelId
358 : "grok-4.6";
359 return {
360 currentModelId: modelId,
361 availableModels: grokAcpModels,
362 };
364​
365const program = Effect.gen(function* () {
366 const agent = yield* EffectAcpAgent.AcpAgent;
367 const resumeRelease = yield* Deferred.make<void>();
368 const nativeCancelRequested = yield* Deferred.make<void>();
369 const nativeCancelRelease = yield* Deferred.make<void>();
370 const publishAntigravityCommands = (targetSessionId: string) =>
371 agent.client.sessionUpdate({
372 sessionId: targetSessionId,
373 update: {
374 sessionUpdate: "available_commands_update",
375 availableCommands: [
376 { name: "plan", description: "Plan a task", input: { hint: "task" } },
377 { name: "logout", description: "Sign out" },
378 ],
379 },
380 });
381​
382 yield* agent.handleInitialize((request) =>
383 Effect.gen(function* () {
384 if (floodStderr) {
385 yield* Effect.promise(
386 () =>
387 new Promise<void>((resolve) => {
388 process.stderr.write("stderr".repeat(350_000), () => resolve());
389 }),
390 );
391 }
392 parameterizedModelPicker =
393 request.clientCapabilities?._meta?.parameterizedModelPicker === true;
394 if (antigravityProfile) {
395 return {
396 protocolVersion: 1,
397 agentInfo: { name: "antigravity-acp", version: "mock" },
398 agentCapabilities: {
399 loadSession: true,
400 sessionCapabilities: { resume: {} },
401 auth: { logout: {} },
402 promptCapabilities: { image: true, embeddedContext: true },
403 },
404 authMethods: [{ id: "oauth-personal", name: "Sign in with Google" }],
405 };
406 }
407 return {
408 protocolVersion: 1,
409 agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } },
410 // Grok advertises model state before any session exists; the provider
411 // health check reads it from here without authenticating.
412 _meta: { modelState: modelState() },
413 };
414 }),
415 );
416​
417 // Mirrors the real agent: the API key method reads GEMINI_API_KEY from the
418 // process environment and rejects when it is missing.
419 yield* agent.handleAuthenticate((request) =>
420 !antigravityProfile || request.methodId === "oauth-personal"
421 ? Effect.succeed({})
422 : request.methodId === "gemini-api-key" && process.env.GEMINI_API_KEY
423 ? Effect.succeed({})
424 : Effect.fail(
425 AcpError.AcpRequestError.invalidParams(
426 `Mock Antigravity rejected auth method ${request.methodId}.`,
427 ),
428 ),
429 );
430 if (antigravityProfile) {
431 yield* agent.handleLogout(() => Effect.succeed({}));
432 }
433​
434 yield* agent.handleCreateSession(() =>
435 Effect.gen(function* () {
436 if (antigravityProfile) {
437 yield* publishAntigravityCommands(sessionId);
438 }
439 return {
440 sessionId,
441 modes: modeState(),
442 models: modelState(),
443 configOptions: configOptions(),
444 };
445 }),
446 );
447​
448 yield* agent.handleResumeSession((request) =>
449 Effect.gen(function* () {
450 yield* agent.client.sessionUpdate({
451 sessionId: request.sessionId,
452 update: {
453 sessionUpdate: "user_message_chunk",
454 content: { type: "text", text: "native-resume-started" },
455 },
456 });
457 if (waitForResumeRelease) {
458 yield* Deferred.await(resumeRelease);
459 }
460 if (antigravityProfile) {
461 yield* publishAntigravityCommands(request.sessionId);
462 }
463 return {
464 modes: modeState(),
465 models: modelState(),
466 configOptions: configOptions(),
467 _meta: { nativeResume: true },
468 };
469 }),
470 );
471​
472 const emitLoadReplayNotifications = (requestedSessionId: string) => {
473 writeJsonRpcNotification("session/update", {
474 _meta: { isReplay: true },
475 sessionId: requestedSessionId,
476 update: {
477 sessionUpdate: "tool_call",
478 toolCallId: "replay-tool-1",
479 title: "Replay tool",
480 kind: "search",
481 status: "completed",
482 },
483 });
484 writeJsonRpcNotification("session/update", {
485 _meta: { isReplay: true },
486 sessionId: requestedSessionId,
487 update: {
488 sessionUpdate: "agent_message_chunk",
489 content: { type: "text", text: "replayed assistant text" },
490 },
491 });
492 };
493​
494 yield* agent.handleLoadSession((request) =>
495 Effect.gen(function* () {
496 const requestedSessionId = String(request.sessionId ?? sessionId);
497 if (failLoadSession) {
498 return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
499 }
500 if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
501 emitLoadReplayNotifications(requestedSessionId);
502 yield* agent.client.sessionUpdate({
503 sessionId: requestedSessionId,
504 update: {
505 sessionUpdate: "user_message_chunk",
506 content: { type: "text", text: "replay-tail" },
507 },
508 });
509 yield* Effect.sleep(loadSessionDelayMs);
510 return {
511 modes: modeState(),
512 models: modelState(),
513 configOptions: configOptions(),
514 };
515 }
516 if (emitLoadReplay) {
517 emitLoadReplayNotifications(requestedSessionId);
518 }
519 yield* agent.client.sessionUpdate({
520 sessionId: requestedSessionId,
521 update: {
522 sessionUpdate: "user_message_chunk",
523 content: { type: "text", text: "replay" },
524 },
525 });
526 return {
527 modes: modeState(),
528 models: modelState(),
529 configOptions: configOptions(),
530 };
531 }),
532 );
533​
534 yield* agent.handleSetSessionModel((request) =>
535 Effect.gen(function* () {
536 if (!modelState().availableModels.some((model) => model.modelId === request.modelId)) {
537 return yield* AcpError.AcpRequestError.invalidParams(
538 `Unknown mock model id: ${request.modelId}`,
539 {
540 method: "session/set_model",
541 params: request,
542 },
543 );
544 }
545 currentModelId = request.modelId;
546 return {};
547 }),
548 );
549​
550 yield* agent.handleSetSessionConfigOption((request) =>
551 Effect.gen(function* () {
552 if (exitOnSetConfigOption) {
553 return yield* Effect.sync(() => {
554 process.exit(7);
555 });
556 }
557 if (failSetConfigOption) {
558 return yield* AcpError.AcpRequestError.invalidParams(
559 "Mock invalid params for session/set_config_option",
560 {
561 method: "session/set_config_option",
562 params: request,
563 },
564 );
565 }
566 if (request.configId === "mode" && typeof request.value === "string") {
567 currentModeId = request.value;
568 }
569 if (request.configId === "model" && typeof request.value === "string") {
570 currentModelId = request.value;
571 }
572 if (request.configId === "reasoning" && typeof request.value === "string") {
573 currentReasoning = request.value;
574 }
575 if (request.configId === "context" && typeof request.value === "string") {
576 currentContext = request.value;
577 }
578 if (request.configId === "fast") {
579 currentFast = request.value === true || request.value === "true";
580 }
581 return {
582 configOptions: configOptions(),
583 };
584 }),
585 );
586​
587 yield* agent.handleCancel(({ sessionId }) =>
588 Effect.gen(function* () {
589 const cancelledSessionId = String(sessionId ?? "mock-session-1");
590 cancelledSessions.add(cancelledSessionId);
591 if (completeFirstPromptOnCancel) {
592 yield* Deferred.succeed(nativeCancelRequested, undefined);
593 yield* agent.client.sessionUpdate({
594 sessionId: cancelledSessionId,
595 update: {
596 sessionUpdate: "agent_thought_chunk",
597 content: { type: "text", text: "native-cancel-received" },
598 },
599 });
600 }
601 if (emitLateUpdateAfterCancel) {
602 yield* Effect.sleep("50 millis");
603 yield* Effect.sync(() => {
604 writeJsonRpcNotification("session/update", {
605 sessionId: cancelledSessionId,
606 update: {
607 sessionUpdate: "agent_message_chunk",
608 content: { type: "text", text: "late after cancel" },
609 },
610 });
611 });
612 }
613 }),
614 );
615​
616 yield* agent.handlePrompt((request) =>
617 Effect.gen(function* () {
618 const requestedSessionId = String(request.sessionId ?? sessionId);
619 promptCount += 1;
620​
621 if (completeFirstPromptOnCancel && promptCount === 1) {
622 yield* agent.client.sessionUpdate({
623 sessionId: requestedSessionId,
624 update: {
625 sessionUpdate: "tool_call",
626 toolCallId: "native-cancel-tool",
627 title: "Long command",
628 kind: "execute",
629 status: "in_progress",
630 },
631 });
632 yield* Deferred.await(nativeCancelRequested);
633 yield* Deferred.await(nativeCancelRelease);
634 yield* agent.client.sessionUpdate({
635 sessionId: requestedSessionId,
636 update: {
637 sessionUpdate: "tool_call_update",
638 toolCallId: "native-cancel-tool",
639 status: "failed",
640 content: [{ type: "content", content: { type: "text", text: "Cancelled." } }],
641 },
642 });
643 yield* agent.client.sessionUpdate({
644 sessionId: requestedSessionId,
645 update: {
646 sessionUpdate: "agent_message_chunk",
647 content: { type: "text", text: "Request cancelled." },
648 },
649 });
650 return { stopReason: "cancelled", _meta: { nativeCancel: true } };
651 }
652​
653 if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
654 yield* Effect.sleep(`${promptDelayMs} millis`);
655 }
656​
657 if (failPrompt) {
658 return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
659 }
660​
661 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
662 return {
663 stopReason: "end_turn",
664 _meta: {
665 promptId: "mock-stale-xai-prompt-1",
666 requestId: "mock-stale-xai-prompt-1",
667 },
668 };
669 }
670​
671 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
672 const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
673 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
674 sessionId: requestedSessionId,
675 promptId: "mock-stale-xai-prompt-1",
676 stopReason: "end_turn",
677 agentResult: null,
678 });
679​
680 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
681 sessionId: requestedSessionId,
682 promptId: currentPromptId,
683 stopReason: "end_turn",
684 agentResult: null,
685 });
686​
687 return yield* Effect.never;
688 }
689​
690 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
691 overlappingFirstPromptId = promptIdFromRequestMeta(request);
692 return yield* Effect.never;
693 }
694​
695 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
696 const secondPromptId = promptIdFromRequestMeta(request);
697 if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
698 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
699 sessionId: requestedSessionId,
700 promptId: secondPromptId,
701 stopReason: "end_turn",
702 agentResult: null,
703 });
704 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
705 sessionId: requestedSessionId,
706 promptId: overlappingFirstPromptId,
707 stopReason: "end_turn",
708 agentResult: null,
709 });
710 }
711 return yield* Effect.never;
712 }
713​
714 if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
715 return yield* Effect.never;
716 }
717​
718 if (emitXAiRateLimitThenHang) {
719 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
720 sessionId: requestedSessionId,
721 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-rate-limit-prompt-1",
722 stopReason: "rate_limit",
723 agentResult: null,
724 });
725 return yield* Effect.never;
726 }
727​
728 if (emitContentThenHang) {
729 yield* agent.client.sessionUpdate({
730 sessionId: requestedSessionId,
731 update: {
732 sessionUpdate: "agent_message_chunk",
733 content: { type: "text", text: "partial before stall" },
734 },
735 });
736 return yield* Effect.never;
737 }
738​
739 if (emitPlanThenHang) {
740 yield* agent.client.sessionUpdate({
741 sessionId: requestedSessionId,
742 update: {
743 sessionUpdate: "plan",
744 entries: [
745 {
746 content: "Wait for more ACP progress",
747 priority: "high",
748 status: "in_progress",
749 },
750 ],
751 },
752 });
753 return yield* Effect.never;
754 }
755​
756 if (emitActiveToolThenHang) {
757 const toolCallId = "tool-call-long-running-1";
758 yield* agent.client.sessionUpdate({
759 sessionId: requestedSessionId,
760 update: {
761 sessionUpdate: "tool_call",
762 toolCallId,
763 title: "Long-running tool",
764 kind: "execute",
765 status: "pending",
766 rawInput: { command: ["long-running-tool"] },
767 },
768 });
769 yield* agent.client.sessionUpdate({
770 sessionId: requestedSessionId,
771 update: {
772 sessionUpdate: "tool_call_update",
773 toolCallId,
774 status: "in_progress",
775 },
776 });
777 return yield* Effect.never;
778 }
779​
780 if (emitXAiPromptCompleteThenHang) {
781 writeJsonRpcNotification("session/update", {
782 sessionId: requestedSessionId,
783 update: {
784 sessionUpdate: "agent_message_chunk",
785 content: { type: "text", text: "hello from " },
786 },
787 });
788​
789 if (emitForeignSessionUpdates) {
790 writeJsonRpcNotification("session/update", {
791 sessionId: "mock-child-session-1",
792 update: {
793 sessionUpdate: "agent_message_chunk",
794 content: { type: "text", text: "child before completion" },
795 },
796 });
797 }
798​
799 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
800 sessionId: requestedSessionId,
801 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
802 ...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
803 agentResult: null,
804 });
805​
806 if (emitForeignSessionUpdates) {
807 writeJsonRpcNotification("session/update", {
808 sessionId: "mock-child-session-1",
809 update: {
810 sessionUpdate: "tool_call",
811 toolCallId: "child-tool-call-1",
812 title: "Child-only tool",
813 kind: "other",
814 status: "pending",
815 rawInput: {},
816 },
817 });
818 writeJsonRpcNotification("session/update", {
819 sessionId: "mock-child-session-1",
820 update: {
821 sessionUpdate: "agent_message_chunk",
822 content: { type: "text", text: "child after completion" },
823 },
824 });
825 }
826​
827 writeJsonRpcNotification("session/update", {
828 sessionId: requestedSessionId,
829 update: {
830 sessionUpdate: "agent_message_chunk",
831 content: { type: "text", text: "mock" },
832 },
833 });
834​
835 return yield* Effect.never;
836 }
837​
838 if (emitInterleavedAssistantToolCalls) {
839 const toolCallId = "tool-call-1";
840​
841 yield* agent.client.sessionUpdate({
842 sessionId: requestedSessionId,
843 update: {
844 sessionUpdate: "agent_message_chunk",
845 content: { type: "text", text: "before tool" },
846 },
847 });
848​
849 yield* agent.client.sessionUpdate({
850 sessionId: requestedSessionId,
851 update: {
852 sessionUpdate: "tool_call",
853 toolCallId,
854 title: "Terminal",
855 kind: "execute",
856 status: "pending",
857 rawInput: {
858 command: ["echo", "hello"],
859 },
860 },
861 });
862​
863 yield* agent.client.sessionUpdate({
864 sessionId: requestedSessionId,
865 update: {
866 sessionUpdate: "tool_call_update",
867 toolCallId,
868 status: "completed",
869 rawOutput: {
870 exitCode: 0,
871 stdout: "hello",
872 stderr: "",
873 },
874 },
875 });
876​
877 yield* agent.client.sessionUpdate({
878 sessionId: requestedSessionId,
879 update: {
880 sessionUpdate: "agent_message_chunk",
881 content: { type: "text", text: "after tool" },
882 },
883 });
884​
885 return { stopReason: "end_turn" };
886 }
887​
888 if (emitToolCalls) {
889 const toolCallId = "tool-call-1";
890​
891 yield* agent.client.sessionUpdate({
892 sessionId: requestedSessionId,
893 update: {
894 sessionUpdate: "tool_call",
895 toolCallId,
896 title: "Terminal",
897 kind: "execute",
898 status: "pending",
899 rawInput: {
900 command: ["cat", "server/package.json"],
901 },
902 },
903 });
904​
905 yield* agent.client.sessionUpdate({
906 sessionId: requestedSessionId,
907 update: {
908 sessionUpdate: "tool_call_update",
909 toolCallId,
910 status: "in_progress",
911 },
912 });
913​
914 const permissionOptions: Array<AcpSchema.PermissionOption> = [
915 { optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
916 ...(omitAllowAlways
917 ? []
918 : [
919 {
920 optionId: permissionOptionIds.allowAlways,
921 name: "Allow always",
922 kind: "allow_always" as const,
923 },
924 ]),
925 { optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
926 ];
927​
928 let cancelled = cancelledSessions.delete(requestedSessionId);
929 for (let index = 0; index < permissionRequestCount; index++) {
930 const command =
931 index > 0
932 ? (process.env.T3_ACP_SECOND_PERMISSION_COMMAND ?? "cat server/package.json")
933 : "cat server/package.json";
934 const permission = yield* agent.client.requestPermission({
935 sessionId: requestedSessionId,
936 toolCall: {
937 toolCallId: index === 0 ? toolCallId : `${toolCallId}-${index + 1}`,
938 title: process.env.T3_ACP_PERMISSION_TITLE ?? `\`${command}\``,
939 kind: "execute",
940 status: "pending",
941 rawInput: {
942 variant: "Bash",
943 command,
944 description: index === 0 ? "Read package metadata" : "Read it again",
945 },
946 content: [
947 {
948 type: "content",
949 content: {
950 type: "text",
951 text: `Not in allowlist: ${command}`,
952 },
953 },
954 ],
955 },
956 options: permissionOptions,
957 });
958 cancelled =
959 cancelled ||
960 cancelledSessions.delete(requestedSessionId) ||
961 permission.outcome.outcome === "cancelled";
962 if (cancelled) {
963 break;
964 }
965 }
966​
967 yield* agent.client.sessionUpdate({
968 sessionId: requestedSessionId,
969 update: {
970 sessionUpdate: "tool_call_update",
971 toolCallId,
972 title: "Terminal",
973 kind: "execute",
974 status: "completed",
975 rawOutput: {
976 exitCode: 0,
977 stdout: '{ "name": "t3" }',
978 stderr: "",
979 },
980 },
981 });
982​
983 yield* agent.client.sessionUpdate({
984 sessionId: requestedSessionId,
985 update: {
986 sessionUpdate: "agent_message_chunk",
987 content: { type: "text", text: "hello from mock" },
988 },
989 });
990​
991 return { stopReason: cancelled ? "cancelled" : "end_turn" };
992 }
993​
994 if (emitGenericToolPlaceholders) {
995 const toolCallId = "tool-call-generic-1";
996​
997 yield* agent.client.sessionUpdate({
998 sessionId: requestedSessionId,
999 update: {
1000 sessionUpdate: "tool_call",
1001 toolCallId,
1002 title: "Read File",
1003 kind: "read",
1004 status: "pending",
1005 rawInput: {},
1006 },
1007 });
1008​
1009 yield* agent.client.sessionUpdate({
1010 sessionId: requestedSessionId,
1011 update: {
1012 sessionUpdate: "tool_call_update",
1013 toolCallId,
1014 status: "in_progress",
1015 },
1016 });
1017​
1018 yield* agent.client.sessionUpdate({
1019 sessionId: requestedSessionId,
1020 update: {
1021 sessionUpdate: "tool_call_update",
1022 toolCallId,
1023 status: "completed",
1024 rawOutput: {
1025 content: "package.json\n",
1026 },
1027 },
1028 });
1029​
1030 return { stopReason: "end_turn" };
1032​
1033 if (emitAskQuestion) {
1034 yield* agent.client.extRequest("cursor/ask_question", {
1035 toolCallId: "ask-question-tool-call-1",
1036 title: "Question",
1037 questions: [
1039 id: "scope",
1040 prompt: "Which scope?",
1041 options: [
1042 { id: "workspace", label: "Workspace" },
1043 { id: "session", label: "Session" },
1044 ],
1045 },
1046 ],
1047 });
1048​
1049 return { stopReason: "end_turn" };
1051​
1052 if (emitXAiAskUserQuestion || emitXAiAskUserQuestionThenHang) {
1053 const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
1054 method: "x.ai/ask_user_question",
1055 params: {
1056 sessionId: requestedSessionId,
1057 toolCallId: "ask-user-question-tool-call-1",
1058 questions: [
1060 question: "Which scope should Grok use?",
1061 multiSelect: null,
1062 options: [
1063 { label: "Workspace", description: "Use the current workspace" },
1064 { label: "Session", description: "Only use this session" },
1065 ],
1066 },
1067 ],
1068 mode: "default",
1069 },
1070 });
1071 if (typeof result !== "object" || result === null || !("outcome" in result)) {
1072 throw new Error("Expected _x.ai/ask_user_question response outcome.");
1074 if (result.outcome === "cancelled") {
1075 return { stopReason: "end_turn" };
1077 if (
1078 result.outcome !== "accepted" ||
1079 !("answers" in result) ||
1080 typeof result.answers !== "object" ||
1081 result.answers === null
1082 ) {
1083 throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
1085​
1086 if (emitXAiAskUserQuestionThenHang) {
1087 return yield* Effect.never;
1089​
1090 return { stopReason: "end_turn" };
1092​
1093 if (emitXAiPlanMdWrite) {
1094 // Match Grok's real session layout so isGrokPlanMarkdownPath accepts it.
1095 const planRoot = process.env.T3_ACP_PLAN_ROOT ?? "/tmp/mock-home/.grok";
1096 const planPath = `${planRoot}/sessions/${requestedSessionId}/plan.md`;
1097 const planBody = "# Mock plan\n\n- Write the feature\n- Add a test\n- Ship it\n";
1098 // enter_plan_mode first so the adapter arms planModeActive.
1099 yield* agent.client.sessionUpdate({
1100 sessionId: requestedSessionId,
1101 update: {
1102 sessionUpdate: "tool_call",
1103 toolCallId: "enter-plan-mode-1",
1104 title: "enter_plan_mode",
1105 kind: "other",
1106 status: "completed",
1107 rawInput: { variant: "EnterPlanMode" },
1108 },
1109 });
1110 yield* agent.client.sessionUpdate({
1111 sessionId: requestedSessionId,
1112 update: {
1113 sessionUpdate: "tool_call",
1114 toolCallId: "plan-md-write-1",
1115 title: "write",
1116 kind: "edit",
1117 status: "pending",
1118 rawInput: { file_path: planPath, content: planBody },
1119 },
1120 });
1121 yield* agent.client.sessionUpdate({
1122 sessionId: requestedSessionId,
1123 update: {
1124 sessionUpdate: "tool_call_update",
1125 toolCallId: "plan-md-write-1",
1126 kind: "edit",
1127 status: "completed",
1128 title: `Write \`${planPath}\``,
1129 rawInput: { file_path: planPath, content: planBody },
1130 content: [
1132 type: "diff",
1133 path: planPath,
1134 oldText: "",
1135 newText: planBody,
1136 },
1137 ],
1138 },
1139 });
1140 return { stopReason: "end_turn" };
1142​
1143 if (emitXAiExitPlanMode) {
1144 const result = yield* agent.client.extRequest("_x.ai/exit_plan_mode", {
1145 method: "x.ai/exit_plan_mode",
1146 params: {
1147 sessionId: requestedSessionId,
1148 toolCallId: "exit-plan-mode-tool-call-1",
1149 planContent: "# Exit plan\n\n- Step one\n- Step two\n",
1150 },
1151 });
1152 if (typeof result !== "object" || result === null || !("outcome" in result)) {
1153 throw new Error("Expected _x.ai/exit_plan_mode response outcome.");
1155 if (
1156 result.outcome !== "abandoned" &&
1157 result.outcome !== "approved" &&
1158 result.outcome !== "request_changes"
1159 ) {
1160 throw new Error(
1161 `Expected exit_plan_mode outcome abandoned|approved|request_changes, got ${String(result.outcome)}`,
1162 );
1164 return { stopReason: "end_turn" };
1166​
1167 if (emitForeignSessionUpdates) {
1168 yield* agent.client.sessionUpdate({
1169 sessionId: requestedSessionId,
1170 update: {
1171 sessionUpdate: "agent_message_chunk",
1172 content: { type: "text", text: "root before child" },
1173 },
1174 });
1175 yield* agent.client.sessionUpdate({
1176 sessionId: "mock-child-session-1",
1177 update: {
1178 sessionUpdate: "agent_message_chunk",
1179 content: { type: "text", text: "child content" },
1180 },
1181 });
1182 yield* agent.client.sessionUpdate({
1183 sessionId: "mock-child-session-1",
1184 update: {
1185 sessionUpdate: "tool_call",
1186 toolCallId: "child-tool-call-1",
1187 title: "Child-only tool",
1188 kind: "other",
1189 status: "pending",
1190 rawInput: {},
1191 },
1192 });
1193 yield* agent.client.sessionUpdate({
1194 sessionId: requestedSessionId,
1195 update: {
1196 sessionUpdate: "agent_message_chunk",
1197 content: { type: "text", text: " root after child" },
1198 },
1199 });
1200 return { stopReason: "end_turn" };
1202​
1203 yield* agent.client.sessionUpdate({
1204 sessionId: requestedSessionId,
1205 update: {
1206 sessionUpdate: "plan",
1207 entries: [
1209 content: "Inspect mock ACP state",
1210 priority: "high",
1211 status: "completed",
1212 },
1214 content: "Implement the requested change",
1215 priority: "high",
1216 status: "in_progress",
1217 },
1218 ],
1219 },
1220 });
1221​
1222 yield* agent.client.sessionUpdate({
1223 sessionId: requestedSessionId,
1224 update: {
1225 sessionUpdate: "agent_message_chunk",
1226 content: { type: "text", text: promptResponseText ?? "hello from mock" },
1227 },
1228 });
1229​
1230 return { stopReason: "end_turn" };
1231 }),
1232 );
1233​
1234 yield* agent.handleUnknownExtRequest((method, params) => {
1235 if (method === "_test/environment") {
1236 return Effect.succeed({
1237 inherited: process.env.T3_ACP_RUNTIME_AMBIENT === "sentinel",
1238 explicit: process.env.T3_ACP_RUNTIME_EXPLICIT === "kept",
1239 });
1241 if (method === "_test/release-resume") {
1242 return Deferred.succeed(resumeRelease, undefined).pipe(Effect.as({}));
1244 if (method === "_test/finish-cancel") {
1245 return Deferred.succeed(nativeCancelRelease, undefined).pipe(Effect.as({}));
1247 if (method === "_test/startup-metadata") {
1248 return Effect.gen(function* () {
1249 for (const [metadataSessionId, commandName, modeId] of [
1250 [sessionId, "plan", "code"],
1251 ["child-session", "foreign-command", "ask"],
1252 ] as const) {
1253 yield* agent.client.sessionUpdate({
1254 sessionId: metadataSessionId,
1255 update: {
1256 sessionUpdate: "available_commands_update",
1257 availableCommands: [{ name: commandName, description: "Native command" }],
1258 },
1259 });
1260 yield* agent.client.sessionUpdate({
1261 sessionId: metadataSessionId,
1262 update: { sessionUpdate: "current_mode_update", currentModeId: modeId },
1263 });
1264 yield* agent.client.sessionUpdate({
1265 sessionId: metadataSessionId,
1266 update: {
1267 sessionUpdate: "config_option_update",
1268 configOptions: configOptions().map((option) =>
1269 option.type === "select" && option.category === "model"
1270 ? {
1271 ...option,
1272 currentValue: metadataSessionId === sessionId ? "gpt-5.4" : "default",
1274 : option,
1275 ),
1276 },
1277 });
1278 yield* agent.client.sessionUpdate({
1279 sessionId: metadataSessionId,
1280 update: {
1281 sessionUpdate: "agent_message_chunk",
1282 content: { type: "text", text: "Startup transcript must not replay." },
1283 },
1284 });
1286 return {};
1287 });
1289 if (method === "cursor/list_available_models") {
1290 return Effect.succeed({
1291 models: availableModels(),
1292 });
1294​
1295 if (method !== "session/mode/set") {
1296 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
1298​
1299 const nextModeId =
1300 typeof params === "object" &&
1301 params !== null &&
1302 "modeId" in params &&
1303 typeof params.modeId === "string"
1304 ? params.modeId
1305 : typeof params === "object" &&
1306 params !== null &&
1307 "mode" in params &&
1308 typeof params.mode === "string"
1309 ? params.mode
1310 : undefined;
1311 const requestedSessionId =
1312 typeof params === "object" &&
1313 params !== null &&
1314 "sessionId" in params &&
1315 typeof params.sessionId === "string"
1316 ? params.sessionId
1317 : sessionId;
1318​
1319 if (typeof nextModeId === "string" && nextModeId.trim()) {
1320 currentModeId = nextModeId.trim();
1321 return agent.client
1322 .sessionUpdate({
1323 sessionId: requestedSessionId,
1324 update: {
1325 sessionUpdate: "current_mode_update",
1326 currentModeId,
1327 },
1328 })
1329 .pipe(Effect.as({}));
1331​
1332 return Effect.succeed({});
1333 });
1334​
1335 yield* agent.handleUnknownExtNotification((method) =>
1336 method === "_test/exit" ? Effect.sync(() => process.exit(19)) : Effect.void,
1337 );
1338​
1339 return yield* Effect.never;
1340}).pipe(
1341 Effect.provide(
1342 EffectAcpAgent.layerStdio(
1343 requestLogPath
1344 ? {
1345 logIncoming: true,
1346 logger: (event) => {
1347 if (event.direction !== "incoming" || event.stage !== "raw") {
1348 return Effect.void;
1350 if (typeof event.payload !== "string") {
1351 return Effect.void;
1353 const payload = event.payload;
1354 return Effect.sync(() => {
1355 NodeFS.appendFileSync(
1356 requestLogPath,
1357 payload.endsWith("\n") ? payload : `${payload}\n`,
1358 "utf8",
1359 );
1360 });
1361 },
1363 : {},
1364 ),
1365 ),
1366 Effect.scoped,
1367 Effect.provide(NodeServices.layer),
1369​
1370NodeRuntime.runMain(program);