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

GrokAdapterV2.test.ts

608 lines21.1 KB

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