@trans-ai/trans-code 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +203 -2
- package/bin/transcode.ts +4 -0
- package/docs/ACP.md +231 -0
- package/package.json +42 -4
- package/src/acp/protocol.ts +115 -0
- package/src/acp/server.ts +202 -0
- package/src/acp/session.ts +269 -0
- package/src/acp/transport.ts +216 -0
- package/src/agent/loop.ts +334 -0
- package/src/agent/system-prompt.ts +86 -0
- package/src/agent/tools.ts +483 -0
- package/src/cli.ts +53 -0
- package/src/commands.ts +61 -0
- package/src/main.tsx +62 -0
- package/src/provider/provider.ts +373 -0
- package/src/screens/REPL.tsx +282 -0
- package/src/tui/cli.tsx +2 -0
- package/src/tui/keyed-stdin.ts +83 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs';
|
|
2
|
+
import { RPC_ERRORS, RpcError, JsonRpcTransport } from './transport.js';
|
|
3
|
+
import { AcpSession, sessionCwd, sessionNewResult, type AcpSessionHost } from './session.js';
|
|
4
|
+
import { VERSION } from '../version.js';
|
|
5
|
+
import type {
|
|
6
|
+
AcpPermissionRequest,
|
|
7
|
+
AcpPermissionResponse,
|
|
8
|
+
AcpPromptBlock,
|
|
9
|
+
AcpPromptParams,
|
|
10
|
+
AcpSessionNewParams,
|
|
11
|
+
AcpSessionUpdate,
|
|
12
|
+
} from './protocol.js';
|
|
13
|
+
|
|
14
|
+
function asRecord(value: unknown): Record<string, unknown> {
|
|
15
|
+
return value && typeof value === 'object' ? (value as Record<string, unknown>) : {};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function requireString(params: Record<string, unknown>, key: string): string {
|
|
19
|
+
const value = params[key];
|
|
20
|
+
if (typeof value !== 'string' || !value) {
|
|
21
|
+
throw new RpcError(RPC_ERRORS.invalidParams, `Missing or invalid "${key}"`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class AcpServer implements AcpSessionHost {
|
|
27
|
+
private readonly sessions = new Map<string, AcpSession>();
|
|
28
|
+
|
|
29
|
+
constructor(private readonly transport: JsonRpcTransport) {
|
|
30
|
+
transport.setHandlers(
|
|
31
|
+
(method, params) => this.handleRequest(method, params),
|
|
32
|
+
(method, params) => this.handleNotification(method, params),
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
sendUpdate(sessionId: string, update: AcpSessionUpdate): void {
|
|
37
|
+
this.transport.notify('session/update', { sessionId, update });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async requestPermission(
|
|
41
|
+
request: AcpPermissionRequest,
|
|
42
|
+
signal?: AbortSignal,
|
|
43
|
+
): Promise<AcpPermissionResponse> {
|
|
44
|
+
const result = await this.transport.request('session/request_permission', request, {
|
|
45
|
+
timeoutMs: 60_000,
|
|
46
|
+
signal,
|
|
47
|
+
});
|
|
48
|
+
return result as AcpPermissionResponse;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
shutdown(): void {
|
|
52
|
+
for (const session of this.sessions.values()) session.cancel();
|
|
53
|
+
this.sessions.clear();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
private getSession(sessionId: string): AcpSession {
|
|
57
|
+
const session = this.sessions.get(sessionId);
|
|
58
|
+
if (!session) {
|
|
59
|
+
throw new RpcError(RPC_ERRORS.sessionNotFound, `Session not found: ${sessionId}`);
|
|
60
|
+
}
|
|
61
|
+
return session;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private async handleRequest(method: string, rawParams: unknown): Promise<unknown> {
|
|
65
|
+
const params = asRecord(rawParams);
|
|
66
|
+
|
|
67
|
+
switch (method) {
|
|
68
|
+
case 'initialize':
|
|
69
|
+
return {
|
|
70
|
+
protocolVersion: 1,
|
|
71
|
+
agentInfo: { name: 'transcode', version: VERSION },
|
|
72
|
+
agentCapabilities: {
|
|
73
|
+
loadSession: false,
|
|
74
|
+
promptCapabilities: {
|
|
75
|
+
image: false,
|
|
76
|
+
audio: false,
|
|
77
|
+
embeddedContext: false,
|
|
78
|
+
},
|
|
79
|
+
mcpCapabilities: {
|
|
80
|
+
http: false,
|
|
81
|
+
sse: false,
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
authMethods: [],
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
case 'authenticate':
|
|
88
|
+
return null;
|
|
89
|
+
|
|
90
|
+
case 'session/new':
|
|
91
|
+
return await this.createSession(params as AcpSessionNewParams);
|
|
92
|
+
|
|
93
|
+
case 'session/load':
|
|
94
|
+
case 'session/resume': {
|
|
95
|
+
const sessionId = requireString(params, 'sessionId');
|
|
96
|
+
return sessionNewResult(this.getSession(sessionId));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
case 'session/prompt': {
|
|
100
|
+
const sessionId = requireString(params, 'sessionId');
|
|
101
|
+
const prompt = Array.isArray(params.prompt)
|
|
102
|
+
? (params.prompt as AcpPromptBlock[])
|
|
103
|
+
: [];
|
|
104
|
+
return await this.getSession(sessionId).prompt({
|
|
105
|
+
sessionId,
|
|
106
|
+
prompt,
|
|
107
|
+
} satisfies AcpPromptParams);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
case 'session/set_model': {
|
|
111
|
+
const sessionId = requireString(params, 'sessionId');
|
|
112
|
+
const modelId = requireString(params, 'modelId');
|
|
113
|
+
const models = this.getSession(sessionId).setModel(modelId);
|
|
114
|
+
return { models };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
case 'session/cancel': {
|
|
118
|
+
const sessionId = requireString(params, 'sessionId');
|
|
119
|
+
this.sessions.get(sessionId)?.cancel();
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// transcode advertises no MCP capability in the MVP; accept the call so a
|
|
124
|
+
// client probing it does not turn a harmless request into a task failure.
|
|
125
|
+
case 'session/set_config_option': {
|
|
126
|
+
return {};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
default:
|
|
130
|
+
throw new RpcError(RPC_ERRORS.methodNotFound, `Method not found: ${method}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private async handleNotification(method: string, rawParams: unknown): Promise<void> {
|
|
135
|
+
if (method !== 'session/cancel' && method !== '$/cancelRequest') return;
|
|
136
|
+
|
|
137
|
+
const params = asRecord(rawParams);
|
|
138
|
+
const sessionId = params.sessionId;
|
|
139
|
+
if (typeof sessionId === 'string') {
|
|
140
|
+
this.sessions.get(sessionId)?.cancel();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private async createSession(params: AcpSessionNewParams): Promise<unknown> {
|
|
145
|
+
const cwd = sessionCwd(params.cwd);
|
|
146
|
+
|
|
147
|
+
let stat;
|
|
148
|
+
try {
|
|
149
|
+
stat = await fs.stat(cwd);
|
|
150
|
+
} catch {
|
|
151
|
+
throw new RpcError(RPC_ERRORS.invalidParams, `cwd does not exist: ${cwd}`);
|
|
152
|
+
}
|
|
153
|
+
if (!stat.isDirectory()) {
|
|
154
|
+
throw new RpcError(RPC_ERRORS.invalidParams, `cwd is not a directory: ${cwd}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (Array.isArray(params.mcpServers) && params.mcpServers.length > 0) {
|
|
158
|
+
process.stderr.write(
|
|
159
|
+
`[transcode] ignoring ${params.mcpServers.length} MCP server(s); MCP is not supported in this MVP\n`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const model = typeof params.model === 'string' ? params.model : undefined;
|
|
164
|
+
const session = new AcpSession(this, cwd, model);
|
|
165
|
+
this.sessions.set(session.id, session);
|
|
166
|
+
process.stderr.write(
|
|
167
|
+
`[transcode] session ${session.id} created cwd=${cwd} model=${session.modelState.currentModelId}\n`,
|
|
168
|
+
);
|
|
169
|
+
return sessionNewResult(session);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function runAcpServer(): Promise<void> {
|
|
174
|
+
// stdout is the JSON-RPC channel. Any library that calls console.log must not
|
|
175
|
+
// corrupt it, so route console output to stderr for the lifetime of the server.
|
|
176
|
+
for (const method of ['log', 'info', 'debug', 'dir', 'table'] as const) {
|
|
177
|
+
(console as unknown as Record<string, (...args: unknown[]) => void>)[method] = (
|
|
178
|
+
...args: unknown[]
|
|
179
|
+
) => console.error(...args);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const transport = new JsonRpcTransport();
|
|
183
|
+
const server = new AcpServer(transport);
|
|
184
|
+
|
|
185
|
+
const shutdown = () => {
|
|
186
|
+
server.shutdown();
|
|
187
|
+
transport.close();
|
|
188
|
+
process.exit(0);
|
|
189
|
+
};
|
|
190
|
+
process.once('SIGINT', shutdown);
|
|
191
|
+
process.once('SIGTERM', shutdown);
|
|
192
|
+
|
|
193
|
+
process.stderr.write(`[transcode] ACP server ready (v${VERSION})\n`);
|
|
194
|
+
|
|
195
|
+
await new Promise<void>((resolve) => {
|
|
196
|
+
process.stdin.once('end', resolve);
|
|
197
|
+
process.stdin.once('close', resolve);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
server.shutdown();
|
|
201
|
+
transport.close();
|
|
202
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {
|
|
4
|
+
AIMessage,
|
|
5
|
+
HumanMessage,
|
|
6
|
+
SystemMessage,
|
|
7
|
+
type BaseMessage,
|
|
8
|
+
} from '@langchain/core/messages';
|
|
9
|
+
import { createModel, getAvailableModels, resolveModel } from '../provider/provider.js';
|
|
10
|
+
import { runAgentLoop, type AgentEvent, type PermissionRequest } from '../agent/loop.js';
|
|
11
|
+
import { buildSystemPrompt, loadProjectContext } from '../agent/system-prompt.js';
|
|
12
|
+
import {
|
|
13
|
+
RPC_ERRORS,
|
|
14
|
+
RpcError,
|
|
15
|
+
} from './transport.js';
|
|
16
|
+
import type {
|
|
17
|
+
AcpModelInfo,
|
|
18
|
+
AcpPermissionRequest,
|
|
19
|
+
AcpPermissionResponse,
|
|
20
|
+
AcpPromptBlock,
|
|
21
|
+
AcpPromptParams,
|
|
22
|
+
AcpPromptResult,
|
|
23
|
+
AcpSessionModelState,
|
|
24
|
+
AcpSessionNewResult,
|
|
25
|
+
AcpSessionUpdate,
|
|
26
|
+
AcpStopReason,
|
|
27
|
+
} from './protocol.js';
|
|
28
|
+
|
|
29
|
+
export interface AcpSessionHost {
|
|
30
|
+
sendUpdate(sessionId: string, update: AcpSessionUpdate): void;
|
|
31
|
+
requestPermission(
|
|
32
|
+
request: AcpPermissionRequest,
|
|
33
|
+
signal?: AbortSignal,
|
|
34
|
+
): Promise<AcpPermissionResponse>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const MAX_TOOL_OUTPUT_IN_UPDATE = 20_000;
|
|
38
|
+
|
|
39
|
+
function modelCatalog(currentId: string): AcpModelInfo[] {
|
|
40
|
+
const models: AcpModelInfo[] = getAvailableModels().map((model) => ({
|
|
41
|
+
modelId: model.id,
|
|
42
|
+
name: model.name,
|
|
43
|
+
}));
|
|
44
|
+
if (!models.some((model) => model.modelId === currentId)) {
|
|
45
|
+
models.unshift({ modelId: currentId, name: currentId });
|
|
46
|
+
}
|
|
47
|
+
return models;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function promptText(prompt: AcpPromptBlock[]): string {
|
|
51
|
+
return prompt
|
|
52
|
+
.map((block) => {
|
|
53
|
+
if (block.type === 'text') return block.text ?? '';
|
|
54
|
+
if (block.type === 'resource_link') {
|
|
55
|
+
return `[resource: ${String(block.uri ?? block.name ?? 'unknown')}]`;
|
|
56
|
+
}
|
|
57
|
+
if (block.type === 'resource') {
|
|
58
|
+
return `[embedded resource${block.uri ? `: ${String(block.uri)}` : ''}]`;
|
|
59
|
+
}
|
|
60
|
+
return '';
|
|
61
|
+
})
|
|
62
|
+
.filter(Boolean)
|
|
63
|
+
.join('\n')
|
|
64
|
+
.trim();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function permissionMode(): 'ask' | 'auto' | 'readonly' {
|
|
68
|
+
const value = (process.env.TRANSCODE_PERMISSION_MODE ?? 'ask').toLowerCase();
|
|
69
|
+
if (value === 'auto' || value === 'readonly') return value;
|
|
70
|
+
return 'ask';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class AcpSession {
|
|
74
|
+
readonly id = `ses_${randomUUID()}`;
|
|
75
|
+
readonly messages: BaseMessage[] = [];
|
|
76
|
+
private busy = false;
|
|
77
|
+
private abortController?: AbortController;
|
|
78
|
+
private modelSpec: string;
|
|
79
|
+
|
|
80
|
+
constructor(
|
|
81
|
+
private readonly host: AcpSessionHost,
|
|
82
|
+
readonly cwd: string,
|
|
83
|
+
modelSpec?: string,
|
|
84
|
+
) {
|
|
85
|
+
this.modelSpec = modelSpec?.trim() || process.env.TRANSCODE_MODEL || '';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
get modelState(): AcpSessionModelState {
|
|
89
|
+
const resolved = resolveModel(this.modelSpec);
|
|
90
|
+
return {
|
|
91
|
+
availableModels: modelCatalog(resolved.id),
|
|
92
|
+
currentModelId: resolved.id,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
setModel(modelId: string): AcpSessionModelState {
|
|
97
|
+
const trimmed = modelId.trim();
|
|
98
|
+
if (!trimmed) throw new RpcError(RPC_ERRORS.invalidParams, 'modelId is required');
|
|
99
|
+
this.modelSpec = trimmed;
|
|
100
|
+
return this.modelState;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
cancel(): void {
|
|
104
|
+
this.abortController?.abort();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async prompt(params: AcpPromptParams): Promise<AcpPromptResult> {
|
|
108
|
+
if (this.busy) {
|
|
109
|
+
throw new RpcError(-32000, 'Session is already processing a prompt');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const text = promptText(params.prompt ?? []);
|
|
113
|
+
if (!text) return { stopReason: 'end_turn' };
|
|
114
|
+
|
|
115
|
+
this.busy = true;
|
|
116
|
+
this.abortController = new AbortController();
|
|
117
|
+
const signal = this.abortController.signal;
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
const systemPrompt = buildSystemPrompt(await loadProjectContext(this.cwd));
|
|
121
|
+
if (this.messages[0]?.getType() === 'system') {
|
|
122
|
+
this.messages[0] = new SystemMessage(systemPrompt);
|
|
123
|
+
} else {
|
|
124
|
+
this.messages.unshift(new SystemMessage(systemPrompt));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
this.messages.push(new HumanMessage(text));
|
|
128
|
+
|
|
129
|
+
const provider =
|
|
130
|
+
process.env.TRANSCODE_MOCK === '1' ? undefined : createModel(this.modelSpec);
|
|
131
|
+
const result = await runAgentLoop({
|
|
132
|
+
model: provider?.model,
|
|
133
|
+
cwd: this.cwd,
|
|
134
|
+
messages: this.messages,
|
|
135
|
+
systemPrompt,
|
|
136
|
+
signal,
|
|
137
|
+
onEvent: (event) => this.forwardEvent(event),
|
|
138
|
+
requestPermission: (request) => this.askPermission(request, signal),
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
this.trimHistory();
|
|
142
|
+
return { stopReason: result.stopReason as AcpStopReason };
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (signal.aborted) return { stopReason: 'cancelled' };
|
|
145
|
+
|
|
146
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
147
|
+
const errorText = `[transcode error] ${message}`;
|
|
148
|
+
this.messages.push(new AIMessage({ content: errorText }));
|
|
149
|
+
this.host.sendUpdate(this.id, {
|
|
150
|
+
sessionUpdate: 'agent_message_chunk',
|
|
151
|
+
content: { type: 'text', text: `\n${errorText}\n` },
|
|
152
|
+
});
|
|
153
|
+
return { stopReason: 'refusal' };
|
|
154
|
+
} finally {
|
|
155
|
+
this.busy = false;
|
|
156
|
+
this.abortController = undefined;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
private trimHistory(): void {
|
|
161
|
+
const MAX_MESSAGES = 80;
|
|
162
|
+
const KEEP_RECENT = 60;
|
|
163
|
+
if (this.messages.length <= MAX_MESSAGES) return;
|
|
164
|
+
|
|
165
|
+
const system =
|
|
166
|
+
this.messages[0]?.getType() === 'system' ? this.messages[0] : undefined;
|
|
167
|
+
const recent = this.messages.slice(-KEEP_RECENT);
|
|
168
|
+
while (recent.length > 0 && recent[0].getType() === 'tool') recent.shift();
|
|
169
|
+
|
|
170
|
+
this.messages.length = 0;
|
|
171
|
+
if (system) this.messages.push(system);
|
|
172
|
+
this.messages.push(...recent);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private forwardEvent(event: AgentEvent): void {
|
|
176
|
+
if (event.type === 'text') {
|
|
177
|
+
this.host.sendUpdate(this.id, {
|
|
178
|
+
sessionUpdate: 'agent_message_chunk',
|
|
179
|
+
content: { type: 'text', text: event.text },
|
|
180
|
+
});
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (event.type === 'thought') {
|
|
185
|
+
this.host.sendUpdate(this.id, {
|
|
186
|
+
sessionUpdate: 'agent_thought_chunk',
|
|
187
|
+
content: { type: 'text', text: event.text },
|
|
188
|
+
});
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (event.type === 'tool_call') {
|
|
193
|
+
this.host.sendUpdate(this.id, {
|
|
194
|
+
sessionUpdate: 'tool_call',
|
|
195
|
+
toolCallId: event.toolCallId,
|
|
196
|
+
name: event.name,
|
|
197
|
+
title: event.title,
|
|
198
|
+
kind: event.kind,
|
|
199
|
+
status: 'pending',
|
|
200
|
+
rawInput: event.input,
|
|
201
|
+
});
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const output =
|
|
206
|
+
event.output.length > MAX_TOOL_OUTPUT_IN_UPDATE
|
|
207
|
+
? `${event.output.slice(0, MAX_TOOL_OUTPUT_IN_UPDATE)}\n... (truncated)`
|
|
208
|
+
: event.output;
|
|
209
|
+
|
|
210
|
+
this.host.sendUpdate(this.id, {
|
|
211
|
+
sessionUpdate: 'tool_call_update',
|
|
212
|
+
toolCallId: event.toolCallId,
|
|
213
|
+
status: event.ok ? 'completed' : 'failed',
|
|
214
|
+
name: event.name,
|
|
215
|
+
content: [{ type: 'content', content: { type: 'text', text: output } }],
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private async askPermission(
|
|
220
|
+
request: PermissionRequest,
|
|
221
|
+
signal: AbortSignal,
|
|
222
|
+
): Promise<boolean> {
|
|
223
|
+
const mode = permissionMode();
|
|
224
|
+
|
|
225
|
+
if (mode === 'auto') return true;
|
|
226
|
+
if (mode === 'readonly') return false;
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
const response = await this.host.requestPermission(
|
|
230
|
+
{
|
|
231
|
+
sessionId: this.id,
|
|
232
|
+
toolCall: {
|
|
233
|
+
toolCallId: request.toolCallId,
|
|
234
|
+
title: request.title,
|
|
235
|
+
kind: request.kind,
|
|
236
|
+
status: 'pending',
|
|
237
|
+
rawInput: request.input,
|
|
238
|
+
},
|
|
239
|
+
options: [
|
|
240
|
+
{ optionId: 'allow_once', name: 'Allow once', kind: 'allow_once' },
|
|
241
|
+
{ optionId: 'reject_once', name: 'Reject', kind: 'reject_once' },
|
|
242
|
+
],
|
|
243
|
+
},
|
|
244
|
+
signal,
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
if (response.outcome.outcome !== 'selected') return false;
|
|
248
|
+
return ['allow_once', 'allow_session', 'approve_for_session'].includes(
|
|
249
|
+
response.outcome.optionId,
|
|
250
|
+
);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
process.stderr.write(
|
|
253
|
+
`[transcode] permission request failed, denying ${request.name}: ${
|
|
254
|
+
error instanceof Error ? error.message : String(error)
|
|
255
|
+
}\n`,
|
|
256
|
+
);
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function sessionCwd(input: unknown): string {
|
|
263
|
+
if (typeof input === 'string' && input.trim()) return path.resolve(input);
|
|
264
|
+
return process.cwd();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function sessionNewResult(session: AcpSession): AcpSessionNewResult {
|
|
268
|
+
return { sessionId: session.id, models: session.modelState };
|
|
269
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { createInterface, type Interface } from 'node:readline';
|
|
2
|
+
import type { JsonRpcId, JsonRpcResponse } from './protocol.js';
|
|
3
|
+
|
|
4
|
+
export class RpcError extends Error {
|
|
5
|
+
constructor(
|
|
6
|
+
public readonly code: number,
|
|
7
|
+
message: string,
|
|
8
|
+
public readonly data?: unknown,
|
|
9
|
+
) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'RpcError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const RPC_ERRORS = {
|
|
16
|
+
parseError: -32700,
|
|
17
|
+
invalidRequest: -32600,
|
|
18
|
+
methodNotFound: -32601,
|
|
19
|
+
invalidParams: -32602,
|
|
20
|
+
internalError: -32603,
|
|
21
|
+
sessionNotFound: -32002,
|
|
22
|
+
} as const;
|
|
23
|
+
|
|
24
|
+
type RequestHandler = (method: string, params: unknown) => Promise<unknown> | unknown;
|
|
25
|
+
type NotificationHandler = (method: string, params: unknown) => void | Promise<void>;
|
|
26
|
+
|
|
27
|
+
interface PendingRequest {
|
|
28
|
+
method: string;
|
|
29
|
+
resolve: (value: unknown) => void;
|
|
30
|
+
reject: (error: Error) => void;
|
|
31
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
32
|
+
abortCleanup?: () => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface RequestOptions {
|
|
36
|
+
timeoutMs?: number;
|
|
37
|
+
signal?: AbortSignal;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Newline-delimited JSON-RPC 2.0 transport over stdio, as required by ACP.
|
|
42
|
+
* stdout is reserved for protocol frames; diagnostics must go to stderr.
|
|
43
|
+
*/
|
|
44
|
+
export class JsonRpcTransport {
|
|
45
|
+
private readonly reader: Interface;
|
|
46
|
+
private pending = new Map<JsonRpcId, PendingRequest>();
|
|
47
|
+
private nextId = 1;
|
|
48
|
+
private closed = false;
|
|
49
|
+
private requestHandler?: RequestHandler;
|
|
50
|
+
private notificationHandler?: NotificationHandler;
|
|
51
|
+
|
|
52
|
+
constructor(
|
|
53
|
+
input: NodeJS.ReadableStream = process.stdin,
|
|
54
|
+
private readonly output: NodeJS.WritableStream = process.stdout,
|
|
55
|
+
) {
|
|
56
|
+
this.reader = createInterface({ input, crlfDelay: Infinity });
|
|
57
|
+
this.reader.on('line', (line) => {
|
|
58
|
+
void this.handleLine(line);
|
|
59
|
+
});
|
|
60
|
+
this.reader.on('close', () => {
|
|
61
|
+
this.failAll(new Error('ACP connection closed'));
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
setHandlers(requestHandler: RequestHandler, notificationHandler?: NotificationHandler): void {
|
|
66
|
+
this.requestHandler = requestHandler;
|
|
67
|
+
this.notificationHandler = notificationHandler;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async request(method: string, params: unknown, options: RequestOptions = {}): Promise<unknown> {
|
|
71
|
+
if (this.closed) throw new Error('ACP transport is closed');
|
|
72
|
+
|
|
73
|
+
const id = this.nextId++;
|
|
74
|
+
return await new Promise<unknown>((resolve, reject) => {
|
|
75
|
+
const pending: PendingRequest = { method, resolve, reject };
|
|
76
|
+
|
|
77
|
+
if (options.timeoutMs && options.timeoutMs > 0) {
|
|
78
|
+
pending.timer = setTimeout(() => {
|
|
79
|
+
if (!this.pending.delete(id)) return;
|
|
80
|
+
reject(new RpcError(-32000, `Request timed out: ${method}`));
|
|
81
|
+
}, options.timeoutMs);
|
|
82
|
+
pending.timer.unref?.();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (options.signal) {
|
|
86
|
+
const onAbort = () => {
|
|
87
|
+
if (!this.pending.delete(id)) return;
|
|
88
|
+
this.cleanupPending(pending);
|
|
89
|
+
reject(new Error(`Request cancelled: ${method}`));
|
|
90
|
+
};
|
|
91
|
+
if (options.signal.aborted) {
|
|
92
|
+
onAbort();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
options.signal.addEventListener('abort', onAbort, { once: true });
|
|
96
|
+
pending.abortCleanup = () => options.signal?.removeEventListener('abort', onAbort);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
this.pending.set(id, pending);
|
|
100
|
+
try {
|
|
101
|
+
this.write({ jsonrpc: '2.0', id, method, params });
|
|
102
|
+
} catch (error) {
|
|
103
|
+
this.pending.delete(id);
|
|
104
|
+
this.cleanupPending(pending);
|
|
105
|
+
reject(error as Error);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
notify(method: string, params?: unknown): void {
|
|
111
|
+
if (this.closed) return;
|
|
112
|
+
this.write({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
respond(id: JsonRpcId, result: unknown): void {
|
|
116
|
+
this.write({ jsonrpc: '2.0', id, result: result ?? null });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
respondError(id: JsonRpcId, code: number, message: string, data?: unknown): void {
|
|
120
|
+
this.write({
|
|
121
|
+
jsonrpc: '2.0',
|
|
122
|
+
id,
|
|
123
|
+
error: { code, message, ...(data === undefined ? {} : { data }) },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
close(): void {
|
|
128
|
+
if (this.closed) return;
|
|
129
|
+
this.closed = true;
|
|
130
|
+
this.reader.close();
|
|
131
|
+
this.failAll(new Error('ACP transport closed'));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private cleanupPending(pending: PendingRequest): void {
|
|
135
|
+
if (pending.timer) clearTimeout(pending.timer);
|
|
136
|
+
pending.abortCleanup?.();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private failAll(error: Error): void {
|
|
140
|
+
for (const pending of this.pending.values()) {
|
|
141
|
+
this.cleanupPending(pending);
|
|
142
|
+
pending.reject(error);
|
|
143
|
+
}
|
|
144
|
+
this.pending.clear();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private write(frame: unknown): void {
|
|
148
|
+
this.output.write(`${JSON.stringify(frame)}\n`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private async handleLine(line: string): Promise<void> {
|
|
152
|
+
const trimmed = line.trim();
|
|
153
|
+
if (!trimmed) return;
|
|
154
|
+
|
|
155
|
+
let message: Record<string, unknown>;
|
|
156
|
+
try {
|
|
157
|
+
message = JSON.parse(trimmed) as Record<string, unknown>;
|
|
158
|
+
} catch {
|
|
159
|
+
this.respondError(0, RPC_ERRORS.parseError, 'Invalid JSON');
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const id = message.id as JsonRpcId | undefined;
|
|
164
|
+
const method = typeof message.method === 'string' ? message.method : undefined;
|
|
165
|
+
|
|
166
|
+
if (method && id !== undefined && id !== null) {
|
|
167
|
+
if (!this.requestHandler) {
|
|
168
|
+
this.respondError(id, RPC_ERRORS.methodNotFound, `Method not found: ${method}`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const result = await this.requestHandler(method, message.params);
|
|
173
|
+
this.respond(id, result);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (error instanceof RpcError) {
|
|
176
|
+
this.respondError(id, error.code, error.message, error.data);
|
|
177
|
+
} else {
|
|
178
|
+
this.respondError(
|
|
179
|
+
id,
|
|
180
|
+
RPC_ERRORS.internalError,
|
|
181
|
+
error instanceof Error ? error.message : String(error),
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (method) {
|
|
189
|
+
try {
|
|
190
|
+
await this.notificationHandler?.(method, message.params);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
process.stderr.write(
|
|
193
|
+
`[transcode] notification ${method} failed: ${
|
|
194
|
+
error instanceof Error ? error.message : String(error)
|
|
195
|
+
}\n`,
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Response to a request we sent (for example session/request_permission).
|
|
202
|
+
if (id === undefined || id === null) return;
|
|
203
|
+
const pending = this.pending.get(id);
|
|
204
|
+
if (!pending) return;
|
|
205
|
+
|
|
206
|
+
this.pending.delete(id);
|
|
207
|
+
this.cleanupPending(pending);
|
|
208
|
+
|
|
209
|
+
const error = message.error as JsonRpcResponse['error'];
|
|
210
|
+
if (error) {
|
|
211
|
+
pending.reject(new RpcError(error.code, error.message, error.data));
|
|
212
|
+
} else {
|
|
213
|
+
pending.resolve(message.result ?? null);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|