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

acp-mock-agent.ts

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