@harness-control/sdk 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
+ https://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 qazisaad
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
+ https://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 ADDED
@@ -0,0 +1,45 @@
1
+ # @harness-control/sdk
2
+
3
+ App-side APIs for an HCP runner. Requires Node.js 22+ for the examples; the SDK itself has no Node transport or provider dependency.
4
+
5
+ ```sh
6
+ npm install @harness-control/sdk @harness-control/protocol
7
+ ```
8
+
9
+ The local machine runs `@harness-control/runner`. The application accepts its outbound WebSocket and owns authentication, pairing approval, authorization, and durable storage. HCP is a protocol, not a shared hosted service.
10
+
11
+ ```ts
12
+ import { HcpHostConnection, createCommand } from "@harness-control/sdk";
13
+
14
+ // socket is already authenticated and bound to your authorized machine.
15
+ const host = new HcpHostConnection({ send: message => socket.send(JSON.stringify(message)) });
16
+ socket.on("message", raw => {
17
+ const received = host.receive(raw.toString());
18
+ if (received.message.type === "host.hello") {
19
+ // Check runner_id and host_id against the authenticated identity first.
20
+ host.accept({ protocol_version: "hcp.v0", heartbeat_interval_seconds: 30 });
21
+ }
22
+ // Persist messages and inspect event/snapshot reduction results here.
23
+ // Consume terminal events; an ACK does not mean the turn has finished.
24
+ });
25
+ socket.on("close", () => host.disconnect());
26
+ socket.on("error", () => host.disconnect());
27
+
28
+ // After acceptance and capability discovery:
29
+ const command = createCommand({
30
+ type: "harness.turn.send",
31
+ payload: { session_id: "session-1", turn_id: "turn-1", input: "Explain this repository" },
32
+ }, { id: "your-stable-command-id" });
33
+ // Persist command before sending when recovery across app restarts is required.
34
+ const acknowledgement = await host.send(command);
35
+ ```
36
+
37
+ `startSession`, `sendTurn`, `cancelTurn`, `stopSession`, `requestSnapshot`, `respondToApproval`, `respondToInput`, `detachTools`, `runLocalAction`, and `manageWorkspaces` provide typed convenience calls. Each accepts a protocol payload, optional command identity/timestamp/metadata, and optional wait timeout/AbortSignal. MCP attachments are supplied in `startSession`. Model discovery comes from `host.capabilities.updated`; workspace operations are `list`, `add`, `rename`, and `remove`.
38
+
39
+ Session commands resolve to an ACK. Snapshot, workspace, and local-action commands resolve to their matching result. Local/workspace errors are typed result messages; NACKs throw `HcpCommandRejectedError`. Disconnect, timeout, or aborting a wait throws `HcpOutcomeUnknownError` and never retries or cancels remote work. Send an explicit cancel command when appropriate.
40
+
41
+ Use a new `HcpHostConnection` for each physical socket. Pass only your durably committed resume cursor to `accept`. `events` uses the canonical protocol reducer; gap/conflict results and `host.replay.unavailable` require application recovery. Retaining an event in memory does not acknowledge durable consumption. The app owns event retention and can supply a restored reducer to the constructor.
42
+
43
+ For transactional or non-WebSocket code, import `createCommand` and `parseCommand` without constructing a connection. This is the API used by P2A's Convex integration.
44
+
45
+ See [the public package contract](https://github.com/qazisaad/harness-control-protocol/blob/main/docs/public-packages.md), [pairing](https://github.com/qazisaad/harness-control-protocol/blob/main/docs/pairing.md), and [the standalone example](https://github.com/qazisaad/harness-control-protocol/blob/main/examples/public-sdk.mjs). Provider support is capability-dependent; unsupported policies are never widened automatically.
@@ -0,0 +1,21 @@
1
+ import { type HcpMessage, type HcpMetadata } from "@harness-control/protocol";
2
+ declare const commandTypes: readonly ["harness.session.start", "harness.session.snapshot.request", "harness.turn.send", "harness.turn.cancel", "harness.session.stop", "harness.approval.respond", "harness.input.respond", "tool_servers.detach", "local.action.request", "host.workspaces.request"];
3
+ export type HcpCommandType = typeof commandTypes[number];
4
+ export type HcpCommand = Extract<HcpMessage, {
5
+ type: HcpCommandType;
6
+ }>;
7
+ export type HcpCommandInput = HcpCommand extends infer C ? C extends HcpCommand ? Pick<C, "type" | "payload"> : never : never;
8
+ export type CommandOptions = {
9
+ id?: string;
10
+ sentAt?: string;
11
+ metadata?: HcpMetadata;
12
+ };
13
+ export declare function parseCommand(input: unknown): HcpCommand;
14
+ export declare function createCommand<C extends HcpCommandInput>(input: C, options?: CommandOptions): Extract<HcpCommand, {
15
+ type: C["type"];
16
+ }>;
17
+ export type HcpCommandResponse<T extends HcpCommandType> = Extract<HcpMessage, {
18
+ type: T extends "host.workspaces.request" ? "host.workspaces.result" : T extends "harness.session.snapshot.request" ? "harness.session.snapshot" : T extends "local.action.request" ? "local.action.response" | "local.action.error" : "hcp.command.ack";
19
+ }>;
20
+ export {};
21
+ //# sourceMappingURL=commands.d.ts.map
@@ -0,0 +1,21 @@
1
+ import { HCP_VERSION, parseHcpMessage } from "@harness-control/protocol";
2
+ const commandTypes = [
3
+ "harness.session.start", "harness.session.snapshot.request", "harness.turn.send",
4
+ "harness.turn.cancel", "harness.session.stop", "harness.approval.respond",
5
+ "harness.input.respond", "tool_servers.detach", "local.action.request", "host.workspaces.request",
6
+ ];
7
+ export function parseCommand(input) {
8
+ const message = parseHcpMessage(input);
9
+ if (!commandTypes.includes(message.type)) {
10
+ throw new Error(`Not an app-to-runner command: ${message.type}`);
11
+ }
12
+ return message;
13
+ }
14
+ export function createCommand(input, options = {}) {
15
+ return parseCommand({
16
+ ...input, id: options.id ?? crypto.randomUUID(), version: HCP_VERSION,
17
+ sent_at: options.sentAt ?? new Date().toISOString(),
18
+ ...(options.metadata === undefined ? {} : { metadata: options.metadata }),
19
+ });
20
+ }
21
+ //# sourceMappingURL=commands.js.map
@@ -0,0 +1,77 @@
1
+ import { HcpSessionEventReducer, type HcpMessage, type HcpHostAcceptedPayload, type HcpEventApplyResult, type HcpSnapshotApplyResult, type HcpCommandNackPayload } from "@harness-control/protocol";
2
+ import { type HcpCommand, type HcpCommandType, type HcpCommandResponse, type CommandOptions } from "./commands.js";
3
+ export type ReceiveResult = {
4
+ message: Extract<HcpMessage, {
5
+ type: "harness.event";
6
+ }>;
7
+ reduction: HcpEventApplyResult;
8
+ } | {
9
+ message: Extract<HcpMessage, {
10
+ type: "harness.session.snapshot";
11
+ }>;
12
+ reduction: HcpSnapshotApplyResult;
13
+ } | {
14
+ message: Exclude<HcpMessage, {
15
+ type: "harness.event" | "harness.session.snapshot";
16
+ }>;
17
+ };
18
+ export type WaitOptions = {
19
+ timeoutMs?: number;
20
+ signal?: AbortSignal;
21
+ };
22
+ export declare class HcpOutcomeUnknownError extends Error {
23
+ readonly command: HcpCommand;
24
+ constructor(command: HcpCommand, reason: string, options?: ErrorOptions);
25
+ }
26
+ export declare class HcpCommandRejectedError extends Error {
27
+ readonly rejection: HcpCommandNackPayload;
28
+ constructor(rejection: HcpCommandNackPayload);
29
+ }
30
+ /** One authenticated socket. The application owns authentication and durable replay cursors. */
31
+ export declare class HcpHostConnection {
32
+ #private;
33
+ private readonly transport;
34
+ readonly events: HcpSessionEventReducer;
35
+ constructor(transport: {
36
+ send: (message: HcpMessage) => void;
37
+ }, options?: {
38
+ events?: HcpSessionEventReducer;
39
+ });
40
+ accept(payload: HcpHostAcceptedPayload): void;
41
+ receive(input: unknown): ReceiveResult;
42
+ send<C extends HcpCommand>(input: C, options?: WaitOptions): Promise<HcpCommandResponse<C["type"]>>;
43
+ disconnect(): void;
44
+ startSession(payload: Payload<"harness.session.start">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpCommandAckMessage>;
45
+ sendTurn(payload: Payload<"harness.turn.send">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpCommandAckMessage>;
46
+ cancelTurn(payload: Payload<"harness.turn.cancel">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpCommandAckMessage>;
47
+ stopSession(payload: Payload<"harness.session.stop">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpCommandAckMessage>;
48
+ requestSnapshot(payload: Payload<"harness.session.snapshot.request">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpSessionSnapshotMessage>;
49
+ respondToApproval(payload: Payload<"harness.approval.respond">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpCommandAckMessage>;
50
+ respondToInput(payload: Payload<"harness.input.respond">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpCommandAckMessage>;
51
+ detachTools(payload: Payload<"tool_servers.detach">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpCommandAckMessage>;
52
+ runLocalAction(payload: Payload<"local.action.request">, command?: CommandOptions, wait?: WaitOptions): Promise<HcpCommandResponse<"local.action.request">>;
53
+ manageWorkspaces(payload: Payload<"host.workspaces.request">, command?: CommandOptions, wait?: WaitOptions): Promise<import("@harness-control/protocol").HcpEnvelope<"host.workspaces.result", {
54
+ request_id: string;
55
+ outcome: {
56
+ kind: "success";
57
+ } | {
58
+ kind: "error";
59
+ message: string;
60
+ };
61
+ management: {
62
+ revision: string;
63
+ allowed_roots: string[];
64
+ };
65
+ workspaces: {
66
+ id: string;
67
+ path: string;
68
+ git_remote?: string | undefined;
69
+ display_name?: string | undefined;
70
+ }[];
71
+ }>>;
72
+ }
73
+ type Payload<T extends HcpCommandType> = Extract<HcpCommand, {
74
+ type: T;
75
+ }>["payload"];
76
+ export {};
77
+ //# sourceMappingURL=connection.d.ts.map
@@ -0,0 +1,180 @@
1
+ import { createHcpEnvelope, parseHcpMessage, HcpSessionEventReducer, } from "@harness-control/protocol";
2
+ import { createCommand, parseCommand } from "./commands.js";
3
+ export class HcpOutcomeUnknownError extends Error {
4
+ command;
5
+ constructor(command, reason, options) {
6
+ super(`${reason} Outcome of ${command.id} is unknown; reconcile before retrying.`, options);
7
+ this.command = command;
8
+ this.name = "HcpOutcomeUnknownError";
9
+ }
10
+ }
11
+ export class HcpCommandRejectedError extends Error {
12
+ rejection;
13
+ constructor(rejection) {
14
+ super(rejection.error.message);
15
+ this.rejection = rejection;
16
+ this.name = "HcpCommandRejectedError";
17
+ }
18
+ }
19
+ /** One authenticated socket. The application owns authentication and durable replay cursors. */
20
+ export class HcpHostConnection {
21
+ transport;
22
+ events;
23
+ #pending = new Map();
24
+ #state = { kind: "awaiting_hello" };
25
+ constructor(transport, options = {}) {
26
+ this.transport = transport;
27
+ this.events = options.events ?? new HcpSessionEventReducer();
28
+ }
29
+ accept(payload) {
30
+ if (this.#state.kind !== "awaiting_accept")
31
+ throw new Error("Receive and authorize host.hello before accepting.");
32
+ const message = parseHcpMessage(createHcpEnvelope("host.accepted", payload));
33
+ this.#state = { kind: "accepted", hello: this.#state.hello };
34
+ try {
35
+ this.transport.send(message);
36
+ }
37
+ catch (error) {
38
+ this.disconnect();
39
+ throw error;
40
+ }
41
+ }
42
+ receive(input) {
43
+ if (this.#state.kind === "closed")
44
+ throw new Error("Connection is closed.");
45
+ const message = parseHcpMessage(typeof input === "string" ? JSON.parse(input) : input);
46
+ if (message.type === "host.hello") {
47
+ if (this.#state.kind !== "awaiting_hello")
48
+ throw new Error("Duplicate host.hello on this connection.");
49
+ this.#state = { kind: "awaiting_accept", hello: message.payload };
50
+ return { message };
51
+ }
52
+ if (this.#state.kind !== "accepted")
53
+ throw new Error("Runner has not been accepted.");
54
+ switch (message.type) {
55
+ case "host.heartbeat":
56
+ if (message.payload.host_id !== this.#state.hello.host_id)
57
+ throw new Error("Heartbeat host identity mismatch.");
58
+ return { message };
59
+ case "host.capabilities.updated":
60
+ case "host.replay.unavailable":
61
+ return { message };
62
+ case "harness.event":
63
+ return { message, reduction: this.events.applyEvent(message.payload) };
64
+ case "harness.session.snapshot": {
65
+ const reduction = this.events.applySnapshot(message.payload);
66
+ this.#settle(message);
67
+ return { message, reduction };
68
+ }
69
+ case "hcp.command.ack":
70
+ case "hcp.command.nack":
71
+ case "host.workspaces.result":
72
+ case "local.action.response":
73
+ case "local.action.error":
74
+ this.#settle(message);
75
+ return { message };
76
+ default: throw new Error(`Not a runner-to-app message: ${message.type}`);
77
+ }
78
+ }
79
+ send(input, options = {}) {
80
+ const command = parseCommand(input);
81
+ if (this.#state.kind !== "accepted")
82
+ throw new Error("Runner is not connected and accepted.");
83
+ options.signal?.throwIfAborted();
84
+ const timeoutMs = options.timeoutMs ?? 30_000;
85
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647)
86
+ throw new Error("Invalid command timeout.");
87
+ if (this.#pending.size >= 256)
88
+ throw new Error("Too many pending HCP requests.");
89
+ if (this.#pending.has(command.id))
90
+ throw new Error("Command is already pending.");
91
+ if (command.type === "local.action.request" && [...this.#pending.values()].some(p => p.command.type === "local.action.request" && p.command.payload.request_id === command.payload.request_id)) {
92
+ throw new Error("Local action request is already pending.");
93
+ }
94
+ return new Promise((resolve, reject) => {
95
+ const fail = (reason, cause) => {
96
+ this.#pending.get(command.id)?.dispose();
97
+ this.#pending.delete(command.id);
98
+ reject(new HcpOutcomeUnknownError(command, reason, { cause }));
99
+ };
100
+ const timer = setTimeout(() => fail("Timed out waiting for the runner."), timeoutMs);
101
+ const abort = () => fail("Stopped waiting for the runner.");
102
+ this.#pending.set(command.id, {
103
+ command, resolve: response => resolve(response), reject,
104
+ dispose: () => { clearTimeout(timer); options.signal?.removeEventListener("abort", abort); },
105
+ });
106
+ options.signal?.addEventListener("abort", abort, { once: true });
107
+ try {
108
+ this.transport.send(command);
109
+ }
110
+ catch (error) {
111
+ fail("Sending to the runner failed.", error);
112
+ }
113
+ });
114
+ }
115
+ disconnect() {
116
+ this.#state = { kind: "closed" };
117
+ for (const pending of this.#pending.values()) {
118
+ pending.dispose();
119
+ pending.reject(new HcpOutcomeUnknownError(pending.command, "Runner disconnected."));
120
+ }
121
+ this.#pending.clear();
122
+ }
123
+ #settle(message) {
124
+ let pending;
125
+ if (message.type === "hcp.command.ack" || message.type === "hcp.command.nack") {
126
+ pending = this.#pending.get(message.payload.command_id);
127
+ if (message.type === "hcp.command.ack" && pending && ["host.workspaces.request", "harness.session.snapshot.request", "local.action.request"].includes(pending.command.type))
128
+ return;
129
+ }
130
+ else if (message.type === "local.action.response" || message.type === "local.action.error") {
131
+ pending = [...this.#pending.values()].find(p => p.command.type === "local.action.request"
132
+ && p.command.payload.request_id === message.payload.request_id && p.command.payload.action === message.payload.action);
133
+ }
134
+ else if (message.type === "host.workspaces.result" || message.type === "harness.session.snapshot") {
135
+ pending = this.#pending.get(message.type === "host.workspaces.result" ? message.payload.request_id : message.payload.command_id);
136
+ if (pending && (message.type === "host.workspaces.result" ? pending.command.type !== "host.workspaces.request"
137
+ : pending.command.type !== "harness.session.snapshot.request" || pending.command.payload.session_id !== message.payload.session_id))
138
+ return;
139
+ }
140
+ if (!pending)
141
+ return;
142
+ pending.dispose();
143
+ this.#pending.delete(pending.command.id);
144
+ if (message.type === "hcp.command.nack")
145
+ pending.reject(new HcpCommandRejectedError(message.payload));
146
+ else
147
+ pending.resolve(message);
148
+ }
149
+ startSession(payload, command, wait) {
150
+ return this.send(createCommand({ type: "harness.session.start", payload }, command), wait);
151
+ }
152
+ sendTurn(payload, command, wait) {
153
+ return this.send(createCommand({ type: "harness.turn.send", payload }, command), wait);
154
+ }
155
+ cancelTurn(payload, command, wait) {
156
+ return this.send(createCommand({ type: "harness.turn.cancel", payload }, command), wait);
157
+ }
158
+ stopSession(payload, command, wait) {
159
+ return this.send(createCommand({ type: "harness.session.stop", payload }, command), wait);
160
+ }
161
+ requestSnapshot(payload, command, wait) {
162
+ return this.send(createCommand({ type: "harness.session.snapshot.request", payload }, command), wait);
163
+ }
164
+ respondToApproval(payload, command, wait) {
165
+ return this.send(createCommand({ type: "harness.approval.respond", payload }, command), wait);
166
+ }
167
+ respondToInput(payload, command, wait) {
168
+ return this.send(createCommand({ type: "harness.input.respond", payload }, command), wait);
169
+ }
170
+ detachTools(payload, command, wait) {
171
+ return this.send(createCommand({ type: "tool_servers.detach", payload }, command), wait);
172
+ }
173
+ runLocalAction(payload, command, wait) {
174
+ return this.send(createCommand({ type: "local.action.request", payload }, command), wait);
175
+ }
176
+ manageWorkspaces(payload, command, wait) {
177
+ return this.send(createCommand({ type: "host.workspaces.request", payload }, command), wait);
178
+ }
179
+ }
180
+ //# sourceMappingURL=connection.js.map
@@ -0,0 +1,4 @@
1
+ export * from "./commands.js";
2
+ export * from "./connection.js";
3
+ export { HcpSessionEventReducer } from "@harness-control/protocol";
4
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./commands.js";
2
+ export * from "./connection.js";
3
+ export { HcpSessionEventReducer } from "@harness-control/protocol";
4
+ //# sourceMappingURL=index.js.map
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@harness-control/sdk",
3
+ "version": "0.1.0",
4
+ "description": "App-side SDK for Harness Control Protocol runners",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "build": "tsc -b",
17
+ "check": "tsc -b --pretty false",
18
+ "test": "node --import tsx --test src/*.test.ts"
19
+ },
20
+ "dependencies": {
21
+ "@harness-control/protocol": "0.1.0"
22
+ },
23
+ "engines": {
24
+ "node": ">=22"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/qazisaad/harness-control-protocol.git",
32
+ "directory": "packages/hcp-sdk"
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "!dist/**/*.test.*",
37
+ "!dist/**/test/**",
38
+ "!dist/**/*.map",
39
+ "README.md",
40
+ "LICENSE"
41
+ ]
42
+ }