@alexsun-top/opencode-chat-room 0.8.5 → 0.8.6
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/CHANGELOG.md +12 -2
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/cli.ts +19 -0
- package/dist/cli.js +3747 -1443
- package/package.json +6 -1
- package/packages/chat-room-channeld/README.md +13 -8
- package/packages/chat-room-channeld/src/delivery.ts +0 -4
- package/packages/chat-room-channeld/src/host.ts +48 -37
- package/packages/chat-room-channeld/src/pg/database.ts +141 -49
- package/packages/chat-room-channeld/src/pg/worker.mjs +46 -5
- package/packages/chat-room-channeld/src/pg/worker.mts +41 -6
- package/packages/chat-room-channeld/src/state-rows.ts +132 -0
- package/packages/chat-room-channeld/src/state.ts +129 -157
- package/plugin.ts +20 -4
- package/server/app.ts +9 -0
- package/server/assets/base.css +22 -2
- package/server/assets/chat/admin.js +13 -0
- package/server/assets/chat/announcements.js +76 -34
- package/server/assets/chat/confirm-dialog.js +3 -0
- package/server/assets/chat/create-room-dialog.js +7 -0
- package/server/assets/chat/diagram-viewer.js +4 -8
- package/server/assets/chat/doc-preview.js +70 -30
- package/server/assets/chat/editor.js +38 -3
- package/server/assets/chat/events.js +6 -1
- package/server/assets/chat/files.js +28 -26
- package/server/assets/chat/history-loader.js +31 -15
- package/server/assets/chat/integration-editor.js +25 -1
- package/server/assets/chat/integrations.js +107 -15
- package/server/assets/chat/join-requests.js +39 -1
- package/server/assets/chat/locales/de.js +5 -3
- package/server/assets/chat/locales/es.js +5 -3
- package/server/assets/chat/locales/fr.js +5 -3
- package/server/assets/chat/locales/it.js +5 -3
- package/server/assets/chat/locales/ja.js +5 -3
- package/server/assets/chat/locales/ko.js +5 -3
- package/server/assets/chat/markdown-footnotes.js +19 -8
- package/server/assets/chat/markdown.js +0 -7
- package/server/assets/chat/members.js +31 -19
- package/server/assets/chat/message-cache.js +8 -2
- package/server/assets/chat/message-polling.js +8 -2
- package/server/assets/chat/message-window.js +57 -0
- package/server/assets/chat/messages.js +79 -40
- package/server/assets/chat/operator.js +624 -0
- package/server/assets/chat/palette.js +2 -7
- package/server/assets/chat/panels.js +31 -8
- package/server/assets/chat/questions.js +72 -56
- package/server/assets/chat/recall.js +14 -5
- package/server/assets/chat/receipts.js +63 -7
- package/server/assets/chat/refresh-timing.js +6 -0
- package/server/assets/chat/reminders.js +44 -13
- package/server/assets/chat/replies.js +33 -22
- package/server/assets/chat/resource-format.js +4 -1
- package/server/assets/chat/room-list.js +202 -3
- package/server/assets/chat/room-watcher.js +3 -1
- package/server/assets/chat/rooms.js +22 -3
- package/server/assets/chat/settings.js +33 -3
- package/server/assets/chat/state.js +21 -7
- package/server/assets/chat/tasks.js +33 -11
- package/server/assets/chat/window-controls.js +25 -16
- package/server/assets/code-highlight.css +0 -13
- package/server/assets/conversation.css +31 -3
- package/server/assets/doc-preview.css +3 -0
- package/server/assets/files.css +4 -0
- package/server/assets/monaco/integration-rules.js +1 -1
- package/server/assets/responsive.css +12 -2
- package/server/assets/settings.css +3 -1
- package/server/assets/tasks.css +6 -1
- package/server/assets/window-controls.css +3 -1
- package/server/channels.ts +3 -2
- package/server/chat.html +7 -2
- package/server/inbox.ts +3 -1
- package/server/join-requests.ts +8 -1
- package/server/member-routes.ts +16 -2
- package/server/newrooms.ts +2 -13
- package/server/operator-auth.ts +21 -0
- package/server/operator-routes.ts +150 -0
- package/server/operator-state.ts +64 -0
- package/server/operator.css +139 -0
- package/server/room-owner.ts +17 -0
- package/server/routes/inbox.ts +15 -5
- package/server/routes/pages.ts +12 -2
- package/server/routes/room-actions.ts +4 -3
- package/server/system.html +109 -0
- package/server/wake.ts +1 -1
- package/skills/chatroom/SKILL.md +3 -3
- package/src/acp/client.ts +254 -0
- package/src/acp/protocol.ts +300 -0
- package/src/acp/watch.ts +498 -0
- package/src/agent/agent-receipts.ts +87 -5
- package/src/center/center-client.ts +5 -0
- package/src/center/center-inbox.ts +54 -7
- package/src/center/center-wake.ts +57 -3
- package/src/center/forward-client.ts +48 -0
- package/src/center/mentions.ts +16 -3
- package/src/center/notification-delay.ts +139 -0
- package/src/center/queue.ts +3 -0
- package/src/config/file-config.ts +25 -0
- package/src/mcp/server.ts +389 -0
- package/src/protocol/config.ts +7 -0
- package/src/runtime/plugin-notifications.ts +43 -9
- package/src/runtime/v2-plugin.ts +14 -3
- package/src/runtime/v2-receiver.ts +10 -2
- package/src/runtime/watch.ts +5 -1
- package/src/state/pg-database.ts +133 -49
- package/src/state/pg-worker.mjs +46 -5
- package/src/state/pg-worker.mts +41 -6
- package/src/state/receiver-state.ts +47 -0
- package/src/state/sqlite-database.ts +6 -2
- package/src/state/sqlite-members.ts +48 -4
- package/src/state/sqlite-messages.ts +25 -12
- package/src/state/sqlite-schema.ts +4 -1
- package/src/state/sqlite-state.ts +1 -1
- package/src/state/store.ts +10 -4
- package/src/tui/app.mjs +57 -10
- package/src/tui/app.mts +54 -11
- package/src/tui/room-settings-app.mjs +27 -9
- package/src/tui/room-settings-app.mts +26 -9
- package/src/web/integration-rules-editor.ts +25 -2
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// Stable ACP v1 one-shot client: launch one trusted local agent, give it the
|
|
2
|
+
// chat-room MCP server over stdio, send one prompt, then clean up.
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { statSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { loadRoomConfig, resolveClientSettings } from "../config/file-config.ts";
|
|
8
|
+
import { AcpConnection, AcpTimeoutError, MAX_OUTPUT_CHARS } from "./protocol.ts";
|
|
9
|
+
|
|
10
|
+
const DEFAULT_RUN_TIMEOUT_MS = 600_000;
|
|
11
|
+
const DEFAULT_CHECK_TIMEOUT_MS = 15_000;
|
|
12
|
+
const MAX_PROMPT_CHARS = 1_000_000;
|
|
13
|
+
const MIN_TIMEOUT_MS = 500;
|
|
14
|
+
const MAX_TIMEOUT_MS = 3_600_000;
|
|
15
|
+
const STOP_REASONS = new Set([
|
|
16
|
+
"end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled",
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
export type McpEnv = Array<{ name: string; value: string }>;
|
|
20
|
+
export type AcpCenter = { center: string; token: string; env: McpEnv };
|
|
21
|
+
|
|
22
|
+
type Options =
|
|
23
|
+
| { mode: "check"; command: string; args: string[] }
|
|
24
|
+
| { mode: "run"; sessionId: string; prompt: string; cwd: string; command: string; args: string[] };
|
|
25
|
+
|
|
26
|
+
let active = 0;
|
|
27
|
+
|
|
28
|
+
function writeStdout(text: string): void {
|
|
29
|
+
process.stdout.write(text);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function writeStderr(text: string): void {
|
|
33
|
+
process.stderr.write(`acp: ${text}\n`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function messageOf(error: unknown): string {
|
|
37
|
+
return error instanceof Error ? error.message : "ACP operation failed";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function safeAgentText(value: string): string {
|
|
41
|
+
return value
|
|
42
|
+
.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "")
|
|
43
|
+
.replace(/[\u0000-\u0008\u000B-\u001F\u007F]/g, "")
|
|
44
|
+
.slice(0, MAX_OUTPUT_CHARS);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
48
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
49
|
+
? value as Record<string, unknown>
|
|
50
|
+
: undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function runAcp(args: readonly string[], cliEntry: string): Promise<number> {
|
|
54
|
+
if (active > 0) {
|
|
55
|
+
writeStderr("another ACP client is already running");
|
|
56
|
+
return 1;
|
|
57
|
+
}
|
|
58
|
+
active += 1;
|
|
59
|
+
try {
|
|
60
|
+
if (!path.isAbsolute(cliEntry) || !isFile(cliEntry)) {
|
|
61
|
+
writeStderr("CLI entry must be an absolute file path");
|
|
62
|
+
return 1;
|
|
63
|
+
}
|
|
64
|
+
if (args[0] === "watch") {
|
|
65
|
+
const { runAcpWatch } = await import("./watch.ts");
|
|
66
|
+
return await runAcpWatch(args.slice(1), cliEntry);
|
|
67
|
+
}
|
|
68
|
+
const parsed = parseArgs(args);
|
|
69
|
+
if (typeof parsed === "string") {
|
|
70
|
+
writeStderr(parsed);
|
|
71
|
+
return 2;
|
|
72
|
+
}
|
|
73
|
+
const timeoutMs = timeoutFor(parsed.mode);
|
|
74
|
+
return await runOnce(parsed, cliEntry, timeoutMs);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
writeStderr(messageOf(error));
|
|
77
|
+
return error instanceof AcpTimeoutError ? 3 : 1;
|
|
78
|
+
} finally {
|
|
79
|
+
active -= 1;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isFile(file: string): boolean {
|
|
84
|
+
try {
|
|
85
|
+
return statSync(file).isFile();
|
|
86
|
+
} catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isDirectory(directory: string): boolean {
|
|
92
|
+
try {
|
|
93
|
+
return statSync(directory).isDirectory();
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function timeoutFor(mode: "check" | "run"): number {
|
|
100
|
+
const raw = process.env.CHAT_ROOM_ACP_TIMEOUT_MS;
|
|
101
|
+
if (raw && /^\d+$/.test(raw)) {
|
|
102
|
+
const value = Number(raw);
|
|
103
|
+
if (value >= MIN_TIMEOUT_MS && value <= MAX_TIMEOUT_MS) return value;
|
|
104
|
+
}
|
|
105
|
+
return mode === "check" ? DEFAULT_CHECK_TIMEOUT_MS : DEFAULT_RUN_TIMEOUT_MS;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function parseArgs(args: readonly string[]): Options | string {
|
|
109
|
+
if (args.some((arg) => typeof arg !== "string")) return "arguments must be strings";
|
|
110
|
+
const mode = args[0];
|
|
111
|
+
if (mode === "check") {
|
|
112
|
+
if (args[1] !== "--" || args.length < 3) return "usage: acp check -- <command> [args...]";
|
|
113
|
+
return { mode, command: args[2]!, args: args.slice(3) };
|
|
114
|
+
}
|
|
115
|
+
if (mode !== "run") return "usage: acp check|run ...";
|
|
116
|
+
let sessionId = "";
|
|
117
|
+
let prompt = "";
|
|
118
|
+
let cwd = process.cwd();
|
|
119
|
+
let command: string[] | undefined;
|
|
120
|
+
for (let index = 1; index < args.length; index += 1) {
|
|
121
|
+
const arg = args[index]!;
|
|
122
|
+
if (arg === "--") {
|
|
123
|
+
command = args.slice(index + 1);
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
if (arg === "--session-id" || arg === "--prompt" || arg === "--cwd") {
|
|
127
|
+
const value = args[index + 1];
|
|
128
|
+
index += 1;
|
|
129
|
+
if (value === undefined || value === "") return `missing value for ${arg}`;
|
|
130
|
+
if (arg === "--session-id") sessionId = value;
|
|
131
|
+
else if (arg === "--prompt") prompt = value;
|
|
132
|
+
else cwd = path.resolve(value);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
return `unknown option: ${arg}`;
|
|
136
|
+
}
|
|
137
|
+
if (!command || command.length === 0) return "usage: acp run ... -- <command> [args...]";
|
|
138
|
+
if (!/^\S{1,200}$/.test(sessionId)) return "--session-id must be 1-200 characters without spaces";
|
|
139
|
+
if (!prompt || prompt.length > MAX_PROMPT_CHARS) return "--prompt must be 1-1000000 characters";
|
|
140
|
+
if (!isDirectory(cwd)) return "--cwd must be an existing directory";
|
|
141
|
+
return { mode, sessionId, prompt, cwd, command: command[0]!, args: command.slice(1) };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function runOnce(options: Options, cliEntry: string, timeoutMs: number): Promise<number> {
|
|
145
|
+
const centerEnv = options.mode === "run" ? resolveAcpCenter().env : [];
|
|
146
|
+
const child = spawn(options.command, options.args, {
|
|
147
|
+
cwd: options.mode === "run" ? options.cwd : process.cwd(),
|
|
148
|
+
env: process.env,
|
|
149
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
150
|
+
shell: false,
|
|
151
|
+
windowsHide: true,
|
|
152
|
+
});
|
|
153
|
+
const connection = new AcpConnection(child, timeoutMs);
|
|
154
|
+
try {
|
|
155
|
+
const initialize = record(await connection.request("initialize", {
|
|
156
|
+
protocolVersion: 1,
|
|
157
|
+
clientCapabilities: {
|
|
158
|
+
fs: { readTextFile: false, writeTextFile: false },
|
|
159
|
+
terminal: false,
|
|
160
|
+
auth: { terminal: false },
|
|
161
|
+
},
|
|
162
|
+
clientInfo: { name: "opencode-chat-room", version: "1" },
|
|
163
|
+
}));
|
|
164
|
+
if (initialize?.protocolVersion !== 1) {
|
|
165
|
+
throw new Error("agent does not support ACP protocol version 1");
|
|
166
|
+
}
|
|
167
|
+
if (options.mode === "check") {
|
|
168
|
+
writeStdout(`${JSON.stringify(checkSummary(initialize), null, 2)}\n`);
|
|
169
|
+
return 0;
|
|
170
|
+
}
|
|
171
|
+
const created = record(await connection.request("session/new", {
|
|
172
|
+
cwd: options.cwd,
|
|
173
|
+
mcpServers: [mcpServer(options.sessionId, cliEntry, centerEnv)],
|
|
174
|
+
}));
|
|
175
|
+
const sessionId = created?.sessionId;
|
|
176
|
+
if (typeof sessionId !== "string" || !sessionId) {
|
|
177
|
+
throw new Error("agent returned no session id");
|
|
178
|
+
}
|
|
179
|
+
connection.setSessionId(sessionId);
|
|
180
|
+
connection.markPromptActive();
|
|
181
|
+
const result = record(await connection.request("session/prompt", {
|
|
182
|
+
sessionId,
|
|
183
|
+
prompt: [{ type: "text", text: options.prompt }],
|
|
184
|
+
}));
|
|
185
|
+
connection.markPromptDone();
|
|
186
|
+
const stopReason = result?.stopReason;
|
|
187
|
+
if (typeof stopReason !== "string" || !STOP_REASONS.has(stopReason)) {
|
|
188
|
+
throw new Error("agent returned an invalid stop reason");
|
|
189
|
+
}
|
|
190
|
+
const text = safeAgentText(connection.output);
|
|
191
|
+
if (text) writeStdout(text.endsWith("\n") ? text : `${text}\n`);
|
|
192
|
+
if (stopReason === "end_turn") return 0;
|
|
193
|
+
writeStderr(`stop reason: ${stopReason}`);
|
|
194
|
+
return stopReason === "cancelled" ? 3 : 1;
|
|
195
|
+
} finally {
|
|
196
|
+
await connection.shutdown();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function checkSummary(initialize: Record<string, unknown>): Record<string, unknown> {
|
|
201
|
+
const agent = record(initialize.agentInfo);
|
|
202
|
+
const capabilities = record(initialize.agentCapabilities);
|
|
203
|
+
const mcp = record(capabilities?.mcpCapabilities);
|
|
204
|
+
const methods = Array.isArray(initialize.authMethods) ? initialize.authMethods : [];
|
|
205
|
+
const authMethods = methods.flatMap((method) => {
|
|
206
|
+
const id = record(method)?.id;
|
|
207
|
+
return typeof id === "string" ? [id] : [];
|
|
208
|
+
});
|
|
209
|
+
return {
|
|
210
|
+
protocolVersion: 1,
|
|
211
|
+
agent: agent ? {
|
|
212
|
+
name: typeof agent.name === "string" ? agent.name : null,
|
|
213
|
+
version: typeof agent.version === "string" ? agent.version : null,
|
|
214
|
+
} : null,
|
|
215
|
+
mcp: { stdio: true, http: mcp?.http === true, sse: mcp?.sse === true },
|
|
216
|
+
authMethods,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function resolveAcpCenter(): AcpCenter {
|
|
221
|
+
// The trusted local agent can read this registration. Keep only the center
|
|
222
|
+
// URL and token here so no ambient config or state crosses the ACP wire.
|
|
223
|
+
let settings: ReturnType<typeof resolveClientSettings>;
|
|
224
|
+
try {
|
|
225
|
+
settings = resolveClientSettings(loadRoomConfig());
|
|
226
|
+
} catch {
|
|
227
|
+
throw new Error("cannot load chatroom client config");
|
|
228
|
+
}
|
|
229
|
+
if (!settings.url) throw new Error("no center URL configured");
|
|
230
|
+
if (!validCenter(settings.url)) throw new Error("configured center URL is invalid");
|
|
231
|
+
const center = settings.url.replace(/\/+$/, "");
|
|
232
|
+
const env: McpEnv = [{ name: "CHAT_ROOM_SERVER_URL", value: center }];
|
|
233
|
+
if (settings.token) env.push({ name: "CHAT_ROOM_SERVER_TOKEN", value: settings.token });
|
|
234
|
+
return { center, token: settings.token, env };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function validCenter(value: string): boolean {
|
|
238
|
+
try {
|
|
239
|
+
const url = new URL(value);
|
|
240
|
+
return (url.protocol === "http:" || url.protocol === "https:") &&
|
|
241
|
+
!url.username && !url.password && !url.search && !url.hash;
|
|
242
|
+
} catch {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function mcpServer(sessionId: string, cliEntry: string, env: McpEnv): Record<string, unknown> {
|
|
248
|
+
return {
|
|
249
|
+
name: "chatroom",
|
|
250
|
+
command: process.execPath,
|
|
251
|
+
args: [cliEntry, "mcp", "--session-id", sessionId],
|
|
252
|
+
env,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// SDK-free ACP v1 JSON-RPC over the agent's stdin/stdout. One instance owns
|
|
2
|
+
// one trusted local child and enforces frame, output and lifetime bounds.
|
|
3
|
+
import type { ChildProcess } from "node:child_process";
|
|
4
|
+
import { StringDecoder } from "node:string_decoder";
|
|
5
|
+
|
|
6
|
+
export const MAX_FRAME_CHARS = 8 * 1024 * 1024;
|
|
7
|
+
export const MAX_OUTPUT_CHARS = 2 * 1024 * 1024;
|
|
8
|
+
const EOF_GRACE_MS = 100;
|
|
9
|
+
const TERM_GRACE_MS = 1_500;
|
|
10
|
+
const KILL_GRACE_MS = 1_500;
|
|
11
|
+
|
|
12
|
+
export class AcpTimeoutError extends Error {}
|
|
13
|
+
export class AcpClosedError extends Error {}
|
|
14
|
+
export class AcpProtocolError extends Error {}
|
|
15
|
+
|
|
16
|
+
type Pending = { resolve: (value: unknown) => void; reject: (reason: Error) => void };
|
|
17
|
+
type RpcMessage = {
|
|
18
|
+
jsonrpc?: unknown;
|
|
19
|
+
id?: unknown;
|
|
20
|
+
result?: unknown;
|
|
21
|
+
error?: unknown;
|
|
22
|
+
method?: unknown;
|
|
23
|
+
params?: unknown;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
27
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
28
|
+
? value as Record<string, unknown>
|
|
29
|
+
: undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function waitClose(child: ChildProcess, ms: number): Promise<boolean> {
|
|
33
|
+
return new Promise((resolve) => {
|
|
34
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
35
|
+
resolve(true);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const timer = setTimeout(() => {
|
|
39
|
+
child.off("close", onClose);
|
|
40
|
+
resolve(false);
|
|
41
|
+
}, ms);
|
|
42
|
+
const onClose = () => {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
resolve(true);
|
|
45
|
+
};
|
|
46
|
+
child.once("close", onClose);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class AcpConnection {
|
|
51
|
+
private readonly child: ChildProcess;
|
|
52
|
+
private readonly decoder = new StringDecoder("utf8");
|
|
53
|
+
private readonly pending = new Map<number, Pending>();
|
|
54
|
+
private buffer = "";
|
|
55
|
+
private nextId = 1;
|
|
56
|
+
private closed = false;
|
|
57
|
+
private failing = false;
|
|
58
|
+
private sessionId = "";
|
|
59
|
+
private promptActive = false;
|
|
60
|
+
private text = "";
|
|
61
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
62
|
+
private shutdownPromise: Promise<void> | undefined;
|
|
63
|
+
|
|
64
|
+
constructor(child: ChildProcess, timeoutMs?: number) {
|
|
65
|
+
this.child = child;
|
|
66
|
+
child.stdout?.on("data", (chunk: Buffer) => this.read(chunk));
|
|
67
|
+
child.stdin?.on("error", () => this.fail(new AcpClosedError("agent write failed")));
|
|
68
|
+
child.stdout?.on("error", () => this.fail(new AcpClosedError("agent stream failed")));
|
|
69
|
+
child.once("error", () => this.fail(new AcpClosedError("cannot start agent")));
|
|
70
|
+
child.once("close", () => this.fail(new AcpClosedError("agent exited")));
|
|
71
|
+
if (timeoutMs !== undefined) this.armTimeout(timeoutMs);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
get output(): string {
|
|
75
|
+
return this.text;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
get isClosed(): boolean {
|
|
79
|
+
return this.closed;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
resetOutput(): void {
|
|
83
|
+
this.text = "";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
armTimeout(timeoutMs: number): void {
|
|
87
|
+
if (this.closed) return;
|
|
88
|
+
this.disarmTimeout();
|
|
89
|
+
this.timer = setTimeout(() => this.fail(new AcpTimeoutError("timed out")), timeoutMs);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
disarmTimeout(): void {
|
|
93
|
+
if (this.timer) clearTimeout(this.timer);
|
|
94
|
+
this.timer = undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
setSessionId(sessionId: string): void {
|
|
98
|
+
this.sessionId = sessionId;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
markPromptActive(): void {
|
|
102
|
+
this.promptActive = true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
markPromptDone(): void {
|
|
106
|
+
this.promptActive = false;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
request(method: string, params: unknown): Promise<unknown> {
|
|
110
|
+
if (this.closed) return Promise.reject(new AcpClosedError("connection closed"));
|
|
111
|
+
const id = this.nextId;
|
|
112
|
+
this.nextId += 1;
|
|
113
|
+
return new Promise((resolve, reject) => {
|
|
114
|
+
this.pending.set(id, { resolve, reject });
|
|
115
|
+
this.send({ jsonrpc: "2.0", id, method, params });
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private read(chunk: Buffer): void {
|
|
120
|
+
if (this.closed) return;
|
|
121
|
+
this.buffer += this.decoder.write(chunk);
|
|
122
|
+
if (this.buffer.length > MAX_FRAME_CHARS) {
|
|
123
|
+
this.fail(new AcpProtocolError("agent frame exceeded limit"));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
let index = this.buffer.indexOf("\n");
|
|
127
|
+
while (index >= 0) {
|
|
128
|
+
const line = this.buffer.slice(0, index).trim();
|
|
129
|
+
this.buffer = this.buffer.slice(index + 1);
|
|
130
|
+
if (line) this.handleLine(line);
|
|
131
|
+
if (this.closed) return;
|
|
132
|
+
index = this.buffer.indexOf("\n");
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private handleLine(line: string): void {
|
|
137
|
+
let parsed: unknown;
|
|
138
|
+
try {
|
|
139
|
+
parsed = JSON.parse(line);
|
|
140
|
+
} catch {
|
|
141
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const message = record(parsed);
|
|
145
|
+
if (!message) {
|
|
146
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const rpc = message as RpcMessage;
|
|
150
|
+
if (rpc.jsonrpc !== "2.0") {
|
|
151
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (rpc.method !== undefined) {
|
|
155
|
+
if (typeof rpc.method !== "string") {
|
|
156
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (rpc.id === undefined) {
|
|
160
|
+
this.handleNotification(rpc.method, rpc.params);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (typeof rpc.id !== "number" && typeof rpc.id !== "string") {
|
|
164
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
this.handleRequest(rpc.id, rpc.method, rpc.params);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (typeof rpc.id !== "number" || !Number.isFinite(rpc.id)) {
|
|
171
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const hasResult = Object.hasOwn(rpc, "result");
|
|
175
|
+
const hasError = Object.hasOwn(rpc, "error");
|
|
176
|
+
if (hasResult === hasError) {
|
|
177
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const pending = this.pending.get(rpc.id);
|
|
181
|
+
if (!pending) {
|
|
182
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (hasError) {
|
|
186
|
+
const error = record(rpc.error);
|
|
187
|
+
if (!error || typeof error.code !== "number") {
|
|
188
|
+
this.fail(new AcpProtocolError("agent sent invalid protocol data"));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
this.pending.delete(rpc.id);
|
|
192
|
+
pending.reject(new Error(`agent returned JSON-RPC error ${error.code}`));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
this.pending.delete(rpc.id);
|
|
196
|
+
pending.resolve(rpc.result);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private handleNotification(method: string, params: unknown): void {
|
|
200
|
+
if (method !== "session/update") return;
|
|
201
|
+
const input = record(params);
|
|
202
|
+
if (!input || input.sessionId !== this.sessionId) return;
|
|
203
|
+
const update = record(input.update);
|
|
204
|
+
if (!update) return;
|
|
205
|
+
if (update.sessionUpdate === "agent_message_chunk") {
|
|
206
|
+
const content = record(update.content);
|
|
207
|
+
if (content?.type !== "text" || typeof content.text !== "string") return;
|
|
208
|
+
const next = this.text + content.text;
|
|
209
|
+
if (next.length > MAX_OUTPUT_CHARS) {
|
|
210
|
+
this.fail(new AcpProtocolError("agent output exceeded limit"));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
this.text = next;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
private handleRequest(id: number | string, method: string, params: unknown): void {
|
|
218
|
+
if (method === "session/request_permission") {
|
|
219
|
+
const options = record(params)?.options;
|
|
220
|
+
const option = Array.isArray(options) ? options.find((entry) => {
|
|
221
|
+
const kind = record(entry)?.kind;
|
|
222
|
+
return kind === "reject_once" || kind === "reject_always";
|
|
223
|
+
}) : undefined;
|
|
224
|
+
const optionId = record(option)?.optionId;
|
|
225
|
+
this.respond(id, typeof optionId === "string"
|
|
226
|
+
? { outcome: { outcome: "selected", optionId } }
|
|
227
|
+
: { outcome: { outcome: "cancelled" } });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
this.respondError(id, -32601);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
private respond(id: unknown, result: unknown): void {
|
|
234
|
+
this.send({ jsonrpc: "2.0", id, result });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
private respondError(id: unknown, code: number): void {
|
|
238
|
+
this.send({ jsonrpc: "2.0", id, error: { code, message: "Method not found" } });
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private send(message: unknown): void {
|
|
242
|
+
if (this.closed) return;
|
|
243
|
+
try {
|
|
244
|
+
this.child.stdin?.write(`${JSON.stringify(message)}\n`);
|
|
245
|
+
} catch {
|
|
246
|
+
this.fail(new AcpClosedError("agent write failed"));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private fail(reason: Error): void {
|
|
251
|
+
if (this.closed || this.failing) return;
|
|
252
|
+
this.failing = true;
|
|
253
|
+
if (this.promptActive && this.sessionId) {
|
|
254
|
+
this.send({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.sessionId } });
|
|
255
|
+
}
|
|
256
|
+
this.closed = true;
|
|
257
|
+
this.rejectAll(reason);
|
|
258
|
+
void this.finishChild();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private rejectAll(reason: Error): void {
|
|
262
|
+
for (const pending of this.pending.values()) pending.reject(reason);
|
|
263
|
+
this.pending.clear();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async shutdown(): Promise<void> {
|
|
267
|
+
return this.finishChild();
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private finishChild(): Promise<void> {
|
|
271
|
+
if (this.shutdownPromise) return this.shutdownPromise;
|
|
272
|
+
this.shutdownPromise = this.terminate();
|
|
273
|
+
return this.shutdownPromise;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private async terminate(): Promise<void> {
|
|
277
|
+
if (this.timer) clearTimeout(this.timer);
|
|
278
|
+
this.timer = undefined;
|
|
279
|
+
if (!this.closed) {
|
|
280
|
+
if (this.promptActive && this.sessionId) {
|
|
281
|
+
this.send({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.sessionId } });
|
|
282
|
+
}
|
|
283
|
+
this.closed = true;
|
|
284
|
+
this.rejectAll(new AcpClosedError("connection closed"));
|
|
285
|
+
}
|
|
286
|
+
const stdin = this.child.stdin;
|
|
287
|
+
if (stdin && !stdin.destroyed) stdin.end();
|
|
288
|
+
if (!(await waitClose(this.child, EOF_GRACE_MS))) {
|
|
289
|
+
this.child.kill("SIGTERM");
|
|
290
|
+
if (!(await waitClose(this.child, TERM_GRACE_MS))) {
|
|
291
|
+
this.child.kill("SIGKILL");
|
|
292
|
+
await waitClose(this.child, KILL_GRACE_MS);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
stdin?.destroy();
|
|
296
|
+
this.child.stdout?.destroy();
|
|
297
|
+
this.child.removeAllListeners();
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|