forked from agentclientprotocol/typescript-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
172 lines (148 loc) · 4.69 KB
/
client.ts
File metadata and controls
172 lines (148 loc) · 4.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { Writable, Readable } from "node:stream";
import readline from "node:readline/promises";
import * as acp from "../acp.js";
class ExampleClient implements acp.Client {
async requestPermission(
params: acp.RequestPermissionRequest,
): Promise<acp.RequestPermissionResponse> {
console.log(`\n🔐 Permission requested: ${params.toolCall.title}`);
console.log(`\nOptions:`);
params.options.forEach((option, index) => {
console.log(` ${index + 1}. ${option.name} (${option.kind})`);
});
while (true) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const answer = await rl.question("\nChoose an option: ");
const trimmedAnswer = answer.trim();
const optionIndex = parseInt(trimmedAnswer) - 1;
if (optionIndex >= 0 && optionIndex < params.options.length) {
return {
outcome: {
outcome: "selected",
optionId: params.options[optionIndex].optionId,
},
};
} else {
console.log("Invalid option. Please try again.");
}
}
}
async sessionUpdate(params: acp.SessionNotification): Promise<void> {
const update = params.update;
switch (update.sessionUpdate) {
case "agent_message_chunk":
if (update.content.type === "text") {
console.log(update.content.text);
} else {
console.log(`[${update.content.type}]`);
}
break;
case "agent_message_clear":
// Client should clear accumulated streamed content for current agent message.
console.log(`[${update.sessionUpdate}]`);
break;
case "tool_call":
console.log(`\n🔧 ${update.title} (${update.status})`);
break;
case "tool_call_update":
console.log(
`\n🔧 Tool call \`${update.toolCallId}\` updated: ${update.status}\n`,
);
break;
case "plan":
case "agent_thought_chunk":
case "user_message_chunk":
console.log(`[${update.sessionUpdate}]`);
break;
default:
break;
}
}
async writeTextFile(
params: acp.WriteTextFileRequest,
): Promise<acp.WriteTextFileResponse> {
console.error(
"[Client] Write text file called with:",
JSON.stringify(params, null, 2),
);
return {};
}
async readTextFile(
params: acp.ReadTextFileRequest,
): Promise<acp.ReadTextFileResponse> {
console.error(
"[Client] Read text file called with:",
JSON.stringify(params, null, 2),
);
return {
content: "Mock file content",
};
}
}
async function main() {
// Get the current file's directory to find agent.ts
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const agentPath = join(__dirname, "agent.ts");
// Spawn the agent as a subprocess via npx (npx.cmd on Windows) using tsx
const npxCmd = process.platform === "win32" ? "npx.cmd" : "npx";
const agentProcess = spawn(npxCmd, ["tsx", agentPath], {
stdio: ["pipe", "pipe", "inherit"],
});
// Create streams to communicate with the agent
const input = Writable.toWeb(agentProcess.stdin!);
const output = Readable.toWeb(
agentProcess.stdout!,
) as ReadableStream<Uint8Array>;
// Create the client connection
const client = new ExampleClient();
const stream = acp.ndJsonStream(input, output);
const connection = new acp.ClientSideConnection((_agent) => client, stream);
try {
// Initialize the connection
const initResult = await connection.initialize({
protocolVersion: acp.PROTOCOL_VERSION,
clientCapabilities: {
fs: {
readTextFile: true,
writeTextFile: true,
},
},
});
console.log(
`✅ Connected to agent (protocol v${initResult.protocolVersion})`,
);
// Create a new session
const sessionResult = await connection.newSession({
cwd: process.cwd(),
mcpServers: [],
});
console.log(`📝 Created session: ${sessionResult.sessionId}`);
console.log(`💬 User: Hello, agent!\n`);
process.stdout.write(" ");
// Send a test prompt
const promptResult = await connection.prompt({
sessionId: sessionResult.sessionId,
prompt: [
{
type: "text",
text: "Hello, agent!",
},
],
});
console.log(`\n\n✅ Agent completed with: ${promptResult.stopReason}`);
} catch (error) {
console.error("[Client] Error:", error);
} finally {
agentProcess.kill();
process.exit(0);
}
}
main().catch(console.error);