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

acp-mock-agent.ts

1,152 lines35.9 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​
296// Mirrors the real Grok ACP: it advertises versioned model ids, never the CLI's own
297// "grok-build" product name, and it rejects unknown ids in session/set_model.
298const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
299 {
300 modelId: "grok-4.6",
301 name: "Grok 4.6",
302 _meta: {
303 totalContextTokens: 500_000,
304 supportsReasoningEffort: true,
305 reasoningEffort: initialGrokReasoningEffort ?? "high",
306 reasoningEfforts: [
307 { id: "xhigh", value: "xhigh", label: "Extra High Effort", default: false },
308 { id: "high", value: "high", label: "High Effort", default: true },
309 { id: "low", value: "low", label: "Low Effort", default: false },
310 ],
311 },
312 },
313 { modelId: "grok-mock-alt", name: "Grok Mock Alt" },
314];
315​
316function modelState(): AcpSchema.SessionModelState {
317 const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
318 ? currentModelId
319 : "grok-4.6";
320 return {
321 currentModelId: modelId,
322 availableModels: grokAcpModels,
323 };
325​
326const program = Effect.gen(function* () {
327 const agent = yield* EffectAcpAgent.AcpAgent;
328​
329 yield* agent.handleInitialize((request) =>
330 Effect.sync(() => {
331 parameterizedModelPicker =
332 request.clientCapabilities?._meta?.parameterizedModelPicker === true;
333 return {
334 protocolVersion: 1,
335 agentCapabilities: { loadSession: true },
336 // Grok advertises model state before any session exists; the provider
337 // health check reads it from here without authenticating.
338 _meta: { modelState: modelState() },
339 };
340 }),
341 );
342​
343 yield* agent.handleAuthenticate(() => Effect.succeed({}));
344​
345 yield* agent.handleCreateSession(() =>
346 Effect.succeed({
347 sessionId,
348 modes: modeState(),
349 models: modelState(),
350 configOptions: configOptions(),
351 }),
352 );
353​
354 const emitLoadReplayNotifications = (requestedSessionId: string) => {
355 writeJsonRpcNotification("session/update", {
356 _meta: { isReplay: true },
357 sessionId: requestedSessionId,
358 update: {
359 sessionUpdate: "tool_call",
360 toolCallId: "replay-tool-1",
361 title: "Replay tool",
362 kind: "search",
363 status: "completed",
364 },
365 });
366 writeJsonRpcNotification("session/update", {
367 _meta: { isReplay: true },
368 sessionId: requestedSessionId,
369 update: {
370 sessionUpdate: "agent_message_chunk",
371 content: { type: "text", text: "replayed assistant text" },
372 },
373 });
374 };
375​
376 yield* agent.handleLoadSession((request) =>
377 Effect.gen(function* () {
378 const requestedSessionId = String(request.sessionId ?? sessionId);
379 if (failLoadSession) {
380 return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
381 }
382 if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
383 emitLoadReplayNotifications(requestedSessionId);
384 yield* agent.client.sessionUpdate({
385 sessionId: requestedSessionId,
386 update: {
387 sessionUpdate: "user_message_chunk",
388 content: { type: "text", text: "replay-tail" },
389 },
390 });
391 yield* Effect.sleep(loadSessionDelayMs);
392 return {
393 modes: modeState(),
394 models: modelState(),
395 configOptions: configOptions(),
396 };
397 }
398 if (emitLoadReplay) {
399 emitLoadReplayNotifications(requestedSessionId);
400 }
401 yield* agent.client.sessionUpdate({
402 sessionId: requestedSessionId,
403 update: {
404 sessionUpdate: "user_message_chunk",
405 content: { type: "text", text: "replay" },
406 },
407 });
408 return {
409 modes: modeState(),
410 models: modelState(),
411 configOptions: configOptions(),
412 };
413 }),
414 );
415​
416 yield* agent.handleSetSessionModel((request) =>
417 Effect.gen(function* () {
418 if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
419 return yield* AcpError.AcpRequestError.invalidParams(
420 `Unknown mock model id: ${request.modelId}`,
421 {
422 method: "session/set_model",
423 params: request,
424 },
425 );
426 }
427 currentModelId = request.modelId;
428 return {};
429 }),
430 );
431​
432 yield* agent.handleSetSessionConfigOption((request) =>
433 Effect.gen(function* () {
434 if (exitOnSetConfigOption) {
435 return yield* Effect.sync(() => {
436 process.exit(7);
437 });
438 }
439 if (failSetConfigOption) {
440 return yield* AcpError.AcpRequestError.invalidParams(
441 "Mock invalid params for session/set_config_option",
442 {
443 method: "session/set_config_option",
444 params: request,
445 },
446 );
447 }
448 if (request.configId === "mode" && typeof request.value === "string") {
449 currentModeId = request.value;
450 }
451 if (request.configId === "model" && typeof request.value === "string") {
452 currentModelId = request.value;
453 }
454 if (request.configId === "reasoning" && typeof request.value === "string") {
455 currentReasoning = request.value;
456 }
457 if (request.configId === "context" && typeof request.value === "string") {
458 currentContext = request.value;
459 }
460 if (request.configId === "fast") {
461 currentFast = request.value === true || request.value === "true";
462 }
463 return {
464 configOptions: configOptions(),
465 };
466 }),
467 );
468​
469 yield* agent.handleCancel(({ sessionId }) =>
470 Effect.gen(function* () {
471 const cancelledSessionId = String(sessionId ?? "mock-session-1");
472 cancelledSessions.add(cancelledSessionId);
473 if (emitLateUpdateAfterCancel) {
474 yield* Effect.sleep("50 millis");
475 yield* Effect.sync(() => {
476 writeJsonRpcNotification("session/update", {
477 sessionId: cancelledSessionId,
478 update: {
479 sessionUpdate: "agent_message_chunk",
480 content: { type: "text", text: "late after cancel" },
481 },
482 });
483 });
484 }
485 }),
486 );
487​
488 yield* agent.handlePrompt((request) =>
489 Effect.gen(function* () {
490 const requestedSessionId = String(request.sessionId ?? sessionId);
491 promptCount += 1;
492​
493 if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
494 yield* Effect.sleep(`${promptDelayMs} millis`);
495 }
496​
497 if (failPrompt) {
498 return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
499 }
500​
501 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
502 return {
503 stopReason: "end_turn",
504 _meta: {
505 promptId: "mock-stale-xai-prompt-1",
506 requestId: "mock-stale-xai-prompt-1",
507 },
508 };
509 }
510​
511 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
512 const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
513 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
514 sessionId: requestedSessionId,
515 promptId: "mock-stale-xai-prompt-1",
516 stopReason: "end_turn",
517 agentResult: null,
518 });
519​
520 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
521 sessionId: requestedSessionId,
522 promptId: currentPromptId,
523 stopReason: "end_turn",
524 agentResult: null,
525 });
526​
527 return yield* Effect.never;
528 }
529​
530 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
531 overlappingFirstPromptId = promptIdFromRequestMeta(request);
532 return yield* Effect.never;
533 }
534​
535 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
536 const secondPromptId = promptIdFromRequestMeta(request);
537 if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
538 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
539 sessionId: requestedSessionId,
540 promptId: secondPromptId,
541 stopReason: "end_turn",
542 agentResult: null,
543 });
544 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
545 sessionId: requestedSessionId,
546 promptId: overlappingFirstPromptId,
547 stopReason: "end_turn",
548 agentResult: null,
549 });
550 }
551 return yield* Effect.never;
552 }
553​
554 if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
555 return yield* Effect.never;
556 }
557​
558 if (emitXAiRateLimitThenHang) {
559 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
560 sessionId: requestedSessionId,
561 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-rate-limit-prompt-1",
562 stopReason: "rate_limit",
563 agentResult: null,
564 });
565 return yield* Effect.never;
566 }
567​
568 if (emitContentThenHang) {
569 yield* agent.client.sessionUpdate({
570 sessionId: requestedSessionId,
571 update: {
572 sessionUpdate: "agent_message_chunk",
573 content: { type: "text", text: "partial before stall" },
574 },
575 });
576 return yield* Effect.never;
577 }
578​
579 if (emitPlanThenHang) {
580 yield* agent.client.sessionUpdate({
581 sessionId: requestedSessionId,
582 update: {
583 sessionUpdate: "plan",
584 entries: [
585 {
586 content: "Wait for more ACP progress",
587 priority: "high",
588 status: "in_progress",
589 },
590 ],
591 },
592 });
593 return yield* Effect.never;
594 }
595​
596 if (emitActiveToolThenHang) {
597 const toolCallId = "tool-call-long-running-1";
598 yield* agent.client.sessionUpdate({
599 sessionId: requestedSessionId,
600 update: {
601 sessionUpdate: "tool_call",
602 toolCallId,
603 title: "Long-running tool",
604 kind: "execute",
605 status: "pending",
606 rawInput: { command: ["long-running-tool"] },
607 },
608 });
609 yield* agent.client.sessionUpdate({
610 sessionId: requestedSessionId,
611 update: {
612 sessionUpdate: "tool_call_update",
613 toolCallId,
614 status: "in_progress",
615 },
616 });
617 return yield* Effect.never;
618 }
619​
620 if (emitXAiPromptCompleteThenHang) {
621 writeJsonRpcNotification("session/update", {
622 sessionId: requestedSessionId,
623 update: {
624 sessionUpdate: "agent_message_chunk",
625 content: { type: "text", text: "hello from " },
626 },
627 });
628​
629 if (emitForeignSessionUpdates) {
630 writeJsonRpcNotification("session/update", {
631 sessionId: "mock-child-session-1",
632 update: {
633 sessionUpdate: "agent_message_chunk",
634 content: { type: "text", text: "child before completion" },
635 },
636 });
637 }
638​
639 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
640 sessionId: requestedSessionId,
641 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
642 ...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
643 agentResult: null,
644 });
645​
646 if (emitForeignSessionUpdates) {
647 writeJsonRpcNotification("session/update", {
648 sessionId: "mock-child-session-1",
649 update: {
650 sessionUpdate: "tool_call",
651 toolCallId: "child-tool-call-1",
652 title: "Child-only tool",
653 kind: "other",
654 status: "pending",
655 rawInput: {},
656 },
657 });
658 writeJsonRpcNotification("session/update", {
659 sessionId: "mock-child-session-1",
660 update: {
661 sessionUpdate: "agent_message_chunk",
662 content: { type: "text", text: "child after completion" },
663 },
664 });
665 }
666​
667 writeJsonRpcNotification("session/update", {
668 sessionId: requestedSessionId,
669 update: {
670 sessionUpdate: "agent_message_chunk",
671 content: { type: "text", text: "mock" },
672 },
673 });
674​
675 return yield* Effect.never;
676 }
677​
678 if (emitInterleavedAssistantToolCalls) {
679 const toolCallId = "tool-call-1";
680​
681 yield* agent.client.sessionUpdate({
682 sessionId: requestedSessionId,
683 update: {
684 sessionUpdate: "agent_message_chunk",
685 content: { type: "text", text: "before tool" },
686 },
687 });
688​
689 yield* agent.client.sessionUpdate({
690 sessionId: requestedSessionId,
691 update: {
692 sessionUpdate: "tool_call",
693 toolCallId,
694 title: "Terminal",
695 kind: "execute",
696 status: "pending",
697 rawInput: {
698 command: ["echo", "hello"],
699 },
700 },
701 });
702​
703 yield* agent.client.sessionUpdate({
704 sessionId: requestedSessionId,
705 update: {
706 sessionUpdate: "tool_call_update",
707 toolCallId,
708 status: "completed",
709 rawOutput: {
710 exitCode: 0,
711 stdout: "hello",
712 stderr: "",
713 },
714 },
715 });
716​
717 yield* agent.client.sessionUpdate({
718 sessionId: requestedSessionId,
719 update: {
720 sessionUpdate: "agent_message_chunk",
721 content: { type: "text", text: "after tool" },
722 },
723 });
724​
725 return { stopReason: "end_turn" };
726 }
727​
728 if (emitToolCalls) {
729 const toolCallId = "tool-call-1";
730​
731 yield* agent.client.sessionUpdate({
732 sessionId: requestedSessionId,
733 update: {
734 sessionUpdate: "tool_call",
735 toolCallId,
736 title: "Terminal",
737 kind: "execute",
738 status: "pending",
739 rawInput: {
740 command: ["cat", "server/package.json"],
741 },
742 },
743 });
744​
745 yield* agent.client.sessionUpdate({
746 sessionId: requestedSessionId,
747 update: {
748 sessionUpdate: "tool_call_update",
749 toolCallId,
750 status: "in_progress",
751 },
752 });
753​
754 const permissionOptions: Array<AcpSchema.PermissionOption> = [
755 { optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
756 ...(omitAllowAlways
757 ? []
758 : [
759 {
760 optionId: permissionOptionIds.allowAlways,
761 name: "Allow always",
762 kind: "allow_always" as const,
763 },
764 ]),
765 { optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
766 ];
767​
768 let cancelled = cancelledSessions.delete(requestedSessionId);
769 for (let index = 0; index < permissionRequestCount; index++) {
770 const command =
771 index > 0
772 ? (process.env.T3_ACP_SECOND_PERMISSION_COMMAND ?? "cat server/package.json")
773 : "cat server/package.json";
774 const permission = yield* agent.client.requestPermission({
775 sessionId: requestedSessionId,
776 toolCall: {
777 toolCallId: index === 0 ? toolCallId : `${toolCallId}-${index + 1}`,
778 title: process.env.T3_ACP_PERMISSION_TITLE ?? `\`${command}\``,
779 kind: "execute",
780 status: "pending",
781 rawInput: {
782 variant: "Bash",
783 command,
784 description: index === 0 ? "Read package metadata" : "Read it again",
785 },
786 content: [
787 {
788 type: "content",
789 content: {
790 type: "text",
791 text: `Not in allowlist: ${command}`,
792 },
793 },
794 ],
795 },
796 options: permissionOptions,
797 });
798 cancelled =
799 cancelled ||
800 cancelledSessions.delete(requestedSessionId) ||
801 permission.outcome.outcome === "cancelled";
802 if (cancelled) {
803 break;
804 }
805 }
806​
807 yield* agent.client.sessionUpdate({
808 sessionId: requestedSessionId,
809 update: {
810 sessionUpdate: "tool_call_update",
811 toolCallId,
812 title: "Terminal",
813 kind: "execute",
814 status: "completed",
815 rawOutput: {
816 exitCode: 0,
817 stdout: '{ "name": "t3" }',
818 stderr: "",
819 },
820 },
821 });
822​
823 yield* agent.client.sessionUpdate({
824 sessionId: requestedSessionId,
825 update: {
826 sessionUpdate: "agent_message_chunk",
827 content: { type: "text", text: "hello from mock" },
828 },
829 });
830​
831 return { stopReason: cancelled ? "cancelled" : "end_turn" };
832 }
833​
834 if (emitGenericToolPlaceholders) {
835 const toolCallId = "tool-call-generic-1";
836​
837 yield* agent.client.sessionUpdate({
838 sessionId: requestedSessionId,
839 update: {
840 sessionUpdate: "tool_call",
841 toolCallId,
842 title: "Read File",
843 kind: "read",
844 status: "pending",
845 rawInput: {},
846 },
847 });
848​
849 yield* agent.client.sessionUpdate({
850 sessionId: requestedSessionId,
851 update: {
852 sessionUpdate: "tool_call_update",
853 toolCallId,
854 status: "in_progress",
855 },
856 });
857​
858 yield* agent.client.sessionUpdate({
859 sessionId: requestedSessionId,
860 update: {
861 sessionUpdate: "tool_call_update",
862 toolCallId,
863 status: "completed",
864 rawOutput: {
865 content: "package.json\n",
866 },
867 },
868 });
869​
870 return { stopReason: "end_turn" };
871 }
872​
873 if (emitAskQuestion) {
874 yield* agent.client.extRequest("cursor/ask_question", {
875 toolCallId: "ask-question-tool-call-1",
876 title: "Question",
877 questions: [
878 {
879 id: "scope",
880 prompt: "Which scope?",
881 options: [
882 { id: "workspace", label: "Workspace" },
883 { id: "session", label: "Session" },
884 ],
885 },
886 ],
887 });
888​
889 return { stopReason: "end_turn" };
890 }
891​
892 if (emitXAiAskUserQuestion || emitXAiAskUserQuestionThenHang) {
893 const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
894 method: "x.ai/ask_user_question",
895 params: {
896 sessionId: requestedSessionId,
897 toolCallId: "ask-user-question-tool-call-1",
898 questions: [
899 {
900 question: "Which scope should Grok use?",
901 multiSelect: null,
902 options: [
903 { label: "Workspace", description: "Use the current workspace" },
904 { label: "Session", description: "Only use this session" },
905 ],
906 },
907 ],
908 mode: "default",
909 },
910 });
911 if (typeof result !== "object" || result === null || !("outcome" in result)) {
912 throw new Error("Expected _x.ai/ask_user_question response outcome.");
913 }
914 if (result.outcome === "cancelled") {
915 return { stopReason: "end_turn" };
916 }
917 if (
918 result.outcome !== "accepted" ||
919 !("answers" in result) ||
920 typeof result.answers !== "object" ||
921 result.answers === null
922 ) {
923 throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
924 }
925​
926 if (emitXAiAskUserQuestionThenHang) {
927 return yield* Effect.never;
928 }
929​
930 return { stopReason: "end_turn" };
931 }
932​
933 if (emitXAiPlanMdWrite) {
934 // Match Grok's real session layout so isGrokPlanMarkdownPath accepts it.
935 const planRoot = process.env.T3_ACP_PLAN_ROOT ?? "/tmp/mock-home/.grok";
936 const planPath = `${planRoot}/sessions/${requestedSessionId}/plan.md`;
937 const planBody = "# Mock plan\n\n- Write the feature\n- Add a test\n- Ship it\n";
938 // enter_plan_mode first so the adapter arms planModeActive.
939 yield* agent.client.sessionUpdate({
940 sessionId: requestedSessionId,
941 update: {
942 sessionUpdate: "tool_call",
943 toolCallId: "enter-plan-mode-1",
944 title: "enter_plan_mode",
945 kind: "other",
946 status: "completed",
947 rawInput: { variant: "EnterPlanMode" },
948 },
949 });
950 yield* agent.client.sessionUpdate({
951 sessionId: requestedSessionId,
952 update: {
953 sessionUpdate: "tool_call",
954 toolCallId: "plan-md-write-1",
955 title: "write",
956 kind: "edit",
957 status: "pending",
958 rawInput: { file_path: planPath, content: planBody },
959 },
960 });
961 yield* agent.client.sessionUpdate({
962 sessionId: requestedSessionId,
963 update: {
964 sessionUpdate: "tool_call_update",
965 toolCallId: "plan-md-write-1",
966 kind: "edit",
967 status: "completed",
968 title: `Write \`${planPath}\``,
969 rawInput: { file_path: planPath, content: planBody },
970 content: [
971 {
972 type: "diff",
973 path: planPath,
974 oldText: "",
975 newText: planBody,
976 },
977 ],
978 },
979 });
980 return { stopReason: "end_turn" };
981 }
982​
983 if (emitXAiExitPlanMode) {
984 const result = yield* agent.client.extRequest("_x.ai/exit_plan_mode", {
985 method: "x.ai/exit_plan_mode",
986 params: {
987 sessionId: requestedSessionId,
988 toolCallId: "exit-plan-mode-tool-call-1",
989 planContent: "# Exit plan\n\n- Step one\n- Step two\n",
990 },
991 });
992 if (typeof result !== "object" || result === null || !("outcome" in result)) {
993 throw new Error("Expected _x.ai/exit_plan_mode response outcome.");
994 }
995 if (
996 result.outcome !== "abandoned" &&
997 result.outcome !== "approved" &&
998 result.outcome !== "request_changes"
999 ) {
1000 throw new Error(
1001 `Expected exit_plan_mode outcome abandoned|approved|request_changes, got ${String(result.outcome)}`,
1002 );
1004 return { stopReason: "end_turn" };
1006​
1007 if (emitForeignSessionUpdates) {
1008 yield* agent.client.sessionUpdate({
1009 sessionId: requestedSessionId,
1010 update: {
1011 sessionUpdate: "agent_message_chunk",
1012 content: { type: "text", text: "root before child" },
1013 },
1014 });
1015 yield* agent.client.sessionUpdate({
1016 sessionId: "mock-child-session-1",
1017 update: {
1018 sessionUpdate: "agent_message_chunk",
1019 content: { type: "text", text: "child content" },
1020 },
1021 });
1022 yield* agent.client.sessionUpdate({
1023 sessionId: "mock-child-session-1",
1024 update: {
1025 sessionUpdate: "tool_call",
1026 toolCallId: "child-tool-call-1",
1027 title: "Child-only tool",
1028 kind: "other",
1029 status: "pending",
1030 rawInput: {},
1031 },
1032 });
1033 yield* agent.client.sessionUpdate({
1034 sessionId: requestedSessionId,
1035 update: {
1036 sessionUpdate: "agent_message_chunk",
1037 content: { type: "text", text: " root after child" },
1038 },
1039 });
1040 return { stopReason: "end_turn" };
1042​
1043 yield* agent.client.sessionUpdate({
1044 sessionId: requestedSessionId,
1045 update: {
1046 sessionUpdate: "plan",
1047 entries: [
1049 content: "Inspect mock ACP state",
1050 priority: "high",
1051 status: "completed",
1052 },
1054 content: "Implement the requested change",
1055 priority: "high",
1056 status: "in_progress",
1057 },
1058 ],
1059 },
1060 });
1061​
1062 yield* agent.client.sessionUpdate({
1063 sessionId: requestedSessionId,
1064 update: {
1065 sessionUpdate: "agent_message_chunk",
1066 content: { type: "text", text: promptResponseText ?? "hello from mock" },
1067 },
1068 });
1069​
1070 return { stopReason: "end_turn" };
1071 }),
1072 );
1073​
1074 yield* agent.handleUnknownExtRequest((method, params) => {
1075 if (method === "cursor/list_available_models") {
1076 return Effect.succeed({
1077 models: availableModels(),
1078 });
1080​
1081 if (method !== "session/mode/set") {
1082 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
1084​
1085 const nextModeId =
1086 typeof params === "object" &&
1087 params !== null &&
1088 "modeId" in params &&
1089 typeof params.modeId === "string"
1090 ? params.modeId
1091 : typeof params === "object" &&
1092 params !== null &&
1093 "mode" in params &&
1094 typeof params.mode === "string"
1095 ? params.mode
1096 : undefined;
1097 const requestedSessionId =
1098 typeof params === "object" &&
1099 params !== null &&
1100 "sessionId" in params &&
1101 typeof params.sessionId === "string"
1102 ? params.sessionId
1103 : sessionId;
1104​
1105 if (typeof nextModeId === "string" && nextModeId.trim()) {
1106 currentModeId = nextModeId.trim();
1107 return agent.client
1108 .sessionUpdate({
1109 sessionId: requestedSessionId,
1110 update: {
1111 sessionUpdate: "current_mode_update",
1112 currentModeId,
1113 },
1114 })
1115 .pipe(Effect.as({}));
1117​
1118 return Effect.succeed({});
1119 });
1120​
1121 return yield* Effect.never;
1122}).pipe(
1123 Effect.provide(
1124 EffectAcpAgent.layerStdio(
1125 requestLogPath
1126 ? {
1127 logIncoming: true,
1128 logger: (event) => {
1129 if (event.direction !== "incoming" || event.stage !== "raw") {
1130 return Effect.void;
1132 if (typeof event.payload !== "string") {
1133 return Effect.void;
1135 const payload = event.payload;
1136 return Effect.sync(() => {
1137 NodeFS.appendFileSync(
1138 requestLogPath,
1139 payload.endsWith("\n") ? payload : `${payload}\n`,
1140 "utf8",
1141 );
1142 });
1143 },
1145 : {},
1146 ),
1147 ),
1148 Effect.scoped,
1149 Effect.provide(NodeServices.layer),
1151​
1152NodeRuntime.runMain(program);