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

GrokAdapterV2.test.ts

593 lines20.5 KB

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