@anhlp/alp-client 0.0.0-stage → 0.0.1-beta.10

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.
Files changed (78) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +45 -2
  4. package/dist/acp-probe.d.ts +45 -0
  5. package/dist/acp-probe.js +46 -0
  6. package/dist/antigravity-probe.d.ts +33 -0
  7. package/dist/antigravity-probe.js +101 -0
  8. package/dist/command.d.ts +5 -0
  9. package/dist/command.js +35 -0
  10. package/dist/doctor.d.ts +21 -0
  11. package/dist/doctor.js +850 -0
  12. package/dist/index.d.ts +216 -0
  13. package/dist/index.js +702 -0
  14. package/dist/integration-lock.d.ts +37 -0
  15. package/dist/integration-lock.js +199 -0
  16. package/dist/ipc.d.ts +42 -0
  17. package/dist/ipc.js +69 -0
  18. package/dist/library-test.d.ts +94 -0
  19. package/dist/library-test.js +37 -0
  20. package/dist/mcp-probe.d.ts +24 -0
  21. package/dist/mcp-probe.js +147 -0
  22. package/dist/portable.d.ts +20 -0
  23. package/dist/portable.js +36 -0
  24. package/dist/prompt.d.ts +32 -0
  25. package/dist/prompt.js +59 -0
  26. package/dist/render.d.ts +6 -0
  27. package/dist/render.js +123 -0
  28. package/dist/rpc/client.d.ts +82 -0
  29. package/dist/rpc/client.js +292 -0
  30. package/dist/rpc/errors.d.ts +42 -0
  31. package/dist/rpc/errors.js +34 -0
  32. package/dist/rpc/framing.d.ts +21 -0
  33. package/dist/rpc/framing.js +57 -0
  34. package/dist/rpc/handshake.d.ts +24 -0
  35. package/dist/rpc/handshake.js +10 -0
  36. package/dist/rpc/reconnect.d.ts +97 -0
  37. package/dist/rpc/reconnect.js +227 -0
  38. package/dist/rpc/registry.d.ts +227 -0
  39. package/dist/rpc/registry.js +223 -0
  40. package/dist/rpc/terminal-directory.d.ts +24 -0
  41. package/dist/rpc/terminal-directory.js +70 -0
  42. package/dist/rpc/timers.d.ts +11 -0
  43. package/dist/rpc/timers.js +11 -0
  44. package/dist/service.d.ts +50 -0
  45. package/dist/service.js +145 -0
  46. package/dist/setup.d.ts +8 -0
  47. package/dist/setup.js +273 -0
  48. package/dist/supervise.d.ts +14 -0
  49. package/dist/supervise.js +91 -0
  50. package/dist/websocket.d.ts +51 -0
  51. package/dist/websocket.js +190 -0
  52. package/package.json +174 -4
  53. package/src/acp-probe.js +53 -0
  54. package/src/antigravity-probe.js +113 -0
  55. package/src/command.js +20 -0
  56. package/src/doctor.d.ts +21 -0
  57. package/src/doctor.js +912 -0
  58. package/src/index.js +813 -0
  59. package/src/integration-lock.js +203 -0
  60. package/src/ipc.js +92 -0
  61. package/src/library-test.js +41 -0
  62. package/src/mcp-probe.js +118 -0
  63. package/src/portable.js +30 -0
  64. package/src/prompt.js +64 -0
  65. package/src/render.js +139 -0
  66. package/src/rpc/client.js +296 -0
  67. package/src/rpc/errors.js +54 -0
  68. package/src/rpc/framing.js +61 -0
  69. package/src/rpc/handshake.js +21 -0
  70. package/src/rpc/reconnect.js +226 -0
  71. package/src/rpc/registry.js +229 -0
  72. package/src/rpc/terminal-directory.js +61 -0
  73. package/src/rpc/timers.js +16 -0
  74. package/src/service.js +158 -0
  75. package/src/setup.js +316 -0
  76. package/src/supervise.d.ts +14 -0
  77. package/src/supervise.js +97 -0
  78. package/src/websocket.js +259 -0
