@anureo/adapter-ahp 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,70 @@
1
- # Temporary Holding Version
1
+ # @anureo/adapter-ahp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Adapter connecting the Anureo SDK to **external harnesses that implement AHP** over stdio or WebSocket. These harnesses can themselves be built with the Anureo SDK.
4
+
5
+ > Part of the [Anureo SDK workspace](../../../README.md). Install with `npm install @anureo/adapter-ahp`.
6
+
7
+ ## Usage
8
+
9
+ The examples below use the revised workspace API, which differs from the published
10
+ 0.2.0 API. The protocol major remains 1, but external peers must upgrade together
11
+ and reject mismatched lifecycle capabilities during initialization.
12
+
13
+ ```typescript
14
+ import { createClient } from '@anureo/sdk'
15
+ import { createAhpAdapter } from '@anureo/adapter-ahp'
16
+
17
+ const client = await createClient({
18
+ adapter: createAhpAdapter({ command: 'my-harness', args: ['serve'] }),
19
+ identity: { adapterId: 'ahp', runtimeConfigId: 'local' },
20
+ })
21
+ try {
22
+ const session = await client.sessions.create({ cwd: process.cwd() })
23
+ const turn = await session.submit({ input: 'Inspect the workspace.' })
24
+ console.log(await turn.result())
25
+ await session.close()
26
+ } finally {
27
+ await client.dispose()
28
+ }
29
+ ```
30
+
31
+ A standalone revised-v1 reference harness lives in [examples/reference.ts](examples/reference.ts); its stdio and WebSocket paths are exercised by the adapter tests.
32
+
33
+ ## Behavior the adapter enforces
34
+
35
+ - **Version handshake.** `initialize` negotiates major 1 and requires `protocolContract: "native-lifecycle"` in both directions; 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 `interaction/respond` / `interaction/cancel`; 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/adapter/ahp
55
+ bun run typecheck
56
+ bun test tests
57
+ ```
58
+
59
+ ## Documentation
60
+
61
+ - [AHP v1 protocol](../../../spec/ahp-v1.md) — the wire contract
62
+ - [Architecture](../../../docs/architecture.md)
63
+
64
+ ## AHP v1 lifecycle revision
65
+
66
+ The lifecycle design updates AHP v1 and package root entries in place.
67
+ Root migration and local validation are complete: the root implementation and tests
68
+ use the revised lifecycle, and parallel versioned entries have been removed.
69
+ Local conformance and clean-install checks have passed.
70
+ See the [design and implementation plan](../../../docs/native-harness-lifecycle.md).
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Create a scripted AHP peer for stdio or an embedding transport. The supplied send callback
3
+ * receives JSON-RPC frames without line delimiters. receive permits concurrent requests and awaits
4
+ * its reply write. Execution events can continue afterward. Stop admitting requests before close
5
+ * and await outstanding opens if their clients also need to be included in disposal.
6
+ */
7
+ export declare function createReferenceHarness(send: (message: string) => void | Promise<void>): {
8
+ /** Accept one frame and await its reply write. Independent callers can receive concurrently. */
9
+ receive: (frame: string) => Promise<void>;
10
+ /** Attempt all owned client disposals before rejecting the first release failure. */
11
+ close(): Promise<void>;
12
+ };
@@ -0,0 +1,242 @@
1
+ /** A standalone AHP v1 peer backed by a scripted native execution. No model calls. */
2
+ import { createInterface } from 'node:readline';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { createClient, HarnessSdkError } from '@anureo/sdk';
5
+ import { AHP_PROTOCOL_CONTRACT, assertRequest, isAhpMethod, negotiateVersion, supportsExtension } from '@anureo/protocol';
6
+ /**
7
+ * Create a scripted AHP peer for stdio or an embedding transport. The supplied send callback
8
+ * receives JSON-RPC frames without line delimiters. receive permits concurrent requests and awaits
9
+ * its reply write. Execution events can continue afterward. Stop admitting requests before close
10
+ * and await outstanding opens if their clients also need to be included in disposal.
11
+ */
12
+ export function createReferenceHarness(send) {
13
+ const adapter = new ReferenceAdapter();
14
+ // The harness retains and disposes every client when it closes.
15
+ const ownedClients = new Set();
16
+ const openSessions = new Map();
17
+ // Replay logs outlive session closure and remain for the harness lifetime.
18
+ const replayLogs = new Map();
19
+ let initialized = false;
20
+ /** openSession and publishSessionEvents await the send. Record the source sequence first so it is available to concurrent replay. */
21
+ const publish = async (event) => {
22
+ const source = openSessions.get(event.sessionId);
23
+ if (!source)
24
+ return;
25
+ event = { ...event, streamId: source.streamId, seq: ++source.lastPublishedSeq };
26
+ if (event.type === 'session/metadata')
27
+ event = { ...event, type: 'extension', payload: { name: 'x-anureo/session-metadata', version: '1', data: event.payload } };
28
+ const log = replayLogs.get(event.sessionId) ?? [];
29
+ log.push(event);
30
+ if (log.length > 2048)
31
+ log.shift();
32
+ replayLogs.set(event.sessionId, log);
33
+ await send(JSON.stringify({ jsonrpc: '2.0', method: event.type, params: event }));
34
+ };
35
+ /** Drain events in order; a read/send rejection stops forwarding and is suppressed by openSession. */
36
+ const publishSessionEvents = async (reader) => {
37
+ for (;;) {
38
+ const next = await reader.next();
39
+ if (next.done)
40
+ return;
41
+ await publish(next.value);
42
+ }
43
+ };
44
+ /** Own the client before opening; publish initial state before starting the ongoing event drain. */
45
+ const openSession = async (params) => {
46
+ if (openSessions.has(params.binding.sessionId))
47
+ throw new HarnessSdkError('SESSION_ALREADY_OPEN');
48
+ const client = await createClient({ adapter, identity: params.binding, interactions: { approval: undefined } });
49
+ ownedClients.add(client);
50
+ const session = await client.openSession(params);
51
+ const streamId = randomUUID();
52
+ const state = session.snapshot;
53
+ openSessions.set(session.id, { session, streamId, lastPublishedSeq: 0 });
54
+ const reader = session.events()[Symbol.asyncIterator]();
55
+ await publish({ sessionId: session.id, streamId, seq: 1, timestamp: new Date().toISOString(), type: 'session/state', payload: state });
56
+ void publishSessionEvents(reader).catch(() => { });
57
+ return { binding: session.binding, streamId, state, capabilities: session.capabilities };
58
+ };
59
+ /** invoke returns a complete replay range or reports SOURCE_STREAM_UNAVAILABLE, including when old entries were evicted. */
60
+ const readEvents = ({ sessionId, streamId, afterSeq, throughSeq }) => {
61
+ const events = (replayLogs.get(sessionId) ?? []).filter(event => event.streamId === streamId && event.seq > afterSeq && event.seq <= throughSeq);
62
+ if (events.length !== throughSeq - afterSeq)
63
+ throw new HarnessSdkError('SOURCE_STREAM_UNAVAILABLE');
64
+ return { events };
65
+ };
66
+ /** Enforce handshake/session admission and return SDK results; receive converts failures to RPC errors. */
67
+ const invoke = async (method, params) => {
68
+ if (method === 'initialize') {
69
+ assertRequest(method, params);
70
+ const result = await adapter.initialize(params);
71
+ initialized = true;
72
+ return result;
73
+ }
74
+ if (!initialized)
75
+ throw new HarnessSdkError('NOT_INITIALIZED');
76
+ if (method === 'session/open') {
77
+ assertRequest(method, params);
78
+ return openSession(params);
79
+ }
80
+ if (!params || typeof params !== 'object' || !('sessionId' in params) || typeof params.sessionId !== 'string')
81
+ throw new HarnessSdkError('INVALID_PARAMS');
82
+ if (method === 'x-anureo/events/read') {
83
+ return readEvents(params);
84
+ }
85
+ const source = openSessions.get(params.sessionId);
86
+ if (!source)
87
+ throw new HarnessSdkError('SESSION_NOT_FOUND');
88
+ if (!isAhpMethod(method) || method === 'initialize' || method === 'session/open')
89
+ throw new HarnessSdkError('CAPABILITY_UNSUPPORTED');
90
+ assertRequest(method, params);
91
+ const result = await source.session.request(method, params);
92
+ if (method === 'session/close')
93
+ openSessions.delete(params.sessionId);
94
+ return result;
95
+ };
96
+ return {
97
+ /** Accept one frame and await its reply write. Independent callers can receive concurrently. */
98
+ receive: createReceiver(send, invoke),
99
+ /** Attempt all owned client disposals before rejecting the first release failure. */
100
+ async close() {
101
+ const outcomes = await Promise.allSettled([...ownedClients].map(client => client.dispose()));
102
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected');
103
+ if (failed)
104
+ throw failed.reason;
105
+ },
106
+ };
107
+ }
108
+ /**
109
+ * Decode one JSON-RPC frame per call and invoke the harness dispatcher. Ignore initialized and
110
+ * send parse/envelope errors directly. Dispatch or result-write failures attempt an RPC error reply.
111
+ * An unusable envelope or failed error write can reject the returned receive promise.
112
+ */
113
+ function createReceiver(send, invoke) {
114
+ return async function receive(frame) {
115
+ let message;
116
+ try {
117
+ message = JSON.parse(frame);
118
+ }
119
+ catch {
120
+ await sendRpcError(send, null, { code: -32700, message: 'Parse error' });
121
+ return;
122
+ }
123
+ if (message.method === 'initialized' && message.id === undefined)
124
+ return;
125
+ if (message.jsonrpc !== '2.0' || typeof message.method !== 'string' || message.id === undefined) {
126
+ await sendRpcError(send, message.id ?? null, { code: -32600, message: 'Invalid request' });
127
+ return;
128
+ }
129
+ try {
130
+ const id = message.id;
131
+ const result = await invoke(message.method, message.params);
132
+ await send(JSON.stringify({ jsonrpc: '2.0', id, result }));
133
+ }
134
+ catch (cause) {
135
+ const code = cause && typeof cause === 'object' && 'code' in cause
136
+ ? String(cause.code)
137
+ : 'HARNESS_ERROR';
138
+ await sendRpcError(send, message.id, {
139
+ code: -32070,
140
+ message: code,
141
+ data: { code, retryable: false, outcomeUnknown: false },
142
+ });
143
+ }
144
+ };
145
+ }
146
+ /** Write the correlated error frame for receive and let serialization or transport failure escape. */
147
+ function sendRpcError(send, id, error) {
148
+ return send(JSON.stringify({ jsonrpc: '2.0', id, error }));
149
+ }
150
+ const capabilities = {
151
+ input: { delivery: ['native'], interrupt: { targets: ['turn'], reportsPendingInputs: false } },
152
+ turn: { inputModalities: ['text'] }, interactions: ['approval'],
153
+ extensions: [{ name: 'x-anureo/event-replay', version: '1' }, { name: 'x-anureo/session-metadata', version: '1' }],
154
+ };
155
+ /** Scripted native backend used by the reference peer; each open owns its active execution slot. */
156
+ class ReferenceAdapter {
157
+ /**
158
+ * The harness dispatcher and SDK wrapper both negotiate this scripted backend. Reject invalid
159
+ * parameters or versions and retain title support for later opens once a caller advertises it.
160
+ */
161
+ async initialize(params) {
162
+ assertRequest('initialize', params);
163
+ negotiateVersion(params.protocolVersions);
164
+ this.metadataEnabled ||= supportsExtension(params.clientCapabilities ?? {}, 'x-anureo/session-metadata', '1');
165
+ return { protocolVersion: 1, protocolContract: AHP_PROTOCOL_CONTRACT, runtime: { name: 'reference', version: '1', adapter: 'reference/1' }, capabilities };
166
+ }
167
+ /** OutputSession.open adopts this backend, which owns one scripted execution and publishes through the supplied sink. */
168
+ async openSession(params, sink) {
169
+ let active;
170
+ let closed = false;
171
+ const binding = { ...params.binding, nativeRef: { provider: 'reference', value: params.binding.sessionId } };
172
+ const metadataEnabled = this.metadataEnabled;
173
+ /** Submit starts this in the background. Recheck active ownership after approval so interrupted work skips output. */
174
+ const runExecution = async (turnId, text) => {
175
+ if (text === '/approval')
176
+ await sink.requestInteraction({ kind: 'approval', interactionId: `approval:${turnId}`, turnId, options: [{ id: 'allow', label: 'Allow once', semantic: 'allowOnce' }, { id: 'deny', label: 'Deny', semantic: 'deny' }] }, async () => { });
177
+ if (closed || active !== turnId)
178
+ return;
179
+ await sink.emit({ type: 'item/started', payload: { item: { id: 'message', type: 'agentMessage', text: '' } } }, { turnId });
180
+ await sink.emit({ type: 'item/completed', payload: { item: { id: 'message', type: 'agentMessage', text, phase: 'final' } } }, { turnId });
181
+ active = undefined;
182
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } });
183
+ };
184
+ /** Convert background failure into a terminal only while this execution still owns the slot. */
185
+ const handleExecutionFailure = async (turnId) => {
186
+ if (!closed && active === turnId) {
187
+ active = undefined;
188
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: { code: 'SCRIPTED_EXECUTION_FAILED', message: 'Scripted execution failed', retryable: false, outcomeUnknown: false } } });
189
+ }
190
+ };
191
+ return {
192
+ binding, capabilities,
193
+ /**
194
+ * OutputSession dispatches one scripted operation here. Submit returns a dispatch receipt,
195
+ * interrupt waits for the active turn's terminal, and close confirms observation.
196
+ * Busy, mismatched and unsupported requests reject.
197
+ */
198
+ async execute(method, value) {
199
+ if (method === 'session/close') {
200
+ return { closed: true, observationClosed: true, executionStopped: 'unconfirmed' };
201
+ }
202
+ if (method === 'turn/interrupt') {
203
+ const { turnId } = value;
204
+ if (active !== turnId)
205
+ throw new HarnessSdkError('TURN_MISMATCH');
206
+ active = undefined;
207
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'interrupted' } });
208
+ return { accepted: true, turnId };
209
+ }
210
+ if (method !== 'input/submit')
211
+ throw new HarnessSdkError('CAPABILITY_UNSUPPORTED');
212
+ if (active)
213
+ throw new HarnessSdkError('SESSION_BUSY', 'The scripted backend admits one execution at a time');
214
+ const input = value;
215
+ const turnId = randomUUID();
216
+ active = turnId;
217
+ await sink.emit({ type: 'turn/started', payload: { turnId } });
218
+ await sink.bindSubmission(input.submissionId, turnId);
219
+ const text = input.input.filter(block => block.type === 'text').map(block => block.text).join('\n');
220
+ if (metadataEnabled && text.startsWith('/title ')) {
221
+ await sink.emit({ type: 'session/metadata', payload: { title: text.slice(7) || null } });
222
+ }
223
+ if (text !== '/wait')
224
+ void runExecution(turnId, text).catch(() => handleExecutionFailure(turnId));
225
+ return { submissionId: input.submissionId, disposition: 'dispatched' };
226
+ },
227
+ /** Mark closed so executions waiting for approval skip output; the SDK owns observation teardown. */
228
+ async dispose() { closed = true; },
229
+ };
230
+ }
231
+ /** Session handles own all scripted state, so client disposal has no shared native resource to release. */
232
+ async dispose() { }
233
+ /** Enable metadata cumulatively during negotiation. Each open snapshots the current flag. */
234
+ metadataEnabled = false;
235
+ }
236
+ if (import.meta.main) {
237
+ const harness = createReferenceHarness(message => { process.stdout.write(message + '\n'); });
238
+ const input = createInterface({ input: process.stdin });
239
+ for await (const line of input)
240
+ void harness.receive(line);
241
+ await harness.close();
242
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@anureo/adapter-ahp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Anureo SDK adapter for external AHP harnesses over stdio or WebSocket",
4
+ "version": "0.3.0",
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/adapter/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": "./src/index.d.ts",
30
+ "import": "./src/index.js",
31
+ "default": "./src/index.js"
32
+ }
33
+ },
34
+ "dependencies": {
35
+ "@anureo/protocol": "0.3.0",
36
+ "@anureo/sdk": "0.3.0"
37
+ },
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "files": [
42
+ "src",
43
+ "bin",
44
+ "schema",
45
+ "protocol",
46
+ "examples"
47
+ ]
48
+ }