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

acp-mock-agent.ts

711 lines20.0 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 failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
23const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
24const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
25const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
26const permissionOptionIds = {
27 allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
28 allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
29 rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
30};
31const sessionId = "mock-session-1";
32​
33let currentModeId = "ask";
34let currentModelId = "default";
35let parameterizedModelPicker = false;
36let currentReasoning = "medium";
37let currentContext = "272k";
38let currentFast = false;
39const cancelledSessions = new Set<string>();
40​
41function logExit(reason: string): void {
42 if (!exitLogPath) {
43 return;
44 }
45 NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
47​
48process.once("SIGTERM", () => {
49 logExit("SIGTERM");
50 process.exit(0);
51});
52​
53process.once("SIGINT", () => {
54 logExit("SIGINT");
55 process.exit(0);
56});
57​
58process.once("exit", (code) => {
59 logExit(`exit:${code}`);
60});
61​
62function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
63 if (parameterizedModelPicker) {
64 const baseOptions: Array<AcpSchema.SessionConfigOption> = [
65 {
66 id: "mode",
67 name: "Mode",
68 category: "mode",
69 type: "select",
70 currentValue: currentModeId,
71 options: availableModes.map((mode) => ({
72 value: mode.id,
73 name: mode.name,
74 ...(mode.description ? { description: mode.description } : {}),
75 })),
76 },
77 {
78 id: "model",
79 name: "Model",
80 category: "model",
81 type: "select",
82 currentValue: currentModelId,
83 options: [
84 { value: "default", name: "Auto" },
85 { value: "composer-2", name: "Composer 2" },
86 { value: "gpt-5.4", name: "GPT-5.4" },
87 { value: "claude-opus-4-6", name: "Opus 4.6" },
88 ],
89 },
90 ];
91​
92 switch (currentModelId) {
93 case "gpt-5.4":
94 return [
95 ...baseOptions,
96 {
97 id: "reasoning",
98 name: "Reasoning",
99 category: "thought_level",
100 type: "select",
101 currentValue: currentReasoning,
102 options: [
103 { value: "none", name: "None" },
104 { value: "low", name: "Low" },
105 { value: "medium", name: "Medium" },
106 { value: "high", name: "High" },
107 { value: "extra-high", name: "Extra High" },
108 ],
109 },
110 {
111 id: "context",
112 name: "Context",
113 category: "model_config",
114 type: "select",
115 currentValue: currentContext,
116 options: [
117 { value: "272k", name: "272K" },
118 { value: "1m", name: "1M" },
119 ],
120 },
121 {
122 id: "fast",
123 name: "Fast",
124 category: "model_config",
125 type: "select",
126 currentValue: String(currentFast),
127 options: [
128 { value: "false", name: "Off" },
129 { value: "true", name: "Fast" },
130 ],
131 },
132 ];
133 case "composer-2":
134 return [
135 ...baseOptions,
136 {
137 id: "fast",
138 name: "Fast",
139 category: "model_config",
140 type: "select",
141 currentValue: String(currentFast),
142 options: [
143 { value: "false", name: "Off" },
144 { value: "true", name: "Fast" },
145 ],
146 },
147 ];
148 case "claude-opus-4-6":
149 return [
150 ...baseOptions,
151 {
152 id: "reasoning",
153 name: "Reasoning",
154 category: "thought_level",
155 type: "select",
156 currentValue: currentReasoning,
157 options: [
158 { value: "low", name: "Low" },
159 { value: "medium", name: "Medium" },
160 { value: "high", name: "High" },
161 ],
162 },
163 {
164 id: "thinking",
165 name: "Thinking",
166 category: "model_config",
167 type: "boolean",
168 currentValue: true,
169 },
170 ];
171 default:
172 return baseOptions;
173 }
174 }
175​
176 return [
177 {
178 id: "model",
179 name: "Model",
180 category: "model",
181 type: "select" as const,
182 currentValue: currentModelId,
183 options: [
184 { value: "default", name: "Auto" },
185 { value: "composer-2", name: "Composer 2" },
186 { value: "composer-2[fast=true]", name: "Composer 2 Fast" },
187 { value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
188 ],
189 },
190 ];
192​
193function modelConfigOptionsFor(modelId: string): ReadonlyArray<AcpSchema.SessionConfigOption> {
194 const previousModelId = currentModelId;
195 try {
196 currentModelId = modelId;
197 return configOptions().filter(
198 (option) => option.category !== "mode" && option.category !== "model",
199 );
200 } finally {
201 currentModelId = previousModelId;
202 }
204​
205function availableModels(): ReadonlyArray<{
206 readonly value: string;
207 readonly name: string;
208 readonly configOptions: ReadonlyArray<AcpSchema.SessionConfigOption>;
209}> {
210 return [
211 { value: "default", name: "Auto" },
212 { value: "composer-2", name: "Composer 2" },
213 { value: "gpt-5.4", name: "GPT-5.4" },
214 { value: "claude-opus-4-6", name: "Opus 4.6" },
215 ].map((model) => ({
216 value: model.value,
217 name: model.name,
218 configOptions: modelConfigOptionsFor(model.value),
219 }));
221​
222const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
223 {
224 id: "ask",
225 name: "Ask",
226 description: "Request permission before making any changes",
227 },
228 {
229 id: "architect",
230 name: "Architect",
231 description: "Design and plan software systems without implementation",
232 },
233 {
234 id: "code",
235 name: "Code",
236 description: "Write and modify code with full tool access",
237 },
238];
239​
240function modeState(): AcpSchema.SessionModeState {
241 return {
242 currentModeId,
243 availableModes,
244 };
246​
247const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
248 { modelId: "grok-build", name: "Grok Build" },
249 { modelId: "grok-mock-alt", name: "Grok Mock Alt" },
250];
251​
252function modelState(): AcpSchema.SessionModelState {
253 const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
254 ? currentModelId
255 : "grok-build";
256 return {
257 currentModelId: modelId,
258 availableModels: grokAcpModels,
259 };
261​
262const program = Effect.gen(function* () {
263 const agent = yield* EffectAcpAgent.AcpAgent;
264​
265 yield* agent.handleInitialize((request) =>
266 Effect.sync(() => {
267 parameterizedModelPicker =
268 request.clientCapabilities?._meta?.parameterizedModelPicker === true;
269 return {
270 protocolVersion: 1,
271 agentCapabilities: { loadSession: true },
272 };
273 }),
274 );
275​
276 yield* agent.handleAuthenticate(() => Effect.succeed({}));
277​
278 yield* agent.handleCreateSession(() =>
279 Effect.succeed({
280 sessionId,
281 modes: modeState(),
282 models: modelState(),
283 configOptions: configOptions(),
284 }),
285 );
286​
287 yield* agent.handleLoadSession((request) =>
288 agent.client
289 .sessionUpdate({
290 sessionId: String(request.sessionId ?? sessionId),
291 update: {
292 sessionUpdate: "user_message_chunk",
293 content: { type: "text", text: "replay" },
294 },
295 })
296 .pipe(
297 Effect.as({
298 modes: modeState(),
299 models: modelState(),
300 configOptions: configOptions(),
301 }),
302 ),
303 );
304​
305 yield* agent.handleSetSessionModel((request) =>
306 Effect.gen(function* () {
307 if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
308 return yield* AcpError.AcpRequestError.invalidParams(
309 `Unknown mock model id: ${request.modelId}`,
310 {
311 method: "session/set_model",
312 params: request,
313 },
314 );
315 }
316 currentModelId = request.modelId;
317 return {};
318 }),
319 );
320​
321 yield* agent.handleSetSessionConfigOption((request) =>
322 Effect.gen(function* () {
323 if (exitOnSetConfigOption) {
324 return yield* Effect.sync(() => {
325 process.exit(7);
326 });
327 }
328 if (failSetConfigOption) {
329 return yield* AcpError.AcpRequestError.invalidParams(
330 "Mock invalid params for session/set_config_option",
331 {
332 method: "session/set_config_option",
333 params: request,
334 },
335 );
336 }
337 if (request.configId === "mode" && typeof request.value === "string") {
338 currentModeId = request.value;
339 }
340 if (request.configId === "model" && typeof request.value === "string") {
341 currentModelId = request.value;
342 }
343 if (request.configId === "reasoning" && typeof request.value === "string") {
344 currentReasoning = request.value;
345 }
346 if (request.configId === "context" && typeof request.value === "string") {
347 currentContext = request.value;
348 }
349 if (request.configId === "fast") {
350 currentFast = request.value === true || request.value === "true";
351 }
352 return {
353 configOptions: configOptions(),
354 };
355 }),
356 );
357​
358 yield* agent.handleCancel(({ sessionId }) =>
359 Effect.sync(() => {
360 cancelledSessions.add(String(sessionId ?? "mock-session-1"));
361 }),
362 );
363​
364 yield* agent.handlePrompt((request) =>
365 Effect.gen(function* () {
366 const requestedSessionId = String(request.sessionId ?? sessionId);
367​
368 if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
369 yield* Effect.sleep(`${promptDelayMs} millis`);
370 }
371​
372 if (emitInterleavedAssistantToolCalls) {
373 const toolCallId = "tool-call-1";
374​
375 yield* agent.client.sessionUpdate({
376 sessionId: requestedSessionId,
377 update: {
378 sessionUpdate: "agent_message_chunk",
379 content: { type: "text", text: "before tool" },
380 },
381 });
382​
383 yield* agent.client.sessionUpdate({
384 sessionId: requestedSessionId,
385 update: {
386 sessionUpdate: "tool_call",
387 toolCallId,
388 title: "Terminal",
389 kind: "execute",
390 status: "pending",
391 rawInput: {
392 command: ["echo", "hello"],
393 },
394 },
395 });
396​
397 yield* agent.client.sessionUpdate({
398 sessionId: requestedSessionId,
399 update: {
400 sessionUpdate: "tool_call_update",
401 toolCallId,
402 status: "completed",
403 rawOutput: {
404 exitCode: 0,
405 stdout: "hello",
406 stderr: "",
407 },
408 },
409 });
410​
411 yield* agent.client.sessionUpdate({
412 sessionId: requestedSessionId,
413 update: {
414 sessionUpdate: "agent_message_chunk",
415 content: { type: "text", text: "after tool" },
416 },
417 });
418​
419 return { stopReason: "end_turn" };
420 }
421​
422 if (emitToolCalls) {
423 const toolCallId = "tool-call-1";
424​
425 yield* agent.client.sessionUpdate({
426 sessionId: requestedSessionId,
427 update: {
428 sessionUpdate: "tool_call",
429 toolCallId,
430 title: "Terminal",
431 kind: "execute",
432 status: "pending",
433 rawInput: {
434 command: ["cat", "server/package.json"],
435 },
436 },
437 });
438​
439 yield* agent.client.sessionUpdate({
440 sessionId: requestedSessionId,
441 update: {
442 sessionUpdate: "tool_call_update",
443 toolCallId,
444 status: "in_progress",
445 },
446 });
447​
448 const permission = yield* agent.client.requestPermission({
449 sessionId: requestedSessionId,
450 toolCall: {
451 toolCallId,
452 title: "`cat server/package.json`",
453 kind: "execute",
454 status: "pending",
455 content: [
456 {
457 type: "content",
458 content: {
459 type: "text",
460 text: "Not in allowlist: cat server/package.json",
461 },
462 },
463 ],
464 },
465 options: [
466 { optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
467 {
468 optionId: permissionOptionIds.allowAlways,
469 name: "Allow always",
470 kind: "allow_always",
471 },
472 { optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
473 ],
474 });
475​
476 const cancelled =
477 cancelledSessions.delete(requestedSessionId) ||
478 permission.outcome.outcome === "cancelled";
479​
480 yield* agent.client.sessionUpdate({
481 sessionId: requestedSessionId,
482 update: {
483 sessionUpdate: "tool_call_update",
484 toolCallId,
485 title: "Terminal",
486 kind: "execute",
487 status: "completed",
488 rawOutput: {
489 exitCode: 0,
490 stdout: '{ "name": "t3" }',
491 stderr: "",
492 },
493 },
494 });
495​
496 yield* agent.client.sessionUpdate({
497 sessionId: requestedSessionId,
498 update: {
499 sessionUpdate: "agent_message_chunk",
500 content: { type: "text", text: "hello from mock" },
501 },
502 });
503​
504 return { stopReason: cancelled ? "cancelled" : "end_turn" };
505 }
506​
507 if (emitGenericToolPlaceholders) {
508 const toolCallId = "tool-call-generic-1";
509​
510 yield* agent.client.sessionUpdate({
511 sessionId: requestedSessionId,
512 update: {
513 sessionUpdate: "tool_call",
514 toolCallId,
515 title: "Read File",
516 kind: "read",
517 status: "pending",
518 rawInput: {},
519 },
520 });
521​
522 yield* agent.client.sessionUpdate({
523 sessionId: requestedSessionId,
524 update: {
525 sessionUpdate: "tool_call_update",
526 toolCallId,
527 status: "in_progress",
528 },
529 });
530​
531 yield* agent.client.sessionUpdate({
532 sessionId: requestedSessionId,
533 update: {
534 sessionUpdate: "tool_call_update",
535 toolCallId,
536 status: "completed",
537 rawOutput: {
538 content: "package.json\n",
539 },
540 },
541 });
542​
543 return { stopReason: "end_turn" };
544 }
545​
546 if (emitAskQuestion) {
547 yield* agent.client.extRequest("cursor/ask_question", {
548 toolCallId: "ask-question-tool-call-1",
549 title: "Question",
550 questions: [
551 {
552 id: "scope",
553 prompt: "Which scope?",
554 options: [
555 { id: "workspace", label: "Workspace" },
556 { id: "session", label: "Session" },
557 ],
558 },
559 ],
560 });
561​
562 return { stopReason: "end_turn" };
563 }
564​
565 if (emitXAiAskUserQuestion) {
566 const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
567 method: "x.ai/ask_user_question",
568 params: {
569 sessionId: requestedSessionId,
570 toolCallId: "ask-user-question-tool-call-1",
571 questions: [
572 {
573 question: "Which scope should Grok use?",
574 multiSelect: null,
575 options: [
576 { label: "Workspace", description: "Use the current workspace" },
577 { label: "Session", description: "Only use this session" },
578 ],
579 },
580 ],
581 mode: "default",
582 },
583 });
584 if (typeof result !== "object" || result === null || !("outcome" in result)) {
585 throw new Error("Expected _x.ai/ask_user_question response outcome.");
586 }
587 if (result.outcome === "cancelled") {
588 return { stopReason: "end_turn" };
589 }
590 if (
591 result.outcome !== "accepted" ||
592 !("answers" in result) ||
593 typeof result.answers !== "object" ||
594 result.answers === null
595 ) {
596 throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
597 }
598​
599 return { stopReason: "end_turn" };
600 }
601​
602 yield* agent.client.sessionUpdate({
603 sessionId: requestedSessionId,
604 update: {
605 sessionUpdate: "plan",
606 entries: [
607 {
608 content: "Inspect mock ACP state",
609 priority: "high",
610 status: "completed",
611 },
612 {
613 content: "Implement the requested change",
614 priority: "high",
615 status: "in_progress",
616 },
617 ],
618 },
619 });
620​
621 yield* agent.client.sessionUpdate({
622 sessionId: requestedSessionId,
623 update: {
624 sessionUpdate: "agent_message_chunk",
625 content: { type: "text", text: promptResponseText ?? "hello from mock" },
626 },
627 });
628​
629 return { stopReason: "end_turn" };
630 }),
631 );
632​
633 yield* agent.handleUnknownExtRequest((method, params) => {
634 if (method === "cursor/list_available_models") {
635 return Effect.succeed({
636 models: availableModels(),
637 });
638 }
639​
640 if (method !== "session/mode/set") {
641 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
642 }
643​
644 const nextModeId =
645 typeof params === "object" &&
646 params !== null &&
647 "modeId" in params &&
648 typeof params.modeId === "string"
649 ? params.modeId
650 : typeof params === "object" &&
651 params !== null &&
652 "mode" in params &&
653 typeof params.mode === "string"
654 ? params.mode
655 : undefined;
656 const requestedSessionId =
657 typeof params === "object" &&
658 params !== null &&
659 "sessionId" in params &&
660 typeof params.sessionId === "string"
661 ? params.sessionId
662 : sessionId;
663​
664 if (typeof nextModeId === "string" && nextModeId.trim()) {
665 currentModeId = nextModeId.trim();
666 return agent.client
667 .sessionUpdate({
668 sessionId: requestedSessionId,
669 update: {
670 sessionUpdate: "current_mode_update",
671 currentModeId,
672 },
673 })
674 .pipe(Effect.as({}));
675 }
676​
677 return Effect.succeed({});
678 });
679​
680 return yield* Effect.never;
681}).pipe(
682 Effect.provide(
683 EffectAcpAgent.layerStdio(
684 requestLogPath
685 ? {
686 logIncoming: true,
687 logger: (event) => {
688 if (event.direction !== "incoming" || event.stage !== "raw") {
689 return Effect.void;
690 }
691 if (typeof event.payload !== "string") {
692 return Effect.void;
693 }
694 const payload = event.payload;
695 return Effect.sync(() => {
696 NodeFS.appendFileSync(
697 requestLogPath,
698 payload.endsWith("\n") ? payload : `${payload}\n`,
699 "utf8",
700 );
701 });
702 },
703 }
704 : {},
705 ),
706 ),
707 Effect.scoped,
708 Effect.provide(NodeServices.layer),
709);
710​
711NodeRuntime.runMain(program);