@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,203 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, open, rmdir, unlink } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { moveFile } from '@anhlp/alp-core/atomic';
6
+ import { assertIntegrationName, bootId, bootTime, isSameBoot } from './index.js';
7
+
8
+ /**
9
+ * @typedef {{ pid: number, bootTime: number, bootId?: string, startedUptime?: number, startedAt: string, ready: boolean, lockVersion?: number, owner?: string }} IntegrationLockRecord
10
+ * @typedef {{
11
+ * acquire(): Promise<{ acquired: boolean, lock: IntegrationLockRecord }>,
12
+ * setReady(ready: boolean): Promise<boolean>,
13
+ * release(): Promise<boolean>,
14
+ * }} IntegrationLock
15
+ */
16
+
17
+ /**
18
+ * The single-owner lock of one integration service, at `<home>/integrations/<name>.lock`, with its
19
+ * mutation guard `<name>.lock.reclaim`. Each instance is single-use: acquire once, then setReady and
20
+ * release while it owns the lock.
21
+ *
22
+ * Single-host, same PID namespace, private local filesystem only. Never reap the mutation guard.
23
+ * @param {string} home the ALP_HOME the integration runs under
24
+ * @param {string} name the integration name, for example `web`
25
+ * @returns {IntegrationLock}
26
+ */
27
+ export function createIntegrationLock(home, name) {
28
+ const file = path.join(home, 'integrations', `${assertIntegrationName(name)}.lock`);
29
+ const guard = `${file}.reclaim`;
30
+ /** @type {'new' | 'acquiring' | 'owned' | 'retired'} */
31
+ let phase = 'new';
32
+ /** This instance's lock while it owns it: the lifetime nonce and the file's identity. @type {{ owner: string, dev: number, ino: number } | undefined} */
33
+ let owned;
34
+ /** Serializes concurrent in-process setReady calls to preserve FIFO order. @type {Promise<any>} */
35
+ let readyQueue = Promise.resolve();
36
+ // The lock file as read: its record and the stats of the handle it was read through. Kept inside
37
+ // the factory so the published declarations name only IntegrationLock and its record.
38
+ /** @typedef {{ value: any, info: import('node:fs').Stats }} Snapshot */
39
+ /** @param {string} reason */
40
+ const recovery = reason => new Error(`${reason}. Stop ALL integration processes using this ALP_HOME before manual lock-only recovery of ${file} and ${guard}; see docs/modular-monorepo.md`);
41
+
42
+ /**
43
+ * @template T
44
+ * @param {() => Promise<T>} run
45
+ * @returns {Promise<T>}
46
+ */
47
+ async function guarded(run) {
48
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
49
+ const deadline = Date.now() + 20_000;
50
+ for (;;) {
51
+ try { await mkdir(guard, { mode: 0o700 }); break; }
52
+ catch (error) {
53
+ if (/** @type {any} */ (error)?.code !== 'EEXIST') throw error;
54
+ if (Date.now() >= deadline) throw recovery('Integration mutation guard remains busy or abandoned');
55
+ await new Promise(resolve => setTimeout(resolve, 25));
56
+ }
57
+ }
58
+ const token = path.join(guard, `owner-${process.pid}-${randomUUID()}`);
59
+ // If token initialization/close fails, leave the guard: no speculative cleanup of shared paths.
60
+ try {
61
+ const handle = await open(token, 'wx', 0o600);
62
+ await handle.close();
63
+ } catch (error) { throw recovery(`Integration guard initialization failed: ${String(error)}`); }
64
+ try { return await run(); }
65
+ finally {
66
+ // Only this successful mkdir owner finalizes, once. Missing token may mean a replacement
67
+ // generation: never rmdir in that case. No contender removes any other owner's token.
68
+ try { await unlink(token); }
69
+ catch (error) { throw recovery(/** @type {any} */ (error)?.code === 'ENOENT' ? 'Integration guard ownership was lost' : `Integration guard token cleanup failed: ${String(error)}`); }
70
+ try { await rmdir(guard); }
71
+ catch (error) { throw recovery(`Integration guard cleanup failed: ${String(error)}`); }
72
+ }
73
+ }
74
+
75
+ /** @returns {Promise<Snapshot | undefined>} */
76
+ async function snapshot() {
77
+ let handle;
78
+ try { handle = await open(file, 'r'); }
79
+ catch (error) { if (/** @type {any} */ (error)?.code === 'ENOENT') return undefined; throw error; }
80
+ try {
81
+ const info = await handle.stat();
82
+ const raw = await handle.readFile('utf8');
83
+ let value;
84
+ try { value = JSON.parse(raw); } catch { value = undefined; }
85
+ return { value, info };
86
+ } finally { await handle.close(); }
87
+ }
88
+
89
+ /**
90
+ * @param {any} value
91
+ * @returns {value is IntegrationLockRecord}
92
+ */
93
+ function complete(value) {
94
+ return value && Number.isSafeInteger(value.pid) && value.pid > 0
95
+ && typeof value.bootTime === 'number' && Number.isFinite(value.bootTime) && value.bootTime > 0
96
+ && (value.bootId === undefined || typeof value.bootId === 'string' && value.bootId.length > 0)
97
+ && (value.startedUptime === undefined || typeof value.startedUptime === 'number' && Number.isFinite(value.startedUptime))
98
+ && typeof value.startedAt === 'string' && Number.isFinite(Date.parse(value.startedAt))
99
+ && typeof value.ready === 'boolean'
100
+ && (value.lockVersion === undefined && value.owner === undefined
101
+ || value.lockVersion === 1 && typeof value.owner === 'string' && /^[a-f0-9-]{36}$/.test(value.owner));
102
+ }
103
+
104
+ /**
105
+ * @param {IntegrationLockRecord} value
106
+ * @returns {boolean}
107
+ */
108
+ function dead(value) {
109
+ try { process.kill(value.pid, 0); return false; }
110
+ catch (error) {
111
+ if (/** @type {any} */ (error)?.code !== 'ESRCH') return false; // EPERM and unknown errors never grant takeover.
112
+ // Approximate wall-clock boot metadata is context, never affirmative death evidence.
113
+ if (!isSameBoot(value)) throw recovery('Integration owner boot context is uncertain');
114
+ return true;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * @param {Snapshot | undefined} current
120
+ * @returns {boolean}
121
+ */
122
+ function matches(current) {
123
+ return !!owned && current?.value?.owner === owned.owner
124
+ && current.info.dev === owned.dev && current.info.ino === owned.ino;
125
+ }
126
+
127
+ return {
128
+ async acquire() {
129
+ if (phase !== 'new') throw new Error('Integration lock instance has already been used');
130
+ phase = 'acquiring';
131
+ try {
132
+ return await guarded(async () => {
133
+ const current = await snapshot();
134
+ if (current) {
135
+ if (!complete(current.value)) throw recovery('Integration lock is malformed, incomplete or unsupported');
136
+ if (!dead(current.value)) { phase = 'retired'; return { acquired: false, lock: current.value }; }
137
+ await unlink(file);
138
+ }
139
+ const currentBootId = bootId();
140
+ /** @type {IntegrationLockRecord & { owner: string }} */
141
+ const value = {
142
+ pid: process.pid,
143
+ bootTime: bootTime(),
144
+ ...(currentBootId ? { bootId: currentBootId } : {}),
145
+ startedAt: new Date().toISOString(),
146
+ startedUptime: Math.floor(os.uptime()),
147
+ ready: false,
148
+ lockVersion: 1,
149
+ owner: randomUUID(),
150
+ };
151
+ const handle = await open(file, 'wx', 0o600);
152
+ let info;
153
+ try { await handle.writeFile(JSON.stringify(value)); info = await handle.stat(); }
154
+ finally { await handle.close(); }
155
+ owned = { owner: value.owner, dev: info.dev, ino: info.ino };
156
+ phase = 'owned';
157
+ return { acquired: true, lock: value };
158
+ });
159
+ } catch (error) { phase = 'retired'; owned = undefined; throw error; }
160
+ },
161
+
162
+ async setReady(ready) {
163
+ if (phase !== 'owned') return false;
164
+ const execute = async () => {
165
+ if (phase !== 'owned') return false;
166
+ return guarded(async () => {
167
+ if (phase !== 'owned') return false;
168
+ const current = await snapshot();
169
+ if (!current || !matches(current)) { phase = 'retired'; owned = undefined; return false; }
170
+ const value = { ...current.value, ready };
171
+ const tmp = `${file}.${randomUUID()}.tmp`;
172
+ const handle = await open(tmp, 'wx', 0o600);
173
+ let info;
174
+ try {
175
+ try { await handle.writeFile(JSON.stringify(value)); info = await handle.stat(); }
176
+ finally { await handle.close(); }
177
+ // Readers (alp dashboard --status, a polling client) may hold the lock open; Windows then refuses the
178
+ // replace with EPERM/EACCES/EBUSY for a moment, so moveFile retries it there.
179
+ await moveFile(tmp, file);
180
+ owned = { owner: value.owner, dev: info.dev, ino: info.ino };
181
+ return true;
182
+ } finally { await unlink(tmp).catch(error => { if (error?.code !== 'ENOENT') throw error; }); }
183
+ });
184
+ };
185
+ const chained = readyQueue.then(execute, execute);
186
+ readyQueue = chained.catch(() => {});
187
+ return chained;
188
+ },
189
+
190
+ async release() {
191
+ if (phase !== 'owned') return false;
192
+ return guarded(async () => {
193
+ if (phase !== 'owned') return false;
194
+ const current = await snapshot();
195
+ const ours = matches(current);
196
+ phase = 'retired'; owned = undefined;
197
+ if (!ours) return false;
198
+ await unlink(file);
199
+ return true;
200
+ });
201
+ },
202
+ };
203
+ }
package/src/ipc.js ADDED
@@ -0,0 +1,92 @@
1
+ import { MAX_FRAME } from '@anhlp/alp-protocol';
2
+ import { AlpClientError } from './rpc/errors.js';
3
+ import { createLineDecoder } from './rpc/framing.js';
4
+
5
+ /**
6
+ * The Node transport of the ALP client: a Unix socket or Windows named pipe carrying
7
+ * newline-delimited JSON (plans/reference/ALPD.md §3). Node-only; the portable engine
8
+ * (`@anhlp/alp-client/portable`) never imports it. Socket discovery, the private-socket checks
9
+ * and daemon startup stay in the Node entry (`connect`, `ensureDaemon`).
10
+ *
11
+ * @typedef {import('./rpc/client.js').AlpTransport} AlpTransport
12
+ * @typedef {import('./rpc/client.js').TransportClose} TransportClose
13
+ * @typedef {{ maxFrame?: number, maxBufferedBytes?: number }} SocketTransportOptions
14
+ * `maxBufferedBytes` bounds what may wait in the socket's write buffer; a send beyond it fails
15
+ * as `send_failed` instead of growing memory while the daemon does not read.
16
+ */
17
+
18
+ /**
19
+ * Wraps a connected or still-connecting socket (writes made while it connects are queued by
20
+ * Node). The transport owns the socket from then on.
21
+ * @param {import('node:net').Socket} socket
22
+ * @param {SocketTransportOptions} [options]
23
+ * @returns {AlpTransport}
24
+ */
25
+ export function createSocketTransport(socket, { maxFrame = MAX_FRAME, maxBufferedBytes = 4 * MAX_FRAME } = {}) {
26
+ const decoder = createLineDecoder({ maxFrame });
27
+ /** @type {Set<(frame: string) => void>} */
28
+ const messages = new Set();
29
+ /** @type {Set<(close: TransportClose) => void>} */
30
+ const closes = new Set();
31
+ /** @type {TransportClose | undefined} */
32
+ let ended;
33
+ /** @param {TransportClose} close */
34
+ const end = close => {
35
+ if (ended) return;
36
+ ended = close;
37
+ socket.off('data', onData);
38
+ messages.clear();
39
+ const listeners = [...closes];
40
+ closes.clear();
41
+ for (const listener of listeners) listener(close);
42
+ };
43
+ /** @param {string} chunk */
44
+ const onData = chunk => {
45
+ if (ended) return;
46
+ let frames;
47
+ try { frames = decoder.push(chunk); } catch {
48
+ const error = new AlpClientError('ALP daemon frame exceeds size limit', { reason: 'protocol' });
49
+ socket.destroy();
50
+ return end({ error });
51
+ }
52
+ for (const frame of frames) {
53
+ if (ended) return;
54
+ for (const listener of [...messages]) listener(frame);
55
+ }
56
+ };
57
+ socket.setEncoding('utf8');
58
+ socket.on('data', onData);
59
+ socket.on('error', error => end({ error }));
60
+ socket.on('close', () => end({}));
61
+ if (socket.destroyed) end({});
62
+ // A socket alpd has half-closed (Node ends our side at once) or destroyed is gone, even before
63
+ // Node emits 'close' a tick later.
64
+ const gone = () => socket.destroyed || socket.writableEnded;
65
+ return {
66
+ get state() { return ended || gone() ? 'closed' : 'open'; },
67
+ send(frame) {
68
+ // Report the close now rather than on 'close', so the client is closed when the send fails.
69
+ if (!ended && gone()) end({});
70
+ if (ended) throw new AlpClientError('ALP daemon connection closed', { reason: 'send_failed' });
71
+ if (socket.writableLength + frame.length > maxBufferedBytes) throw new AlpClientError(`ALP socket write buffer is over ${maxBufferedBytes} bytes`, { reason: 'send_failed' });
72
+ socket.write(`${frame}\n`);
73
+ },
74
+ onMessage(listener) {
75
+ if (ended) return () => false;
76
+ messages.add(listener);
77
+ return () => messages.delete(listener);
78
+ },
79
+ onClose(listener) {
80
+ if (ended) return () => false;
81
+ closes.add(listener);
82
+ return () => closes.delete(listener);
83
+ },
84
+ close() {
85
+ // end() lets frames already written reach the daemon, as the client always did; once they
86
+ // have, the socket is destroyed, so a peer that never closes its side cannot hold it open.
87
+ // A side already ended (by this, or by Node after alpd's FIN) is destroyed by Node itself.
88
+ if (!socket.writableEnded) socket.end(() => socket.destroy());
89
+ end({});
90
+ },
91
+ };
92
+ }
@@ -0,0 +1,41 @@
1
+ import path from 'node:path';
2
+ import { AlpError } from '@anhlp/alp-core/errors';
3
+ import { getEntry } from '@anhlp/alp-core/library-edit';
4
+ import { runHook, samplePayload } from '@anhlp/alp-core/hook-run';
5
+ import { normalizeMcp } from '@anhlp/alp-core/validation';
6
+ import { probeMcp } from './mcp-probe.js';
7
+ import { probeAcp } from './acp-probe.js';
8
+ import { probeAntigravity } from './antigravity-probe.js';
9
+ import { loadProvider } from '@anhlp/alp-core/providers';
10
+
11
+ /**
12
+ * Tries an MCP server, a hook or an ACP provider out (ALPD §43, §46). An MCP server is
13
+ * started and its tools listed; a provider is started and initialized; a hook runs once with a sample payload for its event, in the project (or the
14
+ * library when there is none), with the variables ALP gives hooks.
15
+ */
16
+ export async function testEntry(kind, name, { root, library, templates, scope, timeoutMs } = {}) {
17
+ const entry = await getEntry(kind, name, { root, library, templates, scope });
18
+ const home = entry.source === 'project' ? path.join(path.resolve(root), '.alp') : library;
19
+ if (kind === 'mcp') {
20
+ const server = normalizeMcp({ mcpServers: { [name]: entry.content.server } }, path.join(home, 'mcp'), `${name}.json`).mcpServers[name];
21
+ const result = await probeMcp(server, { cwd: root ? path.resolve(root) : library, ...(timeoutMs ? { timeoutMs } : {}) });
22
+ return { kind, name, source: entry.source, ok: true, ...result };
23
+ }
24
+ if (kind === 'hooks') {
25
+ const hook = entry.content.hook;
26
+ const project = root ? path.resolve(root) : undefined;
27
+ const payload = samplePayload(hook.event, { project, agent: hook.match?.agent ?? 'main' });
28
+ const env = { ALP_EVENT: hook.event, ALP_SESSION: payload.session, ALP_AGENT: payload.agent, ALP_PROJECT: project ?? '', ALP_TASK: payload.task ?? '' };
29
+ const result = await runHook(hook, payload, { cwd: project ?? library, env, ...(timeoutMs ? { timeoutMs } : {}) });
30
+ const ok = result.exitCode === 0 && !result.timedOut;
31
+ return { kind, name, source: entry.source, ok, ...(hook.blocking && !ok ? { wouldBlock: true } : {}), payload, ...result };
32
+ }
33
+ if (kind === 'providers') {
34
+ const provider = await loadProvider(library, name);
35
+ const result = provider.kind === 'antigravity'
36
+ ? await probeAntigravity(provider, { cwd: root ? path.resolve(root) : library, ...(timeoutMs ? { timeoutMs } : {}) })
37
+ : await probeAcp(provider, { cwd: root ? path.resolve(root) : library, ...(timeoutMs ? { timeoutMs } : {}) });
38
+ return { kind, name, source: entry.source, ok: true, ...result };
39
+ }
40
+ throw new AlpError('INVALID_KIND', `Only mcp servers, hooks and providers can be tested, not ${kind}`);
41
+ }
@@ -0,0 +1,118 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createInterface } from 'node:readline';
3
+ import { launchCommand } from '@anhlp/alp-core/providers';
4
+
5
+ const PROTOCOL = '2025-06-18';
6
+ const client = { name: 'alp', version: '1' };
7
+
8
+ /**
9
+ * Starts an MCP server once and lists its tools (ALPD §43), for the Test button and
10
+ * `alp mcp test`. `server` is a normalized definition: { command, args, env, cwd } for
11
+ * stdio, or { url, headers } for HTTP. The server is stopped afterwards.
12
+ * @returns {Promise<{ server?: { name?: string, version?: string }, tools: Array<{ name: string, description?: string }> }>}
13
+ */
14
+ export async function probeMcp(server, { cwd, timeoutMs = 15_000 } = {}) {
15
+ const session = server.url ? await httpSession(server, timeoutMs) : stdioSession(server, cwd, timeoutMs);
16
+ try {
17
+ const init = await session.request('initialize', { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: client });
18
+ await session.notify('notifications/initialized');
19
+ const tools = [];
20
+ let cursor;
21
+ for (let page = 0; page < 20; page++) {
22
+ const result = await session.request('tools/list', cursor ? { cursor } : {});
23
+ for (const tool of result.tools ?? []) tools.push({ name: tool.name, ...(tool.description ? { description: tool.description } : {}) });
24
+ cursor = result.nextCursor;
25
+ if (!cursor) break;
26
+ }
27
+ return { ...(init.serverInfo ? { server: { name: init.serverInfo.name, version: init.serverInfo.version } } : {}), tools };
28
+ } finally {
29
+ await session.close();
30
+ }
31
+ }
32
+
33
+ /** A JSON-RPC session with a process over stdio; ACP providers are probed with it too. */
34
+ export function stdioSession(server, cwd, timeoutMs) {
35
+ // Its own process group, so a launcher such as npx is stopped with what it started.
36
+ const env = { ...process.env, ...(server.env ?? {}) };
37
+ const launch = launchCommand(server.command, server.args ?? [], env);
38
+ const child = spawn(launch.command, launch.args, { cwd: server.cwd ?? cwd, env: launch.env ? { ...env, ...launch.env } : env, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
39
+ const signal = name => { try { process.kill(-child.pid, name); } catch { child.kill(name); } };
40
+ let stderr = '';
41
+ child.stderr.setEncoding('utf8');
42
+ child.stderr.on('data', chunk => { if (stderr.length < 4000) stderr += chunk; });
43
+ const pending = new Map();
44
+ let exited;
45
+ const failAll = error => { for (const { reject } of pending.values()) reject(error); pending.clear(); };
46
+ child.on('error', error => { exited = error; failAll(error); });
47
+ child.on('exit', code => {
48
+ exited = new Error(`${server.command} exited (${code ?? 'signal'})${stderr.trim() ? `: ${stderr.trim().split('\n').slice(-3).join(' ')}` : ''}`);
49
+ failAll(exited);
50
+ });
51
+ createInterface({ input: child.stdout }).on('line', line => {
52
+ let message;
53
+ try { message = JSON.parse(line); } catch { return; }
54
+ const waiting = pending.get(message.id);
55
+ if (!waiting) return;
56
+ pending.delete(message.id);
57
+ if (message.error) waiting.reject(new Error(`${message.error.message ?? 'MCP error'} (${message.error.code})`));
58
+ else waiting.resolve(message.result ?? {});
59
+ });
60
+ child.stdin.on('error', () => {});
61
+ let id = 0;
62
+ return {
63
+ request(method, params) {
64
+ if (exited) return Promise.reject(exited);
65
+ const current = ++id;
66
+ return new Promise((resolve, reject) => {
67
+ const timer = setTimeout(() => { pending.delete(current); reject(new Error(`${method} got no answer within ${timeoutMs / 1000} s`)); }, timeoutMs);
68
+ pending.set(current, { resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } });
69
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: current, method, params }) + '\n');
70
+ });
71
+ },
72
+ async notify(method) { if (!exited) child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method }) + '\n'); },
73
+ async close() {
74
+ if (child.exitCode !== null || child.signalCode !== null) return;
75
+ const done = new Promise(resolve => child.once('exit', resolve));
76
+ child.stdin.end();
77
+ signal('SIGTERM');
78
+ const timer = setTimeout(() => signal('SIGKILL'), 2000);
79
+ await done;
80
+ clearTimeout(timer);
81
+ },
82
+ };
83
+ }
84
+
85
+ async function httpSession(server, timeoutMs) {
86
+ let sessionId;
87
+ let id = 0;
88
+ const post = async body => {
89
+ const response = await fetch(server.url, {
90
+ method: 'POST',
91
+ headers: { ...(server.headers ?? {}), 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...(sessionId ? { 'mcp-session-id': sessionId } : {}), 'mcp-protocol-version': PROTOCOL },
92
+ body: JSON.stringify(body),
93
+ signal: AbortSignal.timeout(timeoutMs),
94
+ });
95
+ sessionId = response.headers.get('mcp-session-id') ?? sessionId;
96
+ if (!response.ok) throw new Error(`${server.url} answered ${response.status} ${response.statusText}`);
97
+ return response;
98
+ };
99
+ return {
100
+ async request(method, params) {
101
+ const current = ++id;
102
+ const response = await post({ jsonrpc: '2.0', id: current, method, params });
103
+ const text = await response.text();
104
+ // A streamable HTTP server answers with JSON or with server-sent events.
105
+ const messages = (response.headers.get('content-type') ?? '').includes('text/event-stream')
106
+ ? text.split('\n').filter(line => line.startsWith('data:')).map(line => { try { return JSON.parse(line.slice(5)); } catch { return undefined; } })
107
+ : [JSON.parse(text)];
108
+ const message = messages.find(entry => entry?.id === current);
109
+ if (!message) throw new Error(`${method}: no answer in the response`);
110
+ if (message.error) throw new Error(`${message.error.message ?? 'MCP error'} (${message.error.code})`);
111
+ return message.result ?? {};
112
+ },
113
+ async notify(method) { await post({ jsonrpc: '2.0', method }); },
114
+ async close() {
115
+ if (sessionId) await fetch(server.url, { method: 'DELETE', headers: { ...(server.headers ?? {}), 'mcp-session-id': sessionId }, signal: AbortSignal.timeout(timeoutMs) }).catch(() => {});
116
+ },
117
+ };
118
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The portable ALP client (docs/alp/client-sdk.md): the JSON-RPC engine, its errors, the reconnect
3
+ * helper and NDJSON framing. It runs in Node, browsers and React Native without polyfills: no Node
4
+ * built-ins, no process, no Buffer, no filesystem and no ALP core. Transports come separately:
5
+ * `@anhlp/alp-client/websocket` here, the Unix socket and named pipe in the Node entry.
6
+ */
7
+
8
+ /**
9
+ * @typedef {import('./rpc/client.js').AlpTransport} AlpTransport
10
+ * @typedef {import('./rpc/client.js').TransportClose} TransportClose
11
+ * @typedef {import('./rpc/client.js').TransportState} TransportState
12
+ * @typedef {import('./rpc/client.js').AbortSignalLike} AbortSignalLike
13
+ * @typedef {import('./rpc/client.js').RequestOptions} RequestOptions
14
+ * @typedef {import('./rpc/client.js').AlpRpcClientOptions} AlpRpcClientOptions
15
+ * @typedef {import('./rpc/handshake.js').ClientInfo} ClientInfo
16
+ * @typedef {import('./rpc/reconnect.js').ReconnectOptions} ReconnectOptions
17
+ * @typedef {import('./rpc/reconnect.js').ReconnectingClient} ReconnectingClient
18
+ * @typedef {import('./rpc/reconnect.js').ReconnectState} ReconnectState
19
+ * @typedef {import('./rpc/reconnect.js').Backoff} Backoff
20
+ */
21
+ export { PROTOCOL_VERSION, MAX_FRAME, AlpRpcError, ERROR } from '@anhlp/alp-protocol';
22
+ export { AlpRpcClient, DEFAULT_MAX_PENDING } from './rpc/client.js';
23
+ export { AlpClientError, CLIENT_ERROR, isAlpClientError } from './rpc/errors.js';
24
+ export { createLineDecoder, utf8Length } from './rpc/framing.js';
25
+ export { MAX_TIMER_MS, timerDelay } from './rpc/timers.js';
26
+ export { AGENT_CAPABILITY, hello } from './rpc/handshake.js';
27
+ export { backoffDelay, createReconnectingClient, retryable } from './rpc/reconnect.js';
28
+ export { attachments, base64Encode, conversation, sha256Hex, workspaceRegistry } from './rpc/registry.js';
29
+
30
+ export { watchTerminals } from "./rpc/terminal-directory.js";
package/src/prompt.js ADDED
@@ -0,0 +1,64 @@
1
+ import { emitKeypressEvents } from 'node:readline';
2
+
3
+ const dim = text => `\x1b[2m${text}\x1b[22m`;
4
+ const cyan = text => `\x1b[36m${text}\x1b[39m`;
5
+
6
+ export class Cancelled extends Error {
7
+ constructor() { super('Setup cancelled.'); }
8
+ }
9
+
10
+ /**
11
+ * A select box in the terminal: ↑/↓ (or k/j) move, Enter picks, Ctrl-C or Esc cancels.
12
+ * Choices are { label, value, hint? }; `initial` is the value highlighted first.
13
+ * @template T
14
+ * @param {{ message: string, choices: Array<{ label: string, value: T, hint?: string }>, initial?: T }} question
15
+ * @param {{ input?: NodeJS.ReadStream, output?: NodeJS.WriteStream }} [io]
16
+ * @returns {Promise<T>}
17
+ */
18
+ export function select({ message, choices, initial }, { input = process.stdin, output = process.stdout } = {}) {
19
+ let index = Math.max(0, choices.findIndex(choice => choice.value === initial));
20
+ let drawn = 0;
21
+ const draw = () => {
22
+ if (drawn) output.write(`\x1b[${drawn}A\x1b[0J`);
23
+ const lines = [`${cyan('?')} ${message} ${dim('(↑/↓, Enter)')}`, ...choices.map((choice, at) =>
24
+ at === index ? cyan(`❯ ${choice.label}`) + (choice.hint ? ` ${dim(choice.hint)}` : '') : ` ${choice.label}${choice.hint ? ` ${dim(choice.hint)}` : ''}`)];
25
+ output.write(lines.join('\n') + '\n');
26
+ drawn = lines.length;
27
+ };
28
+ return new Promise((resolve, reject) => {
29
+ emitKeypressEvents(input);
30
+ const raw = input.isRaw;
31
+ input.setRawMode?.(true);
32
+ input.resume();
33
+ output.write('\x1b[?25l');
34
+ const done = (settle, value) => {
35
+ input.off('keypress', onKey);
36
+ input.setRawMode?.(raw ?? false);
37
+ input.pause();
38
+ output.write(`\x1b[${drawn}A\x1b[0J\x1b[?25h`);
39
+ if (settle === resolve) output.write(`${cyan('✔')} ${message} ${cyan(choices[index].label)}\n`);
40
+ settle(value);
41
+ };
42
+ const onKey = (text, key = {}) => {
43
+ if ((key.ctrl && key.name === 'c') || key.name === 'escape') return done(reject, new Cancelled());
44
+ if (key.name === 'return' || key.name === 'enter') return done(resolve, choices[index].value);
45
+ if (key.name === 'up' || key.name === 'k') index = (index + choices.length - 1) % choices.length;
46
+ else if (key.name === 'down' || key.name === 'j') index = (index + 1) % choices.length;
47
+ else return;
48
+ draw();
49
+ };
50
+ input.on('keypress', onKey);
51
+ draw();
52
+ });
53
+ }
54
+
55
+ /**
56
+ * A line of text, for a value the list does not offer.
57
+ * @param {string} message
58
+ * @param {{ input?: NodeJS.ReadStream, output?: NodeJS.WriteStream }} [io]
59
+ */
60
+ export async function text(message, { input = process.stdin, output = process.stdout } = {}) {
61
+ const { createInterface } = await import('node:readline/promises');
62
+ const rl = createInterface({ input, output });
63
+ try { return (await rl.question(`${cyan('?')} ${message} `)).trim(); } finally { rl.close(); }
64
+ }