refactor(provider-acp): move the shared ACP adapter into its own package (#17354)
Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
b5e4f1e0b0
commit
664bd5e524
70 files changed
+673
-553
No files matched your search
@@ -38,6 +38,7 @@
|
||||
"@napi-rs/keyring": "^1.3.0",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@t3tools/provider-acp": "workspace:*",
|
||||
"@t3tools/provider-core": "workspace:*",
|
||||
"@t3tools/provider-cursor": "workspace:*",
|
||||
"@t3tools/provider-muse": "workspace:*",
|
||||
|
||||
@@ -24,14 +24,15 @@ import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import * as ServerConfig from "../src/config.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
|
||||
import {
|
||||
GROK_DEFAULT_INSTANCE_ID,
|
||||
GROK_PROVIDER,
|
||||
grokLaunchRuntimeMode,
|
||||
makeGrokAdapterV2,
|
||||
} from "../src/orchestration-v2/Adapters/GrokAdapterV2.ts";
|
||||
import { ACP_PROTOCOL } from "../src/orchestration-v2/Adapters/AcpAdapterV2.ts";
|
||||
import { ACP_PROTOCOL } from "@t3tools/provider-acp/server/adapter";
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
import type { ProviderAdapterV2SessionRuntime } from "@t3tools/provider-core/server/ProviderAdapter";
|
||||
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/continuationRequests";
|
||||
@@ -40,7 +41,6 @@ import { provideDeterministicTestRuntime } from "../src/orchestration-v2/testkit
|
||||
import { ORCHESTRATOR_REPLAY_FIXTURES } from "../src/orchestration-v2/testkit/fixtures/index.ts";
|
||||
import { materializeFixtureInput } from "../src/orchestration-v2/testkit/fixtures/shared.ts";
|
||||
import { runOrchestratorV2Scenario } from "../src/orchestration-v2/testkit/OrchestratorScenario.ts";
|
||||
import { makeReplayServerConfig } from "../src/orchestration-v2/testkit/ProviderReplayHarness.ts";
|
||||
import * as ProviderReplayHarness from "../src/orchestration-v2/testkit/ProviderReplayHarness.ts";
|
||||
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
|
||||
import { makeGrokAcpRuntime } from "../src/provider/acp/GrokAcpSupport.ts";
|
||||
@@ -455,7 +455,7 @@ const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: s
|
||||
crypto: yield* Crypto.Crypto,
|
||||
fileSystem: yield* FileSystem.FileSystem,
|
||||
idAllocator: yield* IdAllocator.IdAllocatorV2,
|
||||
serverConfig: yield* ServerConfig.ServerConfig,
|
||||
host: yield* ProviderHost.ProviderHost,
|
||||
selfInvocation: yield* resolveSelfInvocation(),
|
||||
continuationRequests: yield* ProviderContinuationRequests.ProviderContinuationRequests,
|
||||
// Production's runtime factory, with the protocol logger teeing raw lines.
|
||||
@@ -496,10 +496,7 @@ const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: s
|
||||
).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
makeReplayServerConfig(`grok-record-${fixtureName}`),
|
||||
).pipe(Layer.provide(NodeServices.layer)),
|
||||
layerTestProviderHost().pipe(Layer.provide(NodeServices.layer)),
|
||||
NodeServices.layer,
|
||||
IdAllocator.layer,
|
||||
),
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
// The bridge intentionally treats MCP JSON-RPC messages as opaque JSON.
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
|
||||
import { makeAcpMcpOverAcpBridge } from "./AcpMcpOverAcpBridge.ts";
|
||||
|
||||
describe("AcpMcpOverAcpBridge", () => {
|
||||
it.effect("forwards authenticated MCP requests and closes the negotiated session", () =>
|
||||
Effect.gen(function* () {
|
||||
const requests: Array<{
|
||||
readonly method: string;
|
||||
readonly headers: Headers;
|
||||
readonly body: unknown;
|
||||
}> = [];
|
||||
const bridge = yield* makeAcpMcpOverAcpBridge({
|
||||
endpoint: "http://127.0.0.1:1/mcp",
|
||||
authorization: "Bearer bridge-test",
|
||||
allocateConnectionId: Effect.succeed("connection-1"),
|
||||
fetchImplementation: async (_url, init) => {
|
||||
const method = init?.method ?? "GET";
|
||||
const headers = new Headers(init?.headers);
|
||||
const body = init?.body === undefined ? null : JSON.parse(String(init.body));
|
||||
requests.push({ method, headers, body });
|
||||
if (method === "DELETE") return new Response(null, { status: 204 });
|
||||
if (body === null || typeof body !== "object") return new Response(null, { status: 202 });
|
||||
const request = body as { readonly id?: unknown; readonly method?: unknown };
|
||||
if (request.method === "notifications/initialized") {
|
||||
return new Response(null, { status: 202 });
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: request.id,
|
||||
result:
|
||||
request.method === "initialize"
|
||||
? { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: {} }
|
||||
: { tools: [] },
|
||||
}),
|
||||
{
|
||||
headers: { "content-type": "application/json", "mcp-session-id": "session-42" },
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const connected = yield* bridge.connect({ serverId: "t3-code" });
|
||||
expect(connected).toEqual({ connectionId: "connection-1" });
|
||||
expect(
|
||||
yield* bridge.message({ connectionId: connected.connectionId, method: "initialize" }),
|
||||
).toMatchObject({ protocolVersion: "2025-06-18" });
|
||||
expect(
|
||||
yield* bridge.message({ connectionId: connected.connectionId, method: "tools/list" }),
|
||||
).toEqual({ tools: [] });
|
||||
yield* bridge.notification({
|
||||
connectionId: connected.connectionId,
|
||||
method: "notifications/initialized",
|
||||
});
|
||||
yield* bridge.disconnect({ connectionId: connected.connectionId });
|
||||
|
||||
expect(requests[0]?.headers.get("authorization")).toBe("Bearer bridge-test");
|
||||
expect(requests[1]?.headers.get("mcp-session-id")).toBe("session-42");
|
||||
expect(requests[1]?.headers.get("mcp-protocol-version")).toBe("2025-06-18");
|
||||
expect(requests.at(-1)?.method).toBe("DELETE");
|
||||
expect(requests.at(-1)?.headers.get("mcp-session-id")).toBe("session-42");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("aborts an in-flight HTTP request when the ACP call is interrupted", () =>
|
||||
Effect.gen(function* () {
|
||||
const started = Promise.withResolvers<AbortSignal>();
|
||||
const bridge = yield* makeAcpMcpOverAcpBridge({
|
||||
endpoint: "http://127.0.0.1:1/mcp",
|
||||
authorization: "Bearer bridge-test",
|
||||
allocateConnectionId: Effect.succeed("connection-1"),
|
||||
fetchImplementation: (_url, init) => {
|
||||
if (!init?.signal) throw new Error("Missing cancellation signal");
|
||||
started.resolve(init.signal);
|
||||
return new Promise<Response>(() => {});
|
||||
},
|
||||
});
|
||||
const connected = yield* bridge.connect({ serverId: "t3-code" });
|
||||
const request = yield* bridge
|
||||
.message({ connectionId: connected.connectionId, method: "tools/list" })
|
||||
.pipe(Effect.forkChild);
|
||||
const signal = yield* Effect.promise(() => started.promise);
|
||||
yield* Fiber.interrupt(request);
|
||||
expect(signal.aborted).toBe(true);
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("rejects unknown servers, connections, and oversized messages", () =>
|
||||
Effect.gen(function* () {
|
||||
const bridge = yield* makeAcpMcpOverAcpBridge({
|
||||
endpoint: "http://127.0.0.1:1/mcp",
|
||||
authorization: "Bearer bridge-test",
|
||||
allocateConnectionId: Effect.succeed("connection-1"),
|
||||
fetchImplementation: () => Promise.resolve(new Response(null, { status: 202 })),
|
||||
});
|
||||
|
||||
expect(yield* bridge.connect({ serverId: "other" }).pipe(Effect.flip)).toMatchObject({
|
||||
_tag: "AcpMcpOverAcpError",
|
||||
});
|
||||
expect(
|
||||
yield* bridge.message({ connectionId: "missing", method: "tools/list" }).pipe(Effect.flip),
|
||||
).toMatchObject({ _tag: "AcpMcpOverAcpError" });
|
||||
|
||||
const connected = yield* bridge.connect({ serverId: "t3-code" });
|
||||
const failure = yield* bridge
|
||||
.message({
|
||||
connectionId: connected.connectionId,
|
||||
method: "tools/call",
|
||||
params: { payload: "x".repeat(8 * 1024 * 1024) },
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
expect(failure.message).toContain("exceeds 8 MiB");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,241 +0,0 @@
|
||||
// The bridge forwards opaque JSON-RPC values without interpreting their schemas.
|
||||
// @effect-diagnostics preferSchemaOverJson:off
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type * as AcpSchema from "effect-acp/compat";
|
||||
|
||||
import { responsePayloads } from "./AcpMcpStdioBridge.ts";
|
||||
|
||||
const MAX_CONNECTIONS = 16;
|
||||
const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
interface JsonRpcEnvelope {
|
||||
readonly id?: unknown;
|
||||
readonly method?: unknown;
|
||||
readonly error?: unknown;
|
||||
readonly result?: unknown;
|
||||
}
|
||||
|
||||
interface Connection {
|
||||
readonly mutex: Semaphore.Semaphore;
|
||||
sessionId: string | null;
|
||||
protocolVersion: string | null;
|
||||
nextRequestId: number;
|
||||
}
|
||||
|
||||
export class AcpMcpOverAcpError extends Error {
|
||||
readonly _tag = "AcpMcpOverAcpError";
|
||||
override readonly name = "AcpMcpOverAcpError";
|
||||
}
|
||||
|
||||
const bridgeError = (cause: unknown): AcpMcpOverAcpError =>
|
||||
cause instanceof AcpMcpOverAcpError
|
||||
? cause
|
||||
: new AcpMcpOverAcpError(cause instanceof Error ? cause.message : String(cause), { cause });
|
||||
|
||||
const asEnvelope = (value: unknown): JsonRpcEnvelope | null =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? (value as JsonRpcEnvelope)
|
||||
: null;
|
||||
|
||||
function protocolVersionOf(payload: unknown): string | null {
|
||||
const result = asEnvelope(payload)?.result;
|
||||
if (typeof result !== "object" || result === null || Array.isArray(result)) return null;
|
||||
const protocolVersion = (result as { readonly protocolVersion?: unknown }).protocolVersion;
|
||||
return typeof protocolVersion === "string" && protocolVersion.length > 0 ? protocolVersion : null;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
if (typeof error !== "object" || error === null || Array.isArray(error)) {
|
||||
return "The MCP server returned an error.";
|
||||
}
|
||||
const message = (error as { readonly message?: unknown }).message;
|
||||
return typeof message === "string" && message.length > 0
|
||||
? message
|
||||
: "The MCP server returned an error.";
|
||||
}
|
||||
|
||||
export interface AcpMcpOverAcpBridgeOptions {
|
||||
readonly endpoint: string;
|
||||
readonly authorization: string;
|
||||
readonly allocateConnectionId: Effect.Effect<string>;
|
||||
readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
|
||||
export interface AcpMcpOverAcpBridge {
|
||||
readonly connect: (
|
||||
request: AcpSchema.ConnectMcpRequest,
|
||||
) => Effect.Effect<AcpSchema.ConnectMcpResponse, AcpMcpOverAcpError>;
|
||||
readonly message: (
|
||||
request: AcpSchema.MessageMcpRequest,
|
||||
) => Effect.Effect<AcpSchema.MessageMcpResponse, AcpMcpOverAcpError>;
|
||||
readonly notification: (
|
||||
request: AcpSchema.MessageMcpNotification,
|
||||
) => Effect.Effect<void, AcpMcpOverAcpError>;
|
||||
readonly disconnect: (
|
||||
request: AcpSchema.DisconnectMcpRequest,
|
||||
) => Effect.Effect<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError>;
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/** Bridges the unstable ACP transport to T3's authenticated streamable-HTTP MCP endpoint. */
|
||||
export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(function* (
|
||||
options: AcpMcpOverAcpBridgeOptions,
|
||||
): Effect.fn.Return<AcpMcpOverAcpBridge> {
|
||||
const fetchImplementation = options.fetchImplementation ?? fetch;
|
||||
const connections = new Map<string, Connection>();
|
||||
|
||||
const connectionFor = (connectionId: string): Effect.Effect<Connection, AcpMcpOverAcpError> =>
|
||||
Effect.suspend(() => {
|
||||
const connection = connections.get(connectionId);
|
||||
return connection === undefined
|
||||
? Effect.fail(new AcpMcpOverAcpError(`Unknown MCP-over-ACP connection "${connectionId}".`))
|
||||
: Effect.succeed(connection);
|
||||
});
|
||||
|
||||
const send = (
|
||||
connection: Connection,
|
||||
message: unknown,
|
||||
): Effect.Effect<ReadonlyArray<unknown>, AcpMcpOverAcpError> =>
|
||||
connection.mutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const body = JSON.stringify(message);
|
||||
if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) {
|
||||
return yield* Effect.fail(new AcpMcpOverAcpError("MCP-over-ACP message exceeds 8 MiB."));
|
||||
}
|
||||
const response = yield* Effect.tryPromise({
|
||||
try: (signal) =>
|
||||
fetchImplementation(options.endpoint, {
|
||||
method: "POST",
|
||||
signal,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
accept: "application/json, text/event-stream",
|
||||
authorization: options.authorization,
|
||||
...(connection.sessionId === null
|
||||
? {}
|
||||
: { "mcp-session-id": connection.sessionId }),
|
||||
...(connection.protocolVersion === null
|
||||
? {}
|
||||
: { "mcp-protocol-version": connection.protocolVersion }),
|
||||
},
|
||||
body,
|
||||
}),
|
||||
catch: bridgeError,
|
||||
});
|
||||
connection.sessionId = response.headers.get("mcp-session-id") ?? connection.sessionId;
|
||||
if (!response.ok) {
|
||||
yield* Effect.promise(
|
||||
() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),
|
||||
);
|
||||
return yield* Effect.fail(
|
||||
new AcpMcpOverAcpError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
|
||||
);
|
||||
}
|
||||
const payloads = [...(yield* Stream.runCollect(responsePayloads(response)))];
|
||||
for (const payload of payloads) {
|
||||
connection.protocolVersion = protocolVersionOf(payload) ?? connection.protocolVersion;
|
||||
}
|
||||
return payloads;
|
||||
}).pipe(Effect.mapError(bridgeError)),
|
||||
);
|
||||
|
||||
const disconnect = (
|
||||
request: AcpSchema.DisconnectMcpRequest,
|
||||
): Effect.Effect<AcpSchema.DisconnectMcpResponse, AcpMcpOverAcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const connection = yield* connectionFor(request.connectionId);
|
||||
connections.delete(request.connectionId);
|
||||
const sessionId = connection.sessionId;
|
||||
if (sessionId !== null) {
|
||||
const response = yield* Effect.tryPromise({
|
||||
try: (signal) =>
|
||||
fetchImplementation(options.endpoint, {
|
||||
method: "DELETE",
|
||||
signal,
|
||||
headers: {
|
||||
authorization: options.authorization,
|
||||
"mcp-session-id": sessionId,
|
||||
...(connection.protocolVersion === null
|
||||
? {}
|
||||
: { "mcp-protocol-version": connection.protocolVersion }),
|
||||
},
|
||||
}),
|
||||
catch: bridgeError,
|
||||
});
|
||||
if (!response.ok && response.status !== 404) {
|
||||
return yield* Effect.fail(
|
||||
new AcpMcpOverAcpError(
|
||||
`T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
yield* Effect.promise(
|
||||
() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),
|
||||
);
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
return {
|
||||
connect: (request) =>
|
||||
Effect.gen(function* () {
|
||||
if (request.serverId !== "t3-code") {
|
||||
return yield* Effect.fail(
|
||||
new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`),
|
||||
);
|
||||
}
|
||||
if (connections.size >= MAX_CONNECTIONS) {
|
||||
return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections."));
|
||||
}
|
||||
const connectionId = yield* options.allocateConnectionId;
|
||||
connections.set(connectionId, {
|
||||
mutex: yield* Semaphore.make(1),
|
||||
sessionId: null,
|
||||
protocolVersion: null,
|
||||
nextRequestId: 0,
|
||||
});
|
||||
return { connectionId };
|
||||
}),
|
||||
message: (request) =>
|
||||
Effect.gen(function* () {
|
||||
const connection = yield* connectionFor(request.connectionId);
|
||||
const id = ++connection.nextRequestId;
|
||||
const payloads = yield* send(connection, {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
method: request.method,
|
||||
...(request.params == null ? {} : { params: request.params }),
|
||||
});
|
||||
const response = payloads.find((payload) => asEnvelope(payload)?.id === id);
|
||||
const envelope = asEnvelope(response);
|
||||
if (envelope === null) {
|
||||
return yield* Effect.fail(
|
||||
new AcpMcpOverAcpError("MCP server did not return a matching response."),
|
||||
);
|
||||
}
|
||||
if (envelope.error !== undefined) {
|
||||
return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error)));
|
||||
}
|
||||
return (envelope.result ?? null) as AcpSchema.MessageMcpResponse;
|
||||
}),
|
||||
notification: (request) =>
|
||||
Effect.gen(function* () {
|
||||
const connection = yield* connectionFor(request.connectionId);
|
||||
yield* send(connection, {
|
||||
jsonrpc: "2.0",
|
||||
method: request.method,
|
||||
...(request.params == null ? {} : { params: request.params }),
|
||||
});
|
||||
}),
|
||||
disconnect,
|
||||
dispose: Effect.suspend(() =>
|
||||
Effect.forEach(
|
||||
[...connections.keys()],
|
||||
(connectionId) => disconnect({ connectionId }).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
),
|
||||
),
|
||||
};
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";
|
||||
|
||||
/**
|
||||
* Stdio-to-HTTP bridge for T3's MCP endpoint.
|
||||
@@ -63,58 +64,6 @@ function protocolVersionOf(entry: unknown): string | null {
|
||||
return typeof version === "string" && version.length > 0 ? version : null;
|
||||
}
|
||||
|
||||
async function* sseDataLines(response: Response): AsyncGenerator<string> {
|
||||
if (response.body === null) return;
|
||||
const decoder = new TextDecoder();
|
||||
let buffered = "";
|
||||
for await (const chunk of response.body) {
|
||||
buffered += decoder.decode(chunk as Uint8Array, { stream: true });
|
||||
let separatorIndex = buffered.search(/\n\n|\r\n\r\n/u);
|
||||
while (separatorIndex !== -1) {
|
||||
const rawEvent = buffered.slice(0, separatorIndex);
|
||||
buffered = buffered.slice(separatorIndex).replace(/^(?:\r?\n){2}/u, "");
|
||||
const data = rawEvent
|
||||
.split(/\r?\n/u)
|
||||
.filter((line) => line.startsWith("data:"))
|
||||
.map((line) => line.slice("data:".length).trimStart())
|
||||
.join("\n");
|
||||
if (data.length > 0) yield data;
|
||||
separatorIndex = buffered.search(/\n\n|\r\n\r\n/u);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const discardResponseBody = (response: Response): Effect.Effect<void> =>
|
||||
Effect.promise(() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve());
|
||||
|
||||
/**
|
||||
* Every JSON-RPC payload carried by a response, in arrival order: nothing for
|
||||
* notification acknowledgements, each SSE `data:` event as it streams in, or
|
||||
* the single JSON body.
|
||||
*/
|
||||
export function responsePayloads(response: Response): Stream.Stream<unknown, AcpMcpBridgeError> {
|
||||
if (response.status === 202 || response.status === 204) {
|
||||
return Stream.unwrap(discardResponseBody(response).pipe(Effect.as(Stream.empty)));
|
||||
}
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
if (contentType.includes("text/event-stream")) {
|
||||
return Stream.fromAsyncIterable(sseDataLines(response), bridgeError).pipe(
|
||||
Stream.mapEffect((data) => Effect.try({ try: () => JSON.parse(data), catch: bridgeError })),
|
||||
);
|
||||
}
|
||||
return Stream.unwrap(
|
||||
Effect.tryPromise({ try: () => response.text(), catch: bridgeError }).pipe(
|
||||
Effect.flatMap((text) =>
|
||||
text.trim().length === 0
|
||||
? Effect.succeed(Stream.empty)
|
||||
: Effect.try({ try: () => JSON.parse(text) as unknown, catch: bridgeError }).pipe(
|
||||
Effect.map((payload) => Stream.fromIterable([payload])),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export interface AcpMcpToolCallOptions {
|
||||
readonly endpoint: string;
|
||||
readonly authorization: string;
|
||||
@@ -164,7 +113,7 @@ export function callAcpMcpTool(
|
||||
new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
|
||||
);
|
||||
}
|
||||
const payloads = yield* Stream.runCollect(responsePayloads(response));
|
||||
const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
|
||||
for (const payload of payloads) {
|
||||
protocolVersion = protocolVersionOf(payload) ?? protocolVersion;
|
||||
}
|
||||
@@ -271,7 +220,7 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
|
||||
}
|
||||
return yield* discardResponseBody(response);
|
||||
}
|
||||
yield* Stream.runForEach(responsePayloads(response), handleServerPayload);
|
||||
yield* Stream.runForEach(responsePayloads(response, bridgeError), handleServerPayload);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (envelope.id === undefined) return Effect.void;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,9 +13,9 @@ import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";
|
||||
import { ACP_PROTOCOL, type AcpAdapterV2RuntimeInput } from "./AcpAdapterV2.ts";
|
||||
import { ACP_PROTOCOL, type AcpAdapterV2RuntimeInput } from "@t3tools/provider-acp/server/adapter";
|
||||
|
||||
export const AcpReplayTranscript = Schema.Struct({
|
||||
provider: ProviderDriverKind,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,15 +14,16 @@ import { HttpClient, HttpClientResponse } from "effect/http";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import type {
|
||||
AcpRegistryAvailableCommands,
|
||||
AcpRegistryLiveConfiguration,
|
||||
} from "../../provider/acp/AcpRegistryProbe.ts";
|
||||
import * as AcpRegistrySupport from "../../provider/acp/AcpRegistrySupport.ts";
|
||||
import { ACP_SESSION_MODE_OPTION_ID } from "../../provider/acp/AcpSessionConfig.ts";
|
||||
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { ACP_SESSION_MODE_OPTION_ID } from "@t3tools/provider-acp/server/sessionConfig";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
import {
|
||||
decodeAcpReplayTranscript,
|
||||
@@ -43,9 +44,7 @@ const decodeAcpRegistryAdapterSettings = Schema.decodeUnknownEffect(
|
||||
AcpRegistryAdapterV2Driver.configSchema,
|
||||
);
|
||||
|
||||
const layerServerConfig = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-acp-registry-v2-adapter-",
|
||||
}).pipe(Layer.provide(NodeServices.layer));
|
||||
const layerHost = layerTestProviderHost().pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const layerRegistry = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
@@ -86,7 +85,7 @@ const layerRegistry = Layer.succeed(
|
||||
const layerTest = Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
IdAllocator.layer,
|
||||
layerServerConfig,
|
||||
layerHost,
|
||||
layerRegistry,
|
||||
ServerSettings.layerTest(),
|
||||
);
|
||||
@@ -202,7 +201,7 @@ describe("AcpRegistryAdapterV2", () => {
|
||||
fileSystem,
|
||||
idAllocator: yield* IdAllocator.IdAllocatorV2,
|
||||
resolver: { resolve: () => Effect.die("the runtime is injected") },
|
||||
serverConfig: yield* ServerConfig.ServerConfig,
|
||||
host: yield* ProviderHost.ProviderHost,
|
||||
makeRuntime: makeAcpReplayRuntime({
|
||||
transcript,
|
||||
statusPath,
|
||||
@@ -272,7 +271,7 @@ describe("AcpRegistryAdapterV2", () => {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocator.IdAllocatorV2;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
@@ -291,7 +290,7 @@ describe("AcpRegistryAdapterV2", () => {
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
resolver: { resolve: () => Effect.die("the runtime is injected") },
|
||||
serverConfig,
|
||||
host,
|
||||
makeRuntime: (input) =>
|
||||
Effect.gen(function* () {
|
||||
clientCapabilities = input.clientCapabilities;
|
||||
@@ -348,13 +347,13 @@ describe("AcpRegistryAdapterV2", () => {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocator.IdAllocatorV2;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({
|
||||
cacheDir: serverConfig.providerStatusCacheDir,
|
||||
toolsDir: serverConfig.baseDir + "/tools",
|
||||
cacheDir: host.paths.providerStatusCacheDir,
|
||||
toolsDir: host.paths.baseDir + "/tools",
|
||||
registryUrl,
|
||||
});
|
||||
const settings = yield* decodeAcpRegistryAdapterSettings({
|
||||
@@ -429,7 +428,7 @@ describe("AcpRegistryAdapterV2", () => {
|
||||
})),
|
||||
),
|
||||
},
|
||||
serverConfig,
|
||||
host,
|
||||
});
|
||||
const threadId = ThreadId.make("thread-acp-registry-fixture");
|
||||
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
|
||||
|
||||
@@ -9,12 +9,12 @@ import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
|
||||
import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";
|
||||
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
|
||||
import { makeReplayServerConfig } from "../testkit/ProviderReplayHarness.ts";
|
||||
import {
|
||||
type AcpReplayTranscript,
|
||||
AcpReplayTranscriptDecodeError,
|
||||
@@ -37,10 +37,7 @@ function layerAcpRegistryProviderAdapterRegistryReplay(
|
||||
transcript: AcpReplayTranscript,
|
||||
options: { readonly replayGate?: ProviderReplayGate } = {},
|
||||
) {
|
||||
const layerServerConfig = Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
makeReplayServerConfig(`acp-registry-${transcript.scenario}`).pipe(Effect.orDie),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
const layerHost = layerTestProviderHost().pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
return ProviderAdapterRegistry.layerFromAdaptersEffect(
|
||||
Effect.gen(function* () {
|
||||
@@ -49,7 +46,7 @@ function layerAcpRegistryProviderAdapterRegistryReplay(
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const idAllocator = yield* IdAllocator.IdAllocatorV2;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const replayGate = options.replayGate;
|
||||
const replayDir = yield* fileSystem
|
||||
.makeTempDirectory({
|
||||
@@ -71,7 +68,7 @@ function layerAcpRegistryProviderAdapterRegistryReplay(
|
||||
resolver: {
|
||||
resolve: () => Effect.die("ACP registry resolver must not run during replay"),
|
||||
},
|
||||
serverConfig,
|
||||
host,
|
||||
selfInvocation: yield* resolveSelfInvocation(),
|
||||
makeRuntime: makeAcpReplayRuntime({
|
||||
transcript,
|
||||
@@ -86,7 +83,7 @@ function layerAcpRegistryProviderAdapterRegistryReplay(
|
||||
return [adapter];
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(Layer.mergeAll(layerServerConfig, NodeServices.layer, IdAllocator.layer)),
|
||||
Layer.provide(Layer.mergeAll(layerHost, NodeServices.layer, IdAllocator.layer)),
|
||||
// Held inbound lines must not outlive the scenario and wedge teardown.
|
||||
Layer.merge(
|
||||
Layer.effectDiscard(
|
||||
|
||||
@@ -21,7 +21,7 @@ import type * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import {
|
||||
normalizeAcpRegistryCommands,
|
||||
normalizeAcpRegistryLiveConfiguration,
|
||||
@@ -29,8 +29,8 @@ import {
|
||||
} from "../../provider/acp/AcpRegistryProbe.ts";
|
||||
import * as AcpRegistrySupport from "../../provider/acp/AcpRegistrySupport.ts";
|
||||
import * as AcpRegistryRuntimeCoordinator from "../../provider/acp/AcpRegistryRuntimeCoordinator.ts";
|
||||
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { makeAcpNativeLoggerFactory } from "../../provider/acp/AcpNativeLogging.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
|
||||
import * as ProviderEventLoggers from "../../provider/ProviderEventLoggers.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
@@ -46,7 +46,7 @@ import {
|
||||
type AcpAdapterV2ExtensionContext,
|
||||
type AcpAdapterV2Flavor,
|
||||
type AcpAdapterV2RuntimeInput,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
} from "@t3tools/provider-acp/server/adapter";
|
||||
|
||||
export const ACP_REGISTRY_PROVIDER = ProviderDriverKind.make("acpRegistry");
|
||||
export const ACP_REGISTRY_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(ACP_REGISTRY_PROVIDER);
|
||||
@@ -65,7 +65,7 @@ export interface AcpRegistryAdapterV2Options {
|
||||
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
|
||||
readonly resolver: Pick<AcpRegistrySupport.AcpRegistryCatalog["Service"], "resolve">;
|
||||
readonly runtimeCoordinator?: AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator["Service"];
|
||||
readonly serverConfig: ServerConfig.ServerConfig["Service"];
|
||||
readonly host: ProviderHost.ProviderHostShape;
|
||||
readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
|
||||
readonly makeRuntime?: (
|
||||
input: AcpAdapterV2RuntimeInput,
|
||||
@@ -243,7 +243,7 @@ export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) {
|
||||
crypto: options.crypto,
|
||||
fileSystem: options.fileSystem,
|
||||
idAllocator: options.idAllocator,
|
||||
serverConfig: options.serverConfig,
|
||||
host: options.host,
|
||||
selfInvocation: options.selfInvocation,
|
||||
// Per-agent exception (see the note above registerMistralVibeAcpExtensions):
|
||||
// Devin runs commands through client terminals and has no ask mode over
|
||||
@@ -269,7 +269,7 @@ export type AcpRegistryAdapterV2DriverEnv =
|
||||
| IdAllocator.IdAllocatorV2
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig;
|
||||
| ProviderHost.ProviderHost;
|
||||
|
||||
export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
|
||||
AcpRegistrySettings,
|
||||
@@ -287,7 +287,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocator.IdAllocatorV2;
|
||||
const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const resolver = yield* AcpRegistrySupport.AcpRegistryCatalog;
|
||||
const runtimeCoordinator = yield* Effect.serviceOption(
|
||||
@@ -305,7 +305,7 @@ export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
|
||||
...(Option.isSome(runtimeCoordinator)
|
||||
? { runtimeCoordinator: runtimeCoordinator.value }
|
||||
: {}),
|
||||
serverConfig,
|
||||
host,
|
||||
selfInvocation,
|
||||
nativeLogging: (threadId) =>
|
||||
makeNativeLogger({
|
||||
|
||||
@@ -22,8 +22,9 @@ import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import type * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
import { ProviderAdapterV2RuntimePolicy } from "@t3tools/provider-core/server/ProviderAdapter";
|
||||
@@ -38,7 +39,7 @@ const flavor = makeAntigravityAcpAdapterFlavor({
|
||||
fileSystem: undefined as never,
|
||||
path: undefined as never,
|
||||
idAllocator: undefined as never,
|
||||
serverConfig: undefined as never,
|
||||
host: undefined as never,
|
||||
selfInvocation: undefined as never,
|
||||
makeRuntime: () => Effect.die("not spawned in this test"),
|
||||
withProcess: (_stop, task) => task,
|
||||
@@ -129,9 +130,7 @@ describe("AntigravityAdapterV2 flavor", () => {
|
||||
const layerSession = Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
IdAllocator.layer,
|
||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3-antigravity-v2-adapter-" }).pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
layerTestProviderHost().pipe(Layer.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
describe("AntigravityAdapterV2 client file system", () => {
|
||||
@@ -140,7 +139,7 @@ describe("AntigravityAdapterV2 client file system", () => {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
);
|
||||
@@ -157,7 +156,7 @@ describe("AntigravityAdapterV2 client file system", () => {
|
||||
fileSystem,
|
||||
path,
|
||||
idAllocator: yield* IdAllocator.IdAllocatorV2,
|
||||
serverConfig,
|
||||
host,
|
||||
makeRuntime: (input) =>
|
||||
makeAntigravityAcpRuntime({
|
||||
...input,
|
||||
@@ -193,7 +192,7 @@ describe("AntigravityAdapterV2 client file system", () => {
|
||||
});
|
||||
const outsideFile = path.join(outside, "secret.txt");
|
||||
yield* fileSystem.writeFileString(outsideFile, "secret");
|
||||
const attachment = path.join(serverConfig.attachmentsDir, "pasted.txt");
|
||||
const attachment = path.join(host.paths.attachmentsDir, "pasted.txt");
|
||||
yield* fileSystem.writeFileString(attachment, "pasted");
|
||||
|
||||
const threadId = ThreadId.make("thread-antigravity-containment");
|
||||
@@ -294,7 +293,7 @@ describe("AntigravityAdapterV2 workspace changes", () => {
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
@@ -309,7 +308,7 @@ describe("AntigravityAdapterV2 workspace changes", () => {
|
||||
fileSystem,
|
||||
path,
|
||||
idAllocator: yield* IdAllocator.IdAllocatorV2,
|
||||
serverConfig,
|
||||
host,
|
||||
makeRuntime: (input) =>
|
||||
makeAntigravityAcpRuntime({
|
||||
...input,
|
||||
@@ -431,7 +430,7 @@ describe("AntigravityAdapterV2 client file system under restrictive policies", (
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const mockAgentPath = yield* path.fromFileUrl(
|
||||
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
|
||||
@@ -459,7 +458,7 @@ describe("AntigravityAdapterV2 client file system under restrictive policies", (
|
||||
fileSystem,
|
||||
path,
|
||||
idAllocator: yield* IdAllocator.IdAllocatorV2,
|
||||
serverConfig,
|
||||
host,
|
||||
makeRuntime: (input) =>
|
||||
makeAntigravityAcpRuntime({
|
||||
...input,
|
||||
|
||||
@@ -14,9 +14,9 @@ import * as Exit from "effect/Exit";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import type { ServerConfig } from "../../config.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts";
|
||||
import type * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import {
|
||||
antigravityPermissionMode,
|
||||
applyAntigravityAcpModelSelection,
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
makeAcpAdapterV2,
|
||||
type AcpAdapterV2Flavor,
|
||||
type AcpAdapterV2RuntimeInput,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
} from "@t3tools/provider-acp/server/adapter";
|
||||
|
||||
const ANTIGRAVITY_PROVIDER = ProviderDriverKind.make("antigravity");
|
||||
|
||||
@@ -68,7 +68,7 @@ export interface AntigravityAdapterV2Options {
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
readonly idAllocator: IdAllocatorV2["Service"];
|
||||
readonly serverConfig: ServerConfig["Service"];
|
||||
readonly host: ProviderHost.ProviderHostShape;
|
||||
/** Spawns the official agent with the instance's Google profile. */
|
||||
readonly makeRuntime: (
|
||||
input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
|
||||
@@ -125,9 +125,7 @@ export function makeAntigravityAcpAdapterFlavor(
|
||||
// the turn text references. It is a leaf directory of uploads. A session
|
||||
// without a workspace gets no workspace root rather than the server's cwd.
|
||||
const antigravityClientFileRoots = (cwd: string | null) =>
|
||||
cwd === null
|
||||
? [options.serverConfig.attachmentsDir]
|
||||
: [cwd, options.serverConfig.attachmentsDir];
|
||||
cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir];
|
||||
const makeRuntime = (input: AcpAdapterV2RuntimeInput) =>
|
||||
Effect.gen(function* () {
|
||||
// AcpAdapterV2 owns the runtime scope; sign-in and sign-out stop the
|
||||
@@ -139,7 +137,7 @@ export function makeAntigravityAcpAdapterFlavor(
|
||||
options.makeRuntime({
|
||||
...input,
|
||||
clientFileSystem: true,
|
||||
additionalDirectories: [options.serverConfig.attachmentsDir],
|
||||
additionalDirectories: [options.host.paths.attachmentsDir],
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.provideService(Scope.Scope, scope));
|
||||
@@ -233,7 +231,7 @@ export function makeAntigravityAdapterV2(options: AntigravityAdapterV2Options) {
|
||||
crypto: options.crypto,
|
||||
fileSystem: options.fileSystem,
|
||||
idAllocator: options.idAllocator,
|
||||
serverConfig: options.serverConfig,
|
||||
host: options.host,
|
||||
selfInvocation: options.selfInvocation,
|
||||
...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
|
||||
...(options.continuationRequests === undefined
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type * as AcpSchema from "effect-acp/compat";
|
||||
import type { AcpToolCallState } from "../../provider/acp/AcpRuntimeModel.ts";
|
||||
import type { AcpAdapterV2SubagentUpdate } from "./AcpAdapterV2.ts";
|
||||
import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
|
||||
import type { AcpAdapterV2SubagentUpdate } from "@t3tools/provider-acp/server/adapter";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | undefined {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
|
||||
@@ -22,7 +22,8 @@ import * as Schema from "effect/Schema";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
|
||||
import * as ProjectStore from "../ProjectStore.ts";
|
||||
import { buildInitialGrokProviderSnapshot } from "../../provider/GrokProvider.ts";
|
||||
import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
|
||||
@@ -30,13 +31,13 @@ import * as ProviderInstanceRegistry from "../../provider/ProviderInstanceRegist
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
import { ProviderAdapterV2RuntimePolicy } from "@t3tools/provider-core/server/ProviderAdapter";
|
||||
import * as RuntimePolicy from "../RuntimePolicy.ts";
|
||||
import { acpPermissionDisposition } from "../../provider/acp/AcpClientPolicy.ts";
|
||||
import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
|
||||
import {
|
||||
AcpProviderCapabilitiesV2,
|
||||
acpCompletedTurnShouldTerminalizeTool,
|
||||
acpSubagentStatusBlocksTurnSettlement,
|
||||
acpSupportsImagePrompts,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
} from "@t3tools/provider-acp/server/adapter";
|
||||
import {
|
||||
makeGrokAcpAdapterFlavor,
|
||||
makeGrokAdapterV2,
|
||||
@@ -311,10 +312,8 @@ describe("Grok permission prompts", () => {
|
||||
});
|
||||
|
||||
describe("Grok launch permission mode", () => {
|
||||
const layerServerConfig = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-grok-v2-launch-",
|
||||
}).pipe(Layer.provide(NodeServices.layer));
|
||||
const layerTest = Layer.mergeAll(NodeServices.layer, IdAllocator.layer, layerServerConfig);
|
||||
const layerHost = layerTestProviderHost().pipe(Layer.provide(NodeServices.layer));
|
||||
const layerTest = Layer.mergeAll(NodeServices.layer, IdAllocator.layer, layerHost);
|
||||
|
||||
// Opens a session through the adapter's own Grok runtime factory and returns
|
||||
// the argv it tried to launch. The spawn fails after recording, so no
|
||||
@@ -342,7 +341,7 @@ describe("Grok launch permission mode", () => {
|
||||
crypto: yield* Crypto.Crypto,
|
||||
fileSystem: yield* FileSystem.FileSystem,
|
||||
idAllocator: yield* IdAllocator.IdAllocatorV2,
|
||||
serverConfig: yield* ServerConfig.ServerConfig,
|
||||
host: yield* ProviderHost.ProviderHost,
|
||||
selfInvocation: yield* resolveSelfInvocation(),
|
||||
});
|
||||
yield* adapter
|
||||
|
||||
@@ -10,7 +10,8 @@ import { ChildProcessSpawner } from "effect/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import { layerTestProviderHost } from "@t3tools/provider-testing/host";
|
||||
import {
|
||||
GROK_ACP_CANCEL_META,
|
||||
GROK_ACP_INITIALIZE_META,
|
||||
@@ -21,7 +22,6 @@ import * as ProviderContinuationRequests from "@t3tools/provider-core/server/con
|
||||
import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
|
||||
import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";
|
||||
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
|
||||
import { makeReplayServerConfig } from "../testkit/ProviderReplayHarness.ts";
|
||||
import {
|
||||
type AcpReplayTranscript,
|
||||
AcpReplayTranscriptDecodeError,
|
||||
@@ -37,10 +37,7 @@ function layerGrokProviderAdapterRegistryReplay(
|
||||
transcript: AcpReplayTranscript,
|
||||
options: { readonly replayGate?: ProviderReplayGate } = {},
|
||||
) {
|
||||
const layerServerConfig = Layer.effect(
|
||||
ServerConfig.ServerConfig,
|
||||
makeReplayServerConfig(`grok-${transcript.scenario}`).pipe(Effect.orDie),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
const layerHost = layerTestProviderHost().pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
return ProviderAdapterRegistry.layerFromAdaptersEffect(
|
||||
Effect.gen(function* () {
|
||||
@@ -50,7 +47,7 @@ function layerGrokProviderAdapterRegistryReplay(
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const idAllocator = yield* IdAllocator.IdAllocatorV2;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
// Same queue the continuation worker drains when the fixture runs it.
|
||||
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
|
||||
const replayGate = options.replayGate;
|
||||
@@ -72,7 +69,7 @@ function layerGrokProviderAdapterRegistryReplay(
|
||||
crypto,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
host,
|
||||
selfInvocation: yield* resolveSelfInvocation(),
|
||||
// Same wrapping as makeGrokAcpRuntime: client type and Ctrl+C cancel
|
||||
// metadata and the x.ai prompt-completion race, so replay sends what
|
||||
@@ -102,7 +99,7 @@ function layerGrokProviderAdapterRegistryReplay(
|
||||
return [adapter];
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(Layer.mergeAll(layerServerConfig, NodeServices.layer, IdAllocator.layer)),
|
||||
Layer.provide(Layer.mergeAll(layerHost, NodeServices.layer, IdAllocator.layer)),
|
||||
// Held inbound lines must not outlive the scenario and wedge teardown.
|
||||
Layer.merge(
|
||||
Layer.effectDiscard(
|
||||
|
||||
@@ -23,8 +23,8 @@ import type * as Scope from "effect/Scope";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import { makeAcpNativeLoggerFactory } from "../../provider/acp/AcpNativeLogging.ts";
|
||||
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
|
||||
import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
currentGrokModelIdFromSessionSetup,
|
||||
@@ -54,8 +54,8 @@ import {
|
||||
XAiExitPlanModeRequest,
|
||||
} from "../../provider/acp/XAiAcpExtension.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
|
||||
import { acpPermissionDisposition } from "../../provider/acp/AcpClientPolicy.ts";
|
||||
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
|
||||
import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import * as ProviderEventLoggers from "../../provider/ProviderEventLoggers.ts";
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/continuationRequests";
|
||||
@@ -71,7 +71,7 @@ import {
|
||||
type AcpAdapterV2ExtensionContext,
|
||||
type AcpAdapterV2Flavor,
|
||||
type AcpAdapterV2RuntimeInput,
|
||||
} from "./AcpAdapterV2.ts";
|
||||
} from "@t3tools/provider-acp/server/adapter";
|
||||
|
||||
export const GROK_PROVIDER = ProviderDriverKind.make("grok");
|
||||
const GROK_DRIVER_KIND = GROK_PROVIDER;
|
||||
@@ -117,7 +117,7 @@ export interface GrokAdapterV2Options {
|
||||
readonly selfInvocation: SelfInvocation;
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
|
||||
readonly serverConfig: ServerConfig.ServerConfig["Service"];
|
||||
readonly host: ProviderHost.ProviderHostShape;
|
||||
readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
|
||||
readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
|
||||
readonly testHooks?: Parameters<typeof makeAcpAdapterV2>[0]["testHooks"];
|
||||
@@ -337,7 +337,7 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
|
||||
crypto: options.crypto,
|
||||
fileSystem: options.fileSystem,
|
||||
idAllocator: options.idAllocator,
|
||||
serverConfig: options.serverConfig,
|
||||
host: options.host,
|
||||
selfInvocation: options.selfInvocation,
|
||||
...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
|
||||
...(options.continuationRequests === undefined
|
||||
@@ -354,7 +354,7 @@ export type GrokAdapterV2DriverEnv =
|
||||
| IdAllocator.IdAllocatorV2
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig;
|
||||
| ProviderHost.ProviderHost;
|
||||
|
||||
export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapterV2DriverEnv> = {
|
||||
driverKind: GROK_DRIVER_KIND,
|
||||
@@ -370,7 +370,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocator.IdAllocatorV2;
|
||||
const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
|
||||
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
return makeGrokAdapterV2({
|
||||
@@ -382,7 +382,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
|
||||
crypto,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
host,
|
||||
selfInvocation,
|
||||
continuationRequests,
|
||||
nativeLogging: (threadId) =>
|
||||
@@ -417,7 +417,7 @@ const layer: Layer.Layer<
|
||||
| FileSystem.FileSystem
|
||||
| IdAllocator.IdAllocatorV2
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ProviderHost.ProviderHost
|
||||
> = Layer.effect(
|
||||
ProviderAdapter.ProviderAdapterV2,
|
||||
Effect.gen(function* () {
|
||||
@@ -429,7 +429,7 @@ const layer: Layer.Layer<
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const idAllocator = yield* IdAllocator.IdAllocatorV2;
|
||||
const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost.ProviderHost;
|
||||
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
|
||||
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
return makeGrokAdapterV2({
|
||||
@@ -441,7 +441,7 @@ const layer: Layer.Layer<
|
||||
crypto,
|
||||
fileSystem,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
host,
|
||||
selfInvocation,
|
||||
continuationRequests,
|
||||
nativeLogging: (threadId) =>
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { AcpProviderCapabilitiesV2 } from "./Adapters/AcpAdapterV2.ts";
|
||||
import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter";
|
||||
import { acpSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
|
||||
|
||||
const selection = (model: string, effort = "medium"): ModelSelection => ({
|
||||
|
||||
@@ -42,7 +42,7 @@ import {
|
||||
CodexProviderCapabilitiesV2,
|
||||
canReuseCodexContextUsage,
|
||||
} from "../Adapters/CodexAdapterV2.ts";
|
||||
import { AcpProviderCapabilitiesV2 } from "../Adapters/AcpAdapterV2.ts";
|
||||
import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter";
|
||||
import { CursorProviderCapabilitiesV2 } from "@t3tools/provider-cursor/testing";
|
||||
import * as EventSink from "../EventSink.ts";
|
||||
import * as EventStore from "../EventStore.ts";
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
type AntigravityAuth,
|
||||
type AntigravityAuthRuntime,
|
||||
} from "./AntigravityAuth.ts";
|
||||
import type { AcpSessionRuntimeStartResult } from "./acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
|
||||
const instanceId = ProviderInstanceId.make("antigravity-auth-test");
|
||||
const owner = "t3-auth-session-owner";
|
||||
@@ -31,7 +31,7 @@ const initialized = {
|
||||
authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
|
||||
agentCapabilities: { auth: { logout: {} } },
|
||||
} satisfies AcpSchema.InitializeResponse;
|
||||
const started: AcpSessionRuntimeStartResult = {
|
||||
const started: AcpSessionRuntime.AcpSessionRuntimeStartResult = {
|
||||
sessionId: "native-session",
|
||||
initializeResult: initialized,
|
||||
sessionSetupResult: {
|
||||
|
||||
@@ -19,7 +19,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
import * as AcpErrors from "effect-acp/errors";
|
||||
|
||||
import type { AcpSessionRuntime, AcpSessionRuntimeStartResult } from "./acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import {
|
||||
parseAntigravityAuthorizationUrl,
|
||||
type AntigravityAuthorizationUrl,
|
||||
@@ -66,19 +66,19 @@ export interface AntigravityAuth {
|
||||
}
|
||||
|
||||
export type AntigravityAuthRuntime = Pick<
|
||||
AcpSessionRuntime["Service"],
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
"initialize" | "start" | "request"
|
||||
>;
|
||||
|
||||
export interface AntigravityAuthOptions<
|
||||
Runtime extends AntigravityAuthRuntime = AcpSessionRuntime["Service"],
|
||||
Runtime extends AntigravityAuthRuntime = AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
> {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly makeRuntime: (input: {
|
||||
readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, AcpErrors.AcpError>;
|
||||
}) => Effect.Effect<Runtime, AcpErrors.AcpError | ProviderSetupError, Scope.Scope>;
|
||||
readonly onAuthenticated: (
|
||||
result: AcpSessionRuntimeStartResult,
|
||||
result: AcpSessionRuntime.AcpSessionRuntimeStartResult,
|
||||
runtime: Runtime,
|
||||
) => Effect.Effect<void>;
|
||||
readonly onSignedOut: Effect.Effect<void>;
|
||||
|
||||
@@ -23,7 +23,7 @@ import * as ServerConfig from "../config.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as ProviderHostLive from "./ProviderHostLive.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import type { AcpSessionRuntimeStartResult } from "./acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import {
|
||||
buildAntigravityModelsFromSession,
|
||||
makeAntigravityProvider,
|
||||
@@ -98,7 +98,7 @@ const started = {
|
||||
initializeResult,
|
||||
sessionSetupResult,
|
||||
modelConfigId: "model",
|
||||
} satisfies AcpSessionRuntimeStartResult;
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult;
|
||||
|
||||
const commands = [
|
||||
{ name: "plan", description: "Create a plan", input: { type: "text", hint: "What to plan" } },
|
||||
|
||||
@@ -18,7 +18,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
|
||||
import type { AcpSessionRuntimeStartResult } from "./acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
|
||||
import {
|
||||
makeManualOnlyProviderMaintenanceCapabilities,
|
||||
@@ -38,7 +38,7 @@ const AUTH_UNCHECKED_MESSAGE =
|
||||
"Antigravity is installed. Google account access is not checked yet.";
|
||||
|
||||
type SessionSetupResult = Pick<
|
||||
AcpSessionRuntimeStartResult["sessionSetupResult"],
|
||||
AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
|
||||
"configOptions" | "models"
|
||||
>;
|
||||
|
||||
@@ -256,7 +256,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
|
||||
});
|
||||
|
||||
const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
|
||||
started: AcpSessionRuntimeStartResult,
|
||||
started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
|
||||
cwd?: string,
|
||||
) {
|
||||
const before = yield* SubscriptionRef.get(metadata);
|
||||
|
||||
@@ -22,7 +22,6 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
|
||||
import { ProviderHost } from "@t3tools/provider-core/server/ProviderHost";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import {
|
||||
AcpRegistryAdapterV2Driver,
|
||||
type AcpRegistryAdapterV2DriverEnv,
|
||||
@@ -489,7 +488,6 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost;
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -528,7 +526,7 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
|
||||
};
|
||||
const confirmedAuthentication =
|
||||
yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({
|
||||
cacheDir: serverConfig.providerStatusCacheDir,
|
||||
cacheDir: host.paths.providerStatusCacheDir,
|
||||
instanceId,
|
||||
settings: effectiveConfig,
|
||||
environment,
|
||||
@@ -573,7 +571,7 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
|
||||
const enrichProvider = checkAcpRegistryProviderStatus(
|
||||
{
|
||||
...readinessInput,
|
||||
cwd: serverConfig.cwd,
|
||||
cwd: host.paths.cwd,
|
||||
},
|
||||
probeAcpRegistryConfiguration,
|
||||
).pipe(
|
||||
@@ -768,7 +766,7 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
|
||||
const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
|
||||
instanceId,
|
||||
settings: effectiveConfig,
|
||||
cwd: serverConfig.cwd,
|
||||
cwd: host.paths.cwd,
|
||||
environment: processEnvironment,
|
||||
onChanged: (authenticated) =>
|
||||
confirmedAuthentication
|
||||
|
||||
@@ -19,7 +19,6 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
||||
import type { AcpError } from "effect-acp/errors";
|
||||
|
||||
import { ProviderHost } from "@t3tools/provider-core/server/ProviderHost";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import {
|
||||
isAntigravityTextGenerationAvailable,
|
||||
makeAntigravityTextGeneration,
|
||||
@@ -40,7 +39,7 @@ import {
|
||||
makeAntigravityAcpRuntime,
|
||||
type AntigravityAcpRuntimeInput,
|
||||
} from "../acp/AntigravityAcpSupport.ts";
|
||||
import type { AcpSessionRuntime, AcpSessionRuntimeStartResult } from "../acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
|
||||
import {
|
||||
removeAntigravityRuntimeTempDirs,
|
||||
@@ -49,7 +48,7 @@ import {
|
||||
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
|
||||
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/continuationRequests";
|
||||
import { makeAntigravityAdapterV2 } from "../../orchestration-v2/Adapters/AntigravityAdapterV2.ts";
|
||||
import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
|
||||
import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeAntigravityProvider } from "../AntigravityProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
@@ -76,8 +75,7 @@ export type AntigravityDriverEnv =
|
||||
| IdAllocator.IdAllocatorV2
|
||||
| ModelManifest.ModelManifest
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig;
|
||||
| ProviderEventLoggers.ProviderEventLoggers;
|
||||
|
||||
/** Each instance owns its Google profile. Executable releases are shared by the environment. */
|
||||
export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityDriverEnv> = {
|
||||
@@ -91,7 +89,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const host = yield* ProviderHost;
|
||||
const selfInvocation = yield* resolveSelfInvocation();
|
||||
const installation = yield* AntigravityInstallation.AntigravityInstallation;
|
||||
const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
@@ -110,7 +108,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
|
||||
const processEnvironment = mergeProviderInstanceEnvironment(environment);
|
||||
const userHome = resolveAntigravityUserHome(yield* HostProcessPlatform, processEnvironment);
|
||||
const directories = yield* resolveAntigravityInstanceDirectories(
|
||||
serverConfig.stateDir,
|
||||
host.paths.stateDir,
|
||||
instanceId,
|
||||
).pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
@@ -158,7 +156,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
|
||||
const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
|
||||
input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
|
||||
): Effect.fn.Return<
|
||||
AcpSessionRuntime["Service"],
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
AcpError | ProviderSetupError,
|
||||
Scope.Scope
|
||||
> {
|
||||
@@ -303,8 +301,8 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
|
||||
});
|
||||
|
||||
const publishCatalog = (
|
||||
started: AcpSessionRuntimeStartResult,
|
||||
runtime: Pick<AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,
|
||||
started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
|
||||
runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
yield* provider.onSessionStarted(started);
|
||||
@@ -405,7 +403,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
|
||||
fileSystem,
|
||||
path,
|
||||
idAllocator,
|
||||
serverConfig,
|
||||
host,
|
||||
selfInvocation,
|
||||
makeRuntime,
|
||||
withProcess: authFlow.withProcess,
|
||||
|
||||
@@ -42,7 +42,7 @@ import {
|
||||
makeGrokAcpRuntime,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "./acp/GrokAcpSupport.ts";
|
||||
import { sessionModelStateFromInitialize } from "./acp/AcpRuntimeModel.ts";
|
||||
import { sessionModelStateFromInitialize } from "@t3tools/provider-acp/server/runtimeModel";
|
||||
import { discoverGrokSkills } from "./Drivers/GrokSkills.ts";
|
||||
|
||||
const GROK_PRESENTATION = {
|
||||
|
||||
@@ -22,7 +22,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
|
||||
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
|
||||
import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
|
||||
import { AcpProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/AcpAdapterV2.ts";
|
||||
import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter";
|
||||
import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
|
||||
import * as ProviderAuthService from "./ProviderAuthService.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
|
||||
@@ -31,6 +31,7 @@ export const layer = Layer.effect(
|
||||
baseDir: config.baseDir,
|
||||
stateDir: config.stateDir,
|
||||
providerStatusCacheDir: config.providerStatusCacheDir,
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
},
|
||||
settings: {
|
||||
get: serverSettings.getSettings,
|
||||
|
||||
@@ -1,348 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import {
|
||||
acpClientExecuteDisposition,
|
||||
acpMcpToolApprovalElicitationDisposition,
|
||||
acpPermissionDisposition,
|
||||
makeAcpClientPolicyGrants,
|
||||
type AcpRuntimePolicy,
|
||||
} from "./AcpClientPolicy.ts";
|
||||
|
||||
function permissionRequest(
|
||||
kind: NonNullable<EffectAcpSchema.RequestPermissionRequest["toolCall"]["kind"]>,
|
||||
locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation>,
|
||||
): EffectAcpSchema.RequestPermissionRequest {
|
||||
return {
|
||||
options: [],
|
||||
sessionId: "permission-session",
|
||||
toolCall: {
|
||||
kind,
|
||||
...(locations === undefined ? {} : { locations }),
|
||||
toolCallId: "permission-tool-call",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("acpPermissionDisposition", () => {
|
||||
const cwd = NodePath.resolve(process.cwd(), "acp-permission-workspace");
|
||||
const writableRoot = NodePath.resolve(process.cwd(), "acp-additional-writable-root");
|
||||
const policy: AcpRuntimePolicy = {
|
||||
runtimeMode: "full-access",
|
||||
cwd,
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
writableRoots: [writableRoot],
|
||||
networkAccess: false,
|
||||
},
|
||||
};
|
||||
|
||||
it("auto-allows mutations only when every location is in cwd or an additional writable root", () => {
|
||||
assert.equal(
|
||||
acpPermissionDisposition(policy, permissionRequest("edit", [{ path: "src/index.ts" }])),
|
||||
"allow",
|
||||
);
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
policy,
|
||||
permissionRequest("delete", [{ path: NodePath.join(writableRoot, "generated.ts") }]),
|
||||
),
|
||||
"allow",
|
||||
);
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
policy,
|
||||
permissionRequest("move", [
|
||||
{ path: NodePath.join(cwd, "from.ts") },
|
||||
{ path: NodePath.join(writableRoot, "to.ts") },
|
||||
]),
|
||||
),
|
||||
"allow",
|
||||
);
|
||||
});
|
||||
|
||||
it("denies missing or out-of-root mutation locations", () => {
|
||||
const outside = NodePath.resolve(process.cwd(), "outside-acp-permission-workspace", "file.ts");
|
||||
assert.equal(acpPermissionDisposition(policy, permissionRequest("edit")), "deny");
|
||||
assert.equal(
|
||||
acpPermissionDisposition(policy, permissionRequest("delete", [{ path: "../escape.ts" }])),
|
||||
"deny",
|
||||
);
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
policy,
|
||||
permissionRequest("move", [{ path: NodePath.join(cwd, "inside.ts") }, { path: outside }]),
|
||||
),
|
||||
"deny",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps non-mutating workspace permissions and denials unchanged", () => {
|
||||
assert.equal(acpPermissionDisposition(policy, permissionRequest("read")), "allow");
|
||||
assert.equal(acpPermissionDisposition(policy, permissionRequest("execute")), "deny");
|
||||
});
|
||||
|
||||
it("auto-accept-edits approves file changes without locations and asks for the rest", () => {
|
||||
// ACP permission requests need not carry locations.
|
||||
const autoAcceptEdits: AcpRuntimePolicy = { runtimeMode: "auto-accept-edits", cwd };
|
||||
for (const kind of ["edit", "delete", "move"] as const) {
|
||||
assert.equal(acpPermissionDisposition(autoAcceptEdits, permissionRequest(kind)), "allow");
|
||||
}
|
||||
for (const kind of ["execute", "fetch", "other"] as const) {
|
||||
assert.equal(acpPermissionDisposition(autoAcceptEdits, permissionRequest(kind)), "ask");
|
||||
}
|
||||
assert.equal(acpPermissionDisposition(autoAcceptEdits, permissionRequest("read")), "allow");
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
{ ...autoAcceptEdits, approvalPolicy: "on-request" },
|
||||
permissionRequest("edit"),
|
||||
),
|
||||
"ask",
|
||||
);
|
||||
});
|
||||
|
||||
it("auto-allows read-kind permission requests under on-request approval", () => {
|
||||
for (const runtimePolicy of [
|
||||
{ ...policy, approvalPolicy: "on-request" },
|
||||
{ ...policy, approvalPolicy: "on-request", sandboxPolicy: { type: "readOnly" } },
|
||||
{ runtimeMode: "approval-required", cwd },
|
||||
] satisfies ReadonlyArray<AcpRuntimePolicy>) {
|
||||
for (const kind of ["read", "search", "think"] as const) {
|
||||
assert.equal(acpPermissionDisposition(runtimePolicy, permissionRequest(kind)), "allow");
|
||||
}
|
||||
for (const kind of ["edit", "delete", "move", "execute", "fetch", "other"] as const) {
|
||||
assert.equal(acpPermissionDisposition(runtimePolicy, permissionRequest(kind)), "ask");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it.effect("denies mutations through workspace symlinks that escape the writable roots", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspace = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-permission-workspace-",
|
||||
});
|
||||
const outside = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-permission-outside-",
|
||||
});
|
||||
const outsideFile = path.join(outside, "existing.ts");
|
||||
yield* fileSystem.writeFileString(outsideFile, "outside");
|
||||
yield* fileSystem.symlink(outsideFile, path.join(workspace, "linked-file.ts"));
|
||||
yield* fileSystem.symlink(outside, path.join(workspace, "linked-directory"));
|
||||
|
||||
const realPolicy: AcpRuntimePolicy = {
|
||||
runtimeMode: "full-access",
|
||||
cwd: workspace,
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
writableRoots: [],
|
||||
networkAccess: false,
|
||||
},
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
realPolicy,
|
||||
permissionRequest("edit", [{ path: "linked-file.ts" }]),
|
||||
),
|
||||
"deny",
|
||||
);
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
realPolicy,
|
||||
permissionRequest("edit", [{ path: "linked-directory/new-file.ts" }]),
|
||||
),
|
||||
"deny",
|
||||
"a missing leaf below an escaping directory symlink must not be auto-approved",
|
||||
);
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
realPolicy,
|
||||
permissionRequest("edit", [{ path: "linked-directory/../escaped-file.ts" }]),
|
||||
),
|
||||
"deny",
|
||||
"physical symlink traversal must be resolved before parent segments",
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("allows existing and new files beneath canonical writable roots", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const workspace = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-permission-workspace-",
|
||||
});
|
||||
const workspaceLinkParent = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-acp-permission-link-parent-",
|
||||
});
|
||||
const workspaceLink = path.join(workspaceLinkParent, "workspace-link");
|
||||
yield* fileSystem.makeDirectory(path.join(workspace, "src"), { recursive: true });
|
||||
yield* fileSystem.writeFileString(path.join(workspace, "src", "existing.ts"), "existing");
|
||||
yield* fileSystem.symlink(workspace, workspaceLink);
|
||||
|
||||
const realPolicy: AcpRuntimePolicy = {
|
||||
runtimeMode: "full-access",
|
||||
cwd: workspaceLink,
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
writableRoots: [],
|
||||
networkAccess: false,
|
||||
},
|
||||
};
|
||||
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
realPolicy,
|
||||
permissionRequest("edit", [{ path: "src/existing.ts" }]),
|
||||
),
|
||||
"allow",
|
||||
);
|
||||
assert.equal(
|
||||
acpPermissionDisposition(
|
||||
realPolicy,
|
||||
permissionRequest("edit", [{ path: "src/generated/new-file.ts" }]),
|
||||
),
|
||||
"allow",
|
||||
"non-existent descendants of a real in-root ancestor remain writable",
|
||||
);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
|
||||
describe("acpMcpToolApprovalElicitationDisposition", () => {
|
||||
it("applies runtime policy only to explicitly tagged MCP approval elicitations", () => {
|
||||
const fullAccess: AcpRuntimePolicy = {
|
||||
runtimeMode: "full-access",
|
||||
cwd: process.cwd(),
|
||||
};
|
||||
const approvalRequired: AcpRuntimePolicy = {
|
||||
runtimeMode: "approval-required",
|
||||
cwd: process.cwd(),
|
||||
};
|
||||
const tagged = {
|
||||
sessionId: "session-1",
|
||||
message: "Approve this request?",
|
||||
mode: "form",
|
||||
requestedSchema: { type: "object", properties: {} },
|
||||
_meta: { codex_approval_kind: "mcp_tool_call" },
|
||||
} satisfies EffectAcpSchema.CreateElicitationRequest;
|
||||
|
||||
assert.equal(acpMcpToolApprovalElicitationDisposition(fullAccess, tagged), "allow");
|
||||
assert.equal(acpMcpToolApprovalElicitationDisposition(approvalRequired, tagged), "ask");
|
||||
assert.equal(
|
||||
acpMcpToolApprovalElicitationDisposition(
|
||||
{ ...fullAccess, approvalPolicy: "on-request" },
|
||||
tagged,
|
||||
),
|
||||
"ask",
|
||||
);
|
||||
assert.equal(
|
||||
acpMcpToolApprovalElicitationDisposition(
|
||||
{
|
||||
runtimeMode: "auto-accept-edits",
|
||||
cwd: process.cwd(),
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "workspaceWrite",
|
||||
writableRoots: [],
|
||||
networkAccess: false,
|
||||
},
|
||||
},
|
||||
tagged,
|
||||
),
|
||||
"allow",
|
||||
);
|
||||
const { _meta: _tag, ...untagged } = tagged;
|
||||
assert.equal(
|
||||
acpMcpToolApprovalElicitationDisposition(
|
||||
fullAccess,
|
||||
untagged,
|
||||
"mcp_tool_call_approval_exec-123",
|
||||
),
|
||||
"allow",
|
||||
);
|
||||
assert.isUndefined(
|
||||
acpMcpToolApprovalElicitationDisposition(fullAccess, {
|
||||
...tagged,
|
||||
_meta: { codex_approval_kind: "ordinary_form" },
|
||||
}),
|
||||
);
|
||||
assert.isUndefined(
|
||||
acpMcpToolApprovalElicitationDisposition(fullAccess, {
|
||||
sessionId: "session-1",
|
||||
message: "Authenticate",
|
||||
mode: "url",
|
||||
elicitationId: "elicitation-1",
|
||||
url: "https://example.com/login",
|
||||
_meta: { codex_approval_kind: "mcp_tool_call" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("client terminal disposition", () => {
|
||||
const cwd = NodePath.resolve(process.cwd(), "acp-client-policy-workspace");
|
||||
|
||||
it("asks in approval-required and auto-accept-edits, allows in auto and full access", () => {
|
||||
assert.equal(acpClientExecuteDisposition({ runtimeMode: "approval-required", cwd }), "ask");
|
||||
assert.equal(acpClientExecuteDisposition({ runtimeMode: "auto-accept-edits", cwd }), "ask");
|
||||
assert.equal(acpClientExecuteDisposition({ runtimeMode: "auto", cwd }), "allow");
|
||||
assert.equal(acpClientExecuteDisposition({ runtimeMode: "full-access", cwd }), "allow");
|
||||
});
|
||||
|
||||
it("denies terminals under explicit read-only and workspace-write sandboxes", () => {
|
||||
for (const sandboxPolicy of [
|
||||
{ type: "readOnly" },
|
||||
{ type: "workspaceWrite", writableRoots: [], networkAccess: false },
|
||||
]) {
|
||||
assert.equal(
|
||||
acpClientExecuteDisposition({
|
||||
runtimeMode: "full-access",
|
||||
cwd,
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy,
|
||||
}),
|
||||
"deny",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("makeAcpClientPolicyGrants", () => {
|
||||
it("grants terminals only from commands, never from an approved read or edit", () => {
|
||||
const grants = makeAcpClientPolicyGrants();
|
||||
grants.recordApproval({ kind: "file-read", scope: "turn", turnKey: "turn-1" });
|
||||
grants.recordApproval({ kind: "file-change", scope: "session", turnKey: "turn-1" });
|
||||
assert.isFalse(grants.allowsExecute("turn-1"));
|
||||
grants.recordApproval({ kind: "command", scope: "turn", turnKey: "turn-1" });
|
||||
assert.isTrue(grants.allowsExecute("turn-1"));
|
||||
assert.isFalse(grants.allowsExecute("turn-2"));
|
||||
assert.isFalse(grants.allowsExecute(null));
|
||||
});
|
||||
|
||||
it("keeps accept-for-session command grants across turns", () => {
|
||||
const grants = makeAcpClientPolicyGrants();
|
||||
grants.recordApproval({ kind: "command", scope: "session", turnKey: "turn-1" });
|
||||
assert.isTrue(grants.allowsExecute("turn-9"));
|
||||
assert.isTrue(grants.allowsExecute(null));
|
||||
});
|
||||
|
||||
it("drops a turn's command grant when a later turn approves one", () => {
|
||||
const grants = makeAcpClientPolicyGrants();
|
||||
grants.recordApproval({ kind: "command", scope: "turn", turnKey: "turn-1" });
|
||||
grants.recordApproval({ kind: "command", scope: "turn", turnKey: "turn-2" });
|
||||
assert.isFalse(grants.allowsExecute("turn-1"));
|
||||
assert.isTrue(grants.allowsExecute("turn-2"));
|
||||
});
|
||||
});
|
||||
@@ -1,297 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import type { ProviderRequestKind, RuntimeMode } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
/**
|
||||
* Runtime-policy decisions for ACP work that T3 mediates.
|
||||
*
|
||||
* ACP agents run their own tools under their own permission model and ask
|
||||
* through `session/request_permission`, which T3 answers by policy. The one
|
||||
* client-mediated path left is Devin's `terminal/*`, which runs with the T3
|
||||
* server's own privileges; it resolves through {@link acpOperationDisposition}
|
||||
* so a client terminal can never do more than an execute permission request.
|
||||
*/
|
||||
|
||||
/** Structural subset of the adapter runtime policy that decisions read. */
|
||||
export interface AcpRuntimePolicy {
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly cwd: string | null;
|
||||
readonly approvalPolicy?: unknown;
|
||||
readonly sandboxPolicy?: unknown;
|
||||
}
|
||||
|
||||
export type AcpPermissionDisposition = "allow" | "ask" | "deny";
|
||||
|
||||
export function unknownRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function resolveAcpPermissionPath(path: string, cwd: string | null): string | undefined {
|
||||
const trimmed = path.trim();
|
||||
if (trimmed.length === 0) return undefined;
|
||||
if (NodePath.isAbsolute(trimmed)) return trimmed;
|
||||
if (cwd === null || cwd.trim().length === 0) return undefined;
|
||||
return `${cwd}${cwd.endsWith(NodePath.sep) ? "" : NodePath.sep}${trimmed}`;
|
||||
}
|
||||
|
||||
function acpPathIsWithinRoot(path: string, root: string): boolean {
|
||||
const relative = NodePath.relative(root, path);
|
||||
return (
|
||||
relative === "" ||
|
||||
(relative !== ".." &&
|
||||
!relative.startsWith(`..${NodePath.sep}`) &&
|
||||
!NodePath.isAbsolute(relative))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonicalize a path for an authorization containment check.
|
||||
*
|
||||
* `realpath` cannot resolve a file that has not been created yet, so walk up
|
||||
* to the deepest existing ancestor and append the missing suffix to that
|
||||
* ancestor's canonical path. This follows symlinked directories while still
|
||||
* allowing normal writes to new files. If an existing entry cannot be
|
||||
* canonicalized (for example, a broken symlink), fail closed.
|
||||
*/
|
||||
function acpCanonicalPathForContainment(path: string): string | undefined {
|
||||
// Do not lexically normalize before realpath. For a path such as
|
||||
// `workspace/link/../file`, the kernel resolves `link` before `..`; an
|
||||
// eager NodePath.resolve would erase that symlink traversal and could turn
|
||||
// an outside target into an apparently in-workspace path.
|
||||
let candidate = path;
|
||||
const missingSuffix: Array<string> = [];
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
return NodePath.resolve(NodeFS.realpathSync.native(candidate), ...missingSuffix);
|
||||
} catch (cause) {
|
||||
if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
NodeFS.lstatSync(candidate);
|
||||
// The entry exists but realpath could not resolve it, as with a broken
|
||||
// symlink. Treat it as untrusted rather than authorizing its lexical path.
|
||||
return undefined;
|
||||
} catch (cause) {
|
||||
if ((cause as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const parent = NodePath.dirname(candidate);
|
||||
if (parent === candidate) return undefined;
|
||||
missingSuffix.unshift(NodePath.basename(candidate));
|
||||
candidate = parent;
|
||||
}
|
||||
}
|
||||
|
||||
/** The parts of a native operation the disposition logic reads. */
|
||||
interface AcpPolicyOperation {
|
||||
readonly kind: string | null | undefined;
|
||||
readonly locations: ReadonlyArray<{ readonly path: string }> | null | undefined;
|
||||
}
|
||||
|
||||
function acpPolicyRequiresApproval(runtimePolicy: AcpRuntimePolicy): boolean {
|
||||
return runtimePolicy.approvalPolicy === undefined
|
||||
? runtimePolicy.runtimeMode === "approval-required"
|
||||
: runtimePolicy.approvalPolicy !== "never";
|
||||
}
|
||||
|
||||
function isAcpReadKind(toolKind: string): boolean {
|
||||
return toolKind === "read" || toolKind === "search" || toolKind === "think";
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads follow the sandbox alone and never ask. Approval policy governs writes
|
||||
* and commands, as it does for Codex and Claude, and every sandbox T3 knows
|
||||
* lets the agent read. That includes no explicit sandbox, since the strictest
|
||||
* runtime mode (approval-required) implies a read-only one. Unknown sandbox
|
||||
* types still fail closed.
|
||||
*/
|
||||
function acpReadDisposition(runtimePolicy: AcpRuntimePolicy): "allow" | "deny" {
|
||||
switch (unknownRecord(runtimePolicy.sandboxPolicy)?.type) {
|
||||
case undefined:
|
||||
case "readOnly":
|
||||
case "workspaceWrite":
|
||||
case "dangerFullAccess":
|
||||
case "externalSandbox":
|
||||
return "allow";
|
||||
default:
|
||||
return "deny";
|
||||
}
|
||||
}
|
||||
|
||||
function acpWorkspaceWriteAllowsMutation(
|
||||
runtimePolicy: AcpRuntimePolicy,
|
||||
sandboxPolicy: Record<string, unknown>,
|
||||
locations: AcpPolicyOperation["locations"],
|
||||
): boolean {
|
||||
const cwd =
|
||||
typeof runtimePolicy.cwd === "string" && runtimePolicy.cwd.trim().length > 0
|
||||
? (resolveAcpPermissionPath(runtimePolicy.cwd, process.cwd()) ?? null)
|
||||
: null;
|
||||
const roots: Array<string> = [];
|
||||
if (cwd !== null) {
|
||||
const canonicalCwd = acpCanonicalPathForContainment(cwd);
|
||||
if (canonicalCwd !== undefined) roots.push(canonicalCwd);
|
||||
}
|
||||
const writableRoots = sandboxPolicy.writableRoots;
|
||||
if (Array.isArray(writableRoots)) {
|
||||
for (const writableRoot of writableRoots) {
|
||||
if (typeof writableRoot !== "string") continue;
|
||||
const resolved = resolveAcpPermissionPath(writableRoot, cwd);
|
||||
if (resolved === undefined) continue;
|
||||
const canonicalRoot = acpCanonicalPathForContainment(resolved);
|
||||
if (canonicalRoot !== undefined) roots.push(canonicalRoot);
|
||||
}
|
||||
}
|
||||
if (roots.length === 0) return false;
|
||||
|
||||
if (locations === undefined || locations === null || locations.length === 0) {
|
||||
return false;
|
||||
}
|
||||
for (const location of locations) {
|
||||
const resolved = resolveAcpPermissionPath(location.path, cwd);
|
||||
const canonicalPath =
|
||||
resolved === undefined ? undefined : acpCanonicalPathForContainment(resolved);
|
||||
if (
|
||||
canonicalPath === undefined ||
|
||||
!roots.some((root) => acpPathIsWithinRoot(canonicalPath, root))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disposition of one native operation under the active runtime policy. Shared
|
||||
* by provider permission requests and the client fs/terminal handlers.
|
||||
*/
|
||||
function acpOperationDisposition(
|
||||
runtimePolicy: AcpRuntimePolicy,
|
||||
operation: AcpPolicyOperation,
|
||||
): AcpPermissionDisposition {
|
||||
const toolKind = operation.kind ?? "other";
|
||||
if (isAcpReadKind(toolKind)) {
|
||||
return acpReadDisposition(runtimePolicy);
|
||||
}
|
||||
if (acpPolicyRequiresApproval(runtimePolicy)) {
|
||||
return "ask";
|
||||
}
|
||||
|
||||
const sandboxPolicy = unknownRecord(runtimePolicy.sandboxPolicy);
|
||||
switch (sandboxPolicy?.type) {
|
||||
case "readOnly":
|
||||
return "deny";
|
||||
case "workspaceWrite":
|
||||
if (isAcpMutationKind(toolKind)) {
|
||||
return acpWorkspaceWriteAllowsMutation(
|
||||
runtimePolicy,
|
||||
sandboxPolicy ?? {},
|
||||
operation.locations,
|
||||
)
|
||||
? "allow"
|
||||
: "deny";
|
||||
}
|
||||
return "deny";
|
||||
case "dangerFullAccess":
|
||||
case "externalSandbox":
|
||||
return "allow";
|
||||
case undefined:
|
||||
if (runtimePolicy.runtimeMode === "approval-required") return "deny";
|
||||
// Auto-accept edits approves file changes wherever the agent makes them
|
||||
// (ACP prompts need not carry locations to confine); other actions still ask.
|
||||
if (
|
||||
runtimePolicy.runtimeMode === "auto-accept-edits" &&
|
||||
runtimePolicy.approvalPolicy === undefined &&
|
||||
!isAcpMutationKind(toolKind)
|
||||
) {
|
||||
return "ask";
|
||||
}
|
||||
return "allow";
|
||||
default:
|
||||
return "deny";
|
||||
}
|
||||
}
|
||||
|
||||
function isAcpMutationKind(toolKind: string): boolean {
|
||||
return toolKind === "edit" || toolKind === "delete" || toolKind === "move";
|
||||
}
|
||||
|
||||
export function acpPermissionDisposition(
|
||||
runtimePolicy: AcpRuntimePolicy,
|
||||
request: EffectAcpSchema.RequestPermissionRequest,
|
||||
): AcpPermissionDisposition {
|
||||
return acpOperationDisposition(runtimePolicy, {
|
||||
kind: request.toolCall.kind,
|
||||
locations: request.toolCall.locations,
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve explicitly tagged MCP approvals through the thread's normal policy. */
|
||||
export function acpMcpToolApprovalElicitationDisposition(
|
||||
runtimePolicy: AcpRuntimePolicy,
|
||||
request: EffectAcpSchema.CreateElicitationRequest,
|
||||
nativeRequestId?: string,
|
||||
): AcpPermissionDisposition | undefined {
|
||||
if (
|
||||
request.mode !== "form" ||
|
||||
(unknownRecord(request._meta)?.codex_approval_kind !== "mcp_tool_call" &&
|
||||
nativeRequestId?.startsWith("mcp_tool_call_approval_") !== true)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
// This request comes from T3's authenticated, scope-checked MCP endpoint,
|
||||
// not an arbitrary provider command. Let explicit approval mode surface it
|
||||
// to the user and otherwise allow the endpoint to enforce its own policy.
|
||||
return acpPolicyRequiresApproval(runtimePolicy) ? "ask" : "allow";
|
||||
}
|
||||
|
||||
/** Disposition of a client-mediated `terminal/create` (Devin's client terminals). */
|
||||
export function acpClientExecuteDisposition(
|
||||
runtimePolicy: AcpRuntimePolicy,
|
||||
): AcpPermissionDisposition {
|
||||
return acpOperationDisposition(runtimePolicy, { kind: "execute", locations: undefined });
|
||||
}
|
||||
|
||||
export interface AcpApprovalGrantInput {
|
||||
readonly kind: ProviderRequestKind;
|
||||
readonly scope: "session" | "turn";
|
||||
readonly turnKey: string;
|
||||
}
|
||||
|
||||
export interface AcpClientPolicyGrants {
|
||||
readonly recordApproval: (input: AcpApprovalGrantInput) => void;
|
||||
readonly allowsExecute: (turnKey: string | null) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Command approvals recorded when the user accepts a `session/request_permission`,
|
||||
* so an "ask" disposition at the client terminal boundary honors a command the
|
||||
* user already approved. ACP does not link an approved tool call to the
|
||||
* terminals the agent then creates, so an approved command authorizes client
|
||||
* terminals for the approving turn, or for the session on accept-for-session.
|
||||
*/
|
||||
export function makeAcpClientPolicyGrants(): AcpClientPolicyGrants {
|
||||
let sessionExecute = false;
|
||||
let turnExecute: string | null = null;
|
||||
return {
|
||||
recordApproval: (input) => {
|
||||
if (input.kind !== "command") return;
|
||||
if (input.scope === "session") {
|
||||
sessionExecute = true;
|
||||
} else {
|
||||
turnExecute = input.turnKey;
|
||||
}
|
||||
},
|
||||
allowsExecute: (turnKey) => sessionExecute || (turnKey !== null && turnExecute === turnKey),
|
||||
};
|
||||
}
|
||||
@@ -1,312 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Result from "effect/Result";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
|
||||
import {
|
||||
makeAcpClientTerminals,
|
||||
resolveEmbeddedTerminalContent,
|
||||
type AcpClientTerminals,
|
||||
} from "./AcpClientTerminals.ts";
|
||||
|
||||
const withTerminals = <A, E>(use: (terminals: AcpClientTerminals) => Effect.Effect<A, E>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const terminals = yield* makeAcpClientTerminals({
|
||||
spawner,
|
||||
defaultCwd: process.cwd(),
|
||||
});
|
||||
return yield* use(terminals).pipe(Effect.ensuring(terminals.disposeAll));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("AcpClientTerminals", () => {
|
||||
it.effect("runs a command, buffers output, and reports the exit status", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const created = yield* terminals.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", "console.log('hello from acp'); process.exit(3);"],
|
||||
});
|
||||
|
||||
const exit = yield* terminals.waitForExit({
|
||||
sessionId: "session",
|
||||
terminalId: created.terminalId,
|
||||
});
|
||||
expect(exit.exitCode).toBe(3);
|
||||
|
||||
const output = yield* terminals.output({
|
||||
sessionId: "session",
|
||||
terminalId: created.terminalId,
|
||||
});
|
||||
expect(output.output).toContain("hello from acp");
|
||||
expect(output.truncated).toBe(false);
|
||||
expect(output.exitStatus?.exitCode).toBe(3);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves terminal environment from the requesting ACP session", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const terminals = yield* makeAcpClientTerminals({
|
||||
spawner,
|
||||
defaultCwd: process.cwd(),
|
||||
environmentForSession: (sessionId) => ({
|
||||
T3_TEST_ACP_SESSION_TOKEN: sessionId === "session-a" ? "token-a" : "token-b",
|
||||
}),
|
||||
});
|
||||
yield* Effect.addFinalizer(() => terminals.disposeAll);
|
||||
|
||||
for (const [sessionId, expected] of [
|
||||
["session-a", "token-a"],
|
||||
["session-b", "token-b"],
|
||||
] as const) {
|
||||
const created = yield* terminals.create({
|
||||
sessionId,
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.stdout.write(process.env.T3_TEST_ACP_SESSION_TOKEN ?? '')"],
|
||||
});
|
||||
yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId });
|
||||
const output = yield* terminals.output({ sessionId, terminalId: created.terminalId });
|
||||
expect(output.output).toBe(expected);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("runs Devin shell source with arguments, pipes, and session fallback variables", () =>
|
||||
Effect.gen(function* () {
|
||||
const terminals = yield* makeAcpClientTerminals({
|
||||
spawner: yield* ChildProcessSpawner.ChildProcessSpawner,
|
||||
defaultCwd: process.cwd(),
|
||||
shellCommands: true,
|
||||
environmentForSession: () => ({ T3_ACP_MCP_NODE: "mailbox-probe" }),
|
||||
});
|
||||
yield* Effect.addFinalizer(() => terminals.disposeAll);
|
||||
// Same command-only shape as the failed production commands and live capture.
|
||||
const terminal = yield* terminals.create({
|
||||
sessionId: "devin",
|
||||
command: 'printf "%s\\n" "$T3_ACP_MCP_NODE" | tr a-z A-Z',
|
||||
});
|
||||
const exit = yield* terminals.waitForExit({ sessionId: "devin", ...terminal });
|
||||
const output = yield* terminals.output({ sessionId: "devin", ...terminal });
|
||||
expect(exit.exitCode).toBe(0);
|
||||
expect(output.output.trim()).toBe("MAILBOX-PROBE");
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("truncates buffered output from the beginning at the byte limit", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const created = yield* terminals.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.stdout.write('a'.repeat(64) + 'TAIL');"],
|
||||
outputByteLimit: 16,
|
||||
});
|
||||
yield* terminals.waitForExit({ sessionId: "session", terminalId: created.terminalId });
|
||||
|
||||
const output = yield* terminals.output({
|
||||
sessionId: "session",
|
||||
terminalId: created.terminalId,
|
||||
});
|
||||
expect(output.truncated).toBe(true);
|
||||
expect(output.output.endsWith("TAIL")).toBe(true);
|
||||
expect(output.output.length).toBeLessThanOrEqual(16);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("kills long-running commands and rejects released terminal handles", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const created = yield* terminals.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", "setInterval(() => {}, 1000);"],
|
||||
});
|
||||
yield* terminals.kill({ sessionId: "session", terminalId: created.terminalId });
|
||||
const exit = yield* terminals.waitForExit({
|
||||
sessionId: "session",
|
||||
terminalId: created.terminalId,
|
||||
});
|
||||
expect(exit.exitCode === 0 ? null : exit.exitCode).not.toBe(0);
|
||||
expect(exit.signal).toBe("SIGTERM");
|
||||
|
||||
yield* terminals.release({ sessionId: "session", terminalId: created.terminalId });
|
||||
const rejected = yield* Effect.flip(
|
||||
terminals.output({ sessionId: "session", terminalId: created.terminalId }),
|
||||
);
|
||||
expect(rejected.message).toContain("unknown terminal ID");
|
||||
|
||||
// Embedded tool-call content still renders released terminals.
|
||||
expect(terminals.readOutputSnapshot("session", created.terminalId)).toBeDefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reserves terminal capacity across concurrent creates", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const results = yield* Effect.all(
|
||||
Array.from({ length: 17 }, () =>
|
||||
terminals
|
||||
.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", "setInterval(() => {}, 1000);"],
|
||||
})
|
||||
.pipe(Effect.result),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
expect(results.filter(Result.isSuccess)).toHaveLength(16);
|
||||
expect(results.filter(Result.isFailure)).toHaveLength(1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds retained snapshots after terminals are released", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const terminalIds: string[] = [];
|
||||
for (let index = 0; index < 33; index += 1) {
|
||||
const created = yield* terminals.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", `process.stdout.write('${index}');`],
|
||||
});
|
||||
yield* terminals.release({ sessionId: "session", terminalId: created.terminalId });
|
||||
terminalIds.push(created.terminalId);
|
||||
}
|
||||
|
||||
expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeUndefined();
|
||||
expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds unreleased terminal handles without invalidating existing ids", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const terminalIds: string[] = [];
|
||||
for (let index = 0; index < 64; index += 1) {
|
||||
const created = yield* terminals.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", `process.stdout.write('${index}');`],
|
||||
});
|
||||
yield* terminals.waitForExit({
|
||||
sessionId: "session",
|
||||
terminalId: created.terminalId,
|
||||
});
|
||||
terminalIds.push(created.terminalId);
|
||||
}
|
||||
|
||||
const rejected = yield* terminals
|
||||
.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", ""],
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
expect(Result.isFailure(rejected)).toBe(true);
|
||||
expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeDefined();
|
||||
expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds aggregate output retained across unreleased terminals", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const terminalIds: string[] = [];
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const created = yield* terminals.create({
|
||||
sessionId: "session",
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.stdout.write('x'.repeat(8 * 1024 * 1024));"],
|
||||
outputByteLimit: 8 * 1024 * 1024,
|
||||
});
|
||||
yield* terminals.waitForExit({
|
||||
sessionId: "session",
|
||||
terminalId: created.terminalId,
|
||||
});
|
||||
terminalIds.push(created.terminalId);
|
||||
}
|
||||
|
||||
const snapshots = terminalIds.map((terminalId) =>
|
||||
terminals.readOutputSnapshot("session", terminalId)!,
|
||||
);
|
||||
const retainedBytes = snapshots.reduce(
|
||||
(total, snapshot) => total + Buffer.byteLength(snapshot.output),
|
||||
0,
|
||||
);
|
||||
expect(retainedBytes).toBeLessThanOrEqual(16 * 1024 * 1024);
|
||||
expect(snapshots.some((snapshot) => snapshot.truncated)).toBe(true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects terminal handles from a different ACP session", () =>
|
||||
withTerminals((terminals) =>
|
||||
Effect.gen(function* () {
|
||||
const created = yield* terminals.create({
|
||||
sessionId: "owner-session",
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.stdout.write('owned');"],
|
||||
});
|
||||
const foreignRequest = {
|
||||
sessionId: "foreign-session",
|
||||
terminalId: created.terminalId,
|
||||
};
|
||||
const results = yield* Effect.all(
|
||||
[
|
||||
terminals.output(foreignRequest),
|
||||
terminals.waitForExit(foreignRequest),
|
||||
terminals.kill(foreignRequest),
|
||||
terminals.release(foreignRequest),
|
||||
].map((effect) => effect.pipe(Effect.result)),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
expect(results.every(Result.isFailure)).toBe(true);
|
||||
expect(terminals.readOutputSnapshot("foreign-session", created.terminalId)).toBeUndefined();
|
||||
expect(terminals.readOutputSnapshot("owner-session", created.terminalId)).toBeDefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveEmbeddedTerminalContent", () => {
|
||||
it("rewrites terminal content into text from the buffered snapshot", () => {
|
||||
const notification = {
|
||||
sessionId: "session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update" as const,
|
||||
toolCallId: "call-1",
|
||||
content: [
|
||||
{ type: "content" as const, content: { type: "text" as const, text: "before" } },
|
||||
{ type: "terminal" as const, terminalId: "t3-term-1" },
|
||||
{ type: "terminal" as const, terminalId: "t3-term-unknown" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const resolved = resolveEmbeddedTerminalContent(notification, (sessionId, terminalId) =>
|
||||
sessionId === "session" && terminalId === "t3-term-1"
|
||||
? { output: "compiled 3 files", truncated: false, exitStatus: undefined }
|
||||
: undefined,
|
||||
);
|
||||
|
||||
expect(resolved.update).toMatchObject({
|
||||
content: [
|
||||
{ type: "content", content: { type: "text", text: "before" } },
|
||||
{ type: "content", content: { type: "text", text: "compiled 3 files" } },
|
||||
{ type: "content", content: { type: "text", text: "[terminal t3-term-unknown]" } },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,459 +0,0 @@
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/process";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
import * as NodeBuffer from "node:buffer";
|
||||
|
||||
/**
|
||||
* Client-side implementation of the ACP `terminal` capability.
|
||||
*
|
||||
* Agents create terminals to run commands through the client
|
||||
* (`terminal/create`), poll buffered output, await exit, kill, and release
|
||||
* them. Terminals also appear as embedded tool-call content, which
|
||||
* {@link resolveEmbeddedTerminalContent} rewrites into plain text so the
|
||||
* existing tool-call projection renders live command output.
|
||||
*/
|
||||
|
||||
const MAX_LIVE_TERMINALS = 16;
|
||||
const MAX_UNRELEASED_TERMINALS = 64;
|
||||
const MAX_RETAINED_TERMINALS = 32;
|
||||
const MAX_RETAINED_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const DEFAULT_OUTPUT_BYTE_LIMIT = 4 * 1024 * 1024;
|
||||
const MAX_OUTPUT_BYTE_LIMIT = 8 * 1024 * 1024;
|
||||
|
||||
const terminalRequestError = (message: string, cause?: unknown) =>
|
||||
EffectAcpErrors.AcpRequestError.internalError(
|
||||
message,
|
||||
undefined,
|
||||
cause === undefined ? {} : { cause },
|
||||
);
|
||||
|
||||
interface OutputBufferState {
|
||||
chunks: Array<Uint8Array>;
|
||||
bytes: number;
|
||||
truncated: boolean;
|
||||
readonly limit: number;
|
||||
}
|
||||
|
||||
function trimOutputStart(state: OutputBufferState, bytes: number): void {
|
||||
let remaining = Math.min(bytes, state.bytes);
|
||||
while (remaining > 0) {
|
||||
const head = state.chunks[0]!;
|
||||
if (head.byteLength <= remaining) {
|
||||
state.chunks.shift();
|
||||
state.bytes -= head.byteLength;
|
||||
remaining -= head.byteLength;
|
||||
} else {
|
||||
state.chunks[0] = head.subarray(remaining);
|
||||
state.bytes -= remaining;
|
||||
remaining = 0;
|
||||
}
|
||||
state.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
function appendOutput(state: OutputBufferState, chunk: Uint8Array): void {
|
||||
state.chunks.push(chunk);
|
||||
state.bytes += chunk.byteLength;
|
||||
// The spec requires truncation from the beginning of the output.
|
||||
if (state.bytes > state.limit) trimOutputStart(state, state.bytes - state.limit);
|
||||
}
|
||||
|
||||
function readOutput(state: OutputBufferState): string {
|
||||
let combined: Uint8Array = NodeBuffer.Buffer.concat(state.chunks, state.bytes);
|
||||
if (state.truncated) {
|
||||
// Drop leading UTF-8 continuation bytes so truncation lands on a
|
||||
// character boundary, as the spec requires.
|
||||
let start = 0;
|
||||
while (start < combined.byteLength && (combined[start]! & 0b1100_0000) === 0b1000_0000) {
|
||||
start += 1;
|
||||
}
|
||||
combined = combined.subarray(start);
|
||||
}
|
||||
return NodeBuffer.Buffer.from(combined).toString("utf8");
|
||||
}
|
||||
|
||||
function terminalExitSignal(error: unknown): string | null {
|
||||
const cause = error instanceof Error ? error.cause : undefined;
|
||||
const message =
|
||||
cause instanceof Error ? cause.message : error instanceof Error ? error.message : "";
|
||||
return message.match(/signal: '([^']+)'/u)?.[1] ?? null;
|
||||
}
|
||||
|
||||
export interface AcpTerminalOutputSnapshot {
|
||||
readonly output: string;
|
||||
readonly truncated: boolean;
|
||||
readonly exitStatus: EffectAcpSchema.TerminalExitStatus | undefined;
|
||||
}
|
||||
|
||||
interface ManagedAcpTerminal {
|
||||
readonly terminalId: string;
|
||||
readonly sessionId: string;
|
||||
/** The spawned command with args, kept for MCP-fallback identification. */
|
||||
readonly commandLine: string;
|
||||
readonly buffer: OutputBufferState;
|
||||
readonly exit: Deferred.Deferred<EffectAcpSchema.WaitForTerminalExitResponse>;
|
||||
readonly kill: Effect.Effect<void>;
|
||||
/** Closes the terminal's scope, killing the process if still running. */
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
exitStatus: EffectAcpSchema.TerminalExitStatus | undefined;
|
||||
released: boolean;
|
||||
}
|
||||
|
||||
export interface AcpClientTerminals {
|
||||
readonly create: (
|
||||
request: EffectAcpSchema.CreateTerminalRequest,
|
||||
) => Effect.Effect<EffectAcpSchema.CreateTerminalResponse, EffectAcpErrors.AcpRequestError>;
|
||||
readonly output: (
|
||||
request: EffectAcpSchema.TerminalOutputRequest,
|
||||
) => Effect.Effect<EffectAcpSchema.TerminalOutputResponse, EffectAcpErrors.AcpRequestError>;
|
||||
readonly waitForExit: (
|
||||
request: EffectAcpSchema.WaitForTerminalExitRequest,
|
||||
) => Effect.Effect<EffectAcpSchema.WaitForTerminalExitResponse, EffectAcpErrors.AcpRequestError>;
|
||||
readonly kill: (
|
||||
request: EffectAcpSchema.KillTerminalRequest,
|
||||
) => Effect.Effect<EffectAcpSchema.KillTerminalResponse, EffectAcpErrors.AcpRequestError>;
|
||||
readonly release: (
|
||||
request: EffectAcpSchema.ReleaseTerminalRequest,
|
||||
) => Effect.Effect<EffectAcpSchema.ReleaseTerminalResponse, EffectAcpErrors.AcpRequestError>;
|
||||
/** Buffered output for embedded tool-call content; survives release. */
|
||||
readonly readOutputSnapshot: (
|
||||
sessionId: string,
|
||||
terminalId: string,
|
||||
) => AcpTerminalOutputSnapshot | undefined;
|
||||
/** Command line a terminal was created with; presentation-only lookup. */
|
||||
readonly readCommandLine: (terminalId: string) => string | undefined;
|
||||
/** Kills every terminal that is still running. Safe to call repeatedly. */
|
||||
readonly disposeAll: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface AcpClientTerminalsOptions {
|
||||
/** Devin sends shell source in command, rather than an executable plus args. */
|
||||
readonly shellCommands?: boolean | undefined;
|
||||
readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly defaultCwd: string;
|
||||
readonly environment?: NodeJS.ProcessEnv | undefined;
|
||||
readonly environmentForSession?:
|
||||
| ((sessionId: string) => NodeJS.ProcessEnv | undefined)
|
||||
| undefined;
|
||||
readonly forceKillAfter?: Duration.Input | undefined;
|
||||
}
|
||||
|
||||
function acpTerminalCommand(input: {
|
||||
readonly request: EffectAcpSchema.CreateTerminalRequest;
|
||||
readonly shellCommands?: boolean | undefined;
|
||||
readonly defaultCwd: string;
|
||||
readonly environment?: NodeJS.ProcessEnv | undefined;
|
||||
readonly forceKillAfter?: Duration.Input | undefined;
|
||||
}) {
|
||||
return ChildProcess.make(input.request.command, input.request.args ?? [], {
|
||||
cwd: input.request.cwd ?? input.defaultCwd,
|
||||
...(input.environment === undefined ? {} : { env: input.environment }),
|
||||
shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0,
|
||||
forceKillAfter: input.forceKillAfter ?? "5 seconds",
|
||||
});
|
||||
}
|
||||
|
||||
export const makeAcpClientTerminals = (
|
||||
options: AcpClientTerminalsOptions,
|
||||
): Effect.Effect<AcpClientTerminals> =>
|
||||
Effect.gen(function* () {
|
||||
const creationPermit = yield* Semaphore.make(1);
|
||||
const terminals = new Map<string, ManagedAcpTerminal>();
|
||||
let nextTerminalNumber = 1;
|
||||
|
||||
const enforceTotalOutputLimit = (): void => {
|
||||
let excess =
|
||||
Array.from(terminals.values()).reduce(
|
||||
(total, terminal) => total + terminal.buffer.bytes,
|
||||
0,
|
||||
) - MAX_RETAINED_OUTPUT_BYTES;
|
||||
if (excess <= 0) return;
|
||||
for (const terminal of terminals.values()) {
|
||||
const before = terminal.buffer.bytes;
|
||||
trimOutputStart(terminal.buffer, excess);
|
||||
excess -= before - terminal.buffer.bytes;
|
||||
if (excess <= 0) return;
|
||||
}
|
||||
};
|
||||
|
||||
const pruneReleasedSnapshots = (): void => {
|
||||
const released = Array.from(terminals.values()).filter((terminal) => terminal.released);
|
||||
let retainedBytes = released.reduce((total, terminal) => total + terminal.buffer.bytes, 0);
|
||||
while (
|
||||
released.length > MAX_RETAINED_TERMINALS ||
|
||||
retainedBytes > MAX_RETAINED_OUTPUT_BYTES
|
||||
) {
|
||||
const terminal = released.shift();
|
||||
if (terminal === undefined) break;
|
||||
retainedBytes -= terminal.buffer.bytes;
|
||||
terminals.delete(terminal.terminalId);
|
||||
}
|
||||
};
|
||||
|
||||
const requireTerminal = (
|
||||
sessionId: string,
|
||||
terminalId: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ManagedAcpTerminal, EffectAcpErrors.AcpRequestError> => {
|
||||
const terminal = terminals.get(terminalId);
|
||||
if (terminal === undefined || terminal.sessionId !== sessionId || terminal.released) {
|
||||
return Effect.fail(
|
||||
terminalRequestError(`ACP ${operation} received an unknown terminal ID '${terminalId}'.`),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(terminal);
|
||||
};
|
||||
|
||||
const create: AcpClientTerminals["create"] = (request) =>
|
||||
creationPermit.withPermit(
|
||||
Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const liveCount = Array.from(terminals.values()).filter(
|
||||
(terminal) => !terminal.released && terminal.exitStatus === undefined,
|
||||
).length;
|
||||
const unreleasedCount = Array.from(terminals.values()).filter(
|
||||
(terminal) => !terminal.released,
|
||||
).length;
|
||||
if (unreleasedCount >= MAX_UNRELEASED_TERMINALS) {
|
||||
return yield* terminalRequestError(
|
||||
`ACP terminal/create exceeded the limit of ${MAX_UNRELEASED_TERMINALS} unreleased terminals.`,
|
||||
);
|
||||
}
|
||||
if (liveCount >= MAX_LIVE_TERMINALS) {
|
||||
return yield* terminalRequestError(
|
||||
`ACP terminal/create exceeded the limit of ${MAX_LIVE_TERMINALS} concurrent terminals.`,
|
||||
);
|
||||
}
|
||||
const requestEnvironment = Object.fromEntries(
|
||||
(request.env ?? []).map((variable) => [variable.name, variable.value] as const),
|
||||
);
|
||||
const sessionEnvironment = options.environmentForSession?.(request.sessionId);
|
||||
const environment =
|
||||
options.environment === undefined &&
|
||||
sessionEnvironment === undefined &&
|
||||
(request.env?.length ?? 0) === 0
|
||||
? undefined
|
||||
: { ...options.environment, ...sessionEnvironment, ...requestEnvironment };
|
||||
// Each terminal owns a scope so the spawned process is reliably reaped:
|
||||
// closing the scope kills a still-running command and frees the handle.
|
||||
const terminalScope = yield* Scope.make();
|
||||
const child = yield* restore(
|
||||
options.spawner
|
||||
.spawn(
|
||||
acpTerminalCommand({
|
||||
request,
|
||||
shellCommands: options.shellCommands,
|
||||
defaultCwd: options.defaultCwd,
|
||||
environment,
|
||||
forceKillAfter: options.forceKillAfter,
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, terminalScope),
|
||||
Effect.mapError((cause) =>
|
||||
terminalRequestError(
|
||||
`Could not start terminal command '${request.command}'.`,
|
||||
cause,
|
||||
),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
Effect.onExit((exit) =>
|
||||
Exit.isFailure(exit) ? Scope.close(terminalScope, Exit.void) : Effect.void,
|
||||
),
|
||||
);
|
||||
|
||||
const terminalId = `t3-term-${nextTerminalNumber}`;
|
||||
nextTerminalNumber += 1;
|
||||
const record: ManagedAcpTerminal = {
|
||||
terminalId,
|
||||
sessionId: request.sessionId,
|
||||
commandLine: [request.command, ...(request.args ?? [])].join(" "),
|
||||
buffer: {
|
||||
chunks: [],
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
limit: Math.min(
|
||||
request.outputByteLimit ?? DEFAULT_OUTPUT_BYTE_LIMIT,
|
||||
MAX_OUTPUT_BYTE_LIMIT,
|
||||
),
|
||||
},
|
||||
exit: yield* Deferred.make<EffectAcpSchema.WaitForTerminalExitResponse>(),
|
||||
kill: child.kill().pipe(Effect.ignore),
|
||||
dispose: Scope.close(terminalScope, Exit.void).pipe(Effect.ignore),
|
||||
exitStatus: undefined,
|
||||
released: false,
|
||||
};
|
||||
terminals.set(terminalId, record);
|
||||
|
||||
const pump = (stream: typeof child.stdout) =>
|
||||
stream.pipe(
|
||||
Stream.runForEach((chunk) =>
|
||||
Effect.sync(() => {
|
||||
appendOutput(record.buffer, chunk);
|
||||
enforceTotalOutputLimit();
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
const stdoutPump = yield* Effect.forkDetach(pump(child.stdout));
|
||||
const stderrPump = yield* Effect.forkDetach(pump(child.stderr));
|
||||
yield* Effect.forkDetach(
|
||||
child.exitCode.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ exitCode: null, signal: terminalExitSignal(error) }),
|
||||
onSuccess: (code) => ({ exitCode: Number(code), signal: null }),
|
||||
}),
|
||||
Effect.flatMap((status) =>
|
||||
Effect.all([Fiber.join(stdoutPump), Fiber.join(stderrPump)], {
|
||||
discard: true,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
record.exitStatus = status;
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Deferred.succeed(record.exit, status)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return { terminalId };
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const output: AcpClientTerminals["output"] = (request) =>
|
||||
requireTerminal(request.sessionId, request.terminalId, "terminal/output").pipe(
|
||||
Effect.map((terminal) => ({
|
||||
output: readOutput(terminal.buffer),
|
||||
truncated: terminal.buffer.truncated,
|
||||
...(terminal.exitStatus === undefined ? {} : { exitStatus: terminal.exitStatus }),
|
||||
})),
|
||||
);
|
||||
|
||||
const waitForExit: AcpClientTerminals["waitForExit"] = (request) =>
|
||||
requireTerminal(request.sessionId, request.terminalId, "terminal/wait_for_exit").pipe(
|
||||
Effect.flatMap((terminal) => Deferred.await(terminal.exit)),
|
||||
);
|
||||
|
||||
const kill: AcpClientTerminals["kill"] = (request) =>
|
||||
requireTerminal(request.sessionId, request.terminalId, "terminal/kill").pipe(
|
||||
Effect.flatMap((terminal) => terminal.kill),
|
||||
Effect.as({}),
|
||||
);
|
||||
|
||||
const release: AcpClientTerminals["release"] = (request) =>
|
||||
Effect.uninterruptible(
|
||||
requireTerminal(request.sessionId, request.terminalId, "terminal/release").pipe(
|
||||
Effect.flatMap((terminal) =>
|
||||
Effect.sync(() => {
|
||||
terminal.released = true;
|
||||
}).pipe(
|
||||
Effect.andThen(terminal.dispose),
|
||||
Effect.andThen(Deferred.await(terminal.exit)),
|
||||
Effect.andThen(Effect.sync(pruneReleasedSnapshots)),
|
||||
),
|
||||
),
|
||||
Effect.as({}),
|
||||
),
|
||||
);
|
||||
|
||||
const readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"] = (
|
||||
sessionId,
|
||||
terminalId,
|
||||
) => {
|
||||
const terminal = terminals.get(terminalId);
|
||||
if (terminal === undefined || terminal.sessionId !== sessionId) return undefined;
|
||||
return {
|
||||
output: readOutput(terminal.buffer),
|
||||
truncated: terminal.buffer.truncated,
|
||||
exitStatus: terminal.exitStatus,
|
||||
};
|
||||
};
|
||||
|
||||
const readCommandLine: AcpClientTerminals["readCommandLine"] = (terminalId) =>
|
||||
terminals.get(terminalId)?.commandLine;
|
||||
|
||||
const disposeAll: AcpClientTerminals["disposeAll"] = Effect.uninterruptible(
|
||||
Effect.suspend(() =>
|
||||
Effect.forEach(
|
||||
Array.from(terminals.values()),
|
||||
(terminal) =>
|
||||
Effect.sync(() => {
|
||||
terminal.released = true;
|
||||
}).pipe(
|
||||
Effect.andThen(terminal.dispose),
|
||||
Effect.andThen(Deferred.await(terminal.exit)),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
).pipe(Effect.andThen(Effect.sync(pruneReleasedSnapshots))),
|
||||
),
|
||||
);
|
||||
|
||||
// Terminal failures surface to the agent as JSON-RPC errors and to the
|
||||
// user only as a failed tool item, so log them for server-side diagnosis.
|
||||
const logged =
|
||||
<Request, Response>(
|
||||
operation: string,
|
||||
handler: (request: Request) => Effect.Effect<Response, EffectAcpErrors.AcpRequestError>,
|
||||
) =>
|
||||
(request: Request) =>
|
||||
handler(request).pipe(
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("ACP client terminal operation failed", {
|
||||
operation,
|
||||
detail: error.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
create: logged("terminal/create", create),
|
||||
output: logged("terminal/output", output),
|
||||
waitForExit: logged("terminal/wait_for_exit", waitForExit),
|
||||
kill: logged("terminal/kill", kill),
|
||||
release: logged("terminal/release", release),
|
||||
readOutputSnapshot,
|
||||
readCommandLine,
|
||||
disposeAll,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Rewrites embedded `terminal` tool-call content into plain text content so
|
||||
* the provider-neutral tool-call projection can display live command output.
|
||||
*/
|
||||
export function resolveEmbeddedTerminalContent(
|
||||
notification: EffectAcpSchema.SessionNotification,
|
||||
readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"],
|
||||
): EffectAcpSchema.SessionNotification {
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
|
||||
return notification;
|
||||
}
|
||||
const content = update.content;
|
||||
if (!content || !content.some((entry) => entry.type === "terminal")) {
|
||||
return notification;
|
||||
}
|
||||
const mapped = content.map((entry): EffectAcpSchema.ToolCallContent => {
|
||||
if (entry.type !== "terminal") return entry;
|
||||
const snapshot = readOutputSnapshot(notification.sessionId, entry.terminalId);
|
||||
return {
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: snapshot === undefined ? `[terminal ${entry.terminalId}]` : snapshot.output,
|
||||
},
|
||||
};
|
||||
});
|
||||
return { ...notification, update: { ...update, content: mapped } };
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
import { ProviderDriverKind, RuntimeRequestId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpRequestResolvedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "./AcpCoreRuntimeEvents.ts";
|
||||
|
||||
describe("AcpCoreRuntimeEvents", () => {
|
||||
it("maps ACP permission requests to canonical runtime events", () => {
|
||||
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const permissionRequest = {
|
||||
kind: "execute" as const,
|
||||
detail: "cat package.json",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
status: "pending" as const,
|
||||
command: "cat package.json",
|
||||
detail: "cat package.json",
|
||||
data: { toolCallId: "tool-1", kind: "execute" },
|
||||
},
|
||||
};
|
||||
|
||||
const openedEvent = makeAcpRequestOpenedEvent({
|
||||
stamp,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
requestId: RuntimeRequestId.make("request-1"),
|
||||
permissionRequest,
|
||||
detail: "cat package.json",
|
||||
args: { command: ["cat", "package.json"] },
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
});
|
||||
expect(openedEvent).toMatchObject({
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
},
|
||||
});
|
||||
expect(openedEvent).not.toHaveProperty("payload.options");
|
||||
|
||||
expect(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
requestId: RuntimeRequestId.make("request-1"),
|
||||
permissionRequest,
|
||||
decision: "accept",
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: "exec_command_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves a native file approval without a remembered-allow choice", () => {
|
||||
const event = makeAcpRequestOpenedEvent({
|
||||
stamp: { eventId: "approval-1" as never, createdAt: "2026-09-02T00:00:00.000Z" },
|
||||
provider: ProviderDriverKind.make("antigravity"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId: TurnId.make("turn-1"),
|
||||
requestId: RuntimeRequestId.make("request-1"),
|
||||
permissionRequest: { kind: "edit" },
|
||||
approvalOptions: [
|
||||
{ decision: "accept", label: "Allow once" },
|
||||
{ decision: "decline", label: "Reject" },
|
||||
],
|
||||
detail: "Edit package.json",
|
||||
args: {},
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
});
|
||||
|
||||
expect(event.payload).toEqual({
|
||||
requestType: "file_change_approval",
|
||||
detail: "Edit package.json",
|
||||
args: {},
|
||||
options: [
|
||||
{ decision: "accept", label: "Allow once" },
|
||||
{ decision: "decline", label: "Reject" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps generic ACP permission kinds to dynamic tool approvals", () => {
|
||||
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
|
||||
|
||||
for (const kind of ["search", "fetch", "other", "unknown", "future-tool-kind"]) {
|
||||
const permissionRequest = { kind };
|
||||
const request = {
|
||||
stamp,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId: TurnId.make("turn-1"),
|
||||
requestId: RuntimeRequestId.make(`request-${kind}`),
|
||||
permissionRequest,
|
||||
};
|
||||
|
||||
expect(
|
||||
makeAcpRequestOpenedEvent({
|
||||
...request,
|
||||
detail: kind,
|
||||
args: {},
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "request.opened",
|
||||
payload: { requestType: "dynamic_tool_call" },
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpRequestResolvedEvent({
|
||||
...request,
|
||||
decision: "accept",
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "request.resolved",
|
||||
payload: { requestType: "dynamic_tool_call" },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("maps ACP core plan, tool-call, and content updates", () => {
|
||||
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
|
||||
const turnId = TurnId.make("turn-1");
|
||||
|
||||
expect(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
payload: {
|
||||
nativePlanId: "plan-1",
|
||||
kind: "items",
|
||||
plan: [{ step: "Inspect state", status: "inProgress" }],
|
||||
},
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/update_todos",
|
||||
rawPayload: { todos: [] },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "turn.plan.updated",
|
||||
raw: {
|
||||
method: "cursor/update_todos",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpToolCallEvent({
|
||||
stamp,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
title: "Terminal",
|
||||
detail: "bun run test",
|
||||
data: { command: "bun run test" },
|
||||
},
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
text: "hello",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "content.delta",
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
payload: {
|
||||
delta: "hello",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "item.started",
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "inProgress",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("maps thoughts to the reasoning stream", () => {
|
||||
expect(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: { eventId: "thought-1" as never, createdAt: "2026-09-02T00:00:00.000Z" },
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: "thread-1" as never,
|
||||
turnId: TurnId.make("turn-1"),
|
||||
streamKind: "reasoning_text",
|
||||
text: "Inspect the current implementation first.",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "reasoning_text",
|
||||
delta: "Inspect the current implementation first.",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,255 +0,0 @@
|
||||
import {
|
||||
type RuntimeEventRawSource,
|
||||
RuntimeItemId,
|
||||
type CanonicalRequestType,
|
||||
type EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderApprovalOption,
|
||||
type ProviderDriverKind,
|
||||
type ProviderRuntimeEvent,
|
||||
type RuntimeRequestId,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
type AcpPermissionRequest,
|
||||
type AcpPlanUpdate,
|
||||
type AcpToolCallState,
|
||||
canonicalItemTypeFromAcpToolKind,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
type AcpAdapterRawSource = Extract<
|
||||
RuntimeEventRawSource,
|
||||
"acp.jsonrpc" | `acp.${string}.extension`
|
||||
>;
|
||||
|
||||
interface AcpEventStamp {
|
||||
readonly eventId: EventId;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
type AcpCanonicalRequestType = Extract<
|
||||
CanonicalRequestType,
|
||||
"exec_command_approval" | "file_read_approval" | "file_change_approval" | "dynamic_tool_call"
|
||||
>;
|
||||
|
||||
function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonicalRequestType {
|
||||
switch (kind) {
|
||||
case "execute":
|
||||
return "exec_command_approval";
|
||||
case "read":
|
||||
return "file_read_approval";
|
||||
case "edit":
|
||||
case "delete":
|
||||
case "move":
|
||||
return "file_change_approval";
|
||||
default:
|
||||
return "dynamic_tool_call";
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeItemStatusFromAcpToolStatus(
|
||||
status: AcpToolCallState["status"],
|
||||
): "inProgress" | "completed" | "failed" | undefined {
|
||||
switch (status) {
|
||||
case "pending":
|
||||
case "inProgress":
|
||||
return "inProgress";
|
||||
case "completed":
|
||||
return "completed";
|
||||
case "failed":
|
||||
return "failed";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function makeAcpRequestOpenedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly permissionRequest: AcpPermissionRequest;
|
||||
readonly approvalOptions?: ReadonlyArray<ProviderApprovalOption>;
|
||||
readonly detail: string;
|
||||
readonly args: unknown;
|
||||
readonly source: AcpAdapterRawSource;
|
||||
readonly method: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "request.opened",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
requestId: input.requestId,
|
||||
payload: {
|
||||
requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),
|
||||
detail: input.detail,
|
||||
args: input.args,
|
||||
...(input.approvalOptions !== undefined ? { options: input.approvalOptions } : {}),
|
||||
},
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpRequestResolvedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly permissionRequest: AcpPermissionRequest;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "request.resolved",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
requestId: input.requestId,
|
||||
payload: {
|
||||
requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),
|
||||
decision: input.decision,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpPlanUpdatedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly payload: AcpPlanUpdate;
|
||||
readonly source: AcpAdapterRawSource;
|
||||
readonly method: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
const payload =
|
||||
input.payload.kind === "items"
|
||||
? {
|
||||
plan: input.payload.plan,
|
||||
...(input.payload.explanation == null ? {} : { explanation: input.payload.explanation }),
|
||||
}
|
||||
: input.payload.kind === "removed"
|
||||
? { plan: [] }
|
||||
: {
|
||||
plan: [
|
||||
{
|
||||
step:
|
||||
input.payload.kind === "markdown"
|
||||
? input.payload.markdown
|
||||
: input.payload.kind === "file"
|
||||
? `Plan file: ${input.payload.uri}`
|
||||
: `[Unsupported ACP plan content: ${input.payload.contentType}]`,
|
||||
status: "pending" as const,
|
||||
},
|
||||
],
|
||||
};
|
||||
return {
|
||||
type: "turn.plan.updated",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
payload,
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpToolCallEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly toolCall: AcpToolCallState;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
const runtimeStatus = runtimeItemStatusFromAcpToolStatus(input.toolCall.status);
|
||||
return {
|
||||
type:
|
||||
input.toolCall.status === "completed" || input.toolCall.status === "failed"
|
||||
? "item.completed"
|
||||
: "item.updated",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
itemId: RuntimeItemId.make(input.toolCall.toolCallId),
|
||||
payload: {
|
||||
itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind),
|
||||
...(runtimeStatus ? { status: runtimeStatus } : {}),
|
||||
...(input.toolCall.title ? { title: input.toolCall.title } : {}),
|
||||
...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),
|
||||
...(Object.keys(input.toolCall.data).length > 0 ? { data: input.toolCall.data } : {}),
|
||||
},
|
||||
raw: {
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpAssistantItemEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly itemId: string;
|
||||
readonly lifecycle: "item.started" | "item.completed";
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: input.lifecycle,
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
itemId: RuntimeItemId.make(input.itemId),
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: input.lifecycle === "item.completed" ? "completed" : "inProgress",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpContentDeltaEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly itemId?: string;
|
||||
readonly streamKind?: "assistant_text" | "reasoning_text";
|
||||
readonly text: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "content.delta",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
|
||||
payload: {
|
||||
streamKind: input.streamKind ?? "assistant_text",
|
||||
delta: input.text,
|
||||
},
|
||||
raw: {
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
|
||||
@@ -1,306 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as AcpErrors from "effect-acp/errors";
|
||||
|
||||
import type { EventNdjsonLogger } from "../EventNdjsonLogger.ts";
|
||||
import { makeAcpNativeLoggerFactory } from "./AcpNativeLogging.ts";
|
||||
|
||||
const nodeServicesIt = it.layer(NodeServices.layer);
|
||||
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
nodeServicesIt("ACP native logging", (it) => {
|
||||
it.effect("records bounded request and protocol diagnostics without raw payloads", () =>
|
||||
Effect.gen(function* () {
|
||||
const records: Array<unknown> = [];
|
||||
const nativeEventLogger: EventNdjsonLogger = {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: (event) => Effect.sync(() => void records.push(event)),
|
||||
close: () => Effect.void,
|
||||
};
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
nativeEventLogger,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
verboseProtocolLogging: true,
|
||||
});
|
||||
const secret = "secret-token-value";
|
||||
const requestLogger = logger.requestLogger;
|
||||
const protocolLogger = logger.protocolLogging?.logger;
|
||||
assert.exists(requestLogger);
|
||||
assert.exists(protocolLogger);
|
||||
if (!requestLogger || !protocolLogger) return;
|
||||
|
||||
yield* requestLogger({
|
||||
method: "session/prompt",
|
||||
payload: { prompt: secret, sessionId: secret },
|
||||
status: "failed",
|
||||
cause: Cause.fail(AcpErrors.AcpRequestError.internalError(secret, { token: secret })),
|
||||
});
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "raw",
|
||||
payload: `{"token":"${secret}"}`,
|
||||
});
|
||||
yield* protocolLogger({
|
||||
direction: "outgoing",
|
||||
stage: "decoded",
|
||||
payload: {
|
||||
_tag: "Request",
|
||||
tag: "session/prompt",
|
||||
payload: { prompt: secret },
|
||||
},
|
||||
});
|
||||
|
||||
const serialized = encodeUnknownJson(records);
|
||||
assert.notInclude(serialized, secret);
|
||||
assert.include(serialized, '"method":"session/prompt"');
|
||||
assert.include(serialized, '"errorTag":"AcpRequestError"');
|
||||
assert.include(serialized, '"reasonCount":1');
|
||||
assert.include(serialized, '"valueType":"string"');
|
||||
assert.include(serialized, '"messageTag":"Request"');
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps request diagnostics without enabling full protocol logging", () =>
|
||||
Effect.gen(function* () {
|
||||
const records: Array<unknown> = [];
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: (event) => Effect.sync(() => void records.push(event)),
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
assert.isUndefined(logger.protocolLogging);
|
||||
const requestLogger = logger.requestLogger;
|
||||
assert.exists(requestLogger);
|
||||
if (!requestLogger) return;
|
||||
yield* requestLogger({
|
||||
method: "session/prompt",
|
||||
payload: {},
|
||||
status: "started",
|
||||
});
|
||||
assert.lengthOf(records, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops transient ACP chunks before formatting verbose protocol logs", () =>
|
||||
Effect.gen(function* () {
|
||||
const records: Array<unknown> = [];
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: (event) => Effect.sync(() => void records.push(event)),
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
verboseProtocolLogging: true,
|
||||
});
|
||||
const protocolLogger = logger.protocolLogging?.logger;
|
||||
assert.exists(protocolLogger);
|
||||
if (!protocolLogger) return;
|
||||
|
||||
for (const updateType of ["agent_message_chunk", "agent_thought_chunk"] as const) {
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "raw",
|
||||
payload: `${encodeUnknownJson({
|
||||
method: "session/update",
|
||||
params: { update: { sessionUpdate: updateType } },
|
||||
})}\n`,
|
||||
});
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "decoded",
|
||||
payload: [
|
||||
{
|
||||
_tag: "Request",
|
||||
tag: "session/update",
|
||||
payload: { update: { sessionUpdate: updateType } },
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
assert.lengthOf(records, 0);
|
||||
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "decoded",
|
||||
payload: [
|
||||
{
|
||||
_tag: "Request",
|
||||
tag: "session/update",
|
||||
payload: { update: { sessionUpdate: "tool_call" } },
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.lengthOf(records, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps mixed and incomplete raw diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
const records: Array<unknown> = [];
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: (event) => Effect.sync(() => void records.push(event)),
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
verboseProtocolLogging: true,
|
||||
});
|
||||
const protocolLogger = logger.protocolLogging?.logger;
|
||||
assert.exists(protocolLogger);
|
||||
if (!protocolLogger) return;
|
||||
|
||||
const transient = encodeUnknownJson({
|
||||
method: "session/update",
|
||||
params: { update: { sessionUpdate: "agent_message_chunk" } },
|
||||
});
|
||||
const lifecycle = encodeUnknownJson({ method: "session/new", params: {} });
|
||||
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "raw",
|
||||
payload: `${transient}\n${lifecycle}\n`,
|
||||
});
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "raw",
|
||||
payload: transient,
|
||||
});
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "raw",
|
||||
payload: `${transient}\n{malformed}\n`,
|
||||
});
|
||||
|
||||
assert.lengthOf(records, 3);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("filters transient entries from mixed decoded batches", () =>
|
||||
Effect.gen(function* () {
|
||||
const records: Array<unknown> = [];
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: (event) => Effect.sync(() => void records.push(event)),
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
verboseProtocolLogging: true,
|
||||
});
|
||||
const protocolLogger = logger.protocolLogging?.logger;
|
||||
assert.exists(protocolLogger);
|
||||
if (!protocolLogger) return;
|
||||
|
||||
yield* protocolLogger({
|
||||
direction: "incoming",
|
||||
stage: "decoded",
|
||||
payload: [
|
||||
{
|
||||
_tag: "Request",
|
||||
tag: "session/update",
|
||||
payload: { update: { sessionUpdate: "agent_thought_chunk" } },
|
||||
},
|
||||
{
|
||||
_tag: "Request",
|
||||
tag: "session/new",
|
||||
payload: {},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.lengthOf(records, 1);
|
||||
assert.include(encodeUnknownJson(records), '"itemCount":1');
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs a structural tag when the native writer defects", () => {
|
||||
const messages: Array<unknown> = [];
|
||||
const logCapture = Logger.make<unknown, void>(({ message }) => {
|
||||
if (Array.isArray(message)) {
|
||||
messages.push(...message);
|
||||
} else {
|
||||
messages.push(message);
|
||||
}
|
||||
});
|
||||
const secret = "secret-writer-failure";
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: () => Effect.die(new Error(secret)),
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
const requestLogger = logger.requestLogger;
|
||||
assert.exists(requestLogger);
|
||||
if (!requestLogger) return;
|
||||
|
||||
yield* requestLogger({
|
||||
method: "session/prompt",
|
||||
payload: {},
|
||||
status: "started",
|
||||
});
|
||||
|
||||
const serialized = encodeUnknownJson(messages);
|
||||
assert.notInclude(serialized, secret);
|
||||
assert.include(serialized, '"errorTag":"Die"');
|
||||
assert.include(serialized, '"reasonCount":1');
|
||||
}).pipe(Effect.provide(Logger.layer([logCapture], { mergeWithExisting: false })));
|
||||
});
|
||||
|
||||
it.effect("preserves native writer interruption", () =>
|
||||
Effect.gen(function* () {
|
||||
const makeLogger = yield* makeAcpNativeLoggerFactory();
|
||||
const logger = makeLogger({
|
||||
nativeEventLogger: {
|
||||
filePath: "/tmp/provider-native.ndjson",
|
||||
write: () => Effect.interrupt,
|
||||
close: () => Effect.void,
|
||||
},
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
const requestLogger = logger.requestLogger;
|
||||
assert.exists(requestLogger);
|
||||
if (!requestLogger) return;
|
||||
|
||||
const exit = yield* requestLogger({
|
||||
method: "session/prompt",
|
||||
payload: {},
|
||||
status: "started",
|
||||
}).pipe(Effect.exit);
|
||||
|
||||
assert.isTrue(Exit.isFailure(exit));
|
||||
if (Exit.isFailure(exit)) {
|
||||
assert.isTrue(Cause.hasInterruptsOnly(exit.cause));
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,188 +0,0 @@
|
||||
import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
|
||||
import { causeErrorTag, errorTag } from "@t3tools/shared/observability";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import type { EventNdjsonLogger } from "../EventNdjsonLogger.ts";
|
||||
import {
|
||||
structuralProtocolMethod,
|
||||
summarizeNativeProtocolPayload,
|
||||
} from "@t3tools/provider-core/server/nativeProtocolLogging";
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
const transientProtocolUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]);
|
||||
|
||||
function structuralMethod(value: string): string {
|
||||
return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
|
||||
}
|
||||
|
||||
function summarizePayload(payload: unknown): Readonly<Record<string, unknown>> {
|
||||
if (payload === null) return { valueType: "null" };
|
||||
if (typeof payload === "string") {
|
||||
return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength };
|
||||
}
|
||||
if (payload instanceof Uint8Array) {
|
||||
return { valueType: "bytes", byteLength: payload.byteLength };
|
||||
}
|
||||
if (Array.isArray(payload)) {
|
||||
return { valueType: "array", itemCount: payload.length };
|
||||
}
|
||||
if (typeof payload !== "object") {
|
||||
return { valueType: typeof payload };
|
||||
}
|
||||
|
||||
try {
|
||||
const record = payload as Record<string, unknown>;
|
||||
return {
|
||||
valueType: "object",
|
||||
fieldCount: Object.keys(record).length,
|
||||
...(typeof record._tag === "string" ? { messageTag: errorTag(record) } : {}),
|
||||
...(typeof record.tag === "string" ? { method: structuralMethod(record.tag) } : {}),
|
||||
};
|
||||
} catch {
|
||||
return { valueType: "object" };
|
||||
}
|
||||
}
|
||||
|
||||
function formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEvent) {
|
||||
return {
|
||||
method: structuralProtocolMethod(event.method),
|
||||
status: event.status,
|
||||
request: summarizeNativeProtocolPayload(event.payload),
|
||||
...(event.result !== undefined ? { result: summarizeNativeProtocolPayload(event.result) } : {}),
|
||||
...(event.cause !== undefined
|
||||
? {
|
||||
errorTag: causeErrorTag(event.cause),
|
||||
reasonCount: event.cause.reasons.length,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function formatAcpProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent) {
|
||||
return {
|
||||
direction: event.direction,
|
||||
stage: event.stage,
|
||||
payload: summarizeNativeProtocolPayload(event.payload),
|
||||
};
|
||||
}
|
||||
|
||||
function isTransientProtocolMessage(message: unknown): boolean {
|
||||
if (typeof message !== "object" || message === null) return false;
|
||||
const method = Reflect.get(message, "tag") ?? Reflect.get(message, "method");
|
||||
if (method !== "session/update") return false;
|
||||
|
||||
const payload = Reflect.get(message, "payload") ?? Reflect.get(message, "params");
|
||||
if (typeof payload !== "object" || payload === null) return false;
|
||||
const update = Reflect.get(payload, "update");
|
||||
if (typeof update !== "object" || update === null) return false;
|
||||
const updateType = Reflect.get(update, "sessionUpdate");
|
||||
return typeof updateType === "string" && transientProtocolUpdates.has(updateType);
|
||||
}
|
||||
|
||||
function rawChunkContainsOnlyTransientMessages(payload: string): boolean {
|
||||
const lines = payload.split("\n");
|
||||
const remainder = lines.pop() ?? "";
|
||||
if (remainder.trim().length > 0) return false;
|
||||
|
||||
const messages: Array<unknown> = [];
|
||||
for (const line of lines) {
|
||||
if (line.trim().length === 0) continue;
|
||||
try {
|
||||
messages.push(JSON.parse(line));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return messages.length > 0 && messages.every(isTransientProtocolMessage);
|
||||
}
|
||||
|
||||
function filterTransientProtocolLog(
|
||||
event: EffectAcpProtocol.AcpProtocolLogEvent,
|
||||
): EffectAcpProtocol.AcpProtocolLogEvent | undefined {
|
||||
if (event.direction !== "incoming") return event;
|
||||
|
||||
if (event.stage === "raw" && typeof event.payload === "string") {
|
||||
return rawChunkContainsOnlyTransientMessages(event.payload) ? undefined : event;
|
||||
}
|
||||
|
||||
if (event.stage !== "decoded") return event;
|
||||
if (!Array.isArray(event.payload)) {
|
||||
return isTransientProtocolMessage(event.payload) ? undefined : event;
|
||||
}
|
||||
|
||||
const payload = event.payload.filter((message) => !isTransientProtocolMessage(message));
|
||||
return payload.length === 0 ? undefined : { ...event, payload };
|
||||
}
|
||||
|
||||
export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory")(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
return (input: {
|
||||
readonly nativeEventLogger: EventNdjsonLogger | undefined;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly verboseProtocolLogging?: boolean;
|
||||
}): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
|
||||
const writeNativeAcpLog = (logInput: {
|
||||
readonly kind: "request" | "protocol";
|
||||
readonly payload: unknown;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
if (!input.nativeEventLogger) return;
|
||||
const observedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* input.nativeEventLogger.write(
|
||||
{
|
||||
observedAt,
|
||||
event: {
|
||||
id: yield* crypto.randomUUIDv4,
|
||||
kind: logInput.kind,
|
||||
provider: input.provider,
|
||||
createdAt: observedAt,
|
||||
threadId: input.threadId,
|
||||
payload: logInput.payload,
|
||||
},
|
||||
},
|
||||
input.threadId,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.interrupt
|
||||
: Effect.logWarning("Failed to write native ACP event log.", {
|
||||
errorTag: causeErrorTag(cause),
|
||||
reasonCount: cause.reasons.length,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>
|
||||
writeNativeAcpLog({
|
||||
kind: "request",
|
||||
payload: formatRequestLogPayload(event),
|
||||
}),
|
||||
...(input.nativeEventLogger && input.verboseProtocolLogging
|
||||
? {
|
||||
protocolLogging: {
|
||||
logIncoming: true,
|
||||
logOutgoing: true,
|
||||
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) => {
|
||||
const filtered = filterTransientProtocolLog(event);
|
||||
return filtered
|
||||
? writeNativeAcpLog({
|
||||
kind: "protocol",
|
||||
payload: formatAcpProtocolLogPayload(filtered),
|
||||
})
|
||||
: Effect.void;
|
||||
},
|
||||
} satisfies NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["protocolLogging"]>,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
});
|
||||
@@ -16,7 +16,7 @@ import { AcpRequestError } from "effect-acp/errors";
|
||||
import * as PtyAdapter from "../../terminal/PtyAdapter.ts";
|
||||
import { makeAcpRegistryAuth } from "./AcpRegistryAuth.ts";
|
||||
import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
|
||||
import type { AcpSessionRuntime } from "./AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
|
||||
const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
|
||||
const instanceId = ProviderInstanceId.make("acp-auth-test");
|
||||
@@ -101,7 +101,7 @@ const makeHarness = (
|
||||
authMethods: [{ ...method, name: `${method.name} ${version}` }],
|
||||
};
|
||||
let elicitation:
|
||||
| Parameters<AcpSessionRuntime["Service"]["handleElicitation"]>[0]
|
||||
| Parameters<AcpSessionRuntime.AcpSessionRuntime["Service"]["handleElicitation"]>[0]
|
||||
| undefined;
|
||||
return {
|
||||
initialize: () => Effect.succeed(initialized),
|
||||
|
||||
@@ -20,7 +20,7 @@ import * as ProviderAuthFlow from "../ProviderAuthFlow.ts";
|
||||
import { normalizeAcpRegistryAuthMethods, normalizeAcpRegistryWebUrl } from "./AcpRegistryProbe.ts";
|
||||
import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
|
||||
import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
|
||||
type Runtime = Pick<
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
|
||||
@@ -12,7 +12,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import type { AcpSessionRuntimeStartResult } from "./AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import {
|
||||
acpRegistryProbeFailure,
|
||||
acpRegistryProbeResult,
|
||||
@@ -68,7 +68,7 @@ describe("ACP Registry probe", () => {
|
||||
],
|
||||
},
|
||||
modelConfigId: "model",
|
||||
} satisfies AcpSessionRuntimeStartResult);
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
|
||||
|
||||
expect(result).toEqual({
|
||||
instanceId,
|
||||
@@ -186,7 +186,7 @@ describe("ACP Registry probe", () => {
|
||||
],
|
||||
},
|
||||
modelConfigId: "model",
|
||||
} satisfies AcpSessionRuntimeStartResult);
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
|
||||
|
||||
expect(result.models).toEqual([
|
||||
{ id: "sonnet", name: "Sonnet", description: "Balanced" },
|
||||
@@ -216,7 +216,7 @@ describe("ACP Registry probe", () => {
|
||||
],
|
||||
},
|
||||
modelConfigId: "model",
|
||||
} satisfies AcpSessionRuntimeStartResult);
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
|
||||
|
||||
expect(result.models).toEqual([{ id: "valid", name: "Valid", description: null }]);
|
||||
expect(result.currentModelId).toBeNull();
|
||||
@@ -270,7 +270,7 @@ describe("ACP Registry probe", () => {
|
||||
],
|
||||
},
|
||||
modelConfigId: "model",
|
||||
} satisfies AcpSessionRuntimeStartResult);
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
|
||||
|
||||
expect(result.models).toEqual([
|
||||
{ id: codexModel, name: "GPT-6.1 Sol", description: null },
|
||||
@@ -312,7 +312,7 @@ describe("ACP Registry probe", () => {
|
||||
],
|
||||
},
|
||||
modelConfigId: "model",
|
||||
} satisfies AcpSessionRuntimeStartResult);
|
||||
} satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
|
||||
|
||||
expect(result.models).toHaveLength(256);
|
||||
expect(result.currentModelId).toBeNull();
|
||||
|
||||
@@ -25,10 +25,10 @@ import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
|
||||
import * as PtyAdapter from "../../terminal/PtyAdapter.ts";
|
||||
import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
|
||||
import { parseSessionModeState } from "./AcpRuntimeModel.ts";
|
||||
import { acpProviderOptionDescriptors } from "./AcpSessionConfig.ts";
|
||||
import { parseSessionModeState } from "@t3tools/provider-acp/server/runtimeModel";
|
||||
import { acpProviderOptionDescriptors } from "@t3tools/provider-acp/server/sessionConfig";
|
||||
import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
|
||||
const MAX_AUTH_METHODS = 32;
|
||||
const MAX_MODELS = 256;
|
||||
|
||||
@@ -43,7 +43,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
|
||||
|
||||
import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import type { AcpSpawnInput } from "./AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
|
||||
const ACP_REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
|
||||
|
||||
@@ -444,7 +444,7 @@ export function resolveAcpRegistryDistribution(input: {
|
||||
export interface ResolvedAcpRegistryAgent {
|
||||
readonly agent?: AcpRegistryAgent;
|
||||
readonly distribution: AcpRegistryDistributionKind | "local";
|
||||
readonly spawn: AcpSpawnInput;
|
||||
readonly spawn: AcpSessionRuntime.AcpSpawnInput;
|
||||
}
|
||||
|
||||
export type AcpRegistryInspection =
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,263 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { ACP_SESSION_MODE_OPTION_ID, acpProviderOptionDescriptors } from "./AcpSessionConfig.ts";
|
||||
|
||||
describe("acpProviderOptionDescriptors", () => {
|
||||
it("maps non-model select options and excludes model and collaboration categories", () => {
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: "gpt-5.6-sol",
|
||||
options: [{ value: "gpt-5.6-sol", name: "GPT-5.6-Sol" }],
|
||||
},
|
||||
{
|
||||
id: "collaboration_mode",
|
||||
name: "Collaboration mode",
|
||||
category: "collaboration_mode",
|
||||
type: "select",
|
||||
currentValue: "default",
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "plan", name: "Plan" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "reasoning_effort",
|
||||
name: "Reasoning effort",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: "medium",
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium", description: "Balanced" },
|
||||
],
|
||||
},
|
||||
],
|
||||
modeState: undefined,
|
||||
});
|
||||
|
||||
expect(descriptors).toEqual([
|
||||
{
|
||||
id: "reasoning_effort",
|
||||
label: "Reasoning effort",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium", description: "Balanced" },
|
||||
],
|
||||
currentValue: "medium",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps boolean session options", () => {
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [
|
||||
{
|
||||
id: "fast_mode",
|
||||
name: "Fast mode",
|
||||
description: "Use lower-latency inference.",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
],
|
||||
modeState: undefined,
|
||||
});
|
||||
|
||||
expect(descriptors).toEqual([
|
||||
{
|
||||
id: "fast_mode",
|
||||
label: "Fast mode",
|
||||
description: "Use lower-latency inference.",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("flattens grouped select choices and drops empty or duplicate values", () => {
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [
|
||||
{
|
||||
id: "sandbox",
|
||||
name: "Sandbox",
|
||||
type: "select",
|
||||
currentValue: "workspace",
|
||||
options: [
|
||||
{
|
||||
groupId: "standard",
|
||||
name: "Standard",
|
||||
options: [
|
||||
{ value: "workspace", name: "Workspace" },
|
||||
{ value: " ", name: "Blank" },
|
||||
],
|
||||
},
|
||||
{
|
||||
groupId: "extra",
|
||||
name: "Extra",
|
||||
options: [
|
||||
{ value: "workspace", name: "Duplicate" },
|
||||
{ value: "full", name: "Full" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
modeState: undefined,
|
||||
});
|
||||
|
||||
expect(descriptors).toEqual([
|
||||
{
|
||||
id: "sandbox",
|
||||
label: "Sandbox",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "workspace", label: "Workspace" },
|
||||
{ id: "full", label: "Full" },
|
||||
],
|
||||
currentValue: "workspace",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("synthesizes a mode descriptor for agents without a mode config option", () => {
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [],
|
||||
modeState: {
|
||||
currentModeId: "safe",
|
||||
availableModes: [
|
||||
{ id: "safe", name: "Safe" },
|
||||
{ id: "yolo", name: "YOLO", description: "No approvals" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(descriptors).toEqual([
|
||||
{
|
||||
id: ACP_SESSION_MODE_OPTION_ID,
|
||||
label: "Mode",
|
||||
description: "Session mode advertised by the ACP agent.",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "safe", label: "Safe" },
|
||||
{ id: "yolo", label: "YOLO", description: "No approvals" },
|
||||
],
|
||||
currentValue: "safe",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("suppresses the synthetic mode descriptor when modes duplicate a config option", () => {
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [
|
||||
{
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: "medium",
|
||||
options: [
|
||||
{ value: "off", name: "Thinking: off" },
|
||||
{ value: "medium", name: "Thinking: medium" },
|
||||
],
|
||||
},
|
||||
],
|
||||
modeState: {
|
||||
currentModeId: "medium",
|
||||
availableModes: [
|
||||
{ id: "off", name: "Thinking: off" },
|
||||
{ id: "medium", name: "Thinking: medium" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(descriptors.map((descriptor) => descriptor.id)).toEqual(["thinking"]);
|
||||
});
|
||||
|
||||
it("does not let an unrelated select option hide the session modes API", () => {
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [
|
||||
{
|
||||
id: "unrelated",
|
||||
name: "Unrelated",
|
||||
type: "select",
|
||||
currentValue: "safe",
|
||||
options: [
|
||||
{ value: "safe", name: "Safe" },
|
||||
{ value: "yolo", name: "YOLO" },
|
||||
],
|
||||
},
|
||||
],
|
||||
modeState: {
|
||||
currentModeId: "safe",
|
||||
availableModes: [
|
||||
{ id: "safe", name: "Safe" },
|
||||
{ id: "yolo", name: "YOLO" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(descriptors.map((descriptor) => descriptor.id)).toEqual([
|
||||
"unrelated",
|
||||
ACP_SESSION_MODE_OPTION_ID,
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves canonical opaque option values and omits values the wire would mutate", () => {
|
||||
const exactValue = "value:with:opaque-markers";
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [
|
||||
{
|
||||
id: "opaque",
|
||||
name: "Opaque",
|
||||
type: "select",
|
||||
currentValue: exactValue,
|
||||
options: [
|
||||
{ value: exactValue, name: "Exact" },
|
||||
{ value: " value with spaces ", name: "Would be trimmed" },
|
||||
{ value: "x".repeat(257), name: "Too long" },
|
||||
],
|
||||
},
|
||||
],
|
||||
modeState: undefined,
|
||||
});
|
||||
|
||||
expect(descriptors[0]).toMatchObject({
|
||||
id: "opaque",
|
||||
currentValue: exactValue,
|
||||
options: [{ id: exactValue, label: "Exact" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("suppresses the synthetic mode descriptor when a mode-category option exists", () => {
|
||||
const descriptors = acpProviderOptionDescriptors({
|
||||
configOptions: [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: "agent",
|
||||
options: [
|
||||
{ value: "read-only", name: "Read-only" },
|
||||
{ value: "agent", name: "Agent" },
|
||||
],
|
||||
},
|
||||
],
|
||||
modeState: {
|
||||
currentModeId: "agent",
|
||||
availableModes: [
|
||||
{ id: "read-only", name: "Read-only" },
|
||||
{ id: "agent", name: "Agent" },
|
||||
{ id: "agent-full-access", name: "Agent (full access)" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(descriptors.map((descriptor) => descriptor.id)).toEqual(["mode"]);
|
||||
});
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
import type { ProviderOptionChoice, ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
|
||||
import type { AcpSessionModeState } from "./AcpRuntimeModel.ts";
|
||||
|
||||
/**
|
||||
* Maps ACP session configuration and session modes onto T3's provider option
|
||||
* descriptors so the existing model-options UI can drive them.
|
||||
*
|
||||
* Model selection stays on the dedicated model picker: `category: "model"`
|
||||
* options are excluded here because they already surface as models. Session
|
||||
* modes advertised through the modes API (rather than a config option) are
|
||||
* folded into one synthetic descriptor that the ACP adapter routes to
|
||||
* `session/set_mode`.
|
||||
*/
|
||||
|
||||
/** Synthetic descriptor ID for agents that expose modes outside config options. */
|
||||
export const ACP_SESSION_MODE_OPTION_ID = "_t3/session-mode";
|
||||
|
||||
const MAX_OPTION_DESCRIPTORS = 16;
|
||||
const MAX_OPTION_CHOICES = 64;
|
||||
const MAX_TEXT_LENGTH = 256;
|
||||
const MAX_DESCRIPTION_LENGTH = 1_024;
|
||||
|
||||
const boundedText = (value: string | null | undefined, maximumLength: number): string =>
|
||||
(value ?? "").trim().slice(0, maximumLength);
|
||||
|
||||
const boundedOpaqueValue = (value: string, maximumLength: number): string | undefined =>
|
||||
value.length > 0 && value === value.trim() && value.length <= maximumLength ? value : undefined;
|
||||
|
||||
function flattenSelectChoices(
|
||||
options: EffectAcpSchema.SessionConfigSelectOptions,
|
||||
): ReadonlyArray<EffectAcpSchema.SessionConfigSelectOption> {
|
||||
return options.flatMap((candidate) => ("value" in candidate ? [candidate] : candidate.options));
|
||||
}
|
||||
|
||||
function selectChoices(
|
||||
candidates: ReadonlyArray<{
|
||||
readonly value: string;
|
||||
readonly name: string;
|
||||
readonly description?: string | null | undefined;
|
||||
}>,
|
||||
): ReadonlyArray<ProviderOptionChoice> {
|
||||
const seen = new Set<string>();
|
||||
const choices: Array<ProviderOptionChoice> = [];
|
||||
for (const candidate of candidates) {
|
||||
const id = boundedOpaqueValue(candidate.value, MAX_TEXT_LENGTH);
|
||||
if (id === undefined || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
const description = boundedText(candidate.description, MAX_DESCRIPTION_LENGTH);
|
||||
choices.push({
|
||||
id,
|
||||
label: boundedText(candidate.name, MAX_TEXT_LENGTH) || id,
|
||||
...(description ? { description } : {}),
|
||||
});
|
||||
if (choices.length === MAX_OPTION_CHOICES) break;
|
||||
}
|
||||
return choices;
|
||||
}
|
||||
|
||||
export function acpProviderOptionDescriptors(input: {
|
||||
readonly configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined;
|
||||
readonly modeState: AcpSessionModeState | undefined;
|
||||
}): ReadonlyArray<ProviderOptionDescriptor> {
|
||||
const descriptors: Array<ProviderOptionDescriptor> = [];
|
||||
const seen = new Set<string>();
|
||||
const mirroredModeChoiceSets: Array<ReadonlySet<string>> = [];
|
||||
let hasModeCategory = false;
|
||||
|
||||
for (const option of input.configOptions ?? []) {
|
||||
// "model" options surface as the model list; "collaboration_mode" options
|
||||
// are driven by T3's own plan/build interaction mode in the ACP adapter.
|
||||
if (option.category === "model" || option.category === "collaboration_mode") {
|
||||
continue;
|
||||
}
|
||||
const id = boundedOpaqueValue(option.id, MAX_TEXT_LENGTH);
|
||||
if (id === undefined || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
const description = boundedText(option.description, MAX_DESCRIPTION_LENGTH);
|
||||
const base = {
|
||||
id,
|
||||
label: boundedText(option.name, MAX_TEXT_LENGTH) || id,
|
||||
...(description ? { description } : {}),
|
||||
} as const;
|
||||
if (option.type === "boolean") {
|
||||
if (option.category === "mode") hasModeCategory = true;
|
||||
descriptors.push({
|
||||
...base,
|
||||
type: "boolean",
|
||||
currentValue: option.currentValue,
|
||||
});
|
||||
if (descriptors.length === MAX_OPTION_DESCRIPTORS) return descriptors;
|
||||
continue;
|
||||
}
|
||||
const choices = selectChoices(flattenSelectChoices(option.options));
|
||||
if (choices.length === 0) {
|
||||
seen.delete(id);
|
||||
continue;
|
||||
}
|
||||
if (option.category === "mode") hasModeCategory = true;
|
||||
if (option.category === "thought_level") {
|
||||
mirroredModeChoiceSets.push(new Set(choices.map((choice) => choice.id)));
|
||||
}
|
||||
const currentValue = option.currentValue;
|
||||
descriptors.push({
|
||||
...base,
|
||||
type: "select",
|
||||
options: choices,
|
||||
...(currentValue && choices.some((choice) => choice.id === currentValue)
|
||||
? { currentValue }
|
||||
: {}),
|
||||
});
|
||||
if (descriptors.length === MAX_OPTION_DESCRIPTORS) return descriptors;
|
||||
}
|
||||
|
||||
const modeState = input.modeState;
|
||||
if (modeState !== undefined && !hasModeCategory) {
|
||||
const choices = selectChoices(
|
||||
modeState.availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
description: mode.description,
|
||||
})),
|
||||
);
|
||||
const currentValue = modeState.currentModeId;
|
||||
// Some agents mirror one knob through both the modes API and a config
|
||||
// option (codex-acp advertises its thinking levels as modes too). Skip
|
||||
// the synthetic descriptor when an existing descriptor already exposes
|
||||
// the same choice set, so the composer shows the knob once.
|
||||
const duplicatesKnownModeDescriptor = mirroredModeChoiceSets.some(
|
||||
(choiceIds) =>
|
||||
choiceIds.size === choices.length && choices.every((choice) => choiceIds.has(choice.id)),
|
||||
);
|
||||
if (
|
||||
choices.length > 1 &&
|
||||
!duplicatesKnownModeDescriptor &&
|
||||
!seen.has(ACP_SESSION_MODE_OPTION_ID)
|
||||
) {
|
||||
descriptors.push({
|
||||
id: ACP_SESSION_MODE_OPTION_ID,
|
||||
label: "Mode",
|
||||
description: "Session mode advertised by the ACP agent.",
|
||||
type: "select",
|
||||
options: choices,
|
||||
...(currentValue && choices.some((choice) => choice.id === currentValue)
|
||||
? { currentValue }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return descriptors.slice(0, MAX_OPTION_DESCRIPTORS);
|
||||
}
|
||||
@@ -11,29 +11,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import {
|
||||
capturePosixOwnershipLedger,
|
||||
isSafeCgroupPath,
|
||||
makeLinuxCgroupController,
|
||||
makePosixProcessTreeController,
|
||||
observePosixOwnershipLedger,
|
||||
observePosixOwnershipLedgerContinuously,
|
||||
parseCgroup2Mount,
|
||||
parseCgroup2Mounts,
|
||||
parseUnifiedCgroupPath,
|
||||
posixProcessIsZombie,
|
||||
resolveLinuxCgroupTargetCommand,
|
||||
signalLinuxCgroupRootTerm,
|
||||
sweepStaleLinuxCgroupSiblings,
|
||||
terminateLinuxCgroupLease,
|
||||
terminatePosixOwnedProcessTree,
|
||||
wrapCommandForLinuxCgroup,
|
||||
type AcpOwnedPosixProcess,
|
||||
type AcpLinuxCgroupLease,
|
||||
type AcpPosixOwnershipRoot,
|
||||
type AcpPosixProcessIdentity,
|
||||
type AcpPosixProcessTreeController,
|
||||
} from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
|
||||
const threadSpawnHelperSource = NodeURL.fileURLToPath(
|
||||
new URL("../../../scripts/acp-thread-spawn-helper.c", import.meta.url),
|
||||
@@ -46,7 +24,7 @@ const identity = (
|
||||
sid: number,
|
||||
startTime = String(pid),
|
||||
state = "S",
|
||||
): AcpPosixProcessIdentity => ({
|
||||
): AcpSessionRuntime.AcpPosixProcessIdentity => ({
|
||||
executable: `/proc/${pid}/exe`,
|
||||
pgid,
|
||||
pid,
|
||||
@@ -57,16 +35,16 @@ const identity = (
|
||||
});
|
||||
|
||||
function makeController(input: {
|
||||
readonly processes: ReadonlyArray<AcpPosixProcessIdentity>;
|
||||
readonly processes: ReadonlyArray<AcpSessionRuntime.AcpPosixProcessIdentity>;
|
||||
readonly onProcess?: (
|
||||
processes: Map<number, AcpPosixProcessIdentity>,
|
||||
processes: Map<number, AcpSessionRuntime.AcpPosixProcessIdentity>,
|
||||
pid: number,
|
||||
signal: NodeJS.Signals,
|
||||
) => void;
|
||||
}) {
|
||||
const processes = new Map(input.processes.map((process) => [process.pid, process]));
|
||||
const signals: Array<string> = [];
|
||||
const controller: AcpPosixProcessTreeController = {
|
||||
const controller: AcpSessionRuntime.AcpPosixProcessTreeController = {
|
||||
childPidsOf: (pid) =>
|
||||
[...processes.values()]
|
||||
.filter((process) => process.ppid === pid)
|
||||
@@ -96,19 +74,23 @@ function processExists(pid: number): boolean {
|
||||
|
||||
describe("terminatePosixOwnedProcessTree", () => {
|
||||
it("parses unified cgroup paths and escaped cgroup2 mountinfo", () => {
|
||||
expect(parseUnifiedCgroupPath("0::/user.slice/app.scope\n")).toBe("/user.slice/app.scope");
|
||||
expect(parseUnifiedCgroupPath("0::/one\n0::/two\n")).toBeUndefined();
|
||||
expect(isSafeCgroupPath("/user.slice/app.scope")).toBe(true);
|
||||
expect(isSafeCgroupPath("/user.slice/../escape")).toBe(false);
|
||||
expect(isSafeCgroupPath("/user.slice/app.scope (deleted)")).toBe(false);
|
||||
expect(AcpSessionRuntime.parseUnifiedCgroupPath("0::/user.slice/app.scope\n")).toBe(
|
||||
"/user.slice/app.scope",
|
||||
);
|
||||
expect(AcpSessionRuntime.parseUnifiedCgroupPath("0::/one\n0::/two\n")).toBeUndefined();
|
||||
expect(AcpSessionRuntime.isSafeCgroupPath("/user.slice/app.scope")).toBe(true);
|
||||
expect(AcpSessionRuntime.isSafeCgroupPath("/user.slice/../escape")).toBe(false);
|
||||
expect(AcpSessionRuntime.isSafeCgroupPath("/user.slice/app.scope (deleted)")).toBe(false);
|
||||
expect(
|
||||
parseCgroup2Mount(
|
||||
AcpSessionRuntime.parseCgroup2Mount(
|
||||
"42 31 0:37 /user.slice /sys/fs/cgroup/user\\040mount rw - cgroup2 cgroup2 rw\n",
|
||||
),
|
||||
).toEqual({ mountPoint: "/sys/fs/cgroup/user mount", root: "/user.slice" });
|
||||
expect(parseCgroup2Mount("42 31 0:37 / /sys/fs/cgroup rw - tmpfs tmpfs rw\n")).toBeUndefined();
|
||||
expect(
|
||||
parseCgroup2Mounts(
|
||||
AcpSessionRuntime.parseCgroup2Mount("42 31 0:37 / /sys/fs/cgroup rw - tmpfs tmpfs rw\n"),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
AcpSessionRuntime.parseCgroup2Mounts(
|
||||
"41 31 0:36 /other /sys/fs/cgroup/other rw - cgroup2 cgroup2 rw\n" +
|
||||
"42 31 0:37 /user.slice /sys/fs/cgroup/user rw - cgroup2 cgroup2 rw\n",
|
||||
),
|
||||
@@ -140,7 +122,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
const unrelated = writeSibling("other-lease", "0");
|
||||
const isProcessAlive = (pid: number) => pid === process.pid || pid === liveForeignPid;
|
||||
try {
|
||||
sweepStaleLinuxCgroupSiblings(parent, {
|
||||
AcpSessionRuntime.sweepStaleLinuxCgroupSiblings(parent, {
|
||||
isProcessAlive,
|
||||
readPopulated: (path) => populatedByPath.get(path),
|
||||
remove: (path) => {
|
||||
@@ -155,7 +137,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
expect(NodeFS.existsSync(unrelated)).toBe(true);
|
||||
// Missing populated state must not remove a sibling.
|
||||
writeSibling(`t3-acp-${deadPid}-eeee`, null);
|
||||
sweepStaleLinuxCgroupSiblings(parent, {
|
||||
AcpSessionRuntime.sweepStaleLinuxCgroupSiblings(parent, {
|
||||
isProcessAlive,
|
||||
readPopulated: (path) => populatedByPath.get(path),
|
||||
remove: (path) => {
|
||||
@@ -174,7 +156,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
it.live("preserves exact argv and strips wrapper-only environment before exec", () =>
|
||||
Effect.gen(function* () {
|
||||
if ((yield* HostProcessPlatform) !== "linux") return;
|
||||
const lease = makeLinuxCgroupController().create();
|
||||
const lease = AcpSessionRuntime.makeLinuxCgroupController().create();
|
||||
if (lease === undefined) return;
|
||||
const scratchRoot = NodePath.join(process.cwd(), "tmp");
|
||||
NodeFS.mkdirSync(scratchRoot, { recursive: true });
|
||||
@@ -192,17 +174,27 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
NodeFS.symlinkSync(process.execPath, bareGrok);
|
||||
NodeFS.symlinkSync(process.execPath, NodePath.join(relativeBin, "grok"));
|
||||
NodeFS.symlinkSync(process.execPath, NodePath.join(validBin, "grok"));
|
||||
expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: scratch })).toBe(bareGrok);
|
||||
expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: "" })).toBe(bareGrok);
|
||||
expect(
|
||||
AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: scratch }),
|
||||
).toBe(bareGrok);
|
||||
expect(AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: "" })).toBe(
|
||||
bareGrok,
|
||||
);
|
||||
// Undefined PATH uses Node's default search path (/usr/bin:/bin), not cwd alone
|
||||
// (bareGrok lives only in cwd / PATH=scratch).
|
||||
expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: undefined })).toBeUndefined();
|
||||
expect(resolveLinuxCgroupTargetCommand("node", scratch, { PATH: undefined })).toBeDefined();
|
||||
expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: "relative-bin" })).toBe(
|
||||
NodePath.join(relativeBin, "grok"),
|
||||
);
|
||||
expect(
|
||||
resolveLinuxCgroupTargetCommand("grok", scratch, {
|
||||
AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: undefined }),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
AcpSessionRuntime.resolveLinuxCgroupTargetCommand("node", scratch, { PATH: undefined }),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, {
|
||||
PATH: "relative-bin",
|
||||
}),
|
||||
).toBe(NodePath.join(relativeBin, "grok"));
|
||||
expect(
|
||||
AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, {
|
||||
PATH: `directory-bin${NodePath.delimiter}valid-bin`,
|
||||
}),
|
||||
).toBe(NodePath.join(validBin, "grok"));
|
||||
@@ -214,7 +206,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
" wrapper: process.env.T3_ACP_CGROUP_WRAPPER,",
|
||||
"}));",
|
||||
].join("\n");
|
||||
const wrapped = wrapCommandForLinuxCgroup(lease, linkedNode, [
|
||||
const wrapped = AcpSessionRuntime.wrapCommandForLinuxCgroup(lease, linkedNode, [
|
||||
"-e",
|
||||
target,
|
||||
outputPath,
|
||||
@@ -236,7 +228,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
'{"args":["space value","single\'quote","double\\"quote"]}',
|
||||
);
|
||||
} finally {
|
||||
yield* terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
|
||||
yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
|
||||
NodeFS.rmSync(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
@@ -251,9 +243,11 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
const outputPath = NodePath.join(scratch, "argv output");
|
||||
NodeFS.mkdirSync(leasePath);
|
||||
NodeFS.writeFileSync(NodePath.join(leasePath, "cgroup.procs"), "");
|
||||
const relativePath = parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8"));
|
||||
const relativePath = AcpSessionRuntime.parseUnifiedCgroupPath(
|
||||
NodeFS.readFileSync("/proc/self/cgroup", "utf8"),
|
||||
);
|
||||
expect(relativePath).toBeDefined();
|
||||
const lease: AcpLinuxCgroupLease = {
|
||||
const lease: AcpSessionRuntime.AcpLinuxCgroupLease = {
|
||||
contains: () => false,
|
||||
exists: () => true,
|
||||
path: leasePath,
|
||||
@@ -264,7 +258,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
};
|
||||
const packagedExecPath = vi.spyOn(process, "execPath", "get").mockReturnValue("/bin/sh");
|
||||
try {
|
||||
const wrapped = wrapCommandForLinuxCgroup(lease, "/bin/sh", [
|
||||
const wrapped = AcpSessionRuntime.wrapCommandForLinuxCgroup(lease, "/bin/sh", [
|
||||
"-c",
|
||||
'printf "%s\\n" "$0" "$1" "$2" "$3" "${ELECTRON_RUN_AS_NODE-}" "${T3_ACP_CGROUP_WRAPPER-}" > "$4"',
|
||||
"packaged-target",
|
||||
@@ -289,7 +283,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
/^\d+\n$/,
|
||||
);
|
||||
|
||||
const mismatch = wrapCommandForLinuxCgroup(
|
||||
const mismatch = AcpSessionRuntime.wrapCommandForLinuxCgroup(
|
||||
{ ...lease, relativePath: "/not-the-current-cgroup" },
|
||||
"/bin/sh",
|
||||
["-c", 'printf executed > "$0"', outputPath],
|
||||
@@ -301,7 +295,11 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
expect(mismatchResult.status, mismatchResult.stderr).toBe(126);
|
||||
expect(NodeFS.existsSync(outputPath)).toBe(false);
|
||||
|
||||
const missingTarget = wrapCommandForLinuxCgroup(lease, "/nonexistent-t3-probe", []);
|
||||
const missingTarget = AcpSessionRuntime.wrapCommandForLinuxCgroup(
|
||||
lease,
|
||||
"/nonexistent-t3-probe",
|
||||
[],
|
||||
);
|
||||
const missingTargetResult = NodeChildProcess.spawnSync(
|
||||
missingTarget.command,
|
||||
missingTarget.args,
|
||||
@@ -319,12 +317,12 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
it.live("kills a post-TERM detached double fork without touching an unrelated sentinel", () =>
|
||||
Effect.gen(function* () {
|
||||
if ((yield* HostProcessPlatform) !== "linux") return;
|
||||
const controller = makeLinuxCgroupController();
|
||||
const controller = AcpSessionRuntime.makeLinuxCgroupController();
|
||||
const lease = controller.create();
|
||||
if (lease === undefined) return;
|
||||
expect(parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8"))).not.toBe(
|
||||
lease.relativePath,
|
||||
);
|
||||
expect(
|
||||
AcpSessionRuntime.parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8")),
|
||||
).not.toBe(lease.relativePath);
|
||||
const scratchRoot = NodePath.join(process.cwd(), "tmp");
|
||||
NodeFS.mkdirSync(scratchRoot, { recursive: true });
|
||||
const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-kill-"));
|
||||
@@ -349,7 +347,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
"});",
|
||||
"setInterval(() => {}, 1000);",
|
||||
].join("\n");
|
||||
const wrapped = wrapCommandForLinuxCgroup(lease, process.execPath, [
|
||||
const wrapped = AcpSessionRuntime.wrapCommandForLinuxCgroup(lease, process.execPath, [
|
||||
"-e",
|
||||
providerProgram,
|
||||
readyPath,
|
||||
@@ -386,7 +384,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
}
|
||||
}).pipe(Effect.timeout("2 seconds"));
|
||||
expect(processExists(detachedChildPid)).toBe(true);
|
||||
yield* terminateLinuxCgroupLease(lease);
|
||||
yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease);
|
||||
expect(processExists(sentinel.pid!)).toBe(true);
|
||||
yield* Effect.gen(function* () {
|
||||
while (processExists(detachedChildPid!)) yield* Effect.sleep("10 millis");
|
||||
@@ -397,11 +395,11 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
expect(replacement?.path).not.toBe(lease.path);
|
||||
if (replacement !== undefined) {
|
||||
NodeFS.mkdirSync(NodePath.join(replacement.path, "nested"));
|
||||
yield* terminateLinuxCgroupLease(replacement);
|
||||
yield* AcpSessionRuntime.terminateLinuxCgroupLease(replacement);
|
||||
expect(NodeFS.existsSync(replacement.path)).toBe(false);
|
||||
}
|
||||
} finally {
|
||||
yield* terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
|
||||
yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
|
||||
try {
|
||||
process.kill(-provider.pid!, "SIGKILL");
|
||||
} catch {
|
||||
@@ -430,7 +428,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
let killCalls = 0;
|
||||
let populated = false;
|
||||
let removeCalls = 0;
|
||||
const lease: AcpLinuxCgroupLease = {
|
||||
const lease: AcpSessionRuntime.AcpLinuxCgroupLease = {
|
||||
contains: () => false,
|
||||
exists: () => exists,
|
||||
path: "/test/t3-acp-repopulation",
|
||||
@@ -457,11 +455,11 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
},
|
||||
};
|
||||
|
||||
yield* terminateLinuxCgroupLease(lease);
|
||||
yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease);
|
||||
expect(killCalls).toBeGreaterThanOrEqual(3);
|
||||
expect(removeCalls).toBe(3);
|
||||
expect(exists).toBe(false);
|
||||
yield* terminateLinuxCgroupLease(lease);
|
||||
yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease);
|
||||
expect(removeCalls).toBe(3);
|
||||
}),
|
||||
);
|
||||
@@ -471,7 +469,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
const removeError = Object.assign(new Error("cgroup remains busy"), {
|
||||
code: "EBUSY",
|
||||
});
|
||||
const lease: AcpLinuxCgroupLease = {
|
||||
const lease: AcpSessionRuntime.AcpLinuxCgroupLease = {
|
||||
contains: () => false,
|
||||
exists: () => true,
|
||||
path: "/test/t3-acp-busy",
|
||||
@@ -483,7 +481,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const error = yield* Effect.flip(terminateLinuxCgroupLease(lease));
|
||||
const error = yield* Effect.flip(AcpSessionRuntime.terminateLinuxCgroupLease(lease));
|
||||
expect(error.detail).toBe("Failed to remove ACP cgroup /test/t3-acp-busy");
|
||||
expect(error.cause).toBe(removeError);
|
||||
}),
|
||||
@@ -493,13 +491,16 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
const fixture = makeController({
|
||||
processes: [server(), identity(100, process.pid, 100, 100, "owned")],
|
||||
});
|
||||
const ownedRoot: AcpOwnedPosixProcess = {
|
||||
const ownedRoot: AcpSessionRuntime.AcpOwnedPosixProcess = {
|
||||
...identity(100, process.pid, 100, 100, "owned"),
|
||||
parentExecutable: server().executable,
|
||||
parentStartTime: server().startTime,
|
||||
};
|
||||
const root: AcpPosixOwnershipRoot = { captureAttempted: true, value: ownedRoot };
|
||||
const lease: AcpLinuxCgroupLease = {
|
||||
const root: AcpSessionRuntime.AcpPosixOwnershipRoot = {
|
||||
captureAttempted: true,
|
||||
value: ownedRoot,
|
||||
};
|
||||
const lease: AcpSessionRuntime.AcpLinuxCgroupLease = {
|
||||
contains: () => true,
|
||||
exists: () => true,
|
||||
path: "/test/t3-acp-root",
|
||||
@@ -508,19 +509,19 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
populated: () => true,
|
||||
remove: () => undefined,
|
||||
};
|
||||
signalLinuxCgroupRootTerm({ controller: fixture.controller, lease, root });
|
||||
AcpSessionRuntime.signalLinuxCgroupRootTerm({ controller: fixture.controller, lease, root });
|
||||
expect(fixture.signals).toEqual(["process:100:SIGTERM"]);
|
||||
|
||||
const reused = makeController({
|
||||
processes: [server(), identity(100, process.pid, 100, 100, "reused")],
|
||||
});
|
||||
signalLinuxCgroupRootTerm({ controller: reused.controller, lease, root });
|
||||
AcpSessionRuntime.signalLinuxCgroupRootTerm({ controller: reused.controller, lease, root });
|
||||
expect(reused.signals).toEqual([]);
|
||||
|
||||
const migrated = makeController({
|
||||
processes: [server(), identity(100, process.pid, 100, 100, "owned")],
|
||||
});
|
||||
signalLinuxCgroupRootTerm({
|
||||
AcpSessionRuntime.signalLinuxCgroupRootTerm({
|
||||
controller: migrated.controller,
|
||||
lease: { ...lease, contains: () => false },
|
||||
root,
|
||||
@@ -565,9 +566,9 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
}).pipe(Effect.timeout("2 seconds"));
|
||||
const [workerTid, childPid] = published;
|
||||
expect(workerTid).not.toBe(helper.pid);
|
||||
expect(makePosixProcessTreeController("linux").childrenOf(helper.pid!)).toContainEqual(
|
||||
expect.objectContaining({ pid: childPid, ppid: helper.pid }),
|
||||
);
|
||||
expect(
|
||||
AcpSessionRuntime.makePosixProcessTreeController("linux").childrenOf(helper.pid!),
|
||||
).toContainEqual(expect.objectContaining({ pid: childPid, ppid: helper.pid }));
|
||||
} finally {
|
||||
try {
|
||||
process.kill(-helper.pid!, "SIGKILL");
|
||||
@@ -585,11 +586,11 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
const fixture = makeController({
|
||||
processes: [server(), identity(100, process.pid, 100, 100), beforeExec],
|
||||
});
|
||||
const frontier = new Map<number, AcpOwnedPosixProcess>();
|
||||
const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const childQueues = new Map<number, Array<number>>();
|
||||
const ledger = new Map<string, AcpOwnedPosixProcess>();
|
||||
const root: AcpPosixOwnershipRoot = { value: undefined };
|
||||
observePosixOwnershipLedger({
|
||||
const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
|
||||
AcpSessionRuntime.observePosixOwnershipLedger({
|
||||
childQueues,
|
||||
controller: fixture.controller,
|
||||
frontier,
|
||||
@@ -598,7 +599,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
rootPid: 100,
|
||||
});
|
||||
fixture.processes.set(110, { ...beforeExec, executable: "/usr/bin/bash" });
|
||||
observePosixOwnershipLedger({
|
||||
AcpSessionRuntime.observePosixOwnershipLedger({
|
||||
childQueues,
|
||||
controller: fixture.controller,
|
||||
frontier,
|
||||
@@ -610,7 +611,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
expect([...ledger.values()].find((process) => process.pid === 110)?.executable).toBe(
|
||||
"/usr/bin/bash",
|
||||
);
|
||||
yield* terminatePosixOwnedProcessTree({
|
||||
yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
ledger,
|
||||
@@ -623,13 +624,13 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
|
||||
it("never adopts a replacement PID after initial root capture failed", () => {
|
||||
const fixture = makeController({ processes: [server()] });
|
||||
const frontier = new Map<number, AcpOwnedPosixProcess>();
|
||||
const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const childQueues = new Map<number, Array<number>>();
|
||||
const ledger = new Map<string, AcpOwnedPosixProcess>();
|
||||
const root: AcpPosixOwnershipRoot = { value: undefined };
|
||||
const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
|
||||
const capture = () => {
|
||||
try {
|
||||
observePosixOwnershipLedger({
|
||||
AcpSessionRuntime.observePosixOwnershipLedger({
|
||||
childQueues,
|
||||
controller: fixture.controller,
|
||||
frontier,
|
||||
@@ -663,7 +664,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
const fixture = makeController({
|
||||
processes: [server(), identity(100, process.pid, 100, 100)],
|
||||
});
|
||||
const controller: AcpPosixProcessTreeController = {
|
||||
const controller: AcpSessionRuntime.AcpPosixProcessTreeController = {
|
||||
...fixture.controller,
|
||||
childPidsOf: (pid) => {
|
||||
childListReads += 1;
|
||||
@@ -678,10 +679,10 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
return fixture.controller.snapshot();
|
||||
},
|
||||
};
|
||||
const frontier = new Map<number, AcpOwnedPosixProcess>();
|
||||
const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const childQueues = new Map<number, Array<number>>();
|
||||
const ledger = new Map<string, AcpOwnedPosixProcess>();
|
||||
const root: AcpPosixOwnershipRoot = { value: undefined };
|
||||
const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
|
||||
for (let index = 0; index < 5_000; index += 1) {
|
||||
const tombstone = identity(100_000 + index, 1, 100_000 + index, 100_000 + index);
|
||||
ledger.set(`${tombstone.pid}:${tombstone.startTime}`, {
|
||||
@@ -690,7 +691,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
parentStartTime: "",
|
||||
});
|
||||
}
|
||||
observePosixOwnershipLedger({
|
||||
AcpSessionRuntime.observePosixOwnershipLedger({
|
||||
childQueues,
|
||||
controller,
|
||||
frontier,
|
||||
@@ -714,7 +715,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
) {
|
||||
childListReads = 0;
|
||||
identityCalls = 0;
|
||||
observePosixOwnershipLedger({
|
||||
AcpSessionRuntime.observePosixOwnershipLedger({
|
||||
childQueues,
|
||||
controller,
|
||||
frontier,
|
||||
@@ -732,7 +733,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
);
|
||||
expect(missing, `missing after ${passes} passes`).toEqual([]);
|
||||
expect(passes).toBeGreaterThan(2);
|
||||
yield* terminatePosixOwnedProcessTree({
|
||||
yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller,
|
||||
grace: 0,
|
||||
ledger,
|
||||
@@ -751,7 +752,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
const fixture = makeController({
|
||||
processes: [server(), identity(100, process.pid, 100, 100), identity(110, 100, 110, 110)],
|
||||
});
|
||||
const controller: AcpPosixProcessTreeController = {
|
||||
const controller: AcpSessionRuntime.AcpPosixProcessTreeController = {
|
||||
...fixture.controller,
|
||||
childPidsOf: (pid) => {
|
||||
childrenCalls += 1;
|
||||
@@ -767,16 +768,16 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
},
|
||||
};
|
||||
const scope = yield* Scope.make();
|
||||
const frontier = new Map<number, AcpOwnedPosixProcess>();
|
||||
const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const childQueues = new Map<number, Array<number>>();
|
||||
let ledgerValuesCalls = 0;
|
||||
const ledger = new (class extends Map<string, AcpOwnedPosixProcess> {
|
||||
override values(): MapIterator<AcpOwnedPosixProcess> {
|
||||
const ledger = new (class extends Map<string, AcpSessionRuntime.AcpOwnedPosixProcess> {
|
||||
override values(): MapIterator<AcpSessionRuntime.AcpOwnedPosixProcess> {
|
||||
ledgerValuesCalls += 1;
|
||||
return super.values();
|
||||
}
|
||||
})();
|
||||
const root: AcpPosixOwnershipRoot = { value: undefined };
|
||||
const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
|
||||
for (let index = 0; index < 5_000; index += 1) {
|
||||
const tombstone = identity(10_000 + index, 1, 10_000 + index, 10_000 + index);
|
||||
ledger.set(`${tombstone.pid}:${tombstone.startTime}`, {
|
||||
@@ -785,7 +786,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
parentStartTime: "",
|
||||
});
|
||||
}
|
||||
yield* observePosixOwnershipLedgerContinuously({
|
||||
yield* AcpSessionRuntime.observePosixOwnershipLedgerContinuously({
|
||||
childQueues,
|
||||
controller,
|
||||
frontier,
|
||||
@@ -831,7 +832,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
},
|
||||
});
|
||||
|
||||
yield* terminatePosixOwnedProcessTree({
|
||||
yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
rootPid: 100,
|
||||
@@ -865,7 +866,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
},
|
||||
});
|
||||
|
||||
yield* terminatePosixOwnedProcessTree({
|
||||
yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
rootPid: 100,
|
||||
@@ -893,7 +894,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
});
|
||||
|
||||
const result = yield* Effect.exit(
|
||||
terminatePosixOwnedProcessTree({
|
||||
AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
rootPid: 100,
|
||||
@@ -913,9 +914,13 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
|
||||
it.live("does not treat zombie residual entries as teardown survivors", () =>
|
||||
Effect.gen(function* () {
|
||||
expect(posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "Z" })).toBe(true);
|
||||
expect(posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "S" })).toBe(false);
|
||||
const withoutState: AcpPosixProcessIdentity = {
|
||||
expect(AcpSessionRuntime.posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "Z" })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(AcpSessionRuntime.posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "S" })).toBe(
|
||||
false,
|
||||
);
|
||||
const withoutState: AcpSessionRuntime.AcpPosixProcessIdentity = {
|
||||
executable: "/proc/1/exe",
|
||||
pgid: 1,
|
||||
pid: 1,
|
||||
@@ -923,7 +928,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
sid: 1,
|
||||
startTime: "1",
|
||||
};
|
||||
expect(posixProcessIsZombie(withoutState)).toBe(false);
|
||||
expect(AcpSessionRuntime.posixProcessIsZombie(withoutState)).toBe(false);
|
||||
|
||||
const root = identity(100, process.pid, 100, 100);
|
||||
const zombieChild = identity(110, 100, 110, 110, "110", "Z");
|
||||
@@ -936,7 +941,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
processes.set(pid, { ...current, state: "Z" });
|
||||
},
|
||||
});
|
||||
yield* terminatePosixOwnedProcessTree({
|
||||
yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
rootPid: 100,
|
||||
@@ -948,19 +953,19 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
);
|
||||
|
||||
it("admits a live child after a free PID was previously reserved by a dead entry", () => {
|
||||
const staleChild: AcpOwnedPosixProcess = {
|
||||
const staleChild: AcpSessionRuntime.AcpOwnedPosixProcess = {
|
||||
...identity(200, 100, 200, 200, "stale-child"),
|
||||
parentExecutable: `/proc/100/exe`,
|
||||
parentStartTime: "100",
|
||||
};
|
||||
const liveChild = identity(200, 100, 200, 200, "live-child");
|
||||
const root = identity(100, process.pid, 100, 100);
|
||||
const ownedRoot: AcpOwnedPosixProcess = {
|
||||
const ownedRoot: AcpSessionRuntime.AcpOwnedPosixProcess = {
|
||||
...root,
|
||||
parentExecutable: `/proc/${process.pid}/exe`,
|
||||
parentStartTime: "server",
|
||||
};
|
||||
const ledger = new Map<string, AcpOwnedPosixProcess>([
|
||||
const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>([
|
||||
[`100:${root.startTime}`, ownedRoot],
|
||||
[`200:${staleChild.startTime}`, staleChild],
|
||||
]);
|
||||
@@ -969,7 +974,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
}).controller;
|
||||
|
||||
// First capture: PID 200 is free, so the dead reservation is dropped.
|
||||
capturePosixOwnershipLedger({
|
||||
AcpSessionRuntime.capturePosixOwnershipLedger({
|
||||
controller,
|
||||
ledger,
|
||||
rootPid: 100,
|
||||
@@ -978,7 +983,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
expect([...ledger.values()].some((entry) => entry.pid === 200)).toBe(false);
|
||||
|
||||
// Second capture: a new process reuses PID 200 under the owned parent.
|
||||
capturePosixOwnershipLedger({
|
||||
AcpSessionRuntime.capturePosixOwnershipLedger({
|
||||
controller: makeController({ processes: [server(), root, liveChild] }).controller,
|
||||
ledger,
|
||||
rootPid: 100,
|
||||
@@ -990,24 +995,24 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
});
|
||||
|
||||
it("admits a live child when a stale ledger entry still occupies the reused PID", () => {
|
||||
const staleChild: AcpOwnedPosixProcess = {
|
||||
const staleChild: AcpSessionRuntime.AcpOwnedPosixProcess = {
|
||||
...identity(200, 100, 200, 200, "stale-child"),
|
||||
parentExecutable: `/proc/100/exe`,
|
||||
parentStartTime: "100",
|
||||
};
|
||||
const liveChild = identity(200, 100, 200, 200, "live-child");
|
||||
const root = identity(100, process.pid, 100, 100);
|
||||
const ownedRoot: AcpOwnedPosixProcess = {
|
||||
const ownedRoot: AcpSessionRuntime.AcpOwnedPosixProcess = {
|
||||
...root,
|
||||
parentExecutable: `/proc/${process.pid}/exe`,
|
||||
parentStartTime: "server",
|
||||
};
|
||||
const ledger = new Map<string, AcpOwnedPosixProcess>([
|
||||
const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>([
|
||||
[`100:${root.startTime}`, ownedRoot],
|
||||
[`200:${staleChild.startTime}`, staleChild],
|
||||
]);
|
||||
|
||||
capturePosixOwnershipLedger({
|
||||
AcpSessionRuntime.capturePosixOwnershipLedger({
|
||||
controller: makeController({ processes: [server(), root, liveChild] }).controller,
|
||||
ledger,
|
||||
rootPid: 100,
|
||||
@@ -1040,7 +1045,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
},
|
||||
});
|
||||
|
||||
yield* terminatePosixOwnedProcessTree({
|
||||
yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
rootPid: 100,
|
||||
@@ -1064,7 +1069,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
},
|
||||
});
|
||||
let snapshotCalls = 0;
|
||||
const controller: AcpPosixProcessTreeController = {
|
||||
const controller: AcpSessionRuntime.AcpPosixProcessTreeController = {
|
||||
...fixture.controller,
|
||||
snapshot: () => {
|
||||
snapshotCalls += 1;
|
||||
@@ -1076,7 +1081,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
};
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
terminatePosixOwnedProcessTree({
|
||||
AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller,
|
||||
discoveryPasses: 2,
|
||||
grace: 0,
|
||||
@@ -1092,10 +1097,10 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
it.live("retains the ledger across root exit and an explicit failure for finalizer retry", () =>
|
||||
Effect.gen(function* () {
|
||||
let ignoreSignals = true;
|
||||
const ledger = new Map<string, AcpOwnedPosixProcess>();
|
||||
const frontier = new Map<number, AcpOwnedPosixProcess>();
|
||||
const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
|
||||
const childQueues = new Map<number, Array<number>>();
|
||||
const root: AcpPosixOwnershipRoot = { value: undefined };
|
||||
const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
|
||||
const fixture = makeController({
|
||||
processes: [
|
||||
server(),
|
||||
@@ -1108,7 +1113,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
if (!ignoreSignals) processes.delete(pid);
|
||||
},
|
||||
});
|
||||
observePosixOwnershipLedger({
|
||||
AcpSessionRuntime.observePosixOwnershipLedger({
|
||||
childQueues,
|
||||
controller: fixture.controller,
|
||||
frontier,
|
||||
@@ -1118,7 +1123,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
});
|
||||
|
||||
const explicit = yield* Effect.exit(
|
||||
terminatePosixOwnedProcessTree({
|
||||
AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
ledger,
|
||||
@@ -1130,7 +1135,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
expect(fixture.processes.has(111)).toBe(true);
|
||||
|
||||
fixture.processes.set(112, identity(112, 110, 112, 112));
|
||||
observePosixOwnershipLedger({
|
||||
AcpSessionRuntime.observePosixOwnershipLedger({
|
||||
childQueues,
|
||||
controller: fixture.controller,
|
||||
frontier,
|
||||
@@ -1139,7 +1144,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
rootPid: 100,
|
||||
});
|
||||
ignoreSignals = false;
|
||||
yield* terminatePosixOwnedProcessTree({
|
||||
yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
|
||||
controller: fixture.controller,
|
||||
grace: 0,
|
||||
ledger,
|
||||
@@ -1153,7 +1158,7 @@ describe("terminatePosixOwnedProcessTree", () => {
|
||||
|
||||
it("fails closed where a stable POSIX identity provider is unavailable", () => {
|
||||
try {
|
||||
makePosixProcessTreeController("darwin");
|
||||
AcpSessionRuntime.makePosixProcessTreeController("darwin");
|
||||
throw new Error("Expected Darwin process ownership to fail closed");
|
||||
} catch (error) {
|
||||
expect(error).toMatchObject({
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,56 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
ACP_STDERR_TAIL_MAX_CHARS,
|
||||
appendAcpStderrTail,
|
||||
sanitizeAcpStderrExcerpt,
|
||||
} from "./AcpStderr.ts";
|
||||
|
||||
describe("AcpStderr", () => {
|
||||
it("keeps a bounded tail of stderr chunks", () => {
|
||||
const prefix = "x".repeat(ACP_STDERR_TAIL_MAX_CHARS);
|
||||
expect(appendAcpStderrTail(prefix, "abc")).toBe(`${prefix.slice(3)}abc`);
|
||||
});
|
||||
|
||||
it("redacts home paths, pairing URLs, and tokens from stderr excerpts", () => {
|
||||
const excerpt = sanitizeAcpStderrExcerpt(
|
||||
[
|
||||
"Invalid project config at /Users/ada/.cursor/cli.json",
|
||||
"Authorization: Bearer secret-token-value",
|
||||
"Visit http://localhost:5733/pair#token=ABCDEF for pairing",
|
||||
"key=sk-abcdefghijklmnopqrstuv",
|
||||
].join("\n"),
|
||||
{ HOME: "/Users/ada" },
|
||||
);
|
||||
|
||||
expect(excerpt).toContain("Invalid project config at ~/.cursor/cli.json");
|
||||
expect(excerpt).toContain("Bearer [redacted]");
|
||||
expect(excerpt).toContain("[pairing-url]");
|
||||
expect(excerpt).toContain("[redacted]");
|
||||
expect(excerpt).not.toContain("secret-token-value");
|
||||
expect(excerpt).not.toContain("ABCDEF");
|
||||
expect(excerpt).not.toContain("sk-abcdefghijklmnopqrstuv");
|
||||
});
|
||||
|
||||
it("redacts hyphenated OpenAI project keys and header credentials", () => {
|
||||
const excerpt = sanitizeAcpStderrExcerpt(
|
||||
[
|
||||
"openai=sk-proj-abcdefghijklmnopqrstuvwxyz012345",
|
||||
"svc=sk-svcacct-abcdefghijklmnopqrstuvwxyz012345",
|
||||
"anthropic=sk-ant-api03-abcdefghijklmnopqrstuvwxyz012345",
|
||||
"Authorization: Basic dXNlcjpwYXNz",
|
||||
"x-api-key: ant-api-key-value",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(excerpt).toContain("[redacted]");
|
||||
expect(excerpt).toContain("Authorization: Basic [redacted]");
|
||||
expect(excerpt).toContain("x-api-key: [redacted]");
|
||||
expect(excerpt).not.toContain("sk-proj-");
|
||||
expect(excerpt).not.toContain("sk-svcacct-");
|
||||
expect(excerpt).not.toContain("sk-ant-api03-");
|
||||
expect(excerpt).not.toContain("abcdefghijklmnopqrstuvwxyz012345");
|
||||
expect(excerpt).not.toContain("dXNlcjpwYXNz");
|
||||
expect(excerpt).not.toContain("ant-api-key-value");
|
||||
});
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off -- The excerpt sanitizer masks the home directory, which only the Node os module can resolve.
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
/** Last few KiB of ACP child stderr kept for startup / exit diagnostics. */
|
||||
export const ACP_STDERR_TAIL_MAX_CHARS = 4_096;
|
||||
|
||||
const PAIRING_URL_PATTERN = /https?:\/\/[^\s]*\/pair#[^\s]*/gi;
|
||||
const BEARER_TOKEN_PATTERN = /\bBearer\s+[A-Za-z0-9._\-+=/]+/gi;
|
||||
const BASIC_AUTH_PATTERN = /\bAuthorization:\s*Basic\s+\S+/gi;
|
||||
const API_KEY_HEADER_PATTERN = /\bx-api-key:\s*\S+/gi;
|
||||
const SECRET_TOKEN_PATTERN =
|
||||
/\b(?:sk-[A-Za-z0-9][A-Za-z0-9-]{7,}|ghp_[A-Za-z0-9]+|xox[a-zA-Z]-[A-Za-z0-9-]+)\b/g;
|
||||
|
||||
export function appendAcpStderrTail(current: string, chunk: string): string {
|
||||
const next = `${current}${chunk}`;
|
||||
return next.length <= ACP_STDERR_TAIL_MAX_CHARS ? next : next.slice(-ACP_STDERR_TAIL_MAX_CHARS);
|
||||
}
|
||||
|
||||
/** Bounded, redacted excerpt safe to put on user-facing adapter errors. */
|
||||
export function sanitizeAcpStderrExcerpt(
|
||||
text: string,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): string {
|
||||
let result = text.replaceAll("\0", "");
|
||||
const homes = [environment.HOME, environment.USERPROFILE, NodeOS.homedir()].filter(
|
||||
(value): value is string => typeof value === "string" && value.length > 1,
|
||||
);
|
||||
for (const home of new Set(homes)) {
|
||||
result = result.split(home).join("~");
|
||||
}
|
||||
result = result
|
||||
.replace(PAIRING_URL_PATTERN, "[pairing-url]")
|
||||
.replace(BEARER_TOKEN_PATTERN, "Bearer [redacted]")
|
||||
.replace(BASIC_AUTH_PATTERN, "Authorization: Basic [redacted]")
|
||||
.replace(API_KEY_HEADER_PATTERN, "x-api-key: [redacted]")
|
||||
.replace(SECRET_TOKEN_PATTERN, "[redacted]");
|
||||
return result.trim();
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
makeAntigravityStderrHandler,
|
||||
makeAntigravityStdoutTransform,
|
||||
} from "../antigravityAuthSupport.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts";
|
||||
|
||||
export interface AntigravityAcpRuntimeInput extends Omit<
|
||||
|
||||
@@ -17,7 +17,10 @@ import {
|
||||
sanitizeAntigravityToolPayload,
|
||||
selectAntigravityPermissionOptionId,
|
||||
} from "./AntigravityProtocol.ts";
|
||||
import { mergeToolCallState, parseSessionUpdateEvent } from "./AcpRuntimeModel.ts";
|
||||
import {
|
||||
mergeToolCallState,
|
||||
parseSessionUpdateEvent,
|
||||
} from "@t3tools/provider-acp/server/runtimeModel";
|
||||
|
||||
const isSessionNotification = Schema.is(AcpWireSchema.SessionNotification);
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import * as Schema from "effect/Schema";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
import * as AcpWireSchema from "effect-acp/schema-v1";
|
||||
|
||||
import type { AcpToolCallState } from "./AcpRuntimeModel.ts";
|
||||
import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
|
||||
|
||||
const TOOL_TEXT_LIMIT = 8_000;
|
||||
const TOOL_TEXT_TRUNCATED = "[Earlier output truncated]\n\n";
|
||||
|
||||
@@ -15,7 +15,7 @@ import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
|
||||
|
||||
const GROK_API_KEY_ENV = "XAI_API_KEY";
|
||||
|
||||
@@ -34,12 +34,12 @@ import {
|
||||
xAiSubagentFinishedNotice,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "./XAiAcpExtension.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import {
|
||||
type AcpToolCallState,
|
||||
mergeToolCallState,
|
||||
parseSessionUpdateEvent,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
} from "@t3tools/provider-acp/server/runtimeModel";
|
||||
|
||||
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
|
||||
|
||||
|
||||
@@ -11,8 +11,8 @@ import * as Schema from "effect/Schema";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
import type { AcpToolCallState } from "./AcpRuntimeModel.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
|
||||
|
||||
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
|
||||
export const xAiRateLimitedErrorCode = -32003;
|
||||
|
||||
@@ -17,7 +17,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
||||
import * as AcpErrors from "effect-acp/errors";
|
||||
|
||||
import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
|
||||
import type { AcpSpawnInput } from "./acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import {
|
||||
antigravityUserSkillDirectories,
|
||||
resolveAntigravityUserHome,
|
||||
@@ -440,7 +440,7 @@ export function buildAntigravityAcpSpawnInput(input: {
|
||||
readonly auth?: AntigravityAuthConfig;
|
||||
/** Per-process temp directory. Defaults to the profile's shared temp directory. */
|
||||
readonly runtimeTempDirectory?: string;
|
||||
}): AcpSpawnInput {
|
||||
}): AcpSessionRuntime.AcpSpawnInput {
|
||||
return {
|
||||
command: input.installation.executablePath,
|
||||
args: input.profile.platform === "linux" ? ["--uid="] : [],
|
||||
|
||||
@@ -20,7 +20,7 @@ import { type AcpError, AcpRequestError } from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/compat";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import type { AcpSessionRuntimeEvent } from "../provider/acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import { removeAntigravitySessionFiles } from "../provider/acp/AntigravitySessionFiles.ts";
|
||||
|
||||
import {
|
||||
@@ -121,7 +121,7 @@ const makeFixture = Effect.fn("makeAntigravityTextGenerationFixture")(function*
|
||||
|
||||
const makeRuntime: AntigravityTextGenerationOptions["makeRuntime"] = (cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const events = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
|
||||
const events = yield* Queue.unbounded<AcpSessionRuntime.AcpSessionRuntimeEvent>();
|
||||
state.workspaces.push(cwd);
|
||||
expect(yield* fs.readDirectory(cwd).pipe(Effect.orDie)).toEqual([]);
|
||||
yield* Effect.addFinalizer(() =>
|
||||
|
||||
@@ -13,7 +13,7 @@ import { type AcpError, AcpRequestError } from "effect-acp/errors";
|
||||
|
||||
import { applyAntigravityAcpModelSelection } from "../provider/acp/AntigravityAcpSupport.ts";
|
||||
import { removeAntigravitySessionFiles } from "../provider/acp/AntigravitySessionFiles.ts";
|
||||
import type { AcpSessionRuntime } from "../provider/acp/AcpSessionRuntime.ts";
|
||||
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
|
||||
import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
|
||||
|
||||
const ANTIGRAVITY_TIMEOUT_MS = 180_000;
|
||||
@@ -25,7 +25,7 @@ const decodeConfiguration = Schema.decodeEffect(Schema.fromJsonString(Configurat
|
||||
const decodeConfigurationObject = Schema.decodeUnknownEffect(Configuration);
|
||||
|
||||
type AntigravityTextRuntime = Pick<
|
||||
AcpSessionRuntime["Service"],
|
||||
AcpSessionRuntime.AcpSessionRuntime["Service"],
|
||||
| "start"
|
||||
| "setMode"
|
||||
| "getConfigOptions"
|
||||
|
||||
Reference in new issue
Block a user