runwork 0.9.4 → 0.10.1

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 (49) hide show
  1. package/dist/agents/__tests__/intro-skill.test.js +6 -2
  2. package/dist/agents/codex.js +9 -3
  3. package/dist/api/__tests__/client.test.js +10 -2
  4. package/dist/api/client.js +5 -4
  5. package/dist/auth/__tests__/login-flow.test.js +57 -81
  6. package/dist/auth/__tests__/store.test.js +35 -6
  7. package/dist/commands/__tests__/info-merge.test.d.ts +1 -0
  8. package/dist/commands/__tests__/info-merge.test.js +55 -0
  9. package/dist/commands/__tests__/upgrade.test.js +25 -42
  10. package/dist/commands/clone.d.ts +2 -2
  11. package/dist/commands/clone.js +39 -7
  12. package/dist/commands/dev.js +9 -1
  13. package/dist/commands/endpoints.js +2 -1
  14. package/dist/commands/files.js +3 -2
  15. package/dist/commands/info.d.ts +141 -0
  16. package/dist/commands/info.js +29 -7
  17. package/dist/commands/init.d.ts +2 -2
  18. package/dist/commands/init.js +34 -5
  19. package/dist/commands/upgrade.js +4 -3
  20. package/dist/commands/welcome.js +2 -2
  21. package/dist/devtools/registry-data.d.ts +7 -0
  22. package/dist/devtools/registry-data.js +1 -0
  23. package/dist/generated/version.d.ts +1 -1
  24. package/dist/generated/version.js +1 -1
  25. package/dist/git/__tests__/credentials.test.js +4 -4
  26. package/dist/git/__tests__/identity.test.d.ts +1 -0
  27. package/dist/git/__tests__/identity.test.js +146 -0
  28. package/dist/git/__tests__/preflight.test.d.ts +1 -0
  29. package/dist/git/__tests__/preflight.test.js +36 -0
  30. package/dist/git/auto-commit.js +8 -2
  31. package/dist/git/credentials.js +1 -1
  32. package/dist/git/identity.d.ts +44 -0
  33. package/dist/git/identity.js +133 -0
  34. package/dist/git/preflight.d.ts +28 -0
  35. package/dist/git/preflight.js +50 -0
  36. package/dist/git/sync.js +3 -1
  37. package/dist/health/__tests__/cli-distribution-checks.test.js +25 -28
  38. package/dist/health/checks.js +3 -2
  39. package/dist/index.js +32 -1
  40. package/dist/utils/__tests__/format-error.test.d.ts +1 -0
  41. package/dist/utils/__tests__/format-error.test.js +43 -0
  42. package/dist/utils/__tests__/http.test.d.ts +1 -0
  43. package/dist/utils/__tests__/http.test.js +381 -0
  44. package/dist/utils/agent-guidance.js +10 -3
  45. package/dist/utils/format-error.d.ts +10 -0
  46. package/dist/utils/format-error.js +38 -0
  47. package/dist/utils/http.d.ts +46 -0
  48. package/dist/utils/http.js +421 -0
  49. package/package.json +3 -2
