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

acp-mock-agent.ts

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