@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
package/src/render.js ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Text the CLI prints for sessions and run logs, kept apart from the commands so
3
+ * golden tests can render fixtures without an alpd (ALPD §39).
4
+ */
5
+
6
+ const TASK_PAST = { create: 'created', update: 'updated', link: 'linked', start: 'started', close: 'closed', reopen: 'reopened', delegate: 'delegated', submit: 'submitted', release: 'released', gate: 'gated', clear: 'cleared a gate of', orphaned: 'reopened (its assignment ended with alpd)' };
7
+
8
+ /** How long ago `since` was, as 42s, 3m05s or 2h10m. */
9
+ export const ago = (since, now = Date.now()) => {
10
+ const seconds = Math.max(0, Math.round((now - Date.parse(since)) / 1000));
11
+ return seconds < 60 ? `${seconds}s` : seconds < 3600 ? `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, '0')}s` : `${Math.floor(seconds / 3600)}h${String(Math.floor(seconds % 3600 / 60)).padStart(2, '0')}m`;
12
+ };
13
+ /** A duration in the same form. */
14
+ export const duration = ms => ago(new Date(0).toISOString(), ms);
15
+ /** A token count as people say it: 164k, 1M. */
16
+ const tokens = count => typeof count !== 'number' ? '?' : count >= 1_000_000 && count % 1_000_000 < 50_000 ? `${Math.round(count / 1_000_000)}M` : `${Math.round(count / 1000)}k`;
17
+
18
+ /** `alp ps`: sessions as a tree, one line each. */
19
+ export function renderPs(sessions) {
20
+ const lines = [];
21
+ const children = new Map();
22
+ for (const session of sessions) {
23
+ const key = session.parentId ?? '';
24
+ children.set(key, [...(children.get(key) ?? []), session]);
25
+ }
26
+ const print = (session, depth) => {
27
+ const status = session.parked ? `parked (${session.parked})` : session.status === 'running' || session.status === 'idle' ? (session.activeTurnId ? 'running' : session.busy ? 'waiting' : 'idle') : session.lastError?.code ?? session.status;
28
+ lines.push(`${' '.repeat(depth)}${session.id} ${session.agent} ${session.runtime}:${session.model} ${session.mode} ${status}${depth ? '' : ` ${session.projectRoot}${session.title ? ` "${session.title}"` : ''}`}`);
29
+ for (const child of children.get(session.id) ?? []) print(child, depth + 1);
30
+ };
31
+ for (const root of children.get('') ?? []) print(root, 0);
32
+ return lines;
33
+ }
34
+
35
+ /** `alp log`: one line per run-log entry, with its time. */
36
+ export function renderLog(rootId, entries) {
37
+ const lines = [];
38
+ const agents = new Map();
39
+ for (const entry of entries) {
40
+ const time = entry.ts.slice(11, 19);
41
+ let text;
42
+ switch (entry.event) {
43
+ case 'assignment.started':
44
+ agents.set(entry.assignmentId, entry.agent);
45
+ text = `${entry.parentAgent} → ${entry.agent} (${entry.mode}${entry.isolation === 'worktree' ? ', worktree' : ''}, ${entry.model}${entry.wait === false ? ', async' : ''}): ${entry.task.split('\n')[0].slice(0, 120)}`;
46
+ break;
47
+ case 'assignment.finished':
48
+ text = `${entry.agent} ${entry.status} after ${duration(entry.durationMs ?? 0)}${entry.handoff ? `, handoff ${entry.handoff.outcome}${entry.handoff.verdict ? `, verdict ${entry.handoff.verdict.result.toUpperCase()}` : ''}: ${entry.handoff.summary.split('\n')[0].slice(0, 120)}` : ''}${entry.error ? `: ${entry.error}` : ''}${entry.reconciled ? ' (after a restart)' : ''}`;
49
+ break;
50
+ case 'mail':
51
+ // Board pins are logged once, as board.pin, not per reader.
52
+ if (entry.kind === 'board') continue;
53
+ text = `✉ ${entry.kind} ${entry.from} → ${entry.to === rootId ? 'main' : agents.get(entry.to) ?? entry.to}${entry.body ? `: ${entry.body.split('\n')[0].slice(0, 120)}` : ''}`;
54
+ break;
55
+ case 'board.pin':
56
+ text = `${entry.kind === 'claim' ? '⚑' : entry.kind === 'decision' ? '◆' : '•'} ${entry.agent} pins ${entry.kind} ${entry.pinId}${entry.task ? ` for ${entry.task}` : ''}${entry.paths ? ` [${entry.paths.join(', ')}]` : ''}: ${entry.body.split('\n')[0].slice(0, 120)}`;
57
+ break;
58
+ case 'task':
59
+ text = `☐ ${entry.agent} ${TASK_PAST[entry.action] ?? entry.action} ${entry.id} "${entry.title}" → ${entry.status}${entry.detail ? `: ${entry.detail.split('\n')[0].slice(0, 120)}` : ''}`;
60
+ break;
61
+ case 'board.unpin':
62
+ text = `⚐ ${entry.pinId} by ${entry.agent} ${entry.reason === 'session_ended' ? 'released when its session ended' : 'taken down'}`;
63
+ break;
64
+ case 'human.question':
65
+ text = `? ${entry.agent} asks the user [${entry.questionId}]: ${entry.body.split('\n')[0].slice(0, 120)}`;
66
+ break;
67
+ case 'verify':
68
+ text = `${entry.skipped ? '–' : entry.passed ? '✓' : '✗'} verify in the ${entry.where}${entry.taskId ? ` for ${entry.taskId}` : ''}${entry.assignmentId ? ` (${entry.assignmentId})` : ''}: ${entry.skipped ? `skipped: ${entry.skipped}` : entry.detail}`;
69
+ break;
70
+ case 'epic.landed':
71
+ text = `◆ ${entry.agent} closed ${entry.id} "${entry.title}": ${entry.tasks} tasks, ${entry.reworked} reworked`;
72
+ break;
73
+ case 'notice':
74
+ text = `${entry.level === 'error' ? '‼' : entry.level === 'warning' ? '!' : 'ℹ'} ${entry.text}`;
75
+ break;
76
+ case 'assignment.parked':
77
+ text = `⏸ ${entry.agent} ${entry.assignmentId} parked: ${entry.reason}`;
78
+ break;
79
+ case 'assignment.resumed':
80
+ text = `▶ ${entry.agent} ${entry.assignmentId} resumed`;
81
+ break;
82
+ case 'instructions':
83
+ text = `# ${entry.agent} instructions ${entry.sha} (ALP.md ${entry.parts?.project}, AGENT.md ${entry.parts?.agent}, ${entry.chars} chars)`;
84
+ break;
85
+ case 'context':
86
+ // Before 0.6 the advice came at 60% and 80% of the window (ALPD §35); since, once near compaction (§57).
87
+ text = entry.level === 'soon'
88
+ ? `◔ ${entry.agent} context ${tokens(entry.tokens)}, compacts at ${tokens(entry.compactAt)}: told it is near`
89
+ : `◔ ${entry.agent} context ${entry.percent}% full: ${entry.level === 'now' ? 'told to hand off now' : 'told to plan a handoff'}`;
90
+ break;
91
+ case 'skill':
92
+ // alp_skill saving a skill (name, roles) shares the name with an agent using one (skill, via).
93
+ text = Array.isArray(entry.roles)
94
+ ? `✦ ${entry.agent} saved skill ${entry.name} for ${entry.roles.join(', ')}`
95
+ : `✦ ${entry.agent} uses skill ${entry.skill}${entry.via === 'skill' ? ' (Skill tool)' : ''}`;
96
+ break;
97
+ case 'skill-resource':
98
+ text = `✦ ${entry.agent} ${entry.action === 'run' ? 'runs' : 'reads'} ${entry.skill}/${entry.resource}`;
99
+ break;
100
+ case 'compacted':
101
+ text = entry.failed
102
+ ? `✗ ${entry.agent}'s context could not be compacted${entry.error ? `: ${entry.error}` : ''}`
103
+ : `◑ ${entry.agent}'s context compacted${entry.preTokens !== undefined ? ` from ${tokens(entry.preTokens)}` : ''}${entry.postTokens !== undefined ? ` to ${tokens(entry.postTokens)}` : ''}${entry.trigger === 'manual' ? ' on request' : ''}`;
104
+ break;
105
+ case 'assignment.interrupted':
106
+ text = `⏹ ${entry.agent} ${entry.assignmentId} interrupted: ${entry.reason}; the next alpd continues it`;
107
+ break;
108
+ case 'assignment.recovered':
109
+ text = `↻ ${entry.agent} ${entry.assignmentId} reopened after alpd restarted`;
110
+ break;
111
+ case 'session.restarted':
112
+ text = `↻ ${entry.agent}'s native process stopped (${entry.error}); restart ${entry.restarts}`;
113
+ break;
114
+ case 'session.revived':
115
+ text = `▶ ${entry.agent} running again`;
116
+ break;
117
+ case 'session.revive_failed':
118
+ text = `✗ ${entry.agent} could not be restarted: ${entry.error}`;
119
+ break;
120
+ case 'human.answer':
121
+ text = `↳ ${entry.questionId} ${entry.outcome}${entry.answer !== undefined ? `: ${entry.answer.split('\n')[0].slice(0, 120)}` : ''}`;
122
+ break;
123
+ case 'hook':
124
+ text = entry.skipped ? `↪ ${entry.agent}'s ${entry.on} hook ${entry.hook} skipped: the workspace's hooks are not trusted`
125
+ : `${entry.blocked ? '⛔' : entry.error || entry.exitCode !== 0 || entry.timedOut ? '✗' : '↪'} ${entry.agent}'s ${entry.on} hook ${entry.hook} ${entry.error ? `could not run: ${entry.error}` : entry.timedOut ? 'timed out' : `exit ${entry.exitCode}`}${entry.durationMs !== undefined ? ` in ${duration(entry.durationMs)}` : ''}${entry.blocked ? ', refused it' : ''}${entry.output ? `: ${entry.output.split('\n')[0].slice(0, 120)}` : ''}`;
126
+ break;
127
+ case 'hook.trust':
128
+ text = `${entry.trusted ? '✓ the user trusts' : '✗ the user did not trust'} the hooks of ${entry.project}${entry.outcome ? ` (${entry.outcome})` : ''}`;
129
+ break;
130
+ case 'runtime.slip':
131
+ text = `⚠ ALP could not handle ${entry.agent}'s ${entry.method}: ${entry.error}; the session went on`;
132
+ break;
133
+ default:
134
+ text = `${entry.event}${entry.branch ? ` ${entry.branch}` : ''}${entry.status ? ` ${entry.status}` : ''}`;
135
+ }
136
+ lines.push(`${time} ${text}`);
137
+ }
138
+ return lines;
139
+ }
@@ -0,0 +1,296 @@
1
+ import { AlpRpcError, MAX_FRAME } from '@anhlp/alp-protocol';
2
+ import { AlpClientError } from './errors.js';
3
+ import { utf8Length } from './framing.js';
4
+ import { timerDelay } from './timers.js';
5
+
6
+ /**
7
+ * The transport-independent JSON-RPC 2.0 engine of an ALP client (plans/reference/ALPD.md §3):
8
+ * request correlation, the daemon's `event` and other notifications, requests the daemon sends
9
+ * the client (extension.register), local timeouts and aborts, and cleanup when the connection
10
+ * ends. It runs unchanged in Node, browsers and React Native; a transport moves whole frames.
11
+ *
12
+ * A transport carries one complete JSON-RPC message per frame, as text. Framing (newlines on a
13
+ * socket, one WebSocket message per frame), byte decoding, connection setup and authentication
14
+ * belong to the transport and whoever creates it, never to this engine.
15
+ */
16
+
17
+ /**
18
+ * @typedef {'open' | 'closed'} TransportState
19
+ * @typedef {{ error?: Error, code?: number, reason?: string }} TransportClose
20
+ * Why a transport closed: `error` when it failed, `code`/`reason` when the peer said so.
21
+ * @typedef {{
22
+ * readonly state: TransportState,
23
+ * send(frame: string): void,
24
+ * onMessage(listener: (frame: string) => void): () => void,
25
+ * onClose(listener: (close: TransportClose) => void): () => void,
26
+ * close(): void,
27
+ * }} AlpTransport
28
+ * Contract (docs/alp/client-sdk.md): `send` delivers or throws, synchronously, and a throw means
29
+ * the frame did not leave; `onMessage` delivers frames in arrival order; `onClose` fires at most
30
+ * once, also after `close()`; nothing is delivered after it; `close` is idempotent.
31
+ * @typedef {{
32
+ * readonly aborted: boolean,
33
+ * readonly reason?: unknown,
34
+ * addEventListener(type: 'abort', listener: () => void, options?: { once?: boolean }): void,
35
+ * removeEventListener(type: 'abort', listener: () => void): void,
36
+ * }} AbortSignalLike
37
+ * @typedef {{ signal?: AbortSignalLike, timeoutMs?: number }} RequestOptions
38
+ * Both end only this client's wait; neither tells the daemon to stop. A timeout of Infinity, or
39
+ * longer than a timer can wait (2^31-1 ms), means none.
40
+ * @typedef {{
41
+ * maxPending?: number,
42
+ * maxFrame?: number,
43
+ * timeoutMs?: number,
44
+ * onListenerError?: (error: unknown) => void,
45
+ * }} AlpRpcClientOptions
46
+ */
47
+
48
+ const CLOSED = 'ALP daemon connection closed';
49
+ /** Requests waiting for an answer at once; beyond it a request fails as `overloaded` and is not sent. */
50
+ export const DEFAULT_MAX_PENDING = 4096;
51
+
52
+ /** A listener's exception must not break dispatch to the others; it surfaces like an uncaught error. @param {unknown} error */
53
+ const rethrow = error => { setTimeout(() => { throw error; }, 0); };
54
+
55
+ /** @param {AlpTransport} transport */
56
+ function assertTransport(transport) {
57
+ for (const name of ['send', 'onMessage', 'onClose', 'close']) {
58
+ if (typeof /** @type {any} */ (transport)?.[name] !== 'function') throw new TypeError(`ALP transport must implement ${name}()`);
59
+ }
60
+ }
61
+
62
+ /** @param {AbortSignalLike} signal */
63
+ const abortError = signal => new AlpClientError('ALP request aborted', { reason: 'aborted', cause: signal.reason });
64
+
65
+ /** @param {object} value @param {string} key */
66
+ const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
67
+
68
+ export class AlpRpcClient {
69
+ /** @type {AlpTransport} */ #transport;
70
+ #sequence = 0;
71
+ /** @type {Map<number, { resolve(value: unknown): void, reject(error: unknown): void, cleanup(): void }>} */
72
+ #pending = new Map();
73
+ /** @type {Set<(envelope: any) => void>} */ #events = new Set();
74
+ /** @type {Set<(method: string, params: any) => void>} */ #notifications = new Set();
75
+ /** @type {Set<(error: Error) => void>} */ #closes = new Set();
76
+ /** @type {Set<(method: string, params: any) => unknown>} */ #requestHandlers = new Set();
77
+ /** @type {Array<() => void>} */ #detach = [];
78
+ /** @type {AlpClientError | undefined} */ #closeError;
79
+ #maxPending;
80
+ #maxFrame;
81
+ #timeoutMs;
82
+ #onListenerError;
83
+
84
+ /**
85
+ * @param {AlpTransport} transport an open transport; the client owns it from now on
86
+ * @param {AlpRpcClientOptions} [options]
87
+ */
88
+ constructor(transport, { maxPending = DEFAULT_MAX_PENDING, maxFrame = MAX_FRAME, timeoutMs, onListenerError = rethrow } = {}) {
89
+ assertTransport(transport);
90
+ this.#transport = transport;
91
+ this.#maxPending = maxPending;
92
+ this.#maxFrame = maxFrame;
93
+ timerDelay(timeoutMs);
94
+ this.#timeoutMs = timeoutMs;
95
+ this.#onListenerError = onListenerError;
96
+ this.#detach.push(transport.onMessage(frame => this.#receive(frame)));
97
+ this.#detach.push(transport.onClose(close => this.#finish(this.#disconnected(close))));
98
+ if (transport.state === 'closed') this.#finish(new AlpClientError(CLOSED, { reason: 'disconnected' }));
99
+ }
100
+
101
+ /** True once the connection is gone, for whatever reason. */
102
+ get closed() { return this.#closeError !== undefined; }
103
+ /** Requests sent and still waiting for an answer. */
104
+ get pendingCount() { return this.#pending.size; }
105
+
106
+ /**
107
+ * Sends one request and resolves with its result, or rejects with AlpRpcError (the daemon
108
+ * answered with an error) or AlpClientError (the client gave up: see CLIENT_ERROR). Requests are
109
+ * never resent, also not after a reconnect.
110
+ * @template [T=any]
111
+ * @param {string} method
112
+ * @param {unknown} [params]
113
+ * @param {RequestOptions} [options]
114
+ * @returns {Promise<T>}
115
+ */
116
+ request(method, params = {}, { signal, timeoutMs = this.#timeoutMs } = {}) {
117
+ if (this.#closeError) return Promise.reject(new AlpClientError(CLOSED, { reason: this.#closeError.reason === 'closed' ? 'closed' : 'disconnected', cause: this.#closeError }));
118
+ if (signal?.aborted) return Promise.reject(abortError(signal));
119
+ if (this.#pending.size >= this.#maxPending) return Promise.reject(new AlpClientError(`Too many ALP requests waiting for an answer (${this.#maxPending})`, { reason: 'overloaded' }));
120
+ /** @type {number | undefined} */
121
+ let delay;
122
+ try { delay = timerDelay(timeoutMs); } catch (error) { return Promise.reject(error); }
123
+ const id = ++this.#sequence;
124
+ let frame;
125
+ try { frame = JSON.stringify({ jsonrpc: '2.0', id, method, params }); } catch (error) { return Promise.reject(error); }
126
+ // The limit counts the newline a stream transport adds, as alpd counts it.
127
+ if (utf8Length(frame) >= this.#maxFrame) return Promise.reject(new AlpClientError(`ALP request ${method} exceeds the ${this.#maxFrame}-byte frame limit`, { reason: 'send_failed' }));
128
+ return new Promise((resolve, reject) => {
129
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
130
+ let timer;
131
+ const onAbort = () => { if (this.#pending.delete(id)) { cleanup(); reject(abortError(/** @type {AbortSignalLike} */ (signal))); } };
132
+ const cleanup = () => {
133
+ if (timer !== undefined) clearTimeout(timer);
134
+ signal?.removeEventListener('abort', onAbort);
135
+ };
136
+ this.#pending.set(id, { resolve, reject, cleanup });
137
+ if (delay !== undefined) {
138
+ timer = setTimeout(() => {
139
+ if (!this.#pending.delete(id)) return;
140
+ cleanup();
141
+ reject(new AlpClientError(`ALP request ${method} timed out after ${timeoutMs} ms`, { reason: 'timeout' }));
142
+ }, delay);
143
+ }
144
+ signal?.addEventListener('abort', onAbort, { once: true });
145
+ try {
146
+ this.#transport.send(frame);
147
+ } catch (error) {
148
+ // A transport that is already gone (a socket half-closed by alpd, a WebSocket closing) ends
149
+ // the connection now, so `closed` is true when this request rejects, as it was before the
150
+ // transport reported its close. A transport still open refused only this frame.
151
+ if (this.#transport.state === 'closed') this.#finish(new AlpClientError(CLOSED, { reason: 'disconnected', cause: error }));
152
+ else if (this.#pending.delete(id)) {
153
+ cleanup();
154
+ reject(new AlpClientError(`Could not send ALP request ${method}: ${error instanceof Error ? error.message : String(error)}`, { reason: 'send_failed', cause: error }));
155
+ }
156
+ }
157
+ });
158
+ }
159
+
160
+ /** Every `event` notification: an envelope of a session the connection attached to. Returns a remover. @param {(envelope: any) => void} listener */
161
+ onEvent(listener) { return this.#add(this.#events, listener); }
162
+
163
+ /** Every notification from the daemon, `event` included; for methods this client does not know yet. @param {(method: string, params: any) => void} listener */
164
+ onNotification(listener) { return this.#add(this.#notifications, listener); }
165
+
166
+ /**
167
+ * Answers requests the daemon sends this client (the extension RPC of ALPD §61). The first
168
+ * handler answers; its result, or its error's numeric `code`, `message` and `data`, goes back.
169
+ * @param {(method: string, params: any) => unknown} handler
170
+ */
171
+ onRequest(handler) { return this.#add(this.#requestHandlers, handler); }
172
+
173
+ /** Called once when the connection ends, with the error pending requests were rejected with. @param {(error: Error) => void} listener */
174
+ onClose(listener) { return this.#add(this.#closes, listener); }
175
+
176
+ /** Ends the connection; waiting requests reject with reason `closed`. Idempotent. */
177
+ close() {
178
+ if (this.#closeError) return;
179
+ this.#finish(new AlpClientError(CLOSED, { reason: 'closed' }));
180
+ }
181
+
182
+ /** @template F @param {Set<F>} set @param {F} listener */
183
+ #add(set, listener) {
184
+ if (typeof listener !== 'function') throw new TypeError('ALP client listener must be a function');
185
+ if (this.#closeError) return () => false;
186
+ set.add(listener);
187
+ return () => set.delete(listener);
188
+ }
189
+
190
+ /** @param {TransportClose} [close] */
191
+ #disconnected(close = {}) {
192
+ if (close.error instanceof AlpClientError) return close.error;
193
+ const data = close.code !== undefined || close.reason ? { code: close.code, reason: close.reason } : undefined;
194
+ return new AlpClientError(close.error?.message ?? CLOSED, { reason: 'disconnected', cause: close.error, data });
195
+ }
196
+
197
+ /** @param {string} message */
198
+ #violation(message) {
199
+ this.#finish(new AlpClientError(message, { reason: 'protocol' }));
200
+ }
201
+
202
+ /** @param {Function} listener @param {unknown[]} args */
203
+ #call(listener, ...args) {
204
+ try { listener(...args); } catch (error) { this.#onListenerError(error); }
205
+ }
206
+
207
+ /** @param {string} frame */
208
+ #receive(frame) {
209
+ if (this.#closeError) return;
210
+ if (typeof frame !== 'string') return this.#violation('Invalid frame from ALP daemon');
211
+ let message;
212
+ try { message = JSON.parse(frame); } catch { return this.#violation('Invalid frame from ALP daemon'); }
213
+ if (typeof message !== 'object' || message === null || Array.isArray(message)) return this.#violation('Invalid frame from ALP daemon');
214
+ const hasId = message.id !== undefined && message.id !== null;
215
+ if (message.method === 'event') {
216
+ for (const listener of [...this.#events]) this.#call(listener, message.params);
217
+ for (const listener of [...this.#notifications]) this.#call(listener, message.method, message.params);
218
+ return;
219
+ }
220
+ if (typeof message.method === 'string' && hasId && !own(message, 'result') && !own(message, 'error')) return this.#answer(message.id, message.method, message.params ?? {});
221
+ if (typeof message.method === 'string' && !hasId) {
222
+ for (const listener of [...this.#notifications]) this.#call(listener, message.method, message.params);
223
+ return;
224
+ }
225
+ // A response to a request this client no longer waits for (timed out, aborted) or never sent,
226
+ // and an error the daemon could not tie to a request (id null), have nobody to go to.
227
+ const waiter = this.#pending.get(message.id);
228
+ if (!waiter) return;
229
+ this.#pending.delete(message.id);
230
+ waiter.cleanup();
231
+ if (own(message, 'error') && typeof message.error === 'object' && message.error !== null) waiter.reject(new AlpRpcError(message.error));
232
+ else if (own(message, 'result') && !own(message, 'error')) waiter.resolve(message.result);
233
+ else waiter.reject(new AlpClientError('Malformed response from ALP daemon', { reason: 'protocol', data: { id: message.id } }));
234
+ }
235
+
236
+ /**
237
+ * Answers a request from alpd. Every request gets exactly one answer: a result that cannot be
238
+ * serialized or does not fit a frame becomes an error, and an error whose data cannot go either
239
+ * goes without it, so alpd's caller never waits for a reply that was silently dropped.
240
+ * @param {unknown} id @param {string} method @param {unknown} params
241
+ */
242
+ #answer(id, method, params) {
243
+ /** The frame for `body`, or undefined if it cannot be serialized or is over the limit. @param {object} body */
244
+ const frameOf = body => {
245
+ try {
246
+ const frame = JSON.stringify({ jsonrpc: '2.0', id, ...body });
247
+ return utf8Length(frame) < this.#maxFrame ? frame : undefined;
248
+ } catch { return undefined; }
249
+ };
250
+ /** @param {string | undefined} frame */
251
+ const send = frame => {
252
+ if (this.#closeError) return;
253
+ if (frame === undefined) return this.#finish(new AlpClientError('ALP reply exceeds the frame limit', { reason: 'protocol' }));
254
+ try { this.#transport.send(frame); } catch (cause) {
255
+ this.#finish(new AlpClientError('Could not send ALP reply', { reason: 'send_failed', cause }));
256
+ }
257
+ };
258
+ /** @param {unknown} error */
259
+ const failure = error => {
260
+ const code = (error && typeof (/** @type {any} */ (error)).code === 'number') ? /** @type {any} */ (error).code : 1000;
261
+ const text = error instanceof Error ? error.message : String(error);
262
+ const message = text.length > 2000 ? `${text.slice(0, 2000)}...` : text;
263
+ const data = (error && /** @type {any} */ (error).data !== undefined) ? { data: /** @type {any} */ (error).data } : {};
264
+ return frameOf({ error: { code, message, ...data } }) ?? frameOf({ error: { code, message } })
265
+ ?? frameOf({ error: { code: -32603, message: 'The reply could not be sent' } });
266
+ };
267
+ const [handler] = this.#requestHandlers;
268
+ if (!handler) return send(failure(Object.assign(new Error(`Unknown method '${method}'`), { code: -32601 })));
269
+ Promise.resolve().then(async () => {
270
+ try {
271
+ const result = await handler(method, params);
272
+ const frame = frameOf({ result: result === undefined ? {} : result });
273
+ send(frame ?? failure(new Error(`The result of ${method} cannot be serialized or exceeds the ${this.#maxFrame}-byte frame limit`)));
274
+ } catch (error) {
275
+ send(failure(error));
276
+ }
277
+ });
278
+ }
279
+
280
+ /** @param {AlpClientError} error */
281
+ #finish(error) {
282
+ if (this.#closeError) return;
283
+ this.#closeError = error;
284
+ for (const detach of this.#detach.splice(0)) { try { detach(); } catch {} }
285
+ try { this.#transport.close(); } catch {}
286
+ const pending = [...this.#pending.values()];
287
+ this.#pending.clear();
288
+ for (const waiter of pending) { waiter.cleanup(); waiter.reject(error); }
289
+ const closes = [...this.#closes];
290
+ this.#events.clear();
291
+ this.#notifications.clear();
292
+ this.#requestHandlers.clear();
293
+ this.#closes.clear();
294
+ for (const listener of closes) this.#call(listener, error);
295
+ }
296
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Errors the client raises itself, as opposed to AlpRpcError, which carries an error alpd returned.
3
+ * Portable: no Node built-ins, process or Buffer (plans/reference/ALPD.md §3, docs/alp/client-sdk.md).
4
+ */
5
+
6
+ const BRAND = Symbol.for('@anhlp/alp-client/AlpClientError');
7
+
8
+ /**
9
+ * Why a request or a connection ended on the client side.
10
+ * - `closed`: this client was closed locally with close().
11
+ * - `disconnected`: the transport closed or failed. A request that was already sent may or may not
12
+ * have run on the daemon; the client never resends it.
13
+ * - `protocol`: the peer sent something that is not ALP JSON-RPC, so the client closed the connection.
14
+ * - `send_failed`: the transport refused the frame; the request never left this client.
15
+ * - `timeout` / `aborted`: the caller stopped waiting. Only the local wait ends; the daemon is not told.
16
+ * - `overloaded`: too many requests are waiting for an answer already; nothing was sent.
17
+ */
18
+ export const CLIENT_ERROR = Object.freeze({
19
+ closed: 'closed',
20
+ disconnected: 'disconnected',
21
+ protocol: 'protocol',
22
+ sendFailed: 'send_failed',
23
+ timeout: 'timeout',
24
+ aborted: 'aborted',
25
+ overloaded: 'overloaded',
26
+ });
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, { reason, cause, data }) {
34
+ super(message, cause === undefined ? undefined : { cause });
35
+ this.name = 'AlpClientError';
36
+ /** @type {'closed' | 'disconnected' | 'protocol' | 'send_failed' | 'timeout' | 'aborted' | 'overloaded'} */
37
+ this.reason = reason;
38
+ /** @type {unknown} */
39
+ this.data = data;
40
+ Object.defineProperty(this, BRAND, { value: true });
41
+ }
42
+ }
43
+
44
+ /**
45
+ * True for an AlpClientError, also one thrown by another copy of this module (a bundle may carry
46
+ * two); `reason` narrows the check.
47
+ * @param {unknown} error
48
+ * @param {string} [reason]
49
+ * @returns {error is AlpClientError}
50
+ */
51
+ export function isAlpClientError(error, reason) {
52
+ return typeof error === 'object' && error !== null && /** @type {any} */ (error)[BRAND] === true
53
+ && (reason === undefined || /** @type {any} */ (error).reason === reason);
54
+ }
@@ -0,0 +1,61 @@
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
+
7
+ /** UTF-8 length of `text` without Buffer or TextEncoder; an unpaired surrogate counts as U+FFFD (3 bytes). @param {string} text */
8
+ export function utf8Length(text) {
9
+ let bytes = 0;
10
+ for (let index = 0; index < text.length; index++) {
11
+ const code = text.charCodeAt(index);
12
+ if (code < 0x80) bytes += 1;
13
+ else if (code < 0x800) bytes += 2;
14
+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < text.length && (text.charCodeAt(index + 1) & 0xfc00) === 0xdc00) { bytes += 4; index++; }
15
+ else bytes += 3;
16
+ }
17
+ return bytes;
18
+ }
19
+
20
+ /**
21
+ * Splits decoded text chunks into frames. `push` returns the complete frames in order, blank
22
+ * lines skipped, and throws once a frame (complete or still arriving) exceeds `maxFrame` bytes;
23
+ * the decoder is unusable after that. Each character is measured once, so a frame that arrives
24
+ * in many chunks costs linear time.
25
+ * @param {{ maxFrame: number }} options
26
+ * @returns {{ push(chunk: string): string[], readonly buffered: number }}
27
+ */
28
+ export function createLineDecoder({ maxFrame }) {
29
+ /** @type {string[]} */
30
+ let parts = [];
31
+ let bytes = 0;
32
+ let failed = false;
33
+ const overflow = () => { failed = true; parts = []; bytes = 0; return new RangeError(`Frame exceeds ${maxFrame} bytes`); };
34
+ return {
35
+ push(chunk) {
36
+ if (failed) throw new RangeError('Line decoder already failed');
37
+ /** @type {string[]} */
38
+ const frames = [];
39
+ let start = 0;
40
+ for (let index = chunk.indexOf('\n'); index >= 0; index = chunk.indexOf('\n', start)) {
41
+ const piece = chunk.slice(start, index);
42
+ bytes += utf8Length(piece);
43
+ if (bytes > maxFrame) throw overflow();
44
+ parts.push(piece);
45
+ const line = parts.length === 1 ? parts[0] : parts.join('');
46
+ parts = [];
47
+ bytes = 0;
48
+ start = index + 1;
49
+ if (line.trim()) frames.push(line);
50
+ }
51
+ if (start < chunk.length) {
52
+ const rest = chunk.slice(start);
53
+ bytes += utf8Length(rest);
54
+ if (bytes > maxFrame) throw overflow();
55
+ parts.push(rest);
56
+ }
57
+ return frames;
58
+ },
59
+ get buffered() { return bytes; },
60
+ };
61
+ }
@@ -0,0 +1,21 @@
1
+ import { PROTOCOL_VERSION } from '@anhlp/alp-protocol';
2
+
3
+ /** The daemon.hello capability a process an ALP agent started announces. */
4
+ export const AGENT_CAPABILITY = 'principal.agent';
5
+
6
+ /** @typedef {{ name: string, version: string }} ClientInfo */
7
+
8
+ /**
9
+ * The version handshake every ALP connection starts with (plans/reference/ALPD.md §3): alpd
10
+ * answers nothing else before it. Shared by the Node `connect` and portable clients, so a change
11
+ * to the handshake (Task 06) lands in one place.
12
+ * @param {{ request(method: string, params?: unknown, options?: import('./client.js').RequestOptions): Promise<any> }} client
13
+ * @param {ClientInfo} [info]
14
+ * @param {import('./client.js').RequestOptions} [options]
15
+ * @param {{ agent?: boolean }} [principal] `agent`: an ALP agent started this process (the Node entry reads ALP_AGENT_SESSION).
16
+ * @returns {Promise<{ protocolVersion: number } & Record<string, unknown>>}
17
+ */
18
+ export function hello(client, info = { name: 'alp', version: '0' }, options, { agent = false } = {}) {
19
+ // A process an ALP agent started says so (t-ca1f): alpd then refuses it what only the user may do.
20
+ return client.request('daemon.hello', { protocolVersion: PROTOCOL_VERSION, client: info, ...(agent ? { capabilities: [AGENT_CAPABILITY] } : {}) }, options);
21
+ }