Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 ProjectId,
4 MessageId,
5 NodeId,
6 RunAttemptId,
7 RunId,
8 type OrchestrationV2UserInputQuestion,
9 type OrchestrationV2RuntimeRequest,
10 ProviderInstanceId,
11 ProviderSessionId,
12 type RuntimeMode,
13 ThreadId,
14} from "@t3tools/contracts";
15import { GrokSettings } from "@t3tools/provider-grok/settings";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
18import * as EffectAcpErrors from "effect-acp/errors";
19import { xAiRateLimitedErrorCode } from "@t3tools/provider-grok/testing";
20import { assert, describe, it } from "@effect/vitest";
21import * as DateTime from "effect/DateTime";
22import * as Effect from "effect/Effect";
23import * as Deferred from "effect/Deferred";
24import * as FileSystem from "effect/FileSystem";
25import * as Path from "effect/Path";
26import * as Stream from "effect/Stream";
27import * as Layer from "effect/Layer";
28import * as PlatformError from "effect/PlatformError";
29import * as Schema from "effect/Schema";
30import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
31import type * as EffectAcpSchema from "effect-acp/compat";
32
33import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
34import * as ProjectStore from "../ProjectStore.ts";
35import { buildInitialGrokProviderSnapshot } from "@t3tools/provider-grok/testing";
36import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
37import * as ProviderInstanceRegistry from "../../provider/ProviderInstanceRegistry.ts";
38import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
39import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
40import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
41import { handoffBudget } from "@t3tools/provider-core/server/handoffBudget";
42import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
43import * as RuntimePolicy from "../RuntimePolicy.ts";
44import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
45import {
46 AcpProviderCapabilitiesV2,
47 acpCompletedTurnShouldTerminalizeTool,
48 acpSubagentStatusBlocksTurnSettlement,
49 acpSupportsImagePrompts,
50} from "@t3tools/provider-acp/server/adapter";
51import {
52 makeGrokAcpAdapterFlavor,
53 makeGrokAdapterV2,
54 GrokProviderCapabilitiesV2,
55 GROK_PROVIDER,
56 GROK_ACP_INITIALIZE_META,
57} from "@t3tools/provider-grok/testing";
58
59import { makeAcpReplayRuntime, type AcpReplayTranscript } from "./AcpAdapterV2.testkit.ts";
60
61const LAUNCH_TEST_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({
62 binaryPath: "grok-launch-test",
63});
64
65function permissionRequest(
66 kind: EffectAcpSchema.ToolKind,
67): EffectAcpSchema.RequestPermissionRequest {
68 return {
69 sessionId: "session-1",
70 options: [
71 { optionId: "allow-once", name: "Allow once", kind: "allow_once" },
72 { optionId: "allow-always", name: "Allow always", kind: "allow_always" },
73 { optionId: "reject-once", name: "Reject", kind: "reject_once" },
74 ],
75 toolCall: {
76 toolCallId: "tool-1",
77 title: "Test tool",
78 kind,
79 },
80 };
81}
82
83function runtimePolicy(input: {
84 readonly runtimeMode: RuntimeMode;
85 readonly approvalPolicy?: unknown;
86 readonly sandboxPolicy?: unknown;
87}) {
88 return ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
89 runtimeMode: input.runtimeMode,
90 interactionMode: "default",
91 cwd: "/workspace",
92 ...(input.approvalPolicy === undefined ? {} : { approvalPolicy: input.approvalPolicy }),
93 ...(input.sandboxPolicy === undefined ? {} : { sandboxPolicy: input.sandboxPolicy }),
94 });
95}
96
97describe("acpSubagentStatusBlocksTurnSettlement", () => {
98 it("blocks settlement for pending and running subagents", () => {
99 assert.isTrue(acpSubagentStatusBlocksTurnSettlement("pending"));
100 assert.isTrue(acpSubagentStatusBlocksTurnSettlement("running"));
101 });
102
103 it("does not block settlement for terminal subagents", () => {
104 assert.isFalse(acpSubagentStatusBlocksTurnSettlement("cancelled"));
105 assert.isFalse(acpSubagentStatusBlocksTurnSettlement("completed"));
106 assert.isFalse(acpSubagentStatusBlocksTurnSettlement("failed"));
107 assert.isFalse(acpSubagentStatusBlocksTurnSettlement("interrupted"));
108 });
109});
110
111describe("GrokAdapterV2 capabilities", () => {
112 it("preserves Grok's rate-limit stop and distinguishes other prompt failures", () => {
113 const flavor = makeGrokAcpAdapterFlavor(
114 {
115 makeRuntime: () => Effect.never,
116 } as unknown as Parameters<typeof makeGrokAcpAdapterFlavor>[0],
117 "/home/ada",
118 );
119 const limit = flavor.promptFailure?.(
120 new EffectAcpErrors.AcpRequestError({
121 code: xAiRateLimitedErrorCode,
122 errorMessage: "Grok usage limit reached. Try again later.",
123 }),
124 );
125 assert.equal(limit?.class, "usage_limit");
126 assert.equal(limit?.code, String(xAiRateLimitedErrorCode));
127 assert.equal(limit?.message, "Grok usage limit reached. Try again later.");
128 assert.equal(
129 flavor.promptFailure?.(
130 new EffectAcpErrors.AcpRequestError({
131 code: -32603,
132 errorMessage: "Internal error",
133 }),
134 ).class,
135 "provider_error",
136 );
137 assert.equal(
138 flavor.promptFailure?.(new Error("Rate limit mentioned in an ordinary error")).class,
139 "provider_error",
140 );
141 });
142
143 it("wires hard Stop teardown but soft non-Stop interrupts in the constructor flavor", () => {
144 const flavor = makeGrokAcpAdapterFlavor(
145 {
146 makeRuntime: () => Effect.never,
147 } as unknown as Parameters<typeof makeGrokAcpAdapterFlavor>[0],
148 "/home/ada",
149 );
150
151 assert.isFalse(flavor.interruptPromptOnCancel);
152 // User Stop (requestRuntimeRestart) keeps the hard process-group kill and
153 // respawn: Grok cancel is detach-and-continue, so only a process kill
154 // stops the work.
155 assert.isTrue(flavor.restartRuntimeAfterInterrupt);
156 assert.isTrue(flavor.terminateRuntimeProcessGroupOnInterrupt);
157 assert.isUndefined(flavor.restartRuntimeOnEveryInterrupt);
158 assert.isTrue(flavor.preserveRuntimeOnSettledInterrupt);
159 });
160
161 it("terminalizes only foreground tools under the actual Grok flavor", () => {
162 const flavor = makeGrokAcpAdapterFlavor(
163 {
164 makeRuntime: () => Effect.never,
165 } as unknown as Parameters<typeof makeGrokAcpAdapterFlavor>[0],
166 "/home/ada",
167 );
168 const foreground = {
169 toolCallId: "foreground-1",
170 title: "Terminal",
171 status: "inProgress" as const,
172 data: {
173 rawInput: { command: "true" },
174 rawOutput: { type: "Bash", exit_code: 0 },
175 },
176 };
177 const monitor = {
178 toolCallId: "monitor-1",
179 title: "Monitor",
180 status: "inProgress" as const,
181 data: {
182 rawInput: { variant: "Monitor", command: "sleep 30" },
183 rawOutput: {
184 type: "Monitor",
185 taskId: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3",
186 },
187 },
188 };
189 const subagent = {
190 toolCallId: "subagent-1",
191 title: "Task",
192 status: "inProgress" as const,
193 data: {
194 rawInput: {
195 description: "Inspect interrupt handling",
196 prompt: "Review the adapter.",
197 subagent_type: "generalPurpose",
198 },
199 },
200 };
201
202 assert.isTrue(acpCompletedTurnShouldTerminalizeTool(foreground, flavor));
203 assert.isFalse(acpCompletedTurnShouldTerminalizeTool(monitor, flavor));
204 assert.isFalse(acpCompletedTurnShouldTerminalizeTool(subagent, flavor));
205 });
206
207 it("keeps optional protocol features conservative until a flavor or handshake confirms them", () => {
208 assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsModelSwitchInSession);
209 assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsRuntimeModeSwitchInSession);
210 assert.isFalse(AcpProviderCapabilitiesV2.threads.canReadThreadSnapshot);
211 assert.isFalse(AcpProviderCapabilitiesV2.tools.supportsMcpTools);
212 });
213
214 it("overrides ACP image capability false so screenshot attachments can prompt", () => {
215 assert.isFalse(
216 acpSupportsImagePrompts({
217 negotiatedImage: false,
218 }),
219 );
220 assert.isTrue(
221 acpSupportsImagePrompts({
222 flavorSupportsImagePrompts: true,
223 negotiatedImage: false,
224 }),
225 );
226 assert.isTrue(
227 acpSupportsImagePrompts({
228 negotiatedImage: true,
229 }),
230 );
231 });
232
233 it("declares Grok Task envelopes as native subagents", () => {
234 assert.isFalse(GrokProviderCapabilitiesV2.threads.canForkThread);
235 assert.isTrue(GrokProviderCapabilitiesV2.subagents.supportsSubagents);
236 assert.isTrue(GrokProviderCapabilitiesV2.subagents.exposesSubagentThreadIds);
237 assert.isTrue(GrokProviderCapabilitiesV2.subagents.emitsSubagentLifecycle);
238 assert.isFalse(GrokProviderCapabilitiesV2.turns.supportsActiveSteering);
239 assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsInterrupt);
240 assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsSteeringByInterruptRestart);
241 assert.isTrue(GrokProviderCapabilitiesV2.context.supportsFullThreadHandoff);
242 });
243
244 it("declares the optional ACP features verified by the Grok handshake", () => {
245 assert.isTrue(GrokProviderCapabilitiesV2.sessions.supportsModelSwitchInSession);
246 assert.isTrue(GrokProviderCapabilitiesV2.threads.canReadThreadSnapshot);
247 assert.isTrue(GrokProviderCapabilitiesV2.tools.supportsMcpTools);
248 assert.isTrue(GrokProviderCapabilitiesV2.checkpointing.providerCanReadConversationSnapshot);
249 });
250});
251
252describe("ACP permission policy", () => {
253 it("honors explicit on-request approval over full-access runtime mode", () => {
254 assert.equal(
255 acpPermissionDisposition(
256 runtimePolicy({
257 runtimeMode: "full-access",
258 approvalPolicy: "on-request",
259 sandboxPolicy: { type: "readOnly" },
260 }),
261 permissionRequest("execute"),
262 ),
263 "ask",
264 );
265 });
266
267 it("rejects mutating escalation under a non-interactive read-only policy", () => {
268 const policy = runtimePolicy({
269 runtimeMode: "full-access",
270 approvalPolicy: "never",
271 sandboxPolicy: { type: "readOnly" },
272 });
273 assert.equal(acpPermissionDisposition(policy, permissionRequest("execute")), "deny");
274 assert.equal(acpPermissionDisposition(policy, permissionRequest("edit")), "deny");
275 assert.equal(acpPermissionDisposition(policy, permissionRequest("read")), "allow");
276 });
277
278 it("auto-approves requests only when the resolved policy permits them", () => {
279 assert.equal(
280 acpPermissionDisposition(
281 runtimePolicy({
282 runtimeMode: "full-access",
283 approvalPolicy: "never",
284 sandboxPolicy: { type: "dangerFullAccess" },
285 }),
286 permissionRequest("execute"),
287 ),
288 "allow",
289 );
290 assert.equal(
291 acpPermissionDisposition(
292 runtimePolicy({ runtimeMode: "approval-required" }),
293 permissionRequest("edit"),
294 ),
295 "ask",
296 );
297 assert.equal(
298 acpPermissionDisposition(
299 runtimePolicy({ runtimeMode: "approval-required" }),
300 permissionRequest("read"),
301 ),
302 "allow",
303 );
304 });
305});
306
307describe("Grok permission prompts", () => {
308 const disposition = makeGrokAcpAdapterFlavor(
309 {
310 makeRuntime: () => Effect.never,
311 } as unknown as Parameters<typeof makeGrokAcpAdapterFlavor>[0],
312 "/home/ada",
313 ).permissionDisposition;
314
315 it("leaves Auto prompts to the user unless an explicit policy launched Grok asking", () => {
316 assert.equal(
317 disposition?.(runtimePolicy({ runtimeMode: "auto" }), permissionRequest("read")),
318 "ask",
319 );
320 const readOnly = runtimePolicy({
321 runtimeMode: "auto",
322 approvalPolicy: "never",
323 sandboxPolicy: { type: "readOnly" },
324 });
325 assert.equal(disposition?.(readOnly, permissionRequest("execute")), "deny");
326 assert.equal(
327 disposition?.(runtimePolicy({ runtimeMode: "approval-required" }), permissionRequest("edit")),
328 "ask",
329 );
330 });
331});
332
333describe("Grok model context windows", () => {
334 const layerHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer));
335 const layerTest = Layer.mergeAll(
336 NodeServices.layer,
337 IdAllocator.layer,
338 McpProviderSessions.layer,
339 layerHost,
340 );
341
342 it.effect("budgets handoffs with the selected Grok model's window", () =>
343 Effect.gen(function* () {
344 const instanceId = ProviderInstanceId.make("grok-window-test");
345 const threadId = ThreadId.make("grok-window-test");
346 const modelSelection = { instanceId, model: "grok-build" };
347 const policy = runtimePolicy({ runtimeMode: "full-access" });
348 const path = yield* Path.Path;
349 const mockAgentPath = yield* path.fromFileUrl(
350 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
351 );
352 const adapter = yield* makeGrokAdapterV2({
353 instanceId,
354 settings: LAUNCH_TEST_GROK_SETTINGS,
355 environment: {},
356 hostPlatform: "linux",
357 selfInvocation: yield* resolveSelfInvocation(),
358 makeRuntime: (input) =>
359 Effect.gen(function* () {
360 const context = yield* Layer.build(
361 AcpSessionRuntime.layer({
362 ...input,
363 spawn: {
364 command: process.execPath,
365 args: [mockAgentPath],
366 cwd: process.cwd(),
367 env: {
368 T3_ACP_SESSION_LIFECYCLE: "1",
369 T3_ACP_GROK_MODEL: "grok-4.7",
370 T3_ACP_GROK_CONTEXT_TOKENS: "256000",
371 },
372 },
373 authMethodId: "test",
374 }),
375 );
376 return yield* AcpSessionRuntime.AcpSessionRuntime.pipe(Effect.provide(context));
377 }),
378 });
379 const runtime = yield* adapter.openSession({
380 threadId,
381 providerSessionId: ProviderSessionId.make("grok-window-test"),
382 modelSelection,
383 runtimePolicy: policy,
384 });
385 const providerThread = yield* runtime.ensureThread({
386 threadId,
387 modelSelection,
388 runtimePolicy: policy,
389 });
390 const budgetInput = {
391 tokenCap: 16_000,
392 userText: "Continue",
393 attachments: [],
394 providerThread,
395 nativeContextEstimate: 160_684,
396 };
397 assert.isNull(providerThread.contextUsage);
398 assert.equal(handoffBudget(budgetInput), 0);
399 assert.equal(
400 handoffBudget({
401 ...budgetInput,
402 modelContextWindow: runtime.getModelContextWindow?.({ instanceId, model: "grok-4.7" }),
403 }),
404 16_000,
405 );
406 assert.equal(runtime.getModelContextWindow?.({ instanceId, model: "grok-4.7" }), 256_000);
407 assert.equal(runtime.getModelContextWindow?.({ instanceId, model: " grok-4.7 " }), 256_000);
408 for (const model of ["custom-model", "grok-build", "toString"]) {
409 assert.isUndefined(runtime.getModelContextWindow?.({ instanceId, model }));
410 }
411 assert.isUndefined(
412 runtime.getModelContextWindow?.({
413 instanceId: ProviderInstanceId.make("another-grok"),
414 model: "grok-4.7",
415 }),
416 );
417 }).pipe(Effect.scoped, Effect.provide(layerTest)),
418 );
419});
420
421describe("Grok launch permission mode", () => {
422 const layerHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer));
423 const layerTest = Layer.mergeAll(
424 NodeServices.layer,
425 IdAllocator.layer,
426 McpProviderSessions.layer,
427 layerHost,
428 );
429
430 const launchArgs = (runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy) =>
431 Effect.gen(function* () {
432 const launches: Array<ReadonlyArray<string>> = [];
433 const childProcessSpawner = ChildProcessSpawner.make((command) => {
434 if (command._tag === "StandardCommand") launches.push(command.args);
435 return Effect.fail(
436 PlatformError.systemError({
437 _tag: "NotFound",
438 module: "grok-launch-test",
439 method: "spawn",
440 }),
441 );
442 });
443 const instanceId = ProviderInstanceId.make("grok-launch-test");
444 const adapter = yield* makeGrokAdapterV2({
445 instanceId,
446 settings: LAUNCH_TEST_GROK_SETTINGS,
447 environment: {},
448 hostPlatform: "darwin",
449 selfInvocation: yield* resolveSelfInvocation(),
450 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner));
451 yield* adapter
452 .openSession({
453 threadId: ThreadId.make("grok-launch-test"),
454 providerSessionId: ProviderSessionId.make("grok-launch-test"),
455 modelSelection: { instanceId, model: "grok-build" },
456 runtimePolicy,
457 })
458 .pipe(Effect.scoped, Effect.ignore);
459 return launches;
460 }).pipe(Effect.provideService(HostProcess.Platform, "darwin"), Effect.provide(layerTest));
461
462 const policy = (
463 runtimeMode: RuntimeMode,
464 override: Partial<ProviderAdapter.ProviderAdapterV2RuntimePolicy> = {},
465 ) =>
466 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
467 runtimeMode,
468 interactionMode: "default",
469 cwd: process.cwd(),
470 ...override,
471 });
472
473 it.effect.each(
474 (
475 [
476 ["approval-required", ["--permission-mode", "default", "agent", "stdio"]],
477 ["auto", ["--permission-mode", "auto", "agent", "stdio"]],
478 ["full-access", ["agent", "--always-approve", "stdio"]],
479 ] as const
480 ).map(([runtimeMode, args]) => [runtimeMode, args.join(" "), args] as const),
481 )("launches %s threads with %s", ([runtimeMode, , args]) =>
482 Effect.gen(function* () {
483 assert.deepEqual(yield* launchArgs(policy(runtimeMode)), [args]);
484 }),
485 );
486
487 it.effect("launches a thread stored as Auto-accept edits asking", () =>
488 Effect.gen(function* () {
489 const snapshot = yield* buildInitialGrokProviderSnapshot(LAUNCH_TEST_GROK_SETTINGS);
490 const instanceId = ProviderInstanceId.make("grok-launch-test");
491 const now = yield* DateTime.now;
492 const threadId = ThreadId.make("grok-launch-test");
493 const modelSelection = { instanceId, model: "grok-build" } as const;
494 const resolved = yield* Effect.gen(function* () {
495 const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
496 return yield* runtimePolicy.resolve({
497 thread: {
498 createdBy: "user",
499 creationSource: "web",
500 id: threadId,
501 projectId: ProjectId.make("grok-launch-test"),
502 title: "Grok launch test",
503 providerInstanceId: instanceId,
504 modelSelection,
505 runtimeMode: "auto-accept-edits",
506 interactionMode: "default",
507 branch: null,
508 worktreePath: process.cwd(),
509 activeProviderThreadId: null,
510 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
511 forkedFrom: null,
512 createdAt: now,
513 updatedAt: now,
514 archivedAt: null,
515 settledOverride: null,
516 settledAt: null,
517 lastVisitedAt: null,
518 deletedAt: null,
519 },
520 modelSelection,
521 });
522 }).pipe(
523 Effect.provide(
524 RuntimePolicy.layerFromProjectStore.pipe(
525 Layer.provide(
526 Layer.mock(ProjectStore.ProjectStoreV2)({
527 get: () => Effect.die("the thread has a worktree"),
528 }),
529 ),
530 Layer.provide(
531 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
532 getInstance: () =>
533 Effect.succeed({
534 snapshot: { getSnapshot: Effect.succeed(snapshot) },
535 } as ProviderInstance),
536 }),
537 ),
538 ),
539 ),
540 );
541 assert.equal(resolved.runtimeMode, "approval-required");
542 assert.deepEqual(yield* launchArgs(resolved), [
543 ["--permission-mode", "default", "agent", "stdio"],
544 ]);
545 }),
546 );
547
548 it.effect("launches asking when an explicit approval or sandbox policy governs the thread", () =>
549 Effect.gen(function* () {
550 const asking = [["--permission-mode", "default", "agent", "stdio"]];
551 assert.deepEqual(
552 yield* launchArgs(
553 policy("full-access", {
554 approvalPolicy: "never",
555 sandboxPolicy: { type: "workspaceWrite", writableRoots: [], networkAccess: false },
556 }),
557 ),
558 asking,
559 );
560 assert.deepEqual(
561 yield* launchArgs(policy("full-access", { approvalPolicy: "on-request" })),
562 asking,
563 );
564 }),
565 );
566});
567
568describe("Grok native questions", () => {
569 const layerHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer));
570 const layerTest = Layer.mergeAll(
571 NodeServices.layer,
572 IdAllocator.layer,
573 McpProviderSessions.layer,
574 layerHost,
575 );
576
577 it.live("keeps x.ai multi-select questions live and returns all selected answers", () =>
578 Effect.gen(function* () {
579 const fs = yield* FileSystem.FileSystem;
580 const path = yield* Path.Path;
581 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
582 const workspace = yield* fs.makeTempDirectoryScoped({ prefix: "grok-multi-select-" });
583 const questionText = "Which changes should be included?";
584 const transcript: AcpReplayTranscript = {
585 provider: GROK_PROVIDER,
586 protocol: "acp.ndjson-jsonrpc",
587 version: "1",
588 scenario: "grok-multi-select",
589 entries: [
590 {
591 type: "expect_outbound",
592 label: "initialize",
593 frame: { kind: "request", method: "initialize", params: "<any>" },
594 },
595 {
596 type: "emit_inbound",
597 label: "initialized",
598 frame: {
599 kind: "response",
600 method: "initialize",
601 result: {
602 protocolVersion: 1,
603 agentCapabilities: { loadSession: true, promptCapabilities: { image: false } },
604 authMethods: [{ id: "replay", name: "Replay" }],
605 },
606 },
607 },
608 {
609 type: "expect_outbound",
610 label: "session.new",
611 frame: { kind: "request", method: "session/new", params: "<any>" },
612 },
613 {
614 type: "emit_inbound",
615 label: "session.created",
616 frame: {
617 kind: "response",
618 method: "session/new",
619 result: {
620 sessionId: "grok-multi-select-session",
621 models: {
622 currentModelId: "grok-build",
623 availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
624 },
625 },
626 },
627 },
628 {
629 type: "expect_outbound",
630 label: "prompt",
631 frame: { kind: "request", method: "session/prompt", params: "<any>" },
632 },
633 {
634 type: "emit_inbound",
635 label: "question",
636 frame: {
637 kind: "request",
638 method: "_x.ai/ask_user_question",
639 params: {
640 method: "x.ai/ask_user_question",
641 params: {
642 sessionId: "grok-multi-select-session",
643 toolCallId: "grok-question",
644 mode: "default",
645 questions: [
646 {
647 id: "changes",
648 question: questionText,
649 multiSelect: true,
650 options: [
651 { label: "Tests", description: "Cover behavior" },
652 { label: "Docs", description: "Explain usage" },
653 ],
654 },
655 ],
656 },
657 },
658 },
659 },
660 {
661 type: "expect_outbound",
662 label: "selected answers",
663 frame: {
664 kind: "response",
665 method: "_x.ai/ask_user_question",
666 result: { outcome: "accepted", answers: { [questionText]: ["Tests", "Docs"] } },
667 },
668 },
669 {
670 type: "emit_inbound",
671 label: "complete",
672 frame: {
673 kind: "response",
674 method: "session/prompt",
675 result: { stopReason: "end_turn" },
676 },
677 },
678 ],
679 };
680 const statusPath = path.join(workspace, "status.json");
681 const scriptPath = yield* path.fromFileUrl(
682 new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
683 );
684 const instanceId = ProviderInstanceId.make("grok-multi-select");
685 const threadId = ThreadId.make("grok-multi-select-thread");
686 const adapter = yield* makeGrokAdapterV2({
687 instanceId,
688 settings: LAUNCH_TEST_GROK_SETTINGS,
689 environment: {},
690 hostPlatform: "darwin",
691 selfInvocation: yield* resolveSelfInvocation(),
692 makeRuntime: makeAcpReplayRuntime({
693 transcript,
694 statusPath,
695 scriptPath,
696 childProcessSpawner,
697 fileSystem: fs,
698 initializeMeta: GROK_ACP_INITIALIZE_META,
699 }),
700 });
701 const policy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
702 runtimeMode: "approval-required",
703 interactionMode: "default",
704 cwd: workspace,
705 });
706 const modelSelection = { instanceId, model: "grok-build" };
707 const runtime = yield* adapter.openSession({
708 threadId,
709 providerSessionId: ProviderSessionId.make("grok-multi-select-session"),
710 modelSelection,
711 runtimePolicy: policy,
712 });
713 const providerThread = yield* runtime.ensureThread({
714 threadId,
715 modelSelection,
716 runtimePolicy: policy,
717 });
718 const question = yield* Deferred.make<OrchestrationV2UserInputQuestion>();
719 const request = yield* Deferred.make<OrchestrationV2RuntimeRequest>();
720 const terminal = yield* Deferred.make<void>();
721 yield* runtime.events.pipe(
722 Stream.runForEach((event) => {
723 if (
724 event.type === "turn_item.updated" &&
725 event.turnItem.type === "user_input_request" &&
726 event.turnItem.questions[0]
727 )
728 return Deferred.succeed(question, event.turnItem.questions[0]);
729 if (event.type === "runtime_request.updated")
730 return Deferred.succeed(request, event.runtimeRequest);
731 if (event.type === "turn.terminal") return Deferred.succeed(terminal, undefined);
732 return Effect.void;
733 }),
734 Effect.forkScoped,
735 );
736 const now = yield* DateTime.now;
737 yield* runtime.startTurn({
738 appThread: {
739 createdBy: "user",
740 creationSource: "web",
741 id: threadId,
742 projectId: ProjectId.make("grok-multi-select-project"),
743 title: "Grok multi-select",
744 providerInstanceId: instanceId,
745 modelSelection,
746 runtimeMode: "approval-required",
747 interactionMode: "default",
748 branch: null,
749 worktreePath: workspace,
750 activeProviderThreadId: providerThread.id,
751 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
752 forkedFrom: null,
753 createdAt: now,
754 updatedAt: now,
755 archivedAt: null,
756 settledOverride: null,
757 settledAt: null,
758 lastVisitedAt: null,
759 deletedAt: null,
760 },
761 threadId,
762 runId: RunId.make("grok-multi-select-run"),
763 runOrdinal: 1,
764 providerTurnOrdinal: 1,
765 attemptId: RunAttemptId.make("grok-multi-select-attempt"),
766 rootNodeId: NodeId.make("grok-multi-select-root"),
767 providerThread,
768 message: {
769 createdBy: "user",
770 creationSource: "web",
771 messageId: MessageId.make("grok-multi-select-message"),
772 text: "Ask which changes to include.",
773 attachments: [],
774 },
775 modelSelection,
776 runtimePolicy: policy,
777 });
778 assert.deepEqual(yield* Deferred.await(question), {
779 id: "changes",
780 header: "Question",
781 question: questionText,
782 multiSelect: true,
783 options: [
784 { label: "Tests", description: "Cover behavior" },
785 { label: "Docs", description: "Explain usage" },
786 ],
787 });
788 const pending = yield* Deferred.await(request);
789 assert.equal(pending.kind, "user_input");
790 assert.equal(pending.responseCapability.type, "live");
791 yield* runtime.respondToRuntimeRequest({
792 requestId: pending.id,
793 answers: { changes: ["Tests", "Docs"] },
794 });
795 yield* Deferred.await(terminal);
796 }).pipe(Effect.scoped, Effect.provide(layerTest)),
797 );
798});