@@ -0,0 +1,42 @@
1
+ /**
2
+ * True for an AlpClientError, also one thrown by another copy of this module (a bundle may carry
3
+ * two); `reason` narrows the check.
4
+ * @param {unknown} error
5
+ * @param {string} [reason]
6
+ * @returns {error is AlpClientError}
7
+ */
8
+ export function isAlpClientError(error: unknown, reason?: string): error is AlpClientError;
9
+ /**
10
+ * Why a request or a connection ended on the client side.
11
+ * - `closed`: this client was closed locally with close().
12
+ * - `disconnected`: the transport closed or failed. A request that was already sent may or may not
13
+ * have run on the daemon; the client never resends it.
14
+ * - `protocol`: the peer sent something that is not ALP JSON-RPC, so the client closed the connection.
15
+ * - `send_failed`: the transport refused the frame; the request never left this client.
16
+ * - `timeout` / `aborted`: the caller stopped waiting. Only the local wait ends; the daemon is not told.
17
+ * - `overloaded`: too many requests are waiting for an answer already; nothing was sent.
18
+ */
19
+ export const CLIENT_ERROR: Readonly<{
20
+ closed: "closed";
21
+ disconnected: "disconnected";
22
+ protocol: "protocol";
23
+ sendFailed: "send_failed";
24
+ timeout: "timeout";
25
+ aborted: "aborted";
26
+ overloaded: "overloaded";
27
+ }>;
28
+ export class AlpClientError extends Error {
29
+ /**
30
+ * @param {string} message
31
+ * @param {{ reason: 'closed' | 'disconnected' | 'protocol' | 'send_failed' | 'timeout' | 'aborted' | 'overloaded', cause?: unknown, data?: unknown }} details
32
+ */
33
+ constructor(message: string, { reason, cause, data }: {
34
+ reason: "closed" | "disconnected" | "protocol" | "send_failed" | "timeout" | "aborted" | "overloaded";
35
+ cause?: unknown;
36
+ data?: unknown;
37
+ });
38
+ /** @type {'closed' | 'disconnected' | 'protocol' | 'send_failed' | 'timeout' | 'aborted' | 'overloaded'} */
39
+ reason: "closed" | "disconnected" | "protocol" | "send_failed" | "timeout" | "aborted" | "overloaded";
40
+ /** @type {unknown} */
41
+ data: unknown;
42
+ }
@@ -0,0 +1,34 @@
1
+ // packages/client/src/rpc/errors.js
2
+ var BRAND = Symbol.for("@anhlp/alp-client/AlpClientError");
3
+ var CLIENT_ERROR = Object.freeze({
4
+ closed: "closed",
5
+ disconnected: "disconnected",
6
+ protocol: "protocol",
7
+ sendFailed: "send_failed",
8
+ timeout: "timeout",
9
+ aborted: "aborted",
10
+ overloaded: "overloaded"
11
+ });
12
+ var AlpClientError = class extends Error {
13
+ /**
14
+ * @param {string} message
15
+ * @param {{ reason: 'closed' | 'disconnected' | 'protocol' | 'send_failed' | 'timeout' | 'aborted' | 'overloaded', cause?: unknown, data?: unknown }} details
16
+ */
17
+ constructor(message, { reason, cause, data }) {
18
+ super(message, cause === void 0 ? void 0 : { cause });
19
+ this.name = "AlpClientError";
20
+ this.reason = reason;
21
+ this.data = data;
22
+ Object.defineProperty(this, BRAND, { value: true });
23
+ }
24
+ };
25
+ function isAlpClientError(error, reason) {
26
+ return typeof error === "object" && error !== null && /** @type {any} */
27
+ error[BRAND] === true && (reason === void 0 || /** @type {any} */
28
+ error.reason === reason);
29
+ }
30
+ export {
31
+ AlpClientError,
32
+ CLIENT_ERROR,
33
+ isAlpClientError
34
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Newline-delimited JSON framing for stream transports (a Unix socket, a named pipe, a TCP
3
+ * stream). Portable: strings in, strings out; the stream owner decodes bytes to text first.
4
+ * Message transports such as a WebSocket carry whole frames and need none of this.
5
+ */
6
+ /** UTF-8 length of `text` without Buffer or TextEncoder; an unpaired surrogate counts as U+FFFD (3 bytes). @param {string} text */
7
+ export function utf8Length(text: string): number;
8
+ /**
9
+ * Splits decoded text chunks into frames. `push` returns the complete frames in order, blank
10
+ * lines skipped, and throws once a frame (complete or still arriving) exceeds `maxFrame` bytes;
11
+ * the decoder is unusable after that. Each character is measured once, so a frame that arrives
12
+ * in many chunks costs linear time.
13
+ * @param {{ maxFrame: number }} options
14
+ * @returns {{ push(chunk: string): string[], readonly buffered: number }}
15
+ */
16
+ export function createLineDecoder({ maxFrame }: {
17
+ maxFrame: number;
18
+ }): {
19
+ push(chunk: string): string[];
20
+ readonly buffered: number;
21
+ };
@@ -0,0 +1,57 @@
1
+ // packages/client/src/rpc/framing.js
2
+ function utf8Length(text) {
3
+ let bytes = 0;
4
+ for (let index = 0; index < text.length; index++) {
5
+ const code = text.charCodeAt(index);
6
+ if (code < 128) bytes += 1;
7
+ else if (code < 2048) bytes += 2;
8
+ else if (code >= 55296 && code <= 56319 && index + 1 < text.length && (text.charCodeAt(index + 1) & 64512) === 56320) {
9
+ bytes += 4;
10
+ index++;
11
+ } else bytes += 3;
12
+ }
13
+ return bytes;
14
+ }
15
+ function createLineDecoder({ maxFrame }) {
16
+ let parts = [];
17
+ let bytes = 0;
18
+ let failed = false;
19
+ const overflow = () => {
20
+ failed = true;
21
+ parts = [];
22
+ bytes = 0;
23
+ return new RangeError(`Frame exceeds ${maxFrame} bytes`);
24
+ };
25
+ return {
26
+ push(chunk) {
27
+ if (failed) throw new RangeError("Line decoder already failed");
28
+ const frames = [];
29
+ let start = 0;
30
+ for (let index = chunk.indexOf("\n"); index >= 0; index = chunk.indexOf("\n", start)) {
31
+ const piece = chunk.slice(start, index);
32
+ bytes += utf8Length(piece);
33
+ if (bytes > maxFrame) throw overflow();
34
+ parts.push(piece);
35
+ const line = parts.length === 1 ? parts[0] : parts.join("");
36
+ parts = [];
37
+ bytes = 0;
38
+ start = index + 1;
39
+ if (line.trim()) frames.push(line);
40
+ }
41
+ if (start < chunk.length) {
42
+ const rest = chunk.slice(start);
43
+ bytes += utf8Length(rest);
44
+ if (bytes > maxFrame) throw overflow();
45
+ parts.push(rest);
46
+ }
47
+ return frames;
48
+ },
49
+ get buffered() {
50
+ return bytes;
51
+ }
52
+ };
53
+ }
54
+ export {
55
+ createLineDecoder,
56
+ utf8Length
57
+ };
@@ -0,0 +1,24 @@
1
+ /** @typedef {{ name: string, version: string }} ClientInfo */
2
+ /**
3
+ * The version handshake every ALP connection starts with (plans/reference/ALPD.md §3): alpd
4
+ * answers nothing else before it. Shared by the Node `connect` and portable clients, so a change
5
+ * to the handshake (Task 06) lands in one place.
6
+ * @param {{ request(method: string, params?: unknown, options?: import('./client.js').RequestOptions): Promise<any> }} client
7
+ * @param {ClientInfo} [info]
8
+ * @param {import('./client.js').RequestOptions} [options]
9
+ * @param {{ agent?: boolean }} [principal] `agent`: an ALP agent started this process (the Node entry reads ALP_AGENT_SESSION).
10
+ * @returns {Promise<{ protocolVersion: number } & Record<string, unknown>>}
11
+ */
12
+ export function hello(client: {
13
+ request(method: string, params?: unknown, options?: import("./client.js").RequestOptions): Promise<any>;
14
+ }, info?: ClientInfo, options?: import("./client.js").RequestOptions, { agent }?: {
15
+ agent?: boolean;
16
+ }): Promise<{
17
+ protocolVersion: number;
18
+ } & Record<string, unknown>>;
19
+ /** The daemon.hello capability a process an ALP agent started announces. */
20
+ export const AGENT_CAPABILITY: "principal.agent";
21
+ export type ClientInfo = {
22
+ name: string;
23
+ version: string;
24
+ };
@@ -0,0 +1,10 @@
1
+ // packages/client/src/rpc/handshake.js
2
+ import { PROTOCOL_VERSION } from "@anhlp/alp-protocol";
3
+ var AGENT_CAPABILITY = "principal.agent";
4
+ function hello(client, info = { name: "alp", version: "0" }, options, { agent = false } = {}) {
5
+ return client.request("daemon.hello", { protocolVersion: PROTOCOL_VERSION, client: info, ...agent ? { capabilities: [AGENT_CAPABILITY] } : {} }, options);
6
+ }
7
+ export {
8
+ AGENT_CAPABILITY,
9
+ hello
10
+ };
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Keeps an ALP connection up: connects, runs the caller's `onConnect` (handshake, reattach and
3
+ * replay as the protocol defines them), and after a disconnect connects again with exponential
4
+ * backoff until stopped. A connection counts as up only once it has stayed open `stableMs`; one
5
+ * that drops sooner (a gateway closing right after the handshake) counts as a failed attempt, so
6
+ * backoff and `maxAttempts` still apply. It never resends a request: requests in flight when the connection drops
7
+ * reject as `disconnected`, and requests made while it is down reject at once. Whether and how to
8
+ * retry belongs to the caller, who knows which methods are safe to repeat.
9
+ */
10
+ /**
11
+ * @typedef {import('./client.js').AlpTransport} AlpTransport
12
+ * @typedef {import('./client.js').AlpRpcClientOptions} AlpRpcClientOptions
13
+ * @typedef {import('./client.js').RequestOptions} RequestOptions
14
+ * @typedef {import('./client.js').AbortSignalLike} AbortSignalLike
15
+ * @typedef {'connecting' | 'open' | 'waiting' | 'stopped'} ReconnectState
16
+ * @typedef {{ initialMs?: number, maxMs?: number, factor?: number, jitter?: number }} Backoff
17
+ * @typedef {{
18
+ * connect(context: { attempt: number, signal: AbortSignalLike }): Promise<AlpTransport>,
19
+ * onConnect?(client: AlpRpcClient, context: { attempt: number, reconnect: boolean, signal: AbortSignalLike }): unknown,
20
+ * onDisconnect?(error: Error, context: { reconnect: boolean }): void,
21
+ * backoff?: Backoff,
22
+ * maxAttempts?: number,
23
+ * stableMs?: number,
24
+ * shouldRetry?(error: Error): boolean,
25
+ * client?: AlpRpcClientOptions,
26
+ * random?: () => number,
27
+ * }} ReconnectOptions
28
+ * @typedef {{
29
+ * readonly state: ReconnectState,
30
+ * readonly client: AlpRpcClient | undefined,
31
+ * readonly attempt: number,
32
+ * ready(options?: { signal?: AbortSignalLike }): Promise<AlpRpcClient>,
33
+ * request<T = any>(method: string, params?: unknown, options?: RequestOptions): Promise<T>,
34
+ * onEvent(listener: (envelope: any) => void): () => boolean,
35
+ * onNotification(listener: (method: string, params: any) => void): () => boolean,
36
+ * onState(listener: (state: ReconnectState, error?: Error) => void): () => boolean,
37
+ * stop(): void,
38
+ * }} ReconnectingClient
39
+ */
40
+ /** The delay before attempt `attempt` (1-based), with ±jitter. @param {number} attempt @param {Backoff} backoff @param {() => number} random */
41
+ export function backoffDelay(attempt: number, { initialMs, maxMs, factor, jitter }?: Backoff, random?: () => number): number;
42
+ /**
43
+ * Whether a failed connect or onConnect is worth another attempt: everything but alpd refusing the
44
+ * handshake (ERROR.protocol, an unsupported protocol version), which retrying cannot fix.
45
+ * @param {Error} error
46
+ */
47
+ export function retryable(error: Error): boolean;
48
+ /**
49
+ * @param {ReconnectOptions} options
50
+ * @returns {ReconnectingClient}
51
+ */
52
+ export function createReconnectingClient({ connect, onConnect, onDisconnect, backoff, maxAttempts, stableMs, shouldRetry, client: clientOptions, random }: ReconnectOptions): ReconnectingClient;
53
+ export type AlpTransport = import("./client.js").AlpTransport;
54
+ export type AlpRpcClientOptions = import("./client.js").AlpRpcClientOptions;
55
+ export type RequestOptions = import("./client.js").RequestOptions;
56
+ export type AbortSignalLike = import("./client.js").AbortSignalLike;
57
+ export type ReconnectState = "connecting" | "open" | "waiting" | "stopped";
58
+ export type Backoff = {
59
+ initialMs?: number;
60
+ maxMs?: number;
61
+ factor?: number;
62
+ jitter?: number;
63
+ };
64
+ export type ReconnectOptions = {
65
+ connect(context: {
66
+ attempt: number;
67
+ signal: AbortSignalLike;
68
+ }): Promise<AlpTransport>;
69
+ onConnect?(client: AlpRpcClient, context: {
70
+ attempt: number;
71
+ reconnect: boolean;
72
+ signal: AbortSignalLike;
73
+ }): unknown;
74
+ onDisconnect?(error: Error, context: {
75
+ reconnect: boolean;
76
+ }): void;
77
+ backoff?: Backoff;
78
+ maxAttempts?: number;
79
+ stableMs?: number;
80
+ shouldRetry?(error: Error): boolean;
81
+ client?: AlpRpcClientOptions;
82
+ random?: () => number;
83
+ };
84
+ export type ReconnectingClient = {
85
+ readonly state: ReconnectState;
86
+ readonly client: AlpRpcClient | undefined;
87
+ readonly attempt: number;
88
+ ready(options?: {
89
+ signal?: AbortSignalLike;
90
+ }): Promise<AlpRpcClient>;
91
+ request<T = any>(method: string, params?: unknown, options?: RequestOptions): Promise<T>;
92
+ onEvent(listener: (envelope: any) => void): () => boolean;
93
+ onNotification(listener: (method: string, params: any) => void): () => boolean;
94
+ onState(listener: (state: ReconnectState, error?: Error) => void): () => boolean;
95
+ stop(): void;
96
+ };
97
+ import { AlpRpcClient } from './client.js';
@@ -0,0 +1,227 @@
1
+ // packages/client/src/rpc/reconnect.js
2
+ import { AlpRpcError, ERROR } from "@anhlp/alp-protocol";
3
+ import { AlpRpcClient } from "./client.js";
4
+ import { AlpClientError } from "./errors.js";
5
+ function backoffDelay(attempt, { initialMs = 250, maxMs = 1e4, factor = 2, jitter = 0.2 } = {}, random = Math.random) {
6
+ const base = Math.min(maxMs, initialMs * factor ** Math.max(0, attempt - 1));
7
+ return Math.max(0, Math.round(base * (1 + jitter * (2 * random() - 1))));
8
+ }
9
+ function retryable(error) {
10
+ return !(error instanceof AlpRpcError && error.code === ERROR.protocol);
11
+ }
12
+ function controller() {
13
+ if (typeof globalThis.AbortController === "function") {
14
+ const native = new globalThis.AbortController();
15
+ return {
16
+ signal: (
17
+ /** @type {AbortSignalLike} */
18
+ native.signal
19
+ ),
20
+ /** @param {unknown} reason */
21
+ abort: (reason) => native.abort(reason)
22
+ };
23
+ }
24
+ const listeners = /* @__PURE__ */ new Set();
25
+ const signal = {
26
+ aborted: false,
27
+ /** @type {unknown} */
28
+ reason: void 0,
29
+ /** @param {'abort'} _type @param {() => void} listener */
30
+ addEventListener(_type, listener) {
31
+ listeners.add(listener);
32
+ },
33
+ /** @param {'abort'} _type @param {() => void} listener */
34
+ removeEventListener(_type, listener) {
35
+ listeners.delete(listener);
36
+ }
37
+ };
38
+ return {
39
+ signal,
40
+ /** @param {unknown} reason */
41
+ abort(reason) {
42
+ if (signal.aborted) return;
43
+ signal.aborted = true;
44
+ signal.reason = reason;
45
+ for (const listener of [...listeners]) listener();
46
+ listeners.clear();
47
+ }
48
+ };
49
+ }
50
+ function createReconnectingClient({ connect, onConnect, onDisconnect, backoff = {}, maxAttempts = Infinity, stableMs = 5e3, shouldRetry = retryable, client: clientOptions, random = Math.random }) {
51
+ if (typeof connect !== "function") throw new TypeError("createReconnectingClient needs connect()");
52
+ let state = "connecting";
53
+ let current;
54
+ let attempt = 0;
55
+ let connectedBefore = false;
56
+ let timer;
57
+ const run = controller();
58
+ const events = /* @__PURE__ */ new Set();
59
+ const notifications = /* @__PURE__ */ new Set();
60
+ const states = /* @__PURE__ */ new Set();
61
+ const waiters = /* @__PURE__ */ new Set();
62
+ const onListenerError = clientOptions?.onListenerError ?? ((error) => {
63
+ setTimeout(() => {
64
+ throw error;
65
+ }, 0);
66
+ });
67
+ const dispatch = (listener, ...args) => {
68
+ try {
69
+ listener(...args);
70
+ } catch (error) {
71
+ onListenerError(error);
72
+ }
73
+ };
74
+ const enter = (next, error) => {
75
+ state = next;
76
+ for (const listener of [...states]) {
77
+ dispatch(listener, next, error);
78
+ if (state !== next) return;
79
+ }
80
+ if (next === "open" && current) for (const waiter of [...waiters]) {
81
+ waiters.delete(waiter);
82
+ waiter.resolve(current);
83
+ }
84
+ if (next === "stopped") for (const waiter of [...waiters]) {
85
+ waiters.delete(waiter);
86
+ waiter.reject(error ?? new AlpClientError("ALP connection stopped", { reason: "closed" }));
87
+ }
88
+ };
89
+ const retry = (error) => {
90
+ if (state === "stopped") return;
91
+ if (attempt >= maxAttempts || !shouldRetry(error)) return enter("stopped", error);
92
+ enter("waiting", error);
93
+ if (state !== "waiting") return;
94
+ timer = setTimeout(() => {
95
+ timer = void 0;
96
+ void open();
97
+ }, backoffDelay(attempt, backoff, random));
98
+ };
99
+ const open = async () => {
100
+ if (state === "stopped") return;
101
+ attempt++;
102
+ enter("connecting");
103
+ const { signal } = run;
104
+ if (state !== "connecting" || signal.aborted) return;
105
+ let candidate;
106
+ const closeCandidate = () => candidate?.close();
107
+ signal.addEventListener("abort", closeCandidate, { once: true });
108
+ try {
109
+ const transport = await connect({ attempt, signal });
110
+ if (signal.aborted) {
111
+ try {
112
+ transport.close();
113
+ } catch {
114
+ }
115
+ return;
116
+ }
117
+ candidate = new AlpRpcClient(transport, clientOptions);
118
+ candidate.onEvent((envelope) => {
119
+ for (const listener of [...events]) dispatch(listener, envelope);
120
+ });
121
+ candidate.onNotification((method, params) => {
122
+ for (const listener of [...notifications]) dispatch(listener, method, params);
123
+ });
124
+ if (onConnect) await onConnect(candidate, { attempt, reconnect: connectedBefore, signal });
125
+ if (signal.aborted) {
126
+ candidate.close();
127
+ return;
128
+ }
129
+ if (candidate.closed) throw new AlpClientError("ALP connection closed during onConnect", { reason: "disconnected" });
130
+ } catch (error) {
131
+ candidate?.close();
132
+ if (signal.aborted) return;
133
+ return retry(error instanceof Error ? error : new Error(String(error)));
134
+ } finally {
135
+ signal.removeEventListener("abort", closeCandidate);
136
+ }
137
+ const connected = (
138
+ /** @type {AlpRpcClient} */
139
+ candidate
140
+ );
141
+ current = connected;
142
+ const reconnect = connectedBefore;
143
+ connectedBefore = true;
144
+ const openedAt = Date.now();
145
+ connected.onClose((error) => {
146
+ if (current !== connected) return;
147
+ current = void 0;
148
+ if (Date.now() - openedAt >= stableMs) attempt = 0;
149
+ dispatch(() => onDisconnect?.(error, { reconnect }));
150
+ retry(error);
151
+ });
152
+ enter("open");
153
+ };
154
+ void open();
155
+ return {
156
+ get state() {
157
+ return state;
158
+ },
159
+ get client() {
160
+ return current;
161
+ },
162
+ get attempt() {
163
+ return attempt;
164
+ },
165
+ ready({ signal } = {}) {
166
+ if (state === "open" && current) return Promise.resolve(current);
167
+ if (state === "stopped") return Promise.reject(new AlpClientError("ALP connection stopped", { reason: "closed" }));
168
+ return new Promise((resolve, reject) => {
169
+ const waiter = {
170
+ /** @param {AlpRpcClient} client */
171
+ resolve: (client) => {
172
+ signal?.removeEventListener("abort", onAbort);
173
+ resolve(client);
174
+ },
175
+ /** @param {Error} error */
176
+ reject: (error) => {
177
+ signal?.removeEventListener("abort", onAbort);
178
+ reject(error);
179
+ }
180
+ };
181
+ const onAbort = () => {
182
+ waiters.delete(waiter);
183
+ reject(new AlpClientError("Waiting for the ALP connection was aborted", { reason: "aborted", cause: signal?.reason }));
184
+ };
185
+ if (signal?.aborted) return onAbort();
186
+ waiters.add(waiter);
187
+ signal?.addEventListener("abort", onAbort, { once: true });
188
+ });
189
+ },
190
+ request(method, params, options) {
191
+ if (state !== "open" || !current) return Promise.reject(new AlpClientError("ALP daemon connection closed", { reason: state === "stopped" ? "closed" : "disconnected" }));
192
+ return current.request(method, params, options);
193
+ },
194
+ onEvent(listener) {
195
+ events.add(listener);
196
+ return () => events.delete(listener);
197
+ },
198
+ onNotification(listener) {
199
+ notifications.add(listener);
200
+ return () => notifications.delete(listener);
201
+ },
202
+ onState(listener) {
203
+ states.add(listener);
204
+ return () => states.delete(listener);
205
+ },
206
+ stop() {
207
+ if (state === "stopped") return;
208
+ if (timer !== void 0) {
209
+ clearTimeout(timer);
210
+ timer = void 0;
211
+ }
212
+ run.abort(new AlpClientError("ALP connection stopped", { reason: "closed" }));
213
+ const last = current;
214
+ current = void 0;
215
+ enter("stopped");
216
+ last?.close();
217
+ events.clear();
218
+ notifications.clear();
219
+ states.clear();
220
+ }
221
+ };
222
+ }
223
+ export {
224
+ backoffDelay,
225
+ createReconnectingClient,
226
+ retryable
227
+ };