Add ACP replay harness and session lifecycle support
- Add replay agent and fixture-driven ACP transcript testing - Support session lifecycle, auth methods, and session resume/fork flows - Expand orchestration V2 adapter coverage and debug tooling
This commit is contained in:
1 parent
9d38de8628
commit
1161529645
65 files changed
+9914
-74
No files matched your search
@@ -23,6 +23,9 @@ const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
|
||||
const supportsSessionLifecycle = process.env.T3_ACP_SESSION_LIFECYCLE === "1";
|
||||
const advertisedAuthMethodId = process.env.T3_ACP_AUTH_METHOD_ID?.trim();
|
||||
const requiresAuthentication = process.env.T3_ACP_REQUIRE_AUTH === "1";
|
||||
const permissionOptionIds = {
|
||||
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
|
||||
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
|
||||
@@ -36,6 +39,7 @@ let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
let authenticated = !requiresAuthentication;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function logExit(reason: string): void {
|
||||
@@ -268,19 +272,56 @@ const program = Effect.gen(function* () {
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
agentCapabilities: {
|
||||
loadSession: true,
|
||||
...(supportsSessionLifecycle
|
||||
? {
|
||||
sessionCapabilities: {
|
||||
list: {},
|
||||
fork: {},
|
||||
resume: {},
|
||||
close: {},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
...(advertisedAuthMethodId
|
||||
? {
|
||||
authMethods: [
|
||||
{
|
||||
id: advertisedAuthMethodId,
|
||||
name: "Mock agent authentication",
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
yield* agent.handleAuthenticate((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (advertisedAuthMethodId && request.methodId !== advertisedAuthMethodId) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
`Unknown mock authentication method: ${request.methodId}`,
|
||||
);
|
||||
}
|
||||
authenticated = true;
|
||||
return {};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
Effect.gen(function* () {
|
||||
if (!authenticated) {
|
||||
return yield* AcpError.AcpRequestError.authRequired();
|
||||
}
|
||||
return {
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -302,6 +343,38 @@ const program = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleListSessions((request) =>
|
||||
Effect.succeed({
|
||||
sessions: [
|
||||
{
|
||||
sessionId,
|
||||
cwd: request.cwd ?? process.cwd(),
|
||||
title: "Mock session",
|
||||
updatedAt: "1970-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleForkSession((request) =>
|
||||
Effect.succeed({
|
||||
sessionId: `${request.sessionId}-fork`,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleResumeSession(() =>
|
||||
Effect.succeed({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleCloseSession(() => Effect.succeed({}));
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env node
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { createInterface } from "node:readline";
|
||||
|
||||
interface ReplayEntry {
|
||||
readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit";
|
||||
readonly label?: string;
|
||||
readonly frame?: unknown;
|
||||
readonly status?: "success" | "error" | "cancelled";
|
||||
readonly error?: unknown;
|
||||
}
|
||||
|
||||
interface ReplayTranscript {
|
||||
readonly scenario: string;
|
||||
readonly entries: ReadonlyArray<ReplayEntry>;
|
||||
}
|
||||
|
||||
interface LogicalFrame {
|
||||
readonly kind: "notification" | "request" | "response";
|
||||
readonly method: string;
|
||||
readonly params?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: unknown;
|
||||
}
|
||||
|
||||
interface JsonRpcMessage {
|
||||
readonly jsonrpc?: string;
|
||||
readonly id?: string | number | null;
|
||||
readonly method?: string;
|
||||
readonly params?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: unknown;
|
||||
readonly headers?: ReadonlyArray<unknown>;
|
||||
}
|
||||
|
||||
const encodedTranscript = process.env.T3_ACP_REPLAY_TRANSCRIPT;
|
||||
const statusPath = process.env.T3_ACP_REPLAY_STATUS_PATH;
|
||||
const replayWorkspace = process.env.T3_ACP_REPLAY_WORKSPACE ?? process.cwd();
|
||||
|
||||
if (encodedTranscript === undefined || statusPath === undefined) {
|
||||
process.stderr.write("ACP replay requires transcript and status environment variables.\n");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const replayStatusPath = statusPath;
|
||||
const transcript = JSON.parse(
|
||||
Buffer.from(encodedTranscript, "base64").toString("utf8"),
|
||||
) as ReplayTranscript;
|
||||
let cursor = 0;
|
||||
let stopped = false;
|
||||
let nextAgentRequestId = 1;
|
||||
const pendingClientRequestIds = new Map<string, string | number>();
|
||||
const pendingAgentRequestMethods = new Map<string, string>();
|
||||
|
||||
function writeStatus(failure?: unknown): void {
|
||||
writeFileSync(
|
||||
replayStatusPath,
|
||||
JSON.stringify({
|
||||
scenario: transcript.scenario,
|
||||
cursor,
|
||||
total: transcript.entries.length,
|
||||
...(failure === undefined ? {} : { failure }),
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
}
|
||||
|
||||
function stableStringify(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map(stableStringify).join(",")}]`;
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
const record = value as Record<string, unknown>;
|
||||
return `{${Object.keys(record)
|
||||
.toSorted()
|
||||
.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function expandExpectedString(value: string): string {
|
||||
return value.replaceAll("<workspace>", replayWorkspace);
|
||||
}
|
||||
|
||||
function matchesExpected(expected: unknown, actual: unknown): boolean {
|
||||
if (expected === "<any>") return true;
|
||||
if (typeof expected === "string" && typeof actual === "string") {
|
||||
const expanded = expandExpectedString(expected);
|
||||
if (!expanded.includes("<any>")) return expanded === actual;
|
||||
const parts = expanded.split("<any>");
|
||||
let offset = 0;
|
||||
for (const part of parts) {
|
||||
const index = actual.indexOf(part, offset);
|
||||
if (index === -1) return false;
|
||||
offset = index + part.length;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (Array.isArray(expected)) {
|
||||
return (
|
||||
Array.isArray(actual) &&
|
||||
expected.length === actual.length &&
|
||||
expected.every((entry, index) => matchesExpected(entry, actual[index]))
|
||||
);
|
||||
}
|
||||
if (typeof expected === "object" && expected !== null) {
|
||||
if (typeof actual !== "object" || actual === null || Array.isArray(actual)) return false;
|
||||
const expectedRecord = expected as Record<string, unknown>;
|
||||
const actualRecord = actual as Record<string, unknown>;
|
||||
const expectedKeys = Object.keys(expectedRecord).toSorted();
|
||||
const actualKeys = Object.keys(actualRecord).toSorted();
|
||||
return (
|
||||
stableStringify(expectedKeys) === stableStringify(actualKeys) &&
|
||||
expectedKeys.every((key) => matchesExpected(expectedRecord[key], actualRecord[key]))
|
||||
);
|
||||
}
|
||||
return Object.is(expected, actual);
|
||||
}
|
||||
|
||||
function stopWithFailure(detail: string, actual?: unknown): void {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
const entry = transcript.entries[cursor];
|
||||
const failure = {
|
||||
detail,
|
||||
cursor,
|
||||
expected: entry,
|
||||
...(actual === undefined ? {} : { actual }),
|
||||
};
|
||||
writeStatus(failure);
|
||||
process.stderr.write(`ACP replay mismatch: ${JSON.stringify(failure)}\n`);
|
||||
process.exitCode = 1;
|
||||
process.stdin.pause();
|
||||
}
|
||||
|
||||
function advance(): void {
|
||||
cursor += 1;
|
||||
writeStatus();
|
||||
}
|
||||
|
||||
function send(message: JsonRpcMessage): void {
|
||||
process.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
function pendingClientRequestId(method: string): string | number | undefined {
|
||||
return pendingClientRequestIds.get(method);
|
||||
}
|
||||
|
||||
function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined {
|
||||
if (typeof message.method === "string") {
|
||||
return {
|
||||
kind:
|
||||
message.id === undefined || message.id === null || message.id === ""
|
||||
? "notification"
|
||||
: "request",
|
||||
method: message.method,
|
||||
...(message.params === undefined ? {} : { params: message.params }),
|
||||
};
|
||||
}
|
||||
if (message.id === undefined || message.id === null) return undefined;
|
||||
const method = pendingAgentRequestMethods.get(String(message.id));
|
||||
if (method === undefined) return undefined;
|
||||
return {
|
||||
kind: "response",
|
||||
method,
|
||||
...(message.result === undefined ? {} : { result: message.result }),
|
||||
...(message.error === undefined ? {} : { error: message.error }),
|
||||
};
|
||||
}
|
||||
|
||||
function emitInbound(frame: LogicalFrame): void {
|
||||
switch (frame.kind) {
|
||||
case "notification":
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: frame.method,
|
||||
...(frame.params === undefined ? {} : { params: frame.params }),
|
||||
});
|
||||
return;
|
||||
case "request": {
|
||||
const id = nextAgentRequestId;
|
||||
nextAgentRequestId += 1;
|
||||
pendingAgentRequestMethods.set(String(id), frame.method);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
method: frame.method,
|
||||
...(frame.params === undefined ? {} : { params: frame.params }),
|
||||
headers: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "response": {
|
||||
const id = pendingClientRequestId(frame.method);
|
||||
if (id === undefined) {
|
||||
stopWithFailure(`No pending client request for ${frame.method}`, frame);
|
||||
return;
|
||||
}
|
||||
pendingClientRequestIds.delete(frame.method);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
...(frame.result === undefined ? {} : { result: frame.result }),
|
||||
...(frame.error === undefined ? {} : { error: frame.error }),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function flushInbound(): void {
|
||||
while (!stopped) {
|
||||
const entry = transcript.entries[cursor];
|
||||
if (entry === undefined || entry.type === "expect_outbound") return;
|
||||
if (entry.type === "runtime_exit") {
|
||||
if (entry.status !== "success") {
|
||||
stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
|
||||
return;
|
||||
}
|
||||
advance();
|
||||
continue;
|
||||
}
|
||||
const frame = entry.frame as LogicalFrame;
|
||||
if (
|
||||
typeof frame !== "object" ||
|
||||
frame === null ||
|
||||
!["notification", "request", "response"].includes(frame.kind) ||
|
||||
typeof frame.method !== "string"
|
||||
) {
|
||||
stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
|
||||
return;
|
||||
}
|
||||
emitInbound(frame);
|
||||
if (stopped) return;
|
||||
advance();
|
||||
}
|
||||
}
|
||||
|
||||
function handleMessage(message: JsonRpcMessage): void {
|
||||
if (stopped) return;
|
||||
const actual = logicalIncoming(message);
|
||||
if (actual === undefined) {
|
||||
stopWithFailure("Could not identify outbound ACP frame", message);
|
||||
return;
|
||||
}
|
||||
const entry = transcript.entries[cursor];
|
||||
if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
|
||||
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
error: { code: -32603, message: "ACP replay frame mismatch" },
|
||||
});
|
||||
}
|
||||
stopWithFailure("Unexpected outbound ACP frame", actual);
|
||||
return;
|
||||
}
|
||||
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
|
||||
pendingClientRequestIds.set(actual.method, message.id);
|
||||
} else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
|
||||
pendingAgentRequestMethods.delete(String(message.id));
|
||||
}
|
||||
advance();
|
||||
flushInbound();
|
||||
}
|
||||
|
||||
writeStatus();
|
||||
flushInbound();
|
||||
|
||||
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
input.on("line", (line) => {
|
||||
if (stopped || line.trim().length === 0) return;
|
||||
try {
|
||||
handleMessage(JSON.parse(line) as JsonRpcMessage);
|
||||
} catch (cause) {
|
||||
stopWithFailure("Failed to decode outbound ACP JSON-RPC", String(cause));
|
||||
}
|
||||
});
|
||||
|
||||
input.on("close", () => {
|
||||
if (!stopped && cursor !== transcript.entries.length) {
|
||||
stopWithFailure("ACP replay input closed before transcript completion");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
type ModelSelection,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { OrchestratorV2 } from "./Orchestrator.ts";
|
||||
import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
|
||||
|
||||
const liveAgentId = process.env.T3_ACP_REGISTRY_LIVE_AGENT_ID?.trim() || "devin";
|
||||
const liveCommandPath = process.env.T3_ACP_REGISTRY_LIVE_COMMAND?.trim();
|
||||
const liveInstanceId = ProviderInstanceId.make("acpRegistry_live");
|
||||
const liveModelSelection = {
|
||||
instanceId: liveInstanceId,
|
||||
model: "default",
|
||||
} satisfies ModelSelection;
|
||||
|
||||
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-acp-registry-v2-live-",
|
||||
});
|
||||
|
||||
const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProcess.layer),
|
||||
Layer.provide(serverConfigLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer));
|
||||
|
||||
const liveLayer = OrchestrationV2LayerLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(checkpointStoreLayer),
|
||||
Layer.provide(serverConfigLayer),
|
||||
Layer.provide(
|
||||
ServerSettingsService.layerTest({
|
||||
providerInstances: {
|
||||
[liveInstanceId]: {
|
||||
driver: ProviderDriverKind.make("acpRegistry"),
|
||||
displayName: `ACP Registry: ${liveAgentId}`,
|
||||
enabled: true,
|
||||
config: {
|
||||
agentId: liveAgentId,
|
||||
...(liveCommandPath ? { commandPath: liveCommandPath } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const waitForIdle = Effect.fn("AcpRegistryOrchestratorV2Live.waitForIdle")(function* (
|
||||
threadId: ThreadId,
|
||||
expectedRunCount: number,
|
||||
) {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
for (let attempt = 0; attempt < 900; attempt += 1) {
|
||||
const projection = yield* orchestrator.getThreadProjection(threadId);
|
||||
if (
|
||||
projection.runs.length >= expectedRunCount &&
|
||||
projection.runs.every(
|
||||
(run) => !["queued", "starting", "running", "waiting"].includes(run.status),
|
||||
)
|
||||
) {
|
||||
return projection;
|
||||
}
|
||||
yield* Effect.sleep("500 millis");
|
||||
}
|
||||
return yield* Effect.die(new Error(`Timed out waiting for ACP Registry thread ${threadId}.`));
|
||||
});
|
||||
|
||||
describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")(
|
||||
"ACP Registry V2 live orchestrator",
|
||||
() => {
|
||||
it.live(
|
||||
"runs and resumes a real registry agent through the production V2 harness",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const projectId = ProjectId.make("project:acp-registry-live");
|
||||
const threadId = ThreadId.make("thread:acp-registry-live");
|
||||
const marker = "ACP_REGISTRY_LIVE_7H3Q";
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("command:acp-registry-live:create"),
|
||||
threadId,
|
||||
projectId,
|
||||
title: `ACP Registry live: ${liveAgentId}`,
|
||||
modelSelection: liveModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
});
|
||||
yield* Console.log(
|
||||
`ACP Registry thread created for '${liveAgentId}'; dispatching first prompt.`,
|
||||
);
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:acp-registry-live:first"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:acp-registry-live:first"),
|
||||
text: `Remember this opaque marker. Respond with exactly: ${marker}`,
|
||||
attachments: [],
|
||||
modelSelection: liveModelSelection,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
const firstProjection = yield* waitForIdle(threadId, 1);
|
||||
const firstAssistant = firstProjection.messages.findLast(
|
||||
(message) => message.role === "assistant",
|
||||
)?.text;
|
||||
|
||||
assert.deepEqual(
|
||||
firstProjection.runs.map((run) => [run.provider, run.status]),
|
||||
[[liveInstanceId, "completed"]],
|
||||
);
|
||||
assert.include(firstAssistant ?? "", marker);
|
||||
|
||||
yield* Console.log("First ACP turn completed; dispatching continuation prompt.");
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:acp-registry-live:second"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:acp-registry-live:second"),
|
||||
text: "Return the opaque marker from the previous turn. Respond with only the marker.",
|
||||
attachments: [],
|
||||
modelSelection: liveModelSelection,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
const finalProjection = yield* waitForIdle(threadId, 2);
|
||||
const finalAssistant = finalProjection.messages.findLast(
|
||||
(message) => message.role === "assistant",
|
||||
)?.text;
|
||||
|
||||
assert.deepEqual(
|
||||
finalProjection.runs.map((run) => [run.provider, run.status]),
|
||||
[
|
||||
[liveInstanceId, "completed"],
|
||||
[liveInstanceId, "completed"],
|
||||
],
|
||||
);
|
||||
assert.include(finalAssistant ?? "", marker);
|
||||
assert.deepEqual(finalProjection.providerSessions.length, 2);
|
||||
assert.isAtLeast(finalProjection.providerThreads.length, 1);
|
||||
assert.deepEqual(
|
||||
finalProjection.providerTurns.map((turn) => turn.status),
|
||||
["completed", "completed"],
|
||||
);
|
||||
}).pipe(Effect.provide(liveLayer), Effect.scoped),
|
||||
480_000,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,358 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
MessageId,
|
||||
NodeId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ProviderSessionId,
|
||||
RunAttemptId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ProviderThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AcpSessionRuntime } from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import {
|
||||
ProviderAdapterV2RuntimePolicy,
|
||||
type ProviderAdapterV2TurnInput,
|
||||
} from "../ProviderAdapter.ts";
|
||||
import {
|
||||
AcpProviderCapabilitiesV2,
|
||||
makeAcpAdapterV2,
|
||||
type AcpAdapterV2Flavor,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
|
||||
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-acp-v2-adapter-",
|
||||
}).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const testLayer = Layer.mergeAll(NodeServices.layer, idAllocatorLayer, serverConfigLayer);
|
||||
|
||||
function makeMockRuntime(input: {
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly mockAgentPath: string;
|
||||
readonly environment?: Readonly<Record<string, string>>;
|
||||
}): AcpAdapterV2Flavor["makeRuntime"] {
|
||||
return (runtimeInput) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...runtimeInput,
|
||||
spawn: {
|
||||
command: process.execPath,
|
||||
args: [input.mockAgentPath],
|
||||
cwd: runtimeInput.cwd,
|
||||
env: { T3_ACP_SESSION_LIFECYCLE: "1", ...input.environment },
|
||||
},
|
||||
authMethodId: "test",
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(context));
|
||||
});
|
||||
}
|
||||
|
||||
function makeTurnInput(input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerThread: OrchestrationV2ProviderThread;
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
|
||||
readonly now: DateTime.Utc;
|
||||
readonly ordinal?: number;
|
||||
}): ProviderAdapterV2TurnInput {
|
||||
const ordinal = input.ordinal ?? 1;
|
||||
const suffix = `${input.threadId}:${ordinal}`;
|
||||
const modelSelection = { instanceId: input.instanceId, model: "default" } as const;
|
||||
return {
|
||||
appThread: {
|
||||
id: input.threadId,
|
||||
projectId: ProjectId.make(`project:${input.threadId}`),
|
||||
title: "ACP adapter test",
|
||||
defaultProvider: "acp-test",
|
||||
modelSelection,
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: input.providerThread.id,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: input.threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
threadId: input.threadId,
|
||||
runId: RunId.make(`run:${suffix}`),
|
||||
runOrdinal: ordinal,
|
||||
providerTurnOrdinal: ordinal,
|
||||
attemptId: RunAttemptId.make(`attempt:${suffix}`),
|
||||
rootNodeId: NodeId.make(`node:${suffix}`),
|
||||
providerThread: input.providerThread,
|
||||
message: {
|
||||
messageId: MessageId.make(`message:${suffix}`),
|
||||
text: "test prompt",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection,
|
||||
runtimePolicy: input.runtimePolicy,
|
||||
};
|
||||
}
|
||||
|
||||
describe("AcpAdapterV2", () => {
|
||||
it.effect("negotiates and executes optional native session forks through the ACP runtime", () =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
const makeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath });
|
||||
|
||||
const instanceId = ProviderInstanceId.make("acp-test");
|
||||
const adapter = makeAcpAdapterV2({
|
||||
instanceId,
|
||||
flavor: {
|
||||
provider: "acp-test",
|
||||
capabilities: AcpProviderCapabilitiesV2,
|
||||
makeRuntime,
|
||||
},
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
});
|
||||
const sourceThreadId = ThreadId.make("thread-acp-native-fork-source");
|
||||
const targetThreadId = ThreadId.make("thread-acp-native-fork-target");
|
||||
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const modelSelection = { instanceId, model: "default" } as const;
|
||||
const runtime = yield* adapter.openSession({
|
||||
threadId: sourceThreadId,
|
||||
providerSessionId: ProviderSessionId.make("provider-session-acp-native-fork"),
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
|
||||
assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread);
|
||||
assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot);
|
||||
|
||||
const sourceProviderThread = yield* runtime.ensureThread({
|
||||
threadId: sourceThreadId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const forkedProviderThread = yield* runtime.forkThread({
|
||||
sourceProviderThread,
|
||||
targetThreadId,
|
||||
});
|
||||
|
||||
assert.equal(sourceProviderThread.nativeThreadRef?.nativeId, "mock-session-1");
|
||||
assert.equal(forkedProviderThread.nativeThreadRef?.nativeId, "mock-session-1-fork");
|
||||
assert.equal(forkedProviderThread.appThreadId, targetThreadId);
|
||||
assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id);
|
||||
}).pipe(Effect.provide(testLayer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("cancels pending permission requests while interrupting an ACP turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
const instanceId = ProviderInstanceId.make("acp-test");
|
||||
const adapter = makeAcpAdapterV2({
|
||||
instanceId,
|
||||
flavor: {
|
||||
provider: "acp-test",
|
||||
capabilities: AcpProviderCapabilitiesV2,
|
||||
makeRuntime: makeMockRuntime({
|
||||
childProcessSpawner,
|
||||
mockAgentPath,
|
||||
environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
|
||||
}),
|
||||
},
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
});
|
||||
const threadId = ThreadId.make("thread-acp-cancel-permission");
|
||||
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const modelSelection = { instanceId, model: "default" } as const;
|
||||
const runtime = yield* adapter.openSession({
|
||||
threadId,
|
||||
providerSessionId: ProviderSessionId.make("provider-session-acp-cancel-permission"),
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const providerThread = yield* runtime.ensureThread({
|
||||
threadId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
yield* runtime.startTurn(
|
||||
makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
|
||||
);
|
||||
|
||||
const pendingRequest = Option.getOrThrow(
|
||||
yield* runtime.events.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
|
||||
),
|
||||
Stream.runHead,
|
||||
),
|
||||
);
|
||||
if (
|
||||
pendingRequest.type !== "runtime_request.updated" ||
|
||||
pendingRequest.runtimeRequest.providerTurnId === null
|
||||
) {
|
||||
return yield* Effect.die("Expected a pending ACP permission request with a provider turn");
|
||||
}
|
||||
|
||||
yield* runtime.interruptTurn({
|
||||
providerThread,
|
||||
providerTurnId: pendingRequest.runtimeRequest.providerTurnId,
|
||||
});
|
||||
|
||||
const cancelledRequest = Option.getOrThrow(
|
||||
yield* runtime.events.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.type === "runtime_request.updated" &&
|
||||
event.runtimeRequest.id === pendingRequest.runtimeRequest.id &&
|
||||
event.runtimeRequest.status === "cancelled",
|
||||
),
|
||||
Stream.runHead,
|
||||
),
|
||||
);
|
||||
assert.equal(cancelledRequest.type, "runtime_request.updated");
|
||||
}).pipe(Effect.provide(testLayer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("does not release an ACP turn when cancellation is not acknowledged", () =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
const instanceId = ProviderInstanceId.make("acp-test");
|
||||
const adapter = makeAcpAdapterV2({
|
||||
instanceId,
|
||||
flavor: {
|
||||
provider: "acp-test",
|
||||
capabilities: AcpProviderCapabilitiesV2,
|
||||
makeRuntime: makeMockRuntime({
|
||||
childProcessSpawner,
|
||||
mockAgentPath,
|
||||
environment: { T3_ACP_PROMPT_DELAY_MS: "5000" },
|
||||
}),
|
||||
},
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
});
|
||||
const threadId = ThreadId.make("thread-acp-cancel-timeout");
|
||||
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const modelSelection = { instanceId, model: "default" } as const;
|
||||
const runtime = yield* adapter.openSession({
|
||||
threadId,
|
||||
providerSessionId: ProviderSessionId.make("provider-session-acp-cancel-timeout"),
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const providerThread = yield* runtime.ensureThread({
|
||||
threadId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const firstTurn = makeTurnInput({
|
||||
threadId,
|
||||
providerThread,
|
||||
instanceId,
|
||||
runtimePolicy,
|
||||
now,
|
||||
});
|
||||
yield* runtime.startTurn(firstTurn);
|
||||
yield* runtime.rawEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) => event.direction === "outgoing" && event.method === "session/prompt",
|
||||
),
|
||||
Stream.runHead,
|
||||
);
|
||||
const providerTurnId = idAllocator.derive.providerTurn({
|
||||
provider: "acp-test",
|
||||
nativeTurnId: "mock-session-1:turn:1",
|
||||
});
|
||||
const interruptFiber = yield* runtime
|
||||
.interruptTurn({ providerThread, providerTurnId })
|
||||
.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* runtime.rawEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) => event.direction === "outgoing" && event.method === "session/cancel",
|
||||
),
|
||||
Stream.runHead,
|
||||
);
|
||||
yield* TestClock.adjust("10 seconds");
|
||||
const interruptError = yield* Fiber.join(interruptFiber);
|
||||
assert.equal(interruptError._tag, "ProviderAdapterInterruptError");
|
||||
|
||||
const secondTurnError = yield* runtime
|
||||
.startTurn(
|
||||
makeTurnInput({
|
||||
threadId,
|
||||
providerThread,
|
||||
instanceId,
|
||||
runtimePolicy,
|
||||
now,
|
||||
ordinal: 2,
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.flip);
|
||||
assert.equal(secondTurnError._tag, "ProviderAdapterTurnStartError");
|
||||
}).pipe(Effect.provide(testLayer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
import {
|
||||
ProviderKind,
|
||||
ProviderReplayEntry,
|
||||
type ProviderReplayTranscript,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import {
|
||||
AcpSessionRuntime,
|
||||
type AcpSessionRuntimeShape,
|
||||
} from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { ACP_PROTOCOL, type AcpAdapterV2RuntimeInput } from "./AcpAdapterV2.ts";
|
||||
|
||||
export const AcpReplayTranscript = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
protocol: Schema.Literal(ACP_PROTOCOL),
|
||||
version: Schema.String,
|
||||
scenario: Schema.String,
|
||||
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
entries: Schema.Array(ProviderReplayEntry),
|
||||
});
|
||||
export type AcpReplayTranscript = typeof AcpReplayTranscript.Type;
|
||||
|
||||
const decodeAcpReplayTranscriptSchema = Schema.decodeUnknownEffect(AcpReplayTranscript);
|
||||
|
||||
export class AcpReplayTranscriptDecodeError extends Schema.TaggedErrorClass<AcpReplayTranscriptDecodeError>()(
|
||||
"AcpReplayTranscriptDecodeError",
|
||||
{
|
||||
expectedProvider: ProviderKind,
|
||||
provider: Schema.optional(Schema.String),
|
||||
protocol: Schema.optional(Schema.String),
|
||||
scenario: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode ${this.expectedProvider} ACP replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const isAcpReplayTranscriptDecodeError = Schema.is(AcpReplayTranscriptDecodeError);
|
||||
|
||||
function metadataFromTranscript(transcript: ProviderReplayTranscript): {
|
||||
readonly provider?: string;
|
||||
readonly protocol?: string;
|
||||
readonly scenario?: string;
|
||||
} {
|
||||
return {
|
||||
provider: transcript.provider,
|
||||
protocol: transcript.protocol,
|
||||
scenario: transcript.scenario,
|
||||
};
|
||||
}
|
||||
|
||||
export function decodeAcpReplayTranscript(
|
||||
transcript: ProviderReplayTranscript,
|
||||
expectedProvider: ProviderKind,
|
||||
options: { readonly retargetProvider?: boolean } = {},
|
||||
): Effect.Effect<AcpReplayTranscript, AcpReplayTranscriptDecodeError> {
|
||||
const candidate = options.retargetProvider
|
||||
? { ...transcript, provider: expectedProvider }
|
||||
: transcript;
|
||||
return decodeAcpReplayTranscriptSchema(candidate).pipe(
|
||||
Effect.filterOrFail(
|
||||
(decoded) => decoded.provider === expectedProvider,
|
||||
() =>
|
||||
new AcpReplayTranscriptDecodeError({
|
||||
expectedProvider,
|
||||
...metadataFromTranscript(transcript),
|
||||
cause: `Expected provider ${expectedProvider}, received ${transcript.provider}`,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isAcpReplayTranscriptDecodeError(cause)
|
||||
? cause
|
||||
: new AcpReplayTranscriptDecodeError({
|
||||
expectedProvider,
|
||||
...metadataFromTranscript(transcript),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
interface ReplayStatus {
|
||||
readonly cursor: number;
|
||||
readonly total: number;
|
||||
readonly failure?: unknown;
|
||||
}
|
||||
|
||||
function decodeReplayStatus(raw: string): ReplayStatus {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (
|
||||
typeof value !== "object" ||
|
||||
value === null ||
|
||||
typeof Reflect.get(value, "cursor") !== "number" ||
|
||||
typeof Reflect.get(value, "total") !== "number"
|
||||
) {
|
||||
throw new Error("ACP replay status is malformed.");
|
||||
}
|
||||
return value as ReplayStatus;
|
||||
}
|
||||
|
||||
export function makeAcpReplayCompletenessAssertion(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
statusPath: string,
|
||||
transcript: AcpReplayTranscript,
|
||||
): Effect.Effect<void, EffectAcpErrors.AcpError> {
|
||||
return fileSystem.readFileString(statusPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
detail: `Failed to read ACP replay status for ${transcript.scenario}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.try({
|
||||
try: () => decodeReplayStatus(raw),
|
||||
catch: (cause) =>
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
detail: `Failed to decode ACP replay status for ${transcript.scenario}`,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((status) => {
|
||||
if (
|
||||
status.failure === undefined &&
|
||||
status.cursor === transcript.entries.length &&
|
||||
status.total === transcript.entries.length
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.fail(
|
||||
new EffectAcpErrors.AcpTransportError({
|
||||
detail: `ACP replay did not consume all frames for ${transcript.scenario}`,
|
||||
cause: status,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function makeAcpReplayRuntime(input: {
|
||||
readonly transcript: AcpReplayTranscript;
|
||||
readonly statusPath: string;
|
||||
readonly scriptPath: string;
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
}): (
|
||||
runtimeInput: AcpAdapterV2RuntimeInput,
|
||||
) => Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> {
|
||||
const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString(
|
||||
"base64",
|
||||
);
|
||||
return (runtimeInput) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...runtimeInput,
|
||||
spawn: {
|
||||
command: process.execPath,
|
||||
args: [input.scriptPath],
|
||||
cwd: runtimeInput.cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
T3_ACP_REPLAY_TRANSCRIPT: encodedTranscript,
|
||||
T3_ACP_REPLAY_STATUS_PATH: input.statusPath,
|
||||
T3_ACP_REPLAY_WORKSPACE: runtimeInput.cwd,
|
||||
},
|
||||
},
|
||||
authMethodId: "replay",
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(context));
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,157 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeAcpRegistryResolver } from "../../provider/acp/AcpRegistrySupport.ts";
|
||||
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
|
||||
import { BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2 } from "../builtInProviderAdapterDrivers.ts";
|
||||
import {
|
||||
ACP_REGISTRY_DRIVER_KIND,
|
||||
AcpRegistryAdapterV2Driver,
|
||||
makeAcpRegistryAdapterV2,
|
||||
} from "./AcpRegistryAdapterV2.ts";
|
||||
|
||||
const registryUrl = "https://registry.test/registry.json";
|
||||
const decodeAcpRegistryAdapterSettings = Schema.decodeUnknownEffect(
|
||||
AcpRegistryAdapterV2Driver.configSchema,
|
||||
);
|
||||
|
||||
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-acp-registry-v2-adapter-",
|
||||
}).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const registryLayer = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({
|
||||
version: "1.0.0",
|
||||
agents: [
|
||||
{
|
||||
id: "fixture-agent",
|
||||
name: "Fixture Agent",
|
||||
version: "1.0.0",
|
||||
description: "ACP V2 adapter fixture",
|
||||
distribution: {
|
||||
binary: {
|
||||
"darwin-aarch64": {
|
||||
archive: "https://registry.test/unused",
|
||||
cmd: "fixture-agent",
|
||||
args: [],
|
||||
},
|
||||
"linux-x86_64": {
|
||||
archive: "https://registry.test/unused",
|
||||
cmd: "fixture-agent",
|
||||
args: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const testLayer = Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
idAllocatorLayer,
|
||||
serverConfigLayer,
|
||||
registryLayer,
|
||||
);
|
||||
|
||||
describe("AcpRegistryAdapterV2", () => {
|
||||
it("is registered as a generic provider driver with schema defaults", () => {
|
||||
assert.isTrue(BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2.has(ACP_REGISTRY_DRIVER_KIND));
|
||||
assert.equal(AcpRegistryAdapterV2Driver.driverKind, ACP_REGISTRY_DRIVER_KIND);
|
||||
assert.deepEqual(AcpRegistryAdapterV2Driver.defaultConfig(), {
|
||||
enabled: true,
|
||||
agentId: "",
|
||||
commandPath: "",
|
||||
authMethodId: "",
|
||||
distribution: "auto",
|
||||
customModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("opens a real ACP child process resolved from registry configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
const resolver = yield* makeAcpRegistryResolver({
|
||||
cacheDir: serverConfig.providerStatusCacheDir,
|
||||
registryUrl,
|
||||
});
|
||||
const settings = yield* decodeAcpRegistryAdapterSettings({
|
||||
agentId: "fixture-agent",
|
||||
commandPath: process.execPath,
|
||||
authMethodId: "test",
|
||||
});
|
||||
const instanceId = ProviderInstanceId.make("acp-registry-fixture");
|
||||
const adapter = makeAcpRegistryAdapterV2({
|
||||
instanceId,
|
||||
settings,
|
||||
environment: {
|
||||
T3_ACP_SESSION_LIFECYCLE: "1",
|
||||
},
|
||||
childProcessSpawner,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
resolver: {
|
||||
resolve: (configuredSettings, cwd, environment) =>
|
||||
resolver.resolve(configuredSettings, cwd, environment).pipe(
|
||||
Effect.map((resolved) => ({
|
||||
...resolved,
|
||||
spawn: {
|
||||
...resolved.spawn,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
})),
|
||||
),
|
||||
},
|
||||
serverConfig,
|
||||
});
|
||||
const threadId = ThreadId.make("thread-acp-registry-fixture");
|
||||
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const modelSelection = { instanceId, model: "default" } as const;
|
||||
const runtime = yield* adapter.openSession({
|
||||
threadId,
|
||||
providerSessionId: ProviderSessionId.make("provider-session-acp-registry-fixture"),
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
const providerThread = yield* runtime.ensureThread({
|
||||
threadId,
|
||||
modelSelection,
|
||||
runtimePolicy,
|
||||
});
|
||||
|
||||
assert.equal(runtime.providerSession.provider, "acpRegistry");
|
||||
assert.equal(providerThread.nativeThreadRef?.nativeId, "mock-session-1");
|
||||
assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot);
|
||||
assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread);
|
||||
}).pipe(Effect.provide(testLayer), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { AcpRegistrySettings } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import { makeLayerEffect as makeProviderAdapterRegistryLayerEffect } from "../ProviderAdapterRegistry.ts";
|
||||
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
|
||||
import { makeReplayServerConfig } from "../testkit/ProviderReplayHarness.ts";
|
||||
import {
|
||||
type AcpReplayTranscript,
|
||||
AcpReplayTranscriptDecodeError,
|
||||
decodeAcpReplayTranscript,
|
||||
makeAcpReplayCompletenessAssertion,
|
||||
makeAcpReplayRuntime,
|
||||
} from "./AcpAdapterV2.testkit.ts";
|
||||
import {
|
||||
ACP_REGISTRY_DEFAULT_INSTANCE_ID,
|
||||
ACP_REGISTRY_PROVIDER,
|
||||
makeAcpRegistryAdapterV2,
|
||||
} from "./AcpRegistryAdapterV2.ts";
|
||||
|
||||
const REPLAY_SETTINGS = Schema.decodeUnknownSync(AcpRegistrySettings)({
|
||||
agentId: "replay-agent",
|
||||
authMethodId: "replay",
|
||||
});
|
||||
|
||||
export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: AcpReplayTranscript) {
|
||||
const serverConfigLayer = Layer.effect(
|
||||
ServerConfig,
|
||||
makeReplayServerConfig(`acp-registry-${transcript.scenario}`).pipe(Effect.orDie),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
return makeProviderAdapterRegistryLayerEffect(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const replayDir = yield* fileSystem
|
||||
.makeTempDirectory({
|
||||
prefix: `t3-orchestration-v2-acp-registry-replay-${transcript.scenario}-`,
|
||||
})
|
||||
.pipe(Effect.orDie);
|
||||
const statusPath = path.join(replayDir, "status.json");
|
||||
const scriptPath = yield* path
|
||||
.fromFileUrl(new URL("../../../scripts/acp-replay-agent.ts", import.meta.url))
|
||||
.pipe(Effect.orDie);
|
||||
const adapter = makeAcpRegistryAdapterV2({
|
||||
instanceId: ACP_REGISTRY_DEFAULT_INSTANCE_ID,
|
||||
settings: REPLAY_SETTINGS,
|
||||
environment: {},
|
||||
childProcessSpawner,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
resolver: {
|
||||
resolve: () => Effect.die("ACP registry resolver must not run during replay"),
|
||||
},
|
||||
serverConfig,
|
||||
makeRuntime: makeAcpReplayRuntime({
|
||||
transcript,
|
||||
statusPath,
|
||||
scriptPath,
|
||||
childProcessSpawner,
|
||||
}),
|
||||
assertComplete: makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript),
|
||||
});
|
||||
return [adapter];
|
||||
}),
|
||||
).pipe(Layer.provide(Layer.mergeAll(serverConfigLayer, NodeServices.layer, idAllocatorLayer)));
|
||||
}
|
||||
|
||||
export const AcpRegistryOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
|
||||
AcpReplayTranscript,
|
||||
AcpReplayTranscriptDecodeError
|
||||
> = {
|
||||
provider: ACP_REGISTRY_PROVIDER,
|
||||
decodeTranscript: (transcript) =>
|
||||
decodeAcpReplayTranscript(transcript, ACP_REGISTRY_PROVIDER, {
|
||||
retargetProvider: true,
|
||||
}),
|
||||
makeProviderAdapterRegistryLayer: makeAcpRegistryProviderAdapterRegistryReplayLayer,
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
import {
|
||||
AcpRegistrySettings,
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
makeAcpRegistryResolver,
|
||||
type AcpRegistryResolverShape,
|
||||
} from "../../provider/acp/AcpRegistrySupport.ts";
|
||||
import {
|
||||
AcpSessionRuntime,
|
||||
type AcpSessionRuntimeShape,
|
||||
} from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
|
||||
import { IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import {
|
||||
ProviderAdapterDriverCreateError,
|
||||
type ProviderAdapterDriver,
|
||||
type ProviderAdapterDriverCreateInput,
|
||||
} from "../ProviderAdapterDriver.ts";
|
||||
import {
|
||||
AcpProviderCapabilitiesV2,
|
||||
makeAcpAdapterV2,
|
||||
type AcpAdapterV2Flavor,
|
||||
type AcpAdapterV2RuntimeInput,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
|
||||
export const ACP_REGISTRY_PROVIDER = "acpRegistry" as const;
|
||||
export const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make(ACP_REGISTRY_PROVIDER);
|
||||
export const ACP_REGISTRY_DEFAULT_INSTANCE_ID =
|
||||
defaultInstanceIdForDriver(ACP_REGISTRY_DRIVER_KIND);
|
||||
|
||||
const DEFAULT_ACP_REGISTRY_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({});
|
||||
|
||||
export interface AcpRegistryAdapterV2Options {
|
||||
readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
|
||||
readonly settings: AcpRegistrySettings;
|
||||
readonly environment: NodeJS.ProcessEnv;
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly idAllocator: IdAllocatorV2["Service"];
|
||||
readonly resolver: AcpRegistryResolverShape;
|
||||
readonly serverConfig: ServerConfig["Service"];
|
||||
readonly makeRuntime?: (
|
||||
input: AcpAdapterV2RuntimeInput,
|
||||
) => Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope>;
|
||||
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) {
|
||||
return (
|
||||
input: AcpAdapterV2RuntimeInput,
|
||||
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const resolved = yield* options.resolver
|
||||
.resolve(options.settings, input.cwd, options.environment)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EffectAcpErrors.AcpSpawnError({
|
||||
command: options.settings.agentId || ACP_REGISTRY_PROVIDER,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const context = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: resolved.spawn,
|
||||
...(options.settings.authMethodId ? { authMethodId: options.settings.authMethodId } : {}),
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, options.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(context));
|
||||
});
|
||||
}
|
||||
|
||||
export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) {
|
||||
const flavor: AcpAdapterV2Flavor = {
|
||||
provider: ACP_REGISTRY_PROVIDER,
|
||||
capabilities: AcpProviderCapabilitiesV2,
|
||||
makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options),
|
||||
...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
|
||||
};
|
||||
return makeAcpAdapterV2({
|
||||
instanceId: options.instanceId,
|
||||
flavor,
|
||||
fileSystem: options.fileSystem,
|
||||
idAllocator: options.idAllocator,
|
||||
serverConfig: options.serverConfig,
|
||||
});
|
||||
}
|
||||
|
||||
export type AcpRegistryAdapterV2DriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| IdAllocatorV2
|
||||
| Path.Path
|
||||
| ServerConfig;
|
||||
|
||||
export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
|
||||
AcpRegistrySettings,
|
||||
AcpRegistryAdapterV2DriverEnv
|
||||
> = {
|
||||
driverKind: ACP_REGISTRY_DRIVER_KIND,
|
||||
configSchema: AcpRegistrySettings,
|
||||
defaultConfig: (): AcpRegistrySettings => DEFAULT_ACP_REGISTRY_SETTINGS,
|
||||
create: Effect.fn("AcpRegistryAdapterV2Driver.create")(
|
||||
function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const resolver = yield* makeAcpRegistryResolver({
|
||||
cacheDir: serverConfig.providerStatusCacheDir,
|
||||
});
|
||||
return makeAcpRegistryAdapterV2({
|
||||
instanceId: input.instanceId,
|
||||
settings: { ...input.config, enabled: input.enabled },
|
||||
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
|
||||
childProcessSpawner,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
resolver,
|
||||
serverConfig,
|
||||
});
|
||||
},
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterDriverCreateError({
|
||||
driver: ACP_REGISTRY_DRIVER_KIND,
|
||||
instanceId: input.instanceId,
|
||||
detail: "Failed to create ACP Registry adapter.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
|
||||
import { AcpProviderCapabilitiesV2, acpPermissionDisposition } from "./AcpAdapterV2.ts";
|
||||
import { GrokProviderCapabilitiesV2 } from "./GrokAdapterV2.ts";
|
||||
|
||||
function permissionRequest(
|
||||
kind: EffectAcpSchema.ToolKind,
|
||||
): EffectAcpSchema.RequestPermissionRequest {
|
||||
return {
|
||||
sessionId: "session-1",
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
title: "Test tool",
|
||||
kind,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function runtimePolicy(input: {
|
||||
readonly runtimeMode: "approval-required" | "auto-accept-edits" | "full-access";
|
||||
readonly approvalPolicy?: unknown;
|
||||
readonly sandboxPolicy?: unknown;
|
||||
}) {
|
||||
return ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: "default",
|
||||
cwd: "/workspace",
|
||||
...(input.approvalPolicy === undefined ? {} : { approvalPolicy: input.approvalPolicy }),
|
||||
...(input.sandboxPolicy === undefined ? {} : { sandboxPolicy: input.sandboxPolicy }),
|
||||
});
|
||||
}
|
||||
|
||||
describe("GrokAdapterV2 capabilities", () => {
|
||||
it("keeps optional protocol features conservative until a flavor or handshake confirms them", () => {
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsModelSwitchInSession);
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsRuntimeModeSwitchInSession);
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.threads.canReadThreadSnapshot);
|
||||
assert.isFalse(AcpProviderCapabilitiesV2.tools.supportsMcpTools);
|
||||
});
|
||||
|
||||
it("leaves non-native features available to orchestrator fallbacks", () => {
|
||||
assert.isFalse(GrokProviderCapabilitiesV2.threads.canForkThread);
|
||||
assert.isFalse(GrokProviderCapabilitiesV2.subagents.supportsSubagents);
|
||||
assert.isFalse(GrokProviderCapabilitiesV2.turns.supportsActiveSteering);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsInterrupt);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.turns.supportsSteeringByInterruptRestart);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.context.supportsFullThreadHandoff);
|
||||
});
|
||||
|
||||
it("declares the optional ACP features verified by the Grok handshake", () => {
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.sessions.supportsModelSwitchInSession);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.threads.canReadThreadSnapshot);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.tools.supportsMcpTools);
|
||||
assert.isTrue(GrokProviderCapabilitiesV2.checkpointing.providerCanReadConversationSnapshot);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACP permission policy", () => {
|
||||
it("honors explicit on-request approval over full-access runtime mode", () => {
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
runtimePolicy({
|
||||
runtimeMode: "full-access",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxPolicy: { type: "readOnly" },
|
||||
}),
|
||||
permissionRequest("execute"),
|
||||
),
|
||||
"ask",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects mutating escalation under a non-interactive read-only policy", () => {
|
||||
const policy = runtimePolicy({
|
||||
runtimeMode: "full-access",
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: { type: "readOnly" },
|
||||
});
|
||||
assert.equal(acpPermissionDisposition(policy, permissionRequest("execute")), "deny");
|
||||
assert.equal(acpPermissionDisposition(policy, permissionRequest("edit")), "deny");
|
||||
assert.equal(acpPermissionDisposition(policy, permissionRequest("read")), "allow");
|
||||
});
|
||||
|
||||
it("auto-approves requests only when the resolved policy permits them", () => {
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
runtimePolicy({
|
||||
runtimeMode: "full-access",
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: { type: "dangerFullAccess" },
|
||||
}),
|
||||
permissionRequest("execute"),
|
||||
),
|
||||
"allow",
|
||||
);
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
runtimePolicy({ runtimeMode: "approval-required" }),
|
||||
permissionRequest("read"),
|
||||
),
|
||||
"ask",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { GrokSettings } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import { makeLayerEffect as makeProviderAdapterRegistryLayerEffect } from "../ProviderAdapterRegistry.ts";
|
||||
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
|
||||
import { makeReplayServerConfig } from "../testkit/ProviderReplayHarness.ts";
|
||||
import {
|
||||
type AcpReplayTranscript,
|
||||
AcpReplayTranscriptDecodeError,
|
||||
decodeAcpReplayTranscript,
|
||||
makeAcpReplayCompletenessAssertion,
|
||||
makeAcpReplayRuntime,
|
||||
} from "./AcpAdapterV2.testkit.ts";
|
||||
import { GROK_DEFAULT_INSTANCE_ID, GROK_PROVIDER, makeGrokAdapterV2 } from "./GrokAdapterV2.ts";
|
||||
|
||||
const DEFAULT_GROK_SETTINGS = Schema.decodeUnknownSync(GrokSettings)({});
|
||||
|
||||
export function makeGrokProviderAdapterRegistryReplayLayer(transcript: AcpReplayTranscript) {
|
||||
const serverConfigLayer = Layer.effect(
|
||||
ServerConfig,
|
||||
makeReplayServerConfig(`grok-${transcript.scenario}`).pipe(Effect.orDie),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
return makeProviderAdapterRegistryLayerEffect(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const replayDir = yield* fileSystem
|
||||
.makeTempDirectory({
|
||||
prefix: `t3-orchestration-v2-grok-replay-${transcript.scenario}-`,
|
||||
})
|
||||
.pipe(Effect.orDie);
|
||||
const statusPath = path.join(replayDir, "status.json");
|
||||
const scriptPath = yield* path
|
||||
.fromFileUrl(new URL("../../../scripts/acp-replay-agent.ts", import.meta.url))
|
||||
.pipe(Effect.orDie);
|
||||
const adapter = makeGrokAdapterV2({
|
||||
instanceId: GROK_DEFAULT_INSTANCE_ID,
|
||||
settings: DEFAULT_GROK_SETTINGS,
|
||||
environment: {},
|
||||
childProcessSpawner,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
makeRuntime: makeAcpReplayRuntime({
|
||||
transcript,
|
||||
statusPath,
|
||||
scriptPath,
|
||||
childProcessSpawner,
|
||||
}),
|
||||
assertComplete: makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript),
|
||||
});
|
||||
return [adapter];
|
||||
}),
|
||||
).pipe(Layer.provide(Layer.mergeAll(serverConfigLayer, NodeServices.layer, idAllocatorLayer)));
|
||||
}
|
||||
|
||||
export const GrokOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
|
||||
AcpReplayTranscript,
|
||||
AcpReplayTranscriptDecodeError
|
||||
> = {
|
||||
provider: GROK_PROVIDER,
|
||||
decodeTranscript: (transcript) => decodeAcpReplayTranscript(transcript, GROK_PROVIDER),
|
||||
makeProviderAdapterRegistryLayer: makeGrokProviderAdapterRegistryReplayLayer,
|
||||
};
|
||||
@@ -0,0 +1,210 @@
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
GrokSettings,
|
||||
ProviderDriverKind,
|
||||
type OrchestrationV2ProviderCapabilities,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
makeGrokAcpRuntime,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "../../provider/acp/GrokAcpSupport.ts";
|
||||
import {
|
||||
extractXAiAskUserQuestionIdentity,
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../../provider/acp/XAiAcpExtension.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
|
||||
import type { AcpSessionRuntimeShape } from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
import { ProviderAdapterV2 } from "../ProviderAdapter.ts";
|
||||
import {
|
||||
ProviderAdapterDriverCreateError,
|
||||
type ProviderAdapterDriver,
|
||||
type ProviderAdapterDriverCreateInput,
|
||||
} from "../ProviderAdapterDriver.ts";
|
||||
import {
|
||||
AcpProviderCapabilitiesV2,
|
||||
makeAcpAdapterV2,
|
||||
type AcpAdapterV2Flavor,
|
||||
type AcpAdapterV2RuntimeInput,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
|
||||
export const GROK_PROVIDER = "grok" as const;
|
||||
export const GROK_DRIVER_KIND = ProviderDriverKind.make(GROK_PROVIDER);
|
||||
export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND);
|
||||
const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
|
||||
|
||||
export const GrokProviderCapabilitiesV2 = {
|
||||
...AcpProviderCapabilitiesV2,
|
||||
sessions: {
|
||||
...AcpProviderCapabilitiesV2.sessions,
|
||||
supportsModelSwitchInSession: true,
|
||||
supportsRuntimeModeSwitchInSession: false,
|
||||
},
|
||||
threads: {
|
||||
...AcpProviderCapabilitiesV2.threads,
|
||||
canReadThreadSnapshot: true,
|
||||
canForkThread: false,
|
||||
canForkFromTurn: false,
|
||||
},
|
||||
subagents: {
|
||||
...AcpProviderCapabilitiesV2.subagents,
|
||||
supportsSubagents: false,
|
||||
},
|
||||
tools: {
|
||||
...AcpProviderCapabilitiesV2.tools,
|
||||
supportsMcpTools: true,
|
||||
},
|
||||
checkpointing: {
|
||||
...AcpProviderCapabilitiesV2.checkpointing,
|
||||
providerCanReadConversationSnapshot: true,
|
||||
},
|
||||
} satisfies OrchestrationV2ProviderCapabilities;
|
||||
|
||||
export interface GrokAdapterV2Options {
|
||||
readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
|
||||
readonly settings: GrokSettings;
|
||||
readonly environment: NodeJS.ProcessEnv;
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly idAllocator: IdAllocatorV2["Service"];
|
||||
readonly serverConfig: ServerConfig["Service"];
|
||||
readonly makeRuntime?: (
|
||||
input: AcpAdapterV2RuntimeInput,
|
||||
) => Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope>;
|
||||
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({
|
||||
runtime,
|
||||
requestUserInput,
|
||||
}) =>
|
||||
Effect.forEach(
|
||||
["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
|
||||
(method) =>
|
||||
runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params) => {
|
||||
const identity = extractXAiAskUserQuestionIdentity(params);
|
||||
const questions = extractXAiAskUserQuestions(params).map((question) => ({
|
||||
id: question.id,
|
||||
header: question.header,
|
||||
question: question.question,
|
||||
options: [...question.options],
|
||||
}));
|
||||
return requestUserInput({
|
||||
nativeItemId: `${identity.sessionId}:xai-question:${identity.toolCallId}`,
|
||||
nativeRequestId: identity.toolCallId,
|
||||
questions,
|
||||
}).pipe(
|
||||
Effect.map((answers) =>
|
||||
answers === null
|
||||
? makeXAiAskUserQuestionCancelledResponse()
|
||||
: makeXAiAskUserQuestionResponse(params, answers),
|
||||
),
|
||||
);
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
|
||||
export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
|
||||
const flavor: AcpAdapterV2Flavor = {
|
||||
provider: GROK_PROVIDER,
|
||||
capabilities: GrokProviderCapabilitiesV2,
|
||||
resolveModelId: (selection) => resolveGrokAcpBaseModelId(selection.model),
|
||||
makeRuntime:
|
||||
options.makeRuntime ??
|
||||
((input) =>
|
||||
makeGrokAcpRuntime({
|
||||
...input,
|
||||
grokSettings: options.settings,
|
||||
environment: options.environment,
|
||||
childProcessSpawner: options.childProcessSpawner,
|
||||
})),
|
||||
registerExtensions: registerGrokAcpExtensions,
|
||||
...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
|
||||
};
|
||||
return makeAcpAdapterV2({
|
||||
instanceId: options.instanceId,
|
||||
flavor,
|
||||
fileSystem: options.fileSystem,
|
||||
idAllocator: options.idAllocator,
|
||||
serverConfig: options.serverConfig,
|
||||
});
|
||||
}
|
||||
|
||||
export type GrokAdapterV2DriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| IdAllocatorV2
|
||||
| ServerConfig;
|
||||
|
||||
export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapterV2DriverEnv> = {
|
||||
driverKind: GROK_DRIVER_KIND,
|
||||
configSchema: GrokSettings,
|
||||
defaultConfig: (): GrokSettings => DEFAULT_GROK_SETTINGS,
|
||||
create: Effect.fn("GrokAdapterV2Driver.create")(
|
||||
function* (input: ProviderAdapterDriverCreateInput<GrokSettings>) {
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
return makeGrokAdapterV2({
|
||||
instanceId: input.instanceId,
|
||||
settings: { ...input.config, enabled: input.enabled },
|
||||
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
|
||||
childProcessSpawner,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
});
|
||||
},
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterDriverCreateError({
|
||||
driver: GROK_DRIVER_KIND,
|
||||
instanceId: input.instanceId,
|
||||
detail: "Failed to create Grok ACP adapter.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
export const layer: Layer.Layer<
|
||||
ProviderAdapterV2,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | IdAllocatorV2 | ServerConfig
|
||||
> = Layer.effect(
|
||||
ProviderAdapterV2,
|
||||
Effect.gen(function* () {
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
return makeGrokAdapterV2({
|
||||
instanceId: GROK_DEFAULT_INSTANCE_ID,
|
||||
settings: DEFAULT_GROK_SETTINGS,
|
||||
environment: hostEnvironment,
|
||||
childProcessSpawner,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,184 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
NodeId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
type OrchestrationV2ProviderTurn,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
openCodeBoundaryAfterProviderTurn,
|
||||
openCodeChildPermissionRules,
|
||||
openCodePermissionRules,
|
||||
openCodePermissionRequestKind,
|
||||
openCodeToolProjectionKind,
|
||||
OpenCodeProviderCapabilitiesV2,
|
||||
} from "./OpenCodeAdapterV2.ts";
|
||||
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
|
||||
|
||||
function runtimePolicy(
|
||||
runtimeMode: ProviderAdapterV2RuntimePolicy["runtimeMode"],
|
||||
override: Partial<ProviderAdapterV2RuntimePolicy> = {},
|
||||
): ProviderAdapterV2RuntimePolicy {
|
||||
return ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
cwd: null,
|
||||
...override,
|
||||
});
|
||||
}
|
||||
|
||||
function permissionAction(rules: ReturnType<typeof openCodePermissionRules>, permission: string) {
|
||||
return rules.findLast((rule) => rule.permission === "*" || rule.permission === permission)
|
||||
?.action;
|
||||
}
|
||||
|
||||
function providerTurn(input: {
|
||||
readonly id: string;
|
||||
readonly ordinal: number;
|
||||
readonly nativeId: string | null;
|
||||
}): OrchestrationV2ProviderTurn {
|
||||
return {
|
||||
id: ProviderTurnId.make(input.id),
|
||||
providerThreadId: ProviderThreadId.make("provider-thread:opencode-test"),
|
||||
nodeId: NodeId.make(`node:${input.id}`),
|
||||
runAttemptId: null,
|
||||
nativeTurnRef:
|
||||
input.nativeId === null
|
||||
? null
|
||||
: { provider: "opencode", nativeId: input.nativeId, strength: "weak" },
|
||||
ordinal: input.ordinal,
|
||||
status: "completed",
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("OpenCodeAdapterV2", () => {
|
||||
it("advertises the identity strengths exposed by the SDK boundary", () => {
|
||||
assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeThreadIds, "strong");
|
||||
assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeTurnIds, "weak");
|
||||
assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeItemIds, "strong");
|
||||
assert.equal(OpenCodeProviderCapabilitiesV2.identity.nativeRequestIds, "strong");
|
||||
assert.isTrue(OpenCodeProviderCapabilitiesV2.threads.canForkFromTurn);
|
||||
assert.isTrue(OpenCodeProviderCapabilitiesV2.turns.supportsActiveSteering);
|
||||
assert.equal(OpenCodeProviderCapabilitiesV2.turns.terminalStatusQuality, "strong");
|
||||
assert.isFalse(OpenCodeProviderCapabilitiesV2.subagents.canCloseSubagents);
|
||||
});
|
||||
|
||||
it("maps native permission families to orchestration request kinds", () => {
|
||||
assert.equal(openCodePermissionRequestKind("bash"), "command");
|
||||
assert.equal(openCodePermissionRequestKind("read"), "file-read");
|
||||
assert.equal(openCodePermissionRequestKind("grep"), "file-read");
|
||||
assert.equal(openCodePermissionRequestKind("external_directory"), "file-read");
|
||||
assert.equal(openCodePermissionRequestKind("external_directory", "edit"), "file-change");
|
||||
assert.equal(openCodePermissionRequestKind("edit"), "file-change");
|
||||
assert.equal(openCodePermissionRequestKind("apply_patch"), "file-change");
|
||||
});
|
||||
|
||||
it("maps OpenCode tools to semantic turn-item families", () => {
|
||||
assert.equal(openCodeToolProjectionKind("bash"), "command_execution");
|
||||
assert.equal(openCodeToolProjectionKind("edit"), "file_change");
|
||||
assert.equal(openCodeToolProjectionKind("read"), "file_search");
|
||||
assert.equal(openCodeToolProjectionKind("lsp"), "file_search");
|
||||
assert.equal(openCodeToolProjectionKind("websearch"), "web_search");
|
||||
assert.equal(openCodeToolProjectionKind("codesearch"), "web_search");
|
||||
assert.equal(openCodeToolProjectionKind("custom_tool"), "dynamic_tool");
|
||||
});
|
||||
|
||||
it("maps runtime modes to safe OpenCode permission rules", () => {
|
||||
const approvalRequired = openCodePermissionRules(runtimePolicy("approval-required"));
|
||||
assert.equal(permissionAction(approvalRequired, "read"), "allow");
|
||||
assert.equal(permissionAction(approvalRequired, "edit"), "ask");
|
||||
assert.equal(permissionAction(approvalRequired, "bash"), "ask");
|
||||
assert.equal(permissionAction(approvalRequired, "doom_loop"), "ask");
|
||||
assert.equal(permissionAction(approvalRequired, "unknown_plugin_tool"), "ask");
|
||||
assert.equal(permissionAction(approvalRequired, "question"), "allow");
|
||||
|
||||
const autoAcceptEdits = openCodePermissionRules(runtimePolicy("auto-accept-edits"));
|
||||
assert.equal(permissionAction(autoAcceptEdits, "edit"), "allow");
|
||||
assert.equal(permissionAction(autoAcceptEdits, "bash"), "ask");
|
||||
|
||||
const fullAccess = openCodePermissionRules(runtimePolicy("full-access"));
|
||||
assert.equal(permissionAction(fullAccess, "bash"), "allow");
|
||||
assert.equal(permissionAction(fullAccess, "edit"), "allow");
|
||||
|
||||
const granularApproval = openCodePermissionRules(
|
||||
runtimePolicy("full-access", {
|
||||
approvalPolicy: { granular: { request_permissions: true } },
|
||||
}),
|
||||
);
|
||||
assert.equal(permissionAction(granularApproval, "bash"), "ask");
|
||||
assert.equal(permissionAction(granularApproval, "read"), "allow");
|
||||
});
|
||||
|
||||
it("enforces non-interactive sandbox policy through OpenCode permissions", () => {
|
||||
const readOnly = openCodePermissionRules(
|
||||
runtimePolicy("full-access", {
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.equal(permissionAction(readOnly, "read"), "allow");
|
||||
assert.equal(permissionAction(readOnly, "edit"), "deny");
|
||||
assert.equal(permissionAction(readOnly, "bash"), "deny");
|
||||
assert.equal(permissionAction(readOnly, "webfetch"), "deny");
|
||||
assert.equal(permissionAction(readOnly, "doom_loop"), "deny");
|
||||
assert.equal(permissionAction(readOnly, "unknown_plugin_tool"), "deny");
|
||||
assert.equal(permissionAction(readOnly, "external_directory"), "allow");
|
||||
|
||||
const workspaceWrite = openCodePermissionRules(
|
||||
runtimePolicy("auto-accept-edits", {
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
writableRoots: ["/tmp/opencode-workspace"],
|
||||
networkAccess: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.equal(permissionAction(workspaceWrite, "edit"), "allow");
|
||||
assert.equal(permissionAction(workspaceWrite, "bash"), "deny");
|
||||
assert.equal(permissionAction(workspaceWrite, "webfetch"), "allow");
|
||||
assert.deepInclude(workspaceWrite, {
|
||||
permission: "external_directory",
|
||||
pattern: "/tmp/opencode-workspace/*",
|
||||
action: "allow",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves OpenCode's recursion guard on task-created child sessions", () => {
|
||||
const childRules = openCodeChildPermissionRules(runtimePolicy("full-access"), [
|
||||
{ permission: "task", pattern: "*", action: "deny" },
|
||||
]);
|
||||
|
||||
assert.equal(permissionAction(childRules, "read"), "allow");
|
||||
assert.equal(permissionAction(childRules, "bash"), "allow");
|
||||
assert.equal(permissionAction(childRules, "task"), "deny");
|
||||
|
||||
const approvalRequiredPolicy = runtimePolicy("approval-required");
|
||||
const parentRules = openCodePermissionRules(approvalRequiredPolicy);
|
||||
const childApprovalRules = openCodeChildPermissionRules(approvalRequiredPolicy, [
|
||||
...parentRules.filter((rule) => rule.action === "deny"),
|
||||
{ permission: "task", pattern: "*", action: "deny" },
|
||||
]);
|
||||
assert.equal(permissionAction(childApprovalRules, "bash"), "ask");
|
||||
assert.equal(permissionAction(childApprovalRules, "task"), "deny");
|
||||
});
|
||||
|
||||
it("uses the next native user message as the exclusive fork and revert boundary", () => {
|
||||
const first = providerTurn({ id: "turn:first", ordinal: 1, nativeId: "msg-user-1" });
|
||||
const synthetic = providerTurn({ id: "turn:synthetic", ordinal: 2, nativeId: null });
|
||||
const third = providerTurn({ id: "turn:third", ordinal: 3, nativeId: "msg-user-3" });
|
||||
|
||||
assert.equal(
|
||||
openCodeBoundaryAfterProviderTurn([third, first, synthetic], first.id),
|
||||
"msg-user-3",
|
||||
);
|
||||
assert.isUndefined(openCodeBoundaryAfterProviderTurn([first, synthetic, third], third.id));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,385 @@
|
||||
import type { Event as OpenCodeEvent, OpencodeClient } from "@opencode-ai/sdk/v2";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderReplayEntry, type ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||
import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts";
|
||||
import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts";
|
||||
import {
|
||||
makeReplayServerConfig,
|
||||
type OrchestratorV2ProviderReplayHarness,
|
||||
} from "../testkit/ProviderReplayHarness.ts";
|
||||
import {
|
||||
OPENCODE_DEFAULT_INSTANCE_ID,
|
||||
OPENCODE_DRIVER_KIND,
|
||||
OPENCODE_PROVIDER,
|
||||
OpenCodeAdapterV2Driver,
|
||||
} from "./OpenCodeAdapterV2.ts";
|
||||
|
||||
export const OPENCODE_SDK_REPLAY_PROTOCOL = "opencode-sdk.sse" as const;
|
||||
|
||||
const OpenCodeSdkReplayTranscript = Schema.Struct({
|
||||
provider: Schema.Literal(OPENCODE_PROVIDER),
|
||||
protocol: Schema.Literal(OPENCODE_SDK_REPLAY_PROTOCOL),
|
||||
version: Schema.String,
|
||||
scenario: Schema.String,
|
||||
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
entries: Schema.Array(ProviderReplayEntry),
|
||||
});
|
||||
export type OpenCodeSdkReplayTranscript = typeof OpenCodeSdkReplayTranscript.Type;
|
||||
const decodeOpenCodeSdkReplayTranscript = Schema.decodeUnknownEffect(OpenCodeSdkReplayTranscript);
|
||||
|
||||
export class OpenCodeReplayTranscriptDecodeError extends Schema.TaggedErrorClass<OpenCodeReplayTranscriptDecodeError>()(
|
||||
"OpenCodeReplayTranscriptDecodeError",
|
||||
{
|
||||
provider: Schema.optional(Schema.String),
|
||||
protocol: Schema.optional(Schema.String),
|
||||
scenario: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to decode OpenCode replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenCodeReplayMismatchError extends Schema.TaggedErrorClass<OpenCodeReplayMismatchError>()(
|
||||
"OpenCodeReplayMismatchError",
|
||||
{
|
||||
scenario: Schema.String,
|
||||
cursor: Schema.Number,
|
||||
expected: Schema.Unknown,
|
||||
actual: Schema.Unknown,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode replay frame mismatch at cursor ${this.cursor} in scenario ${this.scenario}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenCodeReplayIncompleteError extends Schema.TaggedErrorClass<OpenCodeReplayIncompleteError>()(
|
||||
"OpenCodeReplayIncompleteError",
|
||||
{
|
||||
scenario: Schema.String,
|
||||
cursor: Schema.Number,
|
||||
remaining: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const OpenCodeReplayError = Schema.Union([
|
||||
OpenCodeReplayTranscriptDecodeError,
|
||||
OpenCodeReplayMismatchError,
|
||||
OpenCodeReplayIncompleteError,
|
||||
]);
|
||||
export type OpenCodeReplayError = typeof OpenCodeReplayError.Type;
|
||||
export const OpenCodeOrchestratorReplayHarnessError = Schema.Union([
|
||||
OpenCodeReplayError,
|
||||
ProviderAdapterDriverCreateError,
|
||||
]);
|
||||
export type OpenCodeOrchestratorReplayHarnessError =
|
||||
typeof OpenCodeOrchestratorReplayHarnessError.Type;
|
||||
|
||||
function replayValueMatches(expected: unknown, actual: unknown): boolean {
|
||||
if (expected === "<any>" || expected === "<workspace>") return true;
|
||||
if (Array.isArray(expected)) {
|
||||
return (
|
||||
Array.isArray(actual) &&
|
||||
expected.length === actual.length &&
|
||||
expected.every((entry, index) => replayValueMatches(entry, actual[index]))
|
||||
);
|
||||
}
|
||||
if (typeof expected === "object" && expected !== null) {
|
||||
if (typeof actual !== "object" || actual === null) return false;
|
||||
return Object.entries(expected).every(([key, value]) =>
|
||||
replayValueMatches(value, (actual as Record<string, unknown>)[key]),
|
||||
);
|
||||
}
|
||||
return Object.is(expected, actual);
|
||||
}
|
||||
|
||||
function frameRecord(frame: unknown): Record<string, unknown> | null {
|
||||
return typeof frame === "object" && frame !== null ? (frame as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
class OpenCodeReplayController {
|
||||
private cursor = 0;
|
||||
private readonly waiters = new Set<() => void>();
|
||||
private failure: unknown = null;
|
||||
private readonly transcript: OpenCodeSdkReplayTranscript;
|
||||
|
||||
constructor(transcript: OpenCodeSdkReplayTranscript) {
|
||||
this.transcript = transcript;
|
||||
}
|
||||
|
||||
async expectOutbound(actual: unknown): Promise<void> {
|
||||
try {
|
||||
const entry = this.transcript.entries[this.cursor];
|
||||
if (entry?.type !== "expect_outbound" || !replayValueMatches(entry.frame, actual)) {
|
||||
throw new OpenCodeReplayMismatchError({
|
||||
scenario: this.transcript.scenario,
|
||||
cursor: this.cursor,
|
||||
expected: entry?.type === "expect_outbound" ? entry.frame : (entry ?? null),
|
||||
actual,
|
||||
});
|
||||
}
|
||||
this.advance();
|
||||
} catch (cause) {
|
||||
this.fail(cause);
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
async response(operation: string): Promise<unknown> {
|
||||
while (true) {
|
||||
this.throwFailure();
|
||||
const entry = this.transcript.entries[this.cursor];
|
||||
if (entry?.type === "emit_inbound") {
|
||||
const frame = frameRecord(entry.frame);
|
||||
if (frame?.type === "sdk.response" && frame.operation === operation) {
|
||||
if (entry.afterMs !== undefined && entry.afterMs > 0) {
|
||||
await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
|
||||
}
|
||||
const data = frame.data;
|
||||
this.advance();
|
||||
return data;
|
||||
}
|
||||
}
|
||||
if (entry?.type === "runtime_exit") {
|
||||
const mismatch = new OpenCodeReplayMismatchError({
|
||||
scenario: this.transcript.scenario,
|
||||
cursor: this.cursor,
|
||||
expected: { type: "sdk.response", operation },
|
||||
actual: entry,
|
||||
});
|
||||
this.fail(mismatch);
|
||||
throw mismatch;
|
||||
}
|
||||
await this.changed();
|
||||
}
|
||||
}
|
||||
|
||||
async *events(signal?: AbortSignal): AsyncIterable<OpenCodeEvent> {
|
||||
while (true) {
|
||||
if (signal?.aborted === true) return;
|
||||
this.throwFailure();
|
||||
const entry = this.transcript.entries[this.cursor];
|
||||
if (entry?.type === "emit_inbound") {
|
||||
const frame = frameRecord(entry.frame);
|
||||
if (frame?.type === "sdk.event") {
|
||||
if (entry.afterMs !== undefined && entry.afterMs > 0) {
|
||||
await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
|
||||
}
|
||||
const event = frame.event as OpenCodeEvent;
|
||||
this.advance();
|
||||
yield event;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (entry?.type === "runtime_exit") {
|
||||
this.advance();
|
||||
if (entry.status === "success") return;
|
||||
const mismatch = new OpenCodeReplayMismatchError({
|
||||
scenario: this.transcript.scenario,
|
||||
cursor: this.cursor - 1,
|
||||
expected: { status: "success" },
|
||||
actual: entry,
|
||||
});
|
||||
this.fail(mismatch);
|
||||
throw mismatch;
|
||||
}
|
||||
await this.changed(signal);
|
||||
}
|
||||
}
|
||||
|
||||
assertComplete(): void {
|
||||
while (this.transcript.entries[this.cursor]?.type === "runtime_exit") {
|
||||
const exit = this.transcript.entries[this.cursor];
|
||||
if (exit?.type !== "runtime_exit" || exit.status !== "success") break;
|
||||
this.cursor += 1;
|
||||
}
|
||||
this.throwFailure();
|
||||
if (this.cursor !== this.transcript.entries.length) {
|
||||
throw new OpenCodeReplayIncompleteError({
|
||||
scenario: this.transcript.scenario,
|
||||
cursor: this.cursor,
|
||||
remaining: this.transcript.entries.length - this.cursor,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private advance(): void {
|
||||
this.cursor += 1;
|
||||
for (const waiter of this.waiters) waiter();
|
||||
this.waiters.clear();
|
||||
}
|
||||
|
||||
private fail(cause: unknown): void {
|
||||
this.failure = cause;
|
||||
for (const waiter of this.waiters) waiter();
|
||||
this.waiters.clear();
|
||||
}
|
||||
|
||||
private throwFailure(): void {
|
||||
if (this.failure !== null) throw this.failure;
|
||||
}
|
||||
|
||||
private changed(signal?: AbortSignal): Promise<void> {
|
||||
if (signal?.aborted === true) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
const done = () => {
|
||||
signal?.removeEventListener("abort", done);
|
||||
this.waiters.delete(done);
|
||||
resolve();
|
||||
};
|
||||
this.waiters.add(done);
|
||||
signal?.addEventListener("abort", done, { once: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function makeReplayClient(controller: OpenCodeReplayController): OpencodeClient {
|
||||
const request = async (operation: string, input: unknown) => {
|
||||
await controller.expectOutbound({ type: operation, input });
|
||||
return { data: await controller.response(operation) };
|
||||
};
|
||||
return {
|
||||
event: {
|
||||
subscribe: async (_input?: unknown, options?: { readonly signal?: AbortSignal }) => {
|
||||
await controller.expectOutbound({ type: "event.subscribe" });
|
||||
return { stream: controller.events(options?.signal) };
|
||||
},
|
||||
},
|
||||
session: {
|
||||
create: (input: unknown) => request("session.create", input),
|
||||
get: (input: unknown) => request("session.get", input),
|
||||
update: (input: unknown) => request("session.update", input),
|
||||
messages: (input: unknown) => request("session.messages", input),
|
||||
promptAsync: (input: unknown) => request("session.promptAsync", input),
|
||||
abort: (input: unknown) => request("session.abort", input),
|
||||
revert: (input: unknown) => request("session.revert", input),
|
||||
unrevert: (input: unknown) => request("session.unrevert", input),
|
||||
fork: (input: unknown) => request("session.fork", input),
|
||||
},
|
||||
permission: {
|
||||
reply: (input: unknown) => request("permission.reply", input),
|
||||
},
|
||||
question: {
|
||||
reply: (input: unknown) => request("question.reply", input),
|
||||
},
|
||||
mcp: {
|
||||
add: (input: unknown) => request("mcp.add", input),
|
||||
},
|
||||
} as unknown as OpencodeClient;
|
||||
}
|
||||
|
||||
function makeOpenCodeReplayRuntimeLayer(transcript: OpenCodeSdkReplayTranscript) {
|
||||
return Layer.effect(
|
||||
OpenCodeRuntime,
|
||||
Effect.gen(function* () {
|
||||
const controller = new OpenCodeReplayController(transcript);
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
controller.assertComplete();
|
||||
}),
|
||||
);
|
||||
const client = makeReplayClient(controller);
|
||||
return OpenCodeRuntime.of({
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: "OpenCode replay uses an external in-memory SDK boundary.",
|
||||
}),
|
||||
),
|
||||
connectToOpenCodeServer: () =>
|
||||
Effect.succeed({
|
||||
url: "replay://opencode",
|
||||
exitCode: null,
|
||||
external: true,
|
||||
}),
|
||||
runOpenCodeCommand: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: "OpenCode replay does not execute commands.",
|
||||
}),
|
||||
),
|
||||
createOpenCodeSdkClient: () => client,
|
||||
loadOpenCodeInventory: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: "OpenCode replay does not load inventory.",
|
||||
}),
|
||||
),
|
||||
} satisfies OpenCodeRuntimeShape);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function makeOpenCodeProviderAdapterRegistryReplayLayer(
|
||||
transcript: OpenCodeSdkReplayTranscript,
|
||||
) {
|
||||
const serverConfigLayer = Layer.effect(
|
||||
ServerConfig,
|
||||
makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
return makeProviderAdapterRegistryDriverLayer({
|
||||
drivers: [OpenCodeAdapterV2Driver],
|
||||
configMap: {
|
||||
[OPENCODE_DEFAULT_INSTANCE_ID]: {
|
||||
driver: OPENCODE_DRIVER_KIND,
|
||||
config: { serverUrl: "replay://opencode" },
|
||||
},
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeOpenCodeReplayRuntimeLayer(transcript),
|
||||
serverConfigLayer,
|
||||
NodeServices.layer,
|
||||
idAllocatorLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function transcriptMetadata(transcript: ProviderReplayTranscript) {
|
||||
return {
|
||||
provider: transcript.provider,
|
||||
protocol: transcript.protocol,
|
||||
scenario: transcript.scenario,
|
||||
};
|
||||
}
|
||||
|
||||
export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
|
||||
OpenCodeSdkReplayTranscript,
|
||||
OpenCodeOrchestratorReplayHarnessError
|
||||
> = {
|
||||
provider: OPENCODE_PROVIDER,
|
||||
decodeTranscript: (transcript) =>
|
||||
decodeOpenCodeSdkReplayTranscript(transcript).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeReplayTranscriptDecodeError({
|
||||
...transcriptMetadata(transcript),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
makeProviderAdapterRegistryLayer: makeOpenCodeProviderAdapterRegistryReplayLayer,
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { CursorProviderCapabilitiesV2 } from "./Adapters/CursorAdapterV2.ts";
|
||||
import { GrokProviderCapabilitiesV2 } from "./Adapters/GrokAdapterV2.ts";
|
||||
import {
|
||||
CommandPolicyCapabilityUnsupportedError,
|
||||
CommandPolicyV2,
|
||||
@@ -62,6 +63,21 @@ layer("CommandPolicyV2", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses interrupt-and-restart steering for Grok ACP", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const result = yield* policy.decideSteeringExecution({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "grok",
|
||||
capabilities: GrokProviderCapabilitiesV2,
|
||||
});
|
||||
|
||||
assert.equal(result, "interrupt_restart");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("honors an explicit interrupt-and-restart request", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
@@ -165,6 +181,24 @@ layer("CommandPolicyV2", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to portable context when Grok ACP cannot fork natively", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const result = yield* policy.decideForkExecution({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "grok",
|
||||
capabilities: GrokProviderCapabilitiesV2,
|
||||
sameProvider: true,
|
||||
hasStrongNativeSource: true,
|
||||
fromSpecificTurn: true,
|
||||
});
|
||||
|
||||
assert.equal(result, "portable_context");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a typed error when neither native nor portable fork is available", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { OrchestratorV2 } from "./Orchestrator.ts";
|
||||
import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
|
||||
import { GROK_MODEL_SELECTION } from "./testkit/fixtures/shared.ts";
|
||||
|
||||
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-grok-v2-live-",
|
||||
});
|
||||
|
||||
const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProcess.layer),
|
||||
Layer.provide(serverConfigLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer));
|
||||
|
||||
const liveLayer = OrchestrationV2LayerLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(checkpointStoreLayer),
|
||||
Layer.provide(serverConfigLayer),
|
||||
Layer.provide(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
grok: { enabled: true },
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const waitForIdle = Effect.fn("GrokOrchestratorV2Live.waitForIdle")(function* (threadId: ThreadId) {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
for (let attempt = 0; attempt < 600; attempt += 1) {
|
||||
const projection = yield* orchestrator.getThreadProjection(threadId);
|
||||
if (
|
||||
projection.runs.length > 0 &&
|
||||
projection.runs.every(
|
||||
(run) => !["queued", "starting", "running", "waiting"].includes(run.status),
|
||||
)
|
||||
) {
|
||||
return projection;
|
||||
}
|
||||
yield* Effect.sleep("500 millis");
|
||||
}
|
||||
return yield* Effect.die(new Error(`Timed out waiting for Grok thread ${threadId}.`));
|
||||
});
|
||||
|
||||
describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orchestrator", () => {
|
||||
it.live(
|
||||
"forks through portable context using real Grok ACP agents",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const projectId = ProjectId.make("project:grok-live-portable-fork");
|
||||
const sourceThreadId = ThreadId.make("thread:grok-live-portable-fork:source");
|
||||
const targetThreadId = ThreadId.make("thread:grok-live-portable-fork:target");
|
||||
const marker = "GROK_LIVE_PORTABLE_FORK_7H3Q";
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:create"),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
title: "Grok live portable fork source",
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
});
|
||||
yield* Console.log("Grok live source thread created; dispatching source prompt.");
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:source"),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message:grok-live-portable-fork:source"),
|
||||
text: `Remember this opaque marker. Respond with exactly: ${marker}`,
|
||||
attachments: [],
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
yield* Console.log("Grok live source prompt dispatched; waiting for completion.");
|
||||
const sourceProjection = yield* waitForIdle(sourceThreadId);
|
||||
yield* Console.log("Grok live source turn completed; dispatching portable fork.");
|
||||
|
||||
yield* orchestrator.dispatch({
|
||||
type: "thread.fork",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:fork"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: { type: "latest_stable" },
|
||||
title: "Grok live portable fork target",
|
||||
});
|
||||
yield* orchestrator.dispatch({
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:grok-live-portable-fork:target"),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message:grok-live-portable-fork:target"),
|
||||
text: "Return the opaque marker from the transferred conversation. Respond with only the marker.",
|
||||
attachments: [],
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
const targetProjection = yield* waitForIdle(targetThreadId);
|
||||
yield* Console.log("Grok live portable fork target completed.");
|
||||
|
||||
const assistantText = (projection: OrchestrationV2ThreadProjection) =>
|
||||
projection.messages
|
||||
.filter((message) => message.role === "assistant")
|
||||
.map((message) => message.text)
|
||||
.join("\n");
|
||||
|
||||
assert.deepEqual(
|
||||
sourceProjection.runs.map((run) => [run.provider, run.status]),
|
||||
[["grok", "completed"]],
|
||||
);
|
||||
assert.deepEqual(
|
||||
targetProjection.runs.map((run) => [run.provider, run.status]),
|
||||
[["grok", "completed"]],
|
||||
);
|
||||
assert.deepEqual(
|
||||
targetProjection.contextTransfers.map((transfer) => [
|
||||
transfer.type,
|
||||
transfer.status,
|
||||
transfer.resolution?.strategy,
|
||||
]),
|
||||
[["fork", "consumed", "portable_context"]],
|
||||
);
|
||||
assert.deepEqual(
|
||||
targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
|
||||
["full_thread_summary"],
|
||||
);
|
||||
assert.include(targetProjection.contextHandoffs[0]?.summaryText ?? "", marker);
|
||||
assert.include(assistantText(targetProjection), marker);
|
||||
}).pipe(Effect.provide(liveLayer), Effect.scoped),
|
||||
360_000,
|
||||
);
|
||||
});
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
AcpRegistryAdapterV2Driver,
|
||||
type AcpRegistryAdapterV2DriverEnv,
|
||||
} from "./Adapters/AcpRegistryAdapterV2.ts";
|
||||
import {
|
||||
ClaudeAdapterV2Driver,
|
||||
type ClaudeAdapterV2DriverEnv,
|
||||
@@ -9,16 +13,31 @@ import {
|
||||
CursorAdapterV2Driver,
|
||||
type CursorAdapterV2DriverEnv,
|
||||
} from "./Adapters/CursorAdapterV2.ts";
|
||||
import { GrokAdapterV2Driver, type GrokAdapterV2DriverEnv } from "./Adapters/GrokAdapterV2.ts";
|
||||
import {
|
||||
OpenCodeAdapterV2Driver,
|
||||
type OpenCodeAdapterV2DriverEnv,
|
||||
} from "./Adapters/OpenCodeAdapterV2.ts";
|
||||
import type { AnyProviderAdapterDriver } from "./ProviderAdapterDriver.ts";
|
||||
|
||||
export type BuiltInProviderAdapterDriversV2Env =
|
||||
| AcpRegistryAdapterV2DriverEnv
|
||||
| ClaudeAdapterV2DriverEnv
|
||||
| CodexAdapterV2DriverEnv
|
||||
| CursorAdapterV2DriverEnv;
|
||||
| CursorAdapterV2DriverEnv
|
||||
| GrokAdapterV2DriverEnv
|
||||
| OpenCodeAdapterV2DriverEnv;
|
||||
|
||||
export const BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2: ReadonlyArray<
|
||||
AnyProviderAdapterDriver<BuiltInProviderAdapterDriversV2Env>
|
||||
> = [CodexAdapterV2Driver, ClaudeAdapterV2Driver, CursorAdapterV2Driver];
|
||||
> = [
|
||||
CodexAdapterV2Driver,
|
||||
ClaudeAdapterV2Driver,
|
||||
CursorAdapterV2Driver,
|
||||
OpenCodeAdapterV2Driver,
|
||||
GrokAdapterV2Driver,
|
||||
AcpRegistryAdapterV2Driver,
|
||||
];
|
||||
|
||||
export const BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2: ReadonlySet<ProviderDriverKind> = new Set(
|
||||
BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2.map((driver) => driver.driverKind),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import * as Layer from "effect/Layer";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts";
|
||||
import { claudeAgentSdkQueryRunnerLiveLayer } from "./Adapters/ClaudeAdapterV2.ts";
|
||||
import { codexAppServerClientFactoryFromSettingsLayer } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { cursorAgentSdkRunnerLiveLayer } from "./Adapters/CursorAgentSdk.ts";
|
||||
@@ -40,6 +42,8 @@ const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromSettings
|
||||
Layer.provide(codexAppServerClientFactoryFromSettingsLayer),
|
||||
Layer.provide(claudeAgentSdkQueryRunnerLiveLayer),
|
||||
Layer.provide(cursorAgentSdkRunnerLiveLayer),
|
||||
Layer.provide(OpenCodeRuntimeLive),
|
||||
Layer.provide(FetchHttpClient.layer),
|
||||
Layer.provide(idAllocatorLayer),
|
||||
);
|
||||
|
||||
|
||||
+9
-1
@@ -49,7 +49,15 @@ describe("orchestrator replay fixture contract", () => {
|
||||
const firstCommand = materialized.commands[0];
|
||||
|
||||
assert.equal(transcript.scenario, fixture.name);
|
||||
assert.equal(transcript.provider, provider.provider);
|
||||
if (provider.provider === "acpRegistry") {
|
||||
assert.include(
|
||||
["acpRegistry", "grok"],
|
||||
transcript.provider,
|
||||
"ACP Registry may retarget protocol-standard Grok ACP evidence",
|
||||
);
|
||||
} else {
|
||||
assert.equal(transcript.provider, provider.provider);
|
||||
}
|
||||
assert.equal(provider.modelSelection.instanceId, provider.provider);
|
||||
assert.isDefined(materialized.projectionThreadIds[0]);
|
||||
assert.equal(firstCommand?.type, "thread.create");
|
||||
|
||||
+18
@@ -7,6 +7,9 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts";
|
||||
import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts";
|
||||
import { CursorOrchestratorReplayHarness } from "../Adapters/CursorAdapterV2.testkit.ts";
|
||||
import { AcpRegistryOrchestratorReplayHarness } from "../Adapters/AcpRegistryAdapterV2.testkit.ts";
|
||||
import { GrokOrchestratorReplayHarness } from "../Adapters/GrokAdapterV2.testkit.ts";
|
||||
import { OpenCodeOrchestratorReplayHarness } from "../Adapters/OpenCodeAdapterV2.testkit.ts";
|
||||
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
|
||||
import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
|
||||
@@ -118,6 +121,21 @@ function runFixtureProviderWithRegisteredHarness(input: {
|
||||
...input,
|
||||
harness: CursorOrchestratorReplayHarness,
|
||||
}).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
|
||||
case "grok":
|
||||
return runFixtureProvider({
|
||||
...input,
|
||||
harness: GrokOrchestratorReplayHarness,
|
||||
}).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
|
||||
case "acpRegistry":
|
||||
return runFixtureProvider({
|
||||
...input,
|
||||
harness: AcpRegistryOrchestratorReplayHarness,
|
||||
}).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
|
||||
case "opencode":
|
||||
return runFixtureProvider({
|
||||
...input,
|
||||
harness: OpenCodeOrchestratorReplayHarness,
|
||||
}).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
|
||||
default:
|
||||
return Effect.die(
|
||||
new Error(`No replay harness registered for provider ${input.provider.provider}.`),
|
||||
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
type OrchestratorV2ScenarioResult,
|
||||
} from "./OrchestratorScenario.ts";
|
||||
|
||||
function makeReplayServerConfig(
|
||||
export function makeReplayServerConfig(
|
||||
scenario: string,
|
||||
): Effect.Effect<
|
||||
ServerConfigShape,
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"acp_elicitation","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"generic-acp-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete"}]}}}
|
||||
{"type":"emit_inbound","label":"elicitation.request","frame":{"kind":"request","method":"session/elicitation","params":{"sessionId":"grok-replay-session-1","mode":"form","message":"Choose the fixture preference.","requestedSchema":{"type":"object","title":"Fixture preference","properties":{"schema_vs_ui_flexibility":{"type":"string","title":"Fixture","description":"Should this fixture prefer strict schemas or UI flexibility?","enum":["Strict schemas (Recommended)","UI flexibility"]}},"required":["schema_vs_ui_flexibility"]}}}}
|
||||
{"type":"expect_outbound","label":"elicitation.response","frame":{"kind":"response","method":"session/elicitation","result":{"action":{"action":"accept","content":{"schema_vs_ui_flexibility":"Strict schemas (Recommended)"}}}}}
|
||||
{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"plan questions fixture complete"}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -1,11 +1,15 @@
|
||||
import { assertClaudeMessageSteeringOutput } from "./message_steering/claude_output.ts";
|
||||
import { assertMessageSteeringOutput } from "./message_steering/codex_output.ts";
|
||||
import { assertCursorMessageSteeringOutput } from "./message_steering/cursor_output.ts";
|
||||
import { assertGrokMessageSteeringOutput } from "./message_steering/grok_output.ts";
|
||||
import { messageSteeringInput } from "./message_steering/input.ts";
|
||||
import { assertMultiTurnClaudeOutput } from "./multi_turn/claude_output.ts";
|
||||
import { assertMultiTurnOutput } from "./multi_turn/codex_output.ts";
|
||||
import { multiTurnInput } from "./multi_turn/input.ts";
|
||||
import { openCodeSubagentInput } from "./opencode_subagent/input.ts";
|
||||
import { assertOpenCodeSubagentOutput } from "./opencode_subagent/output.ts";
|
||||
import { assertPlanQuestionsOutput } from "./plan_questions/codex_output.ts";
|
||||
import { assertOpenCodePlanQuestionsOutput } from "./plan_questions/opencode_output.ts";
|
||||
import { planQuestionsInput } from "./plan_questions/input.ts";
|
||||
import { assertProposedPlanOutput } from "./proposed_plan/codex_output.ts";
|
||||
import { assertProposedPlanCursorOutput } from "./proposed_plan/cursor_output.ts";
|
||||
@@ -26,6 +30,7 @@ import { assertThreadRollbackOutput } from "./thread_rollback/codex_output.ts";
|
||||
import { threadRollbackInput } from "./thread_rollback/input.ts";
|
||||
import { assertTodoListOutput } from "./todo_list/codex_output.ts";
|
||||
import { assertTodoListCursorOutput } from "./todo_list/cursor_output.ts";
|
||||
import { assertTodoListGrokOutput } from "./todo_list/grok_output.ts";
|
||||
import { todoListInput } from "./todo_list/input.ts";
|
||||
import { assertToolCallReadOnlyClaudeOutput } from "./tool_call_read_only/claude_output.ts";
|
||||
import { assertToolCallReadOnlyCursorOutput } from "./tool_call_read_only/cursor_output.ts";
|
||||
@@ -52,9 +57,12 @@ import { assertClaudeWebSearchOutput } from "./web_search/claude_output.ts";
|
||||
import { assertWebSearchOutput } from "./web_search/codex_output.ts";
|
||||
import { webSearchInput } from "./web_search/input.ts";
|
||||
import {
|
||||
ACP_REGISTRY_MODEL_SELECTION,
|
||||
CLAUDE_MODEL_SELECTION,
|
||||
CODEX_MODEL_SELECTION,
|
||||
CURSOR_MODEL_SELECTION,
|
||||
GROK_MODEL_SELECTION,
|
||||
OPENCODE_MODEL_SELECTION,
|
||||
READ_ONLY_NEVER_POLICY,
|
||||
READ_ONLY_ON_REQUEST_POLICY,
|
||||
RESTRICTED_GRANULAR_POLICY,
|
||||
@@ -63,6 +71,26 @@ import {
|
||||
} from "./shared.ts";
|
||||
|
||||
export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
{
|
||||
name: "acp_elicitation",
|
||||
buildInput: planQuestionsInput,
|
||||
providers: [
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertPlanQuestionsOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertPlanQuestionsOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "simple",
|
||||
buildInput: simpleInput,
|
||||
@@ -85,6 +113,24 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
modelSelection: CURSOR_MODEL_SELECTION,
|
||||
assertOutput: assertSimpleOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
assertOutput: assertSimpleOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
assertOutput: assertSimpleOutput,
|
||||
},
|
||||
{
|
||||
provider: "opencode",
|
||||
transcriptFile: new URL("./simple/opencode_transcript.ndjson", import.meta.url),
|
||||
modelSelection: OPENCODE_MODEL_SELECTION,
|
||||
assertOutput: assertSimpleOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -105,6 +151,20 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertToolCallReadOnlyCursorOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertToolCallReadOnlyCursorOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertToolCallReadOnlyCursorOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -131,6 +191,26 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY,
|
||||
assertOutput: assertToolCallReadOnlyOnRequestClaudeOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL(
|
||||
"./tool_call_read_only_on_request/grok_transcript.ndjson",
|
||||
import.meta.url,
|
||||
),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY,
|
||||
assertOutput: assertToolCallReadOnlyOnRequestOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL(
|
||||
"./tool_call_read_only_on_request/grok_transcript.ndjson",
|
||||
import.meta.url,
|
||||
),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY,
|
||||
assertOutput: assertToolCallReadOnlyOnRequestOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -223,6 +303,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "opencode_subagent",
|
||||
buildInput: openCodeSubagentInput,
|
||||
providers: [
|
||||
{
|
||||
provider: "opencode",
|
||||
transcriptFile: new URL("./opencode_subagent/opencode_transcript.ndjson", import.meta.url),
|
||||
modelSelection: OPENCODE_MODEL_SELECTION,
|
||||
assertOutput: assertOpenCodeSubagentOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "multi_turn",
|
||||
buildInput: multiTurnInput,
|
||||
@@ -245,6 +337,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
modelSelection: CURSOR_MODEL_SELECTION,
|
||||
assertOutput: assertMultiTurnOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
assertOutput: assertMultiTurnOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
assertOutput: assertMultiTurnOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -281,6 +385,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
modelSelection: CURSOR_MODEL_SELECTION,
|
||||
assertOutput: assertQueuedTurnOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
assertOutput: assertQueuedTurnOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
assertOutput: assertQueuedTurnOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -301,6 +417,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertTodoListCursorOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
assertOutput: assertTodoListGrokOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
assertOutput: assertTodoListGrokOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -332,6 +460,20 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertPlanQuestionsOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./plan_questions/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertPlanQuestionsOutput,
|
||||
},
|
||||
{
|
||||
provider: "opencode",
|
||||
transcriptFile: new URL("./plan_questions/opencode_transcript.ndjson", import.meta.url),
|
||||
modelSelection: OPENCODE_MODEL_SELECTION,
|
||||
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
|
||||
assertOutput: assertOpenCodePlanQuestionsOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -376,6 +518,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
modelSelection: CURSOR_MODEL_SELECTION,
|
||||
assertOutput: assertCursorMessageSteeringOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
assertOutput: assertGrokMessageSteeringOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
assertOutput: assertGrokMessageSteeringOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -396,6 +550,27 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
|
||||
assertOutput: assertTurnInterruptClaudeOutput,
|
||||
},
|
||||
{
|
||||
provider: "grok",
|
||||
transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: GROK_MODEL_SELECTION,
|
||||
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
|
||||
assertOutput: assertTurnInterruptOutput,
|
||||
},
|
||||
{
|
||||
provider: "acpRegistry",
|
||||
transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url),
|
||||
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
|
||||
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
|
||||
assertOutput: assertTurnInterruptOutput,
|
||||
},
|
||||
{
|
||||
provider: "opencode",
|
||||
transcriptFile: new URL("./turn_interrupt/opencode_transcript.ndjson", import.meta.url),
|
||||
modelSelection: OPENCODE_MODEL_SELECTION,
|
||||
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
|
||||
assertOutput: assertTurnInterruptOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import {
|
||||
assertAssistantTextIncludes,
|
||||
assertBaseProjection,
|
||||
assertRuntimeRequestCounts,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessageInputIntents,
|
||||
assertUserMessagesInclude,
|
||||
MESSAGE_STEERING_INITIAL_PROMPT,
|
||||
MESSAGE_STEERING_STEER_PROMPT,
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
|
||||
export function assertGrokMessageSteeringOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertTurnItemTypes(projection, ["user_message", "run_interrupt_result", "assistant_message"]);
|
||||
assertRuntimeRequestCounts(projection, { total: 0 });
|
||||
assertUserMessagesInclude(projection, [
|
||||
MESSAGE_STEERING_INITIAL_PROMPT,
|
||||
MESSAGE_STEERING_STEER_PROMPT,
|
||||
]);
|
||||
assertUserMessageInputIntents(projection, ["turn_start", "steer"]);
|
||||
assertAssistantTextIncludes(projection, "steering fixture observed");
|
||||
|
||||
assert.lengthOf(projection.runs, 1, "steering must preserve the app run");
|
||||
assert.deepEqual(
|
||||
projection.attempts.map((attempt) => [attempt.reason, attempt.status]),
|
||||
[
|
||||
["initial", "superseded"],
|
||||
["steering_restart", "completed"],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
projection.providerTurns.map((turn) => turn.status),
|
||||
["interrupted", "completed"],
|
||||
);
|
||||
assert.equal(projection.runs[0]?.activeAttemptId, projection.attempts[1]?.id);
|
||||
assert.equal(projection.runs[0]?.rootNodeId, projection.attempts[1]?.rootNodeId);
|
||||
assert.notInclude(
|
||||
projection.visibleTurnItems.map((row) => row.item.type),
|
||||
"run_interrupt_result",
|
||||
"restart steering must keep its internal interruption out of visible chat history",
|
||||
);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"message_steering","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt.1","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: steering fixture initial response"}]}}}
|
||||
{"type":"emit_inbound","label":"assistant.partial","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ste"}}}}}
|
||||
{"type":"expect_outbound","label":"session.cancel","frame":{"kind":"notification","method":"session/cancel","params":{"sessionId":"grok-replay-session-1"}}}
|
||||
{"type":"emit_inbound","label":"prompt.cancelled","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"cancelled"}}}
|
||||
{"type":"expect_outbound","label":"session.prompt.2","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Actually, respond with exactly: steering fixture observed"}]}}}
|
||||
{"type":"emit_inbound","label":"assistant.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"steering fixture "}}}}}
|
||||
{"type":"emit_inbound","label":"assistant.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"observed"}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,12 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"multi_turn","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"first.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: first fixture turn complete"}]}}}
|
||||
{"type":"emit_inbound","label":"first.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"first fixture turn complete"}}}}}
|
||||
{"type":"emit_inbound","label":"first.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"expect_outbound","label":"second.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: second fixture turn complete"}]}}}
|
||||
{"type":"emit_inbound","label":"second.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"second fixture turn complete"}}}}}
|
||||
{"type":"emit_inbound","label":"second.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { OPENCODE_SUBAGENT_PROMPT, type OrchestratorFixtureInput } from "../shared.ts";
|
||||
|
||||
export function openCodeSubagentInput(): OrchestratorFixtureInput {
|
||||
return {
|
||||
steps: [{ type: "message", text: OPENCODE_SUBAGENT_PROMPT }],
|
||||
};
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"opencode_subagent","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_1235df8f8ffekByXP7gVnnXA3P","nativeChildSessionId":"ses_1235debc9ffe9MNk00UheV2j0q","model":"openai/gpt-5.4-mini","description":"One real OpenCode task-tool delegation. The session.update boundary records the adapter policy propagation required before projecting buffered child events."}}
|
||||
{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}}
|
||||
{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"<any>","permission":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_1235df8f8ffekByXP7gVnnXA3P","slug":"kind-tiger","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode v2 probe","time":{"created":1781818066695,"updated":1781818066695}}}}
|
||||
{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK."}]}}}
|
||||
{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}}
|
||||
{"type":"emit_inbound","label":"root.user","frame":{"type":"sdk.event","event":{"id":"evt_edca20735003a32yj1UtyUpHkU","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca20735001Esh39V762TEx7f","role":"user","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","time":{"created":1781818066741},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}}
|
||||
{"type":"emit_inbound","label":"root.user.text","frame":{"type":"sdk.event","event":{"id":"evt_edca207360015UIWeYXmKllHo3","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"type":"text","text":"Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK.","messageID":"msg_edca20735001Esh39V762TEx7f","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","id":"prt_edca20735002U603TIFRMOYd9M"},"time":1781818066742}}}}
|
||||
{"type":"emit_inbound","label":"root.busy","frame":{"type":"sdk.event","event":{"id":"evt_edca207370013ecC1B3n7HWHF0","type":"session.status","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","status":{"type":"busy"}}}}}
|
||||
{"type":"emit_inbound","label":"root.assistant.tool-step","frame":{"type":"sdk.event","event":{"id":"evt_edca207380024rQ5C0LdF5jkgv","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca20738001L0AkDDqxC8ipdK","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818066744},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P"}}}}}
|
||||
{"type":"emit_inbound","label":"task.pending","frame":{"type":"sdk.event","event":{"id":"evt_edca213fb002A7172u3WxPY2Jy","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"id":"prt_edca213fb001pDRIA33EBmsHOT","messageID":"msg_edca20738001L0AkDDqxC8ipdK","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","type":"tool","tool":"task","callID":"call_MMPbMUvLDj12T5aimkDZC8Sl","state":{"status":"pending","input":{},"raw":""}},"time":1781818070011}}}}
|
||||
{"type":"emit_inbound","label":"task.running","frame":{"type":"sdk.event","event":{"id":"evt_edca21438001pcNOWgyXdKFyaI","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"type":"tool","tool":"task","callID":"call_MMPbMUvLDj12T5aimkDZC8Sl","state":{"title":"Return CHILD_OK","metadata":{"sessionId":"ses_1235debc9ffe9MNk00UheV2j0q","model":{"modelID":"gpt-5.4-mini","providerID":"openai"}},"status":"running","input":{"description":"Return CHILD_OK","prompt":"Respond exactly CHILD_OK.","subagent_type":"general","task_id":"","command":"delegate exact response"},"time":{"start":1781818070072}},"id":"prt_edca213fb001pDRIA33EBmsHOT","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","messageID":"msg_edca20738001L0AkDDqxC8ipdK"},"time":1781818070072}}}}
|
||||
{"type":"expect_outbound","label":"session.get.child-policy","frame":{"type":"session.get","input":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q"}}}
|
||||
{"type":"emit_inbound","label":"session.get.child-policy.response","frame":{"type":"sdk.response","operation":"session.get","data":{"id":"ses_1235debc9ffe9MNk00UheV2j0q","slug":"tidy-engine","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","parentID":"ses_1235df8f8ffekByXP7gVnnXA3P","title":"Return CHILD_OK (@general subagent)","version":"1.14.39","permission":[{"permission":"task","action":"deny","pattern":"*"}],"time":{"created":1781818070070,"updated":1781818070072}}}}
|
||||
{"type":"expect_outbound","label":"session.update.child-policy","frame":{"type":"session.update","input":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","permission":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.update.child-policy.response","frame":{"type":"sdk.response","operation":"session.update","data":{"id":"ses_1235debc9ffe9MNk00UheV2j0q","permission":[{"permission":"*","pattern":"*","action":"allow"},{"permission":"task","pattern":"*","action":"deny"}]}}}
|
||||
{"type":"emit_inbound","label":"child.user","frame":{"type":"sdk.event","event":{"id":"evt_edca21439002NEQt3QTkDp4ENI","type":"message.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","info":{"id":"msg_edca21438002r6NiMUSoqNKyyO","role":"user","sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","time":{"created":1781818070073},"tools":{"task":false},"agent":"general","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}}
|
||||
{"type":"emit_inbound","label":"child.user.text","frame":{"type":"sdk.event","event":{"id":"evt_edca21439003pseKePjnoGiTMW","type":"message.part.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","part":{"type":"text","text":"Respond exactly CHILD_OK.","messageID":"msg_edca21438002r6NiMUSoqNKyyO","sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","id":"prt_edca214390014Naiz0G5HjlDbr"},"time":1781818070073}}}}
|
||||
{"type":"emit_inbound","label":"child.busy","frame":{"type":"sdk.event","event":{"id":"evt_edca2143c0013lzfo6Odo5FMzE","type":"session.status","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","status":{"type":"busy"}}}}}
|
||||
{"type":"emit_inbound","label":"child.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edca2143c0033666Mhyl3cAlhK","type":"message.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","info":{"id":"msg_edca2143c002Eu46Ey4Vg2BbuM","parentID":"msg_edca21438002r6NiMUSoqNKyyO","role":"assistant","mode":"general","agent":"general","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818070076},"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q"}}}}}
|
||||
{"type":"emit_inbound","label":"child.assistant.text","frame":{"type":"sdk.event","event":{"id":"evt_edca21a3f001VbjReH1JvfruIc","type":"message.part.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","part":{"id":"prt_edca21a22001xAMVOfMPeu3Pe5","messageID":"msg_edca2143c002Eu46Ey4Vg2BbuM","sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","type":"text","text":"CHILD_OK","time":{"start":1781818071586,"end":1781818071615},"metadata":{"openai":{"itemId":"msg_08dabd7d4c704130016a3462d793f48196a3764bab4f871b8d","phase":"final_answer"}}},"time":1781818071615}}}}
|
||||
{"type":"emit_inbound","label":"child.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5d001RVnmfbE88crcg3","type":"message.updated","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","info":{"id":"msg_edca2143c002Eu46Ey4Vg2BbuM","parentID":"msg_edca21438002r6NiMUSoqNKyyO","role":"assistant","mode":"general","agent":"general","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":7538,"input":7515,"output":9,"reasoning":14,"cache":{"write":0,"read":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818070076,"completed":1781818071645},"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","finish":"stop"}}}}}
|
||||
{"type":"emit_inbound","label":"child.idle","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5d0033WtPpZQdeaACpg","type":"session.status","properties":{"sessionID":"ses_1235debc9ffe9MNk00UheV2j0q","status":{"type":"idle"}}}}}
|
||||
{"type":"emit_inbound","label":"task.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5e001nGDHspvGlDIOu3","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"type":"tool","tool":"task","callID":"call_MMPbMUvLDj12T5aimkDZC8Sl","state":{"status":"completed","input":{"description":"Return CHILD_OK","prompt":"Respond exactly CHILD_OK.","subagent_type":"general","task_id":"","command":"delegate exact response"},"output":"task_id: ses_1235debc9ffe9MNk00UheV2j0q (for resuming to continue this task if needed)\n\n<task_result>\nCHILD_OK\n</task_result>","metadata":{"sessionId":"ses_1235debc9ffe9MNk00UheV2j0q","model":{"modelID":"gpt-5.4-mini","providerID":"openai"},"truncated":false},"title":"Return CHILD_OK","time":{"start":1781818070075,"end":1781818071646}},"metadata":{"openai":{"itemId":"fc_0f59e88787b4bf7e016a3462d5f5d08196893b4fa241992c81"}},"id":"prt_edca213fb001pDRIA33EBmsHOT","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","messageID":"msg_edca20738001L0AkDDqxC8ipdK"},"time":1781818071646}}}}
|
||||
{"type":"emit_inbound","label":"root.assistant.tool-step.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5f001I6X2xOrOgrkGi4","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca20738001L0AkDDqxC8ipdK","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":10945,"input":10835,"output":43,"reasoning":67,"cache":{"write":0,"read":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818066744,"completed":1781818071647},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","finish":"tool-calls"}}}}}
|
||||
{"type":"emit_inbound","label":"root.assistant.final-step","frame":{"type":"sdk.event","event":{"id":"evt_edca21a5f004jTKIwlcQchMbZY","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca21a5f003lreMfrQqG0qWIe","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818071647},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P"}}}}}
|
||||
{"type":"emit_inbound","label":"root.assistant.text","frame":{"type":"sdk.event","event":{"id":"evt_edca21e36001X0l8t5UPa1gOe3","type":"message.part.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","part":{"id":"prt_edca21d9e001I40GbbzvlzhQ6Z","messageID":"msg_edca21a5f003lreMfrQqG0qWIe","sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","type":"text","text":"PARENT_OK","time":{"start":1781818072478,"end":1781818072630},"metadata":{"openai":{"itemId":"msg_06e59296cb53fc7c016a3462d879288196aead5e9838c741df","phase":"final_answer"}}},"time":1781818072630}}}}
|
||||
{"type":"emit_inbound","label":"root.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edca21e3800181OyYIBTDTTK3r","type":"message.updated","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","info":{"id":"msg_edca21a5f003lreMfrQqG0qWIe","parentID":"msg_edca20735001Esh39V762TEx7f","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":11007,"input":248,"output":7,"reasoning":0,"cache":{"write":0,"read":10752}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818071647,"completed":1781818072632},"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","finish":"stop"}}}}}
|
||||
{"type":"emit_inbound","label":"root.idle","frame":{"type":"sdk.event","event":{"id":"evt_edca21e39001lo71BB2Ym4WFC2","type":"session.status","properties":{"sessionID":"ses_1235df8f8ffekByXP7gVnnXA3P","status":{"type":"idle"}}}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import {
|
||||
assertAssistantTextIncludes,
|
||||
assertBaseProjection,
|
||||
assertExecutionNodeKinds,
|
||||
assertNoExtraAppRunsForProviderChildren,
|
||||
assertRunProviderTurnCardinality,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
OPENCODE_SUBAGENT_PROMPT,
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
|
||||
export function assertOpenCodeSubagentOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "subagent", "assistant_message"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "subagent", "assistant_message"]);
|
||||
assertRunProviderTurnCardinality({ projection, rootRunCount: 1 });
|
||||
assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 1 });
|
||||
assertUserMessagesInclude(projection, [OPENCODE_SUBAGENT_PROMPT]);
|
||||
assertAssistantTextIncludes(projection, "PARENT_OK");
|
||||
|
||||
assert.lengthOf(projection.subagents, 1);
|
||||
assert.lengthOf(result.shellSnapshot.threads, 2);
|
||||
const subagent = projection.subagents[0];
|
||||
assert.isDefined(subagent);
|
||||
assert.equal(subagent.origin, "provider_native");
|
||||
assert.equal(subagent.createdBy, "agent");
|
||||
assert.equal(subagent.provider, "opencode");
|
||||
assert.equal(subagent.status, "completed");
|
||||
assert.equal(subagent.prompt, "Respond exactly CHILD_OK.");
|
||||
assert.include(subagent.result ?? "", "CHILD_OK");
|
||||
assert.isNotNull(subagent.childThreadId);
|
||||
assert.isNotNull(subagent.providerThreadId);
|
||||
assert.isNotNull(subagent.nativeTaskRef);
|
||||
assert.isNotNull(subagent.completedAt);
|
||||
if (subagent.childThreadId === null || subagent.providerThreadId === null) {
|
||||
throw new Error("OpenCode subagent is missing its child thread identity");
|
||||
}
|
||||
|
||||
const providerThread = projection.providerThreads.find(
|
||||
(thread) => thread.id === subagent.providerThreadId,
|
||||
);
|
||||
assert.isDefined(providerThread);
|
||||
assert.equal(providerThread.appThreadId, subagent.childThreadId);
|
||||
assert.equal(providerThread.ownerNodeId, subagent.id);
|
||||
|
||||
const childProjection = result.projections.get(subagent.childThreadId);
|
||||
assert.isDefined(childProjection);
|
||||
assert.equal(childProjection.thread.lineage.parentThreadId, projection.thread.id);
|
||||
assert.equal(childProjection.thread.lineage.relationshipToParent, "subagent");
|
||||
assert.equal(childProjection.thread.activeProviderThreadId, providerThread.id);
|
||||
assert.lengthOf(childProjection.runs, 0);
|
||||
assert.lengthOf(childProjection.providerThreads, 1);
|
||||
assert.lengthOf(childProjection.providerTurns, 1);
|
||||
assert.equal(childProjection.providerTurns[0]?.status, "completed");
|
||||
assertExecutionNodeKinds(childProjection, ["root_turn", "assistant_message"]);
|
||||
assertTurnItemTypes(childProjection, ["user_message", "assistant_message"]);
|
||||
assertUserMessagesInclude(childProjection, ["Respond exactly CHILD_OK."]);
|
||||
assertAssistantTextIncludes(childProjection, "CHILD_OK");
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
projectionFor,
|
||||
} from "../shared.ts";
|
||||
|
||||
export function assertPlanQuestionsOutput(
|
||||
export function assertPlanQuestionsOutputBase(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
@@ -35,7 +35,15 @@ export function assertPlanQuestionsOutput(
|
||||
assertTurnItemTypes(projection, ["user_message", "user_input_request", "assistant_message"]);
|
||||
assertUserMessagesInclude(projection, [PLAN_QUESTIONS_PROMPT]);
|
||||
assertAssistantTextIncludes(projection, "plan questions fixture complete");
|
||||
}
|
||||
|
||||
export function assertPlanQuestionsOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertPlanQuestionsOutputBase(result, transcript);
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
const requestItem = projection.turnItems.find((item) => item.type === "user_input_request");
|
||||
assert.isDefined(requestItem);
|
||||
assert.equal(requestItem?.questions[0]?.id, "schema_vs_ui_flexibility");
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"plan_questions","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete"}]}}}
|
||||
{"type":"emit_inbound","label":"question.request","frame":{"kind":"request","method":"_x.ai/ask_user_question","params":{"method":"x.ai/ask_user_question","params":{"sessionId":"grok-replay-session-1","toolCallId":"ask-user-question-tool-call-1","questions":[{"id":"schema_vs_ui_flexibility","question":"For this fixture, should the plan prefer strict schemas or UI flexibility?","multiSelect":null,"options":[{"label":"Strict schemas (Recommended)","description":"Favor precise contracts and validation."},{"label":"UI flexibility","description":"Favor looser fixture shapes."}]}],"mode":"plan"}}}}
|
||||
{"type":"expect_outbound","label":"question.response","frame":{"kind":"response","method":"_x.ai/ask_user_question","result":{"outcome":"accepted","answers":{"For this fixture, should the plan prefer strict schemas or UI flexibility?":["Strict schemas (Recommended)"]}}}}
|
||||
{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"plan questions fixture complete"}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -9,6 +9,7 @@ export function planQuestionsInput(): OrchestratorFixtureInput {
|
||||
type: "answer_next_user_input_request",
|
||||
answers: {
|
||||
schema_vs_ui_flexibility: "Strict schemas (Recommended)",
|
||||
"question-0-schema-vs-flexibility": "Strict schemas",
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import { assertPlanQuestionsOutputBase } from "./codex_output.ts";
|
||||
import { projectionFor } from "../shared.ts";
|
||||
|
||||
export function assertOpenCodePlanQuestionsOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
// The shared assertions cover the runtime-request lifecycle. OpenCode owns
|
||||
// its question identifiers, so assert its normalized native header instead
|
||||
// of Codex's fixture-specific id.
|
||||
assertPlanQuestionsOutputBase(result, transcript);
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
const requestItem = projection.turnItems.find((item) => item.type === "user_input_request");
|
||||
assert.equal(requestItem?.questions[0]?.id, "question-0-schema-vs-flexibility");
|
||||
assert.equal(requestItem?.status, "completed");
|
||||
assert.lengthOf(
|
||||
projection.turnItems.filter(
|
||||
(item) => item.type === "dynamic_tool" && item.toolName === "question",
|
||||
),
|
||||
0,
|
||||
);
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"plan_questions","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_12369ea4cffePl0BsyVg3hGlmZ","model":"openai/gpt-5.4-mini","filteredToRelevantEvents":true,"description":"Real structured-question request/reply and continuation across two assistant steps."}}
|
||||
{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}}
|
||||
{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"<any>","permission":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_12369ea4cffePl0BsyVg3hGlmZ","slug":"mighty-harbor","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode v2 probe","time":{"created":1781817284019,"updated":1781817284019}}}}
|
||||
{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete"}]}}}
|
||||
{"type":"emit_inbound","label":"message.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bb003WEUXUNfpZxMZDD","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9615bb001iCnWab1qzSeRA3","role":"user","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","time":{"created":1781817284027},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}}
|
||||
{"type":"emit_inbound","label":"message.part.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bc001l8KO7edlPViXO0","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"type":"text","text":"Use request_user_input to ask one multiple-choice clarifying question about whether this fixture should prefer strict schemas or UI flexibility. After receiving the answer, respond exactly: plan questions fixture complete","messageID":"msg_edc9615bb001iCnWab1qzSeRA3","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","id":"prt_edc9615bb002fjGpO5oeQE22B9"},"time":1781817284028}}}}
|
||||
{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}}
|
||||
{"type":"emit_inbound","label":"session.status.busy","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bd0012brtruCEXYmNyX","type":"session.status","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","status":{"type":"busy"}}}}}
|
||||
{"type":"emit_inbound","label":"message.updated.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edc9615bd003GQj8GzeHgoMlZ2","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9615bd002qb49gh9N1krbX2","parentID":"msg_edc9615bb001iCnWab1qzSeRA3","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817284029},"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ"}}}}}
|
||||
{"type":"emit_inbound","label":"reasoning.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc96244e001ez77NBs6gJaPZh","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"id":"prt_edc961988001aollEeE48XSJDg","messageID":"msg_edc9615bd002qb49gh9N1krbX2","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","type":"reasoning","text":"Clarifying user input before asking the structured question.","time":{"start":1781817285000,"end":1781817287757}},"time":1781817287757}}}}
|
||||
{"type":"emit_inbound","label":"question.tool.pending","frame":{"type":"sdk.event","event":{"id":"evt_edc96244e003ljcUzfVu0WTFc2","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"id":"prt_edc96244e002RBYg9ASwc10E8R","messageID":"msg_edc9615bd002qb49gh9N1krbX2","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","type":"tool","tool":"question","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT","state":{"status":"pending","input":{},"raw":""}},"time":1781817287758}}}}
|
||||
{"type":"emit_inbound","label":"question.asked","frame":{"type":"sdk.event","event":{"id":"evt_edc9624d90022x2I3Rv9S6t1tt","type":"question.asked","properties":{"id":"que_edc9624d9001e2GFKX724Z8b5Z","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","questions":[{"question":"Should this fixture prefer strict schemas or UI flexibility?","header":"Schema vs Flexibility","options":[{"label":"Strict schemas","description":"Prioritize validation and exact structure over visual freedom."},{"label":"UI flexibility","description":"Prioritize adaptable rendering and tolerant input handling."}],"multiple":false}],"tool":{"messageID":"msg_edc9615bd002qb49gh9N1krbX2","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT"}}}}}
|
||||
{"type":"expect_outbound","label":"question.reply","frame":{"type":"question.reply","input":{"requestID":"que_edc9624d9001e2GFKX724Z8b5Z","answers":[["Strict schemas"]]}}}
|
||||
{"type":"emit_inbound","label":"question.reply.response","frame":{"type":"sdk.response","operation":"question.reply","data":true}}
|
||||
{"type":"emit_inbound","label":"question.tool.running","frame":{"type":"sdk.event","event":{"id":"evt_edc9624da001qamTLzcYoY2CPY","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"type":"tool","tool":"question","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT","state":{"status":"running","input":{"questions":[{"question":"Should this fixture prefer strict schemas or UI flexibility?","header":"Schema vs Flexibility","options":[{"label":"Strict schemas","description":"Prioritize validation and exact structure over visual freedom."},{"label":"UI flexibility","description":"Prioritize adaptable rendering and tolerant input handling."}],"multiple":false}]},"raw":"","time":{"start":1781817287898}},"id":"prt_edc96244e002RBYg9ASwc10E8R","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","messageID":"msg_edc9615bd002qb49gh9N1krbX2"},"time":1781817287898}}}}
|
||||
{"type":"emit_inbound","label":"question.replied","frame":{"type":"sdk.event","event":{"id":"evt_edc9624de001JBbX1qaXzgfeKl","type":"question.replied","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","requestID":"que_edc9624d9001e2GFKX724Z8b5Z","answers":[["Strict schemas"]]}}}}
|
||||
{"type":"emit_inbound","label":"question.tool.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc9624df001Pw6H7GGa8tCa3V","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"type":"tool","tool":"question","callID":"call_XU0dxWGu2ioLZscBtYAIqGfT","state":{"status":"completed","input":{"questions":[{"question":"Should this fixture prefer strict schemas or UI flexibility?","header":"Schema vs Flexibility","options":[{"label":"Strict schemas","description":"Prioritize validation and exact structure over visual freedom."},{"label":"UI flexibility","description":"Prioritize adaptable rendering and tolerant input handling."}],"multiple":false}]},"output":"User answered: Strict schemas","metadata":{"answers":[["Strict schemas"]],"truncated":false},"title":"Asked 1 question","time":{"start":1781817287898,"end":1781817287903}},"id":"prt_edc96244e002RBYg9ASwc10E8R","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","messageID":"msg_edc9615bd002qb49gh9N1krbX2"},"time":1781817287903}}}}
|
||||
{"type":"emit_inbound","label":"message.updated.assistant.second-step","frame":{"type":"sdk.event","event":{"id":"evt_edc9624fa002nuPVbTfhxoDpJh","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9624fa0015O6R1rRjuqc4uS","parentID":"msg_edc9615bb001iCnWab1qzSeRA3","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817287930},"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ"}}}}}
|
||||
{"type":"emit_inbound","label":"assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc9628b5001owQkxpRhqtRF5N","type":"message.part.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","part":{"id":"prt_edc962867001us1nuabvajQrgu","messageID":"msg_edc9624fa0015O6R1rRjuqc4uS","sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","type":"text","text":"plan questions fixture complete","time":{"start":1781817288807,"end":1781817288885}},"time":1781817288885}}}}
|
||||
{"type":"emit_inbound","label":"message.updated.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc9628bf002uUONicDkn1X7YA","type":"message.updated","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","info":{"id":"msg_edc9624fa0015O6R1rRjuqc4uS","parentID":"msg_edc9615bb001iCnWab1qzSeRA3","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":11041,"input":281,"output":8,"reasoning":0,"cache":{"write":0,"read":10752}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817287930,"completed":1781817288895},"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","finish":"stop"}}}}}
|
||||
{"type":"emit_inbound","label":"session.status.idle","frame":{"type":"sdk.event","event":{"id":"evt_edc9628c00021lW2ZypKwU71AE","type":"session.status","properties":{"sessionID":"ses_12369ea4cffePl0BsyVg3hGlmZ","status":{"type":"idle"}}}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,12 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"queued_turn","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"first.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: first fixture turn complete"}]}}}
|
||||
{"type":"emit_inbound","label":"first.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"first fixture turn complete"}}}}}
|
||||
{"type":"emit_inbound","label":"first.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"expect_outbound","label":"queued.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with exactly: second fixture turn complete"}]}}}
|
||||
{"type":"emit_inbound","label":"queued.assistant","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"second fixture turn complete"}}}}}
|
||||
{"type":"emit_inbound","label":"queued.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -42,6 +42,8 @@ export const MESSAGE_STEERING_INITIAL_PROMPT =
|
||||
"Respond with exactly: steering fixture initial response";
|
||||
export const SUBAGENT_PROMPT =
|
||||
"Spawn 2 subagents, one to read package.json and one to read tsconfig.json";
|
||||
export const OPENCODE_SUBAGENT_PROMPT =
|
||||
"Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK.";
|
||||
export const SUBAGENT_CONTINUE_PROMPT =
|
||||
"Spawn one subagent and have it reply exactly: initial subagent response";
|
||||
export const SUBAGENT_CONTINUE_PARENT_PROMPT =
|
||||
@@ -237,6 +239,22 @@ export const CURSOR_MODEL_SELECTION = {
|
||||
model: "composer-2.5",
|
||||
} satisfies ModelSelection;
|
||||
|
||||
export const GROK_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("grok"),
|
||||
model: "grok-build",
|
||||
} satisfies ModelSelection;
|
||||
|
||||
export const OPENCODE_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5.4-mini",
|
||||
options: [{ id: "agent", value: "build" }],
|
||||
} satisfies ModelSelection;
|
||||
|
||||
export const ACP_REGISTRY_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("acpRegistry"),
|
||||
model: "default",
|
||||
} satisfies ModelSelection;
|
||||
|
||||
export const READ_ONLY_ON_REQUEST_POLICY = {
|
||||
approvalPolicy: "on-request",
|
||||
sandboxPolicy: {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"simple","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"},{"modelId":"grok-composer-2.5-fast","name":"Grok Composer 2.5 Fast"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Respond with the following text: fixture simple ok"}]}}}
|
||||
{"type":"emit_inbound","label":"reasoning.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"I should "}}}}}
|
||||
{"type":"emit_inbound","label":"reasoning.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"answer exactly."}}}}}
|
||||
{"type":"emit_inbound","label":"assistant.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"fixture simple "}}}}}
|
||||
{"type":"emit_inbound","label":"assistant.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ok"}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,19 @@
|
||||
{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"simple","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_1236c522dffeunHBidt20OIzWc","model":"openai/gpt-5.4-mini","description":"One real OpenCode session and text-only turn, captured at the SDK request/SSE boundary."}}
|
||||
{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}}
|
||||
{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"<any>","permission":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_1236c522dffeunHBidt20OIzWc","slug":"shiny-tiger","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode v2 probe","time":{"created":1781817126354,"updated":1781817126354}}}}
|
||||
{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Respond with the following text: fixture simple ok"}]}}}
|
||||
{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}}
|
||||
{"type":"emit_inbound","label":"message.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edc93ade5002giWB7gMKgKTh1N","type":"message.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","info":{"role":"user","time":{"created":1781817126365},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"id":"msg_edc93addd001jzzrE6lotn7BJj","sessionID":"ses_1236c522dffeunHBidt20OIzWc","summary":{"diffs":[]}}}}}}
|
||||
{"type":"emit_inbound","label":"session.status.busy","frame":{"type":"sdk.event","event":{"id":"evt_edc93ade80015pjdCBdTty67tQ","type":"session.status","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","status":{"type":"busy"}}}}}
|
||||
{"type":"emit_inbound","label":"step-start","frame":{"type":"sdk.event","event":{"id":"evt_edc93b29c002bOE0jF6Ngtp9WQ","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b29c001e2RRrSU0wC3EBK","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"step-start"},"time":1781817127580}}}}
|
||||
{"type":"emit_inbound","label":"reasoning.started","frame":{"type":"sdk.event","event":{"id":"evt_edc93b3ac002IjQHVrdbEr0grF","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b3ac0018TDuhzb5SgaTNW","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"reasoning","text":"","time":{"start":1781817127852},"metadata":{"openai":{"itemId":"rs_0cebf1703d45601c016a345f27cd448193bf5ca8d64792912b","reasoningEncryptedContent":"<redacted>"}}},"time":1781817127852}}}}
|
||||
{"type":"emit_inbound","label":"reasoning.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5b7001F8JgWVWz3axRi4","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b3ac0018TDuhzb5SgaTNW","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"reasoning","text":"","time":{"start":1781817127852,"end":1781817128375},"metadata":{"openai":{"itemId":"rs_0cebf1703d45601c016a345f27cd448193bf5ca8d64792912b","reasoningEncryptedContent":"<redacted>"}}},"time":1781817128375}}}}
|
||||
{"type":"emit_inbound","label":"assistant.started","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5b8002b8hqk8j4ycOQDv","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b5b8001T13mKZn2DRRWdH","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"text","text":"","time":{"start":1781817128376},"metadata":{"openai":{"itemId":"msg_0cebf1703d45601c016a345f284b7c819398d57b692541e5a1","phase":"final_answer"}}},"time":1781817128376}}}}
|
||||
{"type":"emit_inbound","label":"assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5b90010jWiRMyH8CF4tS","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b5b8001T13mKZn2DRRWdH","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"text","text":"fixture simple ok","time":{"start":1781817128376,"end":1781817128377},"metadata":{"openai":{"itemId":"msg_0cebf1703d45601c016a345f284b7c819398d57b692541e5a1","phase":"final_answer"}}},"time":1781817128377}}}}
|
||||
{"type":"emit_inbound","label":"step-finish","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d500236244jGWEFb6ac","type":"message.part.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","part":{"id":"prt_edc93b5d5001CPBPBe0mxI1DbU","reason":"stop","messageID":"msg_edc93ade1001nkGj5Jt1JAd8nq","sessionID":"ses_1236c522dffeunHBidt20OIzWc","type":"step-finish","tokens":{"total":10837,"input":571,"output":9,"reasoning":17,"cache":{"write":0,"read":10240}},"cost":0},"time":1781817128405}}}}
|
||||
{"type":"emit_inbound","label":"message.updated.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d6001bMOQP8gbJZ0od6","type":"message.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","info":{"id":"msg_edc93ade1001nkGj5Jt1JAd8nq","parentID":"msg_edc93addd001jzzrE6lotn7BJj","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":10837,"input":571,"output":9,"reasoning":17,"cache":{"write":0,"read":10240}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817126369},"sessionID":"ses_1236c522dffeunHBidt20OIzWc","finish":"stop"}}}}}
|
||||
{"type":"emit_inbound","label":"message.updated.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d7001XXJei8Ixk5qMHN","type":"message.updated","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","info":{"id":"msg_edc93ade1001nkGj5Jt1JAd8nq","parentID":"msg_edc93addd001jzzrE6lotn7BJj","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"total":10837,"input":571,"output":9,"reasoning":17,"cache":{"write":0,"read":10240}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781817126369,"completed":1781817128407},"sessionID":"ses_1236c522dffeunHBidt20OIzWc","finish":"stop"}}}}}
|
||||
{"type":"emit_inbound","label":"session.status.busy.finalizing","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d7002NYE00v0LorwLmf","type":"session.status","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","status":{"type":"busy"}}}}}
|
||||
{"type":"emit_inbound","label":"session.status.idle","frame":{"type":"sdk.event","event":{"id":"evt_edc93b5d8001wkyQQVJNv3M9vP","type":"session.status","properties":{"sessionID":"ses_1236c522dffeunHBidt20OIzWc","status":{"type":"idle"}}}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import {
|
||||
assertAssistantTextIncludes,
|
||||
assertBaseProjection,
|
||||
assertExecutionNodeKinds,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
TODO_LIST_PROMPT,
|
||||
} from "../shared.ts";
|
||||
|
||||
export function assertTodoListGrokOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "todo_list", "tool_call"]);
|
||||
assertTurnItemTypes(projection, [
|
||||
"user_message",
|
||||
"todo_list",
|
||||
"file_search",
|
||||
"assistant_message",
|
||||
]);
|
||||
assertUserMessagesInclude(projection, [TODO_LIST_PROMPT]);
|
||||
assertAssistantTextIncludes(projection, "todo list fixture complete");
|
||||
|
||||
const planEvents = result.domainEvents.filter((event) => event.type === "plan.updated");
|
||||
assert.lengthOf(planEvents, 2);
|
||||
assert.lengthOf(
|
||||
new Set(planEvents.map((event) => (event.type === "plan.updated" ? event.payload.id : null))),
|
||||
1,
|
||||
"ACP plan updates must preserve one plan identity",
|
||||
);
|
||||
const todoLists = projection.plans.filter((plan) => plan.kind === "todo_list");
|
||||
assert.isAtLeast(todoLists.length, 1);
|
||||
assert.deepEqual(
|
||||
todoLists.at(-1)?.steps.map((step) => step.status),
|
||||
["completed", "completed", "completed"],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"todo_list","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete"}]}}}
|
||||
{"type":"emit_inbound","label":"assistant.progress","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I'll track the three steps and inspect both files."}}}}}
|
||||
{"type":"emit_inbound","label":"plan.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"plan","entries":[{"content":"Inspect package.json","priority":"high","status":"in_progress"},{"content":"Inspect tsconfig.json","priority":"high","status":"pending"},{"content":"Report completion","priority":"high","status":"pending"}]}}}}
|
||||
{"type":"emit_inbound","label":"tool.package.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-package","title":"Read package.json","kind":"read","status":"pending","rawInput":{"path":"package.json"}}}}}
|
||||
{"type":"emit_inbound","label":"tool.package.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-package","status":"completed","rawOutput":{"content":"{\"name\":\"t3\"}"}}}}}
|
||||
{"type":"emit_inbound","label":"tool.tsconfig.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-tsconfig","title":"Read tsconfig.json","kind":"read","status":"pending","rawInput":{"path":"tsconfig.json"}}}}}
|
||||
{"type":"emit_inbound","label":"tool.tsconfig.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-tsconfig","status":"completed","rawOutput":{"content":"{\"compilerOptions\":{}}"}}}}}
|
||||
{"type":"emit_inbound","label":"plan.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"plan","entries":[{"content":"Inspect package.json","priority":"high","status":"completed"},{"content":"Inspect tsconfig.json","priority":"high","status":"completed"},{"content":"Report completion","priority":"high","status":"completed"}]}}}}
|
||||
{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"todo list fixture complete"}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"tool_call_read_only","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Read /tmp/claude-replay-tool_call_read_only/package.json and /tmp/claude-replay-tool_call_read_only/tsconfig.json, then answer exactly: read only tool fixture complete"}]}}}
|
||||
{"type":"emit_inbound","label":"assistant.progress","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Reading both files now.\n"}}}}}
|
||||
{"type":"emit_inbound","label":"tool.package.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-package","title":"Read package.json","kind":"read","status":"pending","rawInput":{"path":"/tmp/claude-replay-tool_call_read_only/package.json"}}}}}
|
||||
{"type":"emit_inbound","label":"tool.package.running","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-package","status":"in_progress"}}}}
|
||||
{"type":"emit_inbound","label":"tool.package.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-package","status":"completed","rawOutput":{"content":"{\"name\":\"cursor-read-only-fixture\"}"}}}}}
|
||||
{"type":"emit_inbound","label":"tool.tsconfig.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"read-tsconfig","title":"Read tsconfig.json","kind":"read","status":"pending","rawInput":{"path":"/tmp/claude-replay-tool_call_read_only/tsconfig.json"}}}}}
|
||||
{"type":"emit_inbound","label":"tool.tsconfig.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"read-tsconfig","status":"completed","rawOutput":{"content":"{\"compilerOptions\":{\"target\":\"ES2022\"}}"}}}}}
|
||||
{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"read only tool fixture complete"}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"tool_call_read_only_on_request","metadata":{"generatedBy":"live-grok-shape-probe","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Create or overwrite .codex-probe-write-action.txt with exactly this text: codex app-server approval fixture. Use a local shell command or file edit only, then briefly report what happened. Do not read package metadata, use GitHub, use web, or use MCP."}]}}}
|
||||
{"type":"emit_inbound","label":"tool.started","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call","toolCallId":"write-probe","title":"Write probe file","kind":"execute","status":"pending","rawInput":{"command":"printf fixture > .codex-probe-write-action.txt"}}}}}
|
||||
{"type":"emit_inbound","label":"permission.request","frame":{"kind":"request","method":"session/request_permission","params":{"sessionId":"grok-replay-session-1","toolCall":{"toolCallId":"write-probe","title":"Write probe file","kind":"execute","status":"pending","content":[{"type":"content","content":{"type":"text","text":"Write .codex-probe-write-action.txt"}}]},"options":[{"optionId":"allow-once","name":"Allow once","kind":"allow_once"},{"optionId":"allow-always","name":"Allow for session","kind":"allow_always"},{"optionId":"reject-once","name":"Reject","kind":"reject_once"}]}}}
|
||||
{"type":"expect_outbound","label":"permission.response","frame":{"kind":"response","method":"session/request_permission","result":{"outcome":{"outcome":"selected","optionId":"allow-once"}}}}
|
||||
{"type":"emit_inbound","label":"tool.completed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"write-probe","status":"completed","rawOutput":{"exitCode":0,"stdout":"","stderr":""}}}}}
|
||||
{"type":"emit_inbound","label":"assistant.final","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Created the requested probe file."}}}}}
|
||||
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
{"type":"transcript_start","provider":"grok","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"turn_interrupt","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}}
|
||||
{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{}}},"clientInfo":{"name":"t3-code","version":"0.0.0"}}}}
|
||||
{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}}
|
||||
{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"<workspace>","mcpServers":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"}]}}}}
|
||||
{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."}]}}}
|
||||
{"type":"expect_outbound","label":"session.cancel","frame":{"kind":"notification","method":"session/cancel","params":{"sessionId":"grok-replay-session-1"}}}
|
||||
{"type":"emit_inbound","label":"prompt.cancelled","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"cancelled"}}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.14.39","scenario":"turn_interrupt","metadata":{"source":"authenticated-opencode-sdk-probe","capturedAt":"2026-06-18","nativeSessionId":"ses_123570840ffenLEumkPQfegGCd","model":"openai/gpt-5.4-mini","filteredToRelevantEvents":true,"description":"A real immediate session abort where the authoritative idle notification arrived before the abort HTTP response."}}
|
||||
{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}}
|
||||
{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"<any>","permission":"<any>"}}}
|
||||
{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_123570840ffenLEumkPQfegGCd","slug":"shiny-wolf","version":"1.14.39","projectID":"global","directory":"/private/tmp/t3-opencode-probe","path":"private/tmp/t3-opencode-probe","title":"T3 OpenCode interrupt probe","permission":[{"permission":"bash","pattern":"*","action":"deny"},{"permission":"edit","pattern":"*","action":"deny"},{"permission":"webfetch","pattern":"*","action":"deny"},{"permission":"websearch","pattern":"*","action":"deny"},{"permission":"codesearch","pattern":"*","action":"deny"},{"permission":"external_directory","pattern":"*","action":"deny"},{"permission":"question","pattern":"*","action":"allow"},{"permission":"read","pattern":"*","action":"allow"},{"permission":"glob","pattern":"*","action":"allow"},{"permission":"grep","pattern":"*","action":"allow"},{"permission":"lsp","pattern":"*","action":"allow"},{"permission":"todowrite","pattern":"*","action":"allow"},{"permission":"task","pattern":"*","action":"allow"},{"permission":"skill","pattern":"*","action":"allow"},{"permission":"doom_loop","pattern":"*","action":"allow"},{"permission":"edit","pattern":"*","action":"allow"}],"time":{"created":1781818521535,"updated":1781818521535}}}}
|
||||
{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."}]}}}
|
||||
{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}}
|
||||
{"type":"expect_outbound","label":"session.abort","frame":{"type":"session.abort","input":{"sessionID":"ses_123570840ffenLEumkPQfegGCd"}}}
|
||||
{"type":"emit_inbound","label":"message.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7ca002yIVK4oYgGErvdA","type":"message.updated","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","info":{"id":"msg_edca8f7c9001w8R30p1SpzPuUJ","role":"user","sessionID":"ses_123570840ffenLEumkPQfegGCd","time":{"created":1781818521545},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}}
|
||||
{"type":"emit_inbound","label":"message.part.updated.user","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7ca00377fxNZjgW62lds","type":"message.part.updated","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","part":{"type":"text","text":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.","messageID":"msg_edca8f7c9001w8R30p1SpzPuUJ","sessionID":"ses_123570840ffenLEumkPQfegGCd","id":"prt_edca8f7ca001ugmdiNWtC2964M"},"time":1781818521546}}}}
|
||||
{"type":"emit_inbound","label":"session.status.busy","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7cc001qWTqVj4Xrui4Sc","type":"session.status","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","status":{"type":"busy"}}}}}
|
||||
{"type":"emit_inbound","label":"message.updated.assistant","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7cc003brTfV2AHRR2C61","type":"message.updated","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","info":{"id":"msg_edca8f7cc002W56d1gpf5e17kX","parentID":"msg_edca8f7c9001w8R30p1SpzPuUJ","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/private/tmp/t3-opencode-probe","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1781818521548},"sessionID":"ses_123570840ffenLEumkPQfegGCd"}}}}}
|
||||
{"type":"emit_inbound","label":"session.status.idle","frame":{"type":"sdk.event","event":{"id":"evt_edca8f7d0001Gjy7U3InhsfliL","type":"session.status","properties":{"sessionID":"ses_123570840ffenLEumkPQfegGCd","status":{"type":"idle"}}}}}
|
||||
{"type":"emit_inbound","label":"session.abort.response","frame":{"type":"sdk.response","operation":"session.abort","data":true}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -10,7 +10,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
|
||||
import {
|
||||
AcpSessionRuntime,
|
||||
selectAcpAgentAuthMethod,
|
||||
type AcpSessionRequestLogEvent,
|
||||
} from "./AcpSessionRuntime.ts";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -19,6 +23,17 @@ const mockAgentCommand = "node";
|
||||
const mockAgentArgs = [mockAgentPath];
|
||||
|
||||
describe("AcpSessionRuntime", () => {
|
||||
it("selects explicit or agent-managed authentication without choosing terminal auth", () => {
|
||||
const methods = [
|
||||
{ id: "browser", name: "Browser", type: "terminal" as const },
|
||||
{ id: "api-key", name: "API key" },
|
||||
];
|
||||
|
||||
expect(selectAcpAgentAuthMethod(methods)?.id).toBe("api-key");
|
||||
expect(selectAcpAgentAuthMethod(methods, "browser")?.id).toBe("browser");
|
||||
expect(selectAcpAgentAuthMethod(methods, "missing")).toBeUndefined();
|
||||
});
|
||||
|
||||
it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
@@ -62,6 +77,82 @@ describe("AcpSessionRuntime", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not authenticate when an advertised method is not required", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
expect(
|
||||
requestEvents.filter((event) => event.status === "started").map((event) => event.method),
|
||||
).toEqual(["initialize", "session/new"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: { T3_ACP_AUTH_METHOD_ID: "test" },
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
requestLogger: (event) =>
|
||||
Effect.sync(() => {
|
||||
requestEvents.push(event);
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("authenticates and retries once after session creation returns auth_required", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
|
||||
expect(started.sessionId).toBe("mock-session-1");
|
||||
expect(
|
||||
requestEvents.filter((event) => event.status === "started").map((event) => event.method),
|
||||
).toEqual(["initialize", "session/new", "authenticate", "session/new"]);
|
||||
expect(
|
||||
requestEvents.filter(
|
||||
(event) => event.method === "session/new" && event.status === "failed",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
requestEvents.filter(
|
||||
(event) => event.method === "session/new" && event.status === "succeeded",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_AUTH_METHOD_ID: "test",
|
||||
T3_ACP_REQUIRE_AUTH: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
requestLogger: (event) =>
|
||||
Effect.sync(() => {
|
||||
requestEvents.push(event);
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
@@ -264,6 +355,63 @@ describe("AcpSessionRuntime", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("supports negotiated ACP session list, fork, resume, and close methods", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
expect(started.initializeResult.agentCapabilities?.sessionCapabilities).toMatchObject({
|
||||
list: {},
|
||||
fork: {},
|
||||
resume: {},
|
||||
close: {},
|
||||
});
|
||||
|
||||
const listed = yield* runtime.listSessions();
|
||||
expect(listed.sessions.map((session) => session.sessionId)).toEqual(["mock-session-1"]);
|
||||
|
||||
const forked = yield* runtime.forkSession(started.sessionId);
|
||||
expect(forked.sessionId).toBe("mock-session-1-fork");
|
||||
yield* runtime.prompt({ prompt: [{ type: "text", text: "on fork" }] });
|
||||
|
||||
const resumed = yield* runtime.resumeSession(started.sessionId);
|
||||
expect(resumed.sessionId).toBe("mock-session-1");
|
||||
yield* runtime.closeSession();
|
||||
|
||||
expect(
|
||||
requestEvents.find(
|
||||
(event) => event.method === "session/prompt" && event.status === "started",
|
||||
)?.payload,
|
||||
).toMatchObject({ sessionId: "mock-session-1-fork" });
|
||||
expect(
|
||||
requestEvents.filter((event) => event.status === "started").map((event) => event.method),
|
||||
).toEqual(
|
||||
expect.arrayContaining(["session/list", "session/fork", "session/resume", "session/close"]),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: mockAgentCommand,
|
||||
args: mockAgentArgs,
|
||||
env: {
|
||||
T3_ACP_SESSION_LIFECYCLE: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
requestLogger: (event) =>
|
||||
Effect.sync(() => {
|
||||
requestEvents.push(event);
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("skips no-op session config writes when the requested value is already active", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { AcpRegistrySettings } from "@t3tools/contracts";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
makeAcpRegistryResolver,
|
||||
resolveAcpRegistryDistribution,
|
||||
resolveAcpRegistryPlatformTarget,
|
||||
type AcpRegistryAgent,
|
||||
} from "./AcpRegistrySupport.ts";
|
||||
|
||||
const registryUrl = "https://registry.test/registry.json";
|
||||
const archiveUrl = "https://registry.test/example-agent.bin";
|
||||
const decodeAcpRegistrySettings = Schema.decodeSync(AcpRegistrySettings);
|
||||
|
||||
function makeAgent(distribution: AcpRegistryAgent["distribution"]): AcpRegistryAgent {
|
||||
return {
|
||||
id: "example-agent",
|
||||
name: "Example Agent",
|
||||
version: "1.2.3",
|
||||
description: "ACP Registry test agent",
|
||||
distribution,
|
||||
};
|
||||
}
|
||||
|
||||
function makeRegistry(agent: AcpRegistryAgent): string {
|
||||
return JSON.stringify({ version: "1.0.0", agents: [agent] });
|
||||
}
|
||||
|
||||
function settings(input: Partial<AcpRegistrySettings> = {}): AcpRegistrySettings {
|
||||
return decodeAcpRegistrySettings({
|
||||
agentId: "example-agent",
|
||||
...input,
|
||||
});
|
||||
}
|
||||
|
||||
function resolverLayer(execute: Parameters<typeof HttpClient.make>[0]) {
|
||||
return Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
Layer.succeed(HostProcessPlatform, "linux"),
|
||||
Layer.succeed(HostProcessArchitecture, "x64"),
|
||||
Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("AcpRegistrySupport", () => {
|
||||
it("maps supported Node platforms to ACP Registry target keys", () => {
|
||||
expect(resolveAcpRegistryPlatformTarget("darwin", "arm64")).toBe("darwin-aarch64");
|
||||
expect(resolveAcpRegistryPlatformTarget("linux", "x64")).toBe("linux-x86_64");
|
||||
expect(resolveAcpRegistryPlatformTarget("win32", "arm64")).toBe("windows-aarch64");
|
||||
expect(resolveAcpRegistryPlatformTarget("freebsd", "x64")).toBeUndefined();
|
||||
expect(resolveAcpRegistryPlatformTarget("linux", "ia32")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("selects the preferred compatible distribution", () => {
|
||||
const agent = makeAgent({
|
||||
binary: {
|
||||
"linux-x86_64": {
|
||||
archive: archiveUrl,
|
||||
cmd: "./bin/example-agent",
|
||||
args: ["acp"],
|
||||
},
|
||||
},
|
||||
npx: {
|
||||
package: "@example/[email protected]",
|
||||
args: ["--stdio"],
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAcpRegistryDistribution({
|
||||
agent,
|
||||
preference: "auto",
|
||||
platformTarget: "linux-x86_64",
|
||||
}),
|
||||
).toMatchObject({ kind: "binary", args: ["acp"] });
|
||||
expect(
|
||||
resolveAcpRegistryDistribution({
|
||||
agent,
|
||||
preference: "npx",
|
||||
platformTarget: "linux-x86_64",
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "npx",
|
||||
packageName: "@example/[email protected]",
|
||||
args: ["--stdio"],
|
||||
env: {},
|
||||
});
|
||||
expect(
|
||||
resolveAcpRegistryDistribution({
|
||||
agent,
|
||||
preference: "binary",
|
||||
platformTarget: "darwin-aarch64",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it.effect("resolves command overrides while preserving registry args and environment", () => {
|
||||
const agent = makeAgent({
|
||||
binary: {
|
||||
"linux-x86_64": {
|
||||
archive: archiveUrl,
|
||||
cmd: "./bin/example-agent",
|
||||
args: ["acp", "--stdio"],
|
||||
env: { REGISTRY_VALUE: "registry", OVERRIDE_ME: "registry" },
|
||||
},
|
||||
},
|
||||
});
|
||||
const requests: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cacheDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-registry-override-",
|
||||
});
|
||||
const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl });
|
||||
const resolved = yield* resolver.resolve(
|
||||
settings({ commandPath: "/opt/example-agent" }),
|
||||
"/workspace",
|
||||
{ HOST_VALUE: "host", OVERRIDE_ME: "host" },
|
||||
);
|
||||
|
||||
expect(resolved.distribution).toBe("binary");
|
||||
expect(resolved.spawn).toEqual({
|
||||
command: "/opt/example-agent",
|
||||
args: ["acp", "--stdio"],
|
||||
cwd: "/workspace",
|
||||
env: {
|
||||
HOST_VALUE: "host",
|
||||
OVERRIDE_ME: "registry",
|
||||
REGISTRY_VALUE: "registry",
|
||||
},
|
||||
});
|
||||
expect(requests).toEqual([registryUrl]);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
resolverLayer((request) => {
|
||||
requests.push(request.url);
|
||||
return Effect.succeed(
|
||||
HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("installs and reuses a registry binary in the managed cache", () => {
|
||||
const agent = makeAgent({
|
||||
binary: {
|
||||
"linux-x86_64": {
|
||||
archive: archiveUrl,
|
||||
cmd: "./bin/example-agent",
|
||||
args: ["acp"],
|
||||
},
|
||||
},
|
||||
});
|
||||
const binaryBytes = new TextEncoder().encode("#!/bin/sh\necho example\n");
|
||||
const requests: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cacheDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-registry-install-",
|
||||
});
|
||||
const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl });
|
||||
const first = yield* resolver.resolve(settings(), "/workspace");
|
||||
const second = yield* resolver.resolve(settings(), "/workspace");
|
||||
|
||||
expect(first.spawn.command).toBe(second.spawn.command);
|
||||
expect(first.spawn.command).toContain(
|
||||
"/acp-registry/agents/example-agent/1.2.3/linux-x86_64/bin/example-agent",
|
||||
);
|
||||
expect(yield* fileSystem.readFileString(first.spawn.command)).toBe(
|
||||
"#!/bin/sh\necho example\n",
|
||||
);
|
||||
expect(requests).toEqual([registryUrl, archiveUrl]);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
resolverLayer((request) => {
|
||||
requests.push(request.url);
|
||||
const response =
|
||||
request.url === registryUrl
|
||||
? new Response(makeRegistry(agent))
|
||||
: new Response(binaryBytes.buffer as ArrayBuffer);
|
||||
return Effect.succeed(HttpClientResponse.fromWeb(request, response));
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to a valid cached registry index when refresh fails", () => {
|
||||
const agent = makeAgent({
|
||||
npx: {
|
||||
package: "@example/[email protected]",
|
||||
args: ["--stdio"],
|
||||
},
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cacheDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-registry-cache-",
|
||||
});
|
||||
const registryDirectory = `${cacheDir}/acp-registry`;
|
||||
yield* fileSystem.makeDirectory(registryDirectory, { recursive: true });
|
||||
yield* fileSystem.writeFileString(`${registryDirectory}/registry.json`, makeRegistry(agent));
|
||||
const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl });
|
||||
const resolved = yield* resolver.resolve(settings(), "/workspace");
|
||||
|
||||
expect(resolved.spawn).toMatchObject({
|
||||
command: "npx",
|
||||
args: ["--yes", "@example/[email protected]", "--stdio"],
|
||||
});
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
resolverLayer((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 503 })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("rejects unsafe command paths before downloading an archive", () => {
|
||||
const agent = makeAgent({
|
||||
binary: {
|
||||
"linux-x86_64": {
|
||||
archive: archiveUrl,
|
||||
cmd: "../outside",
|
||||
},
|
||||
},
|
||||
});
|
||||
const requests: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cacheDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-registry-invalid-",
|
||||
});
|
||||
const resolver = yield* makeAcpRegistryResolver({ cacheDir, registryUrl });
|
||||
const error = yield* resolver.resolve(settings(), "/workspace").pipe(Effect.flip);
|
||||
|
||||
expect(error.reason).toBe("archive_invalid");
|
||||
expect(requests).toEqual([registryUrl]);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
resolverLayer((request) => {
|
||||
requests.push(request.url);
|
||||
return Effect.succeed(
|
||||
HttpClientResponse.fromWeb(request, new Response(makeRegistry(agent))),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,633 @@
|
||||
import {
|
||||
type AcpRegistryDistributionPreference,
|
||||
type AcpRegistrySettings,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { collectUint8StreamText } from "../../stream/collectUint8StreamText.ts";
|
||||
import type { AcpSpawnInput } from "./AcpSessionRuntime.ts";
|
||||
|
||||
export const ACP_REGISTRY_URL =
|
||||
"https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
|
||||
|
||||
const AcpRegistryPackageDistribution = Schema.Struct({
|
||||
package: Schema.String,
|
||||
args: Schema.optionalKey(Schema.Array(Schema.String)),
|
||||
env: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
|
||||
});
|
||||
|
||||
const AcpRegistryBinaryTarget = Schema.Struct({
|
||||
archive: Schema.String,
|
||||
cmd: Schema.String,
|
||||
args: Schema.optionalKey(Schema.Array(Schema.String)),
|
||||
env: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
|
||||
});
|
||||
|
||||
const AcpRegistryAgent = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
version: Schema.String,
|
||||
description: Schema.String,
|
||||
distribution: Schema.Struct({
|
||||
binary: Schema.optionalKey(Schema.Record(Schema.String, AcpRegistryBinaryTarget)),
|
||||
npx: Schema.optionalKey(AcpRegistryPackageDistribution),
|
||||
uvx: Schema.optionalKey(AcpRegistryPackageDistribution),
|
||||
}),
|
||||
});
|
||||
export type AcpRegistryAgent = typeof AcpRegistryAgent.Type;
|
||||
|
||||
const AcpRegistryIndex = Schema.Struct({
|
||||
version: Schema.String,
|
||||
agents: Schema.Array(AcpRegistryAgent),
|
||||
});
|
||||
export type AcpRegistryIndex = typeof AcpRegistryIndex.Type;
|
||||
|
||||
const decodeRegistryIndex = Schema.decodeUnknownEffect(AcpRegistryIndex);
|
||||
const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
export const AcpRegistryErrorReason = Schema.Literals([
|
||||
"agent_not_configured",
|
||||
"agent_not_found",
|
||||
"archive_invalid",
|
||||
"download_failed",
|
||||
"install_failed",
|
||||
"registry_unavailable",
|
||||
"unsupported_distribution",
|
||||
"unsupported_platform",
|
||||
]);
|
||||
export type AcpRegistryErrorReason = typeof AcpRegistryErrorReason.Type;
|
||||
|
||||
export class AcpRegistryError extends Schema.TaggedErrorClass<AcpRegistryError>()(
|
||||
"AcpRegistryError",
|
||||
{
|
||||
reason: AcpRegistryErrorReason,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
|
||||
const isAcpRegistryError = Schema.is(AcpRegistryError);
|
||||
|
||||
export type AcpRegistryPlatformTarget =
|
||||
| "darwin-aarch64"
|
||||
| "darwin-x86_64"
|
||||
| "linux-aarch64"
|
||||
| "linux-x86_64"
|
||||
| "windows-aarch64"
|
||||
| "windows-x86_64";
|
||||
|
||||
export function resolveAcpRegistryPlatformTarget(
|
||||
platform: NodeJS.Platform,
|
||||
architecture: NodeJS.Architecture,
|
||||
): AcpRegistryPlatformTarget | undefined {
|
||||
const os =
|
||||
platform === "darwin"
|
||||
? "darwin"
|
||||
: platform === "linux"
|
||||
? "linux"
|
||||
: platform === "win32"
|
||||
? "windows"
|
||||
: undefined;
|
||||
const arch = architecture === "arm64" ? "aarch64" : architecture === "x64" ? "x86_64" : undefined;
|
||||
return os && arch ? (`${os}-${arch}` as AcpRegistryPlatformTarget) : undefined;
|
||||
}
|
||||
|
||||
export type AcpRegistryDistributionKind = "binary" | "npx" | "uvx";
|
||||
|
||||
export interface ResolvedAcpRegistryDistribution {
|
||||
readonly kind: AcpRegistryDistributionKind;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly env: Readonly<Record<string, string>>;
|
||||
readonly binaryTarget?: typeof AcpRegistryBinaryTarget.Type;
|
||||
readonly packageName?: string;
|
||||
}
|
||||
|
||||
export function resolveAcpRegistryDistribution(input: {
|
||||
readonly agent: AcpRegistryAgent;
|
||||
readonly preference: AcpRegistryDistributionPreference;
|
||||
readonly platformTarget: AcpRegistryPlatformTarget | undefined;
|
||||
}): ResolvedAcpRegistryDistribution | undefined {
|
||||
const { agent, platformTarget } = input;
|
||||
const binary = platformTarget ? agent.distribution.binary?.[platformTarget] : undefined;
|
||||
const candidates: ReadonlyArray<AcpRegistryDistributionKind> =
|
||||
input.preference === "auto" ? ["binary", "npx", "uvx"] : [input.preference];
|
||||
|
||||
for (const kind of candidates) {
|
||||
if (kind === "binary" && binary) {
|
||||
return {
|
||||
kind,
|
||||
args: binary.args ?? [],
|
||||
env: binary.env ?? {},
|
||||
binaryTarget: binary,
|
||||
};
|
||||
}
|
||||
if (kind === "npx" && agent.distribution.npx) {
|
||||
return {
|
||||
kind,
|
||||
args: agent.distribution.npx.args ?? [],
|
||||
env: agent.distribution.npx.env ?? {},
|
||||
packageName: agent.distribution.npx.package,
|
||||
};
|
||||
}
|
||||
if (kind === "uvx" && agent.distribution.uvx) {
|
||||
return {
|
||||
kind,
|
||||
args: agent.distribution.uvx.args ?? [],
|
||||
env: agent.distribution.uvx.env ?? {},
|
||||
packageName: agent.distribution.uvx.package,
|
||||
};
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export interface ResolvedAcpRegistryAgent {
|
||||
readonly agent: AcpRegistryAgent;
|
||||
readonly distribution: AcpRegistryDistributionKind;
|
||||
readonly spawn: AcpSpawnInput;
|
||||
}
|
||||
|
||||
export interface AcpRegistryResolverShape {
|
||||
readonly resolve: (
|
||||
settings: AcpRegistrySettings,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) => Effect.Effect<ResolvedAcpRegistryAgent, AcpRegistryError>;
|
||||
}
|
||||
|
||||
const INSTALL_LOCK_RETRY_COUNT = 300;
|
||||
const INSTALL_LOCK_RETRY_DELAY = "100 millis";
|
||||
const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
|
||||
const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
|
||||
|
||||
function isAlreadyExists(error: PlatformError.PlatformError): boolean {
|
||||
return error.reason._tag === "AlreadyExists";
|
||||
}
|
||||
|
||||
function normalizeRegistryCommandPath(command: string): ReadonlyArray<string> | undefined {
|
||||
const normalized = command.trim().replaceAll("\\", "/").replace(/^\.\//u, "");
|
||||
const segments = normalized.split("/").filter((segment) => segment.length > 0);
|
||||
if (
|
||||
segments.length === 0 ||
|
||||
normalized.startsWith("/") ||
|
||||
/^[a-zA-Z]:/u.test(normalized) ||
|
||||
segments.some((segment) => segment === "." || segment === "..")
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
function validateArchiveEntries(output: string): boolean {
|
||||
return output
|
||||
.split(/\r?\n/u)
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.every((entry) => normalizeRegistryCommandPath(entry) !== undefined);
|
||||
}
|
||||
|
||||
type ArchiveKind = "raw" | "tar_bz2" | "tar_gz" | "zip";
|
||||
|
||||
function archiveKind(url: string): ArchiveKind {
|
||||
const pathname = new URL(url).pathname.toLowerCase();
|
||||
if (pathname.endsWith(".tar.gz") || pathname.endsWith(".tgz")) return "tar_gz";
|
||||
if (pathname.endsWith(".tar.bz2") || pathname.endsWith(".tbz2")) return "tar_bz2";
|
||||
if (pathname.endsWith(".zip")) return "zip";
|
||||
return "raw";
|
||||
}
|
||||
|
||||
function archiveFileName(kind: ArchiveKind): string {
|
||||
switch (kind) {
|
||||
case "tar_gz":
|
||||
return "agent.tar.gz";
|
||||
case "tar_bz2":
|
||||
return "agent.tar.bz2";
|
||||
case "zip":
|
||||
return "agent.zip";
|
||||
case "raw":
|
||||
return "agent.bin";
|
||||
}
|
||||
}
|
||||
|
||||
export const makeAcpRegistryResolver = Effect.fn("AcpRegistryResolver.make")(function* (input: {
|
||||
readonly cacheDir: string;
|
||||
readonly registryUrl?: string;
|
||||
}): Effect.fn.Return<
|
||||
AcpRegistryResolverShape,
|
||||
never,
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const platform = yield* HostProcessPlatform;
|
||||
const architecture = yield* HostProcessArchitecture;
|
||||
const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture);
|
||||
const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL;
|
||||
const registryDirectory = path.join(input.cacheDir, "acp-registry");
|
||||
const registryCachePath = path.join(registryDirectory, "registry.json");
|
||||
const installsDirectory = path.join(registryDirectory, "agents");
|
||||
const registryRef = yield* Ref.make<AcpRegistryIndex | undefined>(undefined);
|
||||
const registrySemaphore = yield* Semaphore.make(1);
|
||||
const installSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const decodeRegistryText = Effect.fn("AcpRegistryResolver.decodeRegistryText")(function* (
|
||||
text: string,
|
||||
) {
|
||||
const decoded = yield* decodeJson(text).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryError({
|
||||
reason: "registry_unavailable",
|
||||
detail: "ACP Registry returned invalid JSON.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* decodeRegistryIndex(decoded).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryError({
|
||||
reason: "registry_unavailable",
|
||||
detail: "ACP Registry returned an invalid index.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const readCachedRegistry = fileSystem
|
||||
.readFileString(registryCachePath)
|
||||
.pipe(Effect.flatMap(decodeRegistryText), Effect.option);
|
||||
|
||||
const writeRegistryCache = (text: string) =>
|
||||
fileSystem
|
||||
.makeDirectory(registryDirectory, { recursive: true })
|
||||
.pipe(
|
||||
Effect.andThen(fileSystem.writeFileString(`${registryCachePath}.${process.pid}.tmp`, text)),
|
||||
Effect.andThen(
|
||||
fileSystem.rename(`${registryCachePath}.${process.pid}.tmp`, registryCachePath),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
|
||||
const fetchRegistry = Effect.gen(function* () {
|
||||
const response = yield* httpClient.execute(HttpClientRequest.get(registryUrl)).pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryError({
|
||||
reason: "registry_unavailable",
|
||||
detail: `Could not fetch ACP Registry index from ${registryUrl}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const text = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryError({
|
||||
reason: "registry_unavailable",
|
||||
detail: "Could not read ACP Registry response body.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const registry = yield* decodeRegistryText(text);
|
||||
yield* writeRegistryCache(text);
|
||||
return registry;
|
||||
});
|
||||
|
||||
const loadRegistry = registrySemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const memoized = yield* Ref.get(registryRef);
|
||||
if (memoized !== undefined) return memoized;
|
||||
const registry = yield* fetchRegistry.pipe(
|
||||
Effect.catch((networkError) =>
|
||||
readCachedRegistry.pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.fail(networkError),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Ref.set(registryRef, registry);
|
||||
return registry;
|
||||
}),
|
||||
);
|
||||
|
||||
const runCommand = Effect.fn("AcpRegistryResolver.runCommand")(function* (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
cwd?: string,
|
||||
) {
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(command, args, {
|
||||
...(cwd ? { cwd } : {}),
|
||||
shell: false,
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({ stream: child.stdout }),
|
||||
collectUint8StreamText({ stream: child.stderr }),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
if (Number(exitCode) !== 0) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "install_failed",
|
||||
detail: `ACP Registry install command '${command}' exited with code ${Number(exitCode)}: ${stderr.text.trim()}`,
|
||||
});
|
||||
}
|
||||
return stdout.text;
|
||||
});
|
||||
|
||||
const acquireInstallLock = Effect.fn("AcpRegistryResolver.acquireInstallLock")(function* (
|
||||
lockPath: string,
|
||||
) {
|
||||
for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
|
||||
const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
),
|
||||
);
|
||||
if (acquired) return;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
continue;
|
||||
}
|
||||
yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
|
||||
}
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "install_failed",
|
||||
detail: `Timed out waiting for ACP Registry install lock ${lockPath}.`,
|
||||
});
|
||||
});
|
||||
|
||||
const assertExecutableInRoot = Effect.fn("AcpRegistryResolver.assertExecutableInRoot")(function* (
|
||||
root: string,
|
||||
executablePath: string,
|
||||
) {
|
||||
const rootRealPath = yield* fileSystem.realPath(root);
|
||||
const executableRealPath = yield* fileSystem.realPath(executablePath);
|
||||
const relative = path.relative(rootRealPath, executableRealPath);
|
||||
if (relative.startsWith("..") || path.isAbsolute(relative)) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "archive_invalid",
|
||||
detail: "ACP Registry archive command resolves outside its installation directory.",
|
||||
});
|
||||
}
|
||||
return executableRealPath;
|
||||
});
|
||||
|
||||
const installBinary = Effect.fn("AcpRegistryResolver.installBinary")(function* (
|
||||
agent: AcpRegistryAgent,
|
||||
target: typeof AcpRegistryBinaryTarget.Type,
|
||||
) {
|
||||
if (platformTarget === undefined) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "unsupported_platform",
|
||||
detail: `ACP Registry does not support platform ${platform}-${architecture}.`,
|
||||
});
|
||||
}
|
||||
const commandSegments = normalizeRegistryCommandPath(target.cmd);
|
||||
if (commandSegments === undefined) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "archive_invalid",
|
||||
detail: `ACP Registry agent ${agent.id} declares an unsafe command path '${target.cmd}'.`,
|
||||
});
|
||||
}
|
||||
const installRoot = path.join(installsDirectory, agent.id, agent.version, platformTarget);
|
||||
const executablePath = path.join(installRoot, ...commandSegments);
|
||||
if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return yield* assertExecutableInRoot(installRoot, executablePath).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isAcpRegistryError(cause)
|
||||
? cause
|
||||
: new AcpRegistryError({
|
||||
reason: "install_failed",
|
||||
detail: `Could not validate cached ACP Registry agent ${agent.id}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(installRoot), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryError({
|
||||
reason: "install_failed",
|
||||
detail: `Could not create ACP Registry cache for ${agent.id}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const lockPath = `${installRoot}.lock`;
|
||||
yield* acquireInstallLock(lockPath).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isAcpRegistryError(cause)
|
||||
? cause
|
||||
: new AcpRegistryError({
|
||||
reason: "install_failed",
|
||||
detail: `Could not acquire install lock for ACP Registry agent ${agent.id}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
if (yield* fileSystem.exists(executablePath).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return yield* assertExecutableInRoot(installRoot, executablePath);
|
||||
}
|
||||
const temporaryRoot = yield* fileSystem.makeTempDirectoryScoped({
|
||||
directory: path.dirname(installRoot),
|
||||
prefix: `.${agent.id}-install-`,
|
||||
});
|
||||
const extractionRoot = path.join(temporaryRoot, "extracted");
|
||||
yield* fileSystem.makeDirectory(extractionRoot, { recursive: true });
|
||||
const kind = archiveKind(target.archive);
|
||||
const archivePath = path.join(temporaryRoot, archiveFileName(kind));
|
||||
const response = yield* httpClient.execute(HttpClientRequest.get(target.archive)).pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryError({
|
||||
reason: "download_failed",
|
||||
detail: `Could not download ACP Registry agent ${agent.id} ${agent.version}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const bytes = new Uint8Array(
|
||||
yield* response.arrayBuffer.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AcpRegistryError({
|
||||
reason: "download_failed",
|
||||
detail: `Could not read ACP Registry agent ${agent.id} download.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (bytes.byteLength > MAX_ARCHIVE_BYTES) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "archive_invalid",
|
||||
detail: `ACP Registry agent ${agent.id} archive exceeds ${MAX_ARCHIVE_BYTES} bytes.`,
|
||||
});
|
||||
}
|
||||
yield* fileSystem.writeFile(archivePath, bytes);
|
||||
|
||||
if (kind === "raw") {
|
||||
const targetPath = path.join(extractionRoot, ...commandSegments);
|
||||
yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true });
|
||||
yield* fileSystem.rename(archivePath, targetPath);
|
||||
} else {
|
||||
const listArgs =
|
||||
kind === "tar_gz"
|
||||
? ["-tzf", archivePath]
|
||||
: kind === "tar_bz2"
|
||||
? ["-tjf", archivePath]
|
||||
: platform === "win32"
|
||||
? ["-tf", archivePath]
|
||||
: undefined;
|
||||
const entries =
|
||||
listArgs === undefined
|
||||
? yield* runCommand("unzip", ["-Z1", archivePath])
|
||||
: yield* runCommand("tar", listArgs);
|
||||
if (!validateArchiveEntries(entries)) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "archive_invalid",
|
||||
detail: `ACP Registry agent ${agent.id} archive contains an unsafe path.`,
|
||||
});
|
||||
}
|
||||
if (kind === "zip" && platform !== "win32") {
|
||||
yield* runCommand("unzip", ["-q", archivePath, "-d", extractionRoot]);
|
||||
} else {
|
||||
const extractFlag = kind === "tar_gz" ? "-xzf" : kind === "tar_bz2" ? "-xjf" : "-xf";
|
||||
yield* runCommand("tar", [extractFlag, archivePath, "-C", extractionRoot]);
|
||||
}
|
||||
}
|
||||
|
||||
const stagedExecutable = path.join(extractionRoot, ...commandSegments);
|
||||
if (!(yield* fileSystem.exists(stagedExecutable).pipe(Effect.orElseSucceed(() => false)))) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "archive_invalid",
|
||||
detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`,
|
||||
});
|
||||
}
|
||||
if (platform !== "win32") yield* fileSystem.chmod(stagedExecutable, 0o755);
|
||||
yield* assertExecutableInRoot(extractionRoot, stagedExecutable);
|
||||
yield* fileSystem.remove(installRoot, { recursive: true, force: true });
|
||||
yield* fileSystem.rename(extractionRoot, installRoot);
|
||||
return yield* assertExecutableInRoot(installRoot, executablePath);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),
|
||||
Effect.mapError((cause) =>
|
||||
isAcpRegistryError(cause)
|
||||
? cause
|
||||
: new AcpRegistryError({
|
||||
reason: "install_failed",
|
||||
detail: `Could not install ACP Registry agent ${agent.id}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const resolve: AcpRegistryResolverShape["resolve"] = (settings, cwd, environment) =>
|
||||
Effect.gen(function* () {
|
||||
const agentId = settings.agentId.trim();
|
||||
if (agentId.length === 0) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "agent_not_configured",
|
||||
detail: "ACP Registry provider requires a registry agent ID.",
|
||||
});
|
||||
}
|
||||
const registry = yield* loadRegistry;
|
||||
const agent = registry.agents.find((candidate) => candidate.id === agentId);
|
||||
if (agent === undefined) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason: "agent_not_found",
|
||||
detail: `ACP Registry does not contain agent '${agentId}'.`,
|
||||
});
|
||||
}
|
||||
const distribution = resolveAcpRegistryDistribution({
|
||||
agent,
|
||||
preference: settings.distribution,
|
||||
platformTarget,
|
||||
});
|
||||
if (distribution === undefined) {
|
||||
return yield* new AcpRegistryError({
|
||||
reason:
|
||||
platformTarget === undefined ? "unsupported_platform" : "unsupported_distribution",
|
||||
detail: `ACP Registry agent ${agent.id} has no ${settings.distribution === "auto" ? "compatible" : settings.distribution} distribution for ${platform}-${architecture}.`,
|
||||
});
|
||||
}
|
||||
|
||||
let command: string;
|
||||
let args: ReadonlyArray<string>;
|
||||
const commandOverride = settings.commandPath.trim();
|
||||
if (commandOverride.length > 0) {
|
||||
command = commandOverride;
|
||||
args = distribution.args;
|
||||
} else if (distribution.kind === "npx") {
|
||||
command = "npx";
|
||||
args = ["--yes", distribution.packageName!, ...distribution.args];
|
||||
} else if (distribution.kind === "uvx") {
|
||||
command = "uvx";
|
||||
args = [distribution.packageName!, ...distribution.args];
|
||||
} else {
|
||||
command = yield* installSemaphore.withPermits(1)(
|
||||
installBinary(agent, distribution.binaryTarget!),
|
||||
);
|
||||
args = distribution.args;
|
||||
}
|
||||
|
||||
return {
|
||||
agent,
|
||||
distribution: distribution.kind,
|
||||
spawn: {
|
||||
command,
|
||||
args,
|
||||
cwd,
|
||||
env: {
|
||||
...environment,
|
||||
...distribution.env,
|
||||
},
|
||||
},
|
||||
} satisfies ResolvedAcpRegistryAgent;
|
||||
});
|
||||
|
||||
return { resolve };
|
||||
});
|
||||
@@ -72,6 +72,7 @@ export type AcpParsedSessionEvent =
|
||||
};
|
||||
|
||||
type AcpSessionSetupResponse =
|
||||
| EffectAcpSchema.ForkSessionResponse
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
|
||||
@@ -47,7 +47,7 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
readonly authMethodId: string;
|
||||
readonly authMethodId?: string;
|
||||
readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
|
||||
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
|
||||
readonly protocolLogging?: {
|
||||
@@ -65,10 +65,26 @@ export interface AcpSessionRequestLogEvent {
|
||||
readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
export function selectAcpAgentAuthMethod(
|
||||
authMethods: ReadonlyArray<EffectAcpSchema.AuthMethod> | undefined,
|
||||
preferredMethodId?: string,
|
||||
): EffectAcpSchema.AuthMethod | undefined {
|
||||
const preferred = preferredMethodId?.trim();
|
||||
if (preferred) {
|
||||
return authMethods?.find((method) => method.id === preferred);
|
||||
}
|
||||
return authMethods?.find((method) => !("type" in method));
|
||||
}
|
||||
|
||||
function isAcpAuthenticationRequired(error: EffectAcpErrors.AcpError): boolean {
|
||||
return error._tag === "AcpRequestError" && error.code === -32000;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeStartResult {
|
||||
readonly sessionId: string;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
readonly sessionSetupResult:
|
||||
| EffectAcpSchema.ForkSessionResponse
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
@@ -95,6 +111,21 @@ export interface AcpSessionRuntimeShape {
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
|
||||
readonly loadSession: (
|
||||
sessionId: string,
|
||||
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
readonly resumeSession: (
|
||||
sessionId: string,
|
||||
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
readonly forkSession: (
|
||||
sessionId: string,
|
||||
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
readonly listSessions: (
|
||||
cursor?: string,
|
||||
) => Effect.Effect<EffectAcpSchema.ListSessionsResponse, EffectAcpErrors.AcpError>;
|
||||
readonly closeSession: (
|
||||
sessionId?: string,
|
||||
) => Effect.Effect<EffectAcpSchema.CloseSessionResponse, EffectAcpErrors.AcpError>;
|
||||
readonly prompt: (
|
||||
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
|
||||
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
|
||||
@@ -327,6 +358,7 @@ const makeAcpSessionRuntime = (
|
||||
const updateConfigOptions = (
|
||||
response:
|
||||
| EffectAcpSchema.SetSessionConfigOptionResponse
|
||||
| EffectAcpSchema.ForkSessionResponse
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
@@ -337,6 +369,30 @@ const makeAcpSessionRuntime = (
|
||||
current ? { ...current, currentModeId: modeId } : current,
|
||||
);
|
||||
|
||||
const adoptSession = (
|
||||
sessionId: string,
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.ForkSessionResponse
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* getStartedState;
|
||||
const nextState = {
|
||||
sessionId,
|
||||
initializeResult: current.initializeResult,
|
||||
sessionSetupResult,
|
||||
modelConfigId: extractModelConfigId(sessionSetupResult),
|
||||
} satisfies AcpStartedState;
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
|
||||
yield* Ref.set(toolCallsRef, new Map());
|
||||
yield* Ref.set(assistantSegmentRef, { nextSegmentIndex: 0 });
|
||||
yield* Ref.set(startStateRef, { _tag: "Started", result: nextState });
|
||||
return nextState;
|
||||
});
|
||||
|
||||
const setConfigOption = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
@@ -388,35 +444,80 @@ const makeAcpSessionRuntime = (
|
||||
acp.agent.initialize(initializePayload),
|
||||
);
|
||||
|
||||
const authenticatePayload = {
|
||||
methodId: options.authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
const authenticateAfterRequired = (
|
||||
authRequiredError: EffectAcpErrors.AcpError,
|
||||
): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const configuredAuthMethodId = options.authMethodId?.trim();
|
||||
const authMethod = selectAcpAgentAuthMethod(
|
||||
initializeResult.authMethods,
|
||||
configuredAuthMethodId,
|
||||
);
|
||||
if (
|
||||
configuredAuthMethodId &&
|
||||
initializeResult.authMethods !== undefined &&
|
||||
authMethod === undefined
|
||||
) {
|
||||
return yield* new EffectAcpErrors.AcpTransportError({
|
||||
detail: `ACP agent did not advertise configured authentication method "${configuredAuthMethodId}"`,
|
||||
cause: { configuredAuthMethodId, authMethods: initializeResult.authMethods },
|
||||
});
|
||||
}
|
||||
if (authMethod !== undefined && "type" in authMethod) {
|
||||
return yield* new EffectAcpErrors.AcpTransportError({
|
||||
detail: `ACP authentication method "${authMethod.id}" requires ${authMethod.type} authentication, which cannot run inside a headless provider session`,
|
||||
cause: authMethod,
|
||||
});
|
||||
}
|
||||
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
const authMethodId = authMethod?.id ?? configuredAuthMethodId;
|
||||
if (!authMethodId) {
|
||||
return yield* authRequiredError;
|
||||
}
|
||||
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const loadPayload = {
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
const authenticatePayload = {
|
||||
methodId: authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
});
|
||||
|
||||
const setupSession = Effect.gen(function* () {
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const loadPayload = {
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
@@ -430,19 +531,17 @@ const makeAcpSessionRuntime = (
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
return { sessionId, sessionSetupResult };
|
||||
});
|
||||
|
||||
const { sessionId, sessionSetupResult } = yield* setupSession.pipe(
|
||||
Effect.catch((error) =>
|
||||
isAcpAuthenticationRequired(error)
|
||||
? authenticateAfterRequired(error).pipe(Effect.andThen(setupSession))
|
||||
: Effect.fail(error),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
|
||||
@@ -508,6 +607,82 @@ const makeAcpSessionRuntime = (
|
||||
getEvents: () => Stream.fromQueue(eventQueue),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
getConfigOptions: Ref.get(configOptionsRef),
|
||||
loadSession: (sessionId) =>
|
||||
start.pipe(
|
||||
Effect.flatMap(() => {
|
||||
const requestPayload = {
|
||||
sessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
return runLoggedRequest(
|
||||
"session/load",
|
||||
requestPayload,
|
||||
acp.agent.loadSession(requestPayload),
|
||||
);
|
||||
}),
|
||||
Effect.flatMap((response) => adoptSession(sessionId, response)),
|
||||
),
|
||||
resumeSession: (sessionId) =>
|
||||
start.pipe(
|
||||
Effect.flatMap(() => {
|
||||
const requestPayload = {
|
||||
sessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.ResumeSessionRequest;
|
||||
return runLoggedRequest(
|
||||
"session/resume",
|
||||
requestPayload,
|
||||
acp.agent.resumeSession(requestPayload),
|
||||
);
|
||||
}),
|
||||
Effect.flatMap((response) => adoptSession(sessionId, response)),
|
||||
),
|
||||
forkSession: (sessionId) =>
|
||||
start.pipe(
|
||||
Effect.flatMap(() => {
|
||||
const requestPayload = {
|
||||
sessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.ForkSessionRequest;
|
||||
return runLoggedRequest(
|
||||
"session/fork",
|
||||
requestPayload,
|
||||
acp.agent.forkSession(requestPayload),
|
||||
);
|
||||
}),
|
||||
Effect.flatMap((response) => adoptSession(response.sessionId, response)),
|
||||
),
|
||||
listSessions: (cursor) => {
|
||||
const requestPayload = {
|
||||
cwd: options.cwd,
|
||||
...(cursor === undefined ? {} : { cursor }),
|
||||
} satisfies EffectAcpSchema.ListSessionsRequest;
|
||||
return start.pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/list",
|
||||
requestPayload,
|
||||
acp.agent.listSessions(requestPayload),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
closeSession: (sessionId) =>
|
||||
start.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: sessionId ?? started.sessionId,
|
||||
} satisfies EffectAcpSchema.CloseSessionRequest;
|
||||
return runLoggedRequest(
|
||||
"session/close",
|
||||
requestPayload,
|
||||
acp.agent.closeSession(requestPayload),
|
||||
);
|
||||
}),
|
||||
),
|
||||
prompt: (payload) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
|
||||
@@ -66,4 +66,23 @@ describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () =
|
||||
yield* runtime.setSessionModel(currentModelId);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("switches to another advertised model and completes a prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
const models = started.sessionSetupResult.models;
|
||||
const targetModel = models?.availableModels.find(
|
||||
({ modelId }) => modelId !== models.currentModelId,
|
||||
)?.modelId;
|
||||
expect(targetModel).toBeDefined();
|
||||
if (!targetModel) return;
|
||||
|
||||
yield* runtime.setSessionModel(targetModel).pipe(Effect.timeout("20 seconds"));
|
||||
const result = yield* runtime
|
||||
.prompt({ prompt: [{ type: "text", text: "Respond with exactly: grok switch ok" }] })
|
||||
.pipe(Effect.timeout("60 seconds"));
|
||||
expect(result.stopReason).toBe("end_turn");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -23,10 +23,7 @@ const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
|
||||
type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">;
|
||||
|
||||
interface GrokAcpRuntimeInput extends Omit<
|
||||
AcpSessionRuntimeOptions,
|
||||
"authMethodId" | "clientCapabilities" | "spawn"
|
||||
> {
|
||||
interface GrokAcpRuntimeInput extends Omit<AcpSessionRuntimeOptions, "authMethodId" | "spawn"> {
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
|
||||
@@ -64,6 +64,17 @@ export function extractXAiAskUserQuestions(
|
||||
}));
|
||||
}
|
||||
|
||||
export function extractXAiAskUserQuestionIdentity(params: XAiAskUserQuestionRequest): {
|
||||
readonly sessionId: string;
|
||||
readonly toolCallId: string;
|
||||
} {
|
||||
const unwrapped = unwrapAskUserQuestionParams(params);
|
||||
return {
|
||||
sessionId: unwrapped.sessionId,
|
||||
toolCallId: unwrapped.toolCallId,
|
||||
};
|
||||
}
|
||||
|
||||
interface XAiAskUserQuestionAnnotation {
|
||||
readonly preview?: string;
|
||||
readonly notes?: string;
|
||||
|
||||
@@ -13,7 +13,7 @@ import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { normalizeProviderAccentColor } from "../../providerInstances";
|
||||
import { Button } from "../ui/button";
|
||||
import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons";
|
||||
import { Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
@@ -81,11 +81,6 @@ const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
|
||||
label: "Gemini",
|
||||
icon: Gemini,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("acpRegistry"),
|
||||
label: "ACP Registry",
|
||||
icon: ACPRegistryIcon,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("piAgent"),
|
||||
label: "Pi Agent",
|
||||
|
||||
@@ -36,6 +36,18 @@ describe("ProviderSettingsForm helpers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes ACP Registry as an instance-only configurable driver", () => {
|
||||
const acpRegistry = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("acpRegistry")];
|
||||
|
||||
expect(acpRegistry).toBeDefined();
|
||||
expect(acpRegistry?.hasDefaultInstance).toBe(false);
|
||||
expect(deriveProviderSettingsFields(acpRegistry!).map((field) => field.key)).toEqual([
|
||||
"agentId",
|
||||
"commandPath",
|
||||
"authMethodId",
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves unknown config keys while omitting empty configurable fields", () => {
|
||||
const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")];
|
||||
expect(opencode).toBeDefined();
|
||||
|
||||
@@ -1233,6 +1233,35 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
await expect.element(page.getByPlaceholder("Optional")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders configured ACP Registry instances without a blank default card", async () => {
|
||||
const instanceId = ProviderInstanceId.make("acpRegistry_devin");
|
||||
setServerConfigSnapshot({
|
||||
...createBaseServerConfig(),
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("acpRegistry"),
|
||||
displayName: "Devin ACP",
|
||||
config: { agentId: "devin" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<ProviderSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await expect
|
||||
.element(page.getByLabelText("Toggle ACP Registry details"))
|
||||
.not.toBeInTheDocument();
|
||||
await page.getByLabelText("Toggle Devin ACP details").click();
|
||||
await expect.element(page.getByText("Registry agent ID")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("runs one-click provider updates from the provider card", async () => {
|
||||
const updateProvider = vi.fn<LocalApi["server"]["updateProvider"]>().mockResolvedValue({
|
||||
providers: [createOutdatedProvider("codex")],
|
||||
|
||||
@@ -121,6 +121,7 @@ function withoutProviderInstanceFavorites(
|
||||
|
||||
const PROVIDER_SETTINGS = DRIVER_OPTIONS.map((definition) => ({
|
||||
provider: definition.value,
|
||||
hasDefaultInstance: definition.hasDefaultInstance !== false,
|
||||
}));
|
||||
|
||||
function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
|
||||
@@ -1032,9 +1033,9 @@ export function ProviderSettingsPanel() {
|
||||
}
|
||||
|
||||
const defaultSlotIdsBySource = new Set<string>(
|
||||
visibleProviderSettings.map((providerSettings) =>
|
||||
String(defaultInstanceIdForDriver(providerSettings.provider)),
|
||||
),
|
||||
visibleProviderSettings
|
||||
.filter((providerSettings) => providerSettings.hasDefaultInstance)
|
||||
.map((providerSettings) => String(defaultInstanceIdForDriver(providerSettings.provider))),
|
||||
);
|
||||
|
||||
const rows: InstanceRow[] = [];
|
||||
@@ -1043,6 +1044,12 @@ export function ProviderSettingsPanel() {
|
||||
);
|
||||
|
||||
for (const providerSettings of visibleProviderSettings) {
|
||||
if (!providerSettings.hasDefaultInstance) {
|
||||
for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
|
||||
rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
AcpRegistrySettings,
|
||||
ClaudeSettings,
|
||||
CodexSettings,
|
||||
CursorSettings,
|
||||
@@ -7,7 +8,15 @@ import {
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as Schema from "effect/Schema";
|
||||
import { ClaudeAI, CursorIcon, GrokIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import {
|
||||
ACPRegistryIcon,
|
||||
ClaudeAI,
|
||||
CursorIcon,
|
||||
GrokIcon,
|
||||
type Icon,
|
||||
OpenAI,
|
||||
OpenCodeIcon,
|
||||
} from "../Icons";
|
||||
|
||||
type ProviderSettingsSchema = {
|
||||
readonly fields: Readonly<Record<string, Schema.Top>>;
|
||||
@@ -24,6 +33,8 @@ export interface ProviderClientDefinition {
|
||||
readonly label: string;
|
||||
readonly icon: Icon;
|
||||
readonly settingsSchema: ProviderSettingsSchema;
|
||||
/** Whether this driver has a built-in default instance backed by legacy settings. */
|
||||
readonly hasDefaultInstance?: boolean;
|
||||
/**
|
||||
* Optional short label rendered as a `variant="warning"` badge next to
|
||||
* the instance title. Used to flag drivers that still ship under an
|
||||
@@ -61,6 +72,14 @@ export const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] =
|
||||
badgeLabel: "Early Access",
|
||||
settingsSchema: GrokSettings,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("acpRegistry"),
|
||||
label: "ACP Registry",
|
||||
icon: ACPRegistryIcon,
|
||||
badgeLabel: "V2 Preview",
|
||||
settingsSchema: AcpRegistrySettings,
|
||||
hasDefaultInstance: false,
|
||||
},
|
||||
{
|
||||
value: ProviderDriverKind.make("opencode"),
|
||||
label: "OpenCode",
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ProviderInstanceConfigMap,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { deriveOrchestrationV2DebugProviderSnapshots } from "./orchestrationV2DebugProviders";
|
||||
|
||||
const acpRegistry = ProviderDriverKind.make("acpRegistry");
|
||||
const instanceId = ProviderInstanceId.make("acpRegistry_example");
|
||||
|
||||
const unavailable: ServerProvider = {
|
||||
instanceId,
|
||||
driver: acpRegistry,
|
||||
displayName: "Example ACP",
|
||||
enabled: false,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
availability: "unavailable",
|
||||
unavailableReason: "Driver is not registered in the V1 runtime.",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
describe("deriveOrchestrationV2DebugProviderSnapshots", () => {
|
||||
it("replaces the V1 unavailable shadow for a configured registry agent", () => {
|
||||
const providerInstances = {
|
||||
[instanceId]: {
|
||||
driver: acpRegistry,
|
||||
enabled: true,
|
||||
displayName: "Example ACP",
|
||||
config: {
|
||||
agentId: "example-agent",
|
||||
customModels: ["model-one"],
|
||||
},
|
||||
},
|
||||
} satisfies ProviderInstanceConfigMap;
|
||||
|
||||
expect(
|
||||
deriveOrchestrationV2DebugProviderSnapshots({
|
||||
providers: [unavailable],
|
||||
providerInstances,
|
||||
}),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
instanceId,
|
||||
driver: acpRegistry,
|
||||
displayName: "Example ACP",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
status: "ready",
|
||||
availability: "available",
|
||||
models: [
|
||||
expect.objectContaining({ slug: "default", isCustom: false }),
|
||||
expect.objectContaining({ slug: "model-one", isCustom: true }),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not make an incomplete registry instance selectable", () => {
|
||||
const providerInstances = {
|
||||
[instanceId]: {
|
||||
driver: acpRegistry,
|
||||
config: { agentId: "" },
|
||||
},
|
||||
} satisfies ProviderInstanceConfigMap;
|
||||
|
||||
expect(
|
||||
deriveOrchestrationV2DebugProviderSnapshots({
|
||||
providers: [unavailable],
|
||||
providerInstances,
|
||||
}),
|
||||
).toEqual([unavailable]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfigMap,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const ACP_REGISTRY_DRIVER = ProviderDriverKind.make("acpRegistry");
|
||||
const DEBUG_CHECKED_AT = "1970-01-01T00:00:00.000Z";
|
||||
|
||||
function configRecord(config: unknown): Readonly<Record<string, unknown>> {
|
||||
return config !== null && typeof config === "object" && !Array.isArray(config)
|
||||
? (config as Readonly<Record<string, unknown>>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function configuredModels(
|
||||
config: Readonly<Record<string, unknown>>,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const customModels = Array.isArray(config.customModels)
|
||||
? config.customModels.filter(
|
||||
(model): model is string => typeof model === "string" && model.trim().length > 0,
|
||||
)
|
||||
: [];
|
||||
const slugs = [...new Set(["default", ...customModels.map((model) => model.trim())])];
|
||||
return slugs.map((slug) => ({
|
||||
slug,
|
||||
name: slug === "default" ? "Agent default" : slug,
|
||||
shortName: slug === "default" ? "Default" : slug,
|
||||
isCustom: slug !== "default",
|
||||
capabilities: null,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add V2-only ACP Registry instances to the orchestration debugger's provider catalog.
|
||||
* The regular application provider catalog remains V1-owned and is intentionally untouched.
|
||||
*/
|
||||
export function deriveOrchestrationV2DebugProviderSnapshots(input: {
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
readonly providerInstances: ProviderInstanceConfigMap;
|
||||
}): ReadonlyArray<ServerProvider> {
|
||||
const snapshots = [...input.providers];
|
||||
const indexByInstanceId = new Map<ProviderInstanceId, number>(
|
||||
snapshots.map((provider, index) => [provider.instanceId, index]),
|
||||
);
|
||||
|
||||
for (const [instanceId, instance] of Object.entries(input.providerInstances)) {
|
||||
if (instance.driver !== ACP_REGISTRY_DRIVER) continue;
|
||||
const config = configRecord(instance.config);
|
||||
const agentId = typeof config.agentId === "string" ? config.agentId.trim() : "";
|
||||
if (agentId.length === 0) continue;
|
||||
const id = instanceId as ProviderInstanceId;
|
||||
const existingIndex = indexByInstanceId.get(id);
|
||||
const existing = existingIndex === undefined ? undefined : snapshots[existingIndex];
|
||||
const enabled =
|
||||
instance.enabled ?? (typeof config.enabled === "boolean" ? config.enabled : true);
|
||||
const snapshot: ServerProvider = {
|
||||
instanceId: id,
|
||||
driver: ACP_REGISTRY_DRIVER,
|
||||
displayName: instance.displayName?.trim() || `ACP: ${agentId}`,
|
||||
...(instance.accentColor ? { accentColor: instance.accentColor } : {}),
|
||||
badgeLabel: "V2 Preview",
|
||||
showInteractionModeToggle: true,
|
||||
requiresNewThreadForModelChange: false,
|
||||
enabled,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: enabled ? "ready" : "disabled",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: existing?.checkedAt ?? DEBUG_CHECKED_AT,
|
||||
message: `ACP Registry agent '${agentId}' is resolved when the V2 session starts.`,
|
||||
availability: "available",
|
||||
models: configuredModels(config),
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
if (existingIndex === undefined) {
|
||||
indexByInstanceId.set(id, snapshots.length);
|
||||
snapshots.push(snapshot);
|
||||
} else {
|
||||
snapshots[existingIndex] = snapshot;
|
||||
}
|
||||
}
|
||||
|
||||
return snapshots;
|
||||
}
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
} from "../lib/orchestrationV2Timeline";
|
||||
import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils";
|
||||
import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection";
|
||||
import { deriveOrchestrationV2DebugProviderSnapshots } from "../orchestrationV2DebugProviders";
|
||||
import {
|
||||
type ProviderInstanceEntry,
|
||||
deriveProviderInstanceEntries,
|
||||
@@ -1621,7 +1622,14 @@ function OrchestrationV2DebugRoute() {
|
||||
const serverProviders = useServerProviders();
|
||||
const settings = useSettings();
|
||||
const keybindings = useServerKeybindings();
|
||||
const providerSnapshots = serverProviders.length > 0 ? serverProviders : DEBUG_PROVIDER_SNAPSHOTS;
|
||||
const providerSnapshots = useMemo(
|
||||
() =>
|
||||
deriveOrchestrationV2DebugProviderSnapshots({
|
||||
providers: serverProviders.length > 0 ? serverProviders : DEBUG_PROVIDER_SNAPSHOTS,
|
||||
providerInstances: settings.providerInstances,
|
||||
}),
|
||||
[serverProviders, settings.providerInstances],
|
||||
);
|
||||
const providerInstanceEntries = useMemo<ReadonlyArray<ProviderInstanceEntry>>(
|
||||
() => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerSnapshots)),
|
||||
[providerSnapshots],
|
||||
|
||||
@@ -90,9 +90,40 @@ Cursor receives the same authenticated HTTP MCP endpoint through the SDK's
|
||||
`mcpServers` agent and send options. The adapter passes the authorization header
|
||||
to the SDK but projects only redacted option metadata into protocol diagnostics.
|
||||
|
||||
### Grok ACP V2
|
||||
|
||||
Grok receives the authenticated HTTP MCP endpoint through the ACP
|
||||
`session/new`, `session/load`, and `session/fork` `mcpServers` field. The shared
|
||||
ACP adapter owns standard protocol behavior; the Grok flavor adds xAI extension
|
||||
requests such as structured user questions.
|
||||
|
||||
ACP does not define native subagents or active steering. Grok therefore uses
|
||||
orchestrator-owned child threads and implements steering through
|
||||
cancel-and-restart. Its current driver also lacks `session/fork`, so app forks
|
||||
use portable context transfer. These are orchestrator policies, not
|
||||
provider-specific MCP tools.
|
||||
|
||||
### ACP Registry V2
|
||||
|
||||
The `acpRegistry` driver is the generic flavor of the same shared ACP adapter.
|
||||
Each provider instance names an agent from the official ACP Registry. At
|
||||
session startup the driver resolves the current platform distribution, uses a
|
||||
managed binary cache or the declared `npx`/`uvx` package, and then negotiates
|
||||
standard ACP capabilities during `initialize`. A local executable may override
|
||||
the managed command without changing the registry-declared arguments or
|
||||
environment.
|
||||
|
||||
Capabilities such as session loading, session forking, models, modes, and MCP
|
||||
transport are enabled only when the selected agent advertises them. Missing
|
||||
features degrade through V2 policy: steering uses interrupt-and-restart,
|
||||
forking uses portable context when native `session/fork` is unavailable, and
|
||||
subagents use orchestrator-owned child threads. Registry agents do not receive
|
||||
provider-specific extensions; those remain in flavors such as Grok.
|
||||
|
||||
### Initial Provider Support
|
||||
|
||||
The V2 provider adapters are Codex, Claude Agent SDK, and Cursor Agent SDK.
|
||||
The V2 provider adapters are Codex, Claude Agent SDK, Cursor Agent SDK, and
|
||||
Grok plus generic registry agents over ACP.
|
||||
Capability discovery still reports other registered provider instances, but marks them
|
||||
unavailable for orchestration when no V2 adapter exists. This keeps provider
|
||||
selection model-visible without allowing a request that cannot run.
|
||||
@@ -299,6 +330,6 @@ Coverage includes:
|
||||
- inheritance and per-thread provider overrides; and
|
||||
- idempotent retries.
|
||||
|
||||
Provider adapter tests separately verify Codex, Claude, and Cursor MCP injection, and
|
||||
the provider-session manager test verifies that credentials exist before an
|
||||
adapter opens and are revoked when it closes.
|
||||
Provider adapter tests separately verify Codex, Claude, Cursor, Grok, and ACP
|
||||
Registry behavior and MCP injection. The provider-session manager test verifies
|
||||
that credentials exist before an adapter opens and are revoked when it closes.
|
||||
@@ -122,6 +122,14 @@ Claude replay transcript
|
||||
Cursor replay transcript
|
||||
-> Cursor Agent SDK open/send calls and ordered onDelta/run results
|
||||
-> consumed by CursorAdapter
|
||||
|
||||
OpenCode replay transcript
|
||||
-> OpenCode SDK requests/responses plus ordered SSE events
|
||||
-> consumed by OpenCodeAdapter
|
||||
|
||||
ACP replay transcript
|
||||
-> logical JSON-RPC requests/responses/notifications over a strict NDJSON peer
|
||||
-> consumed by AcpAdapter and a provider flavor (Grok or ACP Registry)
|
||||
```
|
||||
|
||||
Fixtures should preserve raw provider evidence as closely as possible. Expected V2 events or projections are assertions, not fixture input.
|
||||
@@ -131,6 +139,17 @@ call. A transcript should include the `query` prompt/options we sent and then re
|
||||
`SDKMessage` chunks in provider order. This intentionally tests the V2 adapter against real Claude
|
||||
SDK output; it does not test the SDK's own subprocess or transport parser.
|
||||
|
||||
ACP fixtures run against a child-process replay peer that validates every outbound frame and
|
||||
serves recorded inbound frames. This replaces only the external ACP driver transport; the shared
|
||||
runtime, adapter normalization, orchestration, persistence, and projections remain production code.
|
||||
The generic ACP Registry harness retargets protocol-standard ACP transcripts;
|
||||
provider-extension transcripts remain scoped to the flavor that owns the extension.
|
||||
|
||||
OpenCode fixtures replace the SDK client at its HTTP/SSE boundary. They must preserve races between
|
||||
request responses and SSE events, because user messages and terminal `session.status` events can
|
||||
arrive before the corresponding `promptAsync` or `abort` response. Subagent fixtures must retain
|
||||
both parent and child session ids so root-only terminal behavior remains testable.
|
||||
|
||||
Provider transcript recorders live with the server orchestration testkit, not with provider client
|
||||
packages. Use `bun run record:codex-replay -- --scenario <name>` for Codex app-server transcripts
|
||||
and `bun run record:claude-replay -- --scenario <name>` for Claude Agent SDK transcripts. Use
|
||||
@@ -206,7 +225,7 @@ Testing infrastructure should be built before production rewrites:
|
||||
2. Effect service definitions.
|
||||
3. provider runtime transport abstraction.
|
||||
4. generic replay runtime.
|
||||
5. Codex, Claude, and Cursor transcript loaders for app-owned provider replay fixtures.
|
||||
5. Codex, Claude, Cursor, OpenCode, and ACP transcript loaders for app-owned provider replay fixtures.
|
||||
6. projection reducer tests for core invariants.
|
||||
7. full command-to-projection integration tests.
|
||||
8. production layers.
|
||||
|
||||
@@ -131,6 +131,7 @@ const CODEX_DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
|
||||
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.4";
|
||||
@@ -141,6 +142,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
|
||||
[CLAUDE_DRIVER_KIND]: "claude-sonnet-4-6",
|
||||
[CURSOR_DRIVER_KIND]: "auto",
|
||||
[GROK_DRIVER_KIND]: "grok-build",
|
||||
[ACP_REGISTRY_DRIVER_KIND]: "default",
|
||||
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
|
||||
};
|
||||
|
||||
@@ -204,5 +206,6 @@ export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>>
|
||||
[CLAUDE_DRIVER_KIND]: "Claude",
|
||||
[CURSOR_DRIVER_KIND]: "Cursor",
|
||||
[GROK_DRIVER_KIND]: "Grok",
|
||||
[ACP_REGISTRY_DRIVER_KIND]: "ACP Registry",
|
||||
[OPENCODE_DRIVER_KIND]: "OpenCode",
|
||||
};
|
||||
@@ -305,6 +305,56 @@ export const GrokSettings = makeProviderSettingsSchema(
|
||||
);
|
||||
export type GrokSettings = typeof GrokSettings.Type;
|
||||
|
||||
export const AcpRegistryDistributionPreference = Schema.Literals(["auto", "binary", "npx", "uvx"]);
|
||||
export type AcpRegistryDistributionPreference = typeof AcpRegistryDistributionPreference.Type;
|
||||
|
||||
export const AcpRegistrySettings = makeProviderSettingsSchema(
|
||||
{
|
||||
enabled: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(true)),
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
agentId: TrimmedString.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("")),
|
||||
Schema.annotateKey({
|
||||
title: "Registry agent ID",
|
||||
description: "Agent identifier from the official ACP Registry, for example 'devin'.",
|
||||
providerSettingsForm: { placeholder: "devin", clearWhenEmpty: "persist" },
|
||||
}),
|
||||
),
|
||||
commandPath: TrimmedString.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("")),
|
||||
Schema.annotateKey({
|
||||
title: "Executable override",
|
||||
description:
|
||||
"Optional local executable to use instead of installing the registry distribution. Registry arguments and environment are still applied.",
|
||||
providerSettingsForm: { placeholder: "devin", clearWhenEmpty: "omit" },
|
||||
}),
|
||||
),
|
||||
authMethodId: TrimmedString.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("")),
|
||||
Schema.annotateKey({
|
||||
title: "Authentication method",
|
||||
description:
|
||||
"Optional ACP authentication method ID. By default, the first agent-managed method is selected.",
|
||||
providerSettingsForm: { placeholder: "auto", clearWhenEmpty: "omit" },
|
||||
}),
|
||||
),
|
||||
distribution: AcpRegistryDistributionPreference.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("auto")),
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
customModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed([])),
|
||||
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
|
||||
),
|
||||
},
|
||||
{
|
||||
order: ["agentId", "commandPath", "authMethodId"],
|
||||
},
|
||||
);
|
||||
export type AcpRegistrySettings = typeof AcpRegistrySettings.Type;
|
||||
|
||||
export const OpenCodeSettings = makeProviderSettingsSchema(
|
||||
{
|
||||
enabled: Schema.Boolean.pipe(
|
||||
|
||||
Reference in new issue
Block a user