murmur-it 0.0.0-stage → 0.2.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/dist/client.js ADDED
@@ -0,0 +1,210 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createConnection } from 'node:net';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { LineReader, MurmurError, PROTOCOL_VERSION, encodeLine } from './protocol.js';
5
+ export class MurmurClient {
6
+ socket;
7
+ decoder;
8
+ reader;
9
+ pending = new Map();
10
+ onEvent;
11
+ // Set by callers that must react when the broker connection drops (the MCP
12
+ // server ends its wait on it). Invoked once, after pending requests fail.
13
+ onClosed;
14
+ // Auth occupies id 1, so requests start at 2.
15
+ nextId = 2;
16
+ closedState = false;
17
+ constructor(socket, onEvent) {
18
+ this.socket = socket;
19
+ this.decoder = new StringDecoder('utf8');
20
+ this.reader = new LineReader();
21
+ this.onEvent = onEvent;
22
+ socket.on('data', (chunk) => {
23
+ this.onData(this.decoder.write(chunk));
24
+ });
25
+ socket.on('close', () => {
26
+ this.onClose();
27
+ });
28
+ socket.on('error', () => {
29
+ // Socket errors surface through the connect rejection or the close
30
+ // handler, which rejects all pending requests.
31
+ });
32
+ }
33
+ static connect(opts) {
34
+ const timeoutMs = opts.connectTimeoutMs ?? 3000;
35
+ const socket = createConnection(opts.socketPath);
36
+ return new Promise((resolve, reject) => {
37
+ let settled = false;
38
+ let timer = null;
39
+ const finish = (err, client) => {
40
+ if (settled) {
41
+ return;
42
+ }
43
+ settled = true;
44
+ if (timer !== null) {
45
+ clearTimeout(timer);
46
+ }
47
+ if (err !== null) {
48
+ socket.destroy();
49
+ reject(err);
50
+ }
51
+ else if (client !== null) {
52
+ resolve(client);
53
+ }
54
+ };
55
+ timer = setTimeout(() => {
56
+ finish(new MurmurError('broker_down', 'connect to ' + opts.socketPath + ' timed out after ' + String(timeoutMs) + 'ms'), null);
57
+ }, timeoutMs);
58
+ socket.once('error', (err) => {
59
+ finish(new MurmurError('broker_down', 'connect to ' + opts.socketPath + ' failed: ' + err.message), null);
60
+ });
61
+ socket.once('connect', () => {
62
+ const client = new MurmurClient(socket, opts.onEvent);
63
+ client
64
+ .send({ type: 'auth', token: opts.token }, 1)
65
+ .then(() => {
66
+ finish(null, client);
67
+ })
68
+ .catch((err) => {
69
+ if (err instanceof MurmurError) {
70
+ finish(err, null);
71
+ }
72
+ else {
73
+ finish(new MurmurError('internal', err.message), null);
74
+ }
75
+ });
76
+ });
77
+ });
78
+ }
79
+ request(msg) {
80
+ if (this.closed) {
81
+ return Promise.reject(new MurmurError('broker_closed', 'connection to the broker is closed'));
82
+ }
83
+ const id = this.nextId;
84
+ this.nextId += 1;
85
+ return this.send(msg, id);
86
+ }
87
+ close() {
88
+ this.socket.destroy();
89
+ }
90
+ get closed() {
91
+ return this.closedState || this.socket.destroyed;
92
+ }
93
+ // Writes one request line with the given id and stores its resolver. The
94
+ // ok reply resolves with result cast to T; an error reply rejects with a
95
+ // MurmurError carrying the wire error code. The message body is typed as
96
+ // object because Omit over the ClientMessage union keeps only the common
97
+ // keys, which would reject concrete message literals here.
98
+ send(msg, id) {
99
+ return new Promise((resolve, reject) => {
100
+ this.pending.set(id, {
101
+ resolve: (reply) => {
102
+ if (reply.ok) {
103
+ resolve(reply.result);
104
+ }
105
+ else {
106
+ reject(new MurmurError(reply.error.code, reply.error.message));
107
+ }
108
+ },
109
+ reject,
110
+ });
111
+ try {
112
+ this.socket.write(encodeLine({ v: PROTOCOL_VERSION, id, ...msg }));
113
+ }
114
+ catch (err) {
115
+ this.pending.delete(id);
116
+ reject(new MurmurError('broker_closed', 'connection to the broker closed before write: ' + err.message));
117
+ }
118
+ });
119
+ }
120
+ onData(chunk) {
121
+ for (const line of this.reader.feed(chunk)) {
122
+ let parsed;
123
+ try {
124
+ parsed = JSON.parse(line);
125
+ }
126
+ catch (err) {
127
+ this.failAll(new MurmurError('internal', 'broker sent a line that failed JSON parse: ' + err.message));
128
+ this.socket.destroy();
129
+ return;
130
+ }
131
+ if (this.isEvent(parsed)) {
132
+ if (this.onEvent !== undefined) {
133
+ this.onEvent(parsed);
134
+ }
135
+ continue;
136
+ }
137
+ if (!this.isReply(parsed)) {
138
+ // Valid JSON but neither an event nor a reply: treat as a protocol
139
+ // violation, same policy as a parse failure.
140
+ this.failAll(new MurmurError('internal', 'broker sent a line that is neither a reply nor an event'));
141
+ this.socket.destroy();
142
+ return;
143
+ }
144
+ const waiting = this.pending.get(parsed.id);
145
+ if (waiting !== undefined) {
146
+ this.pending.delete(parsed.id);
147
+ waiting.resolve(parsed);
148
+ }
149
+ }
150
+ }
151
+ isEvent(msg) {
152
+ return typeof msg === 'object' && msg !== null && msg.type === 'event';
153
+ }
154
+ isReply(msg) {
155
+ if (typeof msg !== 'object' || msg === null) {
156
+ return false;
157
+ }
158
+ const rec = msg;
159
+ if (typeof rec.id !== 'number' || (rec.ok !== true && rec.ok !== false)) {
160
+ return false;
161
+ }
162
+ if (rec.ok === false && (typeof rec.error !== 'object' || rec.error === null)) {
163
+ return false;
164
+ }
165
+ return true;
166
+ }
167
+ onClose() {
168
+ this.closedState = true;
169
+ this.decoder.end();
170
+ this.failAll(new MurmurError('broker_closed', 'connection to the broker closed'));
171
+ this.onClosed?.();
172
+ }
173
+ failAll(err) {
174
+ const waiting = Array.from(this.pending.values());
175
+ this.pending.clear();
176
+ for (const p of waiting) {
177
+ p.reject(err);
178
+ }
179
+ }
180
+ }
181
+ export function isMurmurError(e) {
182
+ return e instanceof MurmurError;
183
+ }
184
+ export function isBrokerDown(e) {
185
+ return e instanceof MurmurError && (e.code === 'broker_down' || e.code === 'broker_closed');
186
+ }
187
+ // Connects, and when the broker is down and autostart is on (the murmur bin
188
+ // sets MURMUR_AUTOSTART=1; tests and library callers never do), starts one
189
+ // detached broker and retries for up to three seconds.
190
+ export async function connectBroker(opts) {
191
+ try {
192
+ return await MurmurClient.connect(opts);
193
+ }
194
+ catch (err) {
195
+ if (process.env.MURMUR_AUTOSTART !== '1' || !(err instanceof MurmurError) || err.code !== 'broker_down') {
196
+ throw err;
197
+ }
198
+ spawn(process.execPath, [process.argv[1] ?? '', 'serve'], { detached: true, stdio: 'ignore' }).unref();
199
+ for (let attempt = 0; attempt < 30; attempt += 1) {
200
+ await new Promise((resolve) => setTimeout(resolve, 100));
201
+ try {
202
+ return await MurmurClient.connect(opts);
203
+ }
204
+ catch {
205
+ // Still starting.
206
+ }
207
+ }
208
+ throw err;
209
+ }
210
+ }
package/dist/config.js ADDED
@@ -0,0 +1,83 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { MurmurError, newToken } from './protocol.js';
5
+ // Resolution order: explicit envHome argument, then MURMUR_HOME, then
6
+ // ~/.murmur.
7
+ export function getPaths(envHome) {
8
+ const home = envHome ?? process.env.MURMUR_HOME ?? join(homedir(), '.murmur');
9
+ return {
10
+ home,
11
+ socketPath: join(home, 'bus.sock'),
12
+ dbPath: join(home, 'murmur.db'),
13
+ tokenPath: join(home, 'token'),
14
+ };
15
+ }
16
+ // Creates the murmur home directory (mode 0700) and, when missing, the token
17
+ // file (mode 0600) holding a freshly generated random token. Throws a plain
18
+ // Error when permissions cannot be set.
19
+ export function ensureHome(paths) {
20
+ mkdirSync(paths.home, { recursive: true });
21
+ try {
22
+ chmodSync(paths.home, 0o700);
23
+ }
24
+ catch (err) {
25
+ throw new Error('murmur: cannot set mode 0700 on home directory ' + paths.home + ': ' + err.message);
26
+ }
27
+ if (!existsSync(paths.tokenPath)) {
28
+ try {
29
+ writeFileSync(paths.tokenPath, newToken(), { encoding: 'utf8', flag: 'wx', mode: 0o600 });
30
+ }
31
+ catch (err) {
32
+ const code = err.code;
33
+ if (code === 'EEXIST') {
34
+ // Lost a creation race; the token written by the winner stands.
35
+ return;
36
+ }
37
+ throw new Error('murmur: cannot create token file ' + paths.tokenPath + ': ' + err.message);
38
+ }
39
+ try {
40
+ // writeFileSync masks the requested mode with the process umask, so
41
+ // pin the mode explicitly.
42
+ chmodSync(paths.tokenPath, 0o600);
43
+ }
44
+ catch (err) {
45
+ throw new Error('murmur: cannot set mode 0600 on token file ' + paths.tokenPath + ': ' + err.message);
46
+ }
47
+ }
48
+ }
49
+ // Reads and trims the shared token. Throws MurmurError('bad_token') when the
50
+ // file is missing or its trimmed contents are empty.
51
+ export function readToken(paths) {
52
+ let raw;
53
+ try {
54
+ raw = readFileSync(paths.tokenPath, 'utf8');
55
+ }
56
+ catch (err) {
57
+ throw new MurmurError('bad_token', 'cannot read token file ' + paths.tokenPath + ': ' + err.message);
58
+ }
59
+ const token = raw.trim();
60
+ if (token.length === 0) {
61
+ throw new MurmurError('bad_token', 'token file ' + paths.tokenPath + ' is empty');
62
+ }
63
+ return token;
64
+ }
65
+ // Asserts that the home directory is mode 0700 and the token file is mode
66
+ // 0600, otherwise throws MurmurError('internal') naming the offending path.
67
+ export function verifyPerms(paths) {
68
+ let homeMode;
69
+ let tokenMode;
70
+ try {
71
+ homeMode = statSync(paths.home).mode & 0o777;
72
+ tokenMode = statSync(paths.tokenPath).mode & 0o777;
73
+ }
74
+ catch (err) {
75
+ throw new MurmurError('internal', 'cannot stat murmur paths under ' + paths.home + ': ' + err.message);
76
+ }
77
+ if (homeMode !== 0o700) {
78
+ throw new MurmurError('internal', 'home directory ' + paths.home + ' has mode ' + homeMode.toString(8) + ', expected 700');
79
+ }
80
+ if (tokenMode !== 0o600) {
81
+ throw new MurmurError('internal', 'token file ' + paths.tokenPath + ' has mode ' + tokenMode.toString(8) + ', expected 600');
82
+ }
83
+ }