@anureo/adapter-acp 0.2.0 → 0.3.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 +60 -14
- package/package.json +15 -16
- package/src/adapter.d.ts +214 -0
- package/src/adapter.js +944 -0
- package/src/diagnostics.d.ts +36 -0
- package/src/diagnostics.js +91 -0
- package/src/dsh.d.ts +32 -0
- package/src/dsh.js +31 -0
- package/src/extensions.d.ts +25 -0
- package/src/extensions.js +30 -0
- package/src/file-changes.d.ts +9 -0
- package/src/file-changes.js +29 -0
- package/src/index.d.ts +3 -0
- package/src/index.js +3 -0
- package/src/mapping.d.ts +119 -0
- package/src/mapping.js +504 -0
- package/src/options.d.ts +103 -0
- package/src/options.js +0 -0
- package/src/request-error.d.ts +6 -0
- package/src/request-error.js +22 -0
- package/src/stdio.d.ts +9 -0
- package/src/stdio.js +108 -0
- package/src/stop.d.ts +18 -0
- package/src/stop.js +30 -0
- package/dist/file-changes.d.ts +0 -3
- package/dist/index.d.ts +0 -98
- package/dist/index.js +0 -852
- package/dist/mapping.d.ts +0 -30
package/dist/index.js
DELETED
|
@@ -1,852 +0,0 @@
|
|
|
1
|
-
// packages/acp/src/file-changes.ts
|
|
2
|
-
function acpFileChanges(content) {
|
|
3
|
-
if (!Array.isArray(content))
|
|
4
|
-
return [];
|
|
5
|
-
return content.flatMap((value) => {
|
|
6
|
-
if (!value || typeof value !== "object")
|
|
7
|
-
return [];
|
|
8
|
-
const part = value;
|
|
9
|
-
if (part.type !== "diff" || typeof part.path !== "string" || !(part.oldText === undefined || part.oldText === null || typeof part.oldText === "string") || typeof part.newText !== "string")
|
|
10
|
-
return [];
|
|
11
|
-
const oldText = part.oldText ?? null;
|
|
12
|
-
return [{ path: part.path, operation: oldText === null ? "add" : "modify", materials: [{ format: "text", scope: "file", oldText, newText: part.newText }], completeness: "complete" }];
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
// packages/acp/src/index.ts
|
|
17
|
-
import * as acp from "@agentclientprotocol/sdk";
|
|
18
|
-
import {
|
|
19
|
-
spawnHarnessProcess,
|
|
20
|
-
HarnessSdkError as HarnessSdkError2,
|
|
21
|
-
waitForRequest
|
|
22
|
-
} from "@anureo/sdk";
|
|
23
|
-
import {
|
|
24
|
-
negotiateVersion,
|
|
25
|
-
assertResult,
|
|
26
|
-
assertDefinition
|
|
27
|
-
} from "@anureo/protocol";
|
|
28
|
-
|
|
29
|
-
// packages/acp/src/mapping.ts
|
|
30
|
-
import { publicValue } from "@anureo/protocol";
|
|
31
|
-
import { HarnessSdkError } from "@anureo/sdk";
|
|
32
|
-
function record(value) {
|
|
33
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
34
|
-
}
|
|
35
|
-
function safe(value) {
|
|
36
|
-
return publicValue(JSON.parse(JSON.stringify(value ?? null)));
|
|
37
|
-
}
|
|
38
|
-
function text(value) {
|
|
39
|
-
if (typeof value === "string")
|
|
40
|
-
return value;
|
|
41
|
-
if (Array.isArray(value))
|
|
42
|
-
return value.map(text).join(`
|
|
43
|
-
`);
|
|
44
|
-
const object = record(value);
|
|
45
|
-
if (object.type === "text" && typeof object.text === "string")
|
|
46
|
-
return object.text;
|
|
47
|
-
if (object.type === "content")
|
|
48
|
-
return text(object.content);
|
|
49
|
-
if (object.type === "diff")
|
|
50
|
-
return `${typeof object.oldText === "string" ? object.oldText : ""}
|
|
51
|
-
${typeof object.newText === "string" ? object.newText : ""}`;
|
|
52
|
-
if (object.type === "resource")
|
|
53
|
-
return text(object.resource);
|
|
54
|
-
return "";
|
|
55
|
-
}
|
|
56
|
-
function input(blocks) {
|
|
57
|
-
return blocks.map((block) => {
|
|
58
|
-
if (block.type === "text")
|
|
59
|
-
return { type: "text", text: block.text };
|
|
60
|
-
if (block.type === "file")
|
|
61
|
-
return { type: "resource_link", uri: block.uri, name: block.name ?? block.uri, ...block.mimeType ? { mimeType: block.mimeType } : {} };
|
|
62
|
-
if (!block.data || !block.mimeType)
|
|
63
|
-
throw new HarnessSdkError("INVALID_PARAMS", "ACP images require inline data and mimeType");
|
|
64
|
-
return { type: "image", data: block.data, mimeType: block.mimeType, ...block.url ? { uri: block.url } : {} };
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
function mcp(servers = []) {
|
|
68
|
-
return servers.map((server) => server.type === "http" ? { type: "http", name: server.name, url: server.url, headers: Object.entries(server.headers ?? {}).map(([name, value]) => ({ name, value })) } : { name: server.name, command: server.command, args: server.args ?? [], env: Object.entries(server.env ?? {}).map(([name, value]) => ({ name, value })) });
|
|
69
|
-
}
|
|
70
|
-
function selectValues(value) {
|
|
71
|
-
return Array.isArray(value) ? value.flatMap((entry) => {
|
|
72
|
-
const option = record(entry);
|
|
73
|
-
return typeof option.value === "string" ? [option.value] : selectValues(option.options);
|
|
74
|
-
}) : [];
|
|
75
|
-
}
|
|
76
|
-
function configuration(data) {
|
|
77
|
-
const options = [], values = {}, keys = new Map;
|
|
78
|
-
for (const item of Array.isArray(data.configOptions) ? data.configOptions : []) {
|
|
79
|
-
const option = record(item);
|
|
80
|
-
if (typeof option.id !== "string")
|
|
81
|
-
continue;
|
|
82
|
-
const id = option.id;
|
|
83
|
-
const current = option.currentValue;
|
|
84
|
-
if (option.type !== "boolean" && option.type !== "select")
|
|
85
|
-
continue;
|
|
86
|
-
const schema = option.type === "boolean" ? { type: "boolean" } : { type: "string", enum: selectValues(option.options) };
|
|
87
|
-
const descriptor = { id, title: typeof option.name === "string" ? option.name : id, scope: "session", schema, ...typeof current === "string" || typeof current === "boolean" ? { value: current } : {} };
|
|
88
|
-
options.push(descriptor);
|
|
89
|
-
keys.set(id, option);
|
|
90
|
-
if (descriptor.value !== undefined)
|
|
91
|
-
values[id] = descriptor.value;
|
|
92
|
-
if (option.category === "model" && id !== "model") {
|
|
93
|
-
options.push({ ...descriptor, id: "model" });
|
|
94
|
-
keys.set("model", option);
|
|
95
|
-
if (descriptor.value !== undefined)
|
|
96
|
-
values.model = descriptor.value;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
const modes = record(data.modes);
|
|
100
|
-
if (Array.isArray(modes.availableModes)) {
|
|
101
|
-
const modeIds = modes.availableModes.map((mode) => record(mode).id).filter((id) => typeof id === "string");
|
|
102
|
-
options.push({ id: "mode", title: "ACP mode", scope: "session", schema: { type: "string", enum: modeIds } });
|
|
103
|
-
keys.set("mode", { id: "mode", type: "mode", options: modeIds });
|
|
104
|
-
if (typeof modes.currentModeId === "string")
|
|
105
|
-
values.mode = modes.currentModeId;
|
|
106
|
-
}
|
|
107
|
-
return { options, values, keys };
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
class AcpUpdateMapper {
|
|
111
|
-
sink;
|
|
112
|
-
getTurn;
|
|
113
|
-
state;
|
|
114
|
-
setState;
|
|
115
|
-
subagents;
|
|
116
|
-
items = new Map;
|
|
117
|
-
ended = new Set;
|
|
118
|
-
serial = 0;
|
|
119
|
-
compaction = new Map;
|
|
120
|
-
constructor(sink, getTurn, state, setState, subagents) {
|
|
121
|
-
this.sink = sink;
|
|
122
|
-
this.getTurn = getTurn;
|
|
123
|
-
this.state = state;
|
|
124
|
-
this.setState = setState;
|
|
125
|
-
this.subagents = subagents;
|
|
126
|
-
}
|
|
127
|
-
reset() {
|
|
128
|
-
this.items.clear();
|
|
129
|
-
this.ended.clear();
|
|
130
|
-
this.compaction.clear();
|
|
131
|
-
this.serial = 0;
|
|
132
|
-
}
|
|
133
|
-
async upsert(item, terminal = false) {
|
|
134
|
-
const turnId = this.getTurn();
|
|
135
|
-
if (!turnId)
|
|
136
|
-
return;
|
|
137
|
-
const old = this.items.get(item.id);
|
|
138
|
-
this.items.set(item.id, item);
|
|
139
|
-
if (this.ended.has(item.id))
|
|
140
|
-
return;
|
|
141
|
-
if (!old)
|
|
142
|
-
await this.sink.emit({ type: "item/started", payload: { item } }, { turnId });
|
|
143
|
-
else if (!terminal)
|
|
144
|
-
await this.sink.emit({ type: "item/delta", payload: { itemId: item.id, kind: "patch", value: safe(item) } }, { turnId });
|
|
145
|
-
if (terminal) {
|
|
146
|
-
this.ended.add(item.id);
|
|
147
|
-
await this.sink.emit({ type: "item/completed", payload: { item } }, { turnId });
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
async complete() {
|
|
151
|
-
for (const item of this.items.values())
|
|
152
|
-
if (!this.ended.has(item.id))
|
|
153
|
-
await this.upsert({ ...item, status: item.status === "running" ? "completed" : item.status }, true);
|
|
154
|
-
}
|
|
155
|
-
async update(update) {
|
|
156
|
-
const kind = update.sessionUpdate;
|
|
157
|
-
const turnId = this.getTurn();
|
|
158
|
-
if (kind === "config_option_update" || kind === "current_mode_update") {
|
|
159
|
-
this.setState(update);
|
|
160
|
-
await this.sink.emit({ type: "session/state", payload: this.state() });
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
if (kind === "usage_update") {
|
|
164
|
-
await this.sink.emit({ type: "usage/updated", payload: { provider: "acp", scope: "session", source: "native", ...typeof update.used === "number" ? { contextUsed: update.used } : {}, ...typeof update.size === "number" ? { contextWindow: update.size } : {} } }, { ...turnId ? { turnId } : {} });
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
if (kind === "session_info_update") {
|
|
168
|
-
if (Object.hasOwn(update, "title") && (typeof update.title === "string" || update.title === null)) {
|
|
169
|
-
const title = update.title;
|
|
170
|
-
if (this.state().metadata?.title !== title) {
|
|
171
|
-
this.setState({ sessionTitle: title });
|
|
172
|
-
await this.sink.emit({ type: "session/metadata", payload: { title } });
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
if (!turnId || kind === "available_commands_update") {
|
|
178
|
-
await this.sink.emit({ type: "notice", payload: { severity: "info", code: `ACP_${String(kind ?? "UPDATE").toUpperCase()}`, message: "ACP session metadata update", raw: safe(update) } });
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
if (["agent_message_chunk", "agent_thought_chunk", "user_message_chunk"].includes(String(kind))) {
|
|
182
|
-
const nativeId = typeof update.messageId === "string" ? update.messageId : String(kind);
|
|
183
|
-
const id = `${String(kind)}:${nativeId}`;
|
|
184
|
-
const chunk = text(update.content);
|
|
185
|
-
if (!chunk && record(update.content).type !== "text")
|
|
186
|
-
await this.sink.emit({ type: "notice", payload: { severity: "info", code: "ACP_NON_TEXT_CONTENT", message: "ACP non-text content retained", raw: safe(update.content) } }, { turnId });
|
|
187
|
-
let item = this.items.get(id);
|
|
188
|
-
if (!item) {
|
|
189
|
-
item = kind === "agent_thought_chunk" ? { id, type: "reasoning", text: "" } : kind === "user_message_chunk" ? { id, type: "userMessage", content: [] } : { id, type: "agentMessage", text: "", phase: "final" };
|
|
190
|
-
this.items.set(id, item);
|
|
191
|
-
await this.sink.emit({ type: "item/started", payload: { item } }, { turnId });
|
|
192
|
-
}
|
|
193
|
-
if (item.type === "userMessage") {
|
|
194
|
-
const content = record(update.content);
|
|
195
|
-
if (content.type === "text")
|
|
196
|
-
item.content.push({ type: "text", text: chunk });
|
|
197
|
-
else if (content.type === "image" && typeof content.data === "string")
|
|
198
|
-
item.content.push({ type: "image", data: content.data, mimeType: typeof content.mimeType === "string" ? content.mimeType : undefined });
|
|
199
|
-
else if (content.type === "resource_link" && typeof content.uri === "string")
|
|
200
|
-
item.content.push({ type: "file", uri: content.uri });
|
|
201
|
-
else
|
|
202
|
-
await this.sink.emit({ type: "notice", payload: { severity: "info", code: "ACP_UNKNOWN_CONTENT", message: "ACP user content", raw: safe(update.content) } }, { turnId });
|
|
203
|
-
await this.sink.emit({ type: "item/delta", payload: { itemId: id, kind: "patch", value: safe(item) } }, { turnId });
|
|
204
|
-
} else if (item.type === "agentMessage" || item.type === "reasoning") {
|
|
205
|
-
item.text = (item.text ?? "") + chunk;
|
|
206
|
-
await this.sink.emit({ type: "item/delta", payload: { itemId: id, kind: "text", text: chunk } }, { turnId });
|
|
207
|
-
}
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
210
|
-
if (kind === "tool_call" || kind === "tool_call_update") {
|
|
211
|
-
const id = String(update.toolCallId);
|
|
212
|
-
const old = this.items.get(id);
|
|
213
|
-
const kindMap = { execute: "command", edit: "fileChange", delete: "fileChange", move: "fileChange", fetch: "web" };
|
|
214
|
-
const status = update.status === "failed" ? "failed" : update.status === "completed" ? "completed" : update.status === undefined && old?.type === "toolCall" ? old.status ?? "running" : "running";
|
|
215
|
-
const item = {
|
|
216
|
-
...old?.type === "toolCall" ? old : { id, type: "toolCall", kind: "other", title: "ACP tool" },
|
|
217
|
-
...typeof update.title === "string" ? { title: update.title } : {},
|
|
218
|
-
...typeof update.kind === "string" ? { kind: kindMap[update.kind] ?? "other", nativeType: update.kind } : {},
|
|
219
|
-
status,
|
|
220
|
-
...update.content !== undefined ? { fileChanges: acpFileChanges(update.content) } : {},
|
|
221
|
-
...update.rawInput !== undefined ? { input: safe(update.rawInput) } : {},
|
|
222
|
-
...update.rawOutput !== undefined ? { output: safe(update.rawOutput) } : update.content !== undefined ? { output: safe(update.content) } : {},
|
|
223
|
-
...Array.isArray(update.locations) ? { locations: update.locations.flatMap((location) => {
|
|
224
|
-
const value = record(location);
|
|
225
|
-
return typeof value.path === "string" ? [{ path: value.path, ...typeof value.line === "number" ? { line: value.line } : {} }] : [];
|
|
226
|
-
}) } : {}
|
|
227
|
-
};
|
|
228
|
-
await this.upsert(item, status !== "running");
|
|
229
|
-
return;
|
|
230
|
-
}
|
|
231
|
-
if (kind === "plan") {
|
|
232
|
-
const entries = Array.isArray(update.entries) ? update.entries : [];
|
|
233
|
-
await this.upsert({ id: "acp-plan", type: "plan", steps: entries.map((entry, index) => {
|
|
234
|
-
const value = record(entry);
|
|
235
|
-
return { id: String(index), text: String(value.content ?? ""), status: value.status === "completed" ? "completed" : value.status === "in_progress" ? "inProgress" : "pending" };
|
|
236
|
-
}) });
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
if (kind === "plan_update" || kind === "plan_removed") {
|
|
240
|
-
const plan = record(update.plan);
|
|
241
|
-
const id = `plan:${String(update.planId ?? plan.planId ?? ++this.serial)}`;
|
|
242
|
-
await this.upsert({ id, type: "plan", steps: kind === "plan_removed" ? [] : [{ id: "content", text: text(plan.content ?? record(plan).markdown ?? plan), status: "pending" }], extensions: { "x-acp/native-plan": safe(update) } }, kind === "plan_removed");
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
if (kind === "compaction_update" || kind === "compaction_summary_chunk") {
|
|
246
|
-
const id = `compaction:${String(update.compactionId)}`;
|
|
247
|
-
let summary = this.compaction.get(id) ?? "";
|
|
248
|
-
if (kind === "compaction_summary_chunk")
|
|
249
|
-
summary += text(update.content);
|
|
250
|
-
else if ("summary" in update)
|
|
251
|
-
summary = text(update.summary);
|
|
252
|
-
this.compaction.set(id, summary);
|
|
253
|
-
const terminal = update.status === "completed" || update.status === "failed" || update.status === "cancelled";
|
|
254
|
-
await this.upsert({ id, type: "compaction", summary, status: update.status === "failed" ? "failed" : update.status === "cancelled" ? "interrupted" : terminal ? "completed" : "running" }, terminal);
|
|
255
|
-
return;
|
|
256
|
-
}
|
|
257
|
-
if ((kind === "subagent_spawned" || kind === "subagent_state_update") && this.subagents) {
|
|
258
|
-
const id = `subagent:${String(update.subagentSessionId)}`;
|
|
259
|
-
const old = this.items.get(id);
|
|
260
|
-
const state = update.state === "completed" ? "completed" : ["cancelled", "disconnected"].includes(String(update.state)) ? "interrupted" : update.state === "failed" ? "failed" : "running";
|
|
261
|
-
await this.upsert({ ...old?.type === "subagent" ? old : { id, type: "subagent", subagentId: String(update.subagentSessionId) }, state, ...typeof update.name === "string" ? { name: update.name } : {}, ...typeof update.task === "string" ? { task: update.task } : {} }, state !== "running");
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
await this.sink.emit({ type: "notice", payload: { severity: "info", code: "ACP_UNKNOWN_UPDATE", message: "Unmapped ACP update retained", raw: safe(update) } }, { turnId });
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
// packages/acp/src/index.ts
|
|
269
|
-
function deferred() {
|
|
270
|
-
let resolve, reject;
|
|
271
|
-
const promise = new Promise((yes, no) => {
|
|
272
|
-
resolve = yes;
|
|
273
|
-
reject = no;
|
|
274
|
-
});
|
|
275
|
-
promise.catch(() => {});
|
|
276
|
-
return { promise, resolve, reject };
|
|
277
|
-
}
|
|
278
|
-
function errorFromNative(error, fallback = "ACP_REQUEST_FAILED") {
|
|
279
|
-
if (error instanceof HarnessSdkError2)
|
|
280
|
-
return error;
|
|
281
|
-
if (error instanceof acp.RequestError) {
|
|
282
|
-
const code = error.code === -32601 ? "CAPABILITY_UNSUPPORTED" : error.code === -32602 ? "INVALID_PARAMS" : error.code === -32000 ? "AUTH_REQUIRED" : error.code === -32002 ? "RESOURCE_NOT_FOUND" : fallback;
|
|
283
|
-
return new HarnessSdkError2(code, code, false, false, { nativeCode: error.code });
|
|
284
|
-
}
|
|
285
|
-
return new HarnessSdkError2("ACP_CONNECTION_CLOSED", "ACP connection closed", false, true);
|
|
286
|
-
}
|
|
287
|
-
function extensions(response) {
|
|
288
|
-
const extension = record(record(record(response)._meta).ahp);
|
|
289
|
-
const methods = {};
|
|
290
|
-
const result = { methods, fork: [], revert: [], subagents: false, instructions: false, userInput: false, dynamicTool: false };
|
|
291
|
-
if (extension.version !== 1)
|
|
292
|
-
return result;
|
|
293
|
-
const names = record(extension.methods);
|
|
294
|
-
for (const key of ["fork", "revert", "steer", "history", "goalSet", "goalClear", "compact", "review"]) {
|
|
295
|
-
const name = names[key];
|
|
296
|
-
if (typeof name === "string" && /^_[a-zA-Z0-9/_.-]+$/.test(name))
|
|
297
|
-
methods[key] = name;
|
|
298
|
-
}
|
|
299
|
-
if (methods.fork && Array.isArray(extension.fork))
|
|
300
|
-
result.fork = extension.fork.filter((value) => value === "before" || value === "through");
|
|
301
|
-
if (methods.revert && Array.isArray(extension.revert))
|
|
302
|
-
result.revert = extension.revert.filter((value) => ["conversation", "files", "both"].includes(String(value)));
|
|
303
|
-
result.subagents = extension.subagents === true;
|
|
304
|
-
result.instructions = extension.instructions === true;
|
|
305
|
-
const requests = record(extension.clientRequests);
|
|
306
|
-
result.userInput = requests.userInput === "_ahp/user_input";
|
|
307
|
-
result.dynamicTool = requests.dynamicTool === "_ahp/dynamic_tool";
|
|
308
|
-
return result;
|
|
309
|
-
}
|
|
310
|
-
async function processStream(options) {
|
|
311
|
-
if (!options.command)
|
|
312
|
-
throw new HarnessSdkError2("HARNESS_UNAVAILABLE", "An ACP executable or stream factory is required");
|
|
313
|
-
const child = await spawnHarnessProcess({ command: options.command, args: options.args, cwd: options.cwd, env: options.env });
|
|
314
|
-
const iterator = child.stdout[Symbol.asyncIterator]();
|
|
315
|
-
let lineBytes = 0;
|
|
316
|
-
const incoming = new ReadableStream({
|
|
317
|
-
async pull(controller) {
|
|
318
|
-
try {
|
|
319
|
-
const value = await iterator.next();
|
|
320
|
-
if (value.done) {
|
|
321
|
-
controller.close();
|
|
322
|
-
return;
|
|
323
|
-
}
|
|
324
|
-
for (const byte of value.value) {
|
|
325
|
-
if (byte === 10)
|
|
326
|
-
lineBytes = 0;
|
|
327
|
-
else if (++lineBytes > (options.maxFrameBytes ?? 8 * 1024 * 1024))
|
|
328
|
-
throw new HarnessSdkError2("BACKPRESSURE_EXCEEDED", "ACP frame exceeds its limit");
|
|
329
|
-
}
|
|
330
|
-
controller.enqueue(value.value);
|
|
331
|
-
} catch (error) {
|
|
332
|
-
controller.error(error);
|
|
333
|
-
}
|
|
334
|
-
},
|
|
335
|
-
async cancel() {
|
|
336
|
-
await iterator.return?.();
|
|
337
|
-
}
|
|
338
|
-
});
|
|
339
|
-
let outgoingLineBytes = 0;
|
|
340
|
-
const outgoing = new WritableStream({ write: (chunk) => {
|
|
341
|
-
for (const byte of chunk) {
|
|
342
|
-
if (byte === 10)
|
|
343
|
-
outgoingLineBytes = 0;
|
|
344
|
-
else if (++outgoingLineBytes > (options.maxFrameBytes ?? 8 * 1024 * 1024))
|
|
345
|
-
throw new HarnessSdkError2("BACKPRESSURE_EXCEEDED", "ACP outgoing frame exceeds its limit");
|
|
346
|
-
}
|
|
347
|
-
return child.write(chunk);
|
|
348
|
-
}, close: () => child.closeInput() });
|
|
349
|
-
(async () => {
|
|
350
|
-
try {
|
|
351
|
-
for await (const _chunk of child.stderr) {}
|
|
352
|
-
} catch {}
|
|
353
|
-
})();
|
|
354
|
-
return { stream: acp.ndJsonStream(outgoing, incoming), dispose: () => child.dispose() };
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
class AcpAdapter {
|
|
358
|
-
options;
|
|
359
|
-
connection;
|
|
360
|
-
channel;
|
|
361
|
-
info;
|
|
362
|
-
sessions = new Map;
|
|
363
|
-
nativeSessions = new Map;
|
|
364
|
-
opening;
|
|
365
|
-
openTail = Promise.resolve();
|
|
366
|
-
deliveries = new Map;
|
|
367
|
-
closing = false;
|
|
368
|
-
extension = { methods: {}, fork: [], revert: [], subagents: false, instructions: false, userInput: false, dynamicTool: false };
|
|
369
|
-
capabilities = {};
|
|
370
|
-
constructor(options) {
|
|
371
|
-
this.options = options;
|
|
372
|
-
}
|
|
373
|
-
get nativeCapabilities() {
|
|
374
|
-
return this.info?.agentCapabilities ?? {};
|
|
375
|
-
}
|
|
376
|
-
get agent() {
|
|
377
|
-
if (!this.connection)
|
|
378
|
-
throw new HarnessSdkError2("ACP_CONNECTION_CLOSED");
|
|
379
|
-
return this.connection.agent;
|
|
380
|
-
}
|
|
381
|
-
backend(nativeId, allowOpening = false) {
|
|
382
|
-
const existing = this.nativeSessions.get(nativeId);
|
|
383
|
-
if (existing)
|
|
384
|
-
return existing;
|
|
385
|
-
if (allowOpening && this.opening && (!this.opening.nativeId || this.opening.nativeId === nativeId)) {
|
|
386
|
-
this.opening.nativeId = nativeId;
|
|
387
|
-
this.nativeSessions.set(nativeId, this.opening);
|
|
388
|
-
return this.opening;
|
|
389
|
-
}
|
|
390
|
-
throw new acp.RequestError(-32602, "Unknown ACP session");
|
|
391
|
-
}
|
|
392
|
-
async interaction(session, requestId, request, transform) {
|
|
393
|
-
const delivery = deferred();
|
|
394
|
-
this.deliveries.set(requestId, delivery);
|
|
395
|
-
return new Promise((resolve, reject) => {
|
|
396
|
-
let answered = false;
|
|
397
|
-
session.sink.requestInteraction(request, async (response) => {
|
|
398
|
-
answered = true;
|
|
399
|
-
resolve(transform(response));
|
|
400
|
-
await delivery.promise;
|
|
401
|
-
}).catch(() => {
|
|
402
|
-
if (!answered)
|
|
403
|
-
reject(new acp.RequestError(-32603, "Interaction could not be completed"));
|
|
404
|
-
});
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
async initialize(params) {
|
|
408
|
-
negotiateVersion(params.protocolVersions);
|
|
409
|
-
if (this.info)
|
|
410
|
-
return { protocolVersion: 1, runtime: this.runtime(), capabilities: structuredClone(this.capabilities) };
|
|
411
|
-
this.channel = this.options.connect ? await this.options.connect() : await processStream(this.options);
|
|
412
|
-
const rawReader = this.channel.stream.readable.getReader();
|
|
413
|
-
const rawWriter = this.channel.stream.writable.getWriter();
|
|
414
|
-
const wrapped = {
|
|
415
|
-
writable: new WritableStream({ write: async (frame) => {
|
|
416
|
-
try {
|
|
417
|
-
await rawWriter.write(frame);
|
|
418
|
-
if ("id" in frame && !("method" in frame)) {
|
|
419
|
-
this.deliveries.get(frame.id)?.resolve();
|
|
420
|
-
this.deliveries.delete(frame.id);
|
|
421
|
-
}
|
|
422
|
-
} catch (error) {
|
|
423
|
-
for (const delivery of this.deliveries.values())
|
|
424
|
-
delivery.reject(error);
|
|
425
|
-
throw error;
|
|
426
|
-
}
|
|
427
|
-
}, close: () => rawWriter.close(), abort: (reason) => rawWriter.abort(reason) }),
|
|
428
|
-
readable: new ReadableStream({ pull: async (controller) => {
|
|
429
|
-
try {
|
|
430
|
-
for (;; ) {
|
|
431
|
-
const next = await rawReader.read();
|
|
432
|
-
if (next.done) {
|
|
433
|
-
controller.close();
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
const frame = next.value;
|
|
437
|
-
if ("method" in frame && !("id" in frame) && frame.method === "session/update") {
|
|
438
|
-
const value = record(frame.params);
|
|
439
|
-
const session = this.backend(String(value.sessionId), true);
|
|
440
|
-
await session.update(record(value.update));
|
|
441
|
-
continue;
|
|
442
|
-
}
|
|
443
|
-
if ("method" in frame && !("id" in frame) && frame.method === "_ahp/event" && Object.keys(this.extension.methods).length) {
|
|
444
|
-
const value = record(frame.params);
|
|
445
|
-
const session = this.backend(String(value.sessionId));
|
|
446
|
-
const event = value.event;
|
|
447
|
-
assertDefinition("AhpEventPayload", event);
|
|
448
|
-
if (event.type === "turn/started")
|
|
449
|
-
session.activeTurn = event.payload.turnId;
|
|
450
|
-
await session.sink.emit(event, { ...typeof value.turnId === "string" ? { turnId: value.turnId } : {} });
|
|
451
|
-
if (event.type === "turn/completed" && session.activeTurn === event.payload.turnId)
|
|
452
|
-
session.activeTurn = undefined;
|
|
453
|
-
continue;
|
|
454
|
-
}
|
|
455
|
-
if ("method" in frame && !("id" in frame) && frame.method !== "elicitation/complete") {
|
|
456
|
-
const scope = record(frame.params).sessionId;
|
|
457
|
-
const recipients = typeof scope === "string" ? [this.backend(scope)] : [...this.sessions.values()];
|
|
458
|
-
for (const session of recipients)
|
|
459
|
-
await session.sink.emit({ type: "notice", payload: { severity: "info", code: "ACP_UNKNOWN_NOTIFICATION", message: "Unknown ACP notification retained", raw: safe({ method: frame.method, params: frame.params }) } });
|
|
460
|
-
continue;
|
|
461
|
-
}
|
|
462
|
-
controller.enqueue(frame);
|
|
463
|
-
return;
|
|
464
|
-
}
|
|
465
|
-
} catch (error) {
|
|
466
|
-
controller.error(error);
|
|
467
|
-
}
|
|
468
|
-
}, cancel: (reason) => rawReader.cancel(reason) })
|
|
469
|
-
};
|
|
470
|
-
const app = acp.client({ name: "anureo-harness-sdk-acp" }).onRequest("session/request_permission", (context) => {
|
|
471
|
-
const session = this.backend(context.params.sessionId);
|
|
472
|
-
return this.interaction(session, context.requestId, {
|
|
473
|
-
kind: "approval",
|
|
474
|
-
interactionId: `acp-permission:${String(context.requestId)}`,
|
|
475
|
-
turnId: session.activeTurn,
|
|
476
|
-
itemId: context.params.toolCall.toolCallId,
|
|
477
|
-
options: context.params.options.map((option) => ({ id: option.optionId, label: option.name, semantic: option.kind === "allow_once" ? "allowOnce" : option.kind === "allow_always" ? "allowSession" : "deny" })),
|
|
478
|
-
...context.params.toolCall.rawInput !== undefined ? { input: safe(context.params.toolCall.rawInput) } : {}
|
|
479
|
-
}, (response) => response?.kind === "approval" ? { outcome: { outcome: "selected", optionId: response.optionId } } : { outcome: { outcome: "cancelled" } });
|
|
480
|
-
}).onRequest("elicitation/create", (context) => {
|
|
481
|
-
const native = record(context.params);
|
|
482
|
-
if (typeof native.sessionId !== "string" || !["form", "url"].includes(String(native.mode)))
|
|
483
|
-
return { action: "cancel" };
|
|
484
|
-
const session = this.backend(native.sessionId);
|
|
485
|
-
const request = { kind: "elicitation", interactionId: `acp-elicitation:${String(context.requestId)}`, turnId: session.activeTurn, mode: native.mode, message: String(native.message ?? ""), ...native.mode === "form" ? { schema: safe(native.requestedSchema) } : { privatePayload: { url: String(native.url ?? ""), elicitationId: String(native.elicitationId ?? "") } } };
|
|
486
|
-
return this.interaction(session, context.requestId, request, (response) => response?.kind === "elicitation" ? { action: response.action, ...response.content ? { content: response.content } : {} } : { action: "cancel" });
|
|
487
|
-
}).onNotification("elicitation/complete", async (context) => {
|
|
488
|
-
for (const session of this.sessions.values())
|
|
489
|
-
await session.sink.emit({ type: "notice", payload: { severity: "info", code: "ACP_ELICITATION_COMPLETE", message: "External authorization completed", raw: safe(context.params) } });
|
|
490
|
-
}).onRequest("_ahp/user_input", (value) => record(value), (context) => this.extensionInteraction("userInput", context.requestId, context.params)).onRequest("_ahp/dynamic_tool", (value) => record(value), (context) => this.extensionInteraction("dynamicTool", context.requestId, context.params));
|
|
491
|
-
if (this.options.fs?.readTextFile)
|
|
492
|
-
app.onRequest("fs/read_text_file", (ctx) => {
|
|
493
|
-
this.backend(ctx.params.sessionId);
|
|
494
|
-
return this.options.fs.readTextFile(ctx.params);
|
|
495
|
-
});
|
|
496
|
-
if (this.options.fs?.writeTextFile)
|
|
497
|
-
app.onRequest("fs/write_text_file", (ctx) => {
|
|
498
|
-
this.backend(ctx.params.sessionId);
|
|
499
|
-
return this.options.fs.writeTextFile(ctx.params);
|
|
500
|
-
});
|
|
501
|
-
const terminal = this.options.terminal;
|
|
502
|
-
if (terminal) {
|
|
503
|
-
app.onRequest("terminal/create", async (ctx) => {
|
|
504
|
-
const session = this.backend(ctx.params.sessionId);
|
|
505
|
-
const result = await terminal.createTerminal(ctx.params);
|
|
506
|
-
session.terminals.add(result.terminalId);
|
|
507
|
-
return result;
|
|
508
|
-
});
|
|
509
|
-
app.onRequest("terminal/output", (ctx) => {
|
|
510
|
-
this.backend(ctx.params.sessionId).requireTerminal(ctx.params.terminalId);
|
|
511
|
-
return terminal.terminalOutput(ctx.params);
|
|
512
|
-
});
|
|
513
|
-
app.onRequest("terminal/wait_for_exit", (ctx) => {
|
|
514
|
-
this.backend(ctx.params.sessionId).requireTerminal(ctx.params.terminalId);
|
|
515
|
-
return terminal.waitForTerminalExit(ctx.params);
|
|
516
|
-
});
|
|
517
|
-
app.onRequest("terminal/kill", (ctx) => {
|
|
518
|
-
this.backend(ctx.params.sessionId).requireTerminal(ctx.params.terminalId);
|
|
519
|
-
return terminal.killTerminal(ctx.params);
|
|
520
|
-
});
|
|
521
|
-
app.onRequest("terminal/release", async (ctx) => {
|
|
522
|
-
const session = this.backend(ctx.params.sessionId);
|
|
523
|
-
session.requireTerminal(ctx.params.terminalId);
|
|
524
|
-
const result = await terminal.releaseTerminal(ctx.params);
|
|
525
|
-
session.terminals.delete(ctx.params.terminalId);
|
|
526
|
-
return result;
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
|
-
this.connection = app.connect(wrapped);
|
|
530
|
-
this.connection.closed.then(async () => {
|
|
531
|
-
const error = new HarnessSdkError2("ACP_CONNECTION_CLOSED", "ACP source connection closed", false, true);
|
|
532
|
-
for (const delivery of this.deliveries.values())
|
|
533
|
-
delivery.reject(error);
|
|
534
|
-
this.deliveries.clear();
|
|
535
|
-
if (!this.closing)
|
|
536
|
-
await Promise.all([...this.sessions.values()].map((session) => session.sink.fail(error).catch(() => {})));
|
|
537
|
-
});
|
|
538
|
-
this.info = await this.call("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientInfo: { name: "anureo-harness-sdk", version: "0.1.0" }, clientCapabilities: {
|
|
539
|
-
fs: { readTextFile: !!this.options.fs?.readTextFile, writeTextFile: !!this.options.fs?.writeTextFile },
|
|
540
|
-
terminal: !!terminal,
|
|
541
|
-
session: { configOptions: { boolean: {} }, compaction: {} },
|
|
542
|
-
plan: {},
|
|
543
|
-
elicitation: params.clientCapabilities?.interactions?.includes("elicitation") ? { form: {}, url: {} } : undefined,
|
|
544
|
-
_meta: { ahp: { version: 1, clientRequests: ["_ahp/user_input", "_ahp/dynamic_tool"] } }
|
|
545
|
-
} });
|
|
546
|
-
if (this.info.protocolVersion !== acp.PROTOCOL_VERSION) {
|
|
547
|
-
await this.dispose();
|
|
548
|
-
throw new HarnessSdkError2("PROTOCOL_VERSION_UNSUPPORTED");
|
|
549
|
-
}
|
|
550
|
-
this.extension = extensions(this.info);
|
|
551
|
-
const native = this.nativeCapabilities;
|
|
552
|
-
this.capabilities = {
|
|
553
|
-
session: { resume: native.loadSession === true || native.sessionCapabilities?.resume != null, fork: this.extension.fork, revert: this.extension.revert, history: !!this.extension.methods.history },
|
|
554
|
-
turn: { interrupt: true, steer: !!this.extension.methods.steer, inputModalities: ["text", ...native.promptCapabilities?.image ? ["image"] : [], ...native.promptCapabilities?.embeddedContext ? ["file"] : []] },
|
|
555
|
-
interactions: ["approval", "elicitation", ...this.extension.userInput ? ["userInput"] : [], ...this.extension.dynamicTool ? ["dynamicTool"] : []],
|
|
556
|
-
goal: { actions: [...this.extension.methods.goalSet ? ["set"] : [], ...this.extension.methods.goalClear ? ["clear"] : []] },
|
|
557
|
-
compact: !!this.extension.methods.compact,
|
|
558
|
-
review: !!this.extension.methods.review,
|
|
559
|
-
subagents: { events: this.extension.subagents ? "nested" : "none" },
|
|
560
|
-
mcp: { stdio: true, http: native.mcpCapabilities?.http === true, elicitation: ["form", "url"] },
|
|
561
|
-
config: { options: [] },
|
|
562
|
-
extensions: Object.keys(this.extension.methods).length || this.extension.subagents || this.extension.userInput || this.extension.dynamicTool ? [{ name: "x-acp/ahp", version: "1" }] : []
|
|
563
|
-
};
|
|
564
|
-
return { protocolVersion: 1, runtime: this.runtime(), capabilities: structuredClone(this.capabilities) };
|
|
565
|
-
}
|
|
566
|
-
runtime() {
|
|
567
|
-
return { name: this.info?.agentInfo?.name ?? "acp", version: this.info?.agentInfo?.version ?? "unknown", adapter: "acp/0.1.0" };
|
|
568
|
-
}
|
|
569
|
-
async call(method, params) {
|
|
570
|
-
try {
|
|
571
|
-
return await waitForRequest(() => this.agent.request(method, params), {}, this.options.requestTimeoutMs ?? 30000);
|
|
572
|
-
} catch (error) {
|
|
573
|
-
throw errorFromNative(error);
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
async extensionInteraction(kind, id, params) {
|
|
577
|
-
if (!this.extension[kind])
|
|
578
|
-
throw new acp.RequestError(-32601, "Extension was not negotiated");
|
|
579
|
-
const session = this.backend(String(params.sessionId));
|
|
580
|
-
const request = { ...record(params.request), kind, interactionId: `acp-${kind}:${String(id)}`, turnId: session.activeTurn };
|
|
581
|
-
assertDefinition("InteractionRequested", request);
|
|
582
|
-
return this.interaction(session, id, request, (response) => response ?? { cancelled: true });
|
|
583
|
-
}
|
|
584
|
-
async openSession(params, sink) {
|
|
585
|
-
const old = this.openTail;
|
|
586
|
-
let release;
|
|
587
|
-
this.openTail = new Promise((resolve) => {
|
|
588
|
-
release = resolve;
|
|
589
|
-
});
|
|
590
|
-
await old;
|
|
591
|
-
const session = new AcpBackendSession(this, params, sink);
|
|
592
|
-
this.opening = session;
|
|
593
|
-
try {
|
|
594
|
-
if (params.instructions && !this.extension.instructions)
|
|
595
|
-
throw new HarnessSdkError2("CAPABILITY_UNSUPPORTED", "ACP peer did not negotiate instructions");
|
|
596
|
-
const common = { cwd: params.cwd, mcpServers: mcp(params.mcpServers), ...params.instructions ? { _meta: { ahp: { version: 1, instructions: params.instructions } } } : {} };
|
|
597
|
-
let response;
|
|
598
|
-
if (params.mode === "new")
|
|
599
|
-
response = record(await this.call("session/new", common));
|
|
600
|
-
else if (params.mode === "resume") {
|
|
601
|
-
if (!params.binding.nativeRef || params.binding.nativeRef.provider !== "acp")
|
|
602
|
-
throw new HarnessSdkError2("SESSION_BINDING_MISMATCH");
|
|
603
|
-
session.nativeId = params.binding.nativeRef.value;
|
|
604
|
-
this.nativeSessions.set(session.nativeId, session);
|
|
605
|
-
session.hydrating = true;
|
|
606
|
-
response = record(await this.call(this.nativeCapabilities.sessionCapabilities?.resume != null ? "session/resume" : "session/load", { ...common, sessionId: session.nativeId }));
|
|
607
|
-
} else {
|
|
608
|
-
const nativeRef = params.fork?.nativeRef ?? this.sessions.get(params.fork.sourceSessionId)?.binding.nativeRef;
|
|
609
|
-
if (!nativeRef || !this.extension.methods.fork)
|
|
610
|
-
throw new HarnessSdkError2("CAPABILITY_UNSUPPORTED");
|
|
611
|
-
response = record(await this.call(this.extension.methods.fork, { ...common, sessionId: nativeRef.value, boundary: params.fork.boundary }));
|
|
612
|
-
}
|
|
613
|
-
if (typeof response.sessionId === "string") {
|
|
614
|
-
if (session.nativeId && response.sessionId !== session.nativeId)
|
|
615
|
-
throw new HarnessSdkError2("ACP_PROTOCOL_ERROR", "ACP session identity changed while opening");
|
|
616
|
-
session.nativeId = response.sessionId;
|
|
617
|
-
}
|
|
618
|
-
if (!session.nativeId)
|
|
619
|
-
throw new HarnessSdkError2("ACP_PROTOCOL_ERROR", "ACP session response lacked an identity");
|
|
620
|
-
this.nativeSessions.set(session.nativeId, session);
|
|
621
|
-
this.sessions.set(params.binding.sessionId, session);
|
|
622
|
-
session.configure(response);
|
|
623
|
-
session.hydrating = false;
|
|
624
|
-
if (session.loadedSnapshot.length)
|
|
625
|
-
this.options.onLoadSnapshot?.(session.binding, session.loadedSnapshot);
|
|
626
|
-
const patch = { ...params.config, ...params.model ? { model: params.model } : {}, ...params.permissionMode ? { permissionMode: params.permissionMode } : {} };
|
|
627
|
-
if (Object.keys(patch).length)
|
|
628
|
-
await session.setConfiguration(patch);
|
|
629
|
-
if (session.state().metadata)
|
|
630
|
-
await sink.emit({ type: "session/metadata", payload: session.state().metadata });
|
|
631
|
-
return session;
|
|
632
|
-
} catch (error) {
|
|
633
|
-
for (const [id, value] of this.nativeSessions)
|
|
634
|
-
if (value === session)
|
|
635
|
-
this.nativeSessions.delete(id);
|
|
636
|
-
this.sessions.delete(params.binding.sessionId);
|
|
637
|
-
throw error;
|
|
638
|
-
} finally {
|
|
639
|
-
this.opening = undefined;
|
|
640
|
-
release();
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
async dispose() {
|
|
644
|
-
if (this.closing)
|
|
645
|
-
return;
|
|
646
|
-
this.closing = true;
|
|
647
|
-
for (const session of this.sessions.values())
|
|
648
|
-
await session.dispose().catch(() => {});
|
|
649
|
-
this.connection?.close();
|
|
650
|
-
await this.channel?.dispose();
|
|
651
|
-
this.sessions.clear();
|
|
652
|
-
this.nativeSessions.clear();
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
class AcpBackendSession {
|
|
657
|
-
adapter;
|
|
658
|
-
params;
|
|
659
|
-
sink;
|
|
660
|
-
nativeId = "";
|
|
661
|
-
activeTurn;
|
|
662
|
-
hydrating = false;
|
|
663
|
-
loadedSnapshot = [];
|
|
664
|
-
terminals = new Set;
|
|
665
|
-
capabilities;
|
|
666
|
-
config = {};
|
|
667
|
-
configKeys = new Map;
|
|
668
|
-
configurationData = {};
|
|
669
|
-
capabilityRevision = 1;
|
|
670
|
-
sessionTitle;
|
|
671
|
-
closed = false;
|
|
672
|
-
mapper;
|
|
673
|
-
snapshotBytes = 0;
|
|
674
|
-
constructor(adapter, params, sink) {
|
|
675
|
-
this.adapter = adapter;
|
|
676
|
-
this.params = params;
|
|
677
|
-
this.sink = sink;
|
|
678
|
-
this.capabilities = structuredClone(adapter.capabilities);
|
|
679
|
-
this.mapper = new AcpUpdateMapper(sink, () => this.activeTurn, () => this.state(), (data) => this.configure(data), adapter.extension.subagents);
|
|
680
|
-
}
|
|
681
|
-
get binding() {
|
|
682
|
-
return { ...this.params.binding, nativeRef: { provider: "acp", value: this.nativeId } };
|
|
683
|
-
}
|
|
684
|
-
state() {
|
|
685
|
-
return { ...this.sessionTitle !== undefined ? { metadata: { title: this.sessionTitle } } : {}, binding: this.binding, config: this.config, capabilities: this.capabilities, capabilityRevision: this.capabilityRevision, status: this.activeTurn ? "running" : "ready", ...this.activeTurn ? { activeTurnId: this.activeTurn } : {} };
|
|
686
|
-
}
|
|
687
|
-
configure(data) {
|
|
688
|
-
if (Object.hasOwn(data, "sessionTitle")) {
|
|
689
|
-
this.sessionTitle = data.sessionTitle;
|
|
690
|
-
return;
|
|
691
|
-
}
|
|
692
|
-
this.configurationData = { ...this.configurationData, ...data };
|
|
693
|
-
if (typeof data.currentModeId === "string")
|
|
694
|
-
this.configurationData.modes = { ...record(this.configurationData.modes), currentModeId: data.currentModeId };
|
|
695
|
-
const descriptor = configuration(this.configurationData);
|
|
696
|
-
this.configKeys = descriptor.keys;
|
|
697
|
-
this.capabilities.config = { options: descriptor.options };
|
|
698
|
-
this.config = { ...this.config, ...descriptor.values };
|
|
699
|
-
if (typeof data.currentModeId === "string")
|
|
700
|
-
this.config.mode = data.currentModeId;
|
|
701
|
-
this.capabilityRevision++;
|
|
702
|
-
}
|
|
703
|
-
async update(data) {
|
|
704
|
-
if (this.hydrating && data.sessionUpdate === "session_info_update") {
|
|
705
|
-
if (typeof data.title === "string" || data.title === null)
|
|
706
|
-
this.sessionTitle = data.title;
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
|
-
if (this.hydrating) {
|
|
710
|
-
this.snapshotBytes += JSON.stringify(data).length * 3;
|
|
711
|
-
if (this.loadedSnapshot.length >= 2048 || this.snapshotBytes > 16 * 1024 * 1024)
|
|
712
|
-
throw new HarnessSdkError2("BACKPRESSURE_EXCEEDED", "ACP load snapshot exceeds its limit");
|
|
713
|
-
this.loadedSnapshot.push(safe(data));
|
|
714
|
-
return;
|
|
715
|
-
}
|
|
716
|
-
await this.mapper.update(data);
|
|
717
|
-
}
|
|
718
|
-
requireTerminal(id) {
|
|
719
|
-
if (!this.terminals.has(id))
|
|
720
|
-
throw new acp.RequestError(-32602, "Terminal does not belong to this session");
|
|
721
|
-
}
|
|
722
|
-
async setConfiguration(patch) {
|
|
723
|
-
for (const key of Object.keys(patch))
|
|
724
|
-
if (!this.configKeys.has(key))
|
|
725
|
-
throw new HarnessSdkError2("CAPABILITY_UNSUPPORTED");
|
|
726
|
-
for (const [key, value] of Object.entries(patch)) {
|
|
727
|
-
const option = this.configKeys.get(key);
|
|
728
|
-
if (option.type === "mode")
|
|
729
|
-
await this.adapter.call("session/set_mode", { sessionId: this.nativeId, modeId: String(value) });
|
|
730
|
-
else {
|
|
731
|
-
const response = await this.adapter.call("session/set_config_option", { sessionId: this.nativeId, configId: String(option.id), type: option.type === "boolean" ? "boolean" : "select", value });
|
|
732
|
-
this.configure(record(response));
|
|
733
|
-
}
|
|
734
|
-
this.config[key] = value;
|
|
735
|
-
}
|
|
736
|
-
return this.state();
|
|
737
|
-
}
|
|
738
|
-
async extension(key, method, params) {
|
|
739
|
-
const nativeMethod = this.adapter.extension.methods[key];
|
|
740
|
-
if (!nativeMethod)
|
|
741
|
-
throw new HarnessSdkError2("CAPABILITY_UNSUPPORTED");
|
|
742
|
-
try {
|
|
743
|
-
let result = await this.adapter.call(nativeMethod, { ...params, sessionId: this.nativeId });
|
|
744
|
-
if (key === "history" && result && typeof result === "object" && Array.isArray(record(result).items)) {
|
|
745
|
-
const page = record(result);
|
|
746
|
-
result = { ...page, items: page.items.map((entry) => {
|
|
747
|
-
const row = record(entry), item = record(row.item);
|
|
748
|
-
return item.type === "toolCall" && item.fileChanges === undefined && Array.isArray(item.output) ? { ...row, item: { ...item, fileChanges: acpFileChanges(item.output) } } : entry;
|
|
749
|
-
}) };
|
|
750
|
-
}
|
|
751
|
-
assertResult(method, result);
|
|
752
|
-
return result;
|
|
753
|
-
} catch (error) {
|
|
754
|
-
if (error instanceof HarnessSdkError2 && error.code === "CAPABILITY_UNSUPPORTED") {
|
|
755
|
-
delete this.adapter.extension.methods[key];
|
|
756
|
-
if (key === "steer")
|
|
757
|
-
this.capabilities.turn.steer = false;
|
|
758
|
-
if (key === "history")
|
|
759
|
-
this.capabilities.session.history = false;
|
|
760
|
-
if (key === "revert")
|
|
761
|
-
this.capabilities.session.revert = [];
|
|
762
|
-
if (key === "compact")
|
|
763
|
-
this.capabilities.compact = false;
|
|
764
|
-
if (key === "review")
|
|
765
|
-
this.capabilities.review = false;
|
|
766
|
-
if (key === "goalSet" || key === "goalClear")
|
|
767
|
-
this.capabilities.goal.actions = this.capabilities.goal.actions?.filter((action) => action !== (key === "goalSet" ? "set" : "clear"));
|
|
768
|
-
await this.sink.emit({ type: "session/state", payload: this.state() });
|
|
769
|
-
}
|
|
770
|
-
throw error;
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
async execute(method, params) {
|
|
774
|
-
let result;
|
|
775
|
-
switch (method) {
|
|
776
|
-
case "turn/start": {
|
|
777
|
-
const turn = params;
|
|
778
|
-
const prompt = input(turn.input);
|
|
779
|
-
this.activeTurn = turn.turnId;
|
|
780
|
-
this.mapper.reset();
|
|
781
|
-
await this.sink.emit({ type: "turn/started", payload: { turnId: turn.turnId } });
|
|
782
|
-
(async () => {
|
|
783
|
-
try {
|
|
784
|
-
const completed = await this.adapter.agent.request("session/prompt", { sessionId: this.nativeId, prompt, ...this.capabilities.extensions?.some((extension) => extension.name === "x-acp/ahp") ? { _meta: { ahp: { version: 1, turnId: turn.turnId } } } : {} });
|
|
785
|
-
await this.mapper.complete();
|
|
786
|
-
await this.sink.emit({ type: "turn/completed", payload: { turnId: turn.turnId, status: completed.stopReason === "cancelled" ? "interrupted" : "completed" } });
|
|
787
|
-
} catch (error) {
|
|
788
|
-
const failure = errorFromNative(error, "ACP_TURN_FAILED");
|
|
789
|
-
if (failure.outcomeUnknown)
|
|
790
|
-
await this.sink.fail(failure);
|
|
791
|
-
else
|
|
792
|
-
await this.sink.emit({ type: "turn/completed", payload: { turnId: turn.turnId, status: "failed", error: { code: failure.code, message: failure.message, retryable: false, outcomeUnknown: false } } });
|
|
793
|
-
} finally {
|
|
794
|
-
if (this.activeTurn === turn.turnId)
|
|
795
|
-
this.activeTurn = undefined;
|
|
796
|
-
}
|
|
797
|
-
})().catch(() => {});
|
|
798
|
-
result = { turnId: turn.turnId, accepted: true };
|
|
799
|
-
break;
|
|
800
|
-
}
|
|
801
|
-
case "turn/interrupt":
|
|
802
|
-
await this.adapter.agent.notify("session/cancel", { sessionId: this.nativeId });
|
|
803
|
-
result = { accepted: true, turnId: params.turnId };
|
|
804
|
-
break;
|
|
805
|
-
case "session/config/set":
|
|
806
|
-
result = await this.setConfiguration(params.patch);
|
|
807
|
-
break;
|
|
808
|
-
case "session/close":
|
|
809
|
-
await this.dispose();
|
|
810
|
-
result = { closed: true };
|
|
811
|
-
break;
|
|
812
|
-
case "turn/steer":
|
|
813
|
-
return this.extension("steer", method, params);
|
|
814
|
-
case "session/revert":
|
|
815
|
-
return this.extension("revert", method, params);
|
|
816
|
-
case "history/read":
|
|
817
|
-
return this.extension("history", method, params);
|
|
818
|
-
case "goal/set":
|
|
819
|
-
return this.extension("goalSet", method, params);
|
|
820
|
-
case "goal/clear":
|
|
821
|
-
return this.extension("goalClear", method, params);
|
|
822
|
-
case "compact/start":
|
|
823
|
-
return this.extension("compact", method, params);
|
|
824
|
-
case "review/start":
|
|
825
|
-
return this.extension("review", method, params);
|
|
826
|
-
case "interaction/respond":
|
|
827
|
-
case "interaction/cancel":
|
|
828
|
-
throw new HarnessSdkError2("INTERACTION_EXPIRED");
|
|
829
|
-
}
|
|
830
|
-
return result;
|
|
831
|
-
}
|
|
832
|
-
async dispose() {
|
|
833
|
-
if (this.closed)
|
|
834
|
-
return;
|
|
835
|
-
this.closed = true;
|
|
836
|
-
if (this.activeTurn)
|
|
837
|
-
await this.adapter.agent.notify("session/cancel", { sessionId: this.nativeId }).catch(() => {});
|
|
838
|
-
for (const terminalId of this.terminals)
|
|
839
|
-
await this.adapter.options.terminal?.releaseTerminal({ sessionId: this.nativeId, terminalId }).catch(() => {});
|
|
840
|
-
this.terminals.clear();
|
|
841
|
-
if (this.adapter.nativeCapabilities.sessionCapabilities?.close != null)
|
|
842
|
-
await this.adapter.call("session/close", { sessionId: this.nativeId }).catch(() => {});
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
function createAcpAdapter(options) {
|
|
846
|
-
return new AcpAdapter(options);
|
|
847
|
-
}
|
|
848
|
-
export {
|
|
849
|
-
AcpAdapter,
|
|
850
|
-
AcpBackendSession,
|
|
851
|
-
createAcpAdapter
|
|
852
|
-
};
|