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 ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
41import * as RuntimePolicy from "../RuntimePolicy.ts";
42import * as ServerSettings from "../../serverSettings.ts";
43import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
44import { acpCompletedTurnShouldTerminalizeTool } from "@t3tools/provider-acp/server/adapter";
45import {
46 makeGrokAcpAdapterFlavor,
47 makeGrokAdapterV2,
48 GROK_PROVIDER,
49 GROK_ACP_INITIALIZE_META,
50} from "@t3tools/provider-grok/testing";
51
52import { makeAcpReplayRuntime, type AcpReplayTranscript } from "./AcpAdapterV2.testkit.ts";
53
54const LAUNCH_TEST_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({
55 binaryPath: "grok-launch-test",
56});
57
58function permissionRequest(
59 kind: EffectAcpSchema.ToolKind,
60): EffectAcpSchema.RequestPermissionRequest {
61 return {
62 sessionId: "session-1",
63 options: [
64 { optionId: "allow-once", name: "Allow once", kind: "allow_once" },
65 { optionId: "allow-always", name: "Allow always", kind: "allow_always" },
66 { optionId: "reject-once", name: "Reject", kind: "reject_once" },
67 ],
68 toolCall: {
69 toolCallId: "tool-1",
70 title: "Test tool",
71 kind,
72 },
73 };
74}
75
76function runtimePolicy(input: {
77 readonly runtimeMode: RuntimeMode;
78 readonly approvalPolicy?: unknown;
79 readonly sandboxPolicy?: unknown;
80}) {
81 return ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
82 runtimeMode: input.runtimeMode,
83 interactionMode: "default",
84 cwd: "/workspace",
85 ...(input.approvalPolicy === undefined ? {} : { approvalPolicy: input.approvalPolicy }),
86 ...(input.sandboxPolicy === undefined ? {} : { sandboxPolicy: input.sandboxPolicy }),
87 });
88}
89
90describe("GrokAdapterV2 capabilities", () => {
91 it("preserves Grok's rate-limit stop and distinguishes other prompt failures", () => {
92 const flavor = makeGrokAcpAdapterFlavor(
93 {
94 makeRuntime: () => Effect.never,
95 } as unknown as Parameters<typeof makeGrokAcpAdapterFlavor>[0],
96 "/home/ada",
97 );
98 const limit = flavor.promptFailure?.(
99 new EffectAcpErrors.AcpRequestError({
100 code: xAiRateLimitedErrorCode,
101 errorMessage: "Grok usage limit reached. Try again later.",
102 }),
103 );
104 assert.equal(limit?.class, "usage_limit");
105 assert.equal(limit?.code, String(xAiRateLimitedErrorCode));
106 assert.equal(limit?.message, "Grok usage limit reached. Try again later.");
107 assert.equal(
108 flavor.promptFailure?.(
109 new EffectAcpErrors.AcpRequestError({
110 code: -32603,
111 errorMessage: "Internal error",
112 }),
113 ).class,
114 "provider_error",
115 );
116 assert.equal(
117 flavor.promptFailure?.(new Error("Rate limit mentioned in an ordinary error")).class,
118 "provider_error",
119 );
120 });
121
122 it("terminalizes only foreground tools under the actual Grok flavor", () => {
123 const flavor = makeGrokAcpAdapterFlavor(
124 {
125 makeRuntime: () => Effect.never,
126 } as unknown as Parameters<typeof makeGrokAcpAdapterFlavor>[0],
127 "/home/ada",
128 );
129 const foreground = {
130 toolCallId: "foreground-1",
131 title: "Terminal",
132 status: "inProgress" as const,
133 data: {
134 rawInput: { command: "true" },
135 rawOutput: { type: "Bash", exit_code: 0 },
136 },
137 };
138 const monitor = {
139 toolCallId: "monitor-1",
140 title: "Monitor",
141 status: "inProgress" as const,
142 data: {
143 rawInput: { variant: "Monitor", command: "sleep 30" },
144 rawOutput: {
145 type: "Monitor",
146 taskId: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3",
147 },
148 },
149 };
150 const subagent = {
151 toolCallId: "subagent-1",
152 title: "Task",
153 status: "inProgress" as const,
154 data: {
155 rawInput: {
156 description: "Inspect interrupt handling",
157 prompt: "Review the adapter.",
158 subagent_type: "generalPurpose",
159 },
160 },
161 };
162
163 assert.isTrue(acpCompletedTurnShouldTerminalizeTool(foreground, flavor));
164 assert.isFalse(acpCompletedTurnShouldTerminalizeTool(monitor, flavor));
165 assert.isFalse(acpCompletedTurnShouldTerminalizeTool(subagent, flavor));
166 });
167});
168
169describe("ACP permission policy", () => {
170 it("rejects mutating escalation under a non-interactive read-only policy", () => {
171 const policy = runtimePolicy({
172 runtimeMode: "full-access",
173 approvalPolicy: "never",
174 sandboxPolicy: { type: "readOnly" },
175 });
176 assert.equal(acpPermissionDisposition(policy, permissionRequest("execute")), "deny");
177 assert.equal(acpPermissionDisposition(policy, permissionRequest("edit")), "deny");
178 assert.equal(acpPermissionDisposition(policy, permissionRequest("read")), "allow");
179 });
180
181 it("auto-approves requests only when the resolved policy permits them", () => {
182 assert.equal(
183 acpPermissionDisposition(
184 runtimePolicy({
185 runtimeMode: "full-access",
186 approvalPolicy: "never",
187 sandboxPolicy: { type: "dangerFullAccess" },
188 }),
189 permissionRequest("execute"),
190 ),
191 "allow",
192 );
193 assert.equal(
194 acpPermissionDisposition(
195 runtimePolicy({ runtimeMode: "approval-required" }),
196 permissionRequest("edit"),
197 ),
198 "ask",
199 );
200 assert.equal(
201 acpPermissionDisposition(
202 runtimePolicy({ runtimeMode: "approval-required" }),
203 permissionRequest("read"),
204 ),
205 "allow",
206 );
207 });
208});
209
210describe("Grok permission prompts", () => {
211 const disposition = makeGrokAcpAdapterFlavor(
212 {
213 makeRuntime: () => Effect.never,
214 } as unknown as Parameters<typeof makeGrokAcpAdapterFlavor>[0],
215 "/home/ada",
216 ).permissionDisposition;
217
218 it("leaves Auto prompts to the user unless an explicit policy launched Grok asking", () => {
219 assert.equal(
220 disposition?.(runtimePolicy({ runtimeMode: "auto" }), permissionRequest("read")),
221 "ask",
222 );
223 const readOnly = runtimePolicy({
224 runtimeMode: "auto",
225 approvalPolicy: "never",
226 sandboxPolicy: { type: "readOnly" },
227 });
228 assert.equal(disposition?.(readOnly, permissionRequest("execute")), "deny");
229 assert.equal(
230 disposition?.(runtimePolicy({ runtimeMode: "approval-required" }), permissionRequest("edit")),
231 "ask",
232 );
233 });
234});
235
236describe("Grok launch permission mode", () => {
237 const layerHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer));
238 const layerTest = Layer.mergeAll(
239 NodeServices.layer,
240 IdAllocator.layer,
241 McpProviderSessions.layer,
242 layerHost,
243 );
244
245 const launchArgs = (runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy) =>
246 Effect.gen(function* () {
247 const launches: Array<ReadonlyArray<string>> = [];
248 const childProcessSpawner = ChildProcessSpawner.make((command) => {
249 if (command._tag === "StandardCommand") launches.push(command.args);
250 return Effect.fail(
251 PlatformError.systemError({
252 _tag: "NotFound",
253 module: "grok-launch-test",
254 method: "spawn",
255 }),
256 );
257 });
258 const instanceId = ProviderInstanceId.make("grok-launch-test");
259 const adapter = yield* makeGrokAdapterV2({
260 instanceId,
261 settings: LAUNCH_TEST_GROK_SETTINGS,
262 environment: {},
263 hostPlatform: "darwin",
264 selfInvocation: yield* resolveSelfInvocation(),
265 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner));
266 yield* adapter
267 .openSession({
268 threadId: ThreadId.make("grok-launch-test"),
269 providerSessionId: ProviderSessionId.make("grok-launch-test"),
270 modelSelection: { instanceId, model: "grok-build" },
271 runtimePolicy,
272 })
273 .pipe(Effect.scoped, Effect.ignore);
274 return launches;
275 }).pipe(Effect.provideService(HostProcess.Platform, "darwin"), Effect.provide(layerTest));
276
277 const policy = (
278 runtimeMode: RuntimeMode,
279 override: Partial<ProviderAdapter.ProviderAdapterV2RuntimePolicy> = {},
280 ) =>
281 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
282 runtimeMode,
283 interactionMode: "default",
284 cwd: process.cwd(),
285 ...override,
286 });
287
288 it.effect.each(
289 (
290 [
291 ["approval-required", ["--permission-mode", "default", "agent", "stdio"]],
292 ["auto", ["--permission-mode", "auto", "agent", "stdio"]],
293 ["full-access", ["agent", "--always-approve", "stdio"]],
294 ] as const
295 ).map(([runtimeMode, args]) => [runtimeMode, args.join(" "), args] as const),
296 )("launches %s threads with %s", ([runtimeMode, , args]) =>
297 Effect.gen(function* () {
298 assert.deepEqual(yield* launchArgs(policy(runtimeMode)), [args]);
299 }),
300 );
301
302 it.effect("launches a thread stored as Auto-accept edits asking", () =>
303 Effect.gen(function* () {
304 const snapshot = yield* buildInitialGrokProviderSnapshot(LAUNCH_TEST_GROK_SETTINGS);
305 const instanceId = ProviderInstanceId.make("grok-launch-test");
306 const now = yield* DateTime.now;
307 const threadId = ThreadId.make("grok-launch-test");
308 const modelSelection = { instanceId, model: "grok-build" } as const;
309 const resolved = yield* Effect.gen(function* () {
310 const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
311 return yield* runtimePolicy.resolve({
312 thread: {
313 createdBy: "user",
314 creationSource: "web",
315 id: threadId,
316 projectId: ProjectId.make("grok-launch-test"),
317 title: "Grok launch test",
318 providerInstanceId: instanceId,
319 modelSelection,
320 runtimeMode: "auto-accept-edits",
321 interactionMode: "default",
322 branch: null,
323 worktreePath: process.cwd(),
324 activeProviderThreadId: null,
325 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
326 forkedFrom: null,
327 createdAt: now,
328 updatedAt: now,
329 archivedAt: null,
330 settledOverride: null,
331 settledAt: null,
332 lastVisitedAt: null,
333 deletedAt: null,
334 },
335 modelSelection,
336 });
337 }).pipe(
338 Effect.provide(
339 RuntimePolicy.layerFromProjectStore.pipe(
340 Layer.provide(ServerSettings.layerTest()),
341 Layer.provide(
342 Layer.mock(ProjectStore.ProjectStoreV2)({
343 get: () => Effect.die("the thread has a worktree"),
344 }),
345 ),
346 Layer.provide(
347 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
348 getInstance: () =>
349 Effect.succeed({
350 snapshot: { getSnapshot: Effect.succeed(snapshot) },
351 } as ProviderInstance),
352 }),
353 ),
354 ),
355 ),
356 );
357 assert.equal(resolved.runtimeMode, "approval-required");
358 assert.deepEqual(yield* launchArgs(resolved), [
359 ["--permission-mode", "default", "agent", "stdio"],
360 ]);
361 }),
362 );
363});
364
365describe("Grok native questions", () => {
366 const layerHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer));
367 const layerTest = Layer.mergeAll(
368 NodeServices.layer,
369 IdAllocator.layer,
370 McpProviderSessions.layer,
371 layerHost,
372 );
373
374 it.live("keeps x.ai multi-select questions live and returns all selected answers", () =>
375 Effect.gen(function* () {
376 const fs = yield* FileSystem.FileSystem;
377 const path = yield* Path.Path;
378 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
379 const workspace = yield* fs.makeTempDirectoryScoped({ prefix: "grok-multi-select-" });
380 const questionText = "Which changes should be included?";
381 const transcript: AcpReplayTranscript = {
382 provider: GROK_PROVIDER,
383 protocol: "acp.ndjson-jsonrpc",
384 version: "1",
385 scenario: "grok-multi-select",
386 entries: [
387 {
388 type: "expect_outbound",
389 label: "initialize",
390 frame: { kind: "request", method: "initialize", params: "<any>" },
391 },
392 {
393 type: "emit_inbound",
394 label: "initialized",
395 frame: {
396 kind: "response",
397 method: "initialize",
398 result: {
399 protocolVersion: 1,
400 agentCapabilities: { loadSession: true, promptCapabilities: { image: false } },
401 authMethods: [{ id: "replay", name: "Replay" }],
402 },
403 },
404 },
405 {
406 type: "expect_outbound",
407 label: "session.new",
408 frame: { kind: "request", method: "session/new", params: "<any>" },
409 },
410 {
411 type: "emit_inbound",
412 label: "session.created",
413 frame: {
414 kind: "response",
415 method: "session/new",
416 result: {
417 sessionId: "grok-multi-select-session",
418 models: {
419 currentModelId: "grok-build",
420 availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
421 },
422 },
423 },
424 },
425 {
426 type: "expect_outbound",
427 label: "prompt",
428 frame: { kind: "request", method: "session/prompt", params: "<any>" },
429 },
430 {
431 type: "emit_inbound",
432 label: "question",
433 frame: {
434 kind: "request",
435 method: "_x.ai/ask_user_question",
436 params: {
437 method: "x.ai/ask_user_question",
438 params: {
439 sessionId: "grok-multi-select-session",
440 toolCallId: "grok-question",
441 mode: "default",
442 questions: [
443 {
444 id: "changes",
445 question: questionText,
446 multiSelect: true,
447 options: [
448 { label: "Tests", description: "Cover behavior" },
449 { label: "Docs", description: "Explain usage" },
450 ],
451 },
452 ],
453 },
454 },
455 },
456 },
457 {
458 type: "expect_outbound",
459 label: "selected answers",
460 frame: {
461 kind: "response",
462 method: "_x.ai/ask_user_question",
463 result: { outcome: "accepted", answers: { [questionText]: ["Tests", "Docs"] } },
464 },
465 },
466 {
467 type: "emit_inbound",
468 label: "complete",
469 frame: {
470 kind: "response",
471 method: "session/prompt",
472 result: { stopReason: "end_turn" },
473 },
474 },
475 ],
476 };
477 const statusPath = path.join(workspace, "status.json");
478 const scriptPath = yield* path.fromFileUrl(
479 new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
480 );
481 const instanceId = ProviderInstanceId.make("grok-multi-select");
482 const threadId = ThreadId.make("grok-multi-select-thread");
483 const adapter = yield* makeGrokAdapterV2({
484 instanceId,
485 settings: LAUNCH_TEST_GROK_SETTINGS,
486 environment: {},
487 hostPlatform: "darwin",
488 selfInvocation: yield* resolveSelfInvocation(),
489 makeRuntime: makeAcpReplayRuntime({
490 transcript,
491 statusPath,
492 scriptPath,
493 childProcessSpawner,
494 fileSystem: fs,
495 initializeMeta: GROK_ACP_INITIALIZE_META,
496 }),
497 });
498 const policy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
499 runtimeMode: "approval-required",
500 interactionMode: "default",
501 cwd: workspace,
502 });
503 const modelSelection = { instanceId, model: "grok-build" };
504 const runtime = yield* adapter.openSession({
505 threadId,
506 providerSessionId: ProviderSessionId.make("grok-multi-select-session"),
507 modelSelection,
508 runtimePolicy: policy,
509 });
510 const providerThread = yield* runtime.ensureThread({
511 threadId,
512 modelSelection,
513 runtimePolicy: policy,
514 });
515 const question = yield* Deferred.make<OrchestrationV2UserInputQuestion>();
516 const request = yield* Deferred.make<OrchestrationV2RuntimeRequest>();
517 const terminal = yield* Deferred.make<void>();
518 yield* runtime.events.pipe(
519 Stream.runForEach((event) => {
520 if (
521 event.type === "turn_item.updated" &&
522 event.turnItem.type === "user_input_request" &&
523 event.turnItem.questions[0]
524 )
525 return Deferred.succeed(question, event.turnItem.questions[0]);
526 if (event.type === "runtime_request.updated")
527 return Deferred.succeed(request, event.runtimeRequest);
528 if (event.type === "turn.terminal") return Deferred.succeed(terminal, undefined);
529 return Effect.void;
530 }),
531 Effect.forkScoped,
532 );
533 const now = yield* DateTime.now;
534 yield* runtime.startTurn({
535 appThread: {
536 createdBy: "user",
537 creationSource: "web",
538 id: threadId,
539 projectId: ProjectId.make("grok-multi-select-project"),
540 title: "Grok multi-select",
541 providerInstanceId: instanceId,
542 modelSelection,
543 runtimeMode: "approval-required",
544 interactionMode: "default",
545 branch: null,
546 worktreePath: workspace,
547 activeProviderThreadId: providerThread.id,
548 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
549 forkedFrom: null,
550 createdAt: now,
551 updatedAt: now,
552 archivedAt: null,
553 settledOverride: null,
554 settledAt: null,
555 lastVisitedAt: null,
556 deletedAt: null,
557 },
558 threadId,
559 runId: RunId.make("grok-multi-select-run"),
560 runOrdinal: 1,
561 providerTurnOrdinal: 1,
562 attemptId: RunAttemptId.make("grok-multi-select-attempt"),
563 rootNodeId: NodeId.make("grok-multi-select-root"),
564 providerThread,
565 message: {
566 createdBy: "user",
567 creationSource: "web",
568 messageId: MessageId.make("grok-multi-select-message"),
569 text: "Ask which changes to include.",
570 attachments: [],
571 },
572 modelSelection,
573 runtimePolicy: policy,
574 });
575 assert.deepEqual(yield* Deferred.await(question), {
576 id: "changes",
577 header: "Question",
578 question: questionText,
579 multiSelect: true,
580 options: [
581 { label: "Tests", description: "Cover behavior" },
582 { label: "Docs", description: "Explain usage" },
583 ],
584 });
585 const pending = yield* Deferred.await(request);
586 assert.equal(pending.kind, "user_input");
587 assert.equal(pending.responseCapability.type, "live");
588 yield* runtime.respondToRuntimeRequest({
589 requestId: pending.id,
590 answers: { changes: ["Tests", "Docs"] },
591 });
592 yield* Deferred.await(terminal);
593 }).pipe(Effect.scoped, Effect.provide(layerTest)),
594 );
595});