@yuandc/aica 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 +9 -0
- package/dist/acp/agent.js +54 -0
- package/dist/acp/client/acp-client.js +102 -0
- package/dist/acp/client/acp-content.js +13 -0
- package/dist/acp/client/acp-events.js +106 -0
- package/dist/acp/client/acp-process.js +34 -0
- package/dist/acp/client/acp-runtime-pool.js +248 -0
- package/dist/acp/client/context-usage.js +29 -0
- package/dist/acp/client/json-rpc.js +128 -0
- package/dist/acp/provider-types.js +1 -0
- package/dist/acp/providers/codex/codex-process.js +51 -0
- package/dist/acp/providers/codex/events.js +1473 -0
- package/dist/acp/providers/codex/permissions.js +49 -0
- package/dist/acp/providers/codex/provider.js +376 -0
- package/dist/acp/providers/codex-acp/adapter.js +947 -0
- package/dist/acp/providers/codex-acp/context-maintenance.js +148 -0
- package/dist/acp/providers/codex-acp/launch.js +35 -0
- package/dist/acp/providers/codex-acp/provider.js +486 -0
- package/dist/acp/providers/mimo/provider.js +448 -0
- package/dist/acp/providers/opencode/provider.js +489 -0
- package/dist/acp/providers/registry.js +23 -0
- package/dist/acp/standard-events.js +167 -0
- package/dist/commands/start.js +137 -0
- package/dist/commands/worker-auth.js +100 -0
- package/dist/commands/worker-project.js +57 -0
- package/dist/core/aca-config.js +74 -0
- package/dist/core/aca-server-client.js +57 -0
- package/dist/core/acp-event-coalescer.js +108 -0
- package/dist/core/acp-event-upload-filter.js +16 -0
- package/dist/core/acp-orphan-cleanup.js +91 -0
- package/dist/core/affected-files.js +268 -0
- package/dist/core/auth.js +36 -0
- package/dist/core/file-transfer-worker.js +169 -0
- package/dist/core/fs.js +28 -0
- package/dist/core/heartbeat.js +578 -0
- package/dist/core/job-permission-policy.js +42 -0
- package/dist/core/job-worker.js +749 -0
- package/dist/core/logger.js +42 -0
- package/dist/core/long-poll-worker.js +26 -0
- package/dist/core/machine-filesystem-worker.js +352 -0
- package/dist/core/paths.js +26 -0
- package/dist/core/process-identity.js +34 -0
- package/dist/core/process.js +33 -0
- package/dist/core/provider-health.js +54 -0
- package/dist/core/runtime-options.js +38 -0
- package/dist/core/worktree.js +95 -0
- package/dist/worker-cli.js +27 -0
- package/dist/worker-single-cli.js +17 -0
- package/package.json +35 -0
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { eventFromAcpSessionUpdate, statusFromAcpSessionUpdate } from "../../client/acp-events.js";
|
|
4
|
+
import { contextUsageFromAcpSessionUpdate } from "../../client/context-usage.js";
|
|
5
|
+
import { defaultAcpRuntimePool } from "../../client/acp-runtime-pool.js";
|
|
6
|
+
export const openCodeCapabilities = {
|
|
7
|
+
sessionResume: true,
|
|
8
|
+
imageInput: true,
|
|
9
|
+
fileAttachment: true,
|
|
10
|
+
filesystem: true,
|
|
11
|
+
terminal: true,
|
|
12
|
+
permissionRequest: true,
|
|
13
|
+
configOptions: true,
|
|
14
|
+
usage: true,
|
|
15
|
+
contextUsage: true,
|
|
16
|
+
contextCompaction: false,
|
|
17
|
+
plan: true,
|
|
18
|
+
diff: true
|
|
19
|
+
};
|
|
20
|
+
export class OpenCodeProvider {
|
|
21
|
+
id = "opencode";
|
|
22
|
+
name = "OpenCode";
|
|
23
|
+
capabilities = openCodeCapabilities;
|
|
24
|
+
async createSession(input) {
|
|
25
|
+
return new OpenCodeSession(input.cwd, input.providerSessionId ?? null, input.timeoutMs);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
class OpenCodeSession {
|
|
29
|
+
cwd;
|
|
30
|
+
providerSessionId;
|
|
31
|
+
defaultTimeoutMs;
|
|
32
|
+
lease = null;
|
|
33
|
+
sessionResponse = null;
|
|
34
|
+
statusCallback = null;
|
|
35
|
+
updateCallback = null;
|
|
36
|
+
permissionCallback = null;
|
|
37
|
+
userInputCallback = null;
|
|
38
|
+
canExecuteTools = true;
|
|
39
|
+
abortHandler = null;
|
|
40
|
+
statusTimeline = [];
|
|
41
|
+
updates = [];
|
|
42
|
+
content = "";
|
|
43
|
+
latestContextUsage = null;
|
|
44
|
+
contextWindow = 0;
|
|
45
|
+
resumedExistingSession = false;
|
|
46
|
+
constructor(cwd, providerSessionId, defaultTimeoutMs = readOpenCodePromptTimeoutMs()) {
|
|
47
|
+
this.cwd = cwd;
|
|
48
|
+
this.providerSessionId = providerSessionId;
|
|
49
|
+
this.defaultTimeoutMs = defaultTimeoutMs;
|
|
50
|
+
}
|
|
51
|
+
async sendPrompt(input) {
|
|
52
|
+
if (!fs.existsSync(input.cwd) || !fs.statSync(input.cwd).isDirectory()) {
|
|
53
|
+
throw new Error(`Project root does not exist or is not a directory: ${input.cwd}`);
|
|
54
|
+
}
|
|
55
|
+
const startedAt = Date.now();
|
|
56
|
+
this.statusCallback = input.onStatus ?? null;
|
|
57
|
+
this.updateCallback = input.onUpdate ?? null;
|
|
58
|
+
this.permissionCallback = input.onPermissionRequest ?? null;
|
|
59
|
+
this.userInputCallback = input.onUserInputRequest ?? null;
|
|
60
|
+
this.canExecuteTools = input.canExecuteTools !== false;
|
|
61
|
+
this.attachAbortSignal(input.signal);
|
|
62
|
+
this.content = "";
|
|
63
|
+
this.updates.length = 0;
|
|
64
|
+
this.statusTimeline.length = 0;
|
|
65
|
+
this.latestContextUsage = null;
|
|
66
|
+
this.contextWindow = positiveNumber(input.contextWindow);
|
|
67
|
+
let client = null;
|
|
68
|
+
let started = null;
|
|
69
|
+
let sessionId = this.providerSessionId;
|
|
70
|
+
let promptResponse;
|
|
71
|
+
try {
|
|
72
|
+
this.emitStatus("initializing", "OpenCode ACP 启动中", "opencode acp");
|
|
73
|
+
const lease = await this.acquireRuntime(input.cwd);
|
|
74
|
+
this.lease = lease;
|
|
75
|
+
client = lease.client;
|
|
76
|
+
started = lease.started;
|
|
77
|
+
await this.initialize(lease);
|
|
78
|
+
sessionId = await this.establishSession(lease, input);
|
|
79
|
+
await this.applyConfig(client, sessionId, input);
|
|
80
|
+
this.emitStatus("thinking", "思考中");
|
|
81
|
+
const prompt = promptBlocksToOpenCodeAcpContent(input.prompt, input.promptBlocks);
|
|
82
|
+
try {
|
|
83
|
+
promptResponse = await this.promptWithAbort(client, {
|
|
84
|
+
sessionId,
|
|
85
|
+
prompt,
|
|
86
|
+
timeoutMs: input.timeoutMs ?? this.defaultTimeoutMs,
|
|
87
|
+
signal: input.signal
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (!this.resumedExistingSession || !isInvalidParamsError(error))
|
|
92
|
+
throw error;
|
|
93
|
+
// OpenCode can successfully load a persisted session whose prompt endpoint
|
|
94
|
+
// is no longer compatible after an upstream/runtime change. Reusing it would
|
|
95
|
+
// make every queued Chat Room task fail identically. Retry once from a fresh
|
|
96
|
+
// ACP session; a second failure is surfaced unchanged to the caller.
|
|
97
|
+
this.appendStderr("OpenCode resumed session rejected session/prompt with Invalid params; creating a fresh session and retrying once.\n");
|
|
98
|
+
await this.lease?.dispose().catch(() => void 0);
|
|
99
|
+
this.lease = null;
|
|
100
|
+
this.providerSessionId = null;
|
|
101
|
+
this.sessionResponse = null;
|
|
102
|
+
this.resumedExistingSession = false;
|
|
103
|
+
this.emitStatus("resuming", "OpenCode 会话已失效,正在新建", "session/prompt invalid params");
|
|
104
|
+
const freshLease = await this.acquireRuntime(input.cwd);
|
|
105
|
+
this.lease = freshLease;
|
|
106
|
+
client = freshLease.client;
|
|
107
|
+
started = freshLease.started;
|
|
108
|
+
await this.initialize(freshLease);
|
|
109
|
+
sessionId = await this.establishSession(freshLease, input);
|
|
110
|
+
await this.applyConfig(client, sessionId, input);
|
|
111
|
+
this.emitStatus("thinking", "思考中");
|
|
112
|
+
promptResponse = await this.promptWithAbort(client, {
|
|
113
|
+
sessionId,
|
|
114
|
+
prompt,
|
|
115
|
+
timeoutMs: input.timeoutMs ?? this.defaultTimeoutMs,
|
|
116
|
+
signal: input.signal
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
if (this.abortHandler && input.signal) {
|
|
122
|
+
input.signal.removeEventListener("abort", this.abortHandler);
|
|
123
|
+
this.abortHandler = null;
|
|
124
|
+
}
|
|
125
|
+
this.releaseLease();
|
|
126
|
+
}
|
|
127
|
+
this.emitStatus("completed", "已完成");
|
|
128
|
+
return {
|
|
129
|
+
providerSessionId: sessionId,
|
|
130
|
+
cliType: "builtin",
|
|
131
|
+
agentType: "opencode",
|
|
132
|
+
effectiveConfig: {
|
|
133
|
+
model: openCodeModelValue(input.model) || null,
|
|
134
|
+
mode: input.mode || null,
|
|
135
|
+
configOptionValues: input.configOptionValues ?? null,
|
|
136
|
+
command: started.command,
|
|
137
|
+
processPid: started.child.pid ?? null,
|
|
138
|
+
provider: "opencode",
|
|
139
|
+
protocol: "acp"
|
|
140
|
+
},
|
|
141
|
+
command: started.command,
|
|
142
|
+
args: started.args,
|
|
143
|
+
cwd: input.cwd,
|
|
144
|
+
exitCode: started.child.exitCode,
|
|
145
|
+
signal: started.child.signalCode,
|
|
146
|
+
durationMs: Date.now() - startedAt,
|
|
147
|
+
stdout: client.rpc.stdout,
|
|
148
|
+
stderr: client.rpc.stderr,
|
|
149
|
+
content: this.content.trim(),
|
|
150
|
+
updates: [...this.updates],
|
|
151
|
+
statusTimeline: [...this.statusTimeline],
|
|
152
|
+
contextUsage: this.latestContextUsage,
|
|
153
|
+
promptResponse
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
async cancel() {
|
|
157
|
+
if (this.providerSessionId)
|
|
158
|
+
this.lease?.client.cancel(this.providerSessionId);
|
|
159
|
+
}
|
|
160
|
+
async close() {
|
|
161
|
+
this.statusCallback = null;
|
|
162
|
+
this.updateCallback = null;
|
|
163
|
+
this.permissionCallback = null;
|
|
164
|
+
this.userInputCallback = null;
|
|
165
|
+
this.canExecuteTools = true;
|
|
166
|
+
if (this.abortHandler)
|
|
167
|
+
this.abortHandler = null;
|
|
168
|
+
this.releaseLease();
|
|
169
|
+
}
|
|
170
|
+
async acquireRuntime(cwd) {
|
|
171
|
+
const command = process.env.ACA_OPENCODE_COMMAND || "opencode";
|
|
172
|
+
return defaultAcpRuntimePool.acquire({
|
|
173
|
+
providerId: "opencode",
|
|
174
|
+
cwd,
|
|
175
|
+
providerSessionId: this.providerSessionId,
|
|
176
|
+
command,
|
|
177
|
+
args: ["acp", "--cwd", cwd],
|
|
178
|
+
onSessionUpdate: (params) => this.handleSessionUpdate(params),
|
|
179
|
+
onClientRequest: (method, params) => this.handleClientRequest(method, params)
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
async initialize(lease) {
|
|
183
|
+
if (lease.initialized)
|
|
184
|
+
return;
|
|
185
|
+
await lease.client.initialize(60_000);
|
|
186
|
+
lease.markInitialized();
|
|
187
|
+
}
|
|
188
|
+
async establishSession(lease, input) {
|
|
189
|
+
const client = lease.client;
|
|
190
|
+
const initialConfig = initialOpenCodeConfig(input);
|
|
191
|
+
this.resumedExistingSession = false;
|
|
192
|
+
if (lease.providerSessionId && lease.sessionEstablished) {
|
|
193
|
+
if (openCodeSessionModelMatches(lease.sessionResponse, input.model)) {
|
|
194
|
+
this.providerSessionId = lease.providerSessionId;
|
|
195
|
+
this.sessionResponse = lease.sessionResponse;
|
|
196
|
+
this.resumedExistingSession = true;
|
|
197
|
+
return lease.providerSessionId;
|
|
198
|
+
}
|
|
199
|
+
this.providerSessionId = null;
|
|
200
|
+
}
|
|
201
|
+
else if (this.providerSessionId) {
|
|
202
|
+
try {
|
|
203
|
+
this.emitStatus("resuming", "OpenCode 会话恢复中", "session/load");
|
|
204
|
+
const loaded = await client.loadSession({ sessionId: this.providerSessionId, cwd: input.cwd }, 60_000);
|
|
205
|
+
this.sessionResponse = objectOrNull(loaded);
|
|
206
|
+
if (openCodeSessionModelMatches(this.sessionResponse, input.model)) {
|
|
207
|
+
const sessionId = sessionIdFromResponse(loaded) || this.providerSessionId;
|
|
208
|
+
this.providerSessionId = sessionId;
|
|
209
|
+
lease.setProviderSession({ providerSessionId: sessionId, sessionResponse: this.sessionResponse });
|
|
210
|
+
this.resumedExistingSession = true;
|
|
211
|
+
return sessionId;
|
|
212
|
+
}
|
|
213
|
+
this.appendStderr(`OpenCode model changed from ${openCodeCurrentModelId(this.sessionResponse) ?? "unknown"} to ${openCodeModelValue(input.model) || "default"}, creating new session\n`);
|
|
214
|
+
this.providerSessionId = null;
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
this.providerSessionId = null;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
this.emitStatus("acp", "OpenCode 会话创建中", "session/new");
|
|
221
|
+
const created = await client.newSession({ cwd: input.cwd, config: initialConfig }, 120_000);
|
|
222
|
+
this.sessionResponse = objectOrNull(created);
|
|
223
|
+
const sessionId = sessionIdFromResponse(created);
|
|
224
|
+
if (!sessionId)
|
|
225
|
+
throw new Error("OpenCode ACP session/new did not return sessionId");
|
|
226
|
+
this.providerSessionId = sessionId;
|
|
227
|
+
lease.setProviderSession({ providerSessionId: sessionId, sessionResponse: this.sessionResponse });
|
|
228
|
+
return sessionId;
|
|
229
|
+
}
|
|
230
|
+
async applyConfig(client, sessionId, input) {
|
|
231
|
+
const mode = openCodeModeValue(input.mode);
|
|
232
|
+
if (mode) {
|
|
233
|
+
await client.setSessionMode({ sessionId, modeId: mode }, 60_000).catch((error) => {
|
|
234
|
+
this.appendStderr(`OpenCode mode config failed: ${errorMessage(error)}\n`);
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
handleSessionUpdate(params) {
|
|
239
|
+
this.updates.push({ method: "session/update", params });
|
|
240
|
+
this.latestContextUsage = contextUsageFromAcpSessionUpdate(params, this.contextWindow) ?? this.latestContextUsage;
|
|
241
|
+
const event = eventFromAcpSessionUpdate(params);
|
|
242
|
+
if (event) {
|
|
243
|
+
if (event.type === "agent_message_chunk")
|
|
244
|
+
this.content += event.text ?? "";
|
|
245
|
+
this.updateCallback?.(event);
|
|
246
|
+
}
|
|
247
|
+
const status = statusFromAcpSessionUpdate(params);
|
|
248
|
+
if (status)
|
|
249
|
+
this.emitStatus(status.phase, status.label, status.detail, status.updateType);
|
|
250
|
+
}
|
|
251
|
+
async handleClientRequest(method, params) {
|
|
252
|
+
if (!this.canExecuteTools && (method === "fs/read_text_file" || method === "fs/write_text_file")) {
|
|
253
|
+
throw new Error(`Chat Room role policy disabled tool execution: ${method}`);
|
|
254
|
+
}
|
|
255
|
+
switch (method) {
|
|
256
|
+
case "fs/read_text_file":
|
|
257
|
+
return this.readTextFile(params);
|
|
258
|
+
case "fs/write_text_file":
|
|
259
|
+
return this.writeTextFile(params);
|
|
260
|
+
case "session/request_permission":
|
|
261
|
+
return this.requestPermission(params);
|
|
262
|
+
case "elicitation/create":
|
|
263
|
+
case "session/request_user_input":
|
|
264
|
+
return this.requestUserInput(params);
|
|
265
|
+
default:
|
|
266
|
+
throw new Error(`Unsupported OpenCode ACP client request: ${method}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
readTextFile(params) {
|
|
270
|
+
const filePath = resolveScopedPath(this.cwd, stringParam(params, "path") || stringParam(params, "filePath"));
|
|
271
|
+
return { content: fs.readFileSync(filePath, "utf8") };
|
|
272
|
+
}
|
|
273
|
+
writeTextFile(params) {
|
|
274
|
+
const filePath = resolveScopedPath(this.cwd, stringParam(params, "path") || stringParam(params, "filePath"));
|
|
275
|
+
const content = stringParam(params, "content") ?? stringParam(params, "text") ?? "";
|
|
276
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
277
|
+
fs.writeFileSync(filePath, content, "utf8");
|
|
278
|
+
return {};
|
|
279
|
+
}
|
|
280
|
+
attachAbortSignal(signal) {
|
|
281
|
+
if (!signal)
|
|
282
|
+
return;
|
|
283
|
+
this.abortHandler = () => {
|
|
284
|
+
void this.cancel();
|
|
285
|
+
};
|
|
286
|
+
if (signal.aborted)
|
|
287
|
+
throw new Error("OpenCode prompt cancelled");
|
|
288
|
+
signal.addEventListener("abort", this.abortHandler, { once: true });
|
|
289
|
+
}
|
|
290
|
+
async promptWithAbort(client, input) {
|
|
291
|
+
const promptPromise = client.prompt({ sessionId: input.sessionId, prompt: input.prompt }, input.timeoutMs);
|
|
292
|
+
if (!input.signal)
|
|
293
|
+
return promptPromise;
|
|
294
|
+
if (input.signal.aborted) {
|
|
295
|
+
await this.lease?.dispose().catch(() => void 0);
|
|
296
|
+
throw new Error("OpenCode prompt cancelled");
|
|
297
|
+
}
|
|
298
|
+
let abortHandler = null;
|
|
299
|
+
const abortPromise = new Promise((_, reject) => {
|
|
300
|
+
abortHandler = () => {
|
|
301
|
+
client.cancel(input.sessionId);
|
|
302
|
+
void this.lease?.dispose().catch(() => void 0);
|
|
303
|
+
reject(new Error("OpenCode prompt cancelled"));
|
|
304
|
+
};
|
|
305
|
+
input.signal?.addEventListener("abort", abortHandler, { once: true });
|
|
306
|
+
});
|
|
307
|
+
try {
|
|
308
|
+
return await Promise.race([promptPromise, abortPromise]);
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
if (abortHandler)
|
|
312
|
+
input.signal.removeEventListener("abort", abortHandler);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
async requestPermission(params) {
|
|
316
|
+
if (!this.permissionCallback)
|
|
317
|
+
return { outcome: { outcome: "cancelled" } };
|
|
318
|
+
const record = objectOrNull(params) ?? {};
|
|
319
|
+
const request = objectOrNull(record.request) ?? record;
|
|
320
|
+
const rawOptions = Array.isArray(request.options) ? request.options : [];
|
|
321
|
+
const options = rawOptions.map((option, index) => {
|
|
322
|
+
const item = objectOrNull(option) ?? {};
|
|
323
|
+
return {
|
|
324
|
+
optionId: String(item.optionId ?? item.id ?? index),
|
|
325
|
+
kind: String(item.kind ?? item.outcome ?? "choice"),
|
|
326
|
+
...(typeof item.label === "string" ? { label: item.label } : {})
|
|
327
|
+
};
|
|
328
|
+
});
|
|
329
|
+
this.emitStatus("requestPermission", "等待授权", permissionRequestDetail(request), "session/request_permission");
|
|
330
|
+
return this.permissionCallback({
|
|
331
|
+
requestId: String(request.requestId ?? request.id ?? `opencode-permission-${Date.now()}`),
|
|
332
|
+
params,
|
|
333
|
+
options
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
async requestUserInput(params) {
|
|
337
|
+
if (!this.userInputCallback)
|
|
338
|
+
return { outcome: { outcome: "cancelled" } };
|
|
339
|
+
const record = objectOrNull(params) ?? {};
|
|
340
|
+
const request = objectOrNull(record.request) ?? record;
|
|
341
|
+
this.emitStatus("requestPermission", "等待输入", userInputRequestDetail(request), "elicitation/create");
|
|
342
|
+
return this.userInputCallback({
|
|
343
|
+
requestId: String(request.requestId ?? request.id ?? `opencode-input-${Date.now()}`),
|
|
344
|
+
prompt: String(request.prompt ?? request.message ?? request.question ?? ""),
|
|
345
|
+
params,
|
|
346
|
+
...(typeof request.defaultValue === "string" ? { defaultValue: request.defaultValue } : {})
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
emitStatus(phase, label, detail, updateType) {
|
|
350
|
+
const status = {
|
|
351
|
+
phase,
|
|
352
|
+
label,
|
|
353
|
+
...(detail ? { detail } : {}),
|
|
354
|
+
...(updateType ? { updateType } : {}),
|
|
355
|
+
atMs: Date.now()
|
|
356
|
+
};
|
|
357
|
+
const last = this.statusTimeline[this.statusTimeline.length - 1];
|
|
358
|
+
if (last && last.phase === status.phase && last.label === status.label && last.detail === status.detail && last.updateType === status.updateType)
|
|
359
|
+
return;
|
|
360
|
+
this.statusTimeline.push(status);
|
|
361
|
+
this.statusCallback?.(status);
|
|
362
|
+
}
|
|
363
|
+
appendStderr(value) {
|
|
364
|
+
const client = this.lease?.client;
|
|
365
|
+
if (client)
|
|
366
|
+
client.rpc.stderr += value;
|
|
367
|
+
}
|
|
368
|
+
releaseLease() {
|
|
369
|
+
this.lease?.release();
|
|
370
|
+
this.lease = null;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
function sessionIdFromResponse(value) {
|
|
374
|
+
const record = objectOrNull(value);
|
|
375
|
+
const sessionId = record?.sessionId;
|
|
376
|
+
return typeof sessionId === "string" && sessionId.trim() ? sessionId.trim() : null;
|
|
377
|
+
}
|
|
378
|
+
function objectOrNull(value) {
|
|
379
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
380
|
+
}
|
|
381
|
+
function positiveNumber(value) {
|
|
382
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
|
|
383
|
+
}
|
|
384
|
+
function initialOpenCodeConfig(input) {
|
|
385
|
+
const model = openCodeModelValue(input.model);
|
|
386
|
+
const mode = openCodeModeValue(input.mode);
|
|
387
|
+
return {
|
|
388
|
+
...openCodeExtraConfig(input.configOptionValues),
|
|
389
|
+
...(model ? { model } : {}),
|
|
390
|
+
...(mode ? { mode } : {})
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function openCodeExtraConfig(values) {
|
|
394
|
+
const result = {};
|
|
395
|
+
for (const [key, value] of Object.entries(values ?? {})) {
|
|
396
|
+
if (["model", "mode", "reasoning_effort", "effort", "variant"].includes(key))
|
|
397
|
+
continue;
|
|
398
|
+
result[key] = value;
|
|
399
|
+
}
|
|
400
|
+
return result;
|
|
401
|
+
}
|
|
402
|
+
function openCodeSessionModelMatches(response, requestedModel) {
|
|
403
|
+
const model = openCodeModelValue(requestedModel);
|
|
404
|
+
if (!model)
|
|
405
|
+
return true;
|
|
406
|
+
const currentModel = openCodeCurrentModelId(response);
|
|
407
|
+
return !currentModel || currentModel === model;
|
|
408
|
+
}
|
|
409
|
+
function openCodeCurrentModelId(response) {
|
|
410
|
+
const models = objectOrNull(response?.models);
|
|
411
|
+
const value = models?.currentModelId;
|
|
412
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
413
|
+
}
|
|
414
|
+
function openCodeModeValue(mode) {
|
|
415
|
+
const normalized = String(mode || "").trim();
|
|
416
|
+
if (!normalized)
|
|
417
|
+
return null;
|
|
418
|
+
if (["agent-full-access", "full-access", "bypassPermissions", "danger-full-access"].includes(normalized))
|
|
419
|
+
return "build";
|
|
420
|
+
if (normalized === "read-only")
|
|
421
|
+
return "plan";
|
|
422
|
+
return normalized;
|
|
423
|
+
}
|
|
424
|
+
function stringParam(params, key) {
|
|
425
|
+
const record = objectOrNull(params);
|
|
426
|
+
const value = record?.[key];
|
|
427
|
+
return typeof value === "string" && value.trim() ? value : null;
|
|
428
|
+
}
|
|
429
|
+
function resolveScopedPath(root, filePath) {
|
|
430
|
+
if (!filePath)
|
|
431
|
+
throw new Error("ACP file request did not include a path");
|
|
432
|
+
const resolved = path.resolve(root, filePath);
|
|
433
|
+
const rootResolved = path.resolve(root);
|
|
434
|
+
if (resolved !== rootResolved && !resolved.startsWith(`${rootResolved}${path.sep}`)) {
|
|
435
|
+
throw new Error(`ACP file request is outside project root: ${filePath}`);
|
|
436
|
+
}
|
|
437
|
+
return resolved;
|
|
438
|
+
}
|
|
439
|
+
function permissionRequestDetail(request) {
|
|
440
|
+
const params = objectOrNull(request.params) ?? request;
|
|
441
|
+
for (const key of ["command", "cwd", "reason", "grantRoot", "method"]) {
|
|
442
|
+
const value = params[key];
|
|
443
|
+
if (typeof value === "string" && value.trim())
|
|
444
|
+
return textPreview(value);
|
|
445
|
+
}
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
function userInputRequestDetail(request) {
|
|
449
|
+
for (const key of ["prompt", "message", "question", "title"]) {
|
|
450
|
+
const value = request[key];
|
|
451
|
+
if (typeof value === "string" && value.trim())
|
|
452
|
+
return textPreview(value);
|
|
453
|
+
}
|
|
454
|
+
return undefined;
|
|
455
|
+
}
|
|
456
|
+
function textPreview(value) {
|
|
457
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
458
|
+
return normalized.length > 120 ? `${normalized.slice(0, 117)}...` : normalized;
|
|
459
|
+
}
|
|
460
|
+
function errorMessage(error) {
|
|
461
|
+
return error instanceof Error ? error.message : String(error);
|
|
462
|
+
}
|
|
463
|
+
function isInvalidParamsError(error) {
|
|
464
|
+
return /\binvalid params\b/i.test(errorMessage(error));
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* OpenCode ACP 对图片仅接受标准 base64 data,不兼容本地 uri 参数。
|
|
468
|
+
* 本地附件路径仍会通过 Job Worker 拼入文本提示,供角色使用工具读取。
|
|
469
|
+
*/
|
|
470
|
+
function promptBlocksToOpenCodeAcpContent(prompt, blocks) {
|
|
471
|
+
const inputBlocks = blocks?.length ? blocks : [{ type: "text", text: prompt }];
|
|
472
|
+
return inputBlocks.map((block) => {
|
|
473
|
+
if (block.type === "image") {
|
|
474
|
+
return { type: "image", data: block.data, mimeType: block.mimeType };
|
|
475
|
+
}
|
|
476
|
+
return { type: "text", text: block.text };
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
function readOpenCodeDefaultModel() {
|
|
480
|
+
return process.env.ACA_OPENCODE_DEFAULT_MODEL || "";
|
|
481
|
+
}
|
|
482
|
+
function openCodeModelValue(model) {
|
|
483
|
+
const normalized = String(model || readOpenCodeDefaultModel()).trim();
|
|
484
|
+
return normalized === "default" || normalized === "opencode-default" ? "" : normalized;
|
|
485
|
+
}
|
|
486
|
+
function readOpenCodePromptTimeoutMs() {
|
|
487
|
+
const parsed = Number.parseInt(process.env.ACA_OPENCODE_PROMPT_TIMEOUT_MS ?? process.env.ACA_ACP_PROMPT_TIMEOUT_MS ?? "", 10);
|
|
488
|
+
return Number.isInteger(parsed) && parsed >= 30_000 ? parsed : 6 * 60 * 60 * 1000;
|
|
489
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { NativeCodexProvider } from "./codex/provider.js";
|
|
2
|
+
import { CodexAcpProvider } from "./codex-acp/provider.js";
|
|
3
|
+
import { MimoCodeProvider } from "./mimo/provider.js";
|
|
4
|
+
import { OpenCodeProvider } from "./opencode/provider.js";
|
|
5
|
+
export function createAgentProvider(input) {
|
|
6
|
+
const agentType = normalizeProviderKey(input.agentType || "codex");
|
|
7
|
+
const cliType = normalizeProviderKey(input.cliType || "builtin");
|
|
8
|
+
if (cliType !== "builtin") {
|
|
9
|
+
throw new Error(`Unsupported ACP cliType: ${input.cliType ?? ""}`);
|
|
10
|
+
}
|
|
11
|
+
if (agentType === "codex" || agentType === "codexacp" || agentType === "codexstandard")
|
|
12
|
+
return new CodexAcpProvider();
|
|
13
|
+
if (agentType === "nativecodex" || agentType === "codexnative")
|
|
14
|
+
return new NativeCodexProvider();
|
|
15
|
+
if (agentType === "mimo" || agentType === "mimocode" || agentType === "mimocodeprovider")
|
|
16
|
+
return new MimoCodeProvider();
|
|
17
|
+
if (agentType === "opencode" || agentType === "opencodeprovider")
|
|
18
|
+
return new OpenCodeProvider();
|
|
19
|
+
throw new Error(`Unsupported ACP agentType: ${input.agentType ?? ""}`);
|
|
20
|
+
}
|
|
21
|
+
function normalizeProviderKey(value) {
|
|
22
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, "");
|
|
23
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
export const STANDARD_AGENT_EVENT_TYPES = new Set([
|
|
2
|
+
"agent_message_chunk",
|
|
3
|
+
"agent_progress_chunk",
|
|
4
|
+
"agent_thought_chunk",
|
|
5
|
+
"tool_call",
|
|
6
|
+
"tool_call_update",
|
|
7
|
+
"plan",
|
|
8
|
+
"plan_update",
|
|
9
|
+
"plan_removed",
|
|
10
|
+
"usage_update",
|
|
11
|
+
"session_info_update",
|
|
12
|
+
"available_commands_update",
|
|
13
|
+
"current_mode_update",
|
|
14
|
+
"config_option_update"
|
|
15
|
+
]);
|
|
16
|
+
export function createAgentMessageChunk(input) {
|
|
17
|
+
return createTextEvent("agent_message_chunk", "message", input);
|
|
18
|
+
}
|
|
19
|
+
export function createAgentProgressChunk(input) {
|
|
20
|
+
return createTextEvent("agent_progress_chunk", "progress", input);
|
|
21
|
+
}
|
|
22
|
+
export function createAgentThoughtChunk(input) {
|
|
23
|
+
return createTextEvent("agent_thought_chunk", "thought", input);
|
|
24
|
+
}
|
|
25
|
+
export function createToolCall(input) {
|
|
26
|
+
return createToolEvent({ ...input, sessionUpdate: "tool_call", status: input.status || "in_progress" });
|
|
27
|
+
}
|
|
28
|
+
export function createToolCallUpdate(input) {
|
|
29
|
+
return createToolEvent({ ...input, sessionUpdate: "tool_call_update" });
|
|
30
|
+
}
|
|
31
|
+
export function normalizeToolKind(value) {
|
|
32
|
+
const normalized = String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
33
|
+
if (["read", "view", "open", "list", "ls", "glob"].some((item) => normalized.includes(item)))
|
|
34
|
+
return "read";
|
|
35
|
+
if (["edit", "write", "patch", "update", "create"].some((item) => normalized.includes(item)))
|
|
36
|
+
return "edit";
|
|
37
|
+
if (normalized.includes("delete") || normalized.includes("remove"))
|
|
38
|
+
return "delete";
|
|
39
|
+
if (normalized.includes("move") || normalized.includes("rename"))
|
|
40
|
+
return "move";
|
|
41
|
+
if (["search", "grep", "find", "ripgrep", "rg"].some((item) => normalized.includes(item)))
|
|
42
|
+
return "search";
|
|
43
|
+
if (["bash", "shell", "execute", "exec", "terminal", "command", "run"].some((item) => normalized.includes(item)))
|
|
44
|
+
return "execute";
|
|
45
|
+
if (normalized.includes("think") || normalized.includes("reason"))
|
|
46
|
+
return "think";
|
|
47
|
+
if (["fetch", "web", "http", "url"].some((item) => normalized.includes(item)))
|
|
48
|
+
return "fetch";
|
|
49
|
+
if (normalized.includes("switch_mode") || normalized.includes("switchmode"))
|
|
50
|
+
return "switch_mode";
|
|
51
|
+
return "other";
|
|
52
|
+
}
|
|
53
|
+
export function normalizeToolStatus(value) {
|
|
54
|
+
const normalized = String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
55
|
+
if (["pending", "queued"].includes(normalized))
|
|
56
|
+
return "pending";
|
|
57
|
+
if (["running", "started", "in_progress", "inprogress", "working"].includes(normalized))
|
|
58
|
+
return "in_progress";
|
|
59
|
+
if (["error", "failed", "failure"].includes(normalized))
|
|
60
|
+
return "failed";
|
|
61
|
+
if (["cancelled", "canceled"].includes(normalized))
|
|
62
|
+
return "cancelled";
|
|
63
|
+
return "completed";
|
|
64
|
+
}
|
|
65
|
+
export function createTextChunkUpdate(sessionUpdate, text) {
|
|
66
|
+
return {
|
|
67
|
+
sessionUpdate,
|
|
68
|
+
content: {
|
|
69
|
+
type: "text",
|
|
70
|
+
text
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export function assertStandardAgentEvent(event) {
|
|
75
|
+
if (!STANDARD_AGENT_EVENT_TYPES.has(event.type)) {
|
|
76
|
+
throw new Error(`Provider 输出了非标准事件类型: ${event.type}`);
|
|
77
|
+
}
|
|
78
|
+
const update = standardUpdateRecord(event);
|
|
79
|
+
if (event.type === "agent_message_chunk" || event.type === "agent_progress_chunk" || event.type === "agent_thought_chunk") {
|
|
80
|
+
if (update.sessionUpdate !== event.type)
|
|
81
|
+
throw new Error(`${event.type} 缺少匹配的 raw.update.sessionUpdate`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (event.type === "tool_call" || event.type === "tool_call_update") {
|
|
85
|
+
if (update.sessionUpdate !== event.type)
|
|
86
|
+
throw new Error(`${event.type} 缺少匹配的 raw.update.sessionUpdate`);
|
|
87
|
+
assertNonEmptyString(update.toolCallId, `${event.type}.raw.update.toolCallId`);
|
|
88
|
+
assertNonEmptyString(update.kind, `${event.type}.raw.update.kind`);
|
|
89
|
+
assertNonEmptyString(update.status, `${event.type}.raw.update.status`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export function standardUpdateRecord(event) {
|
|
93
|
+
const raw = event.raw;
|
|
94
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
95
|
+
throw new Error(`${event.type} 缺少 raw 对象`);
|
|
96
|
+
const update = raw.update;
|
|
97
|
+
if (!update || typeof update !== "object" || Array.isArray(update))
|
|
98
|
+
throw new Error(`${event.type} 缺少 raw.update 对象`);
|
|
99
|
+
return update;
|
|
100
|
+
}
|
|
101
|
+
export function firstString(...values) {
|
|
102
|
+
for (const value of values) {
|
|
103
|
+
if (typeof value === "string" && value.trim())
|
|
104
|
+
return value.trim();
|
|
105
|
+
}
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
export function removeUndefined(value) {
|
|
109
|
+
for (const key of Object.keys(value)) {
|
|
110
|
+
if (value[key] === undefined)
|
|
111
|
+
delete value[key];
|
|
112
|
+
}
|
|
113
|
+
return value;
|
|
114
|
+
}
|
|
115
|
+
function createTextEvent(type, label, input) {
|
|
116
|
+
return {
|
|
117
|
+
type,
|
|
118
|
+
label,
|
|
119
|
+
...(input.text ? { text: input.text } : {}),
|
|
120
|
+
raw: {
|
|
121
|
+
method: input.method,
|
|
122
|
+
params: input.params,
|
|
123
|
+
update: createTextChunkUpdate(type, input.text)
|
|
124
|
+
},
|
|
125
|
+
atMs: input.atMs ?? Date.now()
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function createToolEvent(input) {
|
|
129
|
+
const sessionUpdate = input.sessionUpdate ?? "tool_call_update";
|
|
130
|
+
const kind = normalizeToolKind(input.kind);
|
|
131
|
+
const status = normalizeToolStatus(input.status);
|
|
132
|
+
const update = removeUndefined({
|
|
133
|
+
sessionUpdate,
|
|
134
|
+
toolCallId: input.toolCallId,
|
|
135
|
+
kind,
|
|
136
|
+
title: input.title,
|
|
137
|
+
status,
|
|
138
|
+
rawInput: input.rawInput,
|
|
139
|
+
rawOutput: input.rawOutput,
|
|
140
|
+
content: input.content,
|
|
141
|
+
locations: input.locations,
|
|
142
|
+
_meta: input.meta
|
|
143
|
+
});
|
|
144
|
+
return {
|
|
145
|
+
type: sessionUpdate,
|
|
146
|
+
label: sessionUpdate === "tool_call" ? "tool call" : "tool update",
|
|
147
|
+
status,
|
|
148
|
+
toolCallId: input.toolCallId,
|
|
149
|
+
raw: {
|
|
150
|
+
method: input.method,
|
|
151
|
+
params: input.params,
|
|
152
|
+
tool: removeUndefined({
|
|
153
|
+
id: input.toolCallId,
|
|
154
|
+
kind,
|
|
155
|
+
title: input.title,
|
|
156
|
+
rawInput: input.rawInput,
|
|
157
|
+
rawOutput: input.rawOutput
|
|
158
|
+
}),
|
|
159
|
+
update
|
|
160
|
+
},
|
|
161
|
+
atMs: input.atMs ?? Date.now()
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function assertNonEmptyString(value, field) {
|
|
165
|
+
if (typeof value !== "string" || !value.trim())
|
|
166
|
+
throw new Error(`Provider 标准事件字段无效: ${field}`);
|
|
167
|
+
}
|