Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5
6import * as Effect from "effect/Effect";
7
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10
11import * as EffectAcpAgent from "effect-acp/agent";
12import * as AcpError from "effect-acp/errors";
13import type * as AcpSchema from "effect-acp/schema";
14
15import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
16
17const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
18const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
19const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
20const emitInterleavedAssistantToolCalls =
21 process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
22const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
23const emitPostSettleMonitorFlow = process.env.T3_ACP_EMIT_POST_SETTLE_MONITOR_FLOW === "1";
24const emitInTurnTaskOutputThenLateDuplicate =
25 process.env.T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE === "1";
26const injectedReportTriggerPath = process.env.T3_ACP_INJECTED_REPORT_TRIGGER_PATH;
27const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
28const emitElicitation = process.env.T3_ACP_EMIT_ELICITATION === "1";
29const emitUrlElicitation = process.env.T3_ACP_EMIT_URL_ELICITATION === "1";
30const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
31const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_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 hangAfterPermission = process.env.T3_ACP_HANG_AFTER_PERMISSION === "1";
35const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
36const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
37const emitTaskBackgroundedAfterCancel =
38 process.env.T3_ACP_EMIT_TASK_BACKGROUNDED_AFTER_CANCEL === "1";
39const residualCallbackResponseLogPath = process.env.T3_ACP_RESIDUAL_CALLBACK_RESPONSE_LOG_PATH;
40const residualCallbackTriggerPath = process.env.T3_ACP_RESIDUAL_CALLBACK_TRIGGER_PATH;
41const exitAfterResidualCallbacks = process.env.T3_ACP_EXIT_AFTER_RESIDUAL_CALLBACKS === "1";
42const emitRunningCommandThenHang = process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG === "1";
43const emitRunningCommandThenHangOnFirstPrompt =
44 process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG_FIRST_PROMPT === "1";
45const emitEmptySuccessfulBash = process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH === "1";
46const emitEmptySuccessfulBashThenHang =
47 process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG === "1";
48const exitOnCancel = process.env.T3_ACP_EXIT_ON_CANCEL === "1";
49const runningCommandIgnoresTerm = process.env.T3_ACP_RUNNING_COMMAND_IGNORE_TERM === "1";
50const runningCommandPidPath = process.env.T3_ACP_RUNNING_COMMAND_PID_PATH;
51const runningCommandSeparateSession = process.env.T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION === "1";
52const exitAfterRunningCommandLaunch = process.env.T3_ACP_EXIT_AFTER_RUNNING_COMMAND_LAUNCH === "1";
53const omitXAiPromptCompleteStopReason =
54 process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
55const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
56const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
57const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
58const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
59const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
60const emitStaleXAiPromptCompleteBeforeSecondHang =
61 process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
62const emitOverlappingXAiPromptCompleteOutOfOrder =
63 process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
64const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
65const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
66const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
67const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
68const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
69const supportsSessionLifecycle = process.env.T3_ACP_SESSION_LIFECYCLE === "1";
70const advertisedAuthMethodId = process.env.T3_ACP_AUTH_METHOD_ID?.trim();
71const requiresAuthentication = process.env.T3_ACP_REQUIRE_AUTH === "1";
72const permissionOptionIds = {
73 allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
74 allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
75 rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
76};
77const sessionId = "mock-session-1";
78
79let currentModeId = "ask";
80let currentModelId = "default";
81let parameterizedModelPicker = false;
82let currentReasoning = "medium";
83let currentContext = "272k";
84let currentFast = false;
85let authenticated = !requiresAuthentication;
86let promptCount = 0;
87let overlappingFirstPromptId: string | undefined;
88const cancelledSessions = new Set<string>();
89
90function promptIdFromRequestMeta(
91 request: Pick<AcpSchema.PromptRequest, "_meta">,
92): string | undefined {
93 const meta = request._meta;
94 if (meta === null || typeof meta !== "object") {
95 return undefined;
96 }
97 const promptId = meta.promptId ?? meta.requestId;
98 return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
99}
100
101function logExit(reason: string): void {
102 if (!exitLogPath) {
103 return;
104 }
105 NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
106}
107
108function writeJsonRpcNotification(method: string, params: unknown): void {
109 process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
110}
111
112function logResidualCallbackResponse(kind: string): void {
113 if (!residualCallbackResponseLogPath) return;
114 NodeFS.appendFileSync(residualCallbackResponseLogPath, `${kind}\n`, "utf8");
115}
116
117process.once("SIGTERM", () => {
118 logExit("SIGTERM");
119 process.exit(0);
120});
121
122process.once("SIGINT", () => {
123 logExit("SIGINT");
124 process.exit(0);
125});
126
127process.once("exit", (code) => {
128 logExit(`exit:${code}`);
129});
130
131function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
132 if (parameterizedModelPicker) {
133 const baseOptions: Array<AcpSchema.SessionConfigOption> = [
134 {
135 id: "mode",
136 name: "Mode",
137 category: "mode",
138 type: "select",
139 currentValue: currentModeId,
140 options: availableModes.map((mode) => ({
141 value: mode.id,
142 name: mode.name,
143 ...(mode.description ? { description: mode.description } : {}),
144 })),
145 },
146 {
147 id: "model",
148 name: "Model",
149 category: "model",
150 type: "select",
151 currentValue: currentModelId,
152 options: [
153 { value: "default", name: "Auto" },
154 { value: "composer-2", name: "Composer 2" },
155 { value: "gpt-5.4", name: "GPT-5.4" },
156 { value: "claude-opus-4-6", name: "Opus 4.6" },
157 ],
158 },
159 ];
160
161 switch (currentModelId) {
162 case "gpt-5.4":
163 return [
164 ...baseOptions,
165 {
166 id: "reasoning",
167 name: "Reasoning",
168 category: "thought_level",
169 type: "select",
170 currentValue: currentReasoning,
171 options: [
172 { value: "none", name: "None" },
173 { value: "low", name: "Low" },
174 { value: "medium", name: "Medium" },
175 { value: "high", name: "High" },
176 { value: "extra-high", name: "Extra High" },
177 ],
178 },
179 {
180 id: "context",
181 name: "Context",
182 category: "model_config",
183 type: "select",
184 currentValue: currentContext,
185 options: [
186 { value: "272k", name: "272K" },
187 { value: "1m", name: "1M" },
188 ],
189 },
190 {
191 id: "fast",
192 name: "Fast",
193 category: "model_config",
194 type: "select",
195 currentValue: String(currentFast),
196 options: [
197 { value: "false", name: "Off" },
198 { value: "true", name: "Fast" },
199 ],
200 },
201 ];
202 case "composer-2":
203 return [
204 ...baseOptions,
205 {
206 id: "fast",
207 name: "Fast",
208 category: "model_config",
209 type: "select",
210 currentValue: String(currentFast),
211 options: [
212 { value: "false", name: "Off" },
213 { value: "true", name: "Fast" },
214 ],
215 },
216 ];
217 case "claude-opus-4-6":
218 return [
219 ...baseOptions,
220 {
221 id: "reasoning",
222 name: "Reasoning",
223 category: "thought_level",
224 type: "select",
225 currentValue: currentReasoning,
226 options: [
227 { value: "low", name: "Low" },
228 { value: "medium", name: "Medium" },
229 { value: "high", name: "High" },
230 ],
231 },
232 {
233 id: "thinking",
234 name: "Thinking",
235 category: "model_config",
236 type: "boolean",
237 currentValue: true,
238 },
239 ];
240 default:
241 return baseOptions;
242 }
243 }
244
245 return [
246 {
247 id: "model",
248 name: "Model",
249 category: "model",
250 type: "select" as const,
251 currentValue: currentModelId,
252 options: [
253 { value: "default", name: "Auto" },
254 { value: "composer-2", name: "Composer 2" },
255 { value: "composer-2[fast=true]", name: "Composer 2 Fast" },
256 { value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
257 ],
258 },
259 ];
260}
261
262const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
263 {
264 id: "ask",
265 name: "Ask",
266 description: "Request permission before making any changes",
267 },
268 {
269 id: "architect",
270 name: "Architect",
271 description: "Design and plan software systems without implementation",
272 },
273 {
274 id: "code",
275 name: "Code",
276 description: "Write and modify code with full tool access",
277 },
278];
279
280function modeState(): AcpSchema.SessionModeState {
281 return {
282 currentModeId,
283 availableModes,
284 };
285}
286
287const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
288 { modelId: "grok-build", name: "Grok Build" },
289 { modelId: "grok-mock-alt", name: "Grok Mock Alt" },
290];
291
292function modelState(): AcpSchema.SessionModelState {
293 const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
294 ? currentModelId
295 : "grok-build";
296 return {
297 currentModelId: modelId,
298 availableModels: grokAcpModels,
299 };
300}
301
302const program = Effect.gen(function* () {
303 const agent = yield* EffectAcpAgent.AcpAgent;
304
305 yield* agent.handleInitialize((request) =>
306 Effect.sync(() => {
307 parameterizedModelPicker =
308 request.clientCapabilities?._meta?.parameterizedModelPicker === true;
309 return {
310 protocolVersion: 1,
311 agentCapabilities: {
312 loadSession: true,
313 ...(supportsSessionLifecycle
314 ? {
315 sessionCapabilities: {
316 list: {},
317 fork: {},
318 resume: {},
319 close: {},
320 },
321 }
322 : {}),
323 },
324 ...(advertisedAuthMethodId
325 ? {
326 authMethods: [
327 {
328 id: advertisedAuthMethodId,
329 name: "Mock agent authentication",
330 },
331 ],
332 }
333 : {}),
334 };
335 }),
336 );
337
338 yield* agent.handleAuthenticate((request) =>
339 Effect.gen(function* () {
340 if (advertisedAuthMethodId && request.methodId !== advertisedAuthMethodId) {
341 return yield* AcpError.AcpRequestError.invalidParams(
342 `Unknown mock authentication method: ${request.methodId}`,
343 );
344 }
345 authenticated = true;
346 return {};
347 }),
348 );
349
350 const requireAuthentication = Effect.fn("acpMockAgent.requireAuthentication")(function* () {
351 if (!authenticated) {
352 return yield* AcpError.AcpRequestError.authRequired();
353 }
354 });
355
356 yield* agent.handleCreateSession(() =>
357 Effect.gen(function* () {
358 yield* requireAuthentication();
359 return {
360 sessionId,
361 modes: modeState(),
362 models: modelState(),
363 configOptions: configOptions(),
364 };
365 }),
366 );
367
368 const emitLoadReplayNotifications = (requestedSessionId: string) => {
369 writeJsonRpcNotification("session/update", {
370 _meta: { isReplay: true },
371 sessionId: requestedSessionId,
372 update: {
373 sessionUpdate: "tool_call",
374 toolCallId: "replay-tool-1",
375 title: "Replay tool",
376 kind: "search",
377 status: "completed",
378 },
379 });
380 writeJsonRpcNotification("session/update", {
381 _meta: { isReplay: true },
382 sessionId: requestedSessionId,
383 update: {
384 sessionUpdate: "agent_message_chunk",
385 content: { type: "text", text: "replayed assistant text" },
386 },
387 });
388 };
389
390 yield* agent.handleLoadSession((request) =>
391 Effect.gen(function* () {
392 const requestedSessionId = String(request.sessionId ?? sessionId);
393 if (failLoadSession) {
394 return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
395 }
396 if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
397 emitLoadReplayNotifications(requestedSessionId);
398 yield* agent.client.sessionUpdate({
399 sessionId: requestedSessionId,
400 update: {
401 sessionUpdate: "user_message_chunk",
402 content: { type: "text", text: "replay-tail" },
403 },
404 });
405 yield* Effect.sleep(loadSessionDelayMs);
406 return {
407 modes: modeState(),
408 models: modelState(),
409 configOptions: configOptions(),
410 };
411 }
412 if (emitLoadReplay) {
413 emitLoadReplayNotifications(requestedSessionId);
414 }
415 yield* agent.client.sessionUpdate({
416 sessionId: requestedSessionId,
417 update: {
418 sessionUpdate: "user_message_chunk",
419 content: { type: "text", text: "replay" },
420 },
421 });
422 return {
423 modes: modeState(),
424 models: modelState(),
425 configOptions: configOptions(),
426 };
427 }),
428 );
429
430 yield* agent.handleListSessions((request) =>
431 Effect.gen(function* () {
432 yield* requireAuthentication();
433 return {
434 sessions: [
435 {
436 sessionId,
437 cwd: request.cwd ?? process.cwd(),
438 title: "Mock session",
439 updatedAt: "1970-01-01T00:00:00.000Z",
440 },
441 ],
442 };
443 }),
444 );
445
446 yield* agent.handleForkSession((request) =>
447 Effect.gen(function* () {
448 yield* requireAuthentication();
449 return {
450 sessionId: `${request.sessionId}-fork`,
451 modes: modeState(),
452 models: modelState(),
453 configOptions: configOptions(),
454 };
455 }),
456 );
457
458 yield* agent.handleResumeSession(() =>
459 Effect.gen(function* () {
460 yield* requireAuthentication();
461 return {
462 modes: modeState(),
463 models: modelState(),
464 configOptions: configOptions(),
465 };
466 }),
467 );
468
469 yield* agent.handleCloseSession(() =>
470 Effect.gen(function* () {
471 yield* requireAuthentication();
472 return {};
473 }),
474 );
475
476 yield* agent.handleSetSessionModel((request) =>
477 Effect.gen(function* () {
478 if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
479 return yield* AcpError.AcpRequestError.invalidParams(
480 `Unknown mock model id: ${request.modelId}`,
481 {
482 method: "session/set_model",
483 params: request,
484 },
485 );
486 }
487 currentModelId = request.modelId;
488 return {};
489 }),
490 );
491
492 yield* agent.handleSetSessionConfigOption((request) =>
493 Effect.gen(function* () {
494 if (exitOnSetConfigOption) {
495 return yield* Effect.sync(() => {
496 process.exit(7);
497 });
498 }
499 if (failSetConfigOption) {
500 return yield* AcpError.AcpRequestError.invalidParams(
501 "Mock invalid params for session/set_config_option",
502 {
503 method: "session/set_config_option",
504 params: request,
505 },
506 );
507 }
508 if (request.configId === "mode" && typeof request.value === "string") {
509 currentModeId = request.value;
510 }
511 if (request.configId === "model" && typeof request.value === "string") {
512 currentModelId = request.value;
513 }
514 if (request.configId === "reasoning" && typeof request.value === "string") {
515 currentReasoning = request.value;
516 }
517 if (request.configId === "context" && typeof request.value === "string") {
518 currentContext = request.value;
519 }
520 if (request.configId === "fast") {
521 currentFast = request.value === true || request.value === "true";
522 }
523 return {
524 configOptions: configOptions(),
525 };
526 }),
527 );
528
529 yield* agent.handleCancel(({ sessionId }) =>
530 Effect.gen(function* () {
531 const cancelledSessionId = String(sessionId ?? "mock-session-1");
532 cancelledSessions.add(cancelledSessionId);
533 if (exitOnCancel) {
534 return yield* Effect.sync(() => process.exit(0));
535 }
536 if (emitLateUpdateAfterCancel) {
537 yield* Effect.sleep("50 millis");
538 yield* Effect.sync(() => {
539 writeJsonRpcNotification("session/update", {
540 sessionId: cancelledSessionId,
541 update: {
542 sessionUpdate: "agent_message_chunk",
543 content: { type: "text", text: "late after cancel" },
544 },
545 });
546 });
547 }
548 if (emitTaskBackgroundedAfterCancel) {
549 // Grok cancel-as-detach: the foreground command is re-run as a
550 // background task that later completes on its own.
551 yield* Effect.sync(() => {
552 writeJsonRpcNotification("_x.ai/task_backgrounded", {
553 sessionId: cancelledSessionId,
554 update: {
555 sessionUpdate: "task_backgrounded",
556 tool_call_id: "task-bg-1",
557 task_id: "task-bg-1",
558 command: "sleep 30",
559 },
560 });
561 });
562 yield* Effect.sleep("1200 millis")
563 .pipe(
564 Effect.andThen(
565 Effect.sync(() => {
566 writeJsonRpcNotification("_x.ai/task_completed", {
567 sessionId: cancelledSessionId,
568 update: {
569 sessionUpdate: "task_completed",
570 task_snapshot: { task_id: "task-bg-1", command: "sleep 30" },
571 },
572 });
573 }),
574 ),
575 )
576 .pipe(Effect.forkDetach);
577 }
578 }),
579 );
580
581 yield* agent.handlePrompt((request) =>
582 Effect.gen(function* () {
583 const requestedSessionId = String(request.sessionId ?? sessionId);
584 beginAcpMockPrompt(cancelledSessions, requestedSessionId);
585 promptCount += 1;
586
587 if (residualCallbackTriggerPath !== undefined) {
588 yield* Effect.gen(function* () {
589 while (!(yield* Effect.sync(() => NodeFS.existsSync(residualCallbackTriggerPath)))) {
590 yield* Effect.sleep("20 millis");
591 }
592 yield* Effect.sync(() => {
593 writeJsonRpcNotification("session/update", {
594 sessionId: requestedSessionId,
595 update: {
596 sessionUpdate: "agent_message_chunk",
597 content: { type: "text", text: "residual assistant callback" },
598 },
599 });
600 writeJsonRpcNotification("session/update", {
601 sessionId: requestedSessionId,
602 update: {
603 sessionUpdate: "tool_call",
604 toolCallId: "residual-tool-call",
605 title: "Residual tool callback",
606 kind: "other",
607 status: "pending",
608 rawInput: {},
609 },
610 });
611 writeJsonRpcNotification("session/update", {
612 sessionId: requestedSessionId,
613 update: {
614 sessionUpdate: "plan",
615 entries: [
616 { content: "Residual plan callback", priority: "high", status: "pending" },
617 ],
618 },
619 });
620 });
621 yield* agent.client
622 .requestPermission({
623 sessionId: requestedSessionId,
624 toolCall: {
625 toolCallId: "residual-permission",
626 title: "Residual permission callback",
627 },
628 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
629 })
630 .pipe(
631 Effect.exit,
632 Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("permission"))),
633 Effect.ignore,
634 Effect.forkDetach,
635 );
636 yield* agent.client
637 .elicit({
638 sessionId: requestedSessionId,
639 message: "Residual elicitation callback",
640 mode: "form",
641 requestedSchema: {
642 type: "object",
643 properties: {
644 approved: { type: "boolean", title: "Approved" },
645 },
646 },
647 })
648 .pipe(
649 Effect.exit,
650 Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("elicitation"))),
651 Effect.ignore,
652 Effect.forkDetach,
653 );
654 if (exitAfterResidualCallbacks) {
655 yield* Effect.sleep("100 millis");
656 return yield* Effect.sync(() => process.exit(0));
657 }
658 }).pipe(Effect.forkDetach);
659 }
660
661 if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
662 yield* Effect.sleep(`${promptDelayMs} millis`);
663 }
664
665 if (failPrompt) {
666 return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
667 }
668
669 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
670 return {
671 stopReason: "end_turn",
672 _meta: {
673 promptId: "mock-stale-xai-prompt-1",
674 requestId: "mock-stale-xai-prompt-1",
675 },
676 };
677 }
678
679 if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
680 const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
681 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
682 sessionId: requestedSessionId,
683 promptId: "mock-stale-xai-prompt-1",
684 stopReason: "end_turn",
685 agentResult: null,
686 });
687
688 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
689 sessionId: requestedSessionId,
690 promptId: currentPromptId,
691 stopReason: "end_turn",
692 agentResult: null,
693 });
694
695 return yield* Effect.never;
696 }
697
698 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
699 overlappingFirstPromptId = promptIdFromRequestMeta(request);
700 return yield* Effect.never;
701 }
702
703 if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
704 const secondPromptId = promptIdFromRequestMeta(request);
705 if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
706 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
707 sessionId: requestedSessionId,
708 promptId: secondPromptId,
709 stopReason: "end_turn",
710 agentResult: null,
711 });
712 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
713 sessionId: requestedSessionId,
714 promptId: overlappingFirstPromptId,
715 stopReason: "end_turn",
716 agentResult: null,
717 });
718 }
719 return yield* Effect.never;
720 }
721
722 if (
723 hangPromptForever ||
724 (hangFirstPromptForever && promptCount === 1) ||
725 (emitEmptySuccessfulBashThenHang && promptCount === 2)
726 ) {
727 return yield* Effect.never;
728 }
729
730 if (
731 emitRunningCommandThenHang ||
732 (emitRunningCommandThenHangOnFirstPrompt && promptCount === 1)
733 ) {
734 const toolCallId = "tool-call-running-1";
735 if (runningCommandPidPath !== undefined) {
736 const command = runningCommandIgnoresTerm
737 ? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"'
738 : 'sleep 120 & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"';
739 if (runningCommandSeparateSession) {
740 const launcher = [
741 'const { spawn } = require("node:child_process");',
742 "const child = spawn(process.argv[1], process.argv.slice(2), { stdio: 'ignore' });",
743 "child.once('exit', (code, signal) => process.exitCode = code ?? (signal ? 1 : 0));",
744 ].join(" ");
745 const detachedCommand = runningCommandIgnoresTerm
746 ? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"'
747 : 'sleep 120 & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"';
748 // Nested bash publishes "$PPID $$ $child" once it starts. Do not
749 // write the launcher PID alone here: that races with bash and can
750 // clobber the triple that interrupt tests wait for.
751 const detachedLauncher = NodeChildProcess.spawn(
752 process.execPath,
753 ["-e", launcher, "bash", "-c", detachedCommand, "bash", runningCommandPidPath],
754 { detached: true, stdio: "ignore" },
755 );
756 detachedLauncher.unref();
757 } else {
758 NodeChildProcess.spawn("bash", ["-c", command, "bash", runningCommandPidPath], {
759 stdio: "ignore",
760 });
761 }
762 }
763 yield* agent.client.sessionUpdate({
764 sessionId: requestedSessionId,
765 update: {
766 sessionUpdate: "tool_call",
767 toolCallId,
768 title: "Terminal",
769 kind: "execute",
770 status: "pending",
771 rawInput: {
772 command: ["sleep", "120"],
773 },
774 },
775 });
776 yield* agent.client.sessionUpdate({
777 sessionId: requestedSessionId,
778 update: {
779 sessionUpdate: "tool_call_update",
780 toolCallId,
781 title: "Terminal",
782 kind: "execute",
783 status: "in_progress",
784 rawInput: {
785 command: ["sleep", "120"],
786 },
787 // Grok-like mid-stream Bash re-report: exit_code 0 while still running.
788 rawOutput: { type: "Bash", exit_code: 0 },
789 },
790 });
791 yield* agent.client.sessionUpdate({
792 sessionId: requestedSessionId,
793 update: {
794 sessionUpdate: "tool_call",
795 toolCallId: "tool-call-output-1",
796 title: "get_command_or_subagent_output",
797 kind: "other",
798 status: "pending",
799 rawInput: { task_id: "task-running-1" },
800 },
801 });
802 yield* agent.client.sessionUpdate({
803 sessionId: requestedSessionId,
804 update: {
805 sessionUpdate: "tool_call_update",
806 toolCallId: "tool-call-output-1",
807 status: "in_progress",
808 rawOutput: { task_id: "task-running-1", status: "running" },
809 },
810 });
811 if (exitAfterRunningCommandLaunch) {
812 yield* Effect.sleep("100 millis");
813 return yield* Effect.sync(() => process.exit(0));
814 }
815 // Stay open until session/cancel so interrupt tests can observe a running tool.
816 while (!cancelledSessions.has(requestedSessionId)) {
817 yield* Effect.sleep("25 millis");
818 }
819 cancelledSessions.delete(requestedSessionId);
820 return { stopReason: "cancelled" };
821 }
822
823 if (emitEmptySuccessfulBash || (emitEmptySuccessfulBashThenHang && promptCount === 1)) {
824 const update = {
825 sessionId: requestedSessionId,
826 update: {
827 sessionUpdate: "tool_call_update",
828 toolCallId: "tool-call-empty-success-1",
829 title: "Terminal",
830 kind: "execute",
831 status: "completed",
832 rawInput: { command: "true" },
833 rawOutput: { type: "Bash", exit_code: 0 },
834 },
835 } as const;
836 yield* agent.client.sessionUpdate(update);
837 yield* Effect.sleep("25 millis");
838 yield* agent.client.sessionUpdate(update);
839 return { stopReason: "end_turn" };
840 }
841
842 if (emitXAiPromptCompleteThenHang) {
843 writeJsonRpcNotification("session/update", {
844 sessionId: requestedSessionId,
845 update: {
846 sessionUpdate: "agent_message_chunk",
847 content: { type: "text", text: "hello from " },
848 },
849 });
850
851 if (emitForeignSessionUpdates) {
852 writeJsonRpcNotification("session/update", {
853 sessionId: "mock-child-session-1",
854 update: {
855 sessionUpdate: "agent_message_chunk",
856 content: { type: "text", text: "child before completion" },
857 },
858 });
859 }
860
861 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
862 sessionId: requestedSessionId,
863 promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
864 ...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
865 agentResult: null,
866 });
867
868 if (emitForeignSessionUpdates) {
869 writeJsonRpcNotification("session/update", {
870 sessionId: "mock-child-session-1",
871 update: {
872 sessionUpdate: "tool_call",
873 toolCallId: "child-tool-call-1",
874 title: "Child-only tool",
875 kind: "other",
876 status: "pending",
877 rawInput: {},
878 },
879 });
880 writeJsonRpcNotification("session/update", {
881 sessionId: "mock-child-session-1",
882 update: {
883 sessionUpdate: "agent_message_chunk",
884 content: { type: "text", text: "child after completion" },
885 },
886 });
887 }
888
889 writeJsonRpcNotification("session/update", {
890 sessionId: requestedSessionId,
891 update: {
892 sessionUpdate: "agent_message_chunk",
893 content: { type: "text", text: "mock" },
894 },
895 });
896
897 return yield* Effect.never;
898 }
899
900 if (emitInterleavedAssistantToolCalls) {
901 const toolCallId = "tool-call-1";
902
903 yield* agent.client.sessionUpdate({
904 sessionId: requestedSessionId,
905 update: {
906 sessionUpdate: "agent_message_chunk",
907 content: { type: "text", text: "before tool" },
908 },
909 });
910
911 yield* agent.client.sessionUpdate({
912 sessionId: requestedSessionId,
913 update: {
914 sessionUpdate: "tool_call",
915 toolCallId,
916 title: "Terminal",
917 kind: "execute",
918 status: "pending",
919 rawInput: {
920 command: ["echo", "hello"],
921 },
922 },
923 });
924
925 yield* agent.client.sessionUpdate({
926 sessionId: requestedSessionId,
927 update: {
928 sessionUpdate: "tool_call_update",
929 toolCallId,
930 status: "completed",
931 rawOutput: {
932 exitCode: 0,
933 stdout: "hello",
934 stderr: "",
935 },
936 },
937 });
938
939 yield* agent.client.sessionUpdate({
940 sessionId: requestedSessionId,
941 update: {
942 sessionUpdate: "agent_message_chunk",
943 content: { type: "text", text: "after tool" },
944 },
945 });
946
947 return { stopReason: "end_turn" };
948 }
949
950 if (emitElicitation) {
951 yield* agent.client.elicit({
952 sessionId: requestedSessionId,
953 message: "Approve this request?",
954 mode: "form",
955 requestedSchema: {
956 type: "object",
957 properties: {
958 approved: { type: "boolean", title: "Approved" },
959 },
960 },
961 });
962 return { stopReason: "end_turn" };
963 }
964
965 if (emitUrlElicitation) {
966 yield* agent.client.elicit({
967 sessionId: requestedSessionId,
968 message: "Open authentication page",
969 mode: "url",
970 url: "https://example.com/auth",
971 elicitationId: "url-elicitation-1",
972 });
973 return { stopReason: "end_turn" };
974 }
975
976 if (emitToolCalls) {
977 const toolCallId = "tool-call-1";
978
979 yield* agent.client.sessionUpdate({
980 sessionId: requestedSessionId,
981 update: {
982 sessionUpdate: "tool_call",
983 toolCallId,
984 title: "Terminal",
985 kind: "execute",
986 status: "pending",
987 rawInput: {
988 command: ["cat", "server/package.json"],
989 },
990 },
991 });
992
993 yield* agent.client.sessionUpdate({
994 sessionId: requestedSessionId,
995 update: {
996 sessionUpdate: "tool_call_update",
997 toolCallId,
998 status: "in_progress",
999 },
1000 });
1001
1002 const permission = yield* agent.client.requestPermission({
1003 sessionId: requestedSessionId,
1004 toolCall: {
1005 toolCallId,
1006 title: "`cat server/package.json`",
1007 kind: "execute",
1008 status: "pending",
1009 content: [
1010 {
1011 type: "content",
1012 content: {
1013 type: "text",
1014 text: "Not in allowlist: cat server/package.json",
1015 },
1016 },
1017 ],
1018 },
1019 options: [
1020 { optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
1021 {
1022 optionId: permissionOptionIds.allowAlways,
1023 name: "Allow always",
1024 kind: "allow_always",
1025 },
1026 { optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
1027 ],
1028 });
1029
1030 const cancelled =
1031 cancelledSessions.delete(requestedSessionId) ||
1032 permission.outcome.outcome === "cancelled";
1033
1034 if (hangAfterPermission) {
1035 return yield* Effect.never;
1036 }
1037
1038 yield* agent.client.sessionUpdate({
1039 sessionId: requestedSessionId,
1040 update: {
1041 sessionUpdate: "tool_call_update",
1042 toolCallId,
1043 title: "Terminal",
1044 kind: "execute",
1045 status: "completed",
1046 rawOutput: {
1047 exitCode: 0,
1048 stdout: '{ "name": "t3" }',
1049 stderr: "",
1050 },
1051 },
1052 });
1053
1054 yield* agent.client.sessionUpdate({
1055 sessionId: requestedSessionId,
1056 update: {
1057 sessionUpdate: "agent_message_chunk",
1058 content: { type: "text", text: "hello from mock" },
1059 },
1060 });
1061
1062 return { stopReason: cancelled ? "cancelled" : "end_turn" };
1063 }
1064
1065 if (emitGenericToolPlaceholders) {
1066 const toolCallId = "tool-call-generic-1";
1067
1068 yield* agent.client.sessionUpdate({
1069 sessionId: requestedSessionId,
1070 update: {
1071 sessionUpdate: "tool_call",
1072 toolCallId,
1073 title: "Read File",
1074 kind: "read",
1075 status: "pending",
1076 rawInput: {},
1077 },
1078 });
1079
1080 yield* agent.client.sessionUpdate({
1081 sessionId: requestedSessionId,
1082 update: {
1083 sessionUpdate: "tool_call_update",
1084 toolCallId,
1085 status: "in_progress",
1086 },
1087 });
1088
1089 yield* agent.client.sessionUpdate({
1090 sessionId: requestedSessionId,
1091 update: {
1092 sessionUpdate: "tool_call_update",
1093 toolCallId,
1094 status: "completed",
1095 rawOutput: {
1096 content: "package.json\n",
1097 },
1098 },
1099 });
1100
1101 return { stopReason: "end_turn" };
1102 }
1103
1104 // In-turn monitor + TaskOutput hydrate, then a late post-finalize
1105 // duplicate terminal TaskOutput for the same task. Exercises the
1106 // already-handled short-circuit: must not pin hasPendingBackgroundWork.
1107 if (emitInTurnTaskOutputThenLateDuplicate) {
1108 const monitorToolCallId = "tool-call-monitor-1";
1109 yield* agent.client.sessionUpdate({
1110 sessionId: requestedSessionId,
1111 update: {
1112 sessionUpdate: "tool_call",
1113 toolCallId: monitorToolCallId,
1114 title: "Monitor: mock background task",
1115 kind: "execute",
1116 status: "pending",
1117 rawInput: {},
1118 },
1119 });
1120 yield* agent.client.sessionUpdate({
1121 sessionId: requestedSessionId,
1122 update: {
1123 sessionUpdate: "tool_call_update",
1124 toolCallId: monitorToolCallId,
1125 status: "in_progress",
1126 },
1127 });
1128 yield* agent.client.sessionUpdate({
1129 sessionId: requestedSessionId,
1130 update: {
1131 sessionUpdate: "tool_call",
1132 toolCallId: "tool-call-fetch-1",
1133 title: "get_command_or_subagent_output",
1134 kind: "other",
1135 status: "pending",
1136 rawInput: { task_id: "task-monitor-1" },
1137 },
1138 });
1139 yield* agent.client.sessionUpdate({
1140 sessionId: requestedSessionId,
1141 update: {
1142 sessionUpdate: "tool_call_update",
1143 toolCallId: "tool-call-fetch-1",
1144 status: "completed",
1145 rawOutput: { output: "MONITOR_LISTING_TOKEN" },
1146 },
1147 });
1148 yield* agent.client.sessionUpdate({
1149 sessionId: requestedSessionId,
1150 update: {
1151 sessionUpdate: "agent_message_chunk",
1152 content: { type: "text", text: "Monitor listing ready in-turn." },
1153 },
1154 });
1155 // After deferred finalize (~2s) clears activeTurn, re-emit a terminal
1156 // TaskOutput for the same task so bufferPostSettleWake sees
1157 // alreadyHandledToolUpdate with a non-empty wake path.
1158 yield* Effect.gen(function* () {
1159 yield* Effect.sleep("2500 millis");
1160 yield* Effect.sync(() => {
1161 writeJsonRpcNotification("session/update", {
1162 sessionId: requestedSessionId,
1163 update: {
1164 sessionUpdate: "tool_call_update",
1165 toolCallId: "tool-call-fetch-1",
1166 title: "get_command_or_subagent_output",
1167 kind: "other",
1168 status: "completed",
1169 rawOutput: { output: "MONITOR_LISTING_TOKEN_LATE" },
1170 },
1171 });
1172 });
1173 }).pipe(Effect.forkDetach);
1174 return { stopReason: "end_turn" };
1175 }
1176
1177 if (emitPostSettleMonitorFlow) {
1178 const monitorToolCallId = "tool-call-monitor-1";
1179
1180 yield* agent.client.sessionUpdate({
1181 sessionId: requestedSessionId,
1182 update: {
1183 sessionUpdate: "tool_call",
1184 toolCallId: monitorToolCallId,
1185 title: "Monitor: mock background task",
1186 kind: "execute",
1187 status: "pending",
1188 rawInput: {},
1189 },
1190 });
1191
1192 yield* agent.client.sessionUpdate({
1193 sessionId: requestedSessionId,
1194 update: {
1195 sessionUpdate: "tool_call_update",
1196 toolCallId: monitorToolCallId,
1197 status: "in_progress",
1198 },
1199 });
1200
1201 // After the prompt settles, replay the CLI-injected monitor-event
1202 // turn: end notice, TaskOutput hydration, then (once the trigger
1203 // file exists) the report chunk. Detached fiber on the real clock;
1204 // it outlives the prompt handler.
1205 yield* Effect.gen(function* () {
1206 yield* Effect.sleep("150 millis");
1207 yield* Effect.sync(() => {
1208 writeJsonRpcNotification("session/update", {
1209 sessionId: requestedSessionId,
1210 update: {
1211 sessionUpdate: "user_message_chunk",
1212 content: {
1213 type: "text",
1214 text: 'Monitor "task-monitor-1" ended: [monitor ended: exit 0]',
1215 },
1216 },
1217 });
1218 writeJsonRpcNotification("session/update", {
1219 sessionId: requestedSessionId,
1220 update: {
1221 sessionUpdate: "tool_call",
1222 toolCallId: "tool-call-fetch-1",
1223 title: "get_command_or_subagent_output",
1224 kind: "other",
1225 status: "pending",
1226 rawInput: { task_id: "task-monitor-1" },
1227 },
1228 });
1229 writeJsonRpcNotification("session/update", {
1230 sessionId: requestedSessionId,
1231 update: {
1232 sessionUpdate: "tool_call_update",
1233 toolCallId: "tool-call-fetch-1",
1234 status: "completed",
1235 rawOutput: { output: "MONITOR_LISTING_TOKEN" },
1236 },
1237 });
1238 });
1239 if (injectedReportTriggerPath === undefined) return;
1240 while (!(yield* Effect.sync(() => NodeFS.existsSync(injectedReportTriggerPath)))) {
1241 yield* Effect.sleep("20 millis");
1242 }
1243 yield* Effect.sync(() => {
1244 writeJsonRpcNotification("session/update", {
1245 sessionId: requestedSessionId,
1246 update: {
1247 sessionUpdate: "agent_message_chunk",
1248 content: { type: "text", text: "Monitor finished. MONITOR_REPORT_TOKEN" },
1249 },
1250 });
1251 });
1252 }).pipe(Effect.forkDetach);
1253
1254 return { stopReason: "end_turn" };
1255 }
1256
1257 if (emitAskQuestion) {
1258 yield* agent.client.extRequest("cursor/ask_question", {
1259 toolCallId: "ask-question-tool-call-1",
1260 title: "Question",
1261 questions: [
1262 {
1263 id: "scope",
1264 prompt: "Which scope?",
1265 options: [
1266 { id: "workspace", label: "Workspace" },
1267 { id: "session", label: "Session" },
1268 ],
1269 },
1270 ],
1271 });
1272
1273 return { stopReason: "end_turn" };
1274 }
1275
1276 if (emitXAiAskUserQuestion) {
1277 const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
1278 method: "x.ai/ask_user_question",
1279 params: {
1280 sessionId: requestedSessionId,
1281 toolCallId: "ask-user-question-tool-call-1",
1282 questions: [
1283 {
1284 question: "Which scope should Grok use?",
1285 multiSelect: null,
1286 options: [
1287 { label: "Workspace", description: "Use the current workspace" },
1288 { label: "Session", description: "Only use this session" },
1289 ],
1290 },
1291 ],
1292 mode: "default",
1293 },
1294 });
1295 if (typeof result !== "object" || result === null || !("outcome" in result)) {
1296 throw new Error("Expected _x.ai/ask_user_question response outcome.");
1297 }
1298 if (result.outcome === "cancelled") {
1299 return { stopReason: "end_turn" };
1300 }
1301 if (
1302 result.outcome !== "accepted" ||
1303 !("answers" in result) ||
1304 typeof result.answers !== "object" ||
1305 result.answers === null
1306 ) {
1307 throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
1308 }
1309
1310 return { stopReason: "end_turn" };
1311 }
1312
1313 if (emitForeignSessionUpdates) {
1314 yield* agent.client.sessionUpdate({
1315 sessionId: requestedSessionId,
1316 update: {
1317 sessionUpdate: "agent_message_chunk",
1318 content: { type: "text", text: "root before child" },
1319 },
1320 });
1321 yield* agent.client.sessionUpdate({
1322 sessionId: "mock-child-session-1",
1323 update: {
1324 sessionUpdate: "agent_message_chunk",
1325 content: { type: "text", text: "child content" },
1326 },
1327 });
1328 yield* agent.client.sessionUpdate({
1329 sessionId: "mock-child-session-1",
1330 update: {
1331 sessionUpdate: "tool_call",
1332 toolCallId: "child-tool-call-1",
1333 title: "Child-only tool",
1334 kind: "other",
1335 status: "pending",
1336 rawInput: {},
1337 },
1338 });
1339 yield* agent.client.sessionUpdate({
1340 sessionId: requestedSessionId,
1341 update: {
1342 sessionUpdate: "agent_message_chunk",
1343 content: { type: "text", text: " root after child" },
1344 },
1345 });
1346 return { stopReason: "end_turn" };
1347 }
1348
1349 yield* agent.client.sessionUpdate({
1350 sessionId: requestedSessionId,
1351 update: {
1352 sessionUpdate: "plan",
1353 entries: [
1354 {
1355 content: "Inspect mock ACP state",
1356 priority: "high",
1357 status: "completed",
1358 },
1359 {
1360 content: "Implement the requested change",
1361 priority: "high",
1362 status: "in_progress",
1363 },
1364 ],
1365 },
1366 });
1367
1368 yield* agent.client.sessionUpdate({
1369 sessionId: requestedSessionId,
1370 update: {
1371 sessionUpdate: "agent_message_chunk",
1372 content: { type: "text", text: promptResponseText ?? "hello from mock" },
1373 },
1374 });
1375
1376 return { stopReason: "end_turn" };
1377 }),
1378 );
1379
1380 yield* agent.handleUnknownExtRequest((method, params) => {
1381 if (method !== "session/mode/set") {
1382 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
1383 }
1384
1385 const nextModeId =
1386 typeof params === "object" &&
1387 params !== null &&
1388 "modeId" in params &&
1389 typeof params.modeId === "string"
1390 ? params.modeId
1391 : typeof params === "object" &&
1392 params !== null &&
1393 "mode" in params &&
1394 typeof params.mode === "string"
1395 ? params.mode
1396 : undefined;
1397 const requestedSessionId =
1398 typeof params === "object" &&
1399 params !== null &&
1400 "sessionId" in params &&
1401 typeof params.sessionId === "string"
1402 ? params.sessionId
1403 : sessionId;
1404
1405 if (typeof nextModeId === "string" && nextModeId.trim()) {
1406 currentModeId = nextModeId.trim();
1407 return agent.client
1408 .sessionUpdate({
1409 sessionId: requestedSessionId,
1410 update: {
1411 sessionUpdate: "current_mode_update",
1412 currentModeId,
1413 },
1414 })
1415 .pipe(Effect.as({}));
1416 }
1417
1418 return Effect.succeed({});
1419 });
1420
1421 return yield* Effect.never;
1422}).pipe(
1423 Effect.provide(
1424 EffectAcpAgent.layerStdio(
1425 requestLogPath
1426 ? {
1427 logIncoming: true,
1428 logger: (event) => {
1429 if (event.direction !== "incoming" || event.stage !== "raw") {
1430 return Effect.void;
1431 }
1432 if (typeof event.payload !== "string") {
1433 return Effect.void;
1434 }
1435 const payload = event.payload;
1436 return Effect.sync(() => {
1437 NodeFS.appendFileSync(
1438 requestLogPath,
1439 payload.endsWith("\n") ? payload : `${payload}\n`,
1440 "utf8",
1441 );
1442 });
1443 },
1444 }
1445 : {},
1446 ),
1447 ),
1448 Effect.scoped,
1449 Effect.provide(NodeServices.layer),
1450);
1451
1452NodeRuntime.runMain(program);