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

acp-mock-agent.ts

1,140 lines35.3 KB

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