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
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"name": "@t3tools/provider-acp",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./server/AcpSessionRuntime": {
|
||||
"types": "./src/server/AcpSessionRuntime.ts",
|
||||
"import": "./src/server/AcpSessionRuntime.ts"
|
||||
},
|
||||
"./server/adapter": {
|
||||
"types": "./src/server/adapter.ts",
|
||||
"import": "./src/server/adapter.ts"
|
||||
},
|
||||
"./server/clientPolicy": {
|
||||
"types": "./src/server/clientPolicy.ts",
|
||||
"import": "./src/server/clientPolicy.ts"
|
||||
},
|
||||
"./server/clientTerminals": {
|
||||
"types": "./src/server/clientTerminals.ts",
|
||||
"import": "./src/server/clientTerminals.ts"
|
||||
},
|
||||
"./server/coreRuntimeEvents": {
|
||||
"types": "./src/server/coreRuntimeEvents.ts",
|
||||
"import": "./src/server/coreRuntimeEvents.ts"
|
||||
},
|
||||
"./server/mcpOverAcpBridge": {
|
||||
"types": "./src/server/mcpOverAcpBridge.ts",
|
||||
"import": "./src/server/mcpOverAcpBridge.ts"
|
||||
},
|
||||
"./server/nativeLogging": {
|
||||
"types": "./src/server/nativeLogging.ts",
|
||||
"import": "./src/server/nativeLogging.ts"
|
||||
},
|
||||
"./server/runtimeModel": {
|
||||
"types": "./src/server/runtimeModel.ts",
|
||||
"import": "./src/server/runtimeModel.ts"
|
||||
},
|
||||
"./server/sessionConfig": {
|
||||
"types": "./src/server/sessionConfig.ts",
|
||||
"import": "./src/server/sessionConfig.ts"
|
||||
},
|
||||
"./server/stderr": {
|
||||
"types": "./src/server/stderr.ts",
|
||||
"import": "./src/server/stderr.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vp test run --config ../../vite.config.ts --dir ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/provider-core": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"diff": "8.0.3",
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"vite-plus": "catalog:"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,348 @@
|
||||
// @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 "./clientPolicy.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"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
// @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),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
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 "./clientTerminals.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]" } },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,459 @@
|
||||
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 } };
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { ProviderDriverKind, RuntimeRequestId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpRequestResolvedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "./coreRuntimeEvents.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.",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
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 "./runtimeModel.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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// 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 "./mcpOverAcpBridge.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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
// 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 "@t3tools/shared/mcpResponsePayloads";
|
||||
|
||||
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, bridgeError)))];
|
||||
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 },
|
||||
),
|
||||
),
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
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 * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
|
||||
import { makeAcpNativeLoggerFactory } from "./nativeLogging.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: ProviderEventLoggers.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));
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
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 * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
|
||||
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: ProviderEventLoggers.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"]>,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,263 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { ACP_SESSION_MODE_OPTION_ID, acpProviderOptionDescriptors } from "./sessionConfig.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"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import type { ProviderOptionChoice, ProviderOptionDescriptor } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/compat";
|
||||
|
||||
import type { AcpSessionModeState } from "./runtimeModel.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);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
ACP_STDERR_TAIL_MAX_CHARS,
|
||||
appendAcpStderrTail,
|
||||
sanitizeAcpStderrExcerpt,
|
||||
} from "./stderr.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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
// @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();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -32,6 +32,8 @@ export interface ProviderHostPaths {
|
||||
readonly stateDir: string;
|
||||
/** Scratch space for provider probes and generated helper files. */
|
||||
readonly providerStatusCacheDir: string;
|
||||
/** Where chat attachments are stored; agents that sandbox file reads must be granted it. */
|
||||
readonly attachmentsDir: string;
|
||||
}
|
||||
|
||||
/** One opaque credential blob in the server's secret store. Only the provider decodes it. */
|
||||
|
||||
@@ -109,6 +109,7 @@ function layerProviderHost(input: {
|
||||
baseDir: "/t3",
|
||||
stateDir: "/t3/userdata",
|
||||
providerStatusCacheDir: "/t3/caches",
|
||||
attachmentsDir: "/t3/userdata/attachments",
|
||||
},
|
||||
settings: input.settings ?? {
|
||||
get: Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
|
||||
@@ -42,7 +42,13 @@ export const layerTestProviderHost = (
|
||||
const settings = options.settings ?? DEFAULT_SERVER_SETTINGS;
|
||||
const credentials = new Map<string, Uint8Array>();
|
||||
return ProviderHost.ProviderHost.of({
|
||||
paths: { cwd: options.cwd ?? process.cwd(), baseDir, stateDir, providerStatusCacheDir },
|
||||
paths: {
|
||||
cwd: options.cwd ?? process.cwd(),
|
||||
baseDir,
|
||||
stateDir,
|
||||
providerStatusCacheDir,
|
||||
attachmentsDir,
|
||||
},
|
||||
settings: {
|
||||
get: Effect.succeed(settings),
|
||||
changes: Stream.empty,
|
||||
|
||||
@@ -466,6 +466,10 @@
|
||||
"./atomicWrite": {
|
||||
"types": "./src/atomicWrite.ts",
|
||||
"import": "./src/atomicWrite.ts"
|
||||
},
|
||||
"./mcpResponsePayloads": {
|
||||
"types": "./src/mcpResponsePayloads.ts",
|
||||
"import": "./src/mcpResponsePayloads.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// MCP responses carry opaque JSON-RPC that callers relay verbatim.
|
||||
// @effect-diagnostics preferSchemaOverJson:off
|
||||
/**
|
||||
* Reads the JSON-RPC payloads of a response from an MCP streamable-HTTP
|
||||
* endpoint. Used on the ACP bridge fast path, so it imports only effect core.
|
||||
*
|
||||
* @module mcpResponsePayloads
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export 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<E>(
|
||||
response: Response,
|
||||
onError: (cause: unknown) => E,
|
||||
): Stream.Stream<unknown, E> {
|
||||
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), onError).pipe(
|
||||
Stream.mapEffect((data) => Effect.try({ try: () => JSON.parse(data), catch: onError })),
|
||||
);
|
||||
}
|
||||
return Stream.unwrap(
|
||||
Effect.tryPromise({ try: () => response.text(), catch: onError }).pipe(
|
||||
Effect.flatMap((text) =>
|
||||
text.trim().length === 0
|
||||
? Effect.succeed(Stream.empty)
|
||||
: Effect.try({ try: () => JSON.parse(text) as unknown, catch: onError }).pipe(
|
||||
Effect.map((payload) => Stream.fromIterable([payload])),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user