huaweicloud-devkit 2.0.1-next.2 → 2.0.1-next.4
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/README.md +26 -3
- package/README.zh-CN.md +24 -1
- package/package.json +1 -1
- package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.mcp.json +3 -0
- package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/dist/approval-roster.js +2 -0
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +7 -0
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +30 -1
- package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +21 -0
- package/plugins/huaweicloud-core/dist/mcp-server.js +4227 -3049
- package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
- package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +13 -2
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +198 -10
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +11 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +22 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +46 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-upload.js +11 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +20 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +26 -18
- package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +97 -0
- package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx.js +30 -14
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-backend.js +37 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-connections.js +84 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-client.js +229 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-protocol.js +151 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-transport.js +121 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-service-api.js +80 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-upload.js +106 -0
- package/plugins/huaweicloud-core/dist/sandbox/hwlink-connection.js +12 -0
- package/plugins/huaweicloud-core/dist/sandbox/upload-project.js +5 -2
- package/plugins/huaweicloud-core/dist/server-install.js +363 -0
- package/plugins/huaweicloud-core/dist/setup-cli.js +16 -0
- package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
- package/plugins/huaweicloud-core/dist/tools.js +1 -0
- package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
- package/plugins/huaweicloud-core/safety/policy.json +2 -1
- package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +67 -16
- package/plugins/huaweicloud-core/skills/huawei-sandbox/references/devbox-backend.md +78 -0
- package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +14 -0
- package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +2 -1
- package/plugins/huaweicloud-core/src/approval-roster.ts +2 -0
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +7 -0
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +30 -1
- package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +22 -0
- package/plugins/huaweicloud-core/src/mcp-server-remote.ts +68 -5
- package/plugins/huaweicloud-core/src/mcp-server.ts +4 -1
- package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +15 -2
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +206 -11
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +12 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +23 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +49 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-upload.ts +11 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +23 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +27 -17
- package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +105 -0
- package/plugins/huaweicloud-core/src/sandbox/deploy-nginx.ts +36 -18
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-backend.ts +44 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-connections.ts +115 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-client.ts +281 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-protocol.ts +180 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-transport.ts +142 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-service-api.ts +102 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-upload.ts +167 -0
- package/plugins/huaweicloud-core/src/sandbox/hwlink-connection.ts +12 -0
- package/plugins/huaweicloud-core/src/sandbox/upload-project.ts +5 -2
- package/plugins/huaweicloud-core/src/server-install.ts +442 -0
- package/plugins/huaweicloud-core/src/setup-cli.ts +16 -0
- package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
- package/plugins/huaweicloud-core/src/tools.ts +3 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// DevBox EnvD data-plane client (one-shot only): Process/Start (non-PTY),
|
|
2
|
+
// /files read/write, and a stat helper. No PTY, no Process/Connect, no
|
|
3
|
+
// SendInput/SendSignal — the v1 scope pinned by the design.
|
|
4
|
+
|
|
5
|
+
import { Buffer } from 'node:buffer';
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
ConnectFrameDecoder,
|
|
9
|
+
ENVD_API_PORT,
|
|
10
|
+
PROCESS_START_PATH,
|
|
11
|
+
assertConnectContentType,
|
|
12
|
+
buildProcessStartRequest,
|
|
13
|
+
decodeProcessChunk,
|
|
14
|
+
deriveAppPortUrl,
|
|
15
|
+
encodeConnectFrame,
|
|
16
|
+
parseProcessEvent,
|
|
17
|
+
} from './devbox-envd-protocol.ts';
|
|
18
|
+
import { devboxFetch, rewriteDevboxUrl } from './devbox-envd-transport.ts';
|
|
19
|
+
import type { DevboxConnectionRecord } from './devbox-connections.ts';
|
|
20
|
+
|
|
21
|
+
export interface DevboxExecResult {
|
|
22
|
+
stdout: string;
|
|
23
|
+
stderr: string;
|
|
24
|
+
exitCode: number;
|
|
25
|
+
pid?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class DevboxEnvdHttpError extends Error {
|
|
29
|
+
readonly status: number;
|
|
30
|
+
readonly auth: boolean;
|
|
31
|
+
readonly detail: string | undefined;
|
|
32
|
+
|
|
33
|
+
constructor(status: number, message: string, detail?: string) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = 'DevboxEnvdHttpError';
|
|
36
|
+
this.status = status;
|
|
37
|
+
this.auth = status === 401 || status === 403;
|
|
38
|
+
this.detail = detail;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function envdHeaders(connection: DevboxConnectionRecord): Record<string, string> {
|
|
43
|
+
const headers: Record<string, string> = {
|
|
44
|
+
Cookie: `relay_token=${connection.connectToken}`,
|
|
45
|
+
'E2B-Sandbox-Id': connection.sandboxId,
|
|
46
|
+
'E2B-Sandbox-Port': String(ENVD_API_PORT),
|
|
47
|
+
};
|
|
48
|
+
if (connection.envdAccessToken) headers['X-Access-Token'] = connection.envdAccessToken;
|
|
49
|
+
return headers;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function timeoutError(timeoutMs: number): Error & { exitCode: number } {
|
|
53
|
+
return Object.assign(
|
|
54
|
+
new Error(`sandbox exec: command timed out after ${timeoutMs}ms (the remote process may still be running).`),
|
|
55
|
+
{ exitCode: 124, timeout: true },
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function isAbort(error: unknown): boolean {
|
|
60
|
+
return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function responseError(response: Awaited<ReturnType<typeof devboxFetch>>): Promise<DevboxEnvdHttpError> {
|
|
64
|
+
let detail: string | undefined;
|
|
65
|
+
try {
|
|
66
|
+
const text = (await response.text()).slice(0, 500);
|
|
67
|
+
const parsed: unknown = JSON.parse(text);
|
|
68
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
69
|
+
const rec = parsed as Record<string, unknown>;
|
|
70
|
+
detail =
|
|
71
|
+
(typeof rec.message === 'string' && rec.message) || (typeof rec.error === 'string' && rec.error) || undefined;
|
|
72
|
+
}
|
|
73
|
+
} catch {
|
|
74
|
+
// non-JSON body: status alone is the contract
|
|
75
|
+
}
|
|
76
|
+
return new DevboxEnvdHttpError(
|
|
77
|
+
response.status,
|
|
78
|
+
`DevBox EnvD request failed with HTTP ${response.status}${detail ? `: ${detail}` : ''}`,
|
|
79
|
+
detail,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Runs one command to completion (`/bin/bash -l -c <command>`) and collects
|
|
85
|
+
* stdout/stderr/exit code. The client aborts at timeoutMs; the abort surfaces
|
|
86
|
+
* with exitCode 124 (the hwexec async branch treats that as an uncertain start).
|
|
87
|
+
*/
|
|
88
|
+
export async function execDevboxOneShot(
|
|
89
|
+
connection: DevboxConnectionRecord,
|
|
90
|
+
command: string,
|
|
91
|
+
timeoutMs: number,
|
|
92
|
+
): Promise<DevboxExecResult> {
|
|
93
|
+
const payload = buildProcessStartRequest(command);
|
|
94
|
+
const body = encodeConnectFrame(payload);
|
|
95
|
+
const headers: Record<string, string> = {
|
|
96
|
+
...envdHeaders(connection),
|
|
97
|
+
'Connect-Protocol-Version': '1',
|
|
98
|
+
'Content-Type': 'application/connect+json',
|
|
99
|
+
'Connect-Timeout-Ms': String(Math.max(1, Math.round(timeoutMs))),
|
|
100
|
+
'Keepalive-Ping-Interval': '50',
|
|
101
|
+
};
|
|
102
|
+
const url = new URL(PROCESS_START_PATH, `${connection.envdUrl.replace(/\/$/, '')}/`).toString();
|
|
103
|
+
const controller = new AbortController();
|
|
104
|
+
const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs));
|
|
105
|
+
try {
|
|
106
|
+
let response: Awaited<ReturnType<typeof devboxFetch>>;
|
|
107
|
+
try {
|
|
108
|
+
response = await devboxFetch(url, {
|
|
109
|
+
method: 'POST',
|
|
110
|
+
headers,
|
|
111
|
+
body: body as unknown as BodyInit,
|
|
112
|
+
signal: controller.signal,
|
|
113
|
+
});
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (isAbort(error)) throw timeoutError(timeoutMs);
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
if (!response.ok) throw await responseError(response);
|
|
119
|
+
assertConnectContentType(response.headers.get('content-type'));
|
|
120
|
+
if (!response.body) throw new Error('DevBox EnvD returned an empty Connect stream.');
|
|
121
|
+
|
|
122
|
+
const reader = response.body.getReader();
|
|
123
|
+
const decoder = new ConnectFrameDecoder();
|
|
124
|
+
const stdoutDecoder = new TextDecoder('utf-8');
|
|
125
|
+
const stderrDecoder = new TextDecoder('utf-8');
|
|
126
|
+
const stdout: string[] = [];
|
|
127
|
+
const stderr: string[] = [];
|
|
128
|
+
let pid: number | undefined;
|
|
129
|
+
let exitCode: number | undefined;
|
|
130
|
+
let endError: { code: string; message: string } | undefined;
|
|
131
|
+
try {
|
|
132
|
+
for (;;) {
|
|
133
|
+
const { done, value } = await reader.read();
|
|
134
|
+
if (done) break;
|
|
135
|
+
const fed = decoder.feed(value);
|
|
136
|
+
for (const eventPayload of fed.events) {
|
|
137
|
+
const event = parseProcessEvent(eventPayload);
|
|
138
|
+
if (event.pid !== undefined) pid = event.pid;
|
|
139
|
+
const out = decodeProcessChunk(event.stdoutBase64);
|
|
140
|
+
if (out) {
|
|
141
|
+
const text = stdoutDecoder.decode(out, { stream: true });
|
|
142
|
+
if (text) stdout.push(text);
|
|
143
|
+
}
|
|
144
|
+
const err = decodeProcessChunk(event.stderrBase64);
|
|
145
|
+
if (err) {
|
|
146
|
+
const text = stderrDecoder.decode(err, { stream: true });
|
|
147
|
+
if (text) stderr.push(text);
|
|
148
|
+
}
|
|
149
|
+
if (event.exitCode !== undefined) exitCode = event.exitCode;
|
|
150
|
+
}
|
|
151
|
+
if (fed.endError) {
|
|
152
|
+
endError = fed.endError;
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
decoder.finish();
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (isAbort(error)) throw timeoutError(timeoutMs);
|
|
159
|
+
throw error;
|
|
160
|
+
} finally {
|
|
161
|
+
try {
|
|
162
|
+
await reader.cancel();
|
|
163
|
+
} catch {
|
|
164
|
+
// stream may already be closed
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
stdout.push(stdoutDecoder.decode());
|
|
168
|
+
stderr.push(stderrDecoder.decode());
|
|
169
|
+
if (endError) {
|
|
170
|
+
throw new Error(`DevBox EnvD process failed (${endError.code}): ${endError.message}`);
|
|
171
|
+
}
|
|
172
|
+
if (exitCode === undefined) {
|
|
173
|
+
throw new Error('DevBox EnvD command stream ended without an exit status.');
|
|
174
|
+
}
|
|
175
|
+
return { stdout: stdout.join(''), stderr: stderr.join(''), exitCode, pid };
|
|
176
|
+
} finally {
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function filesUrl(envdUrl: string, path: string): string {
|
|
182
|
+
if (!path.startsWith('/')) throw new Error('sandbox file path must be absolute.');
|
|
183
|
+
const url = new URL('/files', `${envdUrl.replace(/\/$/, '')}/`);
|
|
184
|
+
url.searchParams.set('path', path);
|
|
185
|
+
return url.toString();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function writeDevboxFile(
|
|
189
|
+
connection: DevboxConnectionRecord,
|
|
190
|
+
remotePath: string,
|
|
191
|
+
data: Uint8Array,
|
|
192
|
+
timeoutMs = 120000,
|
|
193
|
+
): Promise<void> {
|
|
194
|
+
const response = await devboxFetch(
|
|
195
|
+
filesUrl(connection.envdUrl, remotePath),
|
|
196
|
+
{
|
|
197
|
+
method: 'POST',
|
|
198
|
+
headers: { ...envdHeaders(connection), 'Content-Type': 'application/octet-stream' },
|
|
199
|
+
body: data as unknown as BodyInit,
|
|
200
|
+
},
|
|
201
|
+
timeoutMs,
|
|
202
|
+
);
|
|
203
|
+
if (!response.ok) throw await responseError(response);
|
|
204
|
+
await response.text();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export async function readDevboxFile(
|
|
208
|
+
connection: DevboxConnectionRecord,
|
|
209
|
+
remotePath: string,
|
|
210
|
+
timeoutMs = 120000,
|
|
211
|
+
): Promise<Uint8Array> {
|
|
212
|
+
const response = await devboxFetch(
|
|
213
|
+
filesUrl(connection.envdUrl, remotePath),
|
|
214
|
+
{ method: 'GET', headers: envdHeaders(connection) },
|
|
215
|
+
timeoutMs,
|
|
216
|
+
);
|
|
217
|
+
if (!response.ok) throw await responseError(response);
|
|
218
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export async function statDevboxPath(
|
|
222
|
+
connection: DevboxConnectionRecord,
|
|
223
|
+
remotePath: string,
|
|
224
|
+
timeoutMs = 30000,
|
|
225
|
+
): Promise<Record<string, unknown> | undefined> {
|
|
226
|
+
const url = new URL('/filesystem.Filesystem/Stat', `${connection.envdUrl.replace(/\/$/, '')}/`).toString();
|
|
227
|
+
const response = await devboxFetch(
|
|
228
|
+
url,
|
|
229
|
+
{
|
|
230
|
+
method: 'POST',
|
|
231
|
+
headers: {
|
|
232
|
+
...envdHeaders(connection),
|
|
233
|
+
'Connect-Protocol-Version': '1',
|
|
234
|
+
'Content-Type': 'application/json',
|
|
235
|
+
},
|
|
236
|
+
body: JSON.stringify({ path: remotePath }),
|
|
237
|
+
},
|
|
238
|
+
timeoutMs,
|
|
239
|
+
);
|
|
240
|
+
if (!response.ok) throw await responseError(response);
|
|
241
|
+
const text = await response.text();
|
|
242
|
+
if (!text) return undefined;
|
|
243
|
+
try {
|
|
244
|
+
const parsed: unknown = JSON.parse(text);
|
|
245
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
246
|
+
? (parsed as Record<string, unknown>)
|
|
247
|
+
: undefined;
|
|
248
|
+
} catch {
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Client-side probe of the public app-port URL (no EnvD token needed).
|
|
255
|
+
* Used by deploy_check and expose_tunnel on the devbox backend.
|
|
256
|
+
*/
|
|
257
|
+
export async function probeDevboxAppUrl(
|
|
258
|
+
envdUrl: string,
|
|
259
|
+
port: number,
|
|
260
|
+
timeoutMs = 10000,
|
|
261
|
+
): Promise<{ url: string; status: number; ok: boolean }> {
|
|
262
|
+
const url = devboxAppPortUrl(envdUrl, port);
|
|
263
|
+
try {
|
|
264
|
+
const response = await devboxFetch(url, { method: 'GET' }, timeoutMs);
|
|
265
|
+
return { url, status: response.status, ok: response.status >= 200 && response.status < 400 };
|
|
266
|
+
} catch {
|
|
267
|
+
return { url, status: 0, ok: false };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function devboxAppPortUrl(envdUrl: string, port: number): string {
|
|
272
|
+
// The test pool advertises a devbox-test host that does not resolve publicly;
|
|
273
|
+
// the explicit DEVBOX_TEST_GATEWAY_HOST override makes the URL the developer
|
|
274
|
+
// receives actually reachable. Production (no override) returns it unchanged.
|
|
275
|
+
return rewriteDevboxUrl(deriveAppPortUrl(envdUrl, port));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Reads a whole local file as a Uint8Array (node:fs kept out of the wire module). */
|
|
279
|
+
export function bytesFromBuffer(buffer: Buffer): Uint8Array {
|
|
280
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
281
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Pure DevBox EnvD wire contract (no I/O, no network): the ConnectRPC JSON
|
|
2
|
+
// frame codec for one-shot Process/Start plus the URL/header derivations.
|
|
3
|
+
// Pinned by test/devbox-envd-protocol.test.ts against the SDK-generated wire
|
|
4
|
+
// shapes verified in devbox-temp/TEST-FINDINGS.md.
|
|
5
|
+
|
|
6
|
+
import { Buffer } from 'node:buffer';
|
|
7
|
+
|
|
8
|
+
export const ENVD_API_PORT = 49983;
|
|
9
|
+
export const PROCESS_START_PATH = '/process.Process/Start';
|
|
10
|
+
export const CONNECT_CONTENT_TYPE = 'application/connect+json';
|
|
11
|
+
|
|
12
|
+
const FLAG_END_STREAM = 0x02;
|
|
13
|
+
const FLAG_COMPRESSED = 0x01;
|
|
14
|
+
|
|
15
|
+
/** One Connect envelope: 1 flag byte + 4-byte big-endian length + JSON body. */
|
|
16
|
+
export function encodeConnectFrame(value: unknown): Uint8Array {
|
|
17
|
+
const data = Buffer.from(JSON.stringify(value), 'utf8');
|
|
18
|
+
const frame = Buffer.allocUnsafe(5 + data.length);
|
|
19
|
+
frame.writeUInt8(0, 0);
|
|
20
|
+
frame.writeUInt32BE(data.length, 1);
|
|
21
|
+
data.copy(frame, 5);
|
|
22
|
+
return frame;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ProcessStartOptions {
|
|
26
|
+
envs?: Record<string, string>;
|
|
27
|
+
cwd?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The exact body `Commands.run` sends: `/bin/bash -l -c <command>`, no PTY. */
|
|
31
|
+
export function buildProcessStartRequest(command: string, options: ProcessStartOptions = {}): Record<string, unknown> {
|
|
32
|
+
if (!command || !command.trim()) {
|
|
33
|
+
throw new Error('sandbox exec: command must not be blank.');
|
|
34
|
+
}
|
|
35
|
+
const processBody: Record<string, unknown> = {
|
|
36
|
+
cmd: '/bin/bash',
|
|
37
|
+
args: ['-l', '-c', command],
|
|
38
|
+
envs: { ...(options.envs ?? {}) },
|
|
39
|
+
};
|
|
40
|
+
if (options.cwd) processBody.cwd = options.cwd;
|
|
41
|
+
return { process: processBody, stdin: false };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ProcessEvent {
|
|
45
|
+
pid?: number;
|
|
46
|
+
/** Base64 chunks: the client must decode with a streaming TextDecoder. */
|
|
47
|
+
stdoutBase64?: string;
|
|
48
|
+
stderrBase64?: string;
|
|
49
|
+
exitCode?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function objectValue(value: unknown): Record<string, unknown> | undefined {
|
|
53
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function decodeProcessChunk(base64: unknown): Uint8Array | undefined {
|
|
57
|
+
if (typeof base64 !== 'string') return undefined;
|
|
58
|
+
// Strict shape validation mirrors the SDK: junk must not decode as binary.
|
|
59
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(base64)) {
|
|
60
|
+
throw new Error('DevBox EnvD returned invalid base64 process output.');
|
|
61
|
+
}
|
|
62
|
+
return Buffer.from(base64, 'base64');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function parseProcessEvent(payload: Record<string, unknown>): ProcessEvent {
|
|
66
|
+
const event = objectValue(payload.event);
|
|
67
|
+
if (!event) return {};
|
|
68
|
+
const out: ProcessEvent = {};
|
|
69
|
+
const start = objectValue(event.start);
|
|
70
|
+
if (start && typeof start.pid === 'number' && Number.isSafeInteger(start.pid) && start.pid > 0) {
|
|
71
|
+
out.pid = start.pid;
|
|
72
|
+
}
|
|
73
|
+
const data = objectValue(event.data);
|
|
74
|
+
if (data) {
|
|
75
|
+
if (typeof data.stdout === 'string') out.stdoutBase64 = data.stdout;
|
|
76
|
+
if (typeof data.stderr === 'string') out.stderrBase64 = data.stderr;
|
|
77
|
+
}
|
|
78
|
+
const end = objectValue(event.end);
|
|
79
|
+
if (end) {
|
|
80
|
+
// EnvD omits exitCode on success (the platform sends
|
|
81
|
+
// {exited:true,status:"exited"}); the SDK's contract defaults it to 0.
|
|
82
|
+
const raw = end.exitCode ?? end.exit_code ?? 0;
|
|
83
|
+
const exitCode = Number(raw);
|
|
84
|
+
if (Number.isFinite(exitCode)) out.exitCode = exitCode;
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface ConnectEndError {
|
|
90
|
+
code: string;
|
|
91
|
+
message: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface ConnectChunkResult {
|
|
95
|
+
events: Record<string, unknown>[];
|
|
96
|
+
endError?: ConnectEndError;
|
|
97
|
+
ended: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Incremental Connect stream decoder. Returns complete message payloads;
|
|
102
|
+
* the 0x02 end-stream frame carries an optional `{error:{code,message}}`.
|
|
103
|
+
*/
|
|
104
|
+
export class ConnectFrameDecoder {
|
|
105
|
+
private buffer: Buffer = Buffer.alloc(0);
|
|
106
|
+
private ended = false;
|
|
107
|
+
|
|
108
|
+
feed(chunk: Uint8Array): ConnectChunkResult {
|
|
109
|
+
if (this.ended && chunk.length > 0) {
|
|
110
|
+
throw new Error('DevBox EnvD sent data after the Connect stream ended.');
|
|
111
|
+
}
|
|
112
|
+
this.buffer = Buffer.concat([this.buffer, Buffer.from(chunk)]);
|
|
113
|
+
const events: Record<string, unknown>[] = [];
|
|
114
|
+
let endError: ConnectEndError | undefined;
|
|
115
|
+
while (this.buffer.length >= 5) {
|
|
116
|
+
const flags = this.buffer.readUInt8(0);
|
|
117
|
+
const size = this.buffer.readUInt32BE(1);
|
|
118
|
+
if (this.buffer.length < size + 5) break;
|
|
119
|
+
const body = this.buffer.subarray(5, size + 5);
|
|
120
|
+
this.buffer = this.buffer.subarray(size + 5);
|
|
121
|
+
if ((flags & FLAG_COMPRESSED) !== 0) {
|
|
122
|
+
throw new Error('DevBox EnvD returned a compressed Connect message (not supported).');
|
|
123
|
+
}
|
|
124
|
+
let payload: Record<string, unknown> = {};
|
|
125
|
+
if (body.length > 0) {
|
|
126
|
+
try {
|
|
127
|
+
const parsed: unknown = JSON.parse(body.toString('utf8'));
|
|
128
|
+
payload = objectValue(parsed) ?? {};
|
|
129
|
+
} catch {
|
|
130
|
+
throw new Error('DevBox EnvD returned invalid Connect JSON.');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if ((flags & FLAG_END_STREAM) !== 0) {
|
|
134
|
+
this.ended = true;
|
|
135
|
+
const error = objectValue(payload.error);
|
|
136
|
+
if (error) {
|
|
137
|
+
endError = {
|
|
138
|
+
code: typeof error.code === 'string' ? error.code : 'unknown',
|
|
139
|
+
message: typeof error.message === 'string' ? error.message : 'EnvD request failed',
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
if (this.buffer.length > 0) {
|
|
143
|
+
throw new Error('DevBox EnvD sent data after the Connect stream ended.');
|
|
144
|
+
}
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
events.push(payload);
|
|
148
|
+
}
|
|
149
|
+
return { events, endError, ended: this.ended };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
finish(): void {
|
|
153
|
+
if (this.buffer.length > 0) {
|
|
154
|
+
throw new Error('DevBox EnvD returned a truncated Connect stream.');
|
|
155
|
+
}
|
|
156
|
+
if (!this.ended) {
|
|
157
|
+
throw new Error('DevBox EnvD closed the Connect stream without a trailer.');
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function assertConnectContentType(contentType: string | null): void {
|
|
163
|
+
const base = (contentType ?? '').split(';', 1)[0]?.trim().toLowerCase();
|
|
164
|
+
if (base !== CONNECT_CONTENT_TYPE) {
|
|
165
|
+
throw new Error(`DevBox EnvD returned an invalid content type (${contentType ?? 'missing'}).`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** EnvD host names embed the API port: `<tunnel>-49983.domain` -> `<tunnel>-<port>.domain`. */
|
|
170
|
+
export function deriveAppPortUrl(envdUrl: string, port: number): string {
|
|
171
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535) {
|
|
172
|
+
throw new Error(`sandbox preview: invalid app port ${port}.`);
|
|
173
|
+
}
|
|
174
|
+
const url = new URL(envdUrl);
|
|
175
|
+
url.hostname = url.hostname.replace(/-49983(?=\.|$)/, `-${port}`);
|
|
176
|
+
url.pathname = '/';
|
|
177
|
+
url.search = '';
|
|
178
|
+
url.hash = '';
|
|
179
|
+
return url.toString();
|
|
180
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// The ONLY devbox module allowed to touch undici. The normal path rides
|
|
2
|
+
// fetchWithProxy (system proxy posture); the test-only TLS/DNS switches build
|
|
3
|
+
// a dedicated undici Agent. Production defaults stay strict TLS + real DNS.
|
|
4
|
+
|
|
5
|
+
import { fetchWithProxy } from '../../proxy/proxy-agent.ts';
|
|
6
|
+
import { isDevboxBackend } from './devbox-backend.ts';
|
|
7
|
+
|
|
8
|
+
export interface DevboxResponseLike {
|
|
9
|
+
ok: boolean;
|
|
10
|
+
status: number;
|
|
11
|
+
headers: { get(name: string): string | null };
|
|
12
|
+
body: ReadableStream<Uint8Array> | null;
|
|
13
|
+
text(): Promise<string>;
|
|
14
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type UndiciModule = typeof import('undici');
|
|
18
|
+
type Dispatcher = import('undici').Dispatcher;
|
|
19
|
+
|
|
20
|
+
let testDispatcher: Dispatcher | undefined;
|
|
21
|
+
let testDispatcherKey = '';
|
|
22
|
+
let insecureWarningEmitted = false;
|
|
23
|
+
|
|
24
|
+
function testOverridesActive(): boolean {
|
|
25
|
+
if (!isDevboxBackend()) return false;
|
|
26
|
+
return (
|
|
27
|
+
process.env.DEVBOX_TLS_INSECURE === '1' ||
|
|
28
|
+
Boolean(process.env.DEVBOX_TEST_GATEWAY_HOST) ||
|
|
29
|
+
Boolean(process.env.DEVBOX_TEST_GATEWAY_IP)
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const NODE_UNDICI_SPECIFIER = 'node:undici';
|
|
34
|
+
|
|
35
|
+
async function importUndici(): Promise<UndiciModule> {
|
|
36
|
+
try {
|
|
37
|
+
// Node exposes the bundled client as `node:undici`; fall back to the npm package.
|
|
38
|
+
return (await import(NODE_UNDICI_SPECIFIER)) as UndiciModule;
|
|
39
|
+
} catch {
|
|
40
|
+
return await import('undici');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Test gateway rewrite (explicit env only): the test pool advertises a
|
|
46
|
+
* `devbox-test.hwtunnel.com` host that does not resolve publicly; keep the
|
|
47
|
+
* tunnel-id label and swap the gateway suffix.
|
|
48
|
+
*/
|
|
49
|
+
export function rewriteDevboxUrl(raw: string): string {
|
|
50
|
+
const testHost = process.env.DEVBOX_TEST_GATEWAY_HOST;
|
|
51
|
+
if (!testOverridesActive() || !testHost) return raw;
|
|
52
|
+
let url: URL;
|
|
53
|
+
try {
|
|
54
|
+
url = new URL(raw);
|
|
55
|
+
} catch {
|
|
56
|
+
return raw;
|
|
57
|
+
}
|
|
58
|
+
if (url.hostname.endsWith(`.${testHost}`) || url.hostname === testHost) return raw;
|
|
59
|
+
const label = url.hostname.split('.')[0];
|
|
60
|
+
if (label) url.hostname = `${label}.${testHost}`;
|
|
61
|
+
return url.toString();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function getTestDispatcher(): Promise<Dispatcher | undefined> {
|
|
65
|
+
if (!testOverridesActive()) return undefined;
|
|
66
|
+
const tlsInsecure = process.env.DEVBOX_TLS_INSECURE === '1';
|
|
67
|
+
const testHost = process.env.DEVBOX_TEST_GATEWAY_HOST ?? '';
|
|
68
|
+
const testIp = process.env.DEVBOX_TEST_GATEWAY_IP ?? '';
|
|
69
|
+
const key = `${tlsInsecure ? '1' : '0'}|${testHost}|${testIp}`;
|
|
70
|
+
if (testDispatcher && testDispatcherKey === key) return testDispatcher;
|
|
71
|
+
const { Agent } = await importUndici();
|
|
72
|
+
const connectOptions: Record<string, unknown> = { rejectUnauthorized: !tlsInsecure };
|
|
73
|
+
if (testIp) {
|
|
74
|
+
const dns = await import('node:dns');
|
|
75
|
+
type LookupCallback = (
|
|
76
|
+
err: NodeJS.ErrnoException | null,
|
|
77
|
+
address?: string | ReadonlyArray<{ address: string; family: number }>,
|
|
78
|
+
family?: number,
|
|
79
|
+
) => void;
|
|
80
|
+
connectOptions.lookup = (hostname: string, options: { all?: boolean } | number, callback: LookupCallback) => {
|
|
81
|
+
const wantsAll = typeof options === 'object' && options !== null && options.all === true;
|
|
82
|
+
if (testHost && hostname.endsWith(`.${testHost}`)) {
|
|
83
|
+
if (wantsAll) return callback(null, [{ address: testIp, family: 4 }]);
|
|
84
|
+
return callback(null, testIp, 4);
|
|
85
|
+
}
|
|
86
|
+
return (dns.lookup as unknown as (host: string, opts: unknown, cb: LookupCallback) => void)(
|
|
87
|
+
hostname,
|
|
88
|
+
options,
|
|
89
|
+
callback,
|
|
90
|
+
);
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
testDispatcher = new Agent({ connect: connectOptions });
|
|
94
|
+
testDispatcherKey = key;
|
|
95
|
+
if (!insecureWarningEmitted && (tlsInsecure || testHost || testIp)) {
|
|
96
|
+
insecureWarningEmitted = true;
|
|
97
|
+
console.warn(
|
|
98
|
+
'[devbox] TEST-only transport overrides active (DEVBOX_TLS_INSECURE / DEVBOX_TEST_GATEWAY_*). ' +
|
|
99
|
+
'Never set these in production.',
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
return testDispatcher;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** DevBox data/API fetch: proxy-aware in production, explicit test Agent otherwise. */
|
|
106
|
+
export async function devboxFetch(
|
|
107
|
+
url: string,
|
|
108
|
+
init: RequestInit = {},
|
|
109
|
+
timeoutMs?: number,
|
|
110
|
+
): Promise<DevboxResponseLike> {
|
|
111
|
+
const rewritten = rewriteDevboxUrl(url);
|
|
112
|
+
const signal =
|
|
113
|
+
timeoutMs !== undefined
|
|
114
|
+
? init.signal
|
|
115
|
+
? AbortSignal.any([init.signal, AbortSignal.timeout(timeoutMs)])
|
|
116
|
+
: AbortSignal.timeout(timeoutMs)
|
|
117
|
+
: init.signal;
|
|
118
|
+
const merged: RequestInit = signal ? { ...init, signal } : init;
|
|
119
|
+
const dispatcher = await getTestDispatcher();
|
|
120
|
+
if (!dispatcher) {
|
|
121
|
+
return (await fetchWithProxy(rewritten, merged)) as unknown as DevboxResponseLike;
|
|
122
|
+
}
|
|
123
|
+
const { fetch: undiciFetch } = await importUndici();
|
|
124
|
+
const response = await undiciFetch(rewritten, {
|
|
125
|
+
...merged,
|
|
126
|
+
dispatcher,
|
|
127
|
+
} as unknown as Parameters<typeof undiciFetch>[1]);
|
|
128
|
+
return response as unknown as DevboxResponseLike;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function closeDevboxTestDispatcher(): Promise<void> {
|
|
132
|
+
if (testDispatcher) {
|
|
133
|
+
try {
|
|
134
|
+
await (testDispatcher as { close(): Promise<void> }).close();
|
|
135
|
+
} catch {
|
|
136
|
+
// best-effort test cleanup
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
testDispatcher = undefined;
|
|
140
|
+
testDispatcherKey = '';
|
|
141
|
+
insecureWarningEmitted = false;
|
|
142
|
+
}
|