The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,233 lines 74.8 KB
Raw
1 #!/usr/bin/env node
2 // @effect-diagnostics nodeBuiltinImport:off
3 import * as NodeFS from "node:fs";
4
5 import * as Effect from "effect/Effect";
6 import * as Schema from "effect/Schema";
7 import * as Deferred from "effect/Deferred";
8
9 import * as NodeServices from "@effect/platform-node/NodeServices";
10 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
11
12 import * as EffectAcpAgent from "effect-acp/agent";
13 import * as AcpError from "effect-acp/errors";
14 import * as AcpSchema from "effect-acp/schema";
15 import type * as AcpCompat from "effect-acp/compat";
16
17 import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
18
19 const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
20 const antigravityProfile = process.env.T3_ACP_ANTIGRAVITY === "1";
21 // GitHub Copilot CLI advertises URL-shaped session mode ids.
22 const copilotModesProfile = process.env.T3_ACP_COPILOT_MODES === "1";
23 const copilotModeId = (name: string) =>
24 `https://agentclientprotocol.com/protocol/session-modes#${name}`;
25 const modeOptionCategory = process.env.T3_ACP_MODE_OPTION_CATEGORY ?? "mode";
26 // Comma-separated command names the mock advertises, so `/compact` support is testable.
27 const advertisedCommandNames = (process.env.T3_ACP_AVAILABLE_COMMANDS ?? "")
28 .split(",")
29 .map((name) => name.trim())
30 .filter((name) => name.length > 0);
31 const loadedCommandNames = process.env.T3_ACP_LOADED_COMMANDS?.split(",").filter(Boolean);
32 // omp advertises a loaded session's commands only after it answers session/load.
33 const loadedCommandsDelayMs = Number(process.env.T3_ACP_LOADED_COMMANDS_DELAY_MS ?? "");
34 const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
35 const emitInterleavedAssistantToolCalls =
36 process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
37 const emitV2Fidelity = process.env.T3_ACP_EMIT_V2_FIDELITY === "1";
38 const emitNotice = process.env.T3_ACP_EMIT_NOTICE === "1";
39 const hangCloseSession = process.env.T3_ACP_HANG_CLOSE_SESSION === "1";
40 const vibeRetryOutcome = process.env.T3_ACP_VIBE_RETRY_OUTCOME;
41 const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
42 const emitInTurnTaskOutputThenLateDuplicate =
43 process.env.T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE === "1";
44 const emitBackgroundToolDuringAnswer =
45 process.env.T3_ACP_EMIT_BACKGROUND_TOOL_DURING_ANSWER === "1";
46 const emitMcpToolApprovalElicitation =
47 process.env.T3_ACP_EMIT_MCP_TOOL_APPROVAL_ELICITATION === "1";
48 const emitElicitation = process.env.T3_ACP_EMIT_ELICITATION === "1";
49 const elicitationSchema = process.env.T3_ACP_ELICITATION_SCHEMA;
50 const decodeElicitationSchema = Schema.decodeUnknownSync(
51 Schema.fromJsonString(AcpSchema.ElicitationSchema),
52 );
53 const elicitationResponseLogPath = process.env.T3_ACP_ELICITATION_RESPONSE_LOG_PATH;
54 const grokKillTaskShape = process.env.T3_ACP_GROK_KILL_TASK_SHAPE;
55 const emitGrokBackgroundTaskPoll = process.env.T3_ACP_GROK_BACKGROUND_TASK_COMPLETION === "poll";
56 const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
57 const omitInitializeModelState = process.env.T3_ACP_OMIT_INITIALIZE_MODEL_STATE === "1";
58 const completeFirstPromptOnCancel = process.env.T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL === "1";
59 const floodStderr = process.env.T3_ACP_FLOOD_STDERR === "1";
60 const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
61 const agentVersion = process.env.T3_ACP_AGENT_VERSION ?? "0.0.0";
62 const geminiApiKey = process.env.GEMINI_API_KEY;
63 const idleError = process.env.T3_ACP_IDLE_ERROR;
64 const emitTrackedToolCallKindThenHang = process.env.T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG;
65 const clientFsProbePath = process.env.T3_ACP_CLIENT_FS_PROBE_PATH;
66 const clientFsProbeLogPath = process.env.T3_ACP_CLIENT_FS_PROBE_LOG_PATH;
67 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
68 const emitEmptySuccessfulBash = process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH === "1";
69 const emitEmptySuccessfulBashThenHang =
70 process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG === "1";
71 const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
72 const failLoadSessionAfterConfigReplay =
73 process.env.T3_ACP_FAIL_LOAD_SESSION_AFTER_CONFIG_REPLAY === "1";
74 const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
75 const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
76 const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
77 const modeNotifiedBeforeDelayedLoadReply = process.env.T3_ACP_NOTIFY_MODE_BEFORE_LOAD_REPLY;
78 const holdSetConfigOptionUntilLoadReply =
79 process.env.T3_ACP_HOLD_SET_CONFIG_OPTION_UNTIL_LOAD_REPLY === "1";
80 const loadReplyDelayMs = Number(process.env.T3_ACP_LOAD_REPLY_DELAY_MS ?? "0");
81 const loadNeverReplies = process.env.T3_ACP_LOAD_NEVER_REPLIES === "1";
82 const rejectPromptUntilLoaded = process.env.T3_ACP_REJECT_PROMPT_UNTIL_LOADED === "1";
83 const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
84 // JSON for the `data` of an "Internal error" response to `session/new`, as
85 // Antigravity sends when its runtime cannot reach its local harness.
86 const newSessionErrorData =
87 process.env.T3_ACP_NEW_SESSION_ERROR_DATA === undefined
88 ? undefined
89 : Schema.decodeSync(Schema.fromJsonString(Schema.Unknown))(
90 process.env.T3_ACP_NEW_SESSION_ERROR_DATA,
91 );
92 const failPromptOrdinal = Number(process.env.T3_ACP_FAIL_PROMPT_ORDINAL);
93 const compactionPromptOrdinals = new Set(
94 (process.env.T3_ACP_COMPACTION_PROMPT_ORDINALS ?? "").split(",").map(Number),
95 );
96 // These prompts end while their compaction is still in progress.
97 const openCompactionPromptOrdinals = new Set(
98 (process.env.T3_ACP_OPEN_COMPACTION_PROMPT_ORDINALS ?? "").split(",").map(Number),
99 );
100 const failSetModeConfigOption = process.env.T3_ACP_FAIL_SET_MODE_CONFIG_OPTION === "1";
101 const emitEmptyDefaultAgentOption = process.env.T3_ACP_EMIT_EMPTY_DEFAULT_AGENT_OPTION === "1";
102 const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
103 const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
104 const terminalOutputBytes = Number(process.env.T3_ACP_EMIT_TERMINAL_OUTPUT_BYTES ?? "0");
105 const supportsSessionLifecycle = process.env.T3_ACP_SESSION_LIFECYCLE === "1";
106 const supportsAcpMcp = process.env.T3_ACP_MCP_ACP === "1";
107 const supportsHttpMcp = process.env.T3_ACP_MCP_HTTP === "1";
108 const supportsV2Management = process.env.T3_ACP_V2_MANAGEMENT === "1";
109 const failDeleteSession = process.env.T3_ACP_FAIL_DELETE_SESSION === "1";
110 const advertisedAuthMethodId = process.env.T3_ACP_AUTH_METHOD_ID?.trim();
111 const initializeAuthMethodId =
112 advertisedAuthMethodId ?? (supportsSessionLifecycle ? "test" : undefined);
113 const requiresAuthentication = process.env.T3_ACP_REQUIRE_AUTH === "1";
114 const permissionOptionIds = {
115 allowOnce: "allow-once",
116 allowAlways: "allow-always",
117 rejectOnce: "reject-once",
118 };
119 const sessionId = "mock-session-1";
120
121 let currentModeId = antigravityProfile
122 ? (process.env.T3_ACP_INITIAL_MODE ?? "default")
123 : copilotModesProfile
124 ? copilotModeId("agent")
125 : "ask";
126 let currentModelId = antigravityProfile ? "gemini-test-low" : "default";
127 let parameterizedModelPicker = false;
128 let currentReasoning = "medium";
129 let currentContext = "272k";
130 let currentFast = false;
131 let currentAgent = "";
132 let authenticated = !requiresAuthentication;
133 let promptCount = 0;
134 const cancelledSessions = new Set<string>();
135 const sessionsLoading = new Set<string>();
136 let configuredProvider: AcpSchema.ProviderCurrentConfig | null = null;
137
138 function promptIdFromRequestMeta(
139 request: Pick<AcpSchema.PromptRequest, "_meta">,
140 ): string | undefined {
141 const meta = request._meta;
142 if (meta === null || typeof meta !== "object") {
143 return undefined;
144 }
145 const promptId = meta.promptId ?? meta.requestId;
146 return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
147 }
148
149 function writeJsonRpcNotification(method: string, params: unknown): void {
150 process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
151 }
152
153 process.once("SIGTERM", () => {
154 process.exit(0);
155 });
156
157 process.once("SIGINT", () => {
158 process.exit(0);
159 });
160
161 function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
162 if (antigravityProfile) {
163 return [
164 {
165 configId: "model",
166 name: "Model",
167 category: "model",
168 type: "select",
169 currentValue: currentModelId,
170 options: antigravityModels.map((model) => ({ value: model.modelId, name: model.name })),
171 },
172 {
173 configId: "mode",
174 name: "Mode",
175 category: "mode",
176 type: "select",
177 currentValue: currentModeId,
178 options: availableModes.map((mode) => ({ value: mode.id, name: mode.name })),
179 },
180 ];
181 }
182 if (parameterizedModelPicker) {
183 const baseOptions: Array<AcpSchema.SessionConfigOption> = [
184 {
185 configId: "mode",
186 name: "Mode",
187 category: "mode",
188 type: "select",
189 currentValue: currentModeId,
190 options: availableModes.map((mode) => ({
191 value: mode.id,
192 name: mode.name,
193 ...(mode.description ? { description: mode.description } : {}),
194 })),
195 },
196 {
197 configId: "model",
198 name: "Model",
199 category: "model",
200 type: "select",
201 currentValue: currentModelId,
202 options: [
203 { value: "default", name: "Auto" },
204 { value: "composer-2", name: "Composer 2" },
205 { value: "gpt-5.4", name: "GPT-5.4" },
206 { value: "claude-opus-4-6", name: "Opus 4.6" },
207 ],
208 },
209 ];
210
211 switch (currentModelId) {
212 case "gpt-5.4":
213 return [
214 ...baseOptions,
215 {
216 configId: "reasoning",
217 name: "Reasoning",
218 category: "thought_level",
219 type: "select",
220 currentValue: currentReasoning,
221 options: [
222 { value: "none", name: "None" },
223 { value: "low", name: "Low" },
224 { value: "medium", name: "Medium" },
225 { value: "high", name: "High" },
226 { value: "extra-high", name: "Extra High" },
227 ],
228 },
229 {
230 configId: "context",
231 name: "Context",
232 category: "model_config",
233 type: "select",
234 currentValue: currentContext,
235 options: [
236 { value: "272k", name: "272K" },
237 { value: "1m", name: "1M" },
238 ],
239 },
240 {
241 configId: "fast",
242 name: "Fast",
243 category: "model_config",
244 type: "select",
245 currentValue: String(currentFast),
246 options: [
247 { value: "false", name: "Off" },
248 { value: "true", name: "Fast" },
249 ],
250 },
251 ];
252 case "composer-2":
253 return [
254 ...baseOptions,
255 {
256 configId: "fast",
257 name: "Fast",
258 category: "model_config",
259 type: "select",
260 currentValue: String(currentFast),
261 options: [
262 { value: "false", name: "Off" },
263 { value: "true", name: "Fast" },
264 ],
265 },
266 ];
267 case "claude-opus-4-6":
268 return [
269 ...baseOptions,
270 {
271 configId: "reasoning",
272 name: "Reasoning",
273 category: "thought_level",
274 type: "select",
275 currentValue: currentReasoning,
276 options: [
277 { value: "low", name: "Low" },
278 { value: "medium", name: "Medium" },
279 { value: "high", name: "High" },
280 ],
281 },
282 {
283 configId: "thinking",
284 name: "Thinking",
285 category: "model_config",
286 type: "boolean",
287 currentValue: true,
288 },
289 ];
290 default:
291 return baseOptions;
292 }
293 }
294
295 return [
296 // Mirrors GitHub Copilot, whose default agent is the empty-valued choice.
297 ...(emitEmptyDefaultAgentOption
298 ? [
299 {
300 configId: "agent",
301 name: "Agent",
302 category: "_agent",
303 type: "select" as const,
304 currentValue: currentAgent,
305 options: [
306 { value: "", name: "Copilot" },
307 { value: "example", name: "example" },
308 ],
309 },
310 ]
311 : []),
312 {
313 configId: "mode",
314 name: "Mode",
315 category: modeOptionCategory,
316 type: "select" as const,
317 currentValue: currentModeId,
318 options: availableModes.map((mode) => ({
319 value: mode.id,
320 name: mode.name,
321 ...(mode.description ? { description: mode.description } : {}),
322 })),
323 },
324 {
325 configId: "model",
326 name: "Model",
327 category: "model",
328 type: "select" as const,
329 currentValue: currentModelId,
330 options: [
331 { value: "default", name: "Auto" },
332 { value: "composer-2", name: "Composer 2" },
333 { value: "composer-2[fast=true]", name: "Composer 2 Fast" },
334 { value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
335 ],
336 },
337 ];
338 }
339
340 function modelConfigOptionsFor(modelId: string): ReadonlyArray<AcpSchema.SessionConfigOption> {
341 const previousModelId = currentModelId;
342 try {
343 currentModelId = modelId;
344 return configOptions().filter(
345 (option) => option.category !== "mode" && option.category !== "model",
346 );
347 } finally {
348 currentModelId = previousModelId;
349 }
350 }
351
352 function availableModels(): ReadonlyArray<{
353 readonly value: string;
354 readonly name: string;
355 readonly configOptions: ReadonlyArray<AcpSchema.SessionConfigOption>;
356 }> {
357 return [
358 { value: "default", name: "Auto" },
359 { value: "composer-2", name: "Composer 2" },
360 { value: "gpt-5.4", name: "GPT-5.4" },
361 { value: "claude-opus-4-6", name: "Opus 4.6" },
362 ].map((model) => ({
363 value: model.value,
364 name: model.name,
365 configOptions: modelConfigOptionsFor(model.value),
366 }));
367 }
368
369 const antigravityModels = [
370 { modelId: "gemini-test-low", name: "Gemini Test Low" },
371 { modelId: "gemini-test-high", name: "Gemini Test High" },
372 ] satisfies ReadonlyArray<AcpCompat.ModelInfo>;
373
374 const availableModes: ReadonlyArray<AcpCompat.SessionMode> = antigravityProfile
375 ? [
376 { id: "default", name: "Default" },
377 { id: "auto_edit", name: "Auto edit" },
378 { id: "yolo", name: "YOLO" },
379 ]
380 : copilotModesProfile
381 ? [
382 { id: copilotModeId("agent"), name: "Agent" },
383 { id: copilotModeId("plan"), name: "Plan" },
384 { id: copilotModeId("autopilot"), name: "Autopilot" },
385 ]
386 : [
387 {
388 id: "ask",
389 name: "Ask",
390 description: "Request permission before making any changes",
391 },
392 {
393 id: "architect",
394 name: "Architect",
395 description: "Design and plan software systems without implementation",
396 },
397 {
398 id: "code",
399 name: "Code",
400 description: "Write and modify code with full tool access",
401 },
402 ];
403
404 function modeState(): AcpCompat.SessionModeState {
405 return {
406 currentModeId,
407 availableModes,
408 };
409 }
410
411 // Grok ACP advertises versioned model ids, never the CLI product name.
412 const grokAcpModels: ReadonlyArray<AcpCompat.ModelInfo> = [
413 {
414 modelId: "grok-4.6",
415 name: "Grok 4.6",
416 _meta: {
417 totalContextTokens: 500_000,
418 contextWindows: [256_000, 500_000],
419 supportsReasoningEffort: true,
420 reasoningEffort: "high",
421 reasoningEfforts: [
422 { id: "xhigh", value: "xhigh", label: "Extra High Effort", default: false },
423 { id: "high", value: "high", label: "High Effort", default: true },
424 { id: "low", value: "low", label: "Low Effort", default: false },
425 ],
426 },
427 },
428 { modelId: "grok-mock-alt", name: "Grok Mock Alt" },
429 ];
430
431 function modelState(): AcpCompat.SessionModelState {
432 if (antigravityProfile) {
433 return { currentModelId, availableModels: antigravityModels };
434 }
435 const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
436 ? currentModelId
437 : "grok-4.6";
438 return {
439 currentModelId: modelId,
440 availableModels: grokAcpModels,
441 };
442 }
443
444 function emitGrokKillTaskScenario(
445 sessionId: string,
446 promptId: string | undefined,
447 shape: string,
448 ): void {
449 const taskId = "call-fb9d0000-0000-0000-0000-000000000026-29";
450 const outcome =
451 shape === "already_exited" || shape === "known_failure" ? "already_exited" : "killed";
452 writeJsonRpcNotification("session/update", {
453 sessionId,
454 update: {
455 sessionUpdate: "tool_call_update",
456 toolCallId: "kill-target-command",
457 title: "run_terminal_command",
458 kind: "execute",
459 status: "in_progress",
460 rawInput: { command: "sleep 40" },
461 },
462 });
463 writeJsonRpcNotification("session/update", {
464 sessionId,
465 update: {
466 sessionUpdate: "tool_call_update",
467 toolCallId: "kill-target-command",
468 status: "completed",
469 rawOutput: {
470 type: "BackgroundTaskStarted",
471 task_id: taskId,
472 task_type: "bash",
473 command: "sleep 40",
474 },
475 },
476 });
477 if (shape === "known_failure") {
478 writeJsonRpcNotification("_x.ai/task_completed", {
479 sessionId,
480 update: {
481 sessionUpdate: "task_completed",
482 task_snapshot: { task_id: taskId, kind: "bash", exit_code: 7, output: "known failure\n" },
483 },
484 });
485 }
486 writeJsonRpcNotification("session/update", {
487 sessionId,
488 update: {
489 sessionUpdate: "tool_call_update",
490 toolCallId: "kill-command",
491 title: `kill ${taskId} (${outcome})`,
492 kind: "other",
493 status: "completed",
494 rawInput: {
495 task_id: taskId,
496 ...(shape === "output_only" ? {} : { variant: "KillTask" }),
497 },
498 ...(shape === "variant_only" ? {} : { rawOutput: { type: "KillTask", outcome } }),
499 },
500 });
501 writeJsonRpcNotification("_x.ai/session/prompt_complete", {
502 sessionId,
503 promptId,
504 stopReason: "end_turn",
505 agentResult: null,
506 });
507 }
508
509 const program = Effect.gen(function* () {
510 const agent = yield* EffectAcpAgent.AcpAgent;
511 const nativeCancelRequested = yield* Deferred.make<void>();
512 const nativeCancelRelease = yield* Deferred.make<void>();
513 const delayedLoadReplied = yield* Deferred.make<void>();
514 const publishAntigravityCommands = (targetSessionId: string) =>
515 agent.client.sessionUpdate({
516 sessionId: targetSessionId,
517 update: {
518 sessionUpdate: "available_commands_update",
519 availableCommands: [
520 { name: "plan", description: "Plan a task", input: { hint: "task" } },
521 { name: "logout", description: "Sign out" },
522 ],
523 },
524 });
525
526 const finishPrompt = (
527 targetSessionId: string,
528 stopReason: AcpSchema.StopReason,
529 _meta?: NonNullable<AcpSchema.PromptResponse["_meta"]>,
530 ) =>
531 agent.client
532 .sessionUpdate({
533 sessionId: targetSessionId,
534 update: {
535 sessionUpdate: "state_update",
536 state: "idle",
537 stopReason,
538 ...(_meta === undefined ? {} : { _meta }),
539 },
540 })
541 .pipe(Effect.as(_meta === undefined ? {} : { _meta }));
542
543 yield* agent.handleInitialize((request) =>
544 Effect.gen(function* () {
545 if (floodStderr) {
546 yield* Effect.promise(
547 () =>
548 new Promise<void>((resolve) => {
549 process.stderr.write("stderr".repeat(350_000), () => resolve());
550 }),
551 );
552 }
553 parameterizedModelPicker = request.capabilities?._meta?.parameterizedModelPicker === true;
554 return {
555 protocolVersion: 2,
556 info: { name: "t3-acp-mock-agent", version: agentVersion },
557 ...(omitInitializeModelState ? {} : { _meta: { modelState: modelState() } }),
558 capabilities: {
559 session: {
560 ...(supportsSessionLifecycle ? { fork: {}, additionalDirectories: {} } : {}),
561 ...(supportsV2Management ? { delete: {} } : {}),
562 ...(supportsAcpMcp || supportsHttpMcp
563 ? {
564 mcp: {
565 ...(supportsAcpMcp ? { acp: {} } : {}),
566 ...(supportsHttpMcp ? { http: {} } : {}),
567 },
568 }
569 : {}),
570 },
571 ...(supportsV2Management ? { providers: {} } : {}),
572 },
573 ...(initializeAuthMethodId
574 ? {
575 authMethods: [
576 {
577 type: "agent" as const,
578 methodId: initializeAuthMethodId,
579 name: "Mock agent authentication",
580 },
581 ],
582 }
583 : {}),
584 };
585 }),
586 );
587
588 // Antigravity requires GEMINI_API_KEY for API key authentication.
589 yield* agent.handleAuthenticate((request) =>
590 Effect.gen(function* () {
591 if (antigravityProfile) {
592 if (
593 request.methodId !== "oauth-personal" &&
594 !(request.methodId === "gemini-api-key" && geminiApiKey)
595 ) {
596 return yield* AcpError.AcpRequestError.invalidParams(
597 `Mock Antigravity rejected auth method ${request.methodId}.`,
598 );
599 }
600 } else if (advertisedAuthMethodId && request.methodId !== advertisedAuthMethodId) {
601 return yield* AcpError.AcpRequestError.invalidParams(
602 `Unknown mock authentication method: ${request.methodId}`,
603 );
604 }
605 authenticated = true;
606 return {};
607 }),
608 );
609 if (antigravityProfile) {
610 yield* agent.handleLogout(() => Effect.succeed({}));
611 }
612
613 yield* agent.handleLogout(() =>
614 Effect.sync(() => {
615 authenticated = false;
616 return {};
617 }),
618 );
619
620 const requireAuthentication = Effect.fn("acpMockAgent.requireAuthentication")(function* () {
621 if (!authenticated) {
622 return yield* AcpError.AcpRequestError.authRequired();
623 }
624 });
625
626 yield* agent.handleCreateSession(() =>
627 Effect.gen(function* () {
628 yield* requireAuthentication();
629 if (newSessionErrorData !== undefined) {
630 return yield* AcpError.AcpRequestError.internalError("Internal error", newSessionErrorData);
631 }
632 if (antigravityProfile) {
633 yield* publishAntigravityCommands(sessionId);
634 }
635 if (advertisedCommandNames.length > 0) {
636 yield* agent.client.sessionUpdate({
637 sessionId,
638 update: {
639 sessionUpdate: "available_commands_update",
640 availableCommands: advertisedCommandNames.map((name) => ({
641 name,
642 description: `${name} command`,
643 })),
644 },
645 });
646 }
647 return {
648 sessionId,
649 configOptions: configOptions(),
650 };
651 }),
652 );
653
654 yield* agent.handleResumeSession((request) =>
655 Effect.gen(function* () {
656 yield* requireAuthentication();
657 yield* agent.client.sessionUpdate({
658 sessionId: request.sessionId,
659 update: {
660 sessionUpdate: "user_message_chunk",
661 content: { type: "text", text: "native-resume-started" },
662 },
663 });
664 if (antigravityProfile) {
665 yield* publishAntigravityCommands(request.sessionId);
666 }
667 return {
668 modes: modeState(),
669 models: modelState(),
670 configOptions: configOptions(),
671 _meta: { nativeResume: true },
672 };
673 }),
674 );
675
676 const emitLoadReplayNotifications = (requestedSessionId: string) => {
677 writeJsonRpcNotification("session/update", {
678 _meta: { isReplay: true },
679 sessionId: requestedSessionId,
680 update: {
681 sessionUpdate: "tool_call_update",
682 toolCallId: "replay-tool-1",
683 title: "Replay tool",
684 kind: "search",
685 status: "completed",
686 },
687 });
688 writeJsonRpcNotification("session/update", {
689 _meta: { isReplay: true },
690 sessionId: requestedSessionId,
691 update: {
692 sessionUpdate: "agent_message_chunk",
693 messageId: "mock-agent-message",
694 content: { type: "text", text: "replayed assistant text" },
695 },
696 });
697 };
698
699 yield* agent.handleLoadSession((request) =>
700 Effect.gen(function* () {
701 const requestedSessionId = String(request.sessionId ?? sessionId);
702 sessionsLoading.add(requestedSessionId);
703 if (loadedCommandNames !== undefined) {
704 const publishLoadedCommands = agent.client.sessionUpdate({
705 sessionId: requestedSessionId,
706 update: {
707 sessionUpdate: "available_commands_update",
708 availableCommands: loadedCommandNames.map((name) => ({ name, description: name })),
709 },
710 });
711 if (Number.isFinite(loadedCommandsDelayMs)) {
712 yield* Effect.sleep(`${loadedCommandsDelayMs} millis`).pipe(
713 Effect.andThen(publishLoadedCommands),
714 Effect.forkDetach,
715 );
716 } else {
717 yield* publishLoadedCommands;
718 }
719 }
720 if (failLoadSession) {
721 return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
722 }
723 if (failLoadSessionAfterConfigReplay) {
724 yield* agent.client.sessionUpdate({
725 sessionId: requestedSessionId,
726 update: {
727 sessionUpdate: "config_option_update",
728 configOptions: [
729 {
730 configId: "candidate-only",
731 name: "Candidate only",
732 type: "boolean",
733 currentValue: true,
734 },
735 ],
736 },
737 });
738 return yield* AcpError.AcpRequestError.internalError(
739 "Mock load session failure after config replay",
740 );
741 }
742 if (delayLoadSessionAfterReplay) {
743 emitLoadReplayNotifications(requestedSessionId);
744 yield* agent.client.sessionUpdate({
745 sessionId: requestedSessionId,
746 update: {
747 sessionUpdate: "user_message_chunk",
748 messageId: "mock-user-message",
749 content: { type: "text", text: "replay-tail" },
750 },
751 });
752 // Answer with the configuration as of the load, like an agent whose
753 // response was built before later selections landed.
754 const loadedConfigOptions = configOptions();
755 if (modeNotifiedBeforeDelayedLoadReply !== undefined) {
756 yield* Effect.sleep(loadSessionDelayMs / 2);
757 currentModeId = modeNotifiedBeforeDelayedLoadReply;
758 yield* agent.client.sessionUpdate({
759 sessionId: requestedSessionId,
760 update: { sessionUpdate: "current_mode_update", currentModeId },
761 });
762 }
763 yield* Effect.sleep(loadSessionDelayMs);
764 yield* Deferred.succeed(delayedLoadReplied, undefined);
765 return {
766 configOptions: loadedConfigOptions,
767 };
768 }
769 if (emitLoadReplay) {
770 emitLoadReplayNotifications(requestedSessionId);
771 }
772 yield* agent.client.sessionUpdate({
773 sessionId: requestedSessionId,
774 update: {
775 sessionUpdate: "user_message_chunk",
776 messageId: "mock-user-message",
777 content: { type: "text", text: "replay" },
778 },
779 });
780 if (loadNeverReplies) {
781 return yield* Effect.never;
782 }
783 if (Number.isFinite(loadReplyDelayMs) && loadReplyDelayMs > 0) {
784 yield* Effect.sleep(`${loadReplyDelayMs} millis`);
785 }
786 sessionsLoading.delete(requestedSessionId);
787 return {
788 configOptions: configOptions(),
789 };
790 }),
791 );
792
793 yield* agent.handleListSessions((request) =>
794 Effect.gen(function* () {
795 yield* requireAuthentication();
796 return {
797 sessions: [
798 {
799 sessionId,
800 cwd: request.cwd ?? process.cwd(),
801 title: "Mock session",
802 updatedAt: "1970-01-01T00:00:00.000Z",
803 },
804 ],
805 };
806 }),
807 );
808
809 yield* agent.handleForkSession((request) =>
810 Effect.gen(function* () {
811 yield* requireAuthentication();
812 return {
813 sessionId: `${request.sessionId}-fork`,
814 configOptions: configOptions(),
815 };
816 }),
817 );
818
819 yield* agent.handleCloseSession(() =>
820 Effect.gen(function* () {
821 yield* requireAuthentication();
822 if (hangCloseSession) {
823 return yield* Effect.never;
824 }
825 return {};
826 }),
827 );
828
829 yield* agent.handleDeleteSession(() =>
830 Effect.gen(function* () {
831 yield* requireAuthentication();
832 if (failDeleteSession) {
833 return yield* AcpError.AcpRequestError.internalError("delete failed");
834 }
835 return {};
836 }),
837 );
838
839 yield* agent.handleListProviders(() =>
840 Effect.gen(function* () {
841 yield* requireAuthentication();
842 return {
843 providers: [
844 {
845 providerId: "mock-provider",
846 supported: ["openai", "anthropic"],
847 required: false,
848 current: configuredProvider,
849 },
850 ],
851 };
852 }),
853 );
854
855 yield* agent.handleSetProvider((request) =>
856 Effect.gen(function* () {
857 yield* requireAuthentication();
858 configuredProvider = { apiType: request.apiType, baseUrl: request.baseUrl };
859 return {};
860 }),
861 );
862
863 yield* agent.handleDisableProvider(() =>
864 Effect.gen(function* () {
865 yield* requireAuthentication();
866 configuredProvider = null;
867 return {};
868 }),
869 );
870
871 yield* agent.handleSetSessionConfigOption((request) =>
872 Effect.gen(function* () {
873 if (holdSetConfigOptionUntilLoadReply) {
874 // Like an agent that serves requests in order: the delayed load reply
875 // goes out first, then this one.
876 yield* Deferred.await(delayedLoadReplied);
877 yield* Effect.sleep(100);
878 }
879 if (failSetModeConfigOption && request.configId === "mode") {
880 return yield* AcpError.AcpRequestError.invalidParams(
881 "Mock invalid params for session/set_config_option",
882 {
883 method: "session/set_config_option",
884 params: request,
885 },
886 );
887 }
888 if (request.configId === "mode" && typeof request.value === "string") {
889 currentModeId = request.value;
890 }
891 if (request.configId === "model" && typeof request.value === "string") {
892 currentModelId = request.value;
893 }
894 if (request.configId === "agent" && typeof request.value === "string") {
895 currentAgent = request.value;
896 }
897 if (request.configId === "reasoning" && typeof request.value === "string") {
898 currentReasoning = request.value;
899 }
900 if (request.configId === "context" && typeof request.value === "string") {
901 currentContext = request.value;
902 }
903 if (request.configId === "fast") {
904 currentFast = request.value === true || request.value === "true";
905 }
906 return {
907 configOptions: configOptions(),
908 };
909 }),
910 );
911
912 yield* agent.handleCancel(({ sessionId }) =>
913 Effect.gen(function* () {
914 const cancelledSessionId = String(sessionId ?? "mock-session-1");
915 cancelledSessions.add(cancelledSessionId);
916 if (completeFirstPromptOnCancel) {
917 yield* Deferred.succeed(nativeCancelRequested, undefined);
918 yield* agent.client.sessionUpdate({
919 sessionId: cancelledSessionId,
920 update: {
921 sessionUpdate: "agent_thought_chunk",
922 content: { type: "text", text: "native-cancel-received" },
923 },
924 });
925 }
926 }),
927 );
928
929 yield* agent.handlePrompt((request) =>
930 Effect.gen(function* () {
931 const requestedSessionId = String(request.sessionId ?? sessionId);
932 if (rejectPromptUntilLoaded && sessionsLoading.has(requestedSessionId)) {
933 return yield* new AcpError.AcpRequestError({
934 code: -32002,
935 errorMessage: `Resource not found: ${requestedSessionId}`,
936 });
937 }
938 beginAcpMockPrompt(cancelledSessions, requestedSessionId);
939 promptCount += 1;
940 if (idleError === "grok-background" && promptCount === 1) {
941 // The structured completion lands before the prompt settles, so it is buffered.
942 const taskId = "call-idle-error-background";
943 writeJsonRpcNotification("session/update", {
944 sessionId: requestedSessionId,
945 update: {
946 sessionUpdate: "tool_call",
947 toolCallId: taskId,
948 title: "run_terminal_command",
949 kind: "execute",
950 status: "in_progress",
951 rawInput: { command: "sleep 1; echo done" },
952 },
953 });
954 writeJsonRpcNotification("session/update", {
955 sessionId: requestedSessionId,
956 update: {
957 sessionUpdate: "tool_call_update",
958 toolCallId: taskId,
959 status: "completed",
960 rawOutput: {
961 type: "BackgroundTaskStarted",
962 task_id: taskId,
963 task_type: "bash",
964 status: "running",
965 command: "sleep 1; echo done",
966 },
967 },
968 });
969 writeJsonRpcNotification("_x.ai/task_completed", {
970 sessionId: requestedSessionId,
971 update: {
972 sessionUpdate: "task_completed",
973 task_snapshot: { task_id: taskId, kind: "bash", exit_code: 0, output: "done\n" },
974 },
975 });
976 writeJsonRpcNotification("session/update", {
977 sessionId: requestedSessionId,
978 update: { sessionUpdate: "state_update", state: "idle", stopReason: "error" },
979 });
980 return {};
981 }
982 if (idleError !== undefined && promptCount === 1) {
983 const toolCallId = "tool-call-idle-error-1";
984 writeJsonRpcNotification("session/update", {
985 sessionId: requestedSessionId,
986 update: {
987 sessionUpdate: "tool_call_update",
988 toolCallId,
989 title: "Terminal",
990 kind: "execute",
991 status: "in_progress",
992 rawInput: { command: ["long-running-tool"] },
993 },
994 });
995 writeJsonRpcNotification("session/update", {
996 sessionId: requestedSessionId,
997 update: {
998 sessionUpdate: "tool_call_update",
999 toolCallId: "tool-call-idle-error-monitor",
1000 title: "Monitor",
1001 kind: "execute",
1002 status: "in_progress",
1003 rawInput: { command: ["background-monitor"] },
1004 },
1005 });
1006 writeJsonRpcNotification("session/update", {
1007 sessionId: requestedSessionId,
1008 update: {
1009 sessionUpdate: "tool_call_update",
1010 toolCallId: "tool-call-idle-error-subagent",
1011 title: "Subagent",
1012 kind: "other",
1013 status: "in_progress",
1014 rawInput: {},
1015 },
1016 });
1017 writeJsonRpcNotification("session/update", {
1018 sessionId: "mock-child-session-idle-error",
1019 update: {
1020 sessionUpdate: "tool_call_update",
1021 toolCallId: "tool-call-idle-error-child",
1022 title: "Child tool",
1023 kind: "execute",
1024 status: "in_progress",
1025 rawInput: { command: ["child-tool"] },
1026 },
1027 });
1028 writeJsonRpcNotification("session/update", {
1029 sessionId: requestedSessionId,
1030 update: {
1031 sessionUpdate: "state_update",
1032 state: "idle",
1033 stopReason: "error",
1034 ...(idleError === "details"
1035 ? { error: { code: -32000, message: "Missing Authentication header" } }
1036 : {}),
1037 },
1038 });
1039 // The agent outlives the failed prompt, so its subagent finishes afterwards.
1040 yield* Effect.sleep("50 millis").pipe(
1041 Effect.andThen(
1042 Effect.sync(() =>
1043 writeJsonRpcNotification("session/update", {
1044 sessionId: requestedSessionId,
1045 update: {
1046 sessionUpdate: "tool_call_update",
1047 toolCallId: "tool-call-idle-error-subagent",
1048 status: "completed",
1049 },
1050 }),
1051 ),
1052 ),
1053 Effect.forkDetach,
1054 );
1055 return {};
1056 }
1057 if (clientFsProbePath !== undefined && clientFsProbeLogPath !== undefined) {
1058 const probes = [
1059 [
1060 "fs/write_text_file",
1061 { sessionId: requestedSessionId, path: clientFsProbePath, content: "probe" },
1062 ],
1063 ["fs/read_text_file", { sessionId: requestedSessionId, path: clientFsProbePath }],
1064 ] as const;
1065 for (const [method, params] of probes) {
1066 const outcome = yield* agent.raw.request(method, params).pipe(
1067 Effect.map((result) => ({ method, result })),
1068 Effect.catch((error) =>
1069 Effect.succeed({
1070 method,
1071 errorCode: error._tag === "AcpRequestError" ? error.code : error._tag,
1072 }),
1073 ),
1074 );
1075 NodeFS.appendFileSync(clientFsProbeLogPath, `${encodeJson(outcome)}\n`, "utf8");
1076 }
1077 }
1078
1079 if (vibeRetryOutcome !== undefined) {
1080 if (vibeRetryOutcome === "recovered") {
1081 yield* Effect.sync(() =>
1082 writeJsonRpcNotification("session/update", {
1083 sessionId: requestedSessionId,
1084 update: {
1085 sessionUpdate: "tool_call",
1086 toolCallId: "tool-before-retry",
1087 title: "Read file",
1088 kind: "read",
1089 status: "in_progress",
1090 },
1091 }),
1092 );
1093 }
1094 for (const [index, noticeSessionId] of [
1095 "unrelated-session",
1096 requestedSessionId,
1097 requestedSessionId,
1098 ].entries()) {
1099 if (index === 2 && vibeRetryOutcome === "recovered") {
1100 yield* Effect.sync(() =>
1101 writeJsonRpcNotification("session/update", {
1102 sessionId: requestedSessionId,
1103 update: {
1104 sessionUpdate: "tool_call_update",
1105 toolCallId: "tool-before-retry",
1106 status: "in_progress",
1107 rawOutput: { progress: "still reading" },
1108 },
1109 }),
1110 );
1111 }
1112 yield* Effect.sync(() =>
1113 writeJsonRpcNotification("_session/retrying", {
1114 sessionId: noticeSessionId,
1115 category: "rate_limited",
1116 detail: "Rate limit reached. Retrying. api_key=private-key",
1117 }),
1118 );
1119 }
1120 if (vibeRetryOutcome === "failed") {
1121 return yield* new AcpError.AcpRequestError({
1122 code: -31001,
1123 errorMessage: "Rate limit exceeded for mistral (model: mistral-vibe-cli-latest).",
1124 });
1125 }
1126 if (vibeRetryOutcome === "completed") {
1127 return yield* finishPrompt(requestedSessionId, "end_turn");
1128 }
1129 if (vibeRetryOutcome === "cancelled") {
1130 return yield* finishPrompt(requestedSessionId, "cancelled");
1131 }
1132 yield* agent.client.sessionUpdate({
1133 sessionId: requestedSessionId,
1134 update: {
1135 sessionUpdate: "agent_message_chunk",
1136 content: { type: "text", text: "Recovered answer" },
1137 },
1138 });
1139 return yield* finishPrompt(requestedSessionId, "end_turn");
1140 }
1141
1142 if (terminalOutputBytes > 0) {
1143 const terminalId = "long-output";
1144 yield* agent.client.sessionUpdate({
1145 sessionId: requestedSessionId,
1146 update: { sessionUpdate: "terminal_update", terminalId, command: "print long output" },
1147 });
1148 // 4 KiB chunks of 64-char numbered lines, like a long build log.
1149 for (let line = 0; line * 64 < terminalOutputBytes; line += 64) {
1150 let chunk = "";
1151 for (let i = line + 1; i <= line + 64; i++) {
1152 chunk += `${String(i).padStart(8, "0")} ${"x".repeat(54)}\n`;
1153 }
1154 yield* agent.client.sessionUpdate({
1155 sessionId: requestedSessionId,
1156 update: {
1157 sessionUpdate: "terminal_output_chunk",
1158 terminalId,
1159 data: Buffer.from(chunk)
1160 .subarray(0, terminalOutputBytes - line * 64)
1161 .toString("base64"),
1162 },
1163 });
1164 }
1165 yield* agent.client.sessionUpdate({
1166 sessionId: requestedSessionId,
1167 update: { sessionUpdate: "terminal_update", terminalId, exitStatus: { exitCode: 0 } },
1168 });
1169 return yield* finishPrompt(requestedSessionId, "end_turn");
1170 }
1171
1172 if (emitNotice) {
1173 // A notice in fx 0.0.14's shape for a skipped skill, between two chunks of one message.
1174 const chunk = (text: string) =>
1175 writeJsonRpcNotification("session/update", {
1176 sessionId: requestedSessionId,
1177 update: {
1178 sessionUpdate: "agent_message_chunk",
1179 messageId: "mock-notice-message",
1180 content: { type: "text", text },
1181 },
1182 });
1183 chunk("before the notice, ");
1184 writeJsonRpcNotification("session/update", {
1185 sessionId: requestedSessionId,
1186 update: {
1187 sessionUpdate: "notice",
1188 severity: "info",
1189 title: "skill discovery warning: candidate was skipped because its metadata is invalid",
1190 },
1191 });
1192 chunk("after the notice");
1193 return yield* finishPrompt(requestedSessionId, "end_turn");
1194 }
1195
1196 if (emitV2Fidelity) {
1197 yield* agent.client.sessionUpdate({
1198 sessionId: `${requestedSessionId}-child`,
1199 update: {
1200 sessionUpdate: "terminal_update",
1201 terminalId: "standalone-terminal",
1202 command: "printf child",
1203 output: { data: Buffer.from("child").toString("base64") },
1204 },
1205 });
1206 const updates: ReadonlyArray<AcpSchema.SessionUpdate> = [
1207 {
1208 sessionUpdate: "user_message_chunk",
1209 messageId: "user-1",
1210 content: { type: "text", text: "stale user text" },
1211 },
1212 { sessionUpdate: "user_message", messageId: "user-1", content: null },
1213 {
1214 sessionUpdate: "agent_thought_chunk",
1215 messageId: "thought-1",
1216 content: { type: "text", text: "stale thought" },
1217 },
1218 {
1219 sessionUpdate: "agent_message_chunk",
1220 messageId: "assistant-1",
1221 content: { type: "text", text: "interleaved answer" },
1222 },
1223 {
1224 sessionUpdate: "agent_message",
1225 messageId: "assistant-1",
1226 content: [{ type: "text", text: "authoritative answer" }],
1227 },
1228 { sessionUpdate: "agent_message", messageId: "assistant-1" },
1229 {
1230 sessionUpdate: "agent_thought",
1231 messageId: "thought-1",
1232 content: [{ type: "text", text: "final thought" }],
1233 },
1234 {
1235 sessionUpdate: "plan_update",
1236 plan: { type: "markdown", planId: "plan-a", content: "# Plan A" },
1237 },
1238 {
1239 sessionUpdate: "plan_update",
1240 plan: {
1241 type: "items",
1242 planId: "plan-b",
1243 entries: [{ content: "Ship B", priority: "high", status: "in_progress" }],
1244 },
1245 },
1246 {
1247 sessionUpdate: "plan_update",
1248 plan: {
1249 type: "items",
1250 planId: "plan-c",
1251 entries: [
1252 { content: "Write the fix", priority: "high", status: "completed" },
1253 { content: "Try another approach", priority: "low", status: "cancelled" },
1254 { content: "Add a test", priority: "medium", status: "completed" },
1255 ],
1256 },
1257 },
1258 { sessionUpdate: "plan_removed", planId: "plan-a" },
1259 {
1260 sessionUpdate: "terminal_update",
1261 terminalId: "standalone-terminal",
1262 command: "printf proof",
1263 cwd: process.cwd(),
1264 },
1265 {
1266 sessionUpdate: "terminal_output_chunk",
1267 terminalId: "standalone-terminal",
1268 data: Buffer.from("proof").toString("base64"),
1269 },
1270 {
1271 sessionUpdate: "terminal_update",
1272 terminalId: "standalone-terminal",
1273 exitStatus: { exitCode: 0 },
1274 },
1275 { sessionUpdate: "state_update", state: "requires_action" },
1276 { sessionUpdate: "state_update", state: "running" },
1277 {
1278 sessionUpdate: "tool_call_update",
1279 toolCallId: "structured-diff",
1280 title: "Edit files",
1281 kind: "edit",
1282 status: "completed",
1283 content: [
1284 {
1285 type: "diff",
1286 changes: [
1287 {
1288 operation: "move",
1289 oldPath: "/workspace/old.ts",
1290 path: "/workspace/new.ts",
1291 fileType: "text",
1292 mimeType: "text/typescript",
1293 },
1294 ],
1295 patch: {
1296 format: "git_patch",
1297 text: "diff --git a/old.ts b/new.ts\nrename from old.ts\nrename to new.ts\n",
1298 },
1299 },
1300 ],
1301 },
1302 {
1303 sessionUpdate: "tool_call_update",
1304 toolCallId: "structured-read",
1305 title: "Read `src/env.ts`",
1306 kind: "read",
1307 status: "completed",
1308 rawInput: { path: "src/env.ts" },
1309 locations: [{ path: "src/env.ts" }],
1310 },
1311 // Antigravity reports an image read with only a text result, never the image bytes.
1312 {
1313 sessionUpdate: "tool_call_update",
1314 toolCallId: "structured-image-read",
1315 title: "Read `mockup.png`",
1316 kind: "read",
1317 status: "completed",
1318 rawInput: { file_path: "/workspace/mockup.png", start_line: 0, end_line: 799 },
1319 rawOutput: "View mockup.png",
1320 },
1321 {
1322 sessionUpdate: "tool_call_update",
1323 toolCallId: "structured-search",
1324 title: "Grep",
1325 kind: "search",
1326 status: "completed",
1327 rawInput: { query: "TODO", path: "apps/web" },
1328 },
1329 {
1330 sessionUpdate: "tool_call_update",
1331 toolCallId: "structured-search-explicit-location",
1332 title: "Grep",
1333 kind: "search",
1334 status: "completed",
1335 rawInput: { query: " README.md " },
1336 locations: [{ path: "README.md" }],
1337 rawOutput: "# Title",
1338 },
1339 {
1340 sessionUpdate: "tool_call_update",
1341 toolCallId: "structured-search-query-only",
1342 title: "Grep",
1343 kind: "search",
1344 status: "completed",
1345 rawInput: { query: "TODO" },
1346 rawOutput: "src/a.ts: TODO",
1347 },
1348 {
1349 sessionUpdate: "tool_call_update",
1350 toolCallId: "structured-search-query-no-output",
1351 title: "Grep",
1352 kind: "search",
1353 status: "completed",
1354 rawInput: { query: "FIXME" },
1355 },
1356 // Grok backend searches: the query only arrives in the completed rawOutput.
1357 {
1358 sessionUpdate: "tool_call_update",
1359 toolCallId: "grok-x-search",
1360 title: "X search:",
1361 kind: "search",
1362 status: "in_progress",
1363 rawInput: { variant: "XSearch", backend: true },
1364 },
1365 {
1366 sessionUpdate: "tool_call_update",
1367 toolCallId: "grok-x-search",
1368 title: "X search:",
1369 status: "completed",
1370 rawOutput: {
1371 call_id: "xs_call-1",
1372 input: '{"query":"conversation_id:42","limit":"10","mode":"Latest"}',
1373 name: "x_keyword_search",
1374 id: "grok-x-search",
1375 },
1376 },
1377 {
1378 sessionUpdate: "tool_call_update",
1379 toolCallId: "grok-web-search",
1380 title: "Web search:",
1381 kind: "search",
1382 status: "completed",
1383 rawInput: { variant: "WebSearch", backend: true },
1384 rawOutput: {
1385 action: {
1386 type: "search",
1387 query: "t3 code",
1388 sources: [
1389 { type: "url", url: "https://t3.codes" },
1390 { type: "url", url: "https://t3.codes" },
1391 { type: "url", url: "https://github.com/pingdotgg/t3code" },
1392 ],
1393 },
1394 id: "grok-web-search",
1395 status: "completed",
1396 },
1397 },
1398 {
1399 sessionUpdate: "tool_call_update",
1400 toolCallId: "grok-web-fetch",
1401 title: "Fetch: https://t3.codes",
1402 kind: "fetch",
1403 status: "completed",
1404 rawInput: { variant: "WebFetch", url: "https://t3.codes" },
1405 rawOutput: {
1406 type: "WebFetch",
1407 Content: { url: "https://t3.codes", content: "T3 Code page" },
1408 },
1409 content: [{ type: "content", content: { type: "text", text: "T3 Code page" } }],
1410 },
1411 {
1412 sessionUpdate: "tool_call_update",
1413 toolCallId: "antigravity-shell",
1414 title: "run_command",
1415 kind: "execute",
1416 status: "completed",
1417 rawInput: { command: "cat probe.txt" },
1418 rawOutput: { commandLine: "cat probe.txt", exitCode: 0, combinedOutput: "after\n" },
1419 },
1420 {
1421 sessionUpdate: "tool_call_update",
1422 toolCallId: "antigravity-web-search",
1423 title: "Web search",
1424 kind: "search",
1425 status: "completed",
1426 rawInput: { query: " top story on Hacker News today " },
1427 rawOutput:
1428 "Sources:\n<https://vertexaisearch.cloud.google.com/grounding-api-redirect/AUZIYQGYNzfz>.",
1429 },
1430 {
1431 sessionUpdate: "tool_call_update",
1432 toolCallId: "antigravity-run-search-web",
1433 title: "Running search_web",
1434 kind: "search",
1435 status: "completed",
1436 rawInput: { query: "top story on Hacker News today" },
1437 },
1438 {
1439 sessionUpdate: "tool_call_update",
1440 toolCallId: "antigravity-web-search-streamed",
1441 title: "Web search",
1442 kind: "search",
1443 status: "in_progress",
1444 rawInput: { query: "streamed citations" },
1445 rawOutput: "Sources: https://example.com/streamed_(detail)",
1446 },
1447 {
1448 sessionUpdate: "tool_call_content_chunk",
1449 toolCallId: "antigravity-web-search-streamed",
1450 content: { type: "content", content: { type: "text", text: " (updated)" } },
1451 },
1452 {
1453 sessionUpdate: "tool_call_update",
1454 toolCallId: "antigravity-web-search-streamed",
1455 status: "completed",
1456 },
1457 {
1458 sessionUpdate: "compaction_update",
1459 compactionId: "compact-1",
1460 status: "in_progress",
1461 },
1462 {
1463 sessionUpdate: "compaction_summary_chunk",
1464 compactionId: "compact-1",
1465 content: { type: "text", text: "Retained decisions." },
1466 },
1467 {
1468 sessionUpdate: "compaction_update",
1469 compactionId: "compact-1",
1470 status: "completed",
1471 summary: [{ type: "text", text: "Retained decisions." }],
1472 },
1473 ];
1474 for (const update of updates) {
1475 yield* agent.client.sessionUpdate({ sessionId: requestedSessionId, update });
1476 }
1477 return yield* finishPrompt(requestedSessionId, "end_turn");
1478 }
1479
1480 if (completeFirstPromptOnCancel && promptCount === 1) {
1481 yield* agent.client.sessionUpdate({
1482 sessionId: requestedSessionId,
1483 update: {
1484 sessionUpdate: "tool_call_update",
1485 toolCallId: "native-cancel-tool",
1486 title: "Long command",
1487 kind: "execute",
1488 status: "in_progress",
1489 },
1490 });
1491 yield* agent.client.sessionUpdate({
1492 sessionId: requestedSessionId,
1493 update: {
1494 sessionUpdate: "tool_call_update",
1495 toolCallId: "native-failed-tool",
1496 title: "Failing command",
1497 kind: "execute",
1498 status: "in_progress",
1499 },
1500 });
1501 yield* Deferred.await(nativeCancelRequested);
1502 yield* Deferred.await(nativeCancelRelease);
1503 yield* agent.client.sessionUpdate({
1504 sessionId: requestedSessionId,
1505 update: {
1506 sessionUpdate: "tool_call_update",
1507 toolCallId: "native-failed-tool",
1508 status: "failed",
1509 content: [{ type: "content", content: { type: "text", text: "Permission denied" } }],
1510 },
1511 });
1512 yield* agent.client.sessionUpdate({
1513 sessionId: requestedSessionId,
1514 update: {
1515 sessionUpdate: "tool_call_update",
1516 toolCallId: "native-cancel-tool",
1517 status: "failed",
1518 content: [{ type: "content", content: { type: "text", text: "Cancelled." } }],
1519 },
1520 });
1521 yield* agent.client.sessionUpdate({
1522 sessionId: requestedSessionId,
1523 update: {
1524 sessionUpdate: "tool_call_update",
1525 toolCallId: "native-unseen-cancel-tool",
1526 title: "Cancelled command",
1527 kind: "execute",
1528 status: "failed",
1529 content: [{ type: "content", content: { type: "text", text: "Cancelled." } }],
1530 },
1531 });
1532 // A later output-only update must not undo the interrupted status.
1533 yield* agent.client.sessionUpdate({
1534 sessionId: requestedSessionId,
1535 update: {
1536 sessionUpdate: "tool_call_update",
1537 toolCallId: "native-cancel-tool",
1538 content: [{ type: "content", content: { type: "text", text: "Cancelled. exit 130" } }],
1539 },
1540 });
1541 yield* agent.client.sessionUpdate({
1542 sessionId: requestedSessionId,
1543 update: {
1544 sessionUpdate: "agent_message_chunk",
1545 content: { type: "text", text: "Request cancelled." },
1546 },
1547 });
1548 return yield* finishPrompt(requestedSessionId, "cancelled", { nativeCancel: true });
1549 }
1550
1551 if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
1552 yield* Effect.sleep(`${promptDelayMs} millis`);
1553 }
1554
1555 if (openCompactionPromptOrdinals.has(promptCount)) {
1556 yield* agent.client.sessionUpdate({
1557 sessionId: requestedSessionId,
1558 update: {
1559 sessionUpdate: "compaction_update",
1560 compactionId: `compact-${promptCount}`,
1561 status: "in_progress",
1562 },
1563 });
1564 }
1565 if (compactionPromptOrdinals.has(promptCount)) {
1566 for (const status of ["in_progress", "completed"] as const) {
1567 yield* agent.client.sessionUpdate({
1568 sessionId: requestedSessionId,
1569 update: {
1570 sessionUpdate: "compaction_update",
1571 compactionId: `compact-${promptCount}`,
1572 status,
1573 },
1574 });
1575 }
1576 }
1577
1578 if (emitTrackedToolCallKindThenHang !== undefined) {
1579 yield* agent.client.sessionUpdate({
1580 sessionId: requestedSessionId,
1581 update: {
1582 sessionUpdate: "tool_call_update",
1583 toolCallId: "tracked-tool-call",
1584 title: "git status",
1585 kind: emitTrackedToolCallKindThenHang as AcpSchema.ToolKind,
1586 status: "pending",
1587 rawInput: { command: "git status" },
1588 },
1589 });
1590 if (!failPrompt && promptCount !== failPromptOrdinal) return yield* Effect.never;
1591 }
1592
1593 if (failPrompt || promptCount === failPromptOrdinal) {
1594 return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
1595 }
1596
1597 if (hangPromptForever || (emitEmptySuccessfulBashThenHang && promptCount === 2)) {
1598 return yield* Effect.never;
1599 }
1600
1601 if (grokKillTaskShape !== undefined) {
1602 emitGrokKillTaskScenario(
1603 requestedSessionId,
1604 promptIdFromRequestMeta(request),
1605 grokKillTaskShape,
1606 );
1607 // Keep the prompt RPC and peer alive after the kill result.
1608 return yield* Effect.never;
1609 }
1610
1611 if (emitEmptySuccessfulBash || (emitEmptySuccessfulBashThenHang && promptCount === 1)) {
1612 const update = {
1613 sessionId: requestedSessionId,
1614 update: {
1615 sessionUpdate: "tool_call_update",
1616 toolCallId: "tool-call-empty-success-1",
1617 title: "Terminal",
1618 kind: "execute",
1619 status: "completed",
1620 rawInput: { command: "true" },
1621 rawOutput: { type: "Bash", exit_code: 0 },
1622 },
1623 } as const;
1624 yield* agent.client.sessionUpdate(update);
1625 yield* Effect.sleep("25 millis");
1626 yield* agent.client.sessionUpdate(update);
1627 return yield* finishPrompt(requestedSessionId, "end_turn");
1628 }
1629
1630 if (emitGrokBackgroundTaskPoll) {
1631 const toolCallId = "call-fb9d0000-0000-0000-0000-000000000026-29";
1632 const command = "sleep 40; echo done-a";
1633 writeJsonRpcNotification("session/update", {
1634 sessionId: requestedSessionId,
1635 update: {
1636 sessionUpdate: "tool_call_update",
1637 toolCallId,
1638 title: "run_terminal_command",
1639 kind: "execute",
1640 status: "in_progress",
1641 rawInput: { command },
1642 },
1643 });
1644 writeJsonRpcNotification("session/update", {
1645 sessionId: requestedSessionId,
1646 update: {
1647 sessionUpdate: "tool_call_update",
1648 toolCallId,
1649 status: "completed",
1650 rawOutput: {
1651 type: "BackgroundTaskStarted",
1652 task_id: toolCallId,
1653 task_type: "bash",
1654 status: "running",
1655 command,
1656 },
1657 },
1658 });
1659 writeJsonRpcNotification("session/update", {
1660 sessionId: requestedSessionId,
1661 update: {
1662 sessionUpdate: "tool_call_update",
1663 toolCallId: "call-background-poll",
1664 title: "get_command_or_subagent_output",
1665 kind: "other",
1666 status: "completed",
1667 rawOutput: {
1668 type: "TaskOutput",
1669 Result: {
1670 task_id: toolCallId,
1671 command,
1672 status: "completed",
1673 exit_code: 0,
1674 output: "done-a",
1675 },
1676 },
1677 },
1678 });
1679
1680 yield* agent.client.sessionUpdate({
1681 sessionId: requestedSessionId,
1682 update: {
1683 sessionUpdate: "agent_message_chunk",
1684 content: { type: "text", text: "The background command finished." },
1685 },
1686 });
1687 writeJsonRpcNotification("_x.ai/session/update", {
1688 sessionId: requestedSessionId,
1689 update: {
1690 sessionUpdate: "turn_completed",
1691 prompt_id: promptIdFromRequestMeta(request),
1692 stop_reason: "end_turn",
1693 },
1694 });
1695 // Neither the prompt RPC nor the process ends, matching the Grok incident.
1696 return yield* Effect.never;
1697 }
1698
1699 if (emitBackgroundToolDuringAnswer) {
1700 const toolCallId = "background-1";
1701 const say = (text: string) =>
1702 agent.client.sessionUpdate({
1703 sessionId: requestedSessionId,
1704 update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
1705 });
1706 const progress = (status: "in_progress" | "completed", stdout: string) =>
1707 agent.client.sessionUpdate({
1708 sessionId: requestedSessionId,
1709 update: {
1710 sessionUpdate: "tool_call_update",
1711 toolCallId,
1712 status,
1713 rawOutput: { stdout },
1714 },
1715 });
1716 yield* agent.client.sessionUpdate({
1717 sessionId: requestedSessionId,
1718 update: {
1719 sessionUpdate: "tool_call_update",
1720 toolCallId,
1721 title: "Terminal",
1722 kind: "execute",
1723 status: "in_progress",
1724 rawInput: { command: "sleep 3 && echo done" },
1725 },
1726 });
1727 yield* say("| a | b |\n|---|---|\n| 1 ");
1728 yield* progress("in_progress", ".");
1729 yield* say("| x |\n");
1730 yield* progress("completed", "done");
1731 yield* say("| 2 | y |\n");
1732 yield* progress("completed", "done");
1733 yield* say("| 3 | z |");
1734 return yield* finishPrompt(requestedSessionId, "end_turn");
1735 }
1736
1737 if (emitInterleavedAssistantToolCalls) {
1738 const toolCallId = "tool-call-1";
1739
1740 yield* agent.client.sessionUpdate({
1741 sessionId: requestedSessionId,
1742 update: {
1743 sessionUpdate: "agent_message_chunk",
1744 messageId: "mock-agent-message",
1745 content: { type: "text", text: "before tool" },
1746 },
1747 });
1748
1749 yield* agent.client.sessionUpdate({
1750 sessionId: requestedSessionId,
1751 update: {
1752 sessionUpdate: "tool_call_update",
1753 toolCallId,
1754 title: "Terminal",
1755 kind: "execute",
1756 status: "pending",
1757 rawInput: {
1758 command: ["echo", "hello"],
1759 },
1760 },
1761 });
1762
1763 yield* agent.client.sessionUpdate({
1764 sessionId: requestedSessionId,
1765 update: {
1766 sessionUpdate: "tool_call_update",
1767 toolCallId,
1768 status: "completed",
1769 rawOutput: {
1770 exitCode: 0,
1771 stdout: "hello",
1772 stderr: "",
1773 },
1774 },
1775 });
1776
1777 yield* agent.client.sessionUpdate({
1778 sessionId: requestedSessionId,
1779 update: {
1780 sessionUpdate: "agent_message_chunk",
1781 messageId: "mock-agent-message",
1782 content: { type: "text", text: "after tool" },
1783 },
1784 });
1785
1786 return yield* finishPrompt(requestedSessionId, "end_turn");
1787 }
1788
1789 if (emitElicitation || emitMcpToolApprovalElicitation) {
1790 const response = yield* agent.client.elicit({
1791 sessionId: requestedSessionId,
1792 message: "Approve this request?",
1793 mode: "form",
1794 requestedSchema: elicitationSchema
1795 ? decodeElicitationSchema(elicitationSchema)
1796 : {
1797 type: "object",
1798 properties: {
1799 approved: { type: "boolean", title: "Approved" },
1800 },
1801 },
1802 ...(emitMcpToolApprovalElicitation
1803 ? { _meta: { codex_approval_kind: "mcp_tool_call" } }
1804 : {}),
1805 });
1806 if (elicitationResponseLogPath)
1807 NodeFS.appendFileSync(elicitationResponseLogPath, `${encodeJson(response)}\n`, "utf8");
1808 return yield* finishPrompt(requestedSessionId, "end_turn");
1809 }
1810
1811 if (emitToolCalls) {
1812 const toolCallId = "tool-call-1";
1813
1814 yield* agent.client.sessionUpdate({
1815 sessionId: requestedSessionId,
1816 update: {
1817 sessionUpdate: "tool_call_update",
1818 toolCallId,
1819 title: "Terminal",
1820 kind: "execute",
1821 status: "pending",
1822 rawInput: {
1823 command: ["cat", "server/package.json"],
1824 },
1825 },
1826 });
1827
1828 yield* agent.client.sessionUpdate({
1829 sessionId: requestedSessionId,
1830 update: {
1831 sessionUpdate: "tool_call_update",
1832 toolCallId,
1833 status: "in_progress",
1834 },
1835 });
1836
1837 const permissionOptions: Array<AcpSchema.PermissionOption> = [
1838 { optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
1839 {
1840 optionId: permissionOptionIds.allowAlways,
1841 name: "Allow always",
1842 kind: "allow_always" as const,
1843 },
1844 { optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
1845 ];
1846
1847 let cancelled = cancelledSessions.delete(requestedSessionId);
1848 const command = "cat server/package.json";
1849 const permission = yield* agent.client.requestPermission({
1850 sessionId: requestedSessionId,
1851 title: `\`${command}\``,
1852 subject: {
1853 type: "tool_call",
1854 toolCall: {
1855 toolCallId,
1856 title: `\`${command}\``,
1857 kind: "execute",
1858 status: "pending",
1859 rawInput: {
1860 variant: "Bash",
1861 command,
1862 description: "Read package metadata",
1863 },
1864 content: [
1865 {
1866 type: "content",
1867 content: {
1868 type: "text",
1869 text: `Not in allowlist: ${command}`,
1870 },
1871 },
1872 ],
1873 },
1874 },
1875 options: permissionOptions,
1876 });
1877 cancelled =
1878 cancelled ||
1879 cancelledSessions.delete(requestedSessionId) ||
1880 permission.outcome.outcome === "cancelled";
1881
1882 yield* agent.client.sessionUpdate({
1883 sessionId: requestedSessionId,
1884 update: {
1885 sessionUpdate: "tool_call_update",
1886 toolCallId,
1887 title: "Terminal",
1888 kind: "execute",
1889 status: "completed",
1890 rawOutput: {
1891 exitCode: 0,
1892 stdout: '{ "name": "t3" }',
1893 stderr: "",
1894 },
1895 },
1896 });
1897
1898 yield* agent.client.sessionUpdate({
1899 sessionId: requestedSessionId,
1900 update: {
1901 sessionUpdate: "agent_message_chunk",
1902 messageId: "mock-agent-message",
1903 content: { type: "text", text: "hello from mock" },
1904 },
1905 });
1906
1907 return yield* finishPrompt(requestedSessionId, cancelled ? "cancelled" : "end_turn");
1908 }
1909
1910 if (emitGenericToolPlaceholders) {
1911 const toolCallId = "tool-call-generic-1";
1912
1913 yield* agent.client.sessionUpdate({
1914 sessionId: requestedSessionId,
1915 update: {
1916 sessionUpdate: "tool_call_update",
1917 toolCallId,
1918 title: "Read File",
1919 kind: "read",
1920 status: "pending",
1921 rawInput: {},
1922 },
1923 });
1924
1925 yield* agent.client.sessionUpdate({
1926 sessionId: requestedSessionId,
1927 update: {
1928 sessionUpdate: "tool_call_update",
1929 toolCallId,
1930 status: "in_progress",
1931 },
1932 });
1933
1934 yield* agent.client.sessionUpdate({
1935 sessionId: requestedSessionId,
1936 update: {
1937 sessionUpdate: "tool_call_update",
1938 toolCallId,
1939 status: "completed",
1940 rawOutput: {
1941 content: "package.json\n",
1942 },
1943 },
1944 });
1945
1946 return yield* finishPrompt(requestedSessionId, "end_turn");
1947 }
1948
1949 if (emitInTurnTaskOutputThenLateDuplicate) {
1950 const monitorToolCallId = "tool-call-monitor-1";
1951 yield* agent.client.sessionUpdate({
1952 sessionId: requestedSessionId,
1953 update: {
1954 sessionUpdate: "tool_call_update",
1955 toolCallId: monitorToolCallId,
1956 title: "Monitor: mock background task",
1957 kind: "execute",
1958 status: "pending",
1959 rawInput: {},
1960 },
1961 });
1962 yield* agent.client.sessionUpdate({
1963 sessionId: requestedSessionId,
1964 update: {
1965 sessionUpdate: "tool_call_update",
1966 toolCallId: monitorToolCallId,
1967 status: "in_progress",
1968 },
1969 });
1970 yield* agent.client.sessionUpdate({
1971 sessionId: requestedSessionId,
1972 update: {
1973 sessionUpdate: "tool_call_update",
1974 toolCallId: "tool-call-fetch-1",
1975 title: "get_command_or_subagent_output",
1976 kind: "other",
1977 status: "pending",
1978 rawInput: { task_id: "task-monitor-1" },
1979 },
1980 });
1981 yield* agent.client.sessionUpdate({
1982 sessionId: requestedSessionId,
1983 update: {
1984 sessionUpdate: "tool_call_update",
1985 toolCallId: "tool-call-fetch-1",
1986 status: "completed",
1987 rawOutput: { output: "MONITOR_LISTING_TOKEN" },
1988 },
1989 });
1990 yield* agent.client.sessionUpdate({
1991 sessionId: requestedSessionId,
1992 update: {
1993 sessionUpdate: "agent_message_chunk",
1994 messageId: "mock-agent-message",
1995 content: { type: "text", text: "Monitor listing ready in-turn." },
1996 },
1997 });
1998 yield* Effect.gen(function* () {
1999 yield* Effect.sleep("2500 millis");
2000 yield* Effect.sync(() => {
2001 writeJsonRpcNotification("session/update", {
2002 sessionId: requestedSessionId,
2003 update: {
2004 sessionUpdate: "tool_call_update",
2005 toolCallId: "tool-call-fetch-1",
2006 title: "get_command_or_subagent_output",
2007 kind: "other",
2008 status: "completed",
2009 rawOutput: { output: "MONITOR_LISTING_TOKEN_LATE" },
2010 },
2011 });
2012 });
2013 }).pipe(Effect.forkDetach);
2014 return yield* finishPrompt(requestedSessionId, "end_turn");
2015 }
2016
2017 if (emitForeignSessionUpdates) {
2018 yield* agent.client.sessionUpdate({
2019 sessionId: requestedSessionId,
2020 update: {
2021 sessionUpdate: "agent_message_chunk",
2022 messageId: "mock-agent-message",
2023 content: { type: "text", text: "root before child" },
2024 },
2025 });
2026 yield* agent.client.sessionUpdate({
2027 sessionId: "mock-child-session-1",
2028 update: {
2029 sessionUpdate: "agent_message_chunk",
2030 messageId: "mock-agent-message",
2031 content: { type: "text", text: "child content" },
2032 },
2033 });
2034 yield* agent.client.sessionUpdate({
2035 sessionId: "mock-child-session-1",
2036 update: {
2037 sessionUpdate: "tool_call_update",
2038 toolCallId: "child-tool-call-1",
2039 title: "Child-only tool",
2040 kind: "other",
2041 status: "pending",
2042 rawInput: {},
2043 },
2044 });
2045 yield* agent.client.sessionUpdate({
2046 sessionId: requestedSessionId,
2047 update: {
2048 sessionUpdate: "agent_message_chunk",
2049 messageId: "mock-agent-message",
2050 content: { type: "text", text: " root after child" },
2051 },
2052 });
2053 return yield* finishPrompt(requestedSessionId, "end_turn");
2054 }
2055
2056 yield* agent.client.sessionUpdate({
2057 sessionId: requestedSessionId,
2058 update: {
2059 sessionUpdate: "plan_update",
2060 plan: {
2061 type: "items",
2062 planId: "mock-plan",
2063 entries: [
2064 {
2065 content: "Inspect mock ACP state",
2066 priority: "high",
2067 status: "completed",
2068 },
2069 {
2070 content: "Implement the requested change",
2071 priority: "high",
2072 status: "in_progress",
2073 },
2074 ],
2075 },
2076 },
2077 });
2078
2079 yield* agent.client.sessionUpdate({
2080 sessionId: requestedSessionId,
2081 update: {
2082 sessionUpdate: "agent_message_chunk",
2083 messageId: "mock-agent-message",
2084 content: { type: "text", text: promptResponseText ?? "hello from mock" },
2085 },
2086 });
2087
2088 return yield* finishPrompt(requestedSessionId, "end_turn");
2089 }),
2090 );
2091
2092 yield* agent.handleUnknownExtRequest((method, params) => {
2093 if (method === "_test/environment") {
2094 return Effect.succeed({
2095 inherited: process.env.T3_ACP_RUNTIME_AMBIENT === "sentinel",
2096 explicit: process.env.T3_ACP_RUNTIME_EXPLICIT === "kept",
2097 });
2098 }
2099 if (method === "_test/finish-cancel") {
2100 return Deferred.succeed(nativeCancelRelease, undefined).pipe(Effect.as({}));
2101 }
2102 if (method === "_test/emit-update") {
2103 return agent.client
2104 .sessionUpdate(params as AcpSchema.SessionNotification)
2105 .pipe(Effect.as({}));
2106 }
2107 if (method === "_test/startup-metadata") {
2108 return Effect.gen(function* () {
2109 for (const [metadataSessionId, commandName, modeId] of [
2110 [sessionId, "plan", "code"],
2111 ["child-session", "foreign-command", "ask"],
2112 ] as const) {
2113 yield* agent.client.sessionUpdate({
2114 sessionId: metadataSessionId,
2115 update: {
2116 sessionUpdate: "available_commands_update",
2117 availableCommands: [{ name: commandName, description: "Native command" }],
2118 },
2119 });
2120 currentModeId = modeId;
2121 yield* agent.client.sessionUpdate({
2122 sessionId: metadataSessionId,
2123 update: {
2124 sessionUpdate: "config_option_update",
2125 configOptions: configOptions().map((option) =>
2126 option.type === "select" && option.category === "model"
2127 ? {
2128 ...option,
2129 currentValue: metadataSessionId === sessionId ? "gpt-5.4" : "default",
2130 }
2131 : option,
2132 ),
2133 },
2134 });
2135 yield* agent.client.sessionUpdate({
2136 sessionId: metadataSessionId,
2137 update: {
2138 sessionUpdate: "agent_message_chunk",
2139 content: { type: "text", text: "Startup transcript must not replay." },
2140 },
2141 });
2142 }
2143 return {};
2144 });
2145 }
2146 if (method === "cursor/list_available_models") {
2147 return Effect.succeed({
2148 models: availableModels(),
2149 });
2150 }
2151
2152 if (method !== "session/mode/set") {
2153 return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
2154 }
2155
2156 const nextModeId =
2157 typeof params === "object" &&
2158 params !== null &&
2159 "modeId" in params &&
2160 typeof params.modeId === "string"
2161 ? params.modeId
2162 : typeof params === "object" &&
2163 params !== null &&
2164 "mode" in params &&
2165 typeof params.mode === "string"
2166 ? params.mode
2167 : undefined;
2168 const requestedSessionId =
2169 typeof params === "object" &&
2170 params !== null &&
2171 "sessionId" in params &&
2172 typeof params.sessionId === "string"
2173 ? params.sessionId
2174 : sessionId;
2175
2176 if (typeof nextModeId === "string" && nextModeId.trim()) {
2177 currentModeId = nextModeId.trim();
2178 return agent.client
2179 .sessionUpdate({
2180 sessionId: requestedSessionId,
2181 update: {
2182 sessionUpdate: "current_mode_update",
2183 currentModeId,
2184 },
2185 })
2186 .pipe(Effect.as({}));
2187 }
2188
2189 return Effect.succeed({});
2190 });
2191
2192 yield* agent.handleUnknownExtNotification((method, params) =>
2193 method === "_test/exit"
2194 ? Effect.sync(() => {
2195 const code =
2196 typeof params === "object" && params !== null ? Reflect.get(params, "code") : undefined;
2197 process.exit(typeof code === "number" ? code : 19);
2198 })
2199 : Effect.void,
2200 );
2201
2202 return yield* Effect.never;
2203 }).pipe(
2204 Effect.provide(
2205 EffectAcpAgent.layerStdio(
2206 requestLogPath
2207 ? {
2208 logIncoming: true,
2209 logger: (event) => {
2210 if (event.direction !== "incoming" || event.stage !== "raw") {
2211 return Effect.void;
2212 }
2213 if (typeof event.payload !== "string") {
2214 return Effect.void;
2215 }
2216 const payload = event.payload;
2217 return Effect.sync(() => {
2218 NodeFS.appendFileSync(
2219 requestLogPath,
2220 payload.endsWith("\n") ? payload : `${payload}\n`,
2221 "utf8",
2222 );
2223 });
2224 },
2225 }
2226 : {},
2227 ),
2228 ),
2229 Effect.scoped,
2230 Effect.provide(NodeServices.layer),
2231 );
2232
2233 NodeRuntime.runMain(program);