@xiashe/sdk 0.1.38 → 0.1.40
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/http.mjs +6 -5
- package/index.mjs +11 -2
- package/package.json +1 -1
- package/runtimeMcp.mjs +32 -12
package/http.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
2
2
|
export function requestUrl(value) {
|
|
3
|
-
|
|
3
|
+
let url;
|
|
4
|
+
try { url = new URL(value); } catch { throw Error('HTTP_TARGET_INVALID'); }
|
|
4
5
|
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
5
6
|
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || url.password || url.hash) throw Error('HTTP_TARGET_INVALID');
|
|
6
7
|
return url;
|
|
@@ -12,9 +13,9 @@ export async function boundedJsonRequest(url, body, { timeoutMs = 20000, headers
|
|
|
12
13
|
let timer;
|
|
13
14
|
const deadline = new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(Error('REQUEST_TIMEOUT')); }, timeoutMs); });
|
|
14
15
|
const request = async () => {
|
|
15
|
-
const response = await fetch(url, { method, redirect: '
|
|
16
|
+
const response = await fetch(url, { method, redirect: 'manual', signal: controller.signal,
|
|
16
17
|
headers: { 'content-type': 'application/json', ...headers }, ...(method === 'GET' ? {} : { body: JSON.stringify(body ?? {}) }) });
|
|
17
|
-
if (response.status >= 300 && response.status < 400) throw Error('HTTP_REDIRECT_REFUSED');
|
|
18
|
+
if (response.status >= 300 && response.status < 400) { await response.body?.cancel(); throw Error('HTTP_REDIRECT_REFUSED'); }
|
|
18
19
|
if (Number(response.headers.get('content-length')) > maxResponseBytes) { controller.abort(); throw Error('HTTP_RESPONSE_TOO_LARGE'); }
|
|
19
20
|
const reader = response.body?.getReader();
|
|
20
21
|
const chunks = []; let total = 0;
|
|
@@ -28,10 +29,10 @@ export async function boundedJsonRequest(url, body, { timeoutMs = 20000, headers
|
|
|
28
29
|
} finally { reader?.releaseLock(); }
|
|
29
30
|
let payload;
|
|
30
31
|
try { const text = Buffer.concat(chunks).toString('utf8'); payload = text ? JSON.parse(text) : {}; }
|
|
31
|
-
catch { throw Error('HTTP_BAD_JSON'); }
|
|
32
|
+
catch { if (response.ok) throw Error('HTTP_BAD_JSON'); payload = { error: `HTTP_${response.status}` }; }
|
|
32
33
|
return { response, payload };
|
|
33
34
|
};
|
|
34
35
|
try { return await Promise.race([request(), deadline]); }
|
|
35
|
-
catch (error) { if (controller.signal.aborted && error.message !== 'HTTP_RESPONSE_TOO_LARGE') throw Error('REQUEST_TIMEOUT'); throw error; }
|
|
36
|
+
catch (error) { if (controller.signal.aborted && error.message !== 'HTTP_RESPONSE_TOO_LARGE') throw Error('REQUEST_TIMEOUT'); if (error instanceof TypeError && /fetch failed|terminated|network/i.test(error.message)) throw Error('HTTP_NETWORK_ERROR'); throw error; }
|
|
36
37
|
finally { clearTimeout(timer); }
|
|
37
38
|
}
|
package/index.mjs
CHANGED
|
@@ -17,7 +17,7 @@ export { serveRuntimeMcp } from './runtimeMcp.mjs';
|
|
|
17
17
|
|
|
18
18
|
export { safeOutput as redactCredentials } from './outputSafety.mjs';
|
|
19
19
|
|
|
20
|
-
export const VERSION = '0.1.
|
|
20
|
+
export const VERSION = '0.1.40';
|
|
21
21
|
export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
|
|
22
22
|
|
|
23
23
|
export const DEFAULTS = {
|
|
@@ -325,7 +325,16 @@ async function withTimeout(promiseFactory, timeoutMs = HTTP_TIMEOUT_MS) {
|
|
|
325
325
|
export async function postJson(url, body, options = {}) {
|
|
326
326
|
let result;
|
|
327
327
|
try { result = await boundedJsonRequest(url, body, options); }
|
|
328
|
-
catch (error) {
|
|
328
|
+
catch (error) {
|
|
329
|
+
const messages = {
|
|
330
|
+
HTTP_NETWORK_ERROR: 'Unable to reach the server or the connection was interrupted. Check the service address and network; verify the operation status before retrying.',
|
|
331
|
+
HTTP_REDIRECT_REFUSED: 'The server redirected a credential-bearing request. Check the configured service address; no redirect was followed.',
|
|
332
|
+
HTTP_TARGET_INVALID: 'Invalid service address. Use HTTPS, without embedded credentials or a fragment.',
|
|
333
|
+
HTTP_BAD_JSON: 'The server returned an invalid JSON response. Check service health and verify the operation status before retrying.',
|
|
334
|
+
REQUEST_TIMEOUT: 'The request timed out. Its outcome may be unknown; check status before retrying an operation.',
|
|
335
|
+
};
|
|
336
|
+
throw new XiasheError(messages[error.message] ? `${error.message}: ${messages[error.message]}` : error.message, { code: error.message });
|
|
337
|
+
}
|
|
329
338
|
const { response, payload } = result;
|
|
330
339
|
if (!response.ok) throw new XiasheError(payload?.error || payload?.message || `HTTP ${response.status}`, {
|
|
331
340
|
code: payload?.error || `HTTP_${response.status}`, status: response.status
|
package/package.json
CHANGED
package/runtimeMcp.mjs
CHANGED
|
@@ -19,9 +19,10 @@ const safeError = error => /^[A-Z][A-Z_]{1,100}$/.test(error?.message) ? error.m
|
|
|
19
19
|
/** MCP 2025-06-18 stdio: newline-delimited JSON-RPC, bounded input, no stdout logs. */
|
|
20
20
|
export async function serveRuntimeMcp(session, { input = process.stdin, output = process.stdout, signal } = {}) {
|
|
21
21
|
const tools = session.supportsNextTask ? [tool('next_task', 'Acquire a task explicitly assigned to this host. If none is available, respect retryAfterMs; do not run an idle model loop.'), ...runtimeTools] : runtimeTools;
|
|
22
|
-
let initialized = false, ready = false, pending = 0, buffer = '', ended = false;
|
|
22
|
+
let initialized = false, ready = false, pending = 0, buffer = '', ended = false, stopping = false;
|
|
23
23
|
const decoder = new StringDecoder('utf8');
|
|
24
24
|
const inflightIds = new Set();
|
|
25
|
+
const jobs = new Set();
|
|
25
26
|
const send = value => { if (!ended && !output.destroyed) {
|
|
26
27
|
if (output.writableLength > 2 * 1024 * 1024) { stop(); return; }
|
|
27
28
|
output.write(JSON.stringify(value) + '\n');
|
|
@@ -30,11 +31,26 @@ export async function serveRuntimeMcp(session, { input = process.stdin, output =
|
|
|
30
31
|
const error = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
|
|
31
32
|
let resolveDone;
|
|
32
33
|
const done = new Promise(resolve => { resolveDone = resolve; });
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
ended = true;
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
let closing, drainTimer;
|
|
35
|
+
const close = () => closing ??= Promise.resolve().then(() => session.close()).catch(() => {}).finally(() => {
|
|
36
|
+
clearTimeout(drainTimer); ended = true; resolveDone();
|
|
37
|
+
});
|
|
38
|
+
const stop = (drain = false) => {
|
|
39
|
+
if (stopping) return;
|
|
40
|
+
stopping = true; input.pause(); input.removeListener('data', consume);
|
|
41
|
+
if (!drain) ended = true;
|
|
42
|
+
if (drain) drainTimer = setTimeout(abort, 30000);
|
|
43
|
+
// EOF is normal after the final request. Deliver already accepted responses
|
|
44
|
+
// before closing; aborts and broken transports still interrupt immediately.
|
|
45
|
+
void (drain ? Promise.allSettled([...jobs]) : Promise.resolve())
|
|
46
|
+
.then(close);
|
|
47
|
+
};
|
|
48
|
+
const end = () => stop(true);
|
|
49
|
+
const abort = () => {
|
|
50
|
+
if (stopping && !ended) {
|
|
51
|
+
ended = true;
|
|
52
|
+
void close();
|
|
53
|
+
} else stop();
|
|
38
54
|
};
|
|
39
55
|
const handle = async message => {
|
|
40
56
|
const validId = typeof message?.id === 'string' && message.id.length <= 128 || Number.isSafeInteger(message?.id);
|
|
@@ -46,6 +62,7 @@ export async function serveRuntimeMcp(session, { input = process.stdin, output =
|
|
|
46
62
|
if (method === 'notifications/initialized' && initialized) ready = true;
|
|
47
63
|
return;
|
|
48
64
|
}
|
|
65
|
+
if (!params || typeof params !== 'object' || Array.isArray(params)) { error(id, -32602, 'Invalid params'); return; }
|
|
49
66
|
if (inflightIds.has(id)) { error(id, -32600, 'Duplicate in-flight request ID'); return; }
|
|
50
67
|
if (++pending > 8) { pending--; error(id, -32000, 'Too many requests'); return; }
|
|
51
68
|
inflightIds.add(id);
|
|
@@ -75,16 +92,19 @@ export async function serveRuntimeMcp(session, { input = process.stdin, output =
|
|
|
75
92
|
buffer += decoder.write(chunk);
|
|
76
93
|
if (Buffer.byteLength(buffer) > 300000) { error(null, -32600, 'Input limit exceeded'); stop(); return; }
|
|
77
94
|
let offset;
|
|
78
|
-
while (!
|
|
95
|
+
while (!stopping && (offset = buffer.indexOf('\n')) >= 0) {
|
|
79
96
|
const line = buffer.slice(0, offset); buffer = buffer.slice(offset + 1);
|
|
80
97
|
let message;
|
|
81
98
|
try { message = JSON.parse(line); } catch { error(null, -32700, 'Parse error'); continue; }
|
|
82
|
-
|
|
99
|
+
const job = handle(message).catch(() => error(message?.id ?? null, -32603, 'Internal error'));
|
|
100
|
+
jobs.add(job);
|
|
101
|
+
void job.finally(() => jobs.delete(job));
|
|
83
102
|
}
|
|
84
103
|
}
|
|
85
|
-
input.on('data', consume); input.once('end',
|
|
86
|
-
signal?.addEventListener('abort',
|
|
87
|
-
if (signal?.aborted)
|
|
104
|
+
input.on('data', consume); input.once('end', end); input.once('error', abort); output.once('error', abort);
|
|
105
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
106
|
+
if (signal?.aborted) abort();
|
|
88
107
|
await done;
|
|
89
|
-
input.removeListener('end',
|
|
108
|
+
input.removeListener('end', end); input.removeListener('error', abort); output.removeListener('error', abort);
|
|
109
|
+
signal?.removeEventListener('abort', abort);
|
|
90
110
|
}
|