@blaxel/core 0.2.70 → 0.2.71-dev.105

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 (93) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/agents/index.js +2 -19
  3. package/dist/cjs/common/autoload.js +64 -0
  4. package/dist/cjs/common/h2fetch.js +207 -0
  5. package/dist/cjs/common/h2pool.js +137 -0
  6. package/dist/cjs/common/h2warm.js +54 -0
  7. package/dist/cjs/common/settings.js +2 -2
  8. package/dist/cjs/jobs/jobs.js +10 -28
  9. package/dist/cjs/mcp/server.js +4 -65
  10. package/dist/cjs/sandbox/action.js +33 -0
  11. package/dist/cjs/sandbox/drive/drive.js +3 -3
  12. package/dist/cjs/sandbox/filesystem/filesystem.js +1 -2
  13. package/dist/cjs/sandbox/interpreter.js +12 -2
  14. package/dist/cjs/sandbox/process/process.js +2 -2
  15. package/dist/cjs/sandbox/sandbox.js +84 -10
  16. package/dist/cjs/tools/index.js +3 -1
  17. package/dist/cjs/tools/mcpTool.js +15 -43
  18. package/dist/cjs/types/agents/index.d.ts +1 -2
  19. package/dist/cjs/types/common/autoload.d.ts +5 -0
  20. package/dist/cjs/types/common/h2fetch.d.ts +22 -0
  21. package/dist/cjs/types/common/h2pool.d.ts +38 -0
  22. package/dist/cjs/types/common/h2warm.d.ts +2 -0
  23. package/dist/cjs/types/jobs/jobs.d.ts +1 -2
  24. package/dist/cjs/types/sandbox/action.d.ts +8 -1
  25. package/dist/cjs/types/sandbox/client/types.gen.d.ts +11 -0
  26. package/dist/cjs/types/sandbox/interpreter.d.ts +1 -0
  27. package/dist/cjs/types/sandbox/sandbox.d.ts +6 -0
  28. package/dist/cjs/types/sandbox/types.d.ts +2 -0
  29. package/dist/cjs/types/tools/index.d.ts +1 -0
  30. package/dist/cjs-browser/.tsbuildinfo +1 -1
  31. package/dist/cjs-browser/agents/index.js +2 -19
  32. package/dist/cjs-browser/common/autoload.js +64 -0
  33. package/dist/cjs-browser/common/h2fetch.js +4 -0
  34. package/dist/cjs-browser/common/h2pool.js +4 -0
  35. package/dist/cjs-browser/common/h2warm.js +2 -0
  36. package/dist/cjs-browser/common/settings.js +2 -2
  37. package/dist/cjs-browser/jobs/jobs.js +10 -28
  38. package/dist/cjs-browser/mcp/server.js +4 -65
  39. package/dist/cjs-browser/sandbox/action.js +33 -0
  40. package/dist/cjs-browser/sandbox/drive/drive.js +3 -3
  41. package/dist/cjs-browser/sandbox/filesystem/filesystem.js +1 -2
  42. package/dist/cjs-browser/sandbox/interpreter.js +12 -2
  43. package/dist/cjs-browser/sandbox/process/process.js +2 -2
  44. package/dist/cjs-browser/sandbox/sandbox.js +84 -10
  45. package/dist/cjs-browser/tools/index.js +3 -1
  46. package/dist/cjs-browser/tools/mcpTool.js +15 -43
  47. package/dist/cjs-browser/types/agents/index.d.ts +1 -2
  48. package/dist/cjs-browser/types/common/autoload.d.ts +5 -0
  49. package/dist/cjs-browser/types/common/h2fetch.d.ts +22 -0
  50. package/dist/cjs-browser/types/common/h2pool.d.ts +38 -0
  51. package/dist/cjs-browser/types/common/h2warm.d.ts +2 -0
  52. package/dist/cjs-browser/types/jobs/jobs.d.ts +1 -2
  53. package/dist/cjs-browser/types/sandbox/action.d.ts +8 -1
  54. package/dist/cjs-browser/types/sandbox/client/types.gen.d.ts +11 -0
  55. package/dist/cjs-browser/types/sandbox/interpreter.d.ts +1 -0
  56. package/dist/cjs-browser/types/sandbox/sandbox.d.ts +6 -0
  57. package/dist/cjs-browser/types/sandbox/types.d.ts +2 -0
  58. package/dist/cjs-browser/types/tools/index.d.ts +1 -0
  59. package/dist/esm/.tsbuildinfo +1 -1
  60. package/dist/esm/agents/index.js +1 -19
  61. package/dist/esm/common/autoload.js +30 -0
  62. package/dist/esm/common/h2fetch.js +202 -0
  63. package/dist/esm/common/h2pool.js +101 -0
  64. package/dist/esm/common/h2warm.js +48 -0
  65. package/dist/esm/common/settings.js +2 -2
  66. package/dist/esm/jobs/jobs.js +9 -28
  67. package/dist/esm/mcp/server.js +4 -65
  68. package/dist/esm/sandbox/action.js +33 -0
  69. package/dist/esm/sandbox/drive/drive.js +3 -3
  70. package/dist/esm/sandbox/filesystem/filesystem.js +1 -2
  71. package/dist/esm/sandbox/interpreter.js +12 -2
  72. package/dist/esm/sandbox/process/process.js +2 -2
  73. package/dist/esm/sandbox/sandbox.js +51 -10
  74. package/dist/esm/tools/index.js +1 -0
  75. package/dist/esm/tools/mcpTool.js +15 -43
  76. package/dist/esm-browser/.tsbuildinfo +1 -1
  77. package/dist/esm-browser/agents/index.js +1 -19
  78. package/dist/esm-browser/common/autoload.js +30 -0
  79. package/dist/esm-browser/common/h2fetch.js +4 -0
  80. package/dist/esm-browser/common/h2pool.js +4 -0
  81. package/dist/esm-browser/common/h2warm.js +2 -0
  82. package/dist/esm-browser/common/settings.js +2 -2
  83. package/dist/esm-browser/jobs/jobs.js +9 -28
  84. package/dist/esm-browser/mcp/server.js +4 -65
  85. package/dist/esm-browser/sandbox/action.js +33 -0
  86. package/dist/esm-browser/sandbox/drive/drive.js +3 -3
  87. package/dist/esm-browser/sandbox/filesystem/filesystem.js +1 -2
  88. package/dist/esm-browser/sandbox/interpreter.js +12 -2
  89. package/dist/esm-browser/sandbox/process/process.js +2 -2
  90. package/dist/esm-browser/sandbox/sandbox.js +51 -10
  91. package/dist/esm-browser/tools/index.js +1 -0
  92. package/dist/esm-browser/tools/mcpTool.js +15 -43
  93. package/package.json +1 -1
