@anureo/adapter-ahp 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 +201 -0
- package/README.md +63 -2
- package/dist/index.d.ts +31 -0
- package/dist/index.js +406 -0
- package/dist/websocket.d.ts +7 -0
- package/dist/wire.d.ts +35 -0
- package/examples/reference.mjs +171 -0
- package/package.json +47 -4
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,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @anureo/adapter-ahp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Adapter connecting the Anureo SDK to **external harnesses that speak AHP themselves** — over stdio or WebSocket. Use the anureo SDK to connect any harness, including one built on anureo: this package is the wire-level client for third-party ACP-style hosts that implement the same protocol the SDK is built on.
|
|
4
|
+
|
|
5
|
+
> Part of the [Anureo SDK workspace](../../README.md). Install with `npm install @anureo/adapter-ahp`.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import { createHarnessRuntime } from '@anureo/sdk'
|
|
11
|
+
import { createAhpAdapter, createWebSocketTransport } from '@anureo/adapter-ahp'
|
|
12
|
+
|
|
13
|
+
// Over stdio:
|
|
14
|
+
const stdioRuntime = createHarnessRuntime(createAhpAdapter({
|
|
15
|
+
command: 'my-harness', // spawned; speaks nd-JSON AHP on stdio
|
|
16
|
+
args: ['serve'],
|
|
17
|
+
}))
|
|
18
|
+
|
|
19
|
+
// Over WebSocket (loopback-only by default):
|
|
20
|
+
const wsRuntime = createHarnessRuntime(createAhpAdapter({
|
|
21
|
+
url: 'ws://127.0.0.1:9210',
|
|
22
|
+
connect: url => createWebSocketTransport(url),
|
|
23
|
+
}))
|
|
24
|
+
|
|
25
|
+
// Or inject any transport you already own:
|
|
26
|
+
const customRuntime = createHarnessRuntime(createAhpAdapter({
|
|
27
|
+
transport: () => Promise.resolve(myTransport),
|
|
28
|
+
}))
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
A minimal, dependency-free reference harness lives in [examples/reference.ts](examples/reference.ts); it implements the AHP wire contract on top of the SDK itself and can serve as the template for third-party harnesses.
|
|
32
|
+
|
|
33
|
+
## Behavior the adapter enforces
|
|
34
|
+
|
|
35
|
+
- **Version handshake.** `initialize` negotiates the AHP major version; every request and result is validated against the protocol schema before use.
|
|
36
|
+
- **Sequence integrity.** Events carry `(sessionId, streamId, seq)`. A gap in the sequence is repaired only when the harness negotiated `x-anureo/event-replay@1` (via `x-anureo/events/read`); otherwise the stream fails with `SOURCE_SEQUENCE_GAP` instead of presenting a hole as complete history.
|
|
37
|
+
- **Session metadata.** Delivered through the negotiated `x-anureo/session-metadata@1` extension; the adapter always requests it and ignores duplicated metadata from other channels.
|
|
38
|
+
- **Interactions.** `interaction/requested` is answered through the session's `respond()`/`cancelInteraction()`; the adapter forwards the answer over the wire and surfaces remote resolutions (`interaction/resolved`) without double-answering.
|
|
39
|
+
- **Unknown notifications.** Native notifications outside the AHP event set are converted to safe `notice` events with the raw (redacted) payload attached — a future-proofing harness cannot crash the host.
|
|
40
|
+
- **Connection loss.** A closed transport fails every open session sink and rejects pending responses with `outcomeUnknown`-carrying errors; no session continues silently on a dead wire.
|
|
41
|
+
|
|
42
|
+
## Exports
|
|
43
|
+
|
|
44
|
+
| Entry | Contents |
|
|
45
|
+
|---|---|
|
|
46
|
+
| `@anureo/adapter-ahp` | `createAhpAdapter`, `AhpAdapterOptions`, `AhpAdapter`, `AhpWire`, `AhpTransport`, `createStdioTransport`, `createWebSocketTransport` |
|
|
47
|
+
| `@anureo/adapter-ahp` (wire) | `AhpWire` — the JSON-RPC 2.0 client with per-request timeouts, frame-size limits (`maxFrameBytes`, default 8 MiB), pending-request limits (`maxPending`, default 256), and notification backlog bounds (`maxNotifications`, default 2048) |
|
|
48
|
+
|
|
49
|
+
`createWebSocketTransport` deliberately restricts addresses: `ws:` is only accepted for loopback hosts (`127.0.0.1`, `localhost`, `[::1]`), credentials, query strings, and fragments in URLs are rejected, and the socket's buffered amount is bounded — remote or authenticated transports must bring their own factory via `options.connect`.
|
|
50
|
+
|
|
51
|
+
## Development
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
cd packages/ahp
|
|
55
|
+
bun run typecheck
|
|
56
|
+
bun test tests
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The workspace's `bun run verify:pack` runs real stdio conversations against the reference harness, covering text turns, rejected approvals, and interrupts.
|
|
60
|
+
|
|
61
|
+
## Documentation
|
|
62
|
+
|
|
63
|
+
- [AHP v1 protocol](../../spec/ahp-v1.md) — the wire contract (currently in Chinese)
|
|
64
|
+
- [Architecture](../../docs/architecture.md)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type HarnessAdapter, type BackendSession, type SessionEventSink } from "@anureo/sdk";
|
|
2
|
+
import { type InitializeParams, type InitializeResult, type SessionOpenParams } from "@anureo/protocol";
|
|
3
|
+
import { createStdioTransport, type AhpTransport, type WireOptions } from "./wire.js";
|
|
4
|
+
export { AhpWire, createStdioTransport, type AhpTransport } from "./wire.js";
|
|
5
|
+
export { createWebSocketTransport } from "./websocket.js";
|
|
6
|
+
export interface AhpAdapterOptions extends WireOptions {
|
|
7
|
+
transport?: AhpTransport | (() => Promise<AhpTransport>);
|
|
8
|
+
command?: string;
|
|
9
|
+
args?: string[];
|
|
10
|
+
env?: Record<string, string | undefined>;
|
|
11
|
+
cwd?: string;
|
|
12
|
+
url?: string;
|
|
13
|
+
connect?: (url: string) => Promise<AhpTransport>;
|
|
14
|
+
processFactory?: Parameters<typeof createStdioTransport>[0]["processFactory"];
|
|
15
|
+
}
|
|
16
|
+
export declare class AhpAdapter implements HarnessAdapter {
|
|
17
|
+
private readonly options;
|
|
18
|
+
private wire?;
|
|
19
|
+
private initialized?;
|
|
20
|
+
private result?;
|
|
21
|
+
private readonly sessions;
|
|
22
|
+
private readonly responding;
|
|
23
|
+
private disposed;
|
|
24
|
+
constructor(options: AhpAdapterOptions);
|
|
25
|
+
initialize(params: InitializeParams): Promise<InitializeResult>;
|
|
26
|
+
private notification;
|
|
27
|
+
private deliver;
|
|
28
|
+
openSession(params: SessionOpenParams, sink: SessionEventSink): Promise<BackendSession>;
|
|
29
|
+
dispose(): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
export declare function createAhpAdapter(options: AhpAdapterOptions): HarnessAdapter;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
// packages/ahp/src/index.ts
|
|
2
|
+
import { HarnessSdkError as HarnessSdkError3 } from "@anureo/sdk";
|
|
3
|
+
import { assertDefinition, assertEvent, assertResult, negotiateVersion, supportsExtension, publicValue } from "@anureo/protocol";
|
|
4
|
+
|
|
5
|
+
// packages/ahp/src/wire.ts
|
|
6
|
+
import { HarnessSdkError } from "@anureo/sdk";
|
|
7
|
+
import { spawnHarnessProcess } from "@anureo/sdk/process";
|
|
8
|
+
|
|
9
|
+
class AhpWire {
|
|
10
|
+
transport;
|
|
11
|
+
options;
|
|
12
|
+
nextId = 1;
|
|
13
|
+
pending = new Map;
|
|
14
|
+
closing = false;
|
|
15
|
+
tail = Promise.resolve();
|
|
16
|
+
backlog = 0;
|
|
17
|
+
loop;
|
|
18
|
+
onNotification;
|
|
19
|
+
onClose;
|
|
20
|
+
constructor(transport, options = {}) {
|
|
21
|
+
this.transport = transport;
|
|
22
|
+
this.options = options;
|
|
23
|
+
this.loop = this.read();
|
|
24
|
+
}
|
|
25
|
+
request(method, params) {
|
|
26
|
+
if (this.closing)
|
|
27
|
+
return Promise.reject(new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
28
|
+
if (this.pending.size >= (this.options.maxPending ?? 256))
|
|
29
|
+
return Promise.reject(new HarnessSdkError("BACKPRESSURE_EXCEEDED"));
|
|
30
|
+
const id = this.nextId++, message = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
31
|
+
if (new TextEncoder().encode(message).byteLength > (this.options.maxFrameBytes ?? 8 * 1024 * 1024))
|
|
32
|
+
return Promise.reject(new HarnessSdkError("FRAME_TOO_LARGE"));
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const timer = setTimeout(() => {
|
|
35
|
+
this.pending.delete(id);
|
|
36
|
+
reject(new HarnessSdkError("RPC_TIMEOUT", "RPC_TIMEOUT", false, true, { method }));
|
|
37
|
+
}, this.options.timeoutMs ?? 30000);
|
|
38
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
39
|
+
this.transport.send(message).catch(() => {
|
|
40
|
+
const p = this.pending.get(id);
|
|
41
|
+
if (p) {
|
|
42
|
+
clearTimeout(p.timer);
|
|
43
|
+
this.pending.delete(id);
|
|
44
|
+
p.reject(new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
notify(method, params) {
|
|
50
|
+
return this.transport.send(JSON.stringify({ jsonrpc: "2.0", method, ...params === undefined ? {} : { params } }));
|
|
51
|
+
}
|
|
52
|
+
async read() {
|
|
53
|
+
let failure = new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true);
|
|
54
|
+
try {
|
|
55
|
+
for await (const frame of this.transport.messages) {
|
|
56
|
+
if (this.closing)
|
|
57
|
+
break;
|
|
58
|
+
if (new TextEncoder().encode(frame).byteLength > (this.options.maxFrameBytes ?? 8 * 1024 * 1024))
|
|
59
|
+
throw new HarnessSdkError("FRAME_TOO_LARGE");
|
|
60
|
+
let value;
|
|
61
|
+
try {
|
|
62
|
+
value = JSON.parse(frame);
|
|
63
|
+
} catch {
|
|
64
|
+
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
65
|
+
}
|
|
66
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
67
|
+
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
68
|
+
const message = value;
|
|
69
|
+
if (message.jsonrpc !== "2.0")
|
|
70
|
+
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
71
|
+
if (typeof message.method === "string") {
|
|
72
|
+
if (message.id !== undefined) {
|
|
73
|
+
await this.transport.send(JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Method not found" } }));
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (++this.backlog > (this.options.maxNotifications ?? 2048))
|
|
77
|
+
throw new HarnessSdkError("BACKPRESSURE_EXCEEDED");
|
|
78
|
+
this.tail = this.tail.then(() => this.onNotification?.(message.method, message.params)).catch(async (cause) => {
|
|
79
|
+
await this.fail(cause);
|
|
80
|
+
}).finally(() => this.backlog--);
|
|
81
|
+
} else {
|
|
82
|
+
const pending = this.pending.get(message.id);
|
|
83
|
+
if (!pending)
|
|
84
|
+
continue;
|
|
85
|
+
clearTimeout(pending.timer);
|
|
86
|
+
this.pending.delete(message.id);
|
|
87
|
+
if (message.error && typeof message.error === "object") {
|
|
88
|
+
const error = message.error, data = error.data && typeof error.data === "object" ? error.data : {};
|
|
89
|
+
pending.reject(new HarnessSdkError(typeof data.code === "string" ? data.code : error.code === -32601 ? "CAPABILITY_UNSUPPORTED" : "AHP_RPC_ERROR", "AHP_RPC_ERROR", data.retryable === true, data.outcomeUnknown === true));
|
|
90
|
+
} else if (Object.hasOwn(message, "result"))
|
|
91
|
+
pending.resolve(message.result);
|
|
92
|
+
else
|
|
93
|
+
pending.reject(new HarnessSdkError("PROTOCOL_ERROR"));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
} catch (cause) {
|
|
97
|
+
failure = cause;
|
|
98
|
+
}
|
|
99
|
+
if (!this.closing)
|
|
100
|
+
await this.fail(failure);
|
|
101
|
+
}
|
|
102
|
+
async fail(cause) {
|
|
103
|
+
if (this.closing)
|
|
104
|
+
return;
|
|
105
|
+
this.closing = true;
|
|
106
|
+
for (const pending of this.pending.values()) {
|
|
107
|
+
clearTimeout(pending.timer);
|
|
108
|
+
pending.reject(new HarnessSdkError("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
109
|
+
}
|
|
110
|
+
this.pending.clear();
|
|
111
|
+
this.options.diagnostic?.(cause instanceof HarnessSdkError ? cause.code : "PROTOCOL_ERROR");
|
|
112
|
+
await this.onClose?.(cause);
|
|
113
|
+
await this.transport.close();
|
|
114
|
+
}
|
|
115
|
+
async close() {
|
|
116
|
+
if (!this.closing)
|
|
117
|
+
await this.fail(new HarnessSdkError("RUNTIME_DISPOSED"));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async function createStdioTransport(options) {
|
|
121
|
+
const process = await (options.processFactory ?? spawnHarnessProcess)(options);
|
|
122
|
+
const max = options.maxFrameBytes ?? 8 * 1024 * 1024;
|
|
123
|
+
(async () => {
|
|
124
|
+
for await (const _ of process.stderr) {}
|
|
125
|
+
})().catch(() => {});
|
|
126
|
+
async function* messages() {
|
|
127
|
+
const decoder = new TextDecoder;
|
|
128
|
+
let buffer = "";
|
|
129
|
+
for await (const chunk of process.stdout) {
|
|
130
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
131
|
+
for (;; ) {
|
|
132
|
+
const index = buffer.indexOf(`
|
|
133
|
+
`);
|
|
134
|
+
if (index < 0)
|
|
135
|
+
break;
|
|
136
|
+
const line = buffer.slice(0, index).replace(/\r$/, "");
|
|
137
|
+
buffer = buffer.slice(index + 1);
|
|
138
|
+
if (new TextEncoder().encode(line).byteLength > max)
|
|
139
|
+
throw new HarnessSdkError("FRAME_TOO_LARGE");
|
|
140
|
+
if (line)
|
|
141
|
+
yield line;
|
|
142
|
+
}
|
|
143
|
+
if (new TextEncoder().encode(buffer).byteLength > max)
|
|
144
|
+
throw new HarnessSdkError("FRAME_TOO_LARGE");
|
|
145
|
+
}
|
|
146
|
+
buffer += decoder.decode();
|
|
147
|
+
if (buffer.trim())
|
|
148
|
+
throw new HarnessSdkError("PROTOCOL_ERROR", "Unterminated AHP frame");
|
|
149
|
+
}
|
|
150
|
+
return { messages: messages(), send: (message) => process.write(message + `
|
|
151
|
+
`), close: () => process.dispose() };
|
|
152
|
+
}
|
|
153
|
+
// packages/ahp/src/websocket.ts
|
|
154
|
+
import { BoundedEventQueue, HarnessSdkError as HarnessSdkError2 } from "@anureo/sdk";
|
|
155
|
+
async function createWebSocketTransport(url, options = {}) {
|
|
156
|
+
const address = new URL(url);
|
|
157
|
+
if (!["ws:", "wss:"].includes(address.protocol) || address.username || address.password || address.search || address.hash || address.protocol === "ws:" && !["127.0.0.1", "localhost", "[::1]"].includes(address.hostname))
|
|
158
|
+
throw new HarnessSdkError2("INVALID_PARAMS", "Invalid AHP WebSocket address");
|
|
159
|
+
if (!options.factory && typeof WebSocket === "undefined")
|
|
160
|
+
throw new HarnessSdkError2("WEBSOCKET_FACTORY_REQUIRED");
|
|
161
|
+
const socket = options.factory ? options.factory(url) : new WebSocket(url);
|
|
162
|
+
const queue = new BoundedEventQueue({ maxFrameBytes: options.maxFrameBytes, maxBytes: options.maxBufferedBytes ?? 16 * 1024 * 1024, maxEvents: 2048 }, (v) => new TextEncoder().encode(v).byteLength);
|
|
163
|
+
let closed = false;
|
|
164
|
+
const fail = () => {
|
|
165
|
+
queue.end(new HarnessSdkError2("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true));
|
|
166
|
+
};
|
|
167
|
+
socket.addEventListener("message", (event) => {
|
|
168
|
+
try {
|
|
169
|
+
if (typeof event.data !== "string")
|
|
170
|
+
throw new HarnessSdkError2("PROTOCOL_ERROR");
|
|
171
|
+
queue.push(event.data);
|
|
172
|
+
} catch (cause) {
|
|
173
|
+
queue.end(cause);
|
|
174
|
+
socket.close();
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
socket.addEventListener("close", () => {
|
|
178
|
+
closed = true;
|
|
179
|
+
fail();
|
|
180
|
+
});
|
|
181
|
+
socket.addEventListener("error", fail);
|
|
182
|
+
await new Promise((resolve, reject) => {
|
|
183
|
+
const timeout = setTimeout(() => {
|
|
184
|
+
socket.close();
|
|
185
|
+
reject(new HarnessSdkError2("RPC_TIMEOUT"));
|
|
186
|
+
}, options.timeoutMs ?? 30000);
|
|
187
|
+
const finish = () => {
|
|
188
|
+
clearTimeout(timeout);
|
|
189
|
+
socket.removeEventListener("open", opened);
|
|
190
|
+
socket.removeEventListener("error", failed);
|
|
191
|
+
socket.removeEventListener("close", failed);
|
|
192
|
+
};
|
|
193
|
+
const opened = () => {
|
|
194
|
+
finish();
|
|
195
|
+
resolve();
|
|
196
|
+
}, failed = () => {
|
|
197
|
+
finish();
|
|
198
|
+
reject(new HarnessSdkError2("RPC_CONNECTION_FAILED"));
|
|
199
|
+
};
|
|
200
|
+
socket.addEventListener("open", opened);
|
|
201
|
+
socket.addEventListener("error", failed);
|
|
202
|
+
socket.addEventListener("close", failed);
|
|
203
|
+
if (socket.readyState === 1)
|
|
204
|
+
opened();
|
|
205
|
+
});
|
|
206
|
+
return { messages: queue, async send(message) {
|
|
207
|
+
if (closed || socket.readyState !== 1)
|
|
208
|
+
throw new HarnessSdkError2("RPC_CONNECTION_CLOSED", "RPC_CONNECTION_CLOSED", false, true);
|
|
209
|
+
if (socket.bufferedAmount > (options.maxBufferedBytes ?? 16 * 1024 * 1024))
|
|
210
|
+
throw new HarnessSdkError2("BACKPRESSURE_EXCEEDED");
|
|
211
|
+
socket.send(message);
|
|
212
|
+
}, async close() {
|
|
213
|
+
if (closed)
|
|
214
|
+
return;
|
|
215
|
+
closed = true;
|
|
216
|
+
socket.close();
|
|
217
|
+
queue.end();
|
|
218
|
+
} };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// packages/ahp/src/index.ts
|
|
222
|
+
var METADATA_EXTENSION = { name: "x-anureo/session-metadata", version: "1" };
|
|
223
|
+
|
|
224
|
+
class AhpAdapter {
|
|
225
|
+
options;
|
|
226
|
+
wire;
|
|
227
|
+
initialized;
|
|
228
|
+
result;
|
|
229
|
+
sessions = new Map;
|
|
230
|
+
responding = new Map;
|
|
231
|
+
disposed = false;
|
|
232
|
+
constructor(options) {
|
|
233
|
+
this.options = options;
|
|
234
|
+
}
|
|
235
|
+
initialize(params) {
|
|
236
|
+
negotiateVersion(params.protocolVersions);
|
|
237
|
+
return this.initialized ??= (async () => {
|
|
238
|
+
let transport;
|
|
239
|
+
if (this.options.transport)
|
|
240
|
+
transport = typeof this.options.transport === "function" ? await this.options.transport() : this.options.transport;
|
|
241
|
+
else if (this.options.url) {
|
|
242
|
+
if (!this.options.connect)
|
|
243
|
+
throw new HarnessSdkError3("WEBSOCKET_FACTORY_REQUIRED");
|
|
244
|
+
transport = await this.options.connect(this.options.url);
|
|
245
|
+
} else {
|
|
246
|
+
if (!this.options.command)
|
|
247
|
+
throw new HarnessSdkError3("HARNESS_UNAVAILABLE");
|
|
248
|
+
transport = await createStdioTransport({ ...this.options, command: this.options.command });
|
|
249
|
+
}
|
|
250
|
+
const wire = this.wire = new AhpWire(transport, this.options);
|
|
251
|
+
wire.onNotification = (method, event) => this.notification(method, event);
|
|
252
|
+
wire.onClose = async (cause) => {
|
|
253
|
+
for (const session of this.sessions.values())
|
|
254
|
+
await session.sink.fail(cause);
|
|
255
|
+
for (const pending of this.responding.values())
|
|
256
|
+
pending.reject(cause);
|
|
257
|
+
this.responding.clear();
|
|
258
|
+
};
|
|
259
|
+
const clientCapabilities = { ...params.clientCapabilities, extensions: [...(params.clientCapabilities?.extensions ?? []).filter((e) => e.name !== METADATA_EXTENSION.name), METADATA_EXTENSION] };
|
|
260
|
+
const result = await wire.request("initialize", { ...params, clientCapabilities });
|
|
261
|
+
assertResult("initialize", result);
|
|
262
|
+
negotiateVersion([result.protocolVersion]);
|
|
263
|
+
this.result = result;
|
|
264
|
+
await wire.notify("initialized");
|
|
265
|
+
return result;
|
|
266
|
+
})();
|
|
267
|
+
}
|
|
268
|
+
async notification(method, value) {
|
|
269
|
+
const known = ["session/metadata", "session/state", "turn/started", "turn/completed", "item/started", "item/delta", "item/completed", "usage/updated", "interaction/requested", "interaction/resolved", "notice", "extension"];
|
|
270
|
+
if (!known.includes(method)) {
|
|
271
|
+
const raw = publicValue(JSON.parse(JSON.stringify(value ?? null)));
|
|
272
|
+
for (const session of this.sessions.values())
|
|
273
|
+
await session.sink.emit({ type: "notice", payload: { severity: "info", code: "UNKNOWN_NOTIFICATION", message: "Unknown AHP notification", raw } });
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
assertEvent(value);
|
|
277
|
+
if (value.type !== method)
|
|
278
|
+
throw new HarnessSdkError3("PROTOCOL_ERROR");
|
|
279
|
+
const session = this.sessions.get(value.sessionId);
|
|
280
|
+
if (!session)
|
|
281
|
+
throw new HarnessSdkError3("SOURCE_SESSION_MISMATCH");
|
|
282
|
+
const last = session.lastByStream.get(value.streamId) ?? 0;
|
|
283
|
+
if (value.seq <= last)
|
|
284
|
+
return;
|
|
285
|
+
if (session.streamId && session.streamId !== value.streamId)
|
|
286
|
+
throw new HarnessSdkError3("SOURCE_STREAM_UNAVAILABLE");
|
|
287
|
+
session.streamId = value.streamId;
|
|
288
|
+
if (value.seq !== last + 1) {
|
|
289
|
+
if (!this.result || !supportsExtension(this.result.capabilities, "x-anureo/event-replay", "1"))
|
|
290
|
+
throw new HarnessSdkError3("SOURCE_SEQUENCE_GAP");
|
|
291
|
+
const raw = await this.wire.request("x-anureo/events/read", { sessionId: value.sessionId, streamId: value.streamId, afterSeq: last, throughSeq: value.seq - 1 });
|
|
292
|
+
if (!raw || typeof raw !== "object" || !("events" in raw) || !Array.isArray(raw.events))
|
|
293
|
+
throw new HarnessSdkError3("SOURCE_STREAM_UNAVAILABLE");
|
|
294
|
+
for (const event of raw.events) {
|
|
295
|
+
assertEvent(event);
|
|
296
|
+
if (event.sessionId !== value.sessionId || event.streamId !== value.streamId || event.seq !== (session.lastByStream.get(value.streamId) ?? 0) + 1 || event.seq >= value.seq)
|
|
297
|
+
throw new HarnessSdkError3("SOURCE_SEQUENCE_GAP");
|
|
298
|
+
await this.deliver(session, event);
|
|
299
|
+
}
|
|
300
|
+
if ((session.lastByStream.get(value.streamId) ?? 0) + 1 !== value.seq)
|
|
301
|
+
throw new HarnessSdkError3("SOURCE_SEQUENCE_GAP");
|
|
302
|
+
}
|
|
303
|
+
await this.deliver(session, value);
|
|
304
|
+
}
|
|
305
|
+
async deliver(session, event) {
|
|
306
|
+
session.lastByStream.set(event.streamId, event.seq);
|
|
307
|
+
const scope = { turnId: event.turnId, itemId: event.itemId };
|
|
308
|
+
if (event.type === "session/metadata" || event.type === "extension" && event.payload.name === METADATA_EXTENSION.name) {
|
|
309
|
+
if (!this.result || !supportsExtension(this.result.capabilities, METADATA_EXTENSION.name, METADATA_EXTENSION.version))
|
|
310
|
+
throw new HarnessSdkError3("CAPABILITY_UNSUPPORTED");
|
|
311
|
+
if (event.type === "extension" && event.payload.version !== METADATA_EXTENSION.version)
|
|
312
|
+
throw new HarnessSdkError3("CAPABILITY_UNSUPPORTED");
|
|
313
|
+
const metadata = event.type === "session/metadata" ? event.payload : event.payload.data;
|
|
314
|
+
assertDefinition("SessionMetadata", metadata);
|
|
315
|
+
if (Object.hasOwn(metadata, "title"))
|
|
316
|
+
session.metadataObserved = true;
|
|
317
|
+
await session.sink.emit({ type: "session/metadata", payload: metadata });
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (event.type === "interaction/requested") {
|
|
321
|
+
const request = event.payload, key = `${event.sessionId}:${request.interactionId}`;
|
|
322
|
+
session.pending.add(request.interactionId);
|
|
323
|
+
session.sink.requestInteraction(request, async (response, reason) => {
|
|
324
|
+
let resolve, reject;
|
|
325
|
+
const confirmation = new Promise((yes, no) => {
|
|
326
|
+
resolve = yes;
|
|
327
|
+
reject = no;
|
|
328
|
+
});
|
|
329
|
+
this.responding.set(key, { resolve, reject });
|
|
330
|
+
try {
|
|
331
|
+
const method = response ? "interaction/respond" : "interaction/cancel";
|
|
332
|
+
const call = this.wire.request(method, { requestId: `ahp:${event.streamId}:${event.seq}`, sessionId: event.sessionId, interactionId: request.interactionId, ...response ? { response } : { reason } });
|
|
333
|
+
const result = await Promise.race([call, confirmation]);
|
|
334
|
+
assertResult(method, result);
|
|
335
|
+
if (result.outcome === "unknown")
|
|
336
|
+
throw new HarnessSdkError3("RESULT_UNKNOWN", "RESULT_UNKNOWN", false, true);
|
|
337
|
+
} finally {
|
|
338
|
+
this.responding.delete(key);
|
|
339
|
+
session.pending.delete(request.interactionId);
|
|
340
|
+
}
|
|
341
|
+
}).catch(() => {});
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
if (event.type === "interaction/resolved") {
|
|
345
|
+
const key = `${event.sessionId}:${event.payload.interactionId}`, responding = this.responding.get(key);
|
|
346
|
+
if (responding) {
|
|
347
|
+
responding.resolve(event.payload);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
if (session.pending.has(event.payload.interactionId)) {
|
|
351
|
+
session.pending.delete(event.payload.interactionId);
|
|
352
|
+
await session.sink.resolveInteraction(event.payload);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
if (event.type === "session/state" && event.payload.metadata && Object.hasOwn(event.payload.metadata, "title"))
|
|
358
|
+
session.metadataObserved = true;
|
|
359
|
+
await session.sink.emit({ type: event.type, payload: event.payload }, scope);
|
|
360
|
+
}
|
|
361
|
+
async openSession(params, sink) {
|
|
362
|
+
if (!this.wire || this.disposed)
|
|
363
|
+
throw new HarnessSdkError3("NOT_INITIALIZED");
|
|
364
|
+
if (this.sessions.has(params.binding.sessionId))
|
|
365
|
+
throw new HarnessSdkError3("SESSION_ALREADY_OPEN");
|
|
366
|
+
const record = { sink, lastByStream: new Map, pending: new Set };
|
|
367
|
+
this.sessions.set(params.binding.sessionId, record);
|
|
368
|
+
try {
|
|
369
|
+
const opened = await this.wire.request("session/open", params);
|
|
370
|
+
assertResult("session/open", opened);
|
|
371
|
+
if (opened.binding.sessionId !== params.binding.sessionId || opened.binding.adapterId !== params.binding.adapterId || opened.binding.runtimeConfigId !== params.binding.runtimeConfigId)
|
|
372
|
+
throw new HarnessSdkError3("SESSION_BINDING_MISMATCH");
|
|
373
|
+
record.streamId = opened.streamId;
|
|
374
|
+
if (!record.metadataObserved && opened.state?.metadata)
|
|
375
|
+
await sink.emit({ type: "session/metadata", payload: opened.state.metadata });
|
|
376
|
+
const adapter = this;
|
|
377
|
+
return { binding: opened.binding, capabilities: opened.capabilities, async execute(method, p) {
|
|
378
|
+
const result = await adapter.wire.request(method, p);
|
|
379
|
+
assertResult(method, result);
|
|
380
|
+
return result;
|
|
381
|
+
}, async dispose() {
|
|
382
|
+
adapter.sessions.delete(params.binding.sessionId);
|
|
383
|
+
} };
|
|
384
|
+
} catch (cause) {
|
|
385
|
+
this.sessions.delete(params.binding.sessionId);
|
|
386
|
+
throw cause;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
async dispose() {
|
|
390
|
+
if (this.disposed)
|
|
391
|
+
return;
|
|
392
|
+
this.disposed = true;
|
|
393
|
+
await this.wire?.close();
|
|
394
|
+
this.sessions.clear();
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function createAhpAdapter(options) {
|
|
398
|
+
return new AhpAdapter(options);
|
|
399
|
+
}
|
|
400
|
+
export {
|
|
401
|
+
AhpAdapter,
|
|
402
|
+
AhpWire,
|
|
403
|
+
createAhpAdapter,
|
|
404
|
+
createStdioTransport,
|
|
405
|
+
createWebSocketTransport
|
|
406
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AhpTransport } from "./wire.js";
|
|
2
|
+
export declare function createWebSocketTransport(url: string, options?: {
|
|
3
|
+
factory?: (url: string) => WebSocket;
|
|
4
|
+
timeoutMs?: number;
|
|
5
|
+
maxFrameBytes?: number;
|
|
6
|
+
maxBufferedBytes?: number;
|
|
7
|
+
}): Promise<AhpTransport>;
|
package/dist/wire.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type HarnessProcess, type HarnessProcessOptions } from "@anureo/sdk/process";
|
|
2
|
+
export interface AhpTransport {
|
|
3
|
+
messages: AsyncIterable<string>;
|
|
4
|
+
send: (message: string) => Promise<void>;
|
|
5
|
+
close: () => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export interface WireOptions {
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
maxFrameBytes?: number;
|
|
10
|
+
maxPending?: number;
|
|
11
|
+
maxNotifications?: number;
|
|
12
|
+
diagnostic?: (code: string) => void;
|
|
13
|
+
}
|
|
14
|
+
export declare class AhpWire {
|
|
15
|
+
private readonly transport;
|
|
16
|
+
private readonly options;
|
|
17
|
+
private nextId;
|
|
18
|
+
private readonly pending;
|
|
19
|
+
private closing;
|
|
20
|
+
private tail;
|
|
21
|
+
private backlog;
|
|
22
|
+
private readonly loop;
|
|
23
|
+
onNotification?: (method: string, params: unknown) => Promise<void> | void;
|
|
24
|
+
onClose?: (cause: unknown) => Promise<void> | void;
|
|
25
|
+
constructor(transport: AhpTransport, options?: WireOptions);
|
|
26
|
+
request(method: string, params: unknown): Promise<unknown>;
|
|
27
|
+
notify(method: string, params?: unknown): Promise<void>;
|
|
28
|
+
private read;
|
|
29
|
+
private fail;
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
export declare function createStdioTransport(options: HarnessProcessOptions & {
|
|
33
|
+
processFactory?: (p: HarnessProcessOptions) => Promise<HarnessProcess>;
|
|
34
|
+
maxFrameBytes?: number;
|
|
35
|
+
}): Promise<AhpTransport>;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// packages/ahp/examples/reference.ts
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
6
|
+
import { createHarnessRuntime, HarnessSdkError } from "@anureo/sdk";
|
|
7
|
+
import { assertRequest, negotiateVersion, supportsExtension } from "@anureo/protocol";
|
|
8
|
+
var capabilities = { turn: { interrupt: true, inputModalities: ["text"] }, interactions: ["approval"], extensions: [{ name: "x-anureo/event-replay", version: "1" }, { name: "x-anureo/session-metadata", version: "1" }] };
|
|
9
|
+
|
|
10
|
+
class ReferenceAdapter {
|
|
11
|
+
metadataEnabled = false;
|
|
12
|
+
async initialize(p) {
|
|
13
|
+
negotiateVersion(p.protocolVersions);
|
|
14
|
+
this.metadataEnabled = supportsExtension(p.clientCapabilities ?? {}, "x-anureo/session-metadata", "1");
|
|
15
|
+
return { protocolVersion: 1, runtime: { name: "reference", version: "1.0.0", adapter: "reference/1" }, capabilities };
|
|
16
|
+
}
|
|
17
|
+
async openSession(p, sink) {
|
|
18
|
+
const binding = { ...p.binding, nativeRef: { provider: "reference", value: p.binding.sessionId } };
|
|
19
|
+
let active, closed = false;
|
|
20
|
+
const metadataEnabled = this.metadataEnabled;
|
|
21
|
+
return { binding, capabilities, async execute(method, params) {
|
|
22
|
+
if (method === "session/close")
|
|
23
|
+
return { closed: true };
|
|
24
|
+
if (method === "turn/interrupt") {
|
|
25
|
+
const turnId = params.turnId;
|
|
26
|
+
if (active === turnId) {
|
|
27
|
+
active = undefined;
|
|
28
|
+
await sink.emit({ type: "turn/completed", payload: { turnId, status: "interrupted" } });
|
|
29
|
+
}
|
|
30
|
+
return { accepted: true, turnId };
|
|
31
|
+
}
|
|
32
|
+
if (method !== "turn/start")
|
|
33
|
+
throw new HarnessSdkError("CAPABILITY_UNSUPPORTED");
|
|
34
|
+
const request = params;
|
|
35
|
+
active = request.turnId;
|
|
36
|
+
await sink.emit({ type: "turn/started", payload: { turnId: request.turnId, nativeTurnId: request.turnId } });
|
|
37
|
+
const text = request.input.filter((x) => x.type === "text").map((x) => x.text).join(`
|
|
38
|
+
`);
|
|
39
|
+
if (metadataEnabled && text.startsWith("/title "))
|
|
40
|
+
await sink.emit({ type: "session/metadata", payload: { title: text.slice(7) || null } });
|
|
41
|
+
if (text !== "/wait")
|
|
42
|
+
(async () => {
|
|
43
|
+
if (text === "/approval")
|
|
44
|
+
await sink.requestInteraction({ kind: "approval", interactionId: `approval:${request.turnId}`, turnId: request.turnId, options: [{ id: "allow", label: "Allow once", semantic: "allowOnce" }, { id: "deny", label: "Deny", semantic: "deny" }] }, async () => {});
|
|
45
|
+
if (closed || active !== request.turnId)
|
|
46
|
+
return;
|
|
47
|
+
const item = { id: "message", type: "agentMessage", text, phase: "final" };
|
|
48
|
+
await sink.emit({ type: "item/started", payload: { item: { ...item, text: "" } } }, { turnId: request.turnId });
|
|
49
|
+
await sink.emit({ type: "item/completed", payload: { item } }, { turnId: request.turnId });
|
|
50
|
+
active = undefined;
|
|
51
|
+
await sink.emit({ type: "turn/completed", payload: { turnId: request.turnId, status: "completed" } });
|
|
52
|
+
})().catch(async () => {
|
|
53
|
+
if (!closed && active === request.turnId) {
|
|
54
|
+
active = undefined;
|
|
55
|
+
await sink.emit({ type: "turn/completed", payload: { turnId: request.turnId, status: "interrupted" } });
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
return { turnId: request.turnId, accepted: true };
|
|
59
|
+
}, async dispose() {
|
|
60
|
+
closed = true;
|
|
61
|
+
active = undefined;
|
|
62
|
+
} };
|
|
63
|
+
}
|
|
64
|
+
async dispose() {}
|
|
65
|
+
}
|
|
66
|
+
function createReferenceHarness(send) {
|
|
67
|
+
const runtime = createHarnessRuntime(new ReferenceAdapter), sessions = new Map, logs = new Map;
|
|
68
|
+
const publish = async (event) => {
|
|
69
|
+
if (event.type === "session/metadata")
|
|
70
|
+
event = { ...event, type: "extension", payload: { name: "x-anureo/session-metadata", version: "1", data: event.payload } };
|
|
71
|
+
const log = logs.get(event.sessionId) ?? [];
|
|
72
|
+
log.push(event);
|
|
73
|
+
if (log.length > 2048)
|
|
74
|
+
log.shift();
|
|
75
|
+
logs.set(event.sessionId, log);
|
|
76
|
+
await send(JSON.stringify({ jsonrpc: "2.0", method: event.type, params: event }));
|
|
77
|
+
};
|
|
78
|
+
const invoke = async (method, params) => {
|
|
79
|
+
if (method === "initialize") {
|
|
80
|
+
assertRequest("initialize", params);
|
|
81
|
+
return runtime.initialize(params);
|
|
82
|
+
}
|
|
83
|
+
if (method === "session/open") {
|
|
84
|
+
assertRequest("session/open", params);
|
|
85
|
+
const session = await runtime.openSession(params);
|
|
86
|
+
sessions.set(session.binding.sessionId, session);
|
|
87
|
+
const reader = session.events()[Symbol.asyncIterator](), first = await reader.next();
|
|
88
|
+
if (first.done || first.value.type !== "session/state")
|
|
89
|
+
throw new HarnessSdkError("PROTOCOL_ERROR");
|
|
90
|
+
await publish(first.value);
|
|
91
|
+
(async () => {
|
|
92
|
+
for (;; ) {
|
|
93
|
+
const entry = await reader.next();
|
|
94
|
+
if (entry.done)
|
|
95
|
+
return;
|
|
96
|
+
await publish(entry.value);
|
|
97
|
+
}
|
|
98
|
+
})().catch(() => {});
|
|
99
|
+
return { binding: session.binding, streamId: first.value.streamId, state: first.value.payload, capabilities: session.capabilities };
|
|
100
|
+
}
|
|
101
|
+
if (!params || typeof params !== "object" || !("sessionId" in params) || typeof params.sessionId !== "string")
|
|
102
|
+
throw new HarnessSdkError("INVALID_PARAMS");
|
|
103
|
+
if (method === "x-anureo/events/read") {
|
|
104
|
+
const p = params, log = logs.get(p.sessionId) ?? [];
|
|
105
|
+
const events = log.filter((e) => e.streamId === p.streamId && e.seq > p.afterSeq && e.seq <= p.throughSeq);
|
|
106
|
+
if (events[0]?.seq !== p.afterSeq + 1 && p.afterSeq < p.throughSeq)
|
|
107
|
+
throw new HarnessSdkError("SOURCE_STREAM_UNAVAILABLE");
|
|
108
|
+
return { events };
|
|
109
|
+
}
|
|
110
|
+
const session = sessions.get(params.sessionId);
|
|
111
|
+
if (!session)
|
|
112
|
+
throw new HarnessSdkError("SESSION_NOT_FOUND");
|
|
113
|
+
switch (method) {
|
|
114
|
+
case "turn/start":
|
|
115
|
+
assertRequest(method, params);
|
|
116
|
+
return session.startTurn(params);
|
|
117
|
+
case "turn/interrupt":
|
|
118
|
+
assertRequest(method, params);
|
|
119
|
+
return session.interrupt(params);
|
|
120
|
+
case "interaction/respond":
|
|
121
|
+
assertRequest(method, params);
|
|
122
|
+
return session.respond(params);
|
|
123
|
+
case "interaction/cancel":
|
|
124
|
+
assertRequest(method, params);
|
|
125
|
+
return session.cancelInteraction(params);
|
|
126
|
+
case "session/close":
|
|
127
|
+
assertRequest(method, params);
|
|
128
|
+
await session.close();
|
|
129
|
+
sessions.delete(params.sessionId);
|
|
130
|
+
return { closed: true };
|
|
131
|
+
default:
|
|
132
|
+
throw new HarnessSdkError("CAPABILITY_UNSUPPORTED");
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
return { async receive(frame) {
|
|
136
|
+
let message;
|
|
137
|
+
try {
|
|
138
|
+
message = JSON.parse(frame);
|
|
139
|
+
} catch {
|
|
140
|
+
await send(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (message.method === "initialized" && message.id === undefined)
|
|
144
|
+
return;
|
|
145
|
+
if (message.jsonrpc !== "2.0" || typeof message.method !== "string" || message.id === undefined) {
|
|
146
|
+
await send(JSON.stringify({ jsonrpc: "2.0", id: message.id ?? null, error: { code: -32600, message: "Invalid request" } }));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const result = await invoke(message.method, message.params);
|
|
151
|
+
await send(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));
|
|
152
|
+
} catch (cause) {
|
|
153
|
+
const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "HARNESS_ERROR";
|
|
154
|
+
await send(JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32070, message: code, data: { code, retryable: false, outcomeUnknown: false } } }));
|
|
155
|
+
}
|
|
156
|
+
}, close: () => runtime.dispose() };
|
|
157
|
+
}
|
|
158
|
+
if (__require.main == __require.module) {
|
|
159
|
+
const harness = createReferenceHarness((message) => {
|
|
160
|
+
process.stdout.write(message + `
|
|
161
|
+
`);
|
|
162
|
+
});
|
|
163
|
+
const input = createInterface({ input: process.stdin });
|
|
164
|
+
for await (const line of input) {
|
|
165
|
+
harness.receive(line);
|
|
166
|
+
}
|
|
167
|
+
await harness.close();
|
|
168
|
+
}
|
|
169
|
+
export {
|
|
170
|
+
createReferenceHarness
|
|
171
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anureo/adapter-ahp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Anureo SDK adapter for external AHP harnesses over stdio or WebSocket",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"anureo",
|
|
8
|
+
"ahp",
|
|
9
|
+
"harness",
|
|
10
|
+
"agent",
|
|
11
|
+
"sdk",
|
|
12
|
+
"client"
|
|
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/ahp"
|
|
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/protocol": "0.2.0",
|
|
44
|
+
"@anureo/sdk": "0.2.0"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=22"
|
|
48
|
+
}
|
|
49
|
+
}
|