@anureo/adapter-acp 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Yoichi
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @anureo/adapter-acp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Adapter connecting the Anureo SDK to agents implementing the [Agent Client Protocol](https://agentclientprotocol.com) (ACP), using the official `@agentclientprotocol/sdk` 1.4.0. ACP is an editor↔agent protocol; this adapter brings any standard ACP agent behind the AHP session model — the interoperability proof that AHP is a host-side semantic layer, not a competing agent protocol.
4
+
5
+ > Part of the [Anureo SDK workspace](../../README.md). Install with `npm install @anureo/adapter-acp`.
6
+
7
+ ## Usage
8
+
9
+ ```typescript
10
+ import { createHarnessRuntime } from '@anureo/sdk'
11
+ import { createAcpAdapter } from '@anureo/adapter-acp'
12
+
13
+ const runtime = createHarnessRuntime(createAcpAdapter({
14
+ command: 'my-acp-agent', // spawn over stdio; or use connect() below
15
+ args: ['--stdio'],
16
+ cwd: '/workspace',
17
+ }))
18
+
19
+ // Remote or custom transports inject an official v1 message stream:
20
+ // createAcpAdapter({ connect: () => openMyStream() })
21
+ ```
22
+
23
+ ## How capabilities are mapped
24
+
25
+ ACP's core protocol covers sessions, turns, messages, and permission requests. AHP-only features are opt-in through an extension object in the agent's `initialize` response (`_meta.ahp`, version 1):
26
+
27
+ - **Optional methods** — `fork`, `revert`, `steer`, `history`, `goalSet`, `goalClear`, `compact`, `review`, each declaring its private `_…` method name, plus fork boundaries and revert scopes where applicable
28
+ - **Client requests** — `userInput` (`_ahp/user_input`) and `dynamicTool` (`_ahp/dynamic_tool`) interactions
29
+ - **Features** — nested subagent events and custom instructions
30
+
31
+ Agents that do not advertise the extension still work: the adapter publishes only the standard ACP baseline (interrupt, approval interactions, text/image/file input). fs and terminal capabilities are announced **only** when the host injects the corresponding ports — connecting an adapter never grants filesystem or terminal permission by itself.
32
+
33
+ Session snapshots loaded via ACP `session/load` have no turn boundaries; they are handed to the host through `onLoadSnapshot` instead of being replayed as realtime events.
34
+
35
+ ## Options
36
+
37
+ | Option | Purpose |
38
+ |---|---|
39
+ | `command`, `args`, `cwd`, `env` | Spawn the agent binary and speak nd-JSON over stdio |
40
+ | `connect` | Provide an official `acp.Stream` factory for remote transports or deterministic wire tests |
41
+ | `fs` (`AcpFileSystemPort`) | Host-implemented read/write text-file callbacks |
42
+ | `terminal` (`AcpTerminalPort`) | Host-implemented terminal lifecycle callbacks |
43
+ | `requestTimeoutMs`, `maxFrameBytes` | Bound each request and every line (default 8 MiB; oversized frames fail with `BACKPRESSURE_EXCEEDED`) |
44
+ | `onLoadSnapshot` | Receive `session/load` snapshot updates separately from the realtime event stream |
45
+
46
+ ACP JSON-RPC error codes map to typed SDK errors (`-32601` → `CAPABILITY_UNSUPPORTED`, `-32602` → `INVALID_PARAMS`, `-32000` → `AUTH_REQUIRED`, `-32002` → `RESOURCE_NOT_FOUND`); a dropped connection surfaces as `ACP_CONNECTION_CLOSED` with `outcomeUnknown`, never as a silent success. Stderr from the agent is drained and discarded — raw provider output and credentials are not retained in diagnostics.
47
+
48
+ ## Development
49
+
50
+ ```sh
51
+ cd packages/acp
52
+ bun run typecheck
53
+ bun test tests
54
+ ```
55
+
56
+ The conformance tests spawn a scripted ACP agent (implementing the standard wire protocol) as a real child process over stdio; `bun run verify:pack` at the workspace root repeats the full text, approval-rejection, and interrupt flows against clean npm installs.
57
+
58
+ ## Documentation
59
+
60
+ - [Architecture](../../docs/architecture.md) — adapters' role in the SDK (currently in Chinese)
61
+ - [AHP v1 protocol](../../spec/ahp-v1.md)
@@ -0,0 +1,3 @@
1
+ import type { FileChange } from '@anureo/protocol';
2
+ /** Only ACP's typed diff blocks are source material. Text output is execution output. */
3
+ export declare function acpFileChanges(content: unknown): FileChange[];
@@ -0,0 +1,98 @@
1
+ import * as acp from '@agentclientprotocol/sdk';
2
+ import { type HarnessAdapter, type BackendSession, type SessionEventSink, type SessionMethod } from '@anureo/sdk';
3
+ import { type Capabilities, type SessionBinding, type SessionOpenParams, type SessionState, type InitializeParams, type InitializeResult, type AhpRequestMap, type AhpResultMap, type JsonObject } from '@anureo/protocol';
4
+ export interface AcpFileSystemPort {
5
+ readTextFile?: (params: acp.ReadTextFileRequest) => Promise<acp.ReadTextFileResponse>;
6
+ writeTextFile?: (params: acp.WriteTextFileRequest) => Promise<acp.WriteTextFileResponse | void>;
7
+ }
8
+ export interface AcpTerminalPort {
9
+ createTerminal(params: acp.CreateTerminalRequest): Promise<acp.CreateTerminalResponse>;
10
+ terminalOutput(params: acp.TerminalOutputRequest): Promise<acp.TerminalOutputResponse>;
11
+ releaseTerminal(params: acp.ReleaseTerminalRequest): Promise<acp.ReleaseTerminalResponse | void>;
12
+ waitForTerminalExit(params: acp.WaitForTerminalExitRequest): Promise<acp.WaitForTerminalExitResponse>;
13
+ killTerminal(params: acp.KillTerminalRequest): Promise<acp.KillTerminalResponse | void>;
14
+ }
15
+ export interface AcpAdapterOptions {
16
+ command?: string;
17
+ args?: readonly string[];
18
+ cwd?: string;
19
+ env?: Record<string, string | undefined>;
20
+ fs?: AcpFileSystemPort;
21
+ terminal?: AcpTerminalPort;
22
+ /** Inject an official v1 message stream for remote transports or deterministic wire tests. */
23
+ connect?: () => Promise<{
24
+ stream: acp.Stream;
25
+ dispose(): Promise<void>;
26
+ }>;
27
+ requestTimeoutMs?: number;
28
+ maxFrameBytes?: number;
29
+ /** session/load snapshots have no turn boundaries; expose them separately from AHP realtime events. */
30
+ onLoadSnapshot?: (binding: SessionBinding, updates: readonly JsonObject[]) => void;
31
+ }
32
+ type ExtensionKey = 'fork' | 'revert' | 'steer' | 'history' | 'goalSet' | 'goalClear' | 'compact' | 'review';
33
+ interface Extensions {
34
+ methods: Partial<Record<ExtensionKey, string>>;
35
+ fork: Array<'before' | 'through'>;
36
+ revert: Array<'conversation' | 'files' | 'both'>;
37
+ subagents: boolean;
38
+ instructions: boolean;
39
+ userInput: boolean;
40
+ dynamicTool: boolean;
41
+ }
42
+ export declare class AcpAdapter implements HarnessAdapter {
43
+ readonly options: AcpAdapterOptions;
44
+ private connection;
45
+ private channel;
46
+ private info;
47
+ readonly sessions: Map<string, AcpBackendSession>;
48
+ private nativeSessions;
49
+ private opening;
50
+ private openTail;
51
+ private readonly deliveries;
52
+ private closing;
53
+ extension: Extensions;
54
+ capabilities: Capabilities;
55
+ constructor(options: AcpAdapterOptions);
56
+ get nativeCapabilities(): acp.AgentCapabilities;
57
+ get agent(): acp.ClientContext;
58
+ private backend;
59
+ private interaction;
60
+ initialize(params: InitializeParams): Promise<InitializeResult>;
61
+ private runtime;
62
+ call<M extends acp.AgentRequestMethod>(method: M, params: acp.AgentRequestParamsByMethod[M]): Promise<acp.AgentRequestResponsesByMethod[M]>;
63
+ call(method: string, params: unknown): Promise<unknown>;
64
+ private extensionInteraction;
65
+ openSession(params: SessionOpenParams, sink: SessionEventSink): Promise<BackendSession>;
66
+ dispose(): Promise<void>;
67
+ }
68
+ export declare class AcpBackendSession implements BackendSession {
69
+ readonly adapter: AcpAdapter;
70
+ private readonly params;
71
+ readonly sink: SessionEventSink;
72
+ nativeId: string;
73
+ activeTurn: string | undefined;
74
+ hydrating: boolean;
75
+ readonly loadedSnapshot: JsonObject[];
76
+ readonly terminals: Set<string>;
77
+ readonly capabilities: Capabilities;
78
+ private config;
79
+ private configKeys;
80
+ private configurationData;
81
+ private capabilityRevision;
82
+ private sessionTitle?;
83
+ private closed;
84
+ private readonly mapper;
85
+ private snapshotBytes;
86
+ constructor(adapter: AcpAdapter, params: SessionOpenParams, sink: SessionEventSink);
87
+ get binding(): SessionBinding;
88
+ state(): SessionState;
89
+ configure(data: Record<string, unknown>): void;
90
+ update(data: Record<string, unknown>): Promise<void>;
91
+ requireTerminal(id: string): void;
92
+ setConfiguration(patch: JsonObject): Promise<SessionState>;
93
+ private extension;
94
+ execute<M extends SessionMethod>(method: M, params: AhpRequestMap[M]): Promise<AhpResultMap[M]>;
95
+ dispose(): Promise<void>;
96
+ }
97
+ export declare function createAcpAdapter(options: AcpAdapterOptions): AcpAdapter;
98
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,852 @@
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
+ };
@@ -0,0 +1,30 @@
1
+ import type { InputBlock, JsonValue, JsonObject, ConfigOption, SessionState } from '@anureo/protocol';
2
+ import { type SessionEventSink } from '@anureo/sdk';
3
+ import type { ContentBlock, McpServer } from '@agentclientprotocol/sdk';
4
+ export declare function record(value: unknown): Record<string, unknown>;
5
+ export declare function safe(value: unknown): JsonValue;
6
+ export declare function text(value: unknown): string;
7
+ export declare function input(blocks: InputBlock[]): ContentBlock[];
8
+ export declare function mcp(servers?: import('@anureo/protocol').McpServer[]): McpServer[];
9
+ export declare function configuration(data: Record<string, unknown>): {
10
+ options: ConfigOption[];
11
+ values: JsonObject;
12
+ keys: Map<string, Record<string, unknown>>;
13
+ };
14
+ /** Accumulates native updates; only complete snapshots become authoritative item/completed. */
15
+ export declare class AcpUpdateMapper {
16
+ private readonly sink;
17
+ private readonly getTurn;
18
+ private readonly state;
19
+ private readonly setState;
20
+ private readonly subagents;
21
+ private readonly items;
22
+ private readonly ended;
23
+ private serial;
24
+ private compaction;
25
+ constructor(sink: SessionEventSink, getTurn: () => string | undefined, state: () => SessionState, setState: (data: Record<string, unknown>) => void, subagents: boolean);
26
+ reset(): void;
27
+ private upsert;
28
+ complete(): Promise<void>;
29
+ update(update: Record<string, unknown>): Promise<void>;
30
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@anureo/adapter-acp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Anureo SDK adapter for standard Agent Client Protocol (ACP) agents",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "anureo",
8
+ "ahp",
9
+ "harness",
10
+ "agent",
11
+ "acp",
12
+ "agent-client-protocol"
13
+ ],
14
+ "homepage": "https://github.com/hi-youichi/anureo-sdk#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/hi-youichi/anureo-sdk.git",
18
+ "directory": "packages/acp"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/hi-youichi/anureo-sdk/issues"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "type": "module",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js",
31
+ "default": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "schema",
37
+ "protocol",
38
+ "examples",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "dependencies": {
43
+ "@anureo/sdk": "0.2.0",
44
+ "@anureo/protocol": "0.2.0",
45
+ "@agentclientprotocol/sdk": "1.4.0"
46
+ },
47
+ "engines": {
48
+ "node": ">=22"
49
+ }
50
+ }