@@ -3,8 +3,7 @@ import { getAgent } from "../client/index.js";
3
3
  import { getForcedUrl, getGlobalUniqueHash } from "../common/internal.js";
4
4
  import { logger } from "../common/logger.js";
5
5
  import { settings } from "../common/settings.js";
6
- import { startSpan } from '../telemetry/telemetry.js';
7
- class BlAgent {
6
+ export class BlAgent {
8
7
  agentName;
9
8
  constructor(agentName) {
10
9
  this.agentName = agentName;
@@ -54,42 +53,25 @@ class BlAgent {
54
53
  }
55
54
  async run(input, headers = {}, params = {}) {
56
55
  logger.debug(`Agent Calling: ${this.agentName}`);
57
- const span = startSpan(this.agentName, {
58
- attributes: {
59
- "agent.name": this.agentName,
60
- "agent.args": JSON.stringify(input),
61
- "span.type": "agent.run",
62
- },
63
- isRoot: false,
64
- });
65
56
  try {
66
57
  const response = await this.call(this.url, input, headers, params);
67
- span.setAttribute("agent.run.result", await response.text());
68
58
  return await response.text();
69
59
  }
70
60
  catch (err) {
71
61
  if (err instanceof Error) {
72
62
  if (!this.fallbackUrl) {
73
- span.setAttribute("agent.run.error", err.stack);
74
63
  throw err;
75
64
  }
76
65
  try {
77
66
  const response = await this.call(this.fallbackUrl, input, headers, params);
78
- span.setAttribute("agent.run.result", await response.text());
79
67
  return await response.text();
80
68
  }
81
69
  catch (err) {
82
- if (err instanceof Error) {
83
- span.setAttribute("agent.run.error", err.stack);
84
- }
85
70
  throw err;
86
71
  }
87
72
  }
88
73
  throw err;
89
74
  }
90
- finally {
91
- span.end();
92
- }
93
75
  }
94
76
  }
95
77
  export const blAgent = (agentName) => {
@@ -21,6 +21,28 @@ for (const interceptor of responseInterceptors) {
21
21
  }
22
22
  // Initialize Sentry for SDK error tracking immediately when module loads
23
23
  initSentry();
24
+ // Background H2 connection warming (Node.js only)
25
+ const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
26
+ /* eslint-disable */
27
+ const isBrowser = typeof globalThis !== "undefined" && globalThis?.window !== undefined;
28
+ if (isNode && !isBrowser) {
29
+ try {
30
+ // Pre-warm edge H2 for the configured region so the first
31
+ // SandboxInstance.create() gets an instant session via the pool.
32
+ // The control-plane client (api.blaxel.ai) stays on regular fetch
33
+ // which already benefits from undici's built-in connection pooling.
34
+ const region = settings.region;
35
+ if (region) {
36
+ import("./h2pool.js").then(({ h2Pool }) => {
37
+ const edgeSuffix = settings.env === "prod" ? "bl.run" : "runv2.blaxel.dev";
38
+ h2Pool.warm(`any.${region}.${edgeSuffix}`);
39
+ }).catch(() => { });
40
+ }
41
+ }
42
+ catch {
43
+ // Silently ignore warming failures
44
+ }
45
+ }
24
46
  // Allow to set custom configuration for browser environment
25
47
  export function initialize(config) {
26
48
  settings.setConfig(config);
@@ -34,3 +56,11 @@ export function initialize(config) {
34
56
  export function authenticate() {
35
57
  return settings.authenticate();
36
58
  }
59
+ /**
60
+ * Close all pooled H2 connections. Call this for explicit cleanup
61
+ * (e.g. in test teardown or before process exit).
62
+ */
63
+ export async function closeConnections() {
64
+ const { h2Pool } = await import("./h2pool.js");
65
+ h2Pool.closeAll();
66
+ }
@@ -0,0 +1,202 @@
1
+ const H2_REQUEST_TIMEOUT_MS = 10_000;
2
+ /**
3
+ * Creates a fetch()-compatible function that sends requests over an existing
4
+ * HTTP/2 session. Falls back to global fetch() if the session is closed,
5
+ * destroyed, or if the H2 request times out.
6
+ */
7
+ export function createH2Fetch(session) {
8
+ return (input) => {
9
+ if (session.closed || session.destroyed) {
10
+ return globalThis.fetch(input);
11
+ }
12
+ return _h2Request(session, input);
13
+ };
14
+ }
15
+ /**
16
+ * Creates a fetch()-compatible function backed by the H2 session pool.
17
+ *
18
+ * Non-blocking: checks the pool cache synchronously. If a warm session is
19
+ * available it's used immediately; otherwise the request goes through
20
+ * regular fetch with zero delay (the pool keeps warming in the background
21
+ * so subsequent calls get H2).
22
+ */
23
+ export function createPoolBackedH2Fetch(pool, domain) {
24
+ return (input) => {
25
+ const session = pool.tryGet(domain);
26
+ if (session) {
27
+ return _h2Request(session, input);
28
+ }
29
+ return globalThis.fetch(input);
30
+ };
31
+ }
32
+ /**
33
+ * Low-level H2 request that takes raw URL + init, skipping Request construction.
34
+ * Used by SandboxAction.h2Fetch() for direct calls from subsystems.
35
+ */
36
+ export function h2RequestDirect(session, url, init) {
37
+ if (session.closed || session.destroyed) {
38
+ return globalThis.fetch(url, init);
39
+ }
40
+ const parsed = new URL(url);
41
+ const method = init?.method || "GET";
42
+ const h2Headers = {
43
+ ":method": method,
44
+ ":path": parsed.pathname + parsed.search,
45
+ ":authority": parsed.host,
46
+ };
47
+ if (init?.headers) {
48
+ const entries = init.headers instanceof Headers
49
+ ? init.headers.entries()
50
+ : Array.isArray(init.headers)
51
+ ? init.headers.values()
52
+ : Object.entries(init.headers).values();
53
+ for (const [key, value] of entries) {
54
+ const k = key.toLowerCase();
55
+ if (k === "host")
56
+ continue;
57
+ h2Headers[k] = value;
58
+ }
59
+ }
60
+ let body;
61
+ if (init?.body) {
62
+ if (typeof init.body === "string") {
63
+ body = Buffer.from(init.body);
64
+ }
65
+ else if (Buffer.isBuffer(init.body)) {
66
+ body = init.body;
67
+ }
68
+ else if (init.body instanceof ArrayBuffer) {
69
+ body = Buffer.from(init.body);
70
+ }
71
+ else if (init.body instanceof Uint8Array) {
72
+ body = Buffer.from(init.body.buffer, init.body.byteOffset, init.body.byteLength);
73
+ }
74
+ else {
75
+ // FormData, ReadableStream, Blob, etc. can't be serialized to Buffer
76
+ // for manual H2 framing — fall back to regular fetch.
77
+ return globalThis.fetch(url, init);
78
+ }
79
+ if (!h2Headers["content-length"]) {
80
+ h2Headers["content-length"] = body.byteLength;
81
+ }
82
+ }
83
+ return _h2Send(session, h2Headers, body, init?.signal ?? null, url, init);
84
+ }
85
+ async function _h2Request(session, input) {
86
+ const url = new URL(input.url);
87
+ const method = input.method || "GET";
88
+ const h2Headers = {
89
+ ":method": method,
90
+ ":path": url.pathname + url.search,
91
+ ":authority": url.host,
92
+ };
93
+ for (const [key, value] of input.headers.entries()) {
94
+ if (key === "host")
95
+ continue;
96
+ h2Headers[key] = value;
97
+ }
98
+ let body;
99
+ if (input.body) {
100
+ body = Buffer.from(await input.arrayBuffer());
101
+ if (!h2Headers["content-length"]) {
102
+ h2Headers["content-length"] = body.byteLength;
103
+ }
104
+ }
105
+ return _h2Send(session, h2Headers, body, input.signal, input.url, {
106
+ method,
107
+ headers: input.headers,
108
+ body,
109
+ });
110
+ }
111
+ function _h2Send(session, h2Headers, body, signal, fallbackUrl, fallbackInit) {
112
+ return new Promise((resolve, reject) => {
113
+ let req;
114
+ try {
115
+ req = session.request(h2Headers);
116
+ }
117
+ catch {
118
+ return globalThis.fetch(fallbackUrl, fallbackInit).then(resolve, reject);
119
+ }
120
+ const timer = setTimeout(() => {
121
+ if (settled)
122
+ return;
123
+ settled = true;
124
+ req.close();
125
+ globalThis.fetch(fallbackUrl, fallbackInit).then(resolve, reject);
126
+ }, H2_REQUEST_TIMEOUT_MS);
127
+ if (signal) {
128
+ if (signal.aborted) {
129
+ clearTimeout(timer);
130
+ req.close();
131
+ reject(new DOMException("The operation was aborted.", "AbortError"));
132
+ return;
133
+ }
134
+ signal.addEventListener("abort", () => {
135
+ clearTimeout(timer);
136
+ req.close();
137
+ if (!settled) {
138
+ settled = true;
139
+ reject(new DOMException("The operation was aborted.", "AbortError"));
140
+ }
141
+ }, { once: true });
142
+ }
143
+ let settled = false;
144
+ req.on("response", (headers) => {
145
+ clearTimeout(timer);
146
+ if (settled)
147
+ return;
148
+ settled = true;
149
+ const status = headers[":status"] ?? 200;
150
+ const resHeaders = new Headers();
151
+ for (const [k, v] of Object.entries(headers)) {
152
+ if (k.startsWith(":"))
153
+ continue;
154
+ if (v === undefined)
155
+ continue;
156
+ resHeaders.set(k, Array.isArray(v) ? v.join(", ") : String(v));
157
+ }
158
+ let streamClosed = false;
159
+ const readable = new ReadableStream({
160
+ start(controller) {
161
+ req.on("data", (chunk) => {
162
+ if (!streamClosed)
163
+ controller.enqueue(new Uint8Array(chunk));
164
+ });
165
+ req.on("end", () => {
166
+ if (!streamClosed) {
167
+ streamClosed = true;
168
+ controller.close();
169
+ }
170
+ });
171
+ req.on("error", (err) => {
172
+ if (!streamClosed) {
173
+ streamClosed = true;
174
+ controller.error(err);
175
+ }
176
+ });
177
+ signal?.addEventListener("abort", () => {
178
+ req.close();
179
+ if (!streamClosed) {
180
+ streamClosed = true;
181
+ controller.error(new DOMException("The operation was aborted.", "AbortError"));
182
+ }
183
+ }, { once: true });
184
+ },
185
+ });
186
+ resolve(new Response(readable, { status, headers: resHeaders }));
187
+ });
188
+ req.on("error", () => {
189
+ clearTimeout(timer);
190
+ if (settled)
191
+ return;
192
+ settled = true;
193
+ globalThis.fetch(fallbackUrl, fallbackInit).then(resolve, reject);
194
+ });
195
+ if (body) {
196
+ req.end(body);
197
+ }
198
+ else {
199
+ req.end();
200
+ }
201
+ });
202
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Singleton H2 session pool keyed by edge domain.
3
+ *
4
+ * - `warm(domain)` starts a background connection (fire-and-forget).
5
+ * - `get(domain)` returns a live session immediately if cached, or awaits
6
+ * an in-flight warming, or establishes a fresh one.
7
+ * - Closed / destroyed sessions are automatically evicted.
8
+ */
9
+ class H2Pool {
10
+ sessions = new Map();
11
+ inflight = new Map();
12
+ _establish = null;
13
+ /**
14
+ * Lazily resolve the establish function so the http2 / tls / dns modules
15
+ * are only imported in Node.js environments.
16
+ */
17
+ async establish(domain) {
18
+ if (!this._establish) {
19
+ const { establishH2 } = await import("./h2warm.js");
20
+ this._establish = establishH2;
21
+ }
22
+ return this._establish(domain);
23
+ }
24
+ /**
25
+ * Fire-and-forget background warming. Safe to call multiple times for
26
+ * the same domain — only one connection attempt per domain at a time.
27
+ */
28
+ warm(domain) {
29
+ const existing = this.sessions.get(domain);
30
+ if (existing && !existing.closed && !existing.destroyed)
31
+ return;
32
+ if (this.inflight.has(domain))
33
+ return;
34
+ const p = this.establish(domain)
35
+ .then((session) => {
36
+ this.sessions.set(domain, session);
37
+ return session;
38
+ })
39
+ .catch(() => null)
40
+ .finally(() => {
41
+ this.inflight.delete(domain);
42
+ });
43
+ this.inflight.set(domain, p);
44
+ }
45
+ /**
46
+ * Synchronous cache check. Returns a live cached session or `null`.
47
+ * Never blocks, never establishes — use for non-blocking fast paths.
48
+ */
49
+ tryGet(domain) {
50
+ const cached = this.sessions.get(domain);
51
+ if (cached && !cached.closed && !cached.destroyed)
52
+ return cached;
53
+ this.sessions.delete(domain);
54
+ return null;
55
+ }
56
+ /**
57
+ * Get a live H2 session for `domain`. Returns immediately from cache,
58
+ * joins an in-flight warming, or starts a new one.
59
+ */
60
+ async get(domain) {
61
+ const fast = this.tryGet(domain);
62
+ if (fast)
63
+ return fast;
64
+ // Join in-flight warming if one exists
65
+ const pending = this.inflight.get(domain);
66
+ if (pending) {
67
+ const session = await pending;
68
+ if (session && !session.closed && !session.destroyed)
69
+ return session;
70
+ }
71
+ // Start fresh, deduplicating concurrent callers via inflight
72
+ // Re-check: another caller may have started a fresh one while we awaited
73
+ const existingInflight = this.inflight.get(domain);
74
+ if (existingInflight)
75
+ return existingInflight;
76
+ const freshCached = this.tryGet(domain);
77
+ if (freshCached)
78
+ return freshCached;
79
+ const p = this.establish(domain)
80
+ .then((session) => {
81
+ this.sessions.set(domain, session);
82
+ return session;
83
+ })
84
+ .catch(() => null)
85
+ .finally(() => {
86
+ this.inflight.delete(domain);
87
+ });
88
+ this.inflight.set(domain, p);
89
+ return p;
90
+ }
91
+ /** Close all sessions (for cleanup). */
92
+ closeAll() {
93
+ for (const [, session] of this.sessions) {
94
+ if (!session.closed && !session.destroyed)
95
+ session.close();
96
+ }
97
+ this.sessions.clear();
98
+ this.inflight.clear();
99
+ }
100
+ }
101
+ export const h2Pool = new H2Pool();
@@ -0,0 +1,48 @@
1
+ import dns from "dns/promises";
2
+ import http2 from "http2";
3
+ import tls from "tls";
4
+ export async function establishH2(sniHostname) {
5
+ let timedOut = false;
6
+ let timer;
7
+ const timeout = new Promise((_, reject) => {
8
+ timer = setTimeout(() => {
9
+ timedOut = true;
10
+ reject(new Error("H2 warm-up timed out"));
11
+ }, 5000);
12
+ });
13
+ const attempt = _establishH2(sniHostname).then((session) => {
14
+ // If the timeout already fired, destroy the orphaned session immediately
15
+ if (timedOut) {
16
+ session.destroy();
17
+ }
18
+ return session;
19
+ });
20
+ return Promise.race([attempt, timeout]).finally(() => clearTimeout(timer));
21
+ }
22
+ async function _establishH2(sniHostname) {
23
+ const { address } = await dns.lookup(sniHostname);
24
+ const tlsSocket = tls.connect({
25
+ host: address,
26
+ port: 443,
27
+ servername: sniHostname,
28
+ ALPNProtocols: ["h2"],
29
+ });
30
+ const session = http2.connect(`https://${sniHostname}:443`, {
31
+ createConnection: () => tlsSocket,
32
+ });
33
+ await new Promise((resolve, reject) => {
34
+ session.on("connect", resolve);
35
+ session.on("error", (err) => {
36
+ // Ensure the TLS socket is cleaned up on connection error
37
+ if (!tlsSocket.destroyed)
38
+ tlsSocket.destroy();
39
+ reject(err);
40
+ });
41
+ });
42
+ // Complete the SETTINGS exchange so the first real request has zero
43
+ // protocol overhead. This RTT is hidden by the parallel createSandbox() call.
44
+ await new Promise((resolve) => session.ping(() => resolve()));
45
+ // Unref so the session doesn't prevent process exit
46
+ session.unref();
47
+ return session;
48
+ }
@@ -3,8 +3,8 @@ import { authentication } from "../authentication/index.js";
3
3
  import { env } from "../common/env.js";
4
4
  import { fs, os, path } from "../common/node.js";
5
5
  // Build info - these placeholders are replaced at build time by build:replace-imports
6
- const BUILD_VERSION = "0.2.70";
7
- const BUILD_COMMIT = "a3bbb13aa4ec149d33f1662d30dfb10ce3683baf";
6
+ const BUILD_VERSION = "0.2.71-dev.105";
7
+ const BUILD_COMMIT = "cd4e249990c84664410df2d7158d13d6342300ed";
8
8
  const BUILD_SENTRY_DSN = "https://fd5e60e1c9820e1eef5ccebb84a07127@o4508714045276160.ingest.us.sentry.io/4510465864564736";
9
9
  // Cache for config.yaml tracking value
10
10
  let configTrackingValue = null;
@@ -1,40 +1,21 @@
1
1
  import { createJobExecution, deleteJobExecution, getJobExecution, listJobExecutions, } from "../client/index.js";
2
2
  import { logger } from "../common/logger.js";
3
3
  import { settings } from "../common/settings.js";
4
- import { startSpan } from "../telemetry/telemetry.js";
5
- class BlJob {
4
+ export class BlJob {
6
5
  jobName;
7
6
  constructor(jobName) {
8
7
  this.jobName = jobName;
9
8
  }
10
9
  async run(tasks, options) {
11
10
  logger.debug(`Job Calling: ${this.jobName}`);
12
- const span = startSpan(this.jobName, {
13
- attributes: {
14
- "job.name": this.jobName,
15
- "span.type": "job.run",
16
- },
17
- isRoot: false,
18
- });
19
- try {
20
- const request = {
21
- tasks,
22
- ...(options?.env && { env: options.env }),
23
- ...(options?.memory && { memory: options.memory }),
24
- ...(options?.executionId && { executionId: options.executionId }),
25
- };
26
- const executionId = await this.createExecution(request);
27
- return executionId;
28
- }
29
- catch (err) {
30
- if (err instanceof Error) {
31
- span.setAttribute("job.run.error", err.stack);
32
- }
33
- throw err;
34
- }
35
- finally {
36
- span.end();
37
- }
11
+ const request = {
12
+ tasks,
13
+ ...(options?.env && { env: options.env }),
14
+ ...(options?.memory && { memory: options.memory }),
15
+ ...(options?.executionId && { executionId: options.executionId }),
16
+ };
17
+ const executionId = await this.createExecution(request);
18
+ return executionId;
38
19
  }
39
20
  /**
40
21
  * Create a new execution for this job and return the execution ID
@@ -2,8 +2,6 @@ import { v4 as uuidv4 } from "uuid";
2
2
  import WebSocket, { WebSocketServer } from "ws";
3
3
  import { env } from "../common/env.js";
4
4
  import { logger } from "../common/logger.js";
5
- import { startSpan } from "../telemetry/telemetry.js";
6
- const spans = new Map();
7
5
  export class BlaxelMcpServerTransport {
8
6
  port;
9
7
  wss;
@@ -38,26 +36,10 @@ export class BlaxelMcpServerTransport {
38
36
  ws,
39
37
  });
40
38
  this.onconnection?.(clientId);
41
- ws.on("message", (data) => {
42
- const span = startSpan("message", {
43
- attributes: {
44
- "mcp.client.id": clientId,
45
- "span.type": "mcp.message",
46
- },
47
- isRoot: false,
48
- });
39
+ ws.on("message", async (data) => {
49
40
  try {
50
41
  const msg = JSON.parse(data.toString());
51
- this.messageHandler?.(msg, clientId);
52
- if ("method" in msg && "id" in msg && "params" in msg) {
53
- span.setAttributes({
54
- "mcp.message.parsed": true,
55
- "mcp.method": msg.method,
56
- "mcp.messageId": msg.id,
57
- "mcp.toolName": msg.params?.name,
58
- });
59
- spans.set(clientId + ":" + msg.id, span);
60
- }
42
+ await this.messageHandler?.(msg, clientId);
61
43
  // Handle msg.id safely
62
44
  const msgId = msg.id ? String(msg.id) : "";
63
45
  const [cId, parsedMsgId] = msgId.split(":");
@@ -65,27 +47,7 @@ export class BlaxelMcpServerTransport {
65
47
  // Use optional chaining for safe access
66
48
  const client = this.clients.get(cId ?? "");
67
49
  if (client?.ws?.readyState === WebSocket.OPEN) {
68
- const msgSpan = spans.get(cId + ":" + (msg.id ?? ""));
69
- try {
70
- client.ws.send(JSON.stringify(msg));
71
- if (msgSpan) {
72
- msgSpan.setAttributes({
73
- "mcp.message.response_sent": true,
74
- });
75
- }
76
- }
77
- catch (err) {
78
- if (msgSpan) {
79
- msgSpan.setStatus("error"); // Error status
80
- msgSpan.recordException(err);
81
- }
82
- throw err;
83
- }
84
- finally {
85
- if (msgSpan) {
86
- msgSpan.end();
87
- }
88
- }
50
+ client.ws.send(JSON.stringify(msg));
89
51
  }
90
52
  else {
91
53
  this.clients.delete(cId);
@@ -94,14 +56,11 @@ export class BlaxelMcpServerTransport {
94
56
  }
95
57
  catch (err) {
96
58
  if (err instanceof Error) {
97
- span.setStatus("error"); // Error status
98
- span.recordException(err);
99
59
  this.onerror?.(err);
100
60
  }
101
61
  else {
102
62
  this.onerror?.(new Error(`Failed to parse message: ${String(err)}`));
103
63
  }
104
- span.end();
105
64
  }
106
65
  });
107
66
  ws.on("close", () => {
@@ -123,27 +82,7 @@ export class BlaxelMcpServerTransport {
123
82
  // Send to specific client
124
83
  const client = this.clients.get(cId);
125
84
  if (client?.ws?.readyState === WebSocket.OPEN) {
126
- const msgSpan = spans.get(cId + ":" + msg.id);
127
- try {
128
- client.ws.send(data);
129
- if (msgSpan) {
130
- msgSpan.setAttributes({
131
- "mcp.message.response_sent": true,
132
- });
133
- }
134
- }
135
- catch (err) {
136
- if (msgSpan) {
137
- msgSpan.setStatus("error"); // Error status
138
- msgSpan.recordException(err);
139
- }
140
- throw err;
141
- }
142
- finally {
143
- if (msgSpan) {
144
- msgSpan.end();
145
- }
146
- }
85
+ client.ws.send(data);
147
86
  }
148
87
  else {
149
88
  this.clients.delete(cId);
@@ -1,4 +1,7 @@
1
1
  import { createClient } from "@hey-api/client-fetch";
2
+ import { interceptors } from "../client/interceptors.js";
3
+ import { responseInterceptors } from "../client/responseInterceptor.js";
4
+ import { createH2Fetch, h2RequestDirect } from "../common/h2fetch.js";
2
5
  import { getForcedUrl, getGlobalUniqueHash } from "../common/internal.js";
3
6
  import { settings } from "../common/settings.js";
4
7
  import { client as defaultClient } from "./client/client.gen.js";
@@ -28,6 +31,7 @@ export class ResponseError extends Error {
28
31
  }
29
32
  export class SandboxAction {
30
33
  sandbox;
34
+ _h2Client = null;
31
35
  constructor(sandbox) {
32
36
  this.sandbox = sandbox;
33
37
  }
@@ -54,8 +58,37 @@ export class SandboxAction {
54
58
  headers: this.sandbox.headers,
55
59
  });
56
60
  }
61
+ const session = this.sandbox.h2Session;
62
+ if (session && !session.closed && !session.destroyed) {
63
+ if (!this._h2Client) {
64
+ this._h2Client = createClient({
65
+ fetch: createH2Fetch(session),
66
+ });
67
+ for (const interceptor of interceptors) {
68
+ // @ts-expect-error - Interceptor is not typed
69
+ this._h2Client.interceptors.request.use(interceptor);
70
+ }
71
+ for (const interceptor of responseInterceptors) {
72
+ this._h2Client.interceptors.response.use(interceptor);
73
+ }
74
+ }
75
+ return this._h2Client;
76
+ }
77
+ // Invalidate cached H2 client when session is no longer usable
78
+ this._h2Client = null;
57
79
  return defaultClient;
58
80
  }
81
+ /**
82
+ * Routes through the H2 session when available, falling back to
83
+ * globalThis.fetch. Uses a direct H2 path that avoids Request allocation.
84
+ */
85
+ h2Fetch(input, init) {
86
+ const session = this.sandbox.h2Session;
87
+ if (session && !session.closed && !session.destroyed) {
88
+ return h2RequestDirect(session, input.toString(), init);
89
+ }
90
+ return globalThis.fetch(input, init);
91
+ }
59
92
  get forcedUrl() {
60
93
  if (this.sandbox.forceUrl)
61
94
  return this.sandbox.forceUrl;