@automatalabs/acp-server 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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 Automata Labs
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.
202
+
package/README.md CHANGED
@@ -1,5 +1,88 @@
1
1
  # `@automatalabs/acp-server`
2
2
 
3
- This `0.0.0` artifact exists only to bootstrap npm trusted-publisher configuration for the package. It is published under the `bootstrap` dist-tag, not `latest`, and contains no runtime implementation.
3
+ Connection-pinned ACP V1 proxy for the backends configured through
4
+ `@automatalabs/acp-agents`. The package exposes the `agentprism-acp-server` stdio executable and a
5
+ programmatic `serveAcpServer()` entry point.
4
6
 
5
- The first functional release will be published from the AgentPrism repository's Changesets release workflow with npm OIDC provenance.
7
+ ```bash
8
+ npx @automatalabs/acp-server
9
+ agentprism-acp-server --version
10
+ ```
11
+
12
+ The server accepts only clients that negotiate AgentPrism router extension version 1 under
13
+ `clientCapabilities._meta["@automatalabs/agentprism"].acpRouter`.
14
+
15
+ ## Connection modes
16
+
17
+ A discovery connection initializes with:
18
+
19
+ ```json
20
+ {
21
+ "protocolVersion": 1,
22
+ "clientCapabilities": {
23
+ "_meta": {
24
+ "@automatalabs/agentprism": {
25
+ "acpRouter": { "versions": [1] }
26
+ }
27
+ }
28
+ },
29
+ "_meta": {
30
+ "@automatalabs/agentprism": {
31
+ "acpRouter": { "version": 1, "mode": "discovery" }
32
+ }
33
+ }
34
+ }
35
+ ```
36
+
37
+ It may then call `_automatalabs/agentprism/backends/probe` with `cwd`, optional
38
+ `additionalDirectories`, and `mcpServers`. The probe opens one temporary no-prompt session per
39
+ configured backend and returns each backend's implementation information, capabilities, modes, and
40
+ configuration options.
41
+
42
+ An operational connection initializes with a backend selection:
43
+
44
+ ```json
45
+ {
46
+ "protocolVersion": 1,
47
+ "clientCapabilities": {
48
+ "_meta": {
49
+ "@automatalabs/agentprism": {
50
+ "acpRouter": { "versions": [1] }
51
+ }
52
+ }
53
+ },
54
+ "_meta": {
55
+ "@automatalabs/agentprism": {
56
+ "acpRouter": {
57
+ "version": 1,
58
+ "mode": "backend",
59
+ "backend": "codex"
60
+ }
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ The initialize request is forwarded unchanged to that backend. The backend response is returned
67
+ with the AgentPrism confirmation merged into `agentCapabilities._meta`. Every `session/new` repeats
68
+ the same backend assertion; after session creation, all ACP and non-AgentPrism extension traffic is
69
+ proxied unchanged over the pinned connection. Native backend session IDs remain unchanged and the
70
+ proxy stores no session-routing table.
71
+
72
+ Built-in backend IDs are `claude`, `codex`, `opencode`, and `pi`. Custom backends use the existing
73
+ `AGENTPRISM_BACKENDS` registry.
74
+
75
+ ## Library API
76
+
77
+ ```ts
78
+ import { serveAcpServer } from "@automatalabs/acp-server";
79
+
80
+ await serveAcpServer();
81
+ ```
82
+
83
+ Embedding hosts can pass a custom ACP `stream`, custom backend registrations, exact `targets`, a
84
+ version string, and an abort signal through `ServeAcpServerOptions`. The package also exports the
85
+ router constants, request parsers, response helpers, probe types, and backend-target resolver.
86
+
87
+ Authentication, authorization, workspace policy, HTTP, WebSocket, and ACP V2 are outside this
88
+ package.
@@ -0,0 +1,15 @@
1
+ import { type CustomBackendConfig, type RawBackendConnection } from "@automatalabs/acp-agents";
2
+ export interface BackendTarget {
3
+ readonly id: string;
4
+ readonly name: string;
5
+ open(): Promise<RawBackendConnection>;
6
+ }
7
+ export interface ResolveBackendTargetsOptions {
8
+ /** Programmatic custom backends merged over AGENTPRISM_BACKENDS by acp-agents. */
9
+ backends?: Record<string, CustomBackendConfig>;
10
+ /** Environment used for AGENTPRISM_BACKENDS resolution. Defaults to process.env. */
11
+ env?: NodeJS.ProcessEnv;
12
+ }
13
+ /** Resolve the same built-in and operator-registered backend namespace used by acp-agents. */
14
+ export declare function resolveBackendTargets(options?: ResolveBackendTargetsOptions): BackendTarget[];
15
+ //# sourceMappingURL=backends.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backends.d.ts","sourceRoot":"","sources":["../src/backends.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EAC1B,MAAM,0BAA0B,CAAC;AASlC,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,IAAI,IAAI,OAAO,CAAC,oBAAoB,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,4BAA4B;IAC3C,kFAAkF;IAClF,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IAC/C,oFAAoF;IACpF,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACzB;AAED,8FAA8F;AAC9F,wBAAgB,qBAAqB,CAAC,OAAO,GAAE,4BAAiC,GAAG,aAAa,EAAE,CAuBjG"}
@@ -0,0 +1,30 @@
1
+ import { BUILTIN_BACKEND_IDS, CustomAcpBackend, builtinBackend, openRawBackendConnection, resolveBackendRegistry, } from "@automatalabs/acp-agents";
2
+ const BUILTIN_TITLES = {
3
+ claude: "Claude",
4
+ codex: "Codex",
5
+ opencode: "OpenCode",
6
+ pi: "pi",
7
+ };
8
+ /** Resolve the same built-in and operator-registered backend namespace used by acp-agents. */
9
+ export function resolveBackendTargets(options = {}) {
10
+ const targets = new Map();
11
+ for (const id of BUILTIN_BACKEND_IDS) {
12
+ const backend = builtinBackend(id);
13
+ if (!backend)
14
+ throw new Error(`Built-in ACP backend ${JSON.stringify(id)} is unavailable`);
15
+ targets.set(id, {
16
+ id,
17
+ name: BUILTIN_TITLES[id] ?? id,
18
+ open: () => openRawBackendConnection(backend),
19
+ });
20
+ }
21
+ for (const [id, config] of resolveBackendRegistry(options.backends, options.env)) {
22
+ const backend = new CustomAcpBackend(config);
23
+ targets.set(id, {
24
+ id,
25
+ name: id,
26
+ open: () => openRawBackendConnection(backend),
27
+ });
28
+ }
29
+ return [...targets.values()];
30
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ // Keep stdout reserved for ACP before importing modules that may log during evaluation.
3
+ if (process.argv.includes("--version") || process.argv.includes("-v")) {
4
+ const manifest = await import("../package.json", { with: { type: "json" } }).then((module) => module.default);
5
+ process.stdout.write(`${manifest.version}\n`);
6
+ process.exit(0);
7
+ }
8
+ console.log = console.error;
9
+ console.info = console.error;
10
+ console.warn = console.error;
11
+ console.debug = console.error;
12
+ process.on("unhandledRejection", (reason) => {
13
+ console.error("unhandledRejection:", reason);
14
+ });
15
+ const abortController = new AbortController();
16
+ process.once("SIGTERM", () => abortController.abort(new Error("SIGTERM")));
17
+ process.once("SIGINT", () => abortController.abort(new Error("SIGINT")));
18
+ try {
19
+ const { serveAcpServer } = await import("./server.js");
20
+ await serveAcpServer({ signal: abortController.signal });
21
+ }
22
+ catch (error) {
23
+ if (!abortController.signal.aborted) {
24
+ console.error("ACP server failed:", error);
25
+ process.exitCode = 1;
26
+ }
27
+ }
28
+ export {};
@@ -0,0 +1,7 @@
1
+ export { serveAcpServer } from "./server.js";
2
+ export type { ServeAcpServerOptions } from "./server.js";
3
+ export { resolveBackendTargets } from "./backends.js";
4
+ export type { BackendTarget, ResolveBackendTargetsOptions } from "./backends.js";
5
+ export { ACP_BACKENDS_PROBE_METHOD, ACP_ROUTER_META_NAMESPACE, ACP_ROUTER_VERSION, assertSessionBackend, discoveryInitializeResponse, mergeBackendInitializeResponse, parseProbeBackendsParams, parseRouterInitialize, } from "./protocol.js";
6
+ export type { BackendProbe, ParsedRouterInitialize, ProbeBackendsParams, ProbeBackendsResult, RouterSelection, } from "./protocol.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,YAAY,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,YAAY,EAAE,aAAa,EAAE,4BAA4B,EAAE,MAAM,eAAe,CAAC;AAEjF,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAClB,oBAAoB,EACpB,2BAA2B,EAC3B,8BAA8B,EAC9B,wBAAwB,EACxB,qBAAqB,GACtB,MAAM,eAAe,CAAC;AACvB,YAAY,EACV,YAAY,EACZ,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,eAAe,GAChB,MAAM,eAAe,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { serveAcpServer } from "./server.js";
2
+ export { resolveBackendTargets } from "./backends.js";
3
+ export { ACP_BACKENDS_PROBE_METHOD, ACP_ROUTER_META_NAMESPACE, ACP_ROUTER_VERSION, assertSessionBackend, discoveryInitializeResponse, mergeBackendInitializeResponse, parseProbeBackendsParams, parseRouterInitialize, } from "./protocol.js";
@@ -0,0 +1,54 @@
1
+ import { type AgentCapabilities, type Implementation, type InitializeRequest, type InitializeResponse, type McpServer, type SessionConfigOption, type SessionModeState } from "@agentclientprotocol/sdk";
2
+ export declare const ACP_ROUTER_META_NAMESPACE: "@automatalabs/agentprism";
3
+ export declare const ACP_ROUTER_VERSION: 1;
4
+ export declare const ACP_BACKENDS_PROBE_METHOD: "_automatalabs/agentprism/backends/probe";
5
+ export type RouterSelection = {
6
+ readonly version: 1;
7
+ readonly mode: "discovery";
8
+ } | {
9
+ readonly version: 1;
10
+ readonly mode: "backend";
11
+ readonly backend: string;
12
+ };
13
+ export interface ParsedRouterInitialize {
14
+ readonly request: InitializeRequest;
15
+ readonly selection: RouterSelection;
16
+ }
17
+ export interface ProbeBackendsParams {
18
+ cwd: string;
19
+ additionalDirectories?: string[];
20
+ mcpServers: McpServer[];
21
+ _meta?: Record<string, unknown> | null;
22
+ }
23
+ export type BackendProbe = {
24
+ id: string;
25
+ name: string;
26
+ available: true;
27
+ agentInfo?: Implementation | null;
28
+ agentCapabilities?: AgentCapabilities;
29
+ modes?: SessionModeState | null;
30
+ configOptions?: SessionConfigOption[] | null;
31
+ initializeMeta?: Record<string, unknown> | null;
32
+ sessionMeta?: Record<string, unknown> | null;
33
+ } | {
34
+ id: string;
35
+ name: string;
36
+ available: false;
37
+ stage: "initialize" | "session/new";
38
+ error: string;
39
+ };
40
+ export interface ProbeBackendsResult {
41
+ backends: BackendProbe[];
42
+ }
43
+ /** Validate the ACP and AgentPrism portions of the connection's first initialize request. */
44
+ export declare function parseRouterInitialize(params: unknown): ParsedRouterInitialize;
45
+ /** Validate the redundant backend assertion required on every session/new request. */
46
+ export declare function assertSessionBackend(params: unknown, selectedBackend: string): void;
47
+ /** Validate and copy the temporary session inputs accepted by the discovery probe. */
48
+ export declare function parseProbeBackendsParams(params: unknown): ProbeBackendsParams;
49
+ /** Router-owned initialize response for a discovery connection. */
50
+ export declare function discoveryInitializeResponse(version: string): InitializeResponse;
51
+ /** Add the proxy's negotiated capability without changing the selected backend's response fields. */
52
+ export declare function mergeBackendInitializeResponse(response: InitializeResponse, backend: string): InitializeResponse;
53
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
54
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,SAAS,EACd,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACtB,MAAM,0BAA0B,CAAC;AAElC,eAAO,MAAM,yBAAyB,EAAG,0BAAmC,CAAC;AAC7E,eAAO,MAAM,kBAAkB,EAAG,CAAU,CAAC;AAC7C,eAAO,MAAM,yBAAyB,EAAG,yCAAkD,CAAC;AAI5F,MAAM,MAAM,eAAe,GACvB;IAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAA;CAAE,GACnD;IAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEhF,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,OAAO,EAAE,iBAAiB,CAAC;IACpC,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC;CACrC;AAED,MAAM,WAAW,mBAAmB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;IACjC,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CACxC;AAED,MAAM,MAAM,YAAY,GACpB;IACE,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,IAAI,CAAC;IAChB,SAAS,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;IAClC,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,KAAK,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAChC,aAAa,CAAC,EAAE,mBAAmB,EAAE,GAAG,IAAI,CAAC;IAC7C,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAChD,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC9C,GACD;IACE,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,KAAK,CAAC;IACjB,KAAK,EAAE,YAAY,GAAG,aAAa,CAAC;IACpC,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEN,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,YAAY,EAAE,CAAC;CAC1B;AAED,6FAA6F;AAC7F,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,OAAO,GAAG,sBAAsB,CA+C7E;AAED,sFAAsF;AACtF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,GAAG,IAAI,CAanF;AAED,sFAAsF;AACtF,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,OAAO,GAAG,mBAAmB,CA0B7E;AAED,mEAAmE;AACnE,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,MAAM,GAAG,kBAAkB,CAoB/E;AAED,qGAAqG;AACrG,wBAAgB,8BAA8B,CAC5C,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,EAAE,MAAM,GACd,kBAAkB,CAsBpB;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAEzE"}
@@ -0,0 +1,138 @@
1
+ import { isAbsolute } from "node:path";
2
+ import { PROTOCOL_VERSION, RequestError, } from "@agentclientprotocol/sdk";
3
+ export const ACP_ROUTER_META_NAMESPACE = "@automatalabs/agentprism";
4
+ export const ACP_ROUTER_VERSION = 1;
5
+ export const ACP_BACKENDS_PROBE_METHOD = "_automatalabs/agentprism/backends/probe";
6
+ const BACKEND_ID_PATTERN = /^[a-z][a-z0-9._-]*$/;
7
+ /** Validate the ACP and AgentPrism portions of the connection's first initialize request. */
8
+ export function parseRouterInitialize(params) {
9
+ const request = requireRecord(params, "initialize params");
10
+ if (request.protocolVersion !== PROTOCOL_VERSION) {
11
+ throw invalidParams(`AgentPrism ACP server supports protocol version ${PROTOCOL_VERSION}`);
12
+ }
13
+ const clientCapabilities = requireRecord(request.clientCapabilities, "clientCapabilities");
14
+ const capabilityMeta = requireRecord(clientCapabilities._meta, "clientCapabilities._meta");
15
+ const capabilityNamespace = requireRecord(capabilityMeta[ACP_ROUTER_META_NAMESPACE], `clientCapabilities._meta[${JSON.stringify(ACP_ROUTER_META_NAMESPACE)}]`);
16
+ const capability = requireRecord(capabilityNamespace.acpRouter, "acpRouter client capability");
17
+ if (!Array.isArray(capability.versions) ||
18
+ !capability.versions.every((value) => Number.isSafeInteger(value)) ||
19
+ !capability.versions.includes(ACP_ROUTER_VERSION)) {
20
+ throw invalidParams(`client must advertise AgentPrism ACP router version ${ACP_ROUTER_VERSION}`);
21
+ }
22
+ const requestMeta = requireRecord(request._meta, "initialize._meta");
23
+ const requestNamespace = requireRecord(requestMeta[ACP_ROUTER_META_NAMESPACE], `initialize._meta[${JSON.stringify(ACP_ROUTER_META_NAMESPACE)}]`);
24
+ const selection = requireRecord(requestNamespace.acpRouter, "initialize acpRouter selection");
25
+ if (selection.version !== ACP_ROUTER_VERSION) {
26
+ throw invalidParams(`initialize must select AgentPrism ACP router version ${ACP_ROUTER_VERSION}`);
27
+ }
28
+ if (selection.mode === "discovery") {
29
+ return { request, selection: { version: ACP_ROUTER_VERSION, mode: "discovery" } };
30
+ }
31
+ if (selection.mode !== "backend") {
32
+ throw invalidParams('initialize acpRouter mode must be "discovery" or "backend"');
33
+ }
34
+ if (typeof selection.backend !== "string" || !BACKEND_ID_PATTERN.test(selection.backend)) {
35
+ throw invalidParams(`initialize acpRouter backend must match ${BACKEND_ID_PATTERN}`);
36
+ }
37
+ return {
38
+ request,
39
+ selection: {
40
+ version: ACP_ROUTER_VERSION,
41
+ mode: "backend",
42
+ backend: selection.backend,
43
+ },
44
+ };
45
+ }
46
+ /** Validate the redundant backend assertion required on every session/new request. */
47
+ export function assertSessionBackend(params, selectedBackend) {
48
+ const request = requireRecord(params, "session/new params");
49
+ const meta = requireRecord(request._meta, "session/new._meta");
50
+ const namespace = requireRecord(meta[ACP_ROUTER_META_NAMESPACE], `session/new._meta[${JSON.stringify(ACP_ROUTER_META_NAMESPACE)}]`);
51
+ const selection = requireRecord(namespace.acpRouter, "session/new acpRouter selection");
52
+ if (selection.version !== ACP_ROUTER_VERSION || selection.backend !== selectedBackend) {
53
+ throw invalidParams(`session/new must select router version ${ACP_ROUTER_VERSION} and backend ${JSON.stringify(selectedBackend)}`);
54
+ }
55
+ }
56
+ /** Validate and copy the temporary session inputs accepted by the discovery probe. */
57
+ export function parseProbeBackendsParams(params) {
58
+ const value = requireRecord(params, "probe params");
59
+ if (typeof value.cwd !== "string" || !isAbsolute(value.cwd)) {
60
+ throw invalidParams("probe cwd must be an absolute path");
61
+ }
62
+ if (!Array.isArray(value.mcpServers)) {
63
+ throw invalidParams("probe mcpServers must be an array");
64
+ }
65
+ if (value.additionalDirectories !== undefined &&
66
+ (!Array.isArray(value.additionalDirectories) ||
67
+ !value.additionalDirectories.every((directory) => typeof directory === "string" && isAbsolute(directory)))) {
68
+ throw invalidParams("probe additionalDirectories must contain only absolute paths");
69
+ }
70
+ if (value._meta !== undefined && value._meta !== null && !isRecord(value._meta)) {
71
+ throw invalidParams("probe _meta must be an object or null");
72
+ }
73
+ return {
74
+ cwd: value.cwd,
75
+ mcpServers: value.mcpServers,
76
+ ...(value.additionalDirectories === undefined
77
+ ? {}
78
+ : { additionalDirectories: [...value.additionalDirectories] }),
79
+ ...(value._meta === undefined ? {} : { _meta: value._meta }),
80
+ };
81
+ }
82
+ /** Router-owned initialize response for a discovery connection. */
83
+ export function discoveryInitializeResponse(version) {
84
+ return {
85
+ protocolVersion: PROTOCOL_VERSION,
86
+ agentInfo: {
87
+ name: "agentprism-acp-server",
88
+ title: "AgentPrism ACP Server",
89
+ version,
90
+ },
91
+ agentCapabilities: {
92
+ _meta: {
93
+ [ACP_ROUTER_META_NAMESPACE]: {
94
+ acpRouter: {
95
+ version: ACP_ROUTER_VERSION,
96
+ mode: "discovery",
97
+ methods: { probeBackends: ACP_BACKENDS_PROBE_METHOD },
98
+ },
99
+ },
100
+ },
101
+ },
102
+ };
103
+ }
104
+ /** Add the proxy's negotiated capability without changing the selected backend's response fields. */
105
+ export function mergeBackendInitializeResponse(response, backend) {
106
+ const capabilities = response.agentCapabilities ?? {};
107
+ const capabilityMeta = capabilities._meta ?? {};
108
+ const namespaceValue = capabilityMeta[ACP_ROUTER_META_NAMESPACE];
109
+ const namespace = isRecord(namespaceValue) ? namespaceValue : {};
110
+ return {
111
+ ...response,
112
+ agentCapabilities: {
113
+ ...capabilities,
114
+ _meta: {
115
+ ...capabilityMeta,
116
+ [ACP_ROUTER_META_NAMESPACE]: {
117
+ ...namespace,
118
+ acpRouter: {
119
+ version: ACP_ROUTER_VERSION,
120
+ mode: "backend",
121
+ backend,
122
+ },
123
+ },
124
+ },
125
+ },
126
+ };
127
+ }
128
+ export function isRecord(value) {
129
+ return value !== null && typeof value === "object" && !Array.isArray(value);
130
+ }
131
+ function requireRecord(value, field) {
132
+ if (!isRecord(value))
133
+ throw invalidParams(`${field} must be an object`);
134
+ return value;
135
+ }
136
+ function invalidParams(message) {
137
+ return RequestError.invalidParams(undefined, message);
138
+ }
@@ -0,0 +1,30 @@
1
+ import { type AnyNotification, type AnyRequest, type Result, type Stream } from "@agentclientprotocol/sdk";
2
+ export interface RawRpcHandler {
3
+ request(message: AnyRequest, signal: AbortSignal): Promise<Result<unknown>> | Result<unknown>;
4
+ notification(message: AnyNotification): Promise<void> | void;
5
+ }
6
+ /** Minimal bidirectional JSON-RPC peer used only by router-owned discovery connections. */
7
+ export declare class RawRpcPeer {
8
+ private readonly handler;
9
+ private readonly reader;
10
+ private readonly writer;
11
+ private readonly pending;
12
+ private readonly incoming;
13
+ private nextRequestId;
14
+ private writeQueue;
15
+ private closeReason;
16
+ readonly closed: Promise<void>;
17
+ constructor(stream: Stream, handler: RawRpcHandler);
18
+ request(method: string, params?: unknown, signal?: AbortSignal): Promise<Result<unknown>>;
19
+ notify(method: string, params?: unknown): Promise<void>;
20
+ close(reason?: unknown): Promise<void>;
21
+ private write;
22
+ private receive;
23
+ private dispatchRequest;
24
+ }
25
+ export declare function errorResponse(error: unknown): {
26
+ code: number;
27
+ message: string;
28
+ data?: unknown;
29
+ };
30
+ //# sourceMappingURL=raw-rpc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"raw-rpc.d.ts","sourceRoot":"","sources":["../src/raw-rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,UAAU,EAEf,KAAK,MAAM,EACX,KAAK,MAAM,EACZ,MAAM,0BAA0B,CAAC;AAElC,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAC9F,YAAY,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAC9D;AAOD,2FAA2F;AAC3F,qBAAa,UAAU;IAUO,OAAO,CAAC,QAAQ,CAAC,OAAO;IATpD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA0C;IACjE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA0C;IACjE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwC;IAChE,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyC;IAClE,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,UAAU,CAAoC;IACtD,OAAO,CAAC,WAAW,CAAU;IAC7B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;gBAEnB,MAAM,EAAE,MAAM,EAAmB,OAAO,EAAE,aAAa;IAanE,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAuBzF,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAQjD,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAY5C,OAAO,CAAC,KAAK;YAMC,OAAO;IA6BrB,OAAO,CAAC,eAAe;CAUxB;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,OAAO,CAAA;CAAE,CAG/F"}
@@ -0,0 +1,127 @@
1
+ import { RequestError, } from "@agentclientprotocol/sdk";
2
+ /** Minimal bidirectional JSON-RPC peer used only by router-owned discovery connections. */
3
+ export class RawRpcPeer {
4
+ handler;
5
+ reader;
6
+ writer;
7
+ pending = new Map();
8
+ incoming = new Map();
9
+ nextRequestId = 0;
10
+ writeQueue = Promise.resolve();
11
+ closeReason;
12
+ closed;
13
+ constructor(stream, handler) {
14
+ this.handler = handler;
15
+ this.reader = stream.readable.getReader();
16
+ this.writer = stream.writable.getWriter();
17
+ this.closed = this.receive().finally(() => {
18
+ const reason = this.closeReason ?? new Error("ACP JSON-RPC connection closed");
19
+ for (const pending of this.pending.values())
20
+ pending.reject(reason);
21
+ this.pending.clear();
22
+ for (const controller of this.incoming.values())
23
+ controller.abort(reason);
24
+ this.incoming.clear();
25
+ });
26
+ this.closed.catch(() => { });
27
+ }
28
+ request(method, params, signal) {
29
+ if (signal?.aborted)
30
+ return Promise.reject(signal.reason);
31
+ const id = `agentprism-${(this.nextRequestId += 1)}`;
32
+ const message = {
33
+ jsonrpc: "2.0",
34
+ id,
35
+ method,
36
+ ...(params === undefined ? {} : { params }),
37
+ };
38
+ const onAbort = () => {
39
+ void this.notify("$/cancel_request", { requestId: id });
40
+ };
41
+ signal?.addEventListener("abort", onAbort, { once: true });
42
+ return new Promise((resolve, reject) => {
43
+ this.pending.set(id, { resolve, reject });
44
+ void this.write(message).catch((error) => {
45
+ this.pending.delete(id);
46
+ reject(error);
47
+ });
48
+ }).finally(() => signal?.removeEventListener("abort", onAbort));
49
+ }
50
+ notify(method, params) {
51
+ return this.write({
52
+ jsonrpc: "2.0",
53
+ method,
54
+ ...(params === undefined ? {} : { params }),
55
+ });
56
+ }
57
+ async close(reason) {
58
+ this.closeReason = reason;
59
+ await Promise.allSettled([
60
+ this.reader.cancel(reason),
61
+ this.writeQueue.then(() => this.writer.close()),
62
+ ]);
63
+ await this.closed.catch(() => { });
64
+ try {
65
+ this.writer.releaseLock();
66
+ }
67
+ catch { }
68
+ }
69
+ write(message) {
70
+ const operation = this.writeQueue.then(() => this.writer.write(message));
71
+ this.writeQueue = operation.catch(() => { });
72
+ return operation;
73
+ }
74
+ async receive() {
75
+ try {
76
+ while (true) {
77
+ const item = await this.reader.read();
78
+ if (item.done)
79
+ return;
80
+ const message = item.value;
81
+ if ("result" in message || "error" in message) {
82
+ const pending = this.pending.get(message.id);
83
+ if (!pending)
84
+ continue;
85
+ this.pending.delete(message.id);
86
+ pending.resolve("result" in message ? { result: message.result } : { error: message.error });
87
+ continue;
88
+ }
89
+ if (!("id" in message)) {
90
+ if (message.method === "$/cancel_request") {
91
+ const requestId = cancelRequestId(message.params);
92
+ if (requestId !== undefined)
93
+ this.incoming.get(requestId)?.abort(RequestError.requestCancelled());
94
+ continue;
95
+ }
96
+ void Promise.resolve(this.handler.notification(message)).catch(() => { });
97
+ continue;
98
+ }
99
+ this.dispatchRequest(message);
100
+ }
101
+ }
102
+ finally {
103
+ this.reader.releaseLock();
104
+ }
105
+ }
106
+ dispatchRequest(message) {
107
+ const controller = new AbortController();
108
+ this.incoming.set(message.id, controller);
109
+ void Promise.resolve()
110
+ .then(() => this.handler.request(message, controller.signal))
111
+ .catch((error) => ({ error: errorResponse(error) }))
112
+ .then((result) => this.write({ jsonrpc: "2.0", id: message.id, ...result }))
113
+ .catch(() => { })
114
+ .finally(() => this.incoming.delete(message.id));
115
+ }
116
+ }
117
+ export function errorResponse(error) {
118
+ if (error instanceof RequestError)
119
+ return error.toErrorResponse();
120
+ return RequestError.internalError(undefined, error instanceof Error ? error.message : String(error)).toErrorResponse();
121
+ }
122
+ function cancelRequestId(params) {
123
+ if (params === null || typeof params !== "object" || Array.isArray(params))
124
+ return undefined;
125
+ const value = params.requestId;
126
+ return typeof value === "string" || typeof value === "number" || value === null ? value : undefined;
127
+ }
@@ -0,0 +1,18 @@
1
+ import { type Stream } from "@agentclientprotocol/sdk";
2
+ import type { CustomBackendConfig } from "@automatalabs/acp-agents";
3
+ import { type BackendTarget } from "./backends.js";
4
+ export interface ServeAcpServerOptions {
5
+ /** Outer ACP stream. Defaults to process stdin/stdout. */
6
+ stream?: Stream;
7
+ /** Programmatic custom backends merged over AGENTPRISM_BACKENDS. */
8
+ backends?: Record<string, CustomBackendConfig>;
9
+ /** Exact backend targets, primarily for embedding and deterministic tests. */
10
+ targets?: readonly BackendTarget[];
11
+ /** Package version advertised on discovery connections. */
12
+ version?: string;
13
+ /** Closes the active outer and downstream connections when aborted. */
14
+ signal?: AbortSignal;
15
+ }
16
+ /** Serve one connection-pinned AgentPrism ACP stdio connection until either side closes. */
17
+ export declare function serveAcpServer(options?: ServeAcpServerOptions): Promise<void>;
18
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AACA,OAAO,EAYL,KAAK,MAAM,EACZ,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,mBAAmB,EAAwB,MAAM,0BAA0B,CAAC;AAC1F,OAAO,EAAyB,KAAK,aAAa,EAAE,MAAM,eAAe,CAAC;AAgB1E,MAAM,WAAW,qBAAqB;IACpC,0DAA0D;IAC1D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oEAAoE;IACpE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IAC/C,8EAA8E;IAC9E,OAAO,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;IACnC,2DAA2D;IAC3D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,4FAA4F;AAC5F,wBAAsB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,IAAI,CAAC,CAiEvF"}
package/dist/server.js ADDED
@@ -0,0 +1,372 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { PROTOCOL_VERSION, RequestError, methods, ndJsonStream, } from "@agentclientprotocol/sdk";
3
+ import { Readable, Writable } from "node:stream";
4
+ import { resolveBackendTargets } from "./backends.js";
5
+ import { ACP_BACKENDS_PROBE_METHOD, assertSessionBackend, discoveryInitializeResponse, isRecord, mergeBackendInitializeResponse, parseProbeBackendsParams, parseRouterInitialize, } from "./protocol.js";
6
+ import { RawRpcPeer, errorResponse } from "./raw-rpc.js";
7
+ /** Serve one connection-pinned AgentPrism ACP stdio connection until either side closes. */
8
+ export async function serveAcpServer(options = {}) {
9
+ const stream = options.stream ?? stdioStream();
10
+ const targets = options.targets ? [...options.targets] : resolveBackendTargets({ backends: options.backends });
11
+ const targetsById = new Map(targets.map((target) => [target.id, target]));
12
+ if (targetsById.size !== targets.length)
13
+ throw new Error("ACP backend target ids must be unique");
14
+ const outerReader = stream.readable.getReader();
15
+ const first = await readFirst(outerReader, options.signal);
16
+ if (!first) {
17
+ outerReader.releaseLock();
18
+ return;
19
+ }
20
+ const remainingReadable = readableFromReader(outerReader);
21
+ const firstRequest = asInitializeRequest(first);
22
+ if (!firstRequest) {
23
+ await rejectFirstMessage(stream.writable, first);
24
+ await remainingReadable.cancel();
25
+ return;
26
+ }
27
+ let parsed;
28
+ try {
29
+ parsed = parseRouterInitialize(firstRequest.params);
30
+ }
31
+ catch (error) {
32
+ await writeResponseAndClose(stream.writable, {
33
+ jsonrpc: "2.0",
34
+ id: firstRequest.id,
35
+ error: errorResponse(error),
36
+ });
37
+ await remainingReadable.cancel();
38
+ return;
39
+ }
40
+ if (parsed.selection.mode === "discovery") {
41
+ await serveDiscoveryConnection({ readable: remainingReadable, writable: stream.writable }, firstRequest, parsed.request, targets, options.version ?? packageVersion(), options.signal);
42
+ return;
43
+ }
44
+ const target = targetsById.get(parsed.selection.backend);
45
+ if (!target) {
46
+ await writeResponseAndClose(stream.writable, {
47
+ jsonrpc: "2.0",
48
+ id: firstRequest.id,
49
+ error: RequestError.invalidParams(undefined, `unknown AgentPrism ACP backend ${JSON.stringify(parsed.selection.backend)}`).toErrorResponse(),
50
+ });
51
+ await remainingReadable.cancel();
52
+ return;
53
+ }
54
+ await serveBackendConnection({ readable: remainingReadable, writable: stream.writable }, firstRequest, target, options.signal);
55
+ }
56
+ function stdioStream() {
57
+ return ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin));
58
+ }
59
+ async function serveDiscoveryConnection(stream, initializeMessage, initializeRequest, targets, version, signal) {
60
+ const writer = stream.writable.getWriter();
61
+ await writer.write({
62
+ jsonrpc: "2.0",
63
+ id: initializeMessage.id,
64
+ result: discoveryInitializeResponse(version),
65
+ });
66
+ writer.releaseLock();
67
+ let peer;
68
+ const handler = {
69
+ request: async (message, requestSignal) => {
70
+ if (message.method !== ACP_BACKENDS_PROBE_METHOD) {
71
+ return { error: RequestError.methodNotFound(message.method).toErrorResponse() };
72
+ }
73
+ try {
74
+ const params = parseProbeBackendsParams(message.params);
75
+ return {
76
+ result: await probeBackends(targets, initializeRequest, params, peer, requestSignal),
77
+ };
78
+ }
79
+ catch (error) {
80
+ return { error: errorResponse(error) };
81
+ }
82
+ },
83
+ notification: () => { },
84
+ };
85
+ peer = new RawRpcPeer(stream, handler);
86
+ const onAbort = () => void peer.close(signal?.reason);
87
+ signal?.addEventListener("abort", onAbort, { once: true });
88
+ try {
89
+ await peer.closed;
90
+ }
91
+ finally {
92
+ signal?.removeEventListener("abort", onAbort);
93
+ await peer.close();
94
+ }
95
+ }
96
+ async function probeBackends(targets, initializeRequest, params, outer, signal) {
97
+ const backends = await Promise.all(targets.map((target) => probeBackend(target, initializeRequest, params, outer, signal)));
98
+ return { backends };
99
+ }
100
+ async function probeBackend(target, initializeRequest, params, outer, signal) {
101
+ let downstream;
102
+ let peer;
103
+ let sessionId;
104
+ let stage = "initialize";
105
+ try {
106
+ signal.throwIfAborted();
107
+ downstream = await target.open();
108
+ peer = new RawRpcPeer(downstream.stream, {
109
+ request: (message, requestSignal) => outer.request(message.method, message.params, requestSignal),
110
+ notification: (message) => outer.notify(message.method, message.params),
111
+ });
112
+ const initialized = await peer.request(methods.agent.initialize, initializeRequest, signal);
113
+ if ("error" in initialized)
114
+ throw new RequestError(initialized.error.code, initialized.error.message, initialized.error.data);
115
+ const initializeResponse = requireInitializeResponse(initialized.result);
116
+ stage = "session/new";
117
+ const created = await peer.request(methods.agent.session.new, params, signal);
118
+ if ("error" in created)
119
+ throw new RequestError(created.error.code, created.error.message, created.error.data);
120
+ const sessionResponse = requireNewSessionResponse(created.result);
121
+ sessionId = sessionResponse.sessionId;
122
+ return {
123
+ id: target.id,
124
+ name: target.name,
125
+ available: true,
126
+ ...(initializeResponse.agentInfo === undefined ? {} : { agentInfo: initializeResponse.agentInfo }),
127
+ ...(initializeResponse.agentCapabilities === undefined
128
+ ? {}
129
+ : { agentCapabilities: initializeResponse.agentCapabilities }),
130
+ ...(sessionResponse.modes === undefined ? {} : { modes: sessionResponse.modes }),
131
+ ...(sessionResponse.configOptions === undefined ? {} : { configOptions: sessionResponse.configOptions }),
132
+ ...(initializeResponse._meta === undefined ? {} : { initializeMeta: initializeResponse._meta }),
133
+ ...(sessionResponse._meta === undefined ? {} : { sessionMeta: sessionResponse._meta }),
134
+ };
135
+ }
136
+ catch (error) {
137
+ return {
138
+ id: target.id,
139
+ name: target.name,
140
+ available: false,
141
+ stage,
142
+ error: error instanceof Error ? error.message : String(error),
143
+ };
144
+ }
145
+ finally {
146
+ if (peer && sessionId) {
147
+ await peer.request(methods.agent.session.close, { sessionId }).catch(() => undefined);
148
+ }
149
+ await peer?.close();
150
+ await downstream?.close();
151
+ }
152
+ }
153
+ async function serveBackendConnection(outerStream, initializeMessage, target, signal) {
154
+ let downstream;
155
+ const outerWriter = outerStream.writable.getWriter();
156
+ const outerReader = outerStream.readable.getReader();
157
+ let innerWriter;
158
+ let innerReader;
159
+ let initializeResponded = false;
160
+ const onAbort = () => {
161
+ void outerReader.cancel(signal?.reason);
162
+ void innerReader?.cancel(signal?.reason);
163
+ };
164
+ signal?.addEventListener("abort", onAbort, { once: true });
165
+ try {
166
+ downstream = await target.open();
167
+ innerWriter = downstream.stream.writable.getWriter();
168
+ innerReader = downstream.stream.readable.getReader();
169
+ await innerWriter.write(initializeMessage);
170
+ const initialized = await readInitializeResponse(innerReader, outerWriter, initializeMessage.id);
171
+ if ("error" in initialized) {
172
+ await outerWriter.write(initialized);
173
+ initializeResponded = true;
174
+ return;
175
+ }
176
+ const response = requireInitializeResponse(initialized.result);
177
+ await outerWriter.write({
178
+ ...initialized,
179
+ result: mergeBackendInitializeResponse(response, target.id),
180
+ });
181
+ initializeResponded = true;
182
+ const clientToBackend = pumpClientToBackend(outerReader, innerWriter, outerWriter, target.id, signal);
183
+ const backendToClient = pumpUnchanged(innerReader, outerWriter, signal);
184
+ await Promise.race([clientToBackend, backendToClient]);
185
+ await Promise.allSettled([
186
+ outerReader.cancel(),
187
+ innerReader.cancel(),
188
+ clientToBackend,
189
+ backendToClient,
190
+ ]);
191
+ }
192
+ catch (error) {
193
+ if (!initializeResponded && !signal?.aborted) {
194
+ await outerWriter.write({
195
+ jsonrpc: "2.0",
196
+ id: initializeMessage.id,
197
+ error: errorResponse(error),
198
+ }).catch(() => undefined);
199
+ initializeResponded = true;
200
+ }
201
+ else if (!signal?.aborted) {
202
+ throw error;
203
+ }
204
+ }
205
+ finally {
206
+ signal?.removeEventListener("abort", onAbort);
207
+ await Promise.allSettled([
208
+ innerWriter?.close() ?? Promise.resolve(),
209
+ outerWriter.close(),
210
+ ]);
211
+ try {
212
+ innerReader?.releaseLock();
213
+ }
214
+ catch { }
215
+ try {
216
+ outerReader.releaseLock();
217
+ }
218
+ catch { }
219
+ try {
220
+ innerWriter?.releaseLock();
221
+ }
222
+ catch { }
223
+ try {
224
+ outerWriter.releaseLock();
225
+ }
226
+ catch { }
227
+ await downstream?.close();
228
+ }
229
+ }
230
+ async function readInitializeResponse(reader, outerWriter, initializeId) {
231
+ while (true) {
232
+ const item = await reader.read();
233
+ if (item.done)
234
+ throw new Error("ACP backend closed before initialize completed");
235
+ const message = item.value;
236
+ if (("result" in message || "error" in message) && message.id === initializeId)
237
+ return message;
238
+ await outerWriter.write(message);
239
+ }
240
+ }
241
+ async function pumpClientToBackend(reader, backendWriter, clientWriter, backendId, signal) {
242
+ while (!signal?.aborted) {
243
+ const item = await reader.read();
244
+ if (item.done)
245
+ return;
246
+ const message = item.value;
247
+ if ("method" in message && message.method === methods.agent.session.new && "id" in message) {
248
+ try {
249
+ assertSessionBackend(message.params, backendId);
250
+ }
251
+ catch (error) {
252
+ await clientWriter.write({ jsonrpc: "2.0", id: message.id, error: errorResponse(error) });
253
+ continue;
254
+ }
255
+ }
256
+ if ("method" in message && message.method.startsWith("_automatalabs/agentprism/")) {
257
+ if ("id" in message) {
258
+ await clientWriter.write({
259
+ jsonrpc: "2.0",
260
+ id: message.id,
261
+ error: RequestError.methodNotFound(message.method).toErrorResponse(),
262
+ });
263
+ }
264
+ continue;
265
+ }
266
+ await backendWriter.write(message);
267
+ }
268
+ }
269
+ async function pumpUnchanged(reader, writer, signal) {
270
+ while (!signal?.aborted) {
271
+ const item = await reader.read();
272
+ if (item.done)
273
+ return;
274
+ await writer.write(item.value);
275
+ }
276
+ }
277
+ function requireInitializeResponse(value) {
278
+ if (!isRecord(value) || value.protocolVersion !== PROTOCOL_VERSION) {
279
+ throw new Error(`ACP backend returned an invalid protocol-${PROTOCOL_VERSION} initialize response`);
280
+ }
281
+ return value;
282
+ }
283
+ function requireNewSessionResponse(value) {
284
+ if (!isRecord(value) || typeof value.sessionId !== "string" || value.sessionId.length === 0) {
285
+ throw new Error("ACP backend returned an invalid session/new response");
286
+ }
287
+ return value;
288
+ }
289
+ function asInitializeRequest(message) {
290
+ return "method" in message && "id" in message && message.method === methods.agent.initialize
291
+ ? message
292
+ : undefined;
293
+ }
294
+ async function rejectFirstMessage(writable, message) {
295
+ if ("method" in message && "id" in message) {
296
+ await writeResponseAndClose(writable, {
297
+ jsonrpc: "2.0",
298
+ id: message.id,
299
+ error: RequestError.invalidRequest(undefined, "first ACP request must be initialize").toErrorResponse(),
300
+ });
301
+ return;
302
+ }
303
+ const writer = writable.getWriter();
304
+ await writer.close();
305
+ writer.releaseLock();
306
+ }
307
+ async function writeResponseAndClose(writable, response) {
308
+ const writer = writable.getWriter();
309
+ try {
310
+ await writer.write(response);
311
+ await writer.close();
312
+ }
313
+ finally {
314
+ writer.releaseLock();
315
+ }
316
+ }
317
+ async function readFirst(reader, signal) {
318
+ if (!signal) {
319
+ const item = await reader.read();
320
+ return item.done ? undefined : item.value;
321
+ }
322
+ if (signal.aborted)
323
+ return undefined;
324
+ return new Promise((resolve, reject) => {
325
+ const onAbort = () => {
326
+ void reader.cancel(signal.reason);
327
+ resolve(undefined);
328
+ };
329
+ signal.addEventListener("abort", onAbort, { once: true });
330
+ reader.read().then((item) => {
331
+ signal.removeEventListener("abort", onAbort);
332
+ resolve(item.done ? undefined : item.value);
333
+ }, (error) => {
334
+ signal.removeEventListener("abort", onAbort);
335
+ reject(error);
336
+ });
337
+ });
338
+ }
339
+ function readableFromReader(reader) {
340
+ return new ReadableStream({
341
+ async pull(controller) {
342
+ try {
343
+ const item = await reader.read();
344
+ if (item.done) {
345
+ controller.close();
346
+ reader.releaseLock();
347
+ }
348
+ else {
349
+ controller.enqueue(item.value);
350
+ }
351
+ }
352
+ catch (error) {
353
+ controller.error(error);
354
+ try {
355
+ reader.releaseLock();
356
+ }
357
+ catch { }
358
+ }
359
+ },
360
+ async cancel(reason) {
361
+ await reader.cancel(reason);
362
+ try {
363
+ reader.releaseLock();
364
+ }
365
+ catch { }
366
+ },
367
+ });
368
+ }
369
+ function packageVersion() {
370
+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
371
+ return typeof manifest.version === "string" ? manifest.version : "0.0.0";
372
+ }
package/package.json CHANGED
@@ -1,21 +1,41 @@
1
1
  {
2
2
  "name": "@automatalabs/acp-server",
3
- "version": "0.0.0",
4
- "description": "Bootstrap package record for AgentPrism's ACP server.",
3
+ "version": "0.1.0",
5
4
  "license": "Apache-2.0",
5
+ "engines": {
6
+ "node": ">=22"
7
+ },
6
8
  "repository": {
7
9
  "type": "git",
8
10
  "url": "git+https://github.com/agentprism/agentprism-workflows.git",
9
11
  "directory": "packages/acp-server"
10
12
  },
11
- "homepage": "https://github.com/agentprism/agentprism-workflows/tree/main/packages/acp-server#readme",
12
- "bugs": {
13
- "url": "https://github.com/agentprism/agentprism-workflows/issues"
13
+ "type": "module",
14
+ "bin": {
15
+ "agentprism-acp-server": "./dist/cli.js"
16
+ },
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "default": "./dist/index.js"
24
+ }
14
25
  },
15
26
  "files": [
16
- "README.md"
27
+ "dist"
17
28
  ],
18
29
  "publishConfig": {
19
30
  "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@agentclientprotocol/sdk": "^1.4.0",
34
+ "@automatalabs/acp-agents": "1.1.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -b",
38
+ "typecheck": "tsc --noEmit",
39
+ "test": "tsx --test \"test/**/*.test.ts\""
20
40
  }
21
- }
41
+ }