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