improve sdk and use it
This commit is contained in:
1 parent
f30e603732
commit
7afe841e21
34 files changed
+1900
-3516
No files matched your search
@@ -32,6 +32,7 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
},
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Minimal NDJSON JSON-RPC "agent" for ACP client tests.
|
||||
* Reads stdin lines; writes responses/notifications to stdout.
|
||||
*/
|
||||
import * as readline from "node:readline";
|
||||
import { appendFileSync } from "node:fs";
|
||||
|
||||
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const sessionId = "mock-session-1";
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let nextRequestId = 1;
|
||||
|
||||
function configOptions() {
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
|
||||
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
description: "Request permission before making any changes",
|
||||
},
|
||||
{
|
||||
id: "architect",
|
||||
name: "Architect",
|
||||
description: "Design and plan software systems without implementation",
|
||||
},
|
||||
{
|
||||
id: "code",
|
||||
name: "Code",
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
const pendingPermissionRequests = new Map();
|
||||
|
||||
function send(obj) {
|
||||
process.stdout.write(`${JSON.stringify(obj)}\n`);
|
||||
}
|
||||
|
||||
function modeState() {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
function sendSessionUpdate(update, session = sessionId) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: session,
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
rl.on("line", (line) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(trimmed);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!msg || typeof msg !== "object") return;
|
||||
if (requestLogPath) {
|
||||
appendFileSync(requestLogPath, `${JSON.stringify(msg)}\n`, "utf8");
|
||||
}
|
||||
|
||||
const id = msg.id;
|
||||
const method = msg.method;
|
||||
|
||||
if (method === undefined && id !== undefined && pendingPermissionRequests.has(id)) {
|
||||
const pending = pendingPermissionRequests.get(id);
|
||||
pendingPermissionRequests.delete(id);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: pending.toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
pending.sessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
pending.sessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: pending.promptRequestId,
|
||||
result: { stopReason: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "initialize" && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "authenticate" && id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: { authenticated: true } });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/new" && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/load" && id !== undefined) {
|
||||
const requestedSessionId = msg.params?.sessionId ?? sessionId;
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/set_config_option" && id !== undefined) {
|
||||
const configId = msg.params?.configId;
|
||||
const value = msg.params?.value;
|
||||
if (configId === "model" && typeof value === "string") {
|
||||
currentModelId = value;
|
||||
}
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: { configOptions: configOptions() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/prompt" && id !== undefined) {
|
||||
const requestedSessionId = msg.params?.sessionId ?? sessionId;
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
const permissionRequestId = nextRequestId++;
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
pendingPermissionRequests.set(permissionRequestId, {
|
||||
promptRequestId: id,
|
||||
sessionId: requestedSessionId,
|
||||
toolCallId,
|
||||
});
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: permissionRequestId,
|
||||
method: "session/request_permission",
|
||||
params: {
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
title: "`cat server/package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist: cat server/package.json",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "plan",
|
||||
explanation: `Mock plan while in ${currentModeId}`,
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: { stopReason: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if ((method === "session/set_mode" || method === "session/mode/set") && id !== undefined) {
|
||||
const nextModeId =
|
||||
typeof msg.params?.modeId === "string"
|
||||
? msg.params.modeId
|
||||
: typeof msg.params?.mode === "string"
|
||||
? msg.params.mode
|
||||
: undefined;
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
sendSessionUpdate({
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
});
|
||||
}
|
||||
send({ jsonrpc: "2.0", id, result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "session/cancel" && id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
if (id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: { code: -32601, message: `Unhandled method: ${String(method)}` },
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,176 +1,28 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Minimal NDJSON JSON-RPC "agent" for ACP client tests.
|
||||
* Reads stdin lines; writes responses/notifications to stdout.
|
||||
*/
|
||||
import * as readline from "node:readline";
|
||||
import { appendFileSync } from "node:fs";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as EffectAcpAgent from "effect-acp/agent";
|
||||
import * as AcpError from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/schema";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "effect-acp/schema";
|
||||
|
||||
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
}
|
||||
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
logExit("SIGINT");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("exit", (code) => {
|
||||
logExit(`exit:${code}`);
|
||||
});
|
||||
|
||||
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
if (parameterizedModelPicker) {
|
||||
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentModeId,
|
||||
options: availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
...(mode.description ? { description: mode.description } : {}),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ value: "claude-opus-4-6", name: "Opus 4.6" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
switch (currentModelId) {
|
||||
case "gpt-5.4":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "none", name: "None" },
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "extra-high", name: "Extra High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "context",
|
||||
name: "Context",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: currentContext,
|
||||
options: [
|
||||
{ value: "272k", name: "272K" },
|
||||
{ value: "1m", name: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "composer-2":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "claude-opus-4-6":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
category: "model_config",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
];
|
||||
default:
|
||||
return baseOptions;
|
||||
}
|
||||
}
|
||||
let nextRequestId = 1;
|
||||
|
||||
function configOptions() {
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select" as const,
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
@@ -182,7 +34,7 @@ function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
const availableModes = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
@@ -199,179 +51,185 @@ const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
const pendingPermissionRequests = new Map();
|
||||
|
||||
function modeState(): AcpSchema.SessionModeState {
|
||||
function send(obj: unknown) {
|
||||
process.stdout.write(`${JSON.stringify(obj)}\n`);
|
||||
}
|
||||
|
||||
function modeState() {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
function sendSessionUpdate(update: unknown, session = sessionId) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: CLIENT_METHODS.session_update,
|
||||
params: {
|
||||
sessionId: session,
|
||||
update,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
yield* agent.handleInitialize((request) =>
|
||||
Effect.sync(() => {
|
||||
parameterizedModelPicker =
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
rl.on("line", (line) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(trimmed);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!msg || typeof msg !== "object") return;
|
||||
if (requestLogPath) {
|
||||
appendFileSync(requestLogPath, `${JSON.stringify(msg)}\n`, "utf8");
|
||||
}
|
||||
|
||||
const rpcMessage = msg as {
|
||||
id?: number | string;
|
||||
method?: string;
|
||||
params?: Record<string, unknown>;
|
||||
};
|
||||
const id = rpcMessage.id;
|
||||
const method = rpcMessage.method;
|
||||
|
||||
if (method === undefined && id !== undefined && pendingPermissionRequests.has(id)) {
|
||||
const pending = pendingPermissionRequests.get(id);
|
||||
pendingPermissionRequests.delete(id);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: pending.toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
pending.sessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
pending.sessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: pending.promptRequestId,
|
||||
result: { stopReason: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === AGENT_METHODS.initialize && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
if (method === AGENT_METHODS.authenticate && id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: { authenticated: true } });
|
||||
return;
|
||||
}
|
||||
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionConfigOption((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (exitOnSetConfigOption) {
|
||||
return yield* Effect.sync(() => {
|
||||
process.exit(7);
|
||||
});
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
"Mock invalid params for session/set_config_option",
|
||||
{
|
||||
method: "session/set_config_option",
|
||||
params: request,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (request.configId === "mode" && typeof request.value === "string") {
|
||||
currentModeId = request.value;
|
||||
}
|
||||
if (request.configId === "model" && typeof request.value === "string") {
|
||||
currentModelId = request.value;
|
||||
}
|
||||
if (request.configId === "reasoning" && typeof request.value === "string") {
|
||||
currentReasoning = request.value;
|
||||
}
|
||||
if (request.configId === "context" && typeof request.value === "string") {
|
||||
currentContext = request.value;
|
||||
}
|
||||
if (request.configId === "fast") {
|
||||
currentFast = request.value === true || request.value === "true";
|
||||
}
|
||||
return {
|
||||
if (method === AGENT_METHODS.session_new && id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
if (method === AGENT_METHODS.session_load && id !== undefined) {
|
||||
const requestedSessionId = rpcMessage.params?.sessionId ?? sessionId;
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
String(requestedSessionId),
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
if (method === AGENT_METHODS.session_set_config_option && id !== undefined) {
|
||||
const configId = rpcMessage.params?.configId;
|
||||
const value = rpcMessage.params?.value;
|
||||
if (configId === "model" && typeof value === "string") {
|
||||
currentModelId = value;
|
||||
}
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: { configOptions: configOptions() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "before tool" },
|
||||
if (method === AGENT_METHODS.session_prompt && id !== undefined) {
|
||||
const requestedSessionId = String(rpcMessage.params?.sessionId ?? sessionId);
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
const permissionRequestId = nextRequestId++;
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["echo", "hello"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "hello",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "after tool" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
pendingPermissionRequests.set(permissionRequestId, {
|
||||
promptRequestId: id,
|
||||
sessionId: requestedSessionId,
|
||||
toolCallId,
|
||||
});
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: permissionRequestId,
|
||||
method: CLIENT_METHODS.session_request_permission,
|
||||
params: {
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
@@ -393,198 +251,77 @@ const program = Effect.gen(function* () {
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
|
||||
const cancelled =
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "plan",
|
||||
explanation: `Mock plan while in ${currentModeId}`,
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: cancelled ? "cancelled" : "end_turn" };
|
||||
}
|
||||
|
||||
if (emitGenericToolPlaceholders) {
|
||||
const toolCallId = "tool-call-generic-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Read File",
|
||||
kind: "read",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
content: "package.json\n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
title: "Question",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Which scope?",
|
||||
options: [
|
||||
{ id: "workspace", label: "Workspace" },
|
||||
{ id: "session", label: "Session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: promptResponseText ?? "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
],
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
sendSessionUpdate(
|
||||
{
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
requestedSessionId,
|
||||
);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: { stopReason: "end_turn" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
(method === AGENT_METHODS.session_set_mode || method === "session/mode/set") &&
|
||||
id !== undefined
|
||||
) {
|
||||
const nextModeId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"modeId" in params &&
|
||||
typeof params.modeId === "string"
|
||||
? params.modeId
|
||||
: typeof params === "object" &&
|
||||
params !== null &&
|
||||
"mode" in params &&
|
||||
typeof params.mode === "string"
|
||||
? params.mode
|
||||
typeof rpcMessage.params?.modeId === "string"
|
||||
? rpcMessage.params.modeId
|
||||
: typeof rpcMessage.params?.mode === "string"
|
||||
? rpcMessage.params.mode
|
||||
: undefined;
|
||||
const requestedSessionId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"sessionId" in params &&
|
||||
typeof params.sessionId === "string"
|
||||
? params.sessionId
|
||||
: sessionId;
|
||||
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
return agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.as({}));
|
||||
sendSessionUpdate({
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
});
|
||||
}
|
||||
send({ jsonrpc: "2.0", id, result: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
return Effect.succeed({});
|
||||
});
|
||||
if (method === AGENT_METHODS.session_cancel) {
|
||||
if (id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id, result: null });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
return yield* Effect.never;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EffectAcpAgent.layerStdio(
|
||||
requestLogPath
|
||||
? {
|
||||
logIncoming: true,
|
||||
logger: (event) => {
|
||||
if (event.direction !== "incoming" || event.stage !== "raw") {
|
||||
return Effect.void;
|
||||
}
|
||||
if (typeof event.payload !== "string") {
|
||||
return Effect.void;
|
||||
}
|
||||
const payload = event.payload;
|
||||
return Effect.sync(() => {
|
||||
appendFileSync(
|
||||
requestLogPath,
|
||||
payload.endsWith("\n") ? payload : `${payload}\n`,
|
||||
"utf8",
|
||||
);
|
||||
});
|
||||
},
|
||||
}
|
||||
: {},
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
NodeRuntime.runMain(program);
|
||||
if (id !== undefined) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
error: { code: -32601, message: `Unhandled method: ${String(method)}` },
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -20,7 +20,7 @@ import * as Stream from "effect/Stream";
|
||||
import * as Reactivity from "effect/unstable/reactivity/Reactivity";
|
||||
import * as Client from "effect/unstable/sql/SqlClient";
|
||||
import type { Connection } from "effect/unstable/sql/SqlConnection";
|
||||
import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError";
|
||||
import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError";
|
||||
import * as Statement from "effect/unstable/sql/Statement";
|
||||
|
||||
const ATTR_DB_SYSTEM_NAME = "db.system.name";
|
||||
@@ -102,38 +102,73 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
return value;
|
||||
};
|
||||
|
||||
const prepareCache = yield* Cache.make({
|
||||
capacity: options.prepareCacheSize ?? 200,
|
||||
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
const prepareCache = yield* Cache.make({
|
||||
capacity: options.prepareCacheSize ?? 200,
|
||||
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
|
||||
try {
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
const runStatement = (
|
||||
statement: StatementSync,
|
||||
params: ReadonlyArray<unknown>,
|
||||
raw: boolean,
|
||||
) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
|
||||
try {
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
|
||||
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
|
||||
|
||||
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
|
||||
Effect.acquireUseRelease(
|
||||
Cache.get(prepareCache, sql),
|
||||
(statement) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(true);
|
||||
// Safe to cast to array after we've setReturnArrays(true)
|
||||
return statement.all(...(params as any)) as unknown as ReadonlyArray<
|
||||
ReadonlyArray<unknown>
|
||||
>;
|
||||
}
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ import { makeCursorAdapterLive } from "./CursorAdapter.ts";
|
||||
import { resolveCursorAcpModelId } from "./CursorProvider.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.mjs");
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const bunExe = "bun";
|
||||
|
||||
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-mock-"));
|
||||
@@ -26,7 +27,7 @@ async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
@@ -48,7 +49,7 @@ printf '%s\t' "$@" >> ${JSON.stringify(argvLogPath)}
|
||||
printf '\n' >> ${JSON.stringify(argvLogPath)}
|
||||
export T3_ACP_REQUEST_LOG_PATH=${JSON.stringify(requestLogPath)}
|
||||
${envExports}
|
||||
exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
@@ -140,13 +141,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
const planUpdate = runtimeEvents.find((event) => event.type === "turn.plan.updated");
|
||||
assert.isDefined(planUpdate);
|
||||
if (planUpdate?.type === "turn.plan.updated") {
|
||||
assert.deepStrictEqual(planUpdate.payload, {
|
||||
explanation: "Mock plan while in code",
|
||||
plan: [
|
||||
{ step: "Inspect mock ACP state", status: "completed" },
|
||||
{ step: "Implement the requested change", status: "inProgress" },
|
||||
],
|
||||
});
|
||||
assert.deepStrictEqual(planUpdate.payload.plan, [
|
||||
{ step: "Inspect mock ACP state", status: "completed" },
|
||||
{ step: "Implement the requested change", status: "inProgress" },
|
||||
]);
|
||||
}
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -772,6 +772,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
if (joined === "login status") {
|
||||
return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "about") {
|
||||
return {
|
||||
stdout: "Version: 1.0.0\nUser Email: [email protected]\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { RuntimeRequestId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";
|
||||
import {
|
||||
acpPermissionOutcome,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "./AcpAdapterSupport.ts";
|
||||
|
||||
describe("AcpAdapterSupport", () => {
|
||||
it("maps ACP approval decisions to permission outcomes", () => {
|
||||
@@ -10,18 +16,92 @@ describe("AcpAdapterSupport", () => {
|
||||
expect(acpPermissionOutcome("decline")).toBe("reject-once");
|
||||
});
|
||||
|
||||
it("maps ACP request errors to provider adapter request errors", () => {
|
||||
const error = mapAcpToAdapterError(
|
||||
"cursor",
|
||||
"thread-1" as never,
|
||||
"session/prompt",
|
||||
new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: "Invalid params",
|
||||
}),
|
||||
);
|
||||
it("builds shared ACP-backed runtime events", () => {
|
||||
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
|
||||
const turnId = TurnId.makeUnsafe("turn-1");
|
||||
|
||||
expect(error._tag).toBe("ProviderAdapterRequestError");
|
||||
expect(error.message).toContain("Invalid params");
|
||||
expect(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
requestId: RuntimeRequestId.makeUnsafe("request-1"),
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
args: { command: ["cat", "package.json"] },
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "request.opened",
|
||||
provider: "cursor",
|
||||
turnId,
|
||||
payload: {
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
payload: {
|
||||
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: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
itemType: "command_execution",
|
||||
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: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
text: "hello",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
delta: "hello",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,12 @@
|
||||
import {
|
||||
RuntimeItemId,
|
||||
type EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderKind,
|
||||
type ProviderRuntimeEvent,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type RuntimeRequestId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
@@ -11,6 +16,30 @@ import {
|
||||
ProviderAdapterSessionClosedError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
import type { AcpToolCallState } from "./AcpRuntimeModel.ts";
|
||||
|
||||
export type AcpAdapterRawSource = "acp.jsonrpc" | `acp.${string}.extension`;
|
||||
|
||||
export interface AcpEventStamp {
|
||||
readonly eventId: EventId;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
function runtimeItemStatusFromToolCallStatus(
|
||||
status: "pending" | "inProgress" | "completed" | "failed" | undefined,
|
||||
): "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 mapAcpToAdapterError(
|
||||
provider: ProviderKind,
|
||||
@@ -48,7 +77,163 @@ export function acpPermissionOutcome(decision: ProviderApprovalDecision): string
|
||||
case "accept":
|
||||
return "allow-once";
|
||||
case "decline":
|
||||
case "cancel":
|
||||
default:
|
||||
return "reject-once";
|
||||
}
|
||||
}
|
||||
|
||||
export function makeAcpRequestOpenedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly requestType:
|
||||
| "exec_command_approval"
|
||||
| "file_read_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown";
|
||||
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: input.requestType,
|
||||
detail: input.detail,
|
||||
args: input.args,
|
||||
},
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpRequestResolvedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly requestType:
|
||||
| "exec_command_approval"
|
||||
| "file_read_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown";
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "request.resolved",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
requestId: input.requestId,
|
||||
payload: {
|
||||
requestType: input.requestType,
|
||||
decision: input.decision,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpPlanUpdatedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly payload: {
|
||||
readonly explanation?: string | null;
|
||||
readonly plan: ReadonlyArray<{
|
||||
readonly step: string;
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
};
|
||||
readonly source: AcpAdapterRawSource;
|
||||
readonly method: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "turn.plan.updated",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
payload: input.payload,
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpToolCallEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly toolCall: AcpToolCallState;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
const runtimeStatus = runtimeItemStatusFromToolCallStatus(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.makeUnsafe(input.toolCall.toolCallId),
|
||||
payload: {
|
||||
itemType: input.toolCall.itemType,
|
||||
...(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 makeAcpContentDeltaEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly text: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "content.delta",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: input.text,
|
||||
},
|
||||
raw: {
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()("AcpSpawnError", {
|
||||
command: Schema.optional(Schema.String),
|
||||
args: Schema.optional(Schema.Array(Schema.String)),
|
||||
shell: Schema.optional(Schema.Boolean),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message() {
|
||||
return `Failed to spawn ACP process: ${this.cause instanceof Error ? this.cause.message : String(this.cause)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpParseError extends Schema.TaggedErrorClass<AcpParseError>()("AcpParseError", {
|
||||
line: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message() {
|
||||
return `Failed to parse ACP message: ${this.line}`;
|
||||
}
|
||||
}
|
||||
export class AcpRpcError extends Schema.TaggedErrorClass<AcpRpcError>()("AcpRpcError", {
|
||||
code: Schema.Number,
|
||||
errorMessage: Schema.optional(Schema.String),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
}) {
|
||||
override get message() {
|
||||
return `Failed to send ACP RPC message (code: ${this.code}, message: ${this.errorMessage}, data: ${JSON.stringify(this.data)})`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExitedError>()(
|
||||
"AcpProcessExitedError",
|
||||
{
|
||||
code: Schema.NullOr(Schema.Number),
|
||||
signal: Schema.NullOr(Schema.String),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `ACP process exited with code ${this.code} and signal ${this.signal}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const AcpError = Schema.Union([
|
||||
AcpSpawnError,
|
||||
AcpParseError,
|
||||
AcpRpcError,
|
||||
AcpProcessExitedError,
|
||||
]);
|
||||
|
||||
export type AcpError = typeof AcpError.Type;
|
||||
@@ -6,46 +6,42 @@ import { it } from "@effect/vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { makeAcpJsonRpcConnection } from "./AcpJsonRpcConnection.ts";
|
||||
import { makeAcpSessionRuntime } from "./AcpSessionRuntime.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.mjs");
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const bunExe = "bun";
|
||||
|
||||
describe("AcpJsonRpcConnection", () => {
|
||||
it.effect("performs initialize → session/new → session/prompt against mock agent", () =>
|
||||
describe("AcpSessionRuntime", () => {
|
||||
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: process.execPath,
|
||||
args: [mockAgentPath],
|
||||
});
|
||||
|
||||
const initResult = yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
});
|
||||
expect(initResult).toMatchObject({ protocolVersion: 1 });
|
||||
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
expect(runtime.initializeResult).toMatchObject({ protocolVersion: 1 });
|
||||
expect(runtime.sessionId).toBe("mock-session-1");
|
||||
|
||||
const newResult = yield* conn.request("session/new", {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
expect(newResult).toMatchObject({ sessionId: "mock-session-1" });
|
||||
|
||||
const promptResult = yield* conn.request("session/prompt", {
|
||||
sessionId: "mock-session-1",
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = yield* Stream.runCollect(Stream.take(conn.notifications, 1));
|
||||
expect(notes.length).toBe(1);
|
||||
expect(notes[0]?._tag).toBe("notification");
|
||||
if (notes[0]?._tag === "notification") {
|
||||
expect(notes[0].method).toBe("session/update");
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 2)));
|
||||
expect(notes).toHaveLength(2);
|
||||
expect(notes.map((note) => note._tag)).toEqual(["PlanUpdated", "ContentDelta"]);
|
||||
const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
|
||||
expect(planUpdate?._tag).toBe("PlanUpdated");
|
||||
if (planUpdate?._tag === "PlanUpdated") {
|
||||
expect(planUpdate.payload.plan).toHaveLength(2);
|
||||
}
|
||||
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,256 +0,0 @@
|
||||
import { createInterface } from "node:readline";
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
|
||||
import {
|
||||
Cause,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
Queue,
|
||||
Ref,
|
||||
Schema,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
} from "effect";
|
||||
|
||||
import {
|
||||
AcpError,
|
||||
AcpParseError,
|
||||
AcpProcessExitedError,
|
||||
AcpRpcError,
|
||||
AcpSpawnError,
|
||||
} from "./AcpErrors.ts";
|
||||
import {
|
||||
decodeAcpInboundFromJsonLine,
|
||||
type AcpInboundMessage,
|
||||
type AcpServerRequestHandler,
|
||||
type AcpSpawnInput,
|
||||
} from "./AcpTypes.ts";
|
||||
|
||||
const JSON_RPC_VERSION = "2.0";
|
||||
|
||||
function parseInboundLine(line: string): Effect.Effect<AcpInboundMessage | null, AcpParseError> {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
const lineSnippet = trimmed.slice(0, 500);
|
||||
return decodeAcpInboundFromJsonLine(trimmed).pipe(
|
||||
Effect.mapError((cause) => new AcpParseError({ line: lineSnippet, cause })),
|
||||
);
|
||||
}
|
||||
|
||||
export interface AcpJsonRpcConnection {
|
||||
readonly request: (method: string, params?: unknown) => Effect.Effect<unknown, AcpError>;
|
||||
readonly notify: (method: string, params?: unknown) => Effect.Effect<void, AcpError>;
|
||||
readonly registerHandler: (
|
||||
method: string,
|
||||
handler: AcpServerRequestHandler,
|
||||
) => Effect.Effect<void>;
|
||||
readonly notifications: Stream.Stream<AcpInboundMessage, never>;
|
||||
}
|
||||
|
||||
export function spawnAcpChildProcess(
|
||||
input: AcpSpawnInput,
|
||||
): Effect.Effect<ChildProcessWithoutNullStreams, AcpSpawnError, never> {
|
||||
const shell = process.platform === "win32";
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
const c = spawn(input.command, [...input.args], {
|
||||
cwd: input.cwd,
|
||||
env: { ...process.env, ...input.env },
|
||||
stdio: ["pipe", "pipe", "inherit"],
|
||||
shell,
|
||||
});
|
||||
if (!c.stdin || !c.stdout) {
|
||||
throw new Error("Child process missing stdio pipes.");
|
||||
}
|
||||
return c as unknown as ChildProcessWithoutNullStreams;
|
||||
},
|
||||
catch: (cause) => new AcpSpawnError({ command: input.command, args: input.args, shell, cause }),
|
||||
});
|
||||
}
|
||||
|
||||
export function disposeAcpChild(child: ChildProcessWithoutNullStreams) {
|
||||
try {
|
||||
child.stdin?.end();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
child.kill("SIGTERM");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach JSON-RPC framing to an existing child process (caller owns spawn/kill).
|
||||
*/
|
||||
export const attachAcpJsonRpcConnection = (
|
||||
child: ChildProcessWithoutNullStreams,
|
||||
): Effect.Effect<AcpJsonRpcConnection, never, never> =>
|
||||
Effect.gen(function* () {
|
||||
const writeLock = yield* Semaphore.make(1);
|
||||
const pending = yield* Ref.make(
|
||||
new Map<number | string, Deferred.Deferred<unknown, AcpError>>(),
|
||||
);
|
||||
const handlers = yield* Ref.make(new Map<string, AcpServerRequestHandler>());
|
||||
const nextId = yield* Ref.make(1);
|
||||
const notificationQueue = yield* Queue.unbounded<AcpInboundMessage>();
|
||||
|
||||
const failAllPending = (error: AcpError) =>
|
||||
Ref.get(pending).pipe(
|
||||
Effect.flatMap((map) =>
|
||||
Effect.forEach([...map.values()], (def) => Deferred.fail(def, error), {
|
||||
discard: true,
|
||||
}),
|
||||
),
|
||||
Effect.tap(() => Ref.set(pending, new Map())),
|
||||
);
|
||||
|
||||
const writeRawLine = (payload: Record<string, unknown>) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
child.stdin.write(`${JSON.stringify(payload)}\n`);
|
||||
},
|
||||
catch: (cause) =>
|
||||
new AcpSpawnError({
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const writeSerialized = (payload: Record<string, unknown>) =>
|
||||
writeLock.withPermits(1)(writeRawLine(payload));
|
||||
|
||||
const sendRequest = (method: string, params?: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
const deferred = yield* Deferred.make<unknown, AcpError>();
|
||||
yield* writeLock.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const id = yield* Ref.get(nextId);
|
||||
yield* Ref.set(nextId, id + 1);
|
||||
yield* Ref.update(pending, (map) => new Map(map).set(id, deferred));
|
||||
yield* writeRawLine({
|
||||
jsonrpc: JSON_RPC_VERSION,
|
||||
id,
|
||||
method,
|
||||
...(params !== undefined ? { params } : {}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return yield* Deferred.await(deferred);
|
||||
});
|
||||
|
||||
const sendNotify = (method: string, params?: unknown) =>
|
||||
writeSerialized({
|
||||
jsonrpc: JSON_RPC_VERSION,
|
||||
method,
|
||||
...(params !== undefined ? { params } : {}),
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const respondResult = (id: number | string, result: unknown) =>
|
||||
writeSerialized({ jsonrpc: JSON_RPC_VERSION, id, result });
|
||||
|
||||
const respondError = (id: number | string, message: string, code = -32601) =>
|
||||
writeSerialized({
|
||||
jsonrpc: JSON_RPC_VERSION,
|
||||
id,
|
||||
error: { code, message },
|
||||
});
|
||||
|
||||
const handleOneLine = (line: string): Effect.Effect<void, AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const parseExit = yield* parseInboundLine(line).pipe(Effect.exit);
|
||||
if (Exit.isFailure(parseExit)) {
|
||||
return;
|
||||
}
|
||||
if (parseExit.value === null) {
|
||||
return;
|
||||
}
|
||||
const msg = parseExit.value;
|
||||
|
||||
if (msg._tag === "response") {
|
||||
const map = yield* Ref.get(pending);
|
||||
const def = map.get(msg.id);
|
||||
if (!def) return;
|
||||
const next = new Map(map);
|
||||
next.delete(msg.id);
|
||||
yield* Ref.set(pending, next);
|
||||
if (msg.error) {
|
||||
yield* Deferred.fail(
|
||||
def,
|
||||
new AcpRpcError({
|
||||
code: msg.error.code,
|
||||
...(msg.error.data !== undefined ? { data: msg.error.data } : {}),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
yield* Deferred.succeed(def, msg.result);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg._tag === "notification") {
|
||||
yield* Queue.offer(notificationQueue, msg);
|
||||
return;
|
||||
}
|
||||
|
||||
const handlerMap = yield* Ref.get(handlers);
|
||||
const handler = handlerMap.get(msg.method);
|
||||
if (!handler) {
|
||||
yield* respondError(msg.id, `Method not found: ${msg.method}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const exit = yield* Effect.exit(handler(msg.params, msg.id));
|
||||
if (Exit.isSuccess(exit)) {
|
||||
yield* respondResult(msg.id, exit.value);
|
||||
} else {
|
||||
const left = Cause.squash(exit.cause);
|
||||
yield* respondError(msg.id, Schema.is(AcpError)(left) ? left.message : String(left));
|
||||
}
|
||||
});
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
child.once("close", (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
const err = new AcpProcessExitedError({ code, signal });
|
||||
void Effect.runPromise(
|
||||
failAllPending(err).pipe(Effect.tap(() => Queue.shutdown(notificationQueue))),
|
||||
).catch(() => {
|
||||
/* ignore shutdown races */
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
||||
yield* Effect.sync(() => {
|
||||
rl.on("line", (ln: string) => {
|
||||
void Effect.runPromise(handleOneLine(ln)).catch(() => {
|
||||
/* parse/handler errors are non-fatal for the transport */
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const registerHandler = (method: string, handler: AcpServerRequestHandler) =>
|
||||
Ref.update(handlers, (map) => new Map(map).set(method, handler));
|
||||
|
||||
return {
|
||||
request: sendRequest,
|
||||
notify: sendNotify,
|
||||
registerHandler,
|
||||
notifications: Stream.fromQueue(notificationQueue),
|
||||
} satisfies AcpJsonRpcConnection;
|
||||
});
|
||||
|
||||
/**
|
||||
* Spawns an ACP agent process and exposes NDJSON JSON-RPC over stdio.
|
||||
* Run under `Effect.scoped` so the child is disposed when the scope ends.
|
||||
*/
|
||||
export const makeAcpJsonRpcConnection = (
|
||||
input: AcpSpawnInput,
|
||||
): Effect.Effect<AcpJsonRpcConnection, AcpSpawnError, Scope.Scope> =>
|
||||
Effect.acquireRelease(spawnAcpChildProcess(input), (child) =>
|
||||
Effect.sync(() => disposeAcpChild(child)),
|
||||
).pipe(Effect.flatMap(attachAcpJsonRpcConnection));
|
||||
@@ -89,8 +89,8 @@ describe("AcpRuntimeModel", () => {
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
title: "Ran command",
|
||||
itemType: "command_execution",
|
||||
title: "Terminal",
|
||||
status: "pending",
|
||||
command: "bun run typecheck",
|
||||
detail: "bun run typecheck",
|
||||
@@ -157,31 +157,11 @@ describe("AcpRuntimeModel", () => {
|
||||
expect(mergeToolCallState(createdEvent.toolCall, updatedEvent.toolCall)).toMatchObject({
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "bun run typecheck",
|
||||
command: "bun run typecheck",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("trims padded current mode updates before emitting a mode change", () => {
|
||||
const result = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId: " code ",
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
expect(result.modeId).toBe("code");
|
||||
expect(result.events).toEqual([
|
||||
{
|
||||
_tag: "ModeChanged",
|
||||
modeId: "code",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("projects typed ACP plan and content updates", () => {
|
||||
const planResult = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
@@ -273,11 +253,11 @@ describe("AcpRuntimeModel", () => {
|
||||
});
|
||||
|
||||
expect(request).toMatchObject({
|
||||
kind: "execute",
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
itemType: "command_execution",
|
||||
status: "pending",
|
||||
command: "cat package.json",
|
||||
},
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
|
||||
import type { ToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -19,7 +18,7 @@ export interface AcpSessionModeState {
|
||||
|
||||
export interface AcpToolCallState {
|
||||
readonly toolCallId: string;
|
||||
readonly kind?: string;
|
||||
readonly itemType: ToolLifecycleItemType;
|
||||
readonly title?: string;
|
||||
readonly status?: "pending" | "inProgress" | "completed" | "failed";
|
||||
readonly command?: string;
|
||||
@@ -36,7 +35,11 @@ export interface AcpPlanUpdate {
|
||||
}
|
||||
|
||||
export interface AcpPermissionRequest {
|
||||
readonly kind: string | "unknown";
|
||||
readonly requestType:
|
||||
| "exec_command_approval"
|
||||
| "file_read_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown";
|
||||
readonly detail?: string;
|
||||
readonly toolCall?: AcpToolCallState;
|
||||
}
|
||||
@@ -46,14 +49,6 @@ export type AcpParsedSessionEvent =
|
||||
readonly _tag: "ModeChanged";
|
||||
readonly modeId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "AssistantItemStarted";
|
||||
readonly itemId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "AssistantItemCompleted";
|
||||
readonly itemId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "PlanUpdated";
|
||||
readonly payload: AcpPlanUpdate;
|
||||
@@ -66,7 +61,6 @@ export type AcpParsedSessionEvent =
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ContentDelta";
|
||||
readonly itemId?: string;
|
||||
readonly text: string;
|
||||
readonly rawPayload: unknown;
|
||||
};
|
||||
@@ -92,31 +86,6 @@ export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse):
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function findSessionConfigOption(
|
||||
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
|
||||
configId: string,
|
||||
): EffectAcpSchema.SessionConfigOption | undefined {
|
||||
if (!configOptions) {
|
||||
return undefined;
|
||||
}
|
||||
const normalizedConfigId = configId.trim();
|
||||
if (!normalizedConfigId) {
|
||||
return undefined;
|
||||
}
|
||||
return configOptions.find((option) => option.id.trim() === normalizedConfigId);
|
||||
}
|
||||
|
||||
export function collectSessionConfigOptionValues(
|
||||
configOption: EffectAcpSchema.SessionConfigOption,
|
||||
): ReadonlyArray<string> {
|
||||
if (configOption.type !== "select") {
|
||||
return [];
|
||||
}
|
||||
return configOption.options.flatMap((entry) =>
|
||||
"value" in entry ? [entry.value] : entry.options.map((option) => option.value),
|
||||
);
|
||||
}
|
||||
|
||||
export function parseSessionModeState(
|
||||
sessionResponse: AcpSessionSetupResponse,
|
||||
): AcpSessionModeState | undefined {
|
||||
@@ -237,11 +206,7 @@ function extractTextContentFromToolCallContent(
|
||||
return chunks.length > 0 ? chunks.join("\n") : undefined;
|
||||
}
|
||||
|
||||
function normalizeToolKind(kind: unknown): string | undefined {
|
||||
return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
|
||||
}
|
||||
|
||||
function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
|
||||
function toolLifecycleItemTypeFromKind(kind: unknown): ToolLifecycleItemType {
|
||||
switch (kind) {
|
||||
case "execute":
|
||||
return "command_execution";
|
||||
@@ -257,6 +222,23 @@ function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecyc
|
||||
}
|
||||
}
|
||||
|
||||
function requestTypeFromToolKind(
|
||||
kind: unknown,
|
||||
): "exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown" {
|
||||
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 "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function makeToolCallState(
|
||||
input: {
|
||||
readonly toolCallId: string;
|
||||
@@ -283,10 +265,10 @@ function makeToolCallState(
|
||||
title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
|
||||
? title
|
||||
: undefined;
|
||||
const detail = command ?? normalizedTitle ?? textContent;
|
||||
const data: Record<string, unknown> = { toolCallId };
|
||||
const kind = normalizeToolKind(input.kind);
|
||||
if (kind) {
|
||||
data.kind = kind;
|
||||
if (input.kind) {
|
||||
data.kind = input.kind;
|
||||
}
|
||||
if (command) {
|
||||
data.command = command;
|
||||
@@ -303,30 +285,14 @@ function makeToolCallState(
|
||||
if (input.locations !== undefined) {
|
||||
data.locations = input.locations;
|
||||
}
|
||||
const fallbackDetail = command ?? normalizedTitle ?? textContent;
|
||||
const hasPresentationSeed =
|
||||
title !== undefined ||
|
||||
kind !== undefined ||
|
||||
command !== undefined ||
|
||||
normalizedTitle !== undefined ||
|
||||
textContent !== undefined;
|
||||
const presentation = hasPresentationSeed
|
||||
? deriveToolActivityPresentation({
|
||||
itemType: canonicalItemTypeFromAcpToolKind(kind),
|
||||
title,
|
||||
detail: fallbackDetail,
|
||||
data,
|
||||
fallbackSummary: title ?? "Tool",
|
||||
})
|
||||
: undefined;
|
||||
const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
|
||||
return {
|
||||
toolCallId,
|
||||
...(kind ? { kind } : {}),
|
||||
...(presentation?.summary ? { title: presentation.summary } : {}),
|
||||
itemType: toolLifecycleItemTypeFromKind(input.kind),
|
||||
...(title ? { title } : {}),
|
||||
...(status ? { status } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(presentation?.detail ? { detail: presentation.detail } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
data,
|
||||
};
|
||||
}
|
||||
@@ -357,14 +323,13 @@ export function mergeToolCallState(
|
||||
next: AcpToolCallState,
|
||||
): AcpToolCallState {
|
||||
const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
|
||||
const kind = nextKind ?? previous?.kind;
|
||||
const title = next.title ?? previous?.title;
|
||||
const status = next.status ?? previous?.status;
|
||||
const command = next.command ?? previous?.command;
|
||||
const detail = next.detail ?? previous?.detail;
|
||||
return {
|
||||
toolCallId: next.toolCallId,
|
||||
...(kind ? { kind } : {}),
|
||||
itemType: nextKind !== undefined ? next.itemType : (previous?.itemType ?? next.itemType),
|
||||
...(title ? { title } : {}),
|
||||
...(status ? { status } : {}),
|
||||
...(command ? { command } : {}),
|
||||
@@ -392,14 +357,14 @@ export function parsePermissionRequest(
|
||||
},
|
||||
{ fallbackStatus: "pending" },
|
||||
);
|
||||
const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
|
||||
const requestType = requestTypeFromToolKind(params.toolCall.kind);
|
||||
const detail =
|
||||
toolCall?.command ??
|
||||
toolCall?.title ??
|
||||
toolCall?.detail ??
|
||||
(typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
|
||||
return {
|
||||
kind,
|
||||
requestType,
|
||||
...(detail ? { detail } : {}),
|
||||
...(toolCall ? { toolCall } : {}),
|
||||
};
|
||||
@@ -415,13 +380,11 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat
|
||||
|
||||
switch (upd.sessionUpdate) {
|
||||
case "current_mode_update": {
|
||||
modeId = upd.currentModeId.trim();
|
||||
if (modeId) {
|
||||
events.push({
|
||||
_tag: "ModeChanged",
|
||||
modeId,
|
||||
});
|
||||
}
|
||||
modeId = upd.currentModeId;
|
||||
events.push({
|
||||
_tag: "ModeChanged",
|
||||
modeId,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "plan": {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { Cause, Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Context, Stream } from "effect";
|
||||
import { Effect, Exit, Queue, Ref, Scope, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpClient from "effect-acp/client";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import {
|
||||
collectSessionConfigOptionValues,
|
||||
extractModelConfigId,
|
||||
findSessionConfigOption,
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
@@ -28,29 +25,15 @@ export interface AcpSessionRuntimeOptions {
|
||||
readonly spawn: AcpSpawnInput;
|
||||
readonly cwd: string;
|
||||
readonly resumeSessionId?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
readonly clientInfo: {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
readonly authMethodId: string;
|
||||
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
|
||||
readonly protocolLogging?: {
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
};
|
||||
readonly authMethodId?: string;
|
||||
readonly handlers?: Omit<EffectAcpClient.AcpClientHandlers, "sessionUpdate">;
|
||||
}
|
||||
|
||||
export interface AcpSessionRequestLogEvent {
|
||||
readonly method: string;
|
||||
readonly payload: unknown;
|
||||
readonly status: "started" | "succeeded" | "failed";
|
||||
readonly result?: unknown;
|
||||
readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeStartResult {
|
||||
export interface AcpSessionRuntime {
|
||||
readonly sessionId: string;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
readonly sessionSetupResult:
|
||||
@@ -58,28 +41,8 @@ export interface AcpSessionRuntimeStartResult {
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
readonly modelConfigId: string | undefined;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeShape {
|
||||
readonly handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"];
|
||||
readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"];
|
||||
readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"];
|
||||
readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"];
|
||||
readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"];
|
||||
readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"];
|
||||
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"];
|
||||
readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"];
|
||||
readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"];
|
||||
readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"];
|
||||
readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"];
|
||||
readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"];
|
||||
readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"];
|
||||
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
|
||||
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
|
||||
readonly prompt: (
|
||||
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
|
||||
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
|
||||
@@ -100,89 +63,22 @@ export interface AcpSessionRuntimeShape {
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly close: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
|
||||
|
||||
type AcpStartState =
|
||||
| { readonly _tag: "NotStarted" }
|
||||
| {
|
||||
readonly _tag: "Starting";
|
||||
readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
| { readonly _tag: "Started"; readonly result: AcpStartedState };
|
||||
|
||||
interface AcpAssistantSegmentState {
|
||||
readonly nextSegmentIndex: number;
|
||||
readonly activeItemId?: string;
|
||||
}
|
||||
|
||||
interface EnsureActiveAssistantSegmentResult {
|
||||
readonly itemId: string;
|
||||
readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
|
||||
}
|
||||
|
||||
export class AcpSessionRuntime extends Context.Service<AcpSessionRuntime, AcpSessionRuntimeShape>()(
|
||||
"t3/provider/acp/AcpSessionRuntime",
|
||||
) {
|
||||
static layer(
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Layer.Layer<
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
|
||||
}
|
||||
}
|
||||
|
||||
const makeAcpSessionRuntime = (
|
||||
export const makeAcpSessionRuntime = (
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntimeShape,
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const runtimeScope = yield* Scope.make("sequential");
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
|
||||
|
||||
const logRequest = (event: AcpSessionRequestLogEvent) =>
|
||||
options.requestLogger ? options.requestLogger(event) : Effect.void;
|
||||
|
||||
const runLoggedRequest = <A>(
|
||||
method: string,
|
||||
payload: unknown,
|
||||
effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
|
||||
): Effect.Effect<A, EffectAcpErrors.AcpError> =>
|
||||
logRequest({ method, payload, status: "started" }).pipe(
|
||||
Effect.flatMap(() =>
|
||||
effect.pipe(
|
||||
Effect.tap((result) =>
|
||||
logRequest({
|
||||
method,
|
||||
payload,
|
||||
status: "succeeded",
|
||||
result,
|
||||
}),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
logRequest({
|
||||
method,
|
||||
payload,
|
||||
status: "failed",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
@@ -203,379 +99,127 @@ const makeAcpSessionRuntime = (
|
||||
),
|
||||
);
|
||||
|
||||
const acpContext = yield* Layer.build(
|
||||
EffectAcpClient.layerChildProcess(child, {
|
||||
...(options.protocolLogging?.logIncoming !== undefined
|
||||
? { logIncoming: options.protocolLogging.logIncoming }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logOutgoing !== undefined
|
||||
? { logOutgoing: options.protocolLogging.logOutgoing }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
|
||||
}),
|
||||
).pipe(Effect.provideService(Scope.Scope, runtimeScope));
|
||||
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
}),
|
||||
);
|
||||
|
||||
const initializeClientCapabilities = {
|
||||
fs: {
|
||||
readTextFile: false,
|
||||
writeTextFile: false,
|
||||
...options.clientCapabilities?.fs,
|
||||
const client = yield* EffectAcpClient.fromChildProcess(child, {
|
||||
handlers: {
|
||||
...options.handlers,
|
||||
sessionUpdate: (notification) =>
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
params: notification,
|
||||
}),
|
||||
},
|
||||
terminal: options.clientCapabilities?.terminal ?? false,
|
||||
...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
|
||||
...(options.clientCapabilities?.elicitation
|
||||
? { elicitation: options.clientCapabilities.elicitation }
|
||||
: {}),
|
||||
...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
|
||||
} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
|
||||
}).pipe(Effect.provideService(Scope.Scope, runtimeScope));
|
||||
|
||||
const getStartedState = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(startStateRef);
|
||||
if (state._tag === "Started") {
|
||||
return state.result;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpTransportError({
|
||||
detail: "ACP session runtime has not been started",
|
||||
cause: new Error("ACP session runtime has not been started"),
|
||||
});
|
||||
const initializeResult = yield* client.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
},
|
||||
clientInfo: options.clientInfo,
|
||||
});
|
||||
|
||||
const validateConfigOptionValue = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
|
||||
if (!configOption) {
|
||||
return;
|
||||
}
|
||||
if (configOption.type === "boolean") {
|
||||
if (typeof value === "boolean") {
|
||||
return;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected boolean`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "boolean",
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (typeof value !== "string") {
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected string`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "string",
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
}
|
||||
const allowedValues = collectSessionConfigOptionValues(configOption);
|
||||
if (allowedValues.includes(value)) {
|
||||
return;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
allowedValues,
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
});
|
||||
yield* client.authenticate({
|
||||
methodId: options.authMethodId ?? "cursor_login",
|
||||
});
|
||||
|
||||
const updateConfigOptions = (
|
||||
response:
|
||||
| EffectAcpSchema.SetSessionConfigOptionResponse
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
|
||||
|
||||
const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
|
||||
Ref.update(modeStateRef, (current) =>
|
||||
current ? { ...current, currentModeId: modeId } : current,
|
||||
);
|
||||
|
||||
const setConfigOption = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
|
||||
validateConfigOptionValue(configId, value).pipe(
|
||||
Effect.flatMap(() => getStartedState),
|
||||
Effect.flatMap((started) =>
|
||||
Ref.get(configOptionsRef).pipe(
|
||||
Effect.flatMap((configOptions) => {
|
||||
const existing = findSessionConfigOption(configOptions, configId);
|
||||
if (existing && configOptionCurrentValueMatches(existing, value)) {
|
||||
return Effect.succeed({
|
||||
configOptions,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
|
||||
}
|
||||
const requestPayload =
|
||||
typeof value === "boolean"
|
||||
? ({
|
||||
sessionId: started.sessionId,
|
||||
configId,
|
||||
type: "boolean",
|
||||
value,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
sessionId: started.sessionId,
|
||||
configId,
|
||||
value: String(value),
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
|
||||
return runLoggedRequest(
|
||||
"session/set_config_option",
|
||||
requestPayload,
|
||||
acp.agent.setSessionConfigOption(requestPayload),
|
||||
).pipe(Effect.tap((response) => updateConfigOptions(response)));
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const startOnce = Effect.gen(function* () {
|
||||
const initializePayload = {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: initializeClientCapabilities,
|
||||
clientInfo: options.clientInfo,
|
||||
} satisfies EffectAcpSchema.InitializeRequest;
|
||||
|
||||
const initializeResult = yield* runLoggedRequest(
|
||||
"initialize",
|
||||
initializePayload,
|
||||
acp.agent.initialize(initializePayload),
|
||||
);
|
||||
|
||||
const authenticatePayload = {
|
||||
methodId: options.authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const loadPayload = {
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const resumed = yield* client
|
||||
.loadSession({
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
})
|
||||
.pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
const created = yield* client.createSession({
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
});
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
|
||||
|
||||
const nextState = {
|
||||
sessionId,
|
||||
initializeResult,
|
||||
sessionSetupResult,
|
||||
modelConfigId: extractModelConfigId(sessionSetupResult),
|
||||
} satisfies AcpStartedState;
|
||||
return nextState;
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
const deferred = yield* Deferred.make<
|
||||
AcpSessionRuntimeStartResult,
|
||||
EffectAcpErrors.AcpError
|
||||
>();
|
||||
const effect = yield* Ref.modify(startStateRef, (state) => {
|
||||
switch (state._tag) {
|
||||
case "Started":
|
||||
return [Effect.succeed(state.result), state] as const;
|
||||
case "Starting":
|
||||
return [Deferred.await(state.deferred), state] as const;
|
||||
case "NotStarted":
|
||||
return [
|
||||
startOnce.pipe(
|
||||
Effect.tap((result) =>
|
||||
Ref.set(startStateRef, { _tag: "Started", result }).pipe(
|
||||
Effect.andThen(Deferred.succeed(deferred, result)),
|
||||
),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
Deferred.failCause(deferred, cause).pipe(
|
||||
Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ _tag: "Starting", deferred } satisfies AcpStartState,
|
||||
] as const;
|
||||
}
|
||||
} else {
|
||||
const created = yield* client.createSession({
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
});
|
||||
return yield* effect;
|
||||
});
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
|
||||
const close = Scope.close(runtimeScope, Exit.void).pipe(Effect.asVoid);
|
||||
|
||||
return {
|
||||
handleRequestPermission: acp.handleRequestPermission,
|
||||
handleElicitation: acp.handleElicitation,
|
||||
handleReadTextFile: acp.handleReadTextFile,
|
||||
handleWriteTextFile: acp.handleWriteTextFile,
|
||||
handleCreateTerminal: acp.handleCreateTerminal,
|
||||
handleTerminalOutput: acp.handleTerminalOutput,
|
||||
handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
|
||||
handleTerminalKill: acp.handleTerminalKill,
|
||||
handleTerminalRelease: acp.handleTerminalRelease,
|
||||
handleSessionUpdate: acp.handleSessionUpdate,
|
||||
handleElicitationComplete: acp.handleElicitationComplete,
|
||||
handleUnknownExtRequest: acp.handleUnknownExtRequest,
|
||||
handleUnknownExtNotification: acp.handleUnknownExtNotification,
|
||||
handleExtRequest: acp.handleExtRequest,
|
||||
handleExtNotification: acp.handleExtNotification,
|
||||
start: () => start,
|
||||
getEvents: () => Stream.fromQueue(eventQueue),
|
||||
sessionId,
|
||||
initializeResult,
|
||||
sessionSetupResult,
|
||||
modelConfigId: extractModelConfigId(sessionSetupResult),
|
||||
events: Stream.fromQueue(eventQueue),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
getConfigOptions: Ref.get(configOptionsRef),
|
||||
prompt: (payload) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
...payload,
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
return closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
),
|
||||
client.prompt({
|
||||
sessionId,
|
||||
...payload,
|
||||
}),
|
||||
cancel: client.cancel({ sessionId }),
|
||||
setMode: (modeId) =>
|
||||
Ref.get(modeStateRef).pipe(
|
||||
Effect.flatMap((modeState) => {
|
||||
if (modeState?.currentModeId === modeId) {
|
||||
return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
|
||||
}
|
||||
return setConfigOption("mode", modeId).pipe(
|
||||
Effect.tap(() => updateCurrentModeId(modeId)),
|
||||
Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
|
||||
);
|
||||
}),
|
||||
client.setSessionMode({
|
||||
sessionId,
|
||||
modeId,
|
||||
}),
|
||||
setConfigOption: (configId, value) =>
|
||||
client.setSessionConfigOption(
|
||||
typeof value === "boolean"
|
||||
? ({
|
||||
sessionId,
|
||||
configId,
|
||||
type: "boolean",
|
||||
value,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
sessionId,
|
||||
configId,
|
||||
value: String(value),
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest),
|
||||
),
|
||||
setConfigOption,
|
||||
setModel: (model) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
request: (method, payload) =>
|
||||
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
|
||||
notify: acp.raw.notify,
|
||||
} satisfies AcpSessionRuntimeShape;
|
||||
client
|
||||
.setSessionConfigOption({
|
||||
sessionId,
|
||||
configId: extractModelConfigId(sessionSetupResult) ?? "model",
|
||||
value: model,
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
request: client.extRequest,
|
||||
notify: client.extNotification,
|
||||
close,
|
||||
} satisfies AcpSessionRuntime;
|
||||
});
|
||||
|
||||
function sessionConfigOptionsFromSetup(
|
||||
response:
|
||||
| {
|
||||
readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
|
||||
}
|
||||
| undefined,
|
||||
): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
|
||||
return response?.configOptions ?? [];
|
||||
}
|
||||
|
||||
function configOptionCurrentValueMatches(
|
||||
configOption: EffectAcpSchema.SessionConfigOption,
|
||||
value: string | boolean,
|
||||
): boolean {
|
||||
const currentValue = configOption.currentValue;
|
||||
if (configOption.type === "boolean") {
|
||||
return currentValue === value;
|
||||
}
|
||||
if (typeof currentValue !== "string") {
|
||||
return false;
|
||||
}
|
||||
return currentValue.trim() === String(value).trim();
|
||||
}
|
||||
|
||||
const handleSessionUpdate = ({
|
||||
queue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly params: EffectAcpSchema.SessionNotification;
|
||||
}): Effect.Effect<void> =>
|
||||
}): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseSessionUpdateEvent(params);
|
||||
if (parsed.modeId) {
|
||||
@@ -585,11 +229,7 @@ const handleSessionUpdate = ({
|
||||
}
|
||||
for (const event of parsed.events) {
|
||||
if (event._tag === "ToolCallUpdated") {
|
||||
yield* closeActiveAssistantSegment({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
});
|
||||
const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {
|
||||
const merged = yield* Ref.modify(toolCallsRef, (current) => {
|
||||
const previous = current.get(event.toolCall.toolCallId);
|
||||
const nextToolCall = mergeToolCallState(previous, event.toolCall);
|
||||
const next = new Map(current);
|
||||
@@ -598,11 +238,8 @@ const handleSessionUpdate = ({
|
||||
} else {
|
||||
next.set(nextToolCall.toolCallId, nextToolCall);
|
||||
}
|
||||
return [{ previous, merged: nextToolCall }, next] as const;
|
||||
return [nextToolCall, next] as const;
|
||||
});
|
||||
if (!shouldEmitToolCallUpdate(previous, merged)) {
|
||||
continue;
|
||||
}
|
||||
yield* Queue.offer(queue, {
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall: merged,
|
||||
@@ -610,27 +247,9 @@ const handleSessionUpdate = ({
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (event._tag === "ContentDelta") {
|
||||
if (event.text.trim().length === 0) {
|
||||
const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
|
||||
if (!assistantSegmentState.activeItemId) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const itemId = yield* ensureActiveAssistantSegment({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId: params.sessionId,
|
||||
});
|
||||
yield* Queue.offer(queue, {
|
||||
...event,
|
||||
itemId,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
yield* Queue.offer(queue, event);
|
||||
}
|
||||
});
|
||||
}).pipe(Effect.mapError(EffectAcpErrors.normalizeAcpError));
|
||||
|
||||
function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
|
||||
const normalized = nextModeId.trim();
|
||||
@@ -644,79 +263,3 @@ function updateModeState(modeState: AcpSessionModeState, nextModeId: string): Ac
|
||||
}
|
||||
: modeState;
|
||||
}
|
||||
|
||||
function shouldEmitToolCallUpdate(
|
||||
previous: AcpToolCallState | undefined,
|
||||
next: AcpToolCallState,
|
||||
): boolean {
|
||||
if (next.status === "completed" || next.status === "failed") {
|
||||
return true;
|
||||
}
|
||||
if (!next.detail) {
|
||||
return false;
|
||||
}
|
||||
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
|
||||
}
|
||||
|
||||
const assistantItemId = (sessionId: string, segmentIndex: number) =>
|
||||
`assistant:${sessionId}:segment:${segmentIndex}`;
|
||||
|
||||
const ensureActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
}) =>
|
||||
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
|
||||
assistantSegmentRef,
|
||||
(current) => {
|
||||
if (current.activeItemId) {
|
||||
return [{ itemId: current.activeItemId }, current] as const;
|
||||
}
|
||||
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
|
||||
return [
|
||||
{
|
||||
itemId,
|
||||
startedEvent: {
|
||||
_tag: "AssistantItemStarted",
|
||||
itemId,
|
||||
} satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
|
||||
},
|
||||
{
|
||||
nextSegmentIndex: current.nextSegmentIndex + 1,
|
||||
activeItemId: itemId,
|
||||
} satisfies AcpAssistantSegmentState,
|
||||
] as const;
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.startedEvent
|
||||
? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
|
||||
: Effect.succeed(result.itemId),
|
||||
),
|
||||
);
|
||||
|
||||
const closeActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
}) =>
|
||||
Ref.modify(assistantSegmentRef, (current) => {
|
||||
if (!current.activeItemId) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
return [
|
||||
{
|
||||
_tag: "AssistantItemCompleted",
|
||||
itemId: current.activeItemId,
|
||||
} satisfies AcpParsedSessionEvent,
|
||||
{
|
||||
nextSegmentIndex: current.nextSegmentIndex,
|
||||
} satisfies AcpAssistantSegmentState,
|
||||
] as const;
|
||||
}).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));
|
||||
@@ -1,147 +0,0 @@
|
||||
import { Effect, Option, Schema, SchemaIssue, SchemaTransformation } from "effect";
|
||||
|
||||
import type { AcpError } from "./AcpErrors.ts";
|
||||
|
||||
/** JSON-RPC 2.0 error object on the wire. */
|
||||
export const JsonRpcErrorPayload = Schema.Struct({
|
||||
code: Schema.Number,
|
||||
message: Schema.String,
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
/** Parsed JSON object from one NDJSON line before JSON-RPC classification. */
|
||||
export const JsonRpcInboundWire = Schema.Struct({
|
||||
jsonrpc: Schema.optional(Schema.String),
|
||||
id: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
|
||||
method: Schema.optional(Schema.String),
|
||||
params: Schema.optional(Schema.Unknown),
|
||||
result: Schema.optional(Schema.Unknown),
|
||||
error: Schema.optional(JsonRpcErrorPayload),
|
||||
});
|
||||
|
||||
export const AcpInboundResponse = Schema.TaggedStruct("response", {
|
||||
id: Schema.Union([Schema.String, Schema.Number]),
|
||||
result: Schema.optional(Schema.Unknown),
|
||||
error: Schema.optional(JsonRpcErrorPayload),
|
||||
});
|
||||
|
||||
export const AcpInboundRequest = Schema.TaggedStruct("request", {
|
||||
id: Schema.Union([Schema.String, Schema.Number]),
|
||||
method: Schema.String,
|
||||
params: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
export const AcpInboundNotification = Schema.TaggedStruct("notification", {
|
||||
method: Schema.String,
|
||||
params: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
/**
|
||||
* Inbound JSON-RPC messages from the ACP agent (stdout), after line framing.
|
||||
*/
|
||||
export const AcpInboundMessage = Schema.Union([
|
||||
AcpInboundResponse,
|
||||
AcpInboundRequest,
|
||||
AcpInboundNotification,
|
||||
]);
|
||||
|
||||
export type AcpInboundMessage = typeof AcpInboundMessage.Type;
|
||||
|
||||
const jsonRpcWireToInbound = SchemaTransformation.transformOrFail({
|
||||
decode: (parsed: typeof JsonRpcInboundWire.Type) => {
|
||||
const id = parsed.id;
|
||||
const method = parsed.method;
|
||||
const hasId = id !== undefined && id !== null;
|
||||
const hasMethod = typeof method === "string";
|
||||
|
||||
if (hasId && (parsed.result !== undefined || parsed.error !== undefined)) {
|
||||
const err = parsed.error;
|
||||
const rpcError =
|
||||
err !== undefined
|
||||
? {
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
...(err.data !== undefined ? { data: err.data } : {}),
|
||||
}
|
||||
: undefined;
|
||||
return Effect.succeed(
|
||||
AcpInboundResponse.makeUnsafe({
|
||||
id,
|
||||
...(parsed.result !== undefined ? { result: parsed.result } : {}),
|
||||
...(rpcError ? { error: rpcError } : {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (hasMethod && hasId) {
|
||||
return Effect.succeed(
|
||||
AcpInboundRequest.makeUnsafe({
|
||||
id,
|
||||
method,
|
||||
...(parsed.params !== undefined ? { params: parsed.params } : {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (hasMethod && !hasId) {
|
||||
return Effect.succeed(
|
||||
AcpInboundNotification.makeUnsafe({
|
||||
method,
|
||||
...(parsed.params !== undefined ? { params: parsed.params } : {}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(parsed), {
|
||||
message: "Unrecognized JSON-RPC inbound message shape",
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
encode: (msg: AcpInboundMessage) => {
|
||||
if (msg._tag === "response") {
|
||||
return Effect.succeed({
|
||||
jsonrpc: "2.0" as const,
|
||||
id: msg.id,
|
||||
...(msg.result !== undefined ? { result: msg.result } : {}),
|
||||
...(msg.error !== undefined ? { error: msg.error } : {}),
|
||||
});
|
||||
}
|
||||
if (msg._tag === "request") {
|
||||
return Effect.succeed({
|
||||
jsonrpc: "2.0" as const,
|
||||
id: msg.id,
|
||||
method: msg.method,
|
||||
...(msg.params !== undefined ? { params: msg.params } : {}),
|
||||
});
|
||||
}
|
||||
return Effect.succeed({
|
||||
jsonrpc: "2.0" as const,
|
||||
method: msg.method,
|
||||
...(msg.params !== undefined ? { params: msg.params } : {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const jsonRpcWireDecodedToInbound = JsonRpcInboundWire.pipe(
|
||||
Schema.decodeTo(Schema.toType(AcpInboundMessage), jsonRpcWireToInbound),
|
||||
);
|
||||
|
||||
/** Decode one NDJSON line (JSON string) to a classified inbound message. */
|
||||
export const AcpInboundFromJsonLine = Schema.fromJsonString(jsonRpcWireDecodedToInbound);
|
||||
|
||||
export const decodeAcpInboundFromJsonLine = Schema.decodeEffect(AcpInboundFromJsonLine);
|
||||
|
||||
export interface AcpSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string;
|
||||
/** Merged with `process.env` for the child. */
|
||||
readonly env?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export type AcpServerRequestHandler = (
|
||||
params: unknown,
|
||||
requestId: number | string,
|
||||
) => Effect.Effect<unknown, AcpError>;
|
||||
@@ -6,125 +6,90 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { makeAcpJsonRpcConnection } from "./AcpJsonRpcConnection.ts";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
import { makeAcpSessionRuntime } from "./AcpSessionRuntime.ts";
|
||||
|
||||
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
|
||||
it.effect("initialize and authenticate against real agent acp", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
const init = yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
});
|
||||
expect(init).toBeDefined();
|
||||
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
expect(runtime.initializeResult).toBeDefined();
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("session/new returns configOptions with a model selector", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
});
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
|
||||
const result = yield* conn.request("session/new", {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
const result = runtime.sessionSetupResult;
|
||||
console.log("session/new result:", JSON.stringify(result, null, 2));
|
||||
|
||||
expect(isRecord(result)).toBe(true);
|
||||
const r = result as Record<string, unknown>;
|
||||
expect(typeof r.sessionId).toBe("string");
|
||||
expect(typeof runtime.sessionId).toBe("string");
|
||||
|
||||
const configOptions = r.configOptions;
|
||||
const configOptions = result.configOptions;
|
||||
console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
|
||||
|
||||
if (Array.isArray(configOptions)) {
|
||||
const modelConfig = configOptions.find(
|
||||
(opt: unknown) => isRecord(opt) && opt.category === "model",
|
||||
);
|
||||
const modelConfig = configOptions.find((opt) => opt.category === "model");
|
||||
console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
|
||||
expect(modelConfig).toBeDefined();
|
||||
expect(isRecord(modelConfig) && typeof modelConfig.id === "string").toBe(true);
|
||||
expect(typeof modelConfig?.id).toBe("string");
|
||||
}
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("session/set_config_option switches the model in-session", () =>
|
||||
Effect.gen(function* () {
|
||||
const conn = yield* makeAcpJsonRpcConnection({
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
const runtime = yield* makeAcpSessionRuntime({
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
|
||||
yield* conn.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
});
|
||||
yield* conn.request("authenticate", { methodId: "cursor_login" });
|
||||
|
||||
const newResult = (yield* conn.request("session/new", {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
})) as Record<string, unknown>;
|
||||
const sessionId = newResult.sessionId as string;
|
||||
const newResult = runtime.sessionSetupResult;
|
||||
|
||||
const configOptions = newResult.configOptions;
|
||||
let modelConfigId = "model";
|
||||
if (Array.isArray(configOptions)) {
|
||||
const modelConfig = configOptions.find(
|
||||
(opt: unknown) => isRecord(opt) && opt.category === "model",
|
||||
);
|
||||
if (isRecord(modelConfig) && typeof modelConfig.id === "string") {
|
||||
const modelConfig = configOptions.find((opt) => opt.category === "model");
|
||||
if (typeof modelConfig?.id === "string") {
|
||||
modelConfigId = modelConfig.id;
|
||||
}
|
||||
}
|
||||
|
||||
const setResult = yield* conn.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: modelConfigId,
|
||||
value: "composer-2",
|
||||
});
|
||||
const setResult: EffectAcpSchema.SetSessionConfigOptionResponse =
|
||||
yield* runtime.setConfigOption(modelConfigId, "composer-2");
|
||||
|
||||
console.log("session/set_config_option result:", JSON.stringify(setResult, null, 2));
|
||||
|
||||
expect(isRecord(setResult)).toBe(true);
|
||||
const sr = setResult as Record<string, unknown>;
|
||||
if (Array.isArray(sr.configOptions)) {
|
||||
const modelConfig = sr.configOptions.find(
|
||||
(opt: unknown) => isRecord(opt) && opt.category === "model",
|
||||
);
|
||||
if (isRecord(modelConfig)) {
|
||||
if (Array.isArray(setResult.configOptions)) {
|
||||
const modelConfig = setResult.configOptions.find((opt) => opt.category === "model");
|
||||
if (modelConfig?.type === "select") {
|
||||
expect(modelConfig.currentValue).toBe("composer-2");
|
||||
}
|
||||
}
|
||||
yield* runtime.close;
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -29,7 +29,6 @@ describe("CursorAcpExtension", () => {
|
||||
id: "language",
|
||||
header: "Question",
|
||||
question: "Which language should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "TypeScript", description: "TypeScript" },
|
||||
{ label: "Rust", description: "Rust" },
|
||||
@@ -38,35 +37,6 @@ describe("CursorAcpExtension", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("defaults ask-question multi-select to false when Cursor omits allowMultiple", () => {
|
||||
const questions = extractAskQuestions({
|
||||
toolCallId: "ask-2",
|
||||
questions: [
|
||||
{
|
||||
id: "mode",
|
||||
prompt: "Which mode should I use?",
|
||||
options: [
|
||||
{ id: "agent", label: "Agent" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "mode",
|
||||
header: "Question",
|
||||
question: "Which mode should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Agent", description: "Agent" },
|
||||
{ label: "Plan", description: "Plan" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("extracts plan markdown from the real Cursor create-plan payload shape", () => {
|
||||
const planMarkdown = extractPlanMarkdown({
|
||||
toolCallId: "plan-1",
|
||||
@@ -83,25 +53,20 @@ describe("CursorAcpExtension", () => {
|
||||
expect(planMarkdown).toBe("# Plan\n\n1. Add schemas\n2. Remove casts");
|
||||
});
|
||||
|
||||
it("projects todo updates into a plan shape and drops invalid entries", () => {
|
||||
it("projects todo updates into a plan shape", () => {
|
||||
expect(
|
||||
extractTodosAsPlan({
|
||||
toolCallId: "todos-1",
|
||||
todos: [
|
||||
{ id: "1", content: "Inspect state", status: "completed" },
|
||||
{ id: "2", content: " Apply fix ", status: "in_progress" },
|
||||
{ id: "3", title: "Fallback title", status: "pending" },
|
||||
{ id: "4", content: "Unknown status", status: "weird_status" },
|
||||
{ id: "5", content: " " },
|
||||
{ content: "Inspect state", status: "completed" },
|
||||
{ title: "Apply fix", status: "in_progress" },
|
||||
{},
|
||||
],
|
||||
merge: true,
|
||||
}),
|
||||
).toEqual({
|
||||
plan: [
|
||||
{ step: "Inspect state", status: "completed" },
|
||||
{ step: "Apply fix", status: "inProgress" },
|
||||
{ step: "Fallback title", status: "pending" },
|
||||
{ step: "Unknown status", status: "pending" },
|
||||
{ step: "Step 3", status: "pending" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
/**
|
||||
* Public Docs: https://cursor.com/docs/cli/acp#cursor-extension-methods
|
||||
* Additional reference provided by the Cursor team: https://anysphere.enterprise.slack.com/files/U068SSJE141/F0APT1HSZRP/cursor-acp-extension-method-schemas.md
|
||||
*/
|
||||
import type { UserInputQuestion } from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
|
||||
@@ -14,31 +10,35 @@ const CursorAskQuestion = Schema.Struct({
|
||||
id: Schema.String,
|
||||
prompt: Schema.String,
|
||||
options: Schema.Array(CursorAskQuestionOption),
|
||||
allowMultiple: Schema.optional(Schema.Boolean),
|
||||
allowMultiple: Schema.Boolean,
|
||||
});
|
||||
|
||||
export const CursorAskQuestionRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
toolCallId: Schema.optional(Schema.String),
|
||||
title: Schema.optional(Schema.String),
|
||||
questions: Schema.Array(CursorAskQuestion),
|
||||
});
|
||||
|
||||
const CursorTodoStatus = Schema.String;
|
||||
const CursorTodoStatus = Schema.Union([
|
||||
Schema.Literal("pending"),
|
||||
Schema.Literal("in_progress"),
|
||||
Schema.Literal("completed"),
|
||||
Schema.Literal("cancelled"),
|
||||
]);
|
||||
|
||||
const CursorTodo = Schema.Struct({
|
||||
id: Schema.optional(Schema.String),
|
||||
content: Schema.optional(Schema.String),
|
||||
title: Schema.optional(Schema.String),
|
||||
status: Schema.optional(CursorTodoStatus),
|
||||
status: CursorTodoStatus,
|
||||
});
|
||||
|
||||
const CursorPlanPhase = Schema.Struct({
|
||||
name: Schema.String,
|
||||
name: Schema.optional(Schema.String),
|
||||
todos: Schema.Array(CursorTodo),
|
||||
});
|
||||
|
||||
export const CursorCreatePlanRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
toolCallId: Schema.optional(Schema.String),
|
||||
name: Schema.optional(Schema.String),
|
||||
overview: Schema.optional(Schema.String),
|
||||
plan: Schema.String,
|
||||
@@ -47,11 +47,7 @@ export const CursorCreatePlanRequest = Schema.Struct({
|
||||
phases: Schema.optional(Schema.Array(CursorPlanPhase)),
|
||||
});
|
||||
|
||||
export const CursorUpdateTodosRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
todos: Schema.Array(CursorTodo),
|
||||
merge: Schema.Boolean,
|
||||
});
|
||||
export const CursorUpdateTodosRequest = Schema.Unknown;
|
||||
|
||||
export function extractAskQuestions(
|
||||
params: typeof CursorAskQuestionRequest.Type,
|
||||
@@ -60,7 +56,7 @@ export function extractAskQuestions(
|
||||
id: question.id,
|
||||
header: "Question",
|
||||
question: question.prompt,
|
||||
multiSelect: question.allowMultiple === true,
|
||||
multiSelect: question.allowMultiple,
|
||||
options:
|
||||
question.options.length > 0
|
||||
? question.options.map((option) => ({
|
||||
@@ -82,18 +78,39 @@ export function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type)
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
} {
|
||||
const plan = params.todos.flatMap((todo) => {
|
||||
const step = todo.content?.trim() ?? todo.title?.trim() ?? "";
|
||||
if (step === "") {
|
||||
return [];
|
||||
}
|
||||
if (typeof params !== "object" || params === null) {
|
||||
return { plan: [] };
|
||||
}
|
||||
const record = params as {
|
||||
readonly todos?: ReadonlyArray<{
|
||||
readonly content?: string;
|
||||
readonly title?: string;
|
||||
readonly status?: string;
|
||||
}>;
|
||||
readonly items?: ReadonlyArray<{
|
||||
readonly content?: string;
|
||||
readonly title?: string;
|
||||
readonly status?: string;
|
||||
}>;
|
||||
};
|
||||
const todos = record.todos ?? record.items;
|
||||
if (!todos) {
|
||||
return { plan: [] };
|
||||
}
|
||||
const plan = todos.map((t, i) => {
|
||||
const step =
|
||||
typeof t?.content === "string"
|
||||
? t.content
|
||||
: typeof t?.title === "string"
|
||||
? t.title
|
||||
: `Step ${i + 1}`;
|
||||
const status: "pending" | "inProgress" | "completed" =
|
||||
todo.status === "completed"
|
||||
t?.status === "completed"
|
||||
? "completed"
|
||||
: todo.status === "in_progress" || todo.status === "inProgress"
|
||||
: t?.status === "in_progress" || t?.status === "inProgress"
|
||||
? "inProgress"
|
||||
: "pending";
|
||||
return [{ step, status }];
|
||||
return { step, status };
|
||||
});
|
||||
return { plan };
|
||||
}
|
||||
@@ -83,10 +83,7 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
);
|
||||
const cursorAdapterLayer = makeCursorAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const acpAdapterLayer = makeAcpAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
).pipe(Layer.provide(AcpAgentRegistryLive));
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
|
||||
@@ -55,6 +55,7 @@
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
},
|
||||
@@ -199,9 +200,9 @@
|
||||
},
|
||||
},
|
||||
},
|
||||
"trustedDependencies": [
|
||||
"node-pty",
|
||||
],
|
||||
"patchedDependencies": {
|
||||
"[email protected]": "patches/[email protected]",
|
||||
},
|
||||
"overrides": {
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
@@ -214,13 +215,13 @@
|
||||
},
|
||||
"catalog": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/openapi-generator": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
|
||||
"@effect/openapi-generator": "4.0.0-beta.41",
|
||||
"@effect/platform-node": "4.0.0-beta.41",
|
||||
"@effect/sql-sqlite-bun": "4.0.0-beta.41",
|
||||
"@effect/vitest": "4.0.0-beta.41",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"effect": "4.0.0-beta.45",
|
||||
"effect": "4.0.0-beta.41",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
@@ -310,21 +311,15 @@
|
||||
|
||||
"@effect/atom-react": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.45", "react": "^19.2.4", "scheduler": "*" } }, "sha512-jCoiae9UNeis9Yoal1p5V/P4eJK9nX89wORom7X5LpR2Ok920SZJc8dIeYkRXRAp9BCYJ/yWcO8gGLf7do71vg=="],
|
||||
|
||||
"@effect/openapi-generator": ["@effect/openapi-generator@https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.25", "effect": "^4.0.0-beta.25" }, "bin": { "openapigen": "./dist/bin.js" } }],
|
||||
"@effect/openapi-generator": ["@effect/openapi-generator@4.0.0-beta.41", "", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.41", "effect": "^4.0.0-beta.41" }, "bin": { "openapigen": "dist/bin.js" } }, "sha512-7eTTSCFjSyCMaG76fl0YiFEjfdTWaUiTS2mJ4RM0Q7jUfrYyw3rwosPqVJ8N9zWmZSnoUyD+qAD/ZK8hW970hw=="],
|
||||
|
||||
"@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25", "ioredis": "^5.7.0" } }],
|
||||
"@effect/platform-node": ["@effect/platform-node@4.0.0-beta.41", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.41", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41", "ioredis": "^5.7.0" } }, "sha512-lgsWfvJfxwg7xXT5rK3xcPyAFPAYXXJ0u/6yCu2suOMhdR5w2W6oA2L2pIQaqap8qR8uEVB5pHq6dqVfdRP7Nw=="],
|
||||
|
||||
"@effect/openapi-generator": ["@effect/openapi-generator@4.0.0-beta.45", "", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.45", "effect": "^4.0.0-beta.45" }, "bin": { "openapigen": "dist/bin.js" } }, "sha512-zT1UPzapV6mZebMuYhoDPQj/FKNn4R+oDgz1hEcQwazal4+lVDyEYGhRl0PgZroy6CP78fAOWNgW7TriGqSlOQ=="],
|
||||
"@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.41", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41" } }, "sha512-YzKWz1G8YofCrQ0Thxymlk71CM3q7R1vzO2vtnb7KSHkTJrvrQB8FbZaM8mEddYOoamR25f46lidFKErmmotKg=="],
|
||||
|
||||
"@effect/platform-bun": ["@effect/platform[email protected]5", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.45" }, "peerDependencies": { "effect": "^4.0.0-beta.45" } }, "sha512-dZsbkJ+o4JfKE1OIAlMq8YWhmEfXxtTYennYADK/M/XlOtkFLsc2jkZppDvMznVni6JpFxWc7wd5rUf8jBVP5g=="],
|
||||
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite[email protected]1", "", { "peerDependencies": { "effect": "^4.0.0-beta.41" } }, "sha512-z3OvuTKE7GYIMZefKrTHNNuPaXxVpcSZmEAJd8ITap8wHVEEBs4WT+p/CHDae4dlJc6HJeWGSHxQuPVmdC16bA=="],
|
||||
|
||||
"@effect/platform-node": ["@effect/platform-node@4.0.0-beta.45", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.45", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.45", "ioredis": "^5.7.0" } }, "sha512-P07NMG4eoy62iLX9szak0hkr7hrwgq5+XMkm7URVug/3zqfZVxEG2kxn9JzVK1lF5WbaVrEKwjt3IkEJxzSPtg=="],
|
||||
|
||||
"@effect/platform-node-shared": ["@effect/[email protected]", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.45" } }, "sha512-0T4RG18o+aCVUSlmPxA7uAjHJkyE3MS/uRrR5kCNSZQNG3X71wdIbu82wE/MnV6+6YSSPDx/6TVdZWYkJF0JWw=="],
|
||||
|
||||
"@effect/sql-sqlite-bun": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.45" } }, "sha512-sJBBztwI4YxjdjhdyjWelh3KKoZucmmZS2ONeNDIzYgqFlsrwEEUrhVkWf5ch9Io+kUUzeb6q7/SedFoLUWO7g=="],
|
||||
|
||||
"@effect/vitest": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.45", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-38JA5Z6c2FoEhpVKbl7rjTrMU8Al5T30Kwtb6N3B9kOkyr2SsmvNsP9T65bh03IBh3ak9U//acrkmjS3hLQwKA=="],
|
||||
"@effect/vitest": ["@effect/vitest@4.0.0-beta.41", "", { "peerDependencies": { "effect": "^4.0.0-beta.41", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-VCwK2Sj1gbCaC7eoipS/pmty1plN08nNKF6z0sn9S3q+6OLCbeJ3+2qKzFQCnpdkvud45HNK3Z9kVCZew6kKhA=="],
|
||||
|
||||
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
|
||||
|
||||
@@ -1076,11 +1071,7 @@
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
|
||||
"ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
|
||||
|
||||
"effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-vvNrUWqnzBIW1hRMa+zw0CLRW6HLgdu7hQ6K7PT/rS+UY/73Ma11O+Oi9oc9zwL8KcN37M47UDseAdlF0bGNWw=="],
|
||||
|
||||
"effect-acp": ["effect-acp@workspace:packages/effect-acp"],
|
||||
"effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-kBjbmo2qqXbOgrvZcPgVdgsOOWcGPYwRcvGO3aGPWJhpXxDFNfgtwqtU6asMq2M7LSFRx1SA+3BzJm7FDqtxew=="],
|
||||
|
||||
"effect-acp": ["effect-acp@workspace:packages/effect-acp"],
|
||||
|
||||
@@ -2054,18 +2045,6 @@
|
||||
|
||||
"@babel/types/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
|
||||
|
||||
"@effect/openapi-generator/@effect/platform-node": ["@effect/[email protected]", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.41", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41", "ioredis": "^5.7.0" } }, "sha512-lgsWfvJfxwg7xXT5rK3xcPyAFPAYXXJ0u/6yCu2suOMhdR5w2W6oA2L2pIQaqap8qR8uEVB5pHq6dqVfdRP7Nw=="],
|
||||
|
||||
"@effect/openapi-generator/effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-kBjbmo2qqXbOgrvZcPgVdgsOOWcGPYwRcvGO3aGPWJhpXxDFNfgtwqtU6asMq2M7LSFRx1SA+3BzJm7FDqtxew=="],
|
||||
|
||||
"@effect/platform-node/effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
|
||||
"@effect/platform-node-shared/effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
|
||||
"@effect/sql-sqlite-bun/effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
|
||||
"@effect/vitest/effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="],
|
||||
|
||||
"@electron/get/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
|
||||
|
||||
"@electron/get/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
@@ -2160,8 +2139,6 @@
|
||||
|
||||
"@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-noLx87RwlBEMrTzncWd/FvTxoJ9+ycHNg0n8yyYydIoDsLZuxknKgWRJUqcrVkNrJ74uGyhWQzQaS3q8xfGAhQ=="],
|
||||
|
||||
"@effect/openapi-generator/@effect/platform-node/@effect/platform-node-shared": ["@effect/[email protected]", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.41" } }, "sha512-YzKWz1G8YofCrQ0Thxymlk71CM3q7R1vzO2vtnb7KSHkTJrvrQB8FbZaM8mEddYOoamR25f46lidFKErmmotKg=="],
|
||||
|
||||
"@electron/get/fs-extra/jsonfile": ["[email protected]", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="],
|
||||
|
||||
"@electron/get/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
|
||||
|
||||
+8
-8
@@ -8,11 +8,11 @@
|
||||
"scripts"
|
||||
],
|
||||
"catalog": {
|
||||
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
|
||||
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
|
||||
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
|
||||
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
|
||||
"@effect/openapi-generator": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/openapi-generator@8881a9b",
|
||||
"effect": "4.0.0-beta.41",
|
||||
"@effect/platform-node": "4.0.0-beta.41",
|
||||
"@effect/sql-sqlite-bun": "4.0.0-beta.41",
|
||||
"@effect/vitest": "4.0.0-beta.41",
|
||||
"@effect/openapi-generator": "4.0.0-beta.41",
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
@@ -81,7 +81,7 @@
|
||||
"apps/web/public"
|
||||
]
|
||||
},
|
||||
"trustedDependencies": [
|
||||
"node-pty"
|
||||
]
|
||||
"patchedDependencies": {
|
||||
"[email protected]": "patches/[email protected]"
|
||||
}
|
||||
}
|
||||
@@ -18,15 +18,15 @@ import { ProviderKind } from "./orchestration.ts";
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
const RuntimeEventRawSource = Schema.Literals([
|
||||
"codex.app-server.notification",
|
||||
"codex.app-server.request",
|
||||
"codex.eventmsg",
|
||||
"claude.sdk.message",
|
||||
"claude.sdk.permission",
|
||||
"codex.sdk.thread-event",
|
||||
"acp.jsonrpc",
|
||||
"acp.cursor.extension",
|
||||
const RuntimeEventRawSource = Schema.Union([
|
||||
Schema.Literal("codex.app-server.notification"),
|
||||
Schema.Literal("codex.app-server.request"),
|
||||
Schema.Literal("codex.eventmsg"),
|
||||
Schema.Literal("claude.sdk.message"),
|
||||
Schema.Literal("claude.sdk.permission"),
|
||||
Schema.Literal("codex.sdk.thread-event"),
|
||||
Schema.Literal("acp.jsonrpc"),
|
||||
Schema.TemplateLiteral(["acp.", Schema.String, ".extension"]),
|
||||
]);
|
||||
export type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type;
|
||||
|
||||
|
||||
@@ -4,74 +4,36 @@
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./client": {
|
||||
"import": {
|
||||
"types": "./src/client.d.mts",
|
||||
"default": "./src/client.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./src/client.d.cts",
|
||||
"default": "./src/client.cjs"
|
||||
}
|
||||
"types": "./src/client.ts",
|
||||
"import": "./src/client.ts"
|
||||
},
|
||||
"./server": {
|
||||
"import": {
|
||||
"types": "./src/server.d.mts",
|
||||
"default": "./src/server.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./src/server.d.cts",
|
||||
"default": "./src/server.cjs"
|
||||
}
|
||||
"types": "./src/server.ts",
|
||||
"import": "./src/server.ts"
|
||||
},
|
||||
"./schema": {
|
||||
"import": {
|
||||
"types": "./src/_generated/schema.gen.d.mts",
|
||||
"default": "./src/_generated/schema.gen.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./src/_generated/schema.gen.d.cts",
|
||||
"default": "./src/_generated/schema.gen.cjs"
|
||||
}
|
||||
"types": "./src/schema.ts",
|
||||
"import": "./src/schema.ts"
|
||||
},
|
||||
"./rpc": {
|
||||
"import": {
|
||||
"types": "./src/rpc.d.mts",
|
||||
"default": "./src/rpc.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./src/rpc.d.cts",
|
||||
"default": "./src/rpc.cjs"
|
||||
}
|
||||
"types": "./src/rpc.ts",
|
||||
"import": "./src/rpc.ts"
|
||||
},
|
||||
"./protocol": {
|
||||
"import": {
|
||||
"types": "./src/protocol.d.mts",
|
||||
"default": "./src/protocol.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./src/protocol.d.cts",
|
||||
"default": "./src/protocol.cjs"
|
||||
}
|
||||
"types": "./src/protocol.ts",
|
||||
"import": "./src/protocol.ts"
|
||||
},
|
||||
"./terminal": {
|
||||
"import": {
|
||||
"types": "./src/terminal.d.mts",
|
||||
"default": "./src/terminal.mts"
|
||||
},
|
||||
"require": {
|
||||
"types": "./src/terminal.d.cts",
|
||||
"default": "./src/terminal.cjs"
|
||||
}
|
||||
"types": "./src/terminal.ts",
|
||||
"import": "./src/terminal.ts"
|
||||
},
|
||||
"./child-process": {
|
||||
"import": {
|
||||
"types": "./src/child-process.d.mts",
|
||||
"default": "./src/child-process.mts"
|
||||
},
|
||||
"require": {
|
||||
"types": "./src/child-process.d.cts",
|
||||
"default": "./src/child-process.cjs"
|
||||
}
|
||||
"types": "./src/child-process.ts",
|
||||
"import": "./src/child-process.ts"
|
||||
},
|
||||
"./errors": {
|
||||
"types": "./src/errors.ts",
|
||||
"import": "./src/errors.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -481,6 +481,17 @@ export const SessionCloseCapabilities = Schema.Struct({
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nCapabilities for the `session/close` method.\n\nBy supplying `{}` it means that the agent supports closing of sessions.",
|
||||
});
|
||||
|
||||
export type SessionConfigOptionCategory = "mode" | "model" | "thought_level" | string;
|
||||
export const SessionConfigOptionCategory = Schema.Union([
|
||||
Schema.Literal("mode").annotate({ description: "Session mode selector." }),
|
||||
Schema.Literal("model").annotate({ description: "Model selector." }),
|
||||
Schema.Literal("thought_level").annotate({ description: "Thought/reasoning level selector." }),
|
||||
Schema.String.annotate({ title: "other", description: "Unknown / uncategorized selector." }),
|
||||
]).annotate({
|
||||
description:
|
||||
"Semantic category for a session configuration option.\n\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\ncategories gracefully.\n\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\nCategory names that do not begin with `_` are reserved for the ACP spec.",
|
||||
});
|
||||
|
||||
export type SessionConfigSelectOption = {
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly description?: string | null;
|
||||
@@ -1800,40 +1811,97 @@ export type SessionConfigOption =
|
||||
readonly options:
|
||||
| ReadonlyArray<SessionConfigSelectOption>
|
||||
| ReadonlyArray<SessionConfigSelectGroup>;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly category?: SessionConfigOptionCategory | null;
|
||||
readonly description?: string | null;
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
}
|
||||
| { readonly type: "boolean"; readonly currentValue: boolean };
|
||||
export const SessionConfigOption = Schema.Union(
|
||||
[
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("select"),
|
||||
currentValue: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option value.",
|
||||
}),
|
||||
options: Schema.Union([
|
||||
Schema.Array(SessionConfigSelectOption).annotate({
|
||||
title: "Ungrouped",
|
||||
description: "A flat list of options with no grouping.",
|
||||
}),
|
||||
Schema.Array(SessionConfigSelectGroup).annotate({
|
||||
title: "Grouped",
|
||||
description: "A list of options grouped under headers.",
|
||||
}),
|
||||
]).annotate({ description: "Possible values for a session configuration option." }),
|
||||
}).annotate({
|
||||
description: "A single-value selector (dropdown) session configuration option payload.",
|
||||
| {
|
||||
readonly type: "boolean";
|
||||
readonly currentValue: boolean;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly category?: SessionConfigOptionCategory | null;
|
||||
readonly description?: string | null;
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
};
|
||||
export const SessionConfigOption = Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("select"),
|
||||
currentValue: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option value.",
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("boolean"),
|
||||
currentValue: Schema.Boolean.annotate({
|
||||
description: "The current value of the boolean option.",
|
||||
options: Schema.Union([
|
||||
Schema.Array(SessionConfigSelectOption).annotate({
|
||||
title: "Ungrouped",
|
||||
description: "A flat list of options with no grouping.",
|
||||
}),
|
||||
}).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nA boolean on/off toggle session configuration option payload.",
|
||||
Schema.Array(SessionConfigSelectGroup).annotate({
|
||||
title: "Grouped",
|
||||
description: "A list of options grouped under headers.",
|
||||
}),
|
||||
]).annotate({ description: "Possible values for a session configuration option." }),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
category: Schema.optionalKey(
|
||||
Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({
|
||||
description: "Optional semantic category for this option (UX only).",
|
||||
}),
|
||||
),
|
||||
description: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({
|
||||
description: "Optional description for the Client to display to the user.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
id: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option.",
|
||||
}),
|
||||
],
|
||||
{ mode: "oneOf" },
|
||||
).annotate({ description: "A session configuration option selector and its current state." });
|
||||
name: Schema.String.annotate({ description: "Human-readable label for the option." }),
|
||||
}).annotate({ description: "A session configuration option selector and its current state." }),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("boolean"),
|
||||
currentValue: Schema.Boolean.annotate({
|
||||
description: "The current value of the boolean option.",
|
||||
}),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
category: Schema.optionalKey(
|
||||
Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({
|
||||
description: "Optional semantic category for this option (UX only).",
|
||||
}),
|
||||
),
|
||||
description: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({
|
||||
description: "Optional description for the Client to display to the user.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
id: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option.",
|
||||
}),
|
||||
name: Schema.String.annotate({ description: "Human-readable label for the option." }),
|
||||
}).annotate({ description: "A session configuration option selector and its current state." }),
|
||||
]);
|
||||
|
||||
export type SessionModeState = {
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
@@ -3005,8 +3073,18 @@ export type AgentRequest = {
|
||||
readonly title?: string | null;
|
||||
readonly type?: "object";
|
||||
};
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly message: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
| {
|
||||
readonly mode: "url";
|
||||
readonly elicitationId: string;
|
||||
readonly url: string;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly message: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
| { readonly mode: "url"; readonly elicitationId: string; readonly url: string }
|
||||
| unknown
|
||||
| null;
|
||||
};
|
||||
@@ -3285,73 +3363,102 @@ export const AgentRequest = Schema.Struct({
|
||||
title: "KillTerminalRequest",
|
||||
description: "Request to kill a terminal without releasing it.",
|
||||
}),
|
||||
Schema.Union(
|
||||
[
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("form"),
|
||||
requestedSchema: Schema.Struct({
|
||||
description: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({
|
||||
description: "Optional description of what this schema represents.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
properties: Schema.optionalKey(
|
||||
Schema.Record(Schema.String, ElicitationPropertySchema).annotate({
|
||||
description: "Property definitions (must be primitive types).",
|
||||
default: {},
|
||||
Schema.Union([
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("form"),
|
||||
requestedSchema: Schema.Struct({
|
||||
description: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({
|
||||
description: "Optional description of what this schema represents.",
|
||||
}),
|
||||
),
|
||||
required: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Array(Schema.String).annotate({
|
||||
description: "List of required property names.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
title: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({ description: "Optional title for the schema." }),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
type: Schema.optionalKey(
|
||||
Schema.Literal("object").annotate({
|
||||
description: "Type discriminator for elicitation schemas.",
|
||||
default: "object",
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
properties: Schema.optionalKey(
|
||||
Schema.Record(Schema.String, ElicitationPropertySchema).annotate({
|
||||
description: "Property definitions (must be primitive types).",
|
||||
default: {},
|
||||
}),
|
||||
),
|
||||
required: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Array(Schema.String).annotate({
|
||||
description: "List of required property names.",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description:
|
||||
"Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
title: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({ description: "Optional title for the schema." }),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
type: Schema.optionalKey(
|
||||
Schema.Literal("object").annotate({
|
||||
description: "Type discriminator for elicitation schemas.",
|
||||
default: "object",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nForm-based elicitation mode where the client renders a form from the provided schema.",
|
||||
"Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.",
|
||||
}),
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("url"),
|
||||
elicitationId: Schema.String.annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.",
|
||||
}),
|
||||
url: Schema.String.annotate({
|
||||
description: "The URL to direct the user to.",
|
||||
format: "uri",
|
||||
}),
|
||||
}).annotate({
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
message: Schema.String.annotate({
|
||||
description: "A human-readable message describing what input is needed.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nURL-based elicitation mode where the client directs the user to a URL.",
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
],
|
||||
{ mode: "oneOf" },
|
||||
).annotate({
|
||||
}).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.",
|
||||
}),
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("url"),
|
||||
elicitationId: Schema.String.annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.",
|
||||
}),
|
||||
url: Schema.String.annotate({
|
||||
description: "The URL to direct the user to.",
|
||||
format: "uri",
|
||||
}),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
message: Schema.String.annotate({
|
||||
description: "A human-readable message describing what input is needed.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
}).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.",
|
||||
}),
|
||||
]).annotate({
|
||||
title: "ElicitationRequest",
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.",
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequests structured user input via a form or URL.",
|
||||
}),
|
||||
Schema.Unknown.annotate({
|
||||
title: "ExtMethodRequest",
|
||||
@@ -4490,8 +4597,19 @@ export type ClientRequest = {
|
||||
readonly modeId: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
| { readonly type: "boolean"; readonly value: boolean }
|
||||
| { readonly value: string }
|
||||
| {
|
||||
readonly type: "boolean";
|
||||
readonly value: boolean;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly configId: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
| {
|
||||
readonly value: string;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly configId: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
| {
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly messageId?: string | null;
|
||||
@@ -4830,19 +4948,52 @@ export const ClientRequest = Schema.Struct({
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("boolean"),
|
||||
value: Schema.Boolean.annotate({ description: "The boolean value." }),
|
||||
}).annotate({ description: 'A boolean value (`type: "boolean"`).' }),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
configId: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
}).annotate({
|
||||
description: "Request parameters for setting a session configuration option.",
|
||||
}),
|
||||
Schema.Struct({
|
||||
value: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option value.",
|
||||
}),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
configId: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
}).annotate({
|
||||
title: "value_id",
|
||||
description:
|
||||
"A [`SessionConfigValueId`] string value.\n\nThis is the default when `type` is absent on the wire. Unknown `type`\nvalues with string payloads also gracefully deserialize into this\nvariant.",
|
||||
description: "Request parameters for setting a session configuration option.",
|
||||
}),
|
||||
]).annotate({
|
||||
title: "SetSessionConfigOptionRequest",
|
||||
description: "Request parameters for setting a session configuration option.",
|
||||
description: "Sets the current value for a session configuration option.",
|
||||
}),
|
||||
Schema.Struct({
|
||||
_meta: Schema.optionalKey(
|
||||
@@ -5818,72 +5969,106 @@ export type ElicitationRequest =
|
||||
readonly title?: string | null;
|
||||
readonly type?: "object";
|
||||
};
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly message: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
| { readonly mode: "url"; readonly elicitationId: string; readonly url: string };
|
||||
export const ElicitationRequest = Schema.Union(
|
||||
[
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("form"),
|
||||
requestedSchema: Schema.Struct({
|
||||
description: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({
|
||||
description: "Optional description of what this schema represents.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
properties: Schema.optionalKey(
|
||||
Schema.Record(Schema.String, ElicitationPropertySchema).annotate({
|
||||
description: "Property definitions (must be primitive types).",
|
||||
default: {},
|
||||
| {
|
||||
readonly mode: "url";
|
||||
readonly elicitationId: string;
|
||||
readonly url: string;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly message: string;
|
||||
readonly sessionId: string;
|
||||
};
|
||||
export const ElicitationRequest = Schema.Union([
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("form"),
|
||||
requestedSchema: Schema.Struct({
|
||||
description: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({
|
||||
description: "Optional description of what this schema represents.",
|
||||
}),
|
||||
),
|
||||
required: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Array(Schema.String).annotate({
|
||||
description: "List of required property names.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
title: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({ description: "Optional title for the schema." }),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
type: Schema.optionalKey(
|
||||
Schema.Literal("object").annotate({
|
||||
description: "Type discriminator for elicitation schemas.",
|
||||
default: "object",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description:
|
||||
"Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
properties: Schema.optionalKey(
|
||||
Schema.Record(Schema.String, ElicitationPropertySchema).annotate({
|
||||
description: "Property definitions (must be primitive types).",
|
||||
default: {},
|
||||
}),
|
||||
),
|
||||
required: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Array(Schema.String).annotate({ description: "List of required property names." }),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
title: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.String.annotate({ description: "Optional title for the schema." }),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
type: Schema.optionalKey(
|
||||
Schema.Literal("object").annotate({
|
||||
description: "Type discriminator for elicitation schemas.",
|
||||
default: "object",
|
||||
}),
|
||||
),
|
||||
}).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nForm-based elicitation mode where the client renders a form from the provided schema.",
|
||||
"Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.",
|
||||
}),
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("url"),
|
||||
elicitationId: Schema.String.annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.",
|
||||
}),
|
||||
url: Schema.String.annotate({ description: "The URL to direct the user to.", format: "uri" }),
|
||||
}).annotate({
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
message: Schema.String.annotate({
|
||||
description: "A human-readable message describing what input is needed.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nURL-based elicitation mode where the client directs the user to a URL.",
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
],
|
||||
{ mode: "oneOf" },
|
||||
).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.",
|
||||
});
|
||||
}).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.",
|
||||
}),
|
||||
Schema.Struct({
|
||||
mode: Schema.Literal("url"),
|
||||
elicitationId: Schema.String.annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nUnique identifier for an elicitation.",
|
||||
}),
|
||||
url: Schema.String.annotate({ description: "The URL to direct the user to.", format: "uri" }),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
message: Schema.String.annotate({
|
||||
description: "A human-readable message describing what input is needed.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
}).annotate({
|
||||
description:
|
||||
"**UNSTABLE**\n\nThis capability is not part of the spec yet, and may be removed or changed at any point.\n\nRequest from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.",
|
||||
}),
|
||||
]);
|
||||
|
||||
export type ElicitationResponse = {
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
@@ -7801,17 +7986,6 @@ export const SessionConfigId = Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option.",
|
||||
});
|
||||
|
||||
export type SessionConfigOptionCategory = "mode" | "model" | "thought_level" | string;
|
||||
export const SessionConfigOptionCategory = Schema.Union([
|
||||
Schema.Literal("mode").annotate({ description: "Session mode selector." }),
|
||||
Schema.Literal("model").annotate({ description: "Model selector." }),
|
||||
Schema.Literal("thought_level").annotate({ description: "Thought/reasoning level selector." }),
|
||||
Schema.String.annotate({ title: "other", description: "Unknown / uncategorized selector." }),
|
||||
]).annotate({
|
||||
description:
|
||||
"Semantic category for a session configuration option.\n\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\ncategories gracefully.\n\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\nCategory names that do not begin with `_` are reserved for the ACP spec.",
|
||||
});
|
||||
|
||||
export type SessionConfigSelect = {
|
||||
readonly currentValue: string;
|
||||
readonly options:
|
||||
@@ -9533,23 +9707,65 @@ export const SessionUpdate = Schema.Union(
|
||||
});
|
||||
|
||||
export type SetSessionConfigOptionRequest =
|
||||
| { readonly type: "boolean"; readonly value: boolean }
|
||||
| { readonly value: string };
|
||||
| {
|
||||
readonly type: "boolean";
|
||||
readonly value: boolean;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly configId: string;
|
||||
readonly sessionId: string;
|
||||
}
|
||||
| {
|
||||
readonly value: string;
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
readonly configId: string;
|
||||
readonly sessionId: string;
|
||||
};
|
||||
export const SetSessionConfigOptionRequest = Schema.Union([
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("boolean"),
|
||||
value: Schema.Boolean.annotate({ description: "The boolean value." }),
|
||||
}).annotate({ description: 'A boolean value (`type: "boolean"`).' }),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
configId: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
}).annotate({ description: "Request parameters for setting a session configuration option." }),
|
||||
Schema.Struct({
|
||||
value: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option value.",
|
||||
}),
|
||||
_meta: Schema.optionalKey(
|
||||
Schema.Union([
|
||||
Schema.Record(Schema.String, Schema.Unknown).annotate({
|
||||
description:
|
||||
"The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)",
|
||||
}),
|
||||
Schema.Null,
|
||||
]),
|
||||
),
|
||||
configId: Schema.String.annotate({
|
||||
description: "Unique identifier for a session configuration option.",
|
||||
}),
|
||||
sessionId: Schema.String.annotate({
|
||||
description:
|
||||
"A unique identifier for a conversation session between a client and agent.\n\nSessions maintain their own context, conversation history, and state,\nallowing multiple independent interactions with the same agent.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)",
|
||||
}),
|
||||
}).annotate({
|
||||
title: "value_id",
|
||||
description:
|
||||
"A [`SessionConfigValueId`] string value.\n\nThis is the default when `type` is absent on the wire. Unknown `type`\nvalues with string payloads also gracefully deserialize into this\nvariant.",
|
||||
description: "Request parameters for setting a session configuration option.",
|
||||
}),
|
||||
]).annotate({ description: "Request parameters for setting a session configuration option." });
|
||||
]);
|
||||
|
||||
export type SetSessionConfigOptionResponse = {
|
||||
readonly _meta?: { readonly [x: string]: unknown } | null;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
@@ -9,11 +10,13 @@ export function makeStdioFromChildProcess(
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
): Stdio.Stdio {
|
||||
return Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
stdin: handle.stdout,
|
||||
stdout: Sink.mapInput(handle.stdin, (chunk) =>
|
||||
typeof chunk === "string" ? textEncoder.encode(chunk) : chunk,
|
||||
),
|
||||
stderr: Sink.drain,
|
||||
stdout: () =>
|
||||
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
|
||||
typeof chunk === "string" ? textEncoder.encode(chunk) : chunk,
|
||||
),
|
||||
stderr: () => Sink.drain,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Path from "effect/Path";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -18,6 +19,8 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* Ref.make<Array<unknown>>([]);
|
||||
const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
|
||||
const typedRequests = yield* Ref.make<Array<unknown>>([]);
|
||||
const typedNotifications = yield* Ref.make<Array<unknown>>([]);
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
@@ -49,6 +52,24 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
Ref.update(updates, (current) => [...current, notification]),
|
||||
elicitationComplete: (notification) =>
|
||||
Ref.update(elicitationCompletions, (current) => [...current, notification]),
|
||||
extRequests: {
|
||||
"x/typed_request": AcpClient.defineExtRequest(
|
||||
Schema.Struct({ message: Schema.String }),
|
||||
(payload) =>
|
||||
Ref.update(typedRequests, (current) => [...current, payload]).pipe(
|
||||
Effect.as({
|
||||
ok: true,
|
||||
echoedMessage: payload.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
},
|
||||
extNotifications: {
|
||||
"x/typed_notification": AcpClient.defineExtNotification(
|
||||
Schema.Struct({ count: Schema.Number }),
|
||||
(payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -85,6 +106,8 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
|
||||
assert.equal(streamed[1]?._tag, "ElicitationComplete");
|
||||
assert.equal((yield* Ref.get(updates)).length, 1);
|
||||
assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
|
||||
assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
|
||||
assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
|
||||
|
||||
const ext = yield* client.extRequest("x/echo", {
|
||||
hello: "world",
|
||||
|
||||
@@ -14,6 +14,26 @@ import * as AcpSchema from "./_generated/schema.gen";
|
||||
import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
export interface AcpExtensionRequestRegistration<A> {
|
||||
readonly payload: Schema.Schema<A>;
|
||||
readonly handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export interface AcpExtensionNotificationRegistration<A> {
|
||||
readonly payload: Schema.Schema<A>;
|
||||
readonly handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>;
|
||||
}
|
||||
|
||||
export const defineExtRequest = <A>(
|
||||
payload: Schema.Schema<A>,
|
||||
handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
|
||||
): AcpExtensionRequestRegistration<A> => ({ payload, handler });
|
||||
|
||||
export const defineExtNotification = <A>(
|
||||
payload: Schema.Schema<A>,
|
||||
handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
|
||||
): AcpExtensionNotificationRegistration<A> => ({ payload, handler });
|
||||
|
||||
export interface AcpClientHandlers {
|
||||
/**
|
||||
* Handles `session/request_permission`.
|
||||
@@ -100,6 +120,10 @@ export interface AcpClientHandlers {
|
||||
method: string,
|
||||
params: unknown,
|
||||
) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
/**
|
||||
* Handles extension requests outside the core ACP method set using typed payload decoders.
|
||||
*/
|
||||
readonly extRequests?: Readonly<Record<string, AcpExtensionRequestRegistration<any>>>;
|
||||
/**
|
||||
* Handles extension notifications outside the core ACP method set.
|
||||
* @see https://agentclientprotocol.com/protocol/extensibility
|
||||
@@ -108,6 +132,10 @@ export interface AcpClientHandlers {
|
||||
method: string,
|
||||
params: unknown,
|
||||
) => Effect.Effect<void, AcpError.AcpError>;
|
||||
/**
|
||||
* Handles extension notifications outside the core ACP method set using typed payload decoders.
|
||||
*/
|
||||
readonly extNotifications?: Readonly<Record<string, AcpExtensionNotificationRegistration<any>>>;
|
||||
}
|
||||
|
||||
export interface AcpClientConnectOptions {
|
||||
@@ -257,16 +285,29 @@ export const fromChildProcess = Effect.fnUntraced(function* (
|
||||
? handlers.elicitationComplete(notification.params)
|
||||
: Effect.void;
|
||||
case "ExtNotification":
|
||||
return handlers.extNotification
|
||||
? handlers.extNotification(notification.method, notification.params)
|
||||
: Effect.void;
|
||||
return runExtNotificationHandler(
|
||||
handlers.extNotifications?.[notification.method],
|
||||
handlers.extNotification,
|
||||
notification.method,
|
||||
notification.params,
|
||||
);
|
||||
case "SessionCancel":
|
||||
return handlers.extNotification
|
||||
? handlers.extNotification(notification.method, notification.params)
|
||||
: Effect.void;
|
||||
}
|
||||
},
|
||||
...(handlers.extRequest ? { onExtRequest: handlers.extRequest } : {}),
|
||||
...(handlers.extRequest || handlers.extRequests
|
||||
? {
|
||||
onExtRequest: (method: string, params: unknown) =>
|
||||
runExtRequestHandler(
|
||||
handlers.extRequests?.[method],
|
||||
handlers.extRequest,
|
||||
method,
|
||||
params,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer(
|
||||
@@ -354,3 +395,52 @@ const runHandler = Effect.fnUntraced(function* <A, B>(
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const decodeUnknownWith = <A>(
|
||||
schema: Schema.Schema<A>,
|
||||
payload: unknown,
|
||||
): Effect.Effect<A, AcpError.AcpError> =>
|
||||
Effect.try({
|
||||
try: () => Schema.decodeUnknownSync(schema as never)(payload) as A,
|
||||
catch: (cause) =>
|
||||
new AcpError.AcpProtocolParseError({
|
||||
detail: "Failed to decode typed ACP extension payload",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const runExtRequestHandler = <A>(
|
||||
registration: AcpExtensionRequestRegistration<A> | undefined,
|
||||
fallback:
|
||||
| ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
|
||||
| undefined,
|
||||
method: string,
|
||||
params: unknown,
|
||||
): Effect.Effect<unknown, AcpError.AcpError> => {
|
||||
if (registration) {
|
||||
return decodeUnknownWith(registration.payload, params).pipe(
|
||||
Effect.mapError(() => AcpError.AcpRequestError.invalidParams(`Invalid ${method} payload`)),
|
||||
Effect.flatMap((payload) => registration.handler(payload)),
|
||||
);
|
||||
}
|
||||
if (fallback) {
|
||||
return fallback(method, params);
|
||||
}
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
};
|
||||
|
||||
const runExtNotificationHandler = <A>(
|
||||
registration: AcpExtensionNotificationRegistration<A> | undefined,
|
||||
fallback:
|
||||
| ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
|
||||
| undefined,
|
||||
method: string,
|
||||
params: unknown,
|
||||
): Effect.Effect<void, AcpError.AcpError> => {
|
||||
if (registration) {
|
||||
return decodeUnknownWith(registration.payload, params).pipe(
|
||||
Effect.flatMap((payload) => registration.handler(payload)),
|
||||
);
|
||||
}
|
||||
return fallback ? fallback(method, params) : Effect.void;
|
||||
};
|
||||
@@ -21,11 +21,13 @@ function makeInMemoryStdio() {
|
||||
|
||||
return {
|
||||
stdio: Stdio.make({
|
||||
args: Effect.succeed([]),
|
||||
stdin: Stream.fromQueue(input),
|
||||
stdout: Sink.forEach((chunk: string | Uint8Array) =>
|
||||
Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),
|
||||
),
|
||||
stderr: Sink.drain,
|
||||
stdout: () =>
|
||||
Sink.forEach((chunk: string | Uint8Array) =>
|
||||
Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),
|
||||
),
|
||||
stderr: () => Sink.drain,
|
||||
}),
|
||||
input,
|
||||
output,
|
||||
|
||||
@@ -44,12 +44,14 @@ export interface AcpPatchedProtocolOptions {
|
||||
readonly serverRequestMethods: ReadonlySet<string>;
|
||||
readonly onNotification?: (
|
||||
notification: AcpIncomingNotification,
|
||||
) => Effect.Effect<void, AcpError.AcpError>;
|
||||
) => Effect.Effect<void, AcpError.AcpError, never>;
|
||||
readonly onExtRequest?: (
|
||||
method: string,
|
||||
params: unknown,
|
||||
) => Effect.Effect<unknown, AcpError.AcpError>;
|
||||
readonly onProcessExit?: (error: AcpError.AcpProcessExitedError) => Effect.Effect<void>;
|
||||
) => Effect.Effect<unknown, AcpError.AcpError, never>;
|
||||
readonly onProcessExit?: (
|
||||
error: AcpError.AcpProcessExitedError,
|
||||
) => Effect.Effect<void, never, never>;
|
||||
}
|
||||
|
||||
export interface AcpPatchedProtocol {
|
||||
@@ -376,7 +378,7 @@ export const makeAcpPatchedProtocol = (
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout), Effect.forkScoped);
|
||||
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
|
||||
|
||||
const clientProtocol = RpcClient.Protocol.of({
|
||||
run: (f) =>
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export * from "./_generated/schema.gen.ts";
|
||||
export * from "./_generated/meta.gen.ts";
|
||||
export * from "./_generated/schema.gen";
|
||||
export * from "./_generated/meta.gen";
|
||||
@@ -47,7 +47,12 @@ Effect.gen(function* () {
|
||||
|
||||
const result = yield* client.prompt({
|
||||
sessionId: session.sessionId,
|
||||
prompt: [{ type: "text", text: "Summarize this repository." }],
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Illustrate your ability to create todo lists and then execute all of them. Do not write the list to disk, illustrate your built in ability!",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* Effect.logInfo("prompt result", result);
|
||||
|
||||
@@ -122,6 +122,8 @@ async function handleRequest(message: {
|
||||
});
|
||||
|
||||
await requestClient("session/elicitation", {
|
||||
sessionId: "mock-session-1",
|
||||
message: "Need confirmation before continuing.",
|
||||
mode: "form",
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
@@ -154,6 +156,14 @@ async function handleRequest(message: {
|
||||
elicitationId: "elicitation-1",
|
||||
});
|
||||
|
||||
await requestClient("x/typed_request", {
|
||||
message: "hello from typed request",
|
||||
});
|
||||
|
||||
notify("x/typed_notification", {
|
||||
count: 2,
|
||||
});
|
||||
|
||||
respond(message.id, {
|
||||
stopReason: "end_turn",
|
||||
});
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
diff --git a/src/SchemaRepresentation.ts b/src/SchemaRepresentation.ts
|
||||
index e1a87e2b..a7797678 100644
|
||||
--- a/src/SchemaRepresentation.ts
|
||||
+++ b/src/SchemaRepresentation.ts
|
||||
@@ -3007,7 +3007,14 @@ export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<"
|
||||
}
|
||||
}
|
||||
|
||||
- let out = on(js)
|
||||
+ const hasAnyOf = Array.isArray(js.anyOf)
|
||||
+ const hasOneOf = Array.isArray(js.oneOf)
|
||||
+ const base =
|
||||
+ hasAnyOf || hasOneOf
|
||||
+ ? ({ ...js, anyOf: undefined, oneOf: undefined } as JsonSchema.JsonSchema)
|
||||
+ : js
|
||||
+
|
||||
+ let out = on(base)
|
||||
|
||||
const annotations = collectAnnotations(js)
|
||||
if (annotations !== undefined) {
|
||||
@@ -3018,6 +3025,14 @@ export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<"
|
||||
return js.allOf.reduce((acc, curr) => combine(acc, recur(curr)), out)
|
||||
}
|
||||
|
||||
+ if (hasAnyOf) {
|
||||
+ out = combine({ _tag: "Union", types: js.anyOf.map((type) => recur(type)), mode: "anyOf" }, out)
|
||||
+ }
|
||||
+
|
||||
+ if (hasOneOf) {
|
||||
+ out = combine({ _tag: "Union", types: js.oneOf.map((type) => recur(type)), mode: "oneOf" }, out)
|
||||
+ }
|
||||
+
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -3054,12 +3069,7 @@ export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<"
|
||||
} else {
|
||||
return { _tag: "Union", types, mode: "anyOf" }
|
||||
}
|
||||
- } else if (Array.isArray(js.anyOf)) {
|
||||
- return { _tag: "Union", types: js.anyOf.map((type) => recur(type)), mode: "anyOf" }
|
||||
- } else if (Array.isArray(js.oneOf)) {
|
||||
- return { _tag: "Union", types: js.oneOf.map((type) => recur(type)), mode: "oneOf" }
|
||||
}
|
||||
-
|
||||
const type = isType(js.type) ? js.type : getType(js)
|
||||
if (type !== undefined) {
|
||||
switch (type) {
|
||||
diff --git a/dist/SchemaRepresentation.js b/dist/SchemaRepresentation.js
|
||||
index 0d3f01d7..c3672558 100644
|
||||
--- a/dist/SchemaRepresentation.js
|
||||
+++ b/dist/SchemaRepresentation.js
|
||||
@@ -2042,7 +2042,14 @@ export function fromJsonSchemaMultiDocument(document, options) {
|
||||
js = {};
|
||||
}
|
||||
}
|
||||
- let out = on(js);
|
||||
+ const hasAnyOf = Array.isArray(js.anyOf);
|
||||
+ const hasOneOf = Array.isArray(js.oneOf);
|
||||
+ const base = hasAnyOf || hasOneOf ? {
|
||||
+ ...js,
|
||||
+ anyOf: undefined,
|
||||
+ oneOf: undefined
|
||||
+ } : js;
|
||||
+ let out = on(base);
|
||||
const annotations = collectAnnotations(js);
|
||||
if (annotations !== undefined) {
|
||||
out = combine(out, {
|
||||
@@ -2053,6 +2060,20 @@ export function fromJsonSchemaMultiDocument(document, options) {
|
||||
if (Array.isArray(js.allOf)) {
|
||||
return js.allOf.reduce((acc, curr) => combine(acc, recur(curr)), out);
|
||||
}
|
||||
+ if (hasAnyOf) {
|
||||
+ out = combine({
|
||||
+ _tag: "Union",
|
||||
+ types: js.anyOf.map(type => recur(type)),
|
||||
+ mode: "anyOf"
|
||||
+ }, out);
|
||||
+ }
|
||||
+ if (hasOneOf) {
|
||||
+ out = combine({
|
||||
+ _tag: "Union",
|
||||
+ types: js.oneOf.map(type => recur(type)),
|
||||
+ mode: "oneOf"
|
||||
+ }, out);
|
||||
+ }
|
||||
return out;
|
||||
}
|
||||
function on(js) {
|
||||
@@ -2105,18 +2126,6 @@ export function fromJsonSchemaMultiDocument(document, options) {
|
||||
mode: "anyOf"
|
||||
};
|
||||
}
|
||||
- } else if (Array.isArray(js.anyOf)) {
|
||||
- return {
|
||||
- _tag: "Union",
|
||||
- types: js.anyOf.map(type => recur(type)),
|
||||
- mode: "anyOf"
|
||||
- };
|
||||
- } else if (Array.isArray(js.oneOf)) {
|
||||
- return {
|
||||
- _tag: "Union",
|
||||
- types: js.oneOf.map(type => recur(type)),
|
||||
- mode: "oneOf"
|
||||
- };
|
||||
}
|
||||
const type = isType(js.type) ? js.type : getType(js);
|
||||
if (type !== undefined) {
|
||||
Reference in new issue
Block a user