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

acp-mock-agent.ts

590 lines16.1 KB

1#!/usr/bin/env bun
2import { appendFileSync } from "node:fs";
3​
4import * as Effect from "effect/Effect";
5​
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
8​
9import * as EffectAcpAgent from "effect-acp/agent";
10import * as AcpError from "effect-acp/errors";
11import type * as AcpSchema from "effect-acp/schema";
12​
13const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
14const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
15const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
16const emitInterleavedAssistantToolCalls =
17 process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
18const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
19const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
20const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
21const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
22const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
23const sessionId = "mock-session-1";
24​
25let currentModeId = "ask";
26let currentModelId = "default";
27let parameterizedModelPicker = false;
28let currentReasoning = "medium";
29let currentContext = "272k";
30let currentFast = false;
31const cancelledSessions = new Set<string>();
32​
33function logExit(reason: string): void {
34 if (!exitLogPath) {
35 return;
36 }
37 appendFileSync(exitLogPath, `${reason}\n`, "utf8");
39​
40process.once("SIGTERM", () => {
41 logExit("SIGTERM");
42 process.exit(0);
43});
44​
45process.once("SIGINT", () => {
46 logExit("SIGINT");
47 process.exit(0);
48});
49​
50process.once("exit", (code) => {
51 logExit(`exit:${code}`);
52});
53​
54function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
55 if (parameterizedModelPicker) {
56 const baseOptions: Array<AcpSchema.SessionConfigOption> = [
57 {
58 id: "mode",
59 name: "Mode",
60 category: "mode",
61 type: "select",
62 currentValue: currentModeId,
63 options: availableModes.map((mode) => ({
64 value: mode.id,
65 name: mode.name,
66 ...(mode.description ? { description: mode.description } : {}),
67 })),
68 },
69 {
70 id: "model",
71 name: "Model",
72 category: "model",
73 type: "select",
74 currentValue: currentModelId,
75 options: [
76 { value: "default", name: "Auto" },
77 { value: "composer-2", name: "Composer 2" },
78 { value: "gpt-5.4", name: "GPT-5.4" },
79 { value: "claude-opus-4-6", name: "Opus 4.6" },
80 ],
81 },
82 ];
83​
84 switch (currentModelId) {
85 case "gpt-5.4":
86 return [
87 ...baseOptions,
88 {
89 id: "reasoning",
90 name: "Reasoning",
91 category: "thought_level",
92 type: "select",
93 currentValue: currentReasoning,
94 options: [
95 { value: "none", name: "None" },
96 { value: "low", name: "Low" },
97 { value: "medium", name: "Medium" },
98 { value: "high", name: "High" },
99 { value: "extra-high", name: "Extra High" },
100 ],
101 },
102 {
103 id: "context",
104 name: "Context",
105 category: "model_config",
106 type: "select",
107 currentValue: currentContext,
108 options: [
109 { value: "272k", name: "272K" },
110 { value: "1m", name: "1M" },
111 ],
112 },
113 {
114 id: "fast",
115 name: "Fast",
116 category: "model_config",
117 type: "select",
118 currentValue: String(currentFast),
119 options: [
120 { value: "false", name: "Off" },
121 { value: "true", name: "Fast" },
122 ],
123 },
124 ];
125 case "composer-2":
126 return [
127 ...baseOptions,
128 {
129 id: "fast",
130 name: "Fast",
131 category: "model_config",
132 type: "select",
133 currentValue: String(currentFast),
134 options: [
135 { value: "false", name: "Off" },
136 { value: "true", name: "Fast" },
137 ],
138 },
139 ];
140 case "claude-opus-4-6":
141 return [
142 ...baseOptions,
143 {
144 id: "reasoning",
145 name: "Reasoning",
146 category: "thought_level",
147 type: "select",
148 currentValue: currentReasoning,
149 options: [
150 { value: "low", name: "Low" },
151 { value: "medium", name: "Medium" },
152 { value: "high", name: "High" },
153 ],
154 },
155 {
156 id: "thinking",
157 name: "Thinking",
158 category: "model_config",
159 type: "boolean",
160 currentValue: true,
161 },
162 ];
163 default:
164 return baseOptions;
165 }
166 }
167​
168 return [
169 {
170 id: "model",
171 name: "Model",
172 category: "model",
173 type: "select" as const,
174 currentValue: currentModelId,
175 options: [
176 { value: "default", name: "Auto" },
177 { value: "composer-2", name: "Composer 2" },
178 { value: "composer-2[fast=true]", name: "Composer 2 Fast" },
179 { value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
180 ],
181 },
182 ];
184​
185const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
186 {
187 id: "ask",
188 name: "Ask",
189 description: "Request permission before making any changes",
190 },
191 {
192 id: "architect",
193 name: "Architect",
194 description: "Design and plan software systems without implementation",
195 },
196 {
197 id: "code",
198 name: "Code",
199 description: "Write and modify code with full tool access",
200 },
201];
202​
203function modeState(): AcpSchema.SessionModeState {
204 return {
205 currentModeId,
206 availableModes,
207 };
209​
210const program = Effect.gen(function* () {
211 const agent = yield* EffectAcpAgent.AcpAgent;
212​
213 yield* agent.handleInitialize((request) =>
214 Effect.sync(() => {
215 parameterizedModelPicker =
216 request.clientCapabilities?._meta?.parameterizedModelPicker === true;
217 return {
218 protocolVersion: 1,
219 agentCapabilities: { loadSession: true },
220 };
221 }),
222 );
223​
224 yield* agent.handleAuthenticate(() => Effect.succeed({}));
225​
226 yield* agent.handleCreateSession(() =>
227 Effect.succeed({
228 sessionId,
229 modes: modeState(),
230 configOptions: configOptions(),
231 }),
232 );
233​
234 yield* agent.handleLoadSession((request) =>
235 agent.client
236 .sessionUpdate({
237 sessionId: String(request.sessionId ?? sessionId),
238 update: {
239 sessionUpdate: "user_message_chunk",
240 content: { type: "text", text: "replay" },
241 },
242 })
243 .pipe(
244 Effect.as({
245 modes: modeState(),
246 configOptions: configOptions(),
247 }),
248 ),
249 );
250​
251 yield* agent.handleSetSessionConfigOption((request) =>
252 Effect.gen(function* () {
253 if (exitOnSetConfigOption) {
254 return yield* Effect.sync(() => {
255 process.exit(7);
256 });
257 }
258 if (failSetConfigOption) {
259 return yield* AcpError.AcpRequestError.invalidParams(
260 "Mock invalid params for session/set_config_option",
261 {
262 method: "session/set_config_option",
263 params: request,
264 },
265 );
266 }
267 if (request.configId === "mode" && typeof request.value === "string") {
268 currentModeId = request.value;
269 }
270 if (request.configId === "model" && typeof request.value === "string") {
271 currentModelId = request.value;
272 }
273 if (request.configId === "reasoning" && typeof request.value === "string") {
274 currentReasoning = request.value;
275 }
276 if (request.configId === "context" && typeof request.value === "string") {
277 currentContext = request.value;
278 }
279 if (request.configId === "fast") {
280 currentFast = request.value === true || request.value === "true";
281 }
282 return {
283 configOptions: configOptions(),
284 };
285 }),
286 );
287​
288 yield* agent.handleCancel(({ sessionId }) =>
289 Effect.sync(() => {
290 cancelledSessions.add(String(sessionId ?? "mock-session-1"));
291 }),
292 );
293​
294 yield* agent.handlePrompt((request) =>
295 Effect.gen(function* () {
296 const requestedSessionId = String(request.sessionId ?? sessionId);
297​
298 if (emitInterleavedAssistantToolCalls) {
299 const toolCallId = "tool-call-1";
300​
301 yield* agent.client.sessionUpdate({
302 sessionId: requestedSessionId,
303 update: {
304 sessionUpdate: "agent_message_chunk",
305 content: { type: "text", text: "before tool" },
306 },
307 });
308​
309 yield* agent.client.sessionUpdate({
310 sessionId: requestedSessionId,
311 update: {
312 sessionUpdate: "tool_call",
313 toolCallId,
314 title: "Terminal",
315 kind: "execute",
316 status: "pending",
317 rawInput: {
318 command: ["echo", "hello"],
319 },
320 },
321 });
322​
323 yield* agent.client.sessionUpdate({
324 sessionId: requestedSessionId,
325 update: {
326 sessionUpdate: "tool_call_update",
327 toolCallId,
328 status: "completed",
329 rawOutput: {
330 exitCode: 0,
331 stdout: "hello",
332 stderr: "",
333 },
334 },
335 });
336​
337 yield* agent.client.sessionUpdate({
338 sessionId: requestedSessionId,
339 update: {
340 sessionUpdate: "agent_message_chunk",
341 content: { type: "text", text: "after tool" },
342 },
343 });
344​
345 return { stopReason: "end_turn" };
346 }
347​
348 if (emitToolCalls) {
349 const toolCallId = "tool-call-1";
350​
351 yield* agent.client.sessionUpdate({
352 sessionId: requestedSessionId,
353 update: {
354 sessionUpdate: "tool_call",
355 toolCallId,
356 title: "Terminal",
357 kind: "execute",
358 status: "pending",
359 rawInput: {
360 command: ["cat", "server/package.json"],
361 },
362 },
363 });
364​
365 yield* agent.client.sessionUpdate({
366 sessionId: requestedSessionId,
367 update: {
368 sessionUpdate: "tool_call_update",
369 toolCallId,
370 status: "in_progress",
371 },
372 });
373​
374 const permission = yield* agent.client.requestPermission({
375 sessionId: requestedSessionId,
376 toolCall: {
377 toolCallId,
378 title: "`cat server/package.json`",
379 kind: "execute",
380 status: "pending",
381 content: [
382 {
383 type: "content",
384 content: {
385 type: "text",
386 text: "Not in allowlist: cat server/package.json",
387 },
388 },
389 ],
390 },
391 options: [
392 { optionId: "allow-once", name: "Allow once", kind: "allow_once" },
393 { optionId: "allow-always", name: "Allow always", kind: "allow_always" },
394 { optionId: "reject-once", name: "Reject", kind: "reject_once" },
395 ],
396 });
397​
398 const cancelled =
399 cancelledSessions.delete(requestedSessionId) ||
400 permission.outcome.outcome === "cancelled";
401​
402 yield* agent.client.sessionUpdate({
403 sessionId: requestedSessionId,
404 update: {
405 sessionUpdate: "tool_call_update",
406 toolCallId,
407 title: "Terminal",
408 kind: "execute",
409 status: "completed",
410 rawOutput: {
411 exitCode: 0,
412 stdout: '{ "name": "t3" }',
413 stderr: "",
414 },
415 },
416 });
417​
418 yield* agent.client.sessionUpdate({
419 sessionId: requestedSessionId,
420 update: {
421 sessionUpdate: "agent_message_chunk",
422 content: { type: "text", text: "hello from mock" },
423 },
424 });
425​
426 return { stopReason: cancelled ? "cancelled" : "end_turn" };
427 }
428​
429 if (emitGenericToolPlaceholders) {
430 const toolCallId = "tool-call-generic-1";
431​
432 yield* agent.client.sessionUpdate({
433 sessionId: requestedSessionId,
434 update: {
435 sessionUpdate: "tool_call",
436 toolCallId,
437 title: "Read File",
438 kind: "read",
439 status: "pending",
440 rawInput: {},
441 },
442 });
443​
444 yield* agent.client.sessionUpdate({
445 sessionId: requestedSessionId,
446 update: {
447 sessionUpdate: "tool_call_update",
448 toolCallId,
449 status: "in_progress",
450 },
451 });
452​
453 yield* agent.client.sessionUpdate({
454 sessionId: requestedSessionId,
455 update: {
456 sessionUpdate: "tool_call_update",
457 toolCallId,
458 status: "completed",
459 rawOutput: {
460 content: "package.json\n",
461 },
462 },
463 });
464​
465 return { stopReason: "end_turn" };
466 }
467​
468 if (emitAskQuestion) {
469 yield* agent.client.extRequest("cursor/ask_question", {
470 toolCallId: "ask-question-tool-call-1",
471 title: "Question",
472 questions: [
473 {
474 id: "scope",
475 prompt: "Which scope?",
476 options: [
477 { id: "workspace", label: "Workspace" },
478 { id: "session", label: "Session" },
479 ],
480 },
481 ],
482 });
483​
484 return { stopReason: "end_turn" };
485 }
486​
487 yield* agent.client.sessionUpdate({
488 sessionId: requestedSessionId,
489 update: {
490 sessionUpdate: "plan",
491 entries: [
492 {
493 content: "Inspect mock ACP state",
494 priority: "high",
495 status: "completed",
496 },
497 {
498 content: "Implement the requested change",
499 priority: "high",
500 status: "in_progress",
501 },
502 ],
503 },
504 });
505​
506 yield* agent.client.sessionUpdate({
507 sessionId: requestedSessionId,
508 update: {
509 sessionUpdate: "agent_message_chunk",
510 content: { type: "text", text: promptResponseText ?? "hello from mock" },
511 },
512 });
513​
514 return { stopReason: "end_turn" };
515 }),
516 );
517​
518 yield* agent.handleUnknownExtRequest((method, params) => {
519 if (method !== "session/mode/set") {
520 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
521 }
522​
523 const nextModeId =
524 typeof params === "object" &&
525 params !== null &&
526 "modeId" in params &&
527 typeof params.modeId === "string"
528 ? params.modeId
529 : typeof params === "object" &&
530 params !== null &&
531 "mode" in params &&
532 typeof params.mode === "string"
533 ? params.mode
534 : undefined;
535 const requestedSessionId =
536 typeof params === "object" &&
537 params !== null &&
538 "sessionId" in params &&
539 typeof params.sessionId === "string"
540 ? params.sessionId
541 : sessionId;
542​
543 if (typeof nextModeId === "string" && nextModeId.trim()) {
544 currentModeId = nextModeId.trim();
545 return agent.client
546 .sessionUpdate({
547 sessionId: requestedSessionId,
548 update: {
549 sessionUpdate: "current_mode_update",
550 currentModeId,
551 },
552 })
553 .pipe(Effect.as({}));
554 }
555​
556 return Effect.succeed({});
557 });
558​
559 return yield* Effect.never;
560}).pipe(
561 Effect.provide(
562 EffectAcpAgent.layerStdio(
563 requestLogPath
564 ? {
565 logIncoming: true,
566 logger: (event) => {
567 if (event.direction !== "incoming" || event.stage !== "raw") {
568 return Effect.void;
569 }
570 if (typeof event.payload !== "string") {
571 return Effect.void;
572 }
573 const payload = event.payload;
574 return Effect.sync(() => {
575 appendFileSync(
576 requestLogPath,
577 payload.endsWith("\n") ? payload : `${payload}\n`,
578 "utf8",
579 );
580 });
581 },
582 }
583 : {},
584 ),
585 ),
586 Effect.scoped,
587 Effect.provide(NodeServices.layer),
588);
589​
590NodeRuntime.runMain(program);