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

acp-mock-agent.ts

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