@@ -0,0 +1,421 @@
1
+ /**
2
+ * Minimal `fetch`-like HTTP client built on `node:http` / `node:https`.
3
+ *
4
+ * Why this exists rather than calling `fetch` directly:
5
+ * 1) Single seam for diagnostics, retries, transport swaps, etc., without
6
+ * touching every call site.
7
+ * 2) Opt-in `curl` transport (set `RUNWORK_HTTP_TRANSPORT=curl`) as a
8
+ * break-glass: it shells out to the system `curl` binary so HTTP runs
9
+ * in a subprocess, immune to any runtime regression in the Bun-compiled
10
+ * binary. We've kept it after needing it once on an older Bun version.
11
+ *
12
+ * Default transport is `node:https` on every platform. Surface mirrors
13
+ * enough of the standard `Response` API for call sites to swap from
14
+ * `fetch(...)` to `httpFetch(...)` with no other change. Out of scope:
15
+ * streaming bodies, AbortController, ReadableStream request bodies, the
16
+ * `cache` option. This is a workaround layer, not a fetch polyfill.
17
+ */
18
+ import { request as httpRequest } from 'node:http';
19
+ import { request as httpsRequest } from 'node:https';
20
+ import { URL } from 'node:url';
21
+ import { spawn } from 'node:child_process';
22
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
23
+ import { tmpdir } from 'node:os';
24
+ import { join } from 'node:path';
25
+ import { createBrotliDecompress, createGunzip, createInflate, createInflateRaw, } from 'node:zlib';
26
+ const MAX_REDIRECTS = 10;
27
+ let transportOverride = 'auto';
28
+ export function __setTransportForTests(t) { transportOverride = t; }
29
+ function pickTransport() {
30
+ if (transportOverride === 'curl')
31
+ return 'curl';
32
+ if (transportOverride === 'node')
33
+ return 'node';
34
+ const env = (process.env.RUNWORK_HTTP_TRANSPORT || '').toLowerCase().trim();
35
+ if (env === 'curl')
36
+ return 'curl';
37
+ return 'node';
38
+ }
39
+ export async function httpFetch(url, init = {}) {
40
+ const transport = pickTransport();
41
+ if (transport === 'curl')
42
+ return curlFetch(url, init);
43
+ return doRequest(url, init, 0);
44
+ }
45
+ async function doRequest(url, init, redirectCount) {
46
+ const parsed = new URL(url);
47
+ const isHttps = parsed.protocol === 'https:';
48
+ const isHttp = parsed.protocol === 'http:';
49
+ if (!isHttps && !isHttp) {
50
+ throw new Error(`Unsupported protocol "${parsed.protocol}" -- only http: and https: are supported.`);
51
+ }
52
+ const requestFn = isHttps ? httpsRequest : httpRequest;
53
+ const headers = normalizeHeaders(init.headers);
54
+ const method = (init.method || 'GET').toUpperCase();
55
+ const isBodylessMethod = method === 'GET' || method === 'HEAD';
56
+ const bodyBuffer = isBodylessMethod ? null : bodyToBuffer(init.body);
57
+ if (bodyBuffer && headers['content-length'] === undefined) {
58
+ headers['content-length'] = String(bodyBuffer.byteLength);
59
+ }
60
+ // Match `fetch`'s default of advertising compression support. We
61
+ // transparently decompress gzip/deflate/br responses below.
62
+ if (headers['accept-encoding'] === undefined) {
63
+ headers['accept-encoding'] = 'gzip, deflate, br';
64
+ }
65
+ const requestOptions = {
66
+ method,
67
+ headers,
68
+ };
69
+ return new Promise((resolve, reject) => {
70
+ const req = requestFn(url, requestOptions, (res) => {
71
+ const status = res.statusCode ?? 0;
72
+ // Follow redirects manually so behavior matches `fetch`. We wait for
73
+ // the previous response to fully drain before starting the recursive
74
+ // request: guarantees socket cleanup ordering and avoids leaking
75
+ // the previous request when the new one fails.
76
+ const location = res.headers.location;
77
+ if (status >= 300 && status < 400 && location && redirectCount < MAX_REDIRECTS) {
78
+ res.resume();
79
+ res.once('end', () => {
80
+ let nextUrl;
81
+ try {
82
+ nextUrl = new URL(location, url).toString();
83
+ }
84
+ catch (err) {
85
+ reject(err);
86
+ return;
87
+ }
88
+ const shouldDowngradeToGet = status === 303 ||
89
+ ((status === 301 || status === 302) && method !== 'GET' && method !== 'HEAD');
90
+ const nextInit = shouldDowngradeToGet
91
+ ? { ...init, method: 'GET', body: undefined }
92
+ : init;
93
+ doRequest(nextUrl, nextInit, redirectCount + 1).then(resolve, reject);
94
+ });
95
+ res.once('error', reject);
96
+ return;
97
+ }
98
+ // Decompress gzip / deflate / br transparently to match fetch.
99
+ const decoded = decompressedStream(res);
100
+ const chunks = [];
101
+ decoded.on('data', (chunk) => {
102
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
103
+ });
104
+ decoded.on('end', () => {
105
+ const buffer = Buffer.concat(chunks);
106
+ // For HEAD responses there is no body; preserve the empty buffer.
107
+ resolve(buildResponse(url, res, status, buffer));
108
+ });
109
+ decoded.on('error', reject);
110
+ // Surface upstream socket errors too when we are reading through a
111
+ // decompressor (the transformed stream wouldn't otherwise see them).
112
+ if (decoded !== res) {
113
+ res.on('error', reject);
114
+ }
115
+ });
116
+ req.on('error', reject);
117
+ if (bodyBuffer)
118
+ req.write(bodyBuffer);
119
+ req.end();
120
+ });
121
+ }
122
+ function normalizeHeaders(input) {
123
+ const out = {};
124
+ if (!input)
125
+ return out;
126
+ if (input instanceof Headers) {
127
+ input.forEach((value, key) => {
128
+ out[key.toLowerCase()] = value;
129
+ });
130
+ return out;
131
+ }
132
+ for (const [key, value] of Object.entries(input)) {
133
+ if (value === undefined || value === null)
134
+ continue;
135
+ out[key.toLowerCase()] = String(value);
136
+ }
137
+ return out;
138
+ }
139
+ function bodyToBuffer(body) {
140
+ if (body === undefined || body === null)
141
+ return null;
142
+ if (typeof body === 'string')
143
+ return Buffer.from(body, 'utf-8');
144
+ if (Buffer.isBuffer(body))
145
+ return body;
146
+ if (body instanceof Uint8Array)
147
+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
148
+ if (body instanceof ArrayBuffer)
149
+ return Buffer.from(new Uint8Array(body));
150
+ throw new TypeError('Unsupported request body type');
151
+ }
152
+ function decompressedStream(res) {
153
+ // Per RFC 7230, Content-Encoding may be a comma-separated list of
154
+ // transformations applied in order. Unwrap them in reverse, but in
155
+ // practice servers send a single encoding so the simple cases dominate.
156
+ const raw = (res.headers['content-encoding'] || '').toString().toLowerCase().trim();
157
+ if (!raw || raw === 'identity')
158
+ return res;
159
+ const encodings = raw.split(',').map((s) => s.trim()).filter(Boolean).reverse();
160
+ let stream = res;
161
+ for (const enc of encodings) {
162
+ let decoder = null;
163
+ if (enc === 'gzip' || enc === 'x-gzip')
164
+ decoder = createGunzip();
165
+ else if (enc === 'br')
166
+ decoder = createBrotliDecompress();
167
+ else if (enc === 'deflate')
168
+ decoder = createInflate();
169
+ else if (enc === 'deflate-raw')
170
+ decoder = createInflateRaw();
171
+ else
172
+ continue; // unknown encoding -- pass bytes through
173
+ stream.pipe(decoder);
174
+ stream = decoder;
175
+ }
176
+ return stream;
177
+ }
178
+ function buildResponse(url, res, status, buffer) {
179
+ const headers = new Headers();
180
+ for (const [name, value] of Object.entries(res.headers)) {
181
+ if (value === undefined)
182
+ continue;
183
+ if (Array.isArray(value)) {
184
+ for (const v of value)
185
+ headers.append(name, v);
186
+ }
187
+ else {
188
+ headers.set(name, value);
189
+ }
190
+ }
191
+ return {
192
+ ok: status >= 200 && status < 300,
193
+ status,
194
+ statusText: res.statusMessage ?? '',
195
+ headers,
196
+ url,
197
+ async text() {
198
+ return buffer.toString('utf-8');
199
+ },
200
+ async json() {
201
+ const text = buffer.toString('utf-8');
202
+ return JSON.parse(text);
203
+ },
204
+ async arrayBuffer() {
205
+ // Slice the underlying buffer so the returned ArrayBuffer matches the
206
+ // exact byte range and is independent of Node's internal pool.
207
+ const copy = new Uint8Array(buffer.byteLength);
208
+ copy.set(buffer);
209
+ return copy.buffer;
210
+ },
211
+ };
212
+ }
213
+ // ────────────────────────────────────────────────────────────────────────
214
+ // curl-based transport (Windows workaround)
215
+ //
216
+ // On Windows we spawn `curl.exe` for every HTTP call so we never touch
217
+ // Bun's broken HTTP runtime in the standalone binary. The subprocess
218
+ // approach trades a few tens of milliseconds of process-spawn overhead per
219
+ // request for rock-solid reliability. Curl ships at
220
+ // C:\Windows\System32\curl.exe on Windows 10+ since 2018.
221
+ //
222
+ // Layout:
223
+ // - body → written by curl to a temp file (--output)
224
+ // - response hdrs → written by curl to a temp file (--dump-header)
225
+ // - status/url → printed by curl to stdout via --write-out
226
+ //
227
+ // We never let body bytes share a stream with metadata, so binary
228
+ // downloads (zip skeletons, presigned URL fetches) round-trip cleanly.
229
+ // ────────────────────────────────────────────────────────────────────────
230
+ async function curlFetch(url, init) {
231
+ return curlFetchOnce(url, init, 0);
232
+ }
233
+ async function curlFetchOnce(url, init, redirectCount) {
234
+ // Quick URL sanity check so we throw the same way the node:https path
235
+ // does for unsupported protocols, before paying the spawn cost.
236
+ const parsed = new URL(url);
237
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
238
+ throw new Error(`Unsupported protocol "${parsed.protocol}" -- only http: and https: are supported.`);
239
+ }
240
+ const headers = normalizeHeaders(init.headers);
241
+ const method = (init.method || 'GET').toUpperCase();
242
+ const isBodyless = method === 'GET' || method === 'HEAD';
243
+ const bodyBuffer = isBodyless ? null : bodyToBuffer(init.body);
244
+ if (headers['accept-encoding'] === undefined) {
245
+ headers['accept-encoding'] = 'identity';
246
+ }
247
+ // Per-call temp directory keeps cleanup simple and concurrent calls from
248
+ // racing on shared filenames.
249
+ const tmp = mkdtempSync(join(tmpdir(), 'runwork-curl-'));
250
+ const bodyOutPath = join(tmp, 'body.bin');
251
+ const headerOutPath = join(tmp, 'headers.txt');
252
+ const args = [
253
+ '--silent',
254
+ '--show-error',
255
+ // We deliberately do NOT pass --location. curl's redirect-method
256
+ // semantics differ subtly from fetch's (notably curl can preserve
257
+ // POST across 303 in some versions despite the spec). We follow
258
+ // redirects ourselves below so behavior matches the node:https
259
+ // transport exactly.
260
+ '--output', bodyOutPath, // body to file (binary safe)
261
+ '--dump-header', headerOutPath, // response headers to file
262
+ '--write-out', '%{http_code}\n%{url_effective}\n',
263
+ ];
264
+ if (method === 'HEAD') {
265
+ // --head sends HEAD AND tells curl not to expect a body, otherwise
266
+ // curl hangs waiting for body bytes. The downside is that --head also
267
+ // writes the response headers into the --output body file -- we work
268
+ // around that below by ignoring the body buffer when method is HEAD.
269
+ args.push('--head');
270
+ }
271
+ else if (method !== 'GET') {
272
+ args.push('--request', method);
273
+ }
274
+ // Curl's default already follows fetch semantics on 301/302/303 (downgrade
275
+ // POST to GET). We do NOT pass --post30x because those flags violate that
276
+ // default and force POST to be preserved across redirects.
277
+ for (const [name, value] of Object.entries(headers)) {
278
+ args.push('--header', `${name}: ${value}`);
279
+ }
280
+ if (bodyBuffer) {
281
+ // Read request body from stdin so we don't have to write it to disk.
282
+ args.push('--data-binary', '@-');
283
+ }
284
+ args.push(url);
285
+ // Async spawn: spawnSync would block the event loop, which deadlocks
286
+ // unit tests (the test server lives in the same Node worker, can't
287
+ // service curl's connection while we're blocked). The async path is
288
+ // also strictly nicer for any future caller that wants to overlap
289
+ // requests.
290
+ const result = await new Promise((resolve) => {
291
+ const child = spawn('curl', args, { windowsHide: true });
292
+ const stdoutChunks = [];
293
+ const stderrChunks = [];
294
+ child.stdout.on('data', (c) => stdoutChunks.push(c));
295
+ child.stderr.on('data', (c) => stderrChunks.push(c));
296
+ child.on('error', (err) => resolve({
297
+ status: -1,
298
+ stdout: Buffer.concat(stdoutChunks).toString('utf-8'),
299
+ stderr: Buffer.concat(stderrChunks).toString('utf-8'),
300
+ error: err,
301
+ }));
302
+ child.on('close', (code) => resolve({
303
+ status: code ?? -1,
304
+ stdout: Buffer.concat(stdoutChunks).toString('utf-8'),
305
+ stderr: Buffer.concat(stderrChunks).toString('utf-8'),
306
+ }));
307
+ if (bodyBuffer) {
308
+ child.stdin.write(bodyBuffer);
309
+ }
310
+ child.stdin.end();
311
+ });
312
+ if (result.error) {
313
+ safeRm(tmp);
314
+ throw result.error;
315
+ }
316
+ const stdoutLines = result.stdout.trim().split(/\r?\n/);
317
+ const statusLine = stdoutLines[0] || '0';
318
+ const finalUrl = stdoutLines[1] || url;
319
+ const status = Number.parseInt(statusLine, 10) || 0;
320
+ if (status === 0) {
321
+ // curl never received a response, or exited before writing the status.
322
+ const stderr = result.stderr.trim();
323
+ safeRm(tmp);
324
+ throw new Error(`curl failed (exit ${result.status}): ${stderr || 'no error output'}`);
325
+ }
326
+ let bodyBuf;
327
+ try {
328
+ bodyBuf = readFileSync(bodyOutPath);
329
+ }
330
+ catch {
331
+ bodyBuf = Buffer.alloc(0);
332
+ }
333
+ // For HEAD, --head causes curl to write the response status line + headers
334
+ // into the body output file (since there is no real body to write). Strip
335
+ // it so callers see an empty body, matching fetch's HEAD behavior.
336
+ if (method === 'HEAD') {
337
+ bodyBuf = Buffer.alloc(0);
338
+ }
339
+ let headerText = '';
340
+ try {
341
+ headerText = readFileSync(headerOutPath, 'utf-8');
342
+ }
343
+ catch {
344
+ // best-effort
345
+ }
346
+ safeRm(tmp);
347
+ // After redirects curl writes one header block per hop; the LAST block is
348
+ // the response we actually want to expose to the caller.
349
+ const blocks = headerText.split(/\r?\n\r?\n/).map((b) => b.trim()).filter(Boolean);
350
+ const finalBlock = blocks[blocks.length - 1] || '';
351
+ const finalLines = finalBlock.split(/\r?\n/);
352
+ // Pull statusText off the HTTP/x.y NNN <reason> status line if present.
353
+ let statusText = '';
354
+ if (finalLines.length > 0 && finalLines[0].startsWith('HTTP/')) {
355
+ const match = finalLines[0].match(/^HTTP\/\S+\s+\d+\s*(.*)$/);
356
+ if (match)
357
+ statusText = match[1].trim();
358
+ }
359
+ const responseHeaders = new Headers();
360
+ for (const line of finalLines) {
361
+ if (line.startsWith('HTTP/'))
362
+ continue;
363
+ const colon = line.indexOf(':');
364
+ if (colon < 0)
365
+ continue;
366
+ const name = line.slice(0, colon).trim();
367
+ const value = line.slice(colon + 1).trim();
368
+ if (!name)
369
+ continue;
370
+ responseHeaders.append(name, value);
371
+ }
372
+ // Manual redirect handling so curl and node:https behave identically.
373
+ // 303 always downgrades to GET; 301/302 downgrade non-GET/HEAD to GET;
374
+ // 307/308 preserve method and body.
375
+ const location = responseHeaders.get('location');
376
+ if (status >= 300 && status < 400 && location && redirectCount < MAX_REDIRECTS) {
377
+ let nextUrl;
378
+ try {
379
+ nextUrl = new URL(location, url).toString();
380
+ }
381
+ catch (err) {
382
+ throw err;
383
+ }
384
+ const shouldDowngradeToGet = status === 303 ||
385
+ ((status === 301 || status === 302) && method !== 'GET' && method !== 'HEAD');
386
+ const nextInit = shouldDowngradeToGet
387
+ ? { ...init, method: 'GET', body: undefined }
388
+ : init;
389
+ return curlFetchOnce(nextUrl, nextInit, redirectCount + 1);
390
+ }
391
+ // Mirror the node-path warning on unexpected encoding so the diagnostics
392
+ // are consistent across platforms.
393
+ const enc = (responseHeaders.get('content-encoding') || '').toLowerCase().trim();
394
+ if (enc && enc !== 'identity') {
395
+ try {
396
+ process.stderr.write(`[http] warning: server returned Content-Encoding: ${enc} despite Accept-Encoding: identity; ` +
397
+ `body returned as raw bytes (${url}).\n`);
398
+ }
399
+ catch { /* ignore */ }
400
+ }
401
+ return {
402
+ ok: status >= 200 && status < 300,
403
+ status,
404
+ statusText,
405
+ headers: responseHeaders,
406
+ url: finalUrl,
407
+ async text() { return bodyBuf.toString('utf-8'); },
408
+ async json() { return JSON.parse(bodyBuf.toString('utf-8')); },
409
+ async arrayBuffer() {
410
+ const copy = new Uint8Array(bodyBuf.byteLength);
411
+ copy.set(bodyBuf);
412
+ return copy.buffer;
413
+ },
414
+ };
415
+ }
416
+ function safeRm(path) {
417
+ try {
418
+ rmSync(path, { recursive: true, force: true });
419
+ }
420
+ catch { /* best-effort */ }
421
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runwork",
3
- "version": "0.9.4",
3
+ "version": "0.10.1",
4
4
  "description": "CLI for Runwork: develop, preview, and deploy Runwork apps from your local machine.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "Runwork <info@runwork.ai> (https://www.runwork.ai)",
@@ -56,7 +56,8 @@
56
56
  "vitest": "^3.2.0"
57
57
  },
58
58
  "engines": {
59
- "node": ">=22.5.0"
59
+ "node": ">=22.5.0",
60
+ "bun": ">=1.3.13"
60
61
  },
61
62
  "files": [
62
63
  "dist/**/*.js",