@dev-anywhere/proxy 0.4.72 → 0.4.74

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/serve.js CHANGED
@@ -41,19 +41,21 @@ import {
41
41
  createFSM,
42
42
  createIpcReader,
43
43
  createWorkerReader,
44
+ decodeFileStreamFrame,
44
45
  defineFSM,
45
46
  encodeBinaryFrame,
47
+ encodeFileStreamFrame,
46
48
  isCompactCommandText,
47
49
  providerValues,
48
50
  serializeControl,
49
51
  serializeIpc,
50
52
  serializeWorkerMsg
51
- } from "./chunk-ID6ZXJRH.js";
53
+ } from "./chunk-IHIFDLM4.js";
52
54
  import {
53
55
  buildProviderEnv,
54
56
  loadConfig,
55
57
  saveAgentCliPath
56
- } from "./chunk-4543KN27.js";
58
+ } from "./chunk-2JSCH6DW.js";
57
59
  import {
58
60
  atomicWriteFileSync
59
61
  } from "./chunk-NQDJ6QAM.js";
@@ -79,7 +81,7 @@ import {
79
81
 
80
82
  // src/serve.ts
81
83
  import { createServer as createServer2 } from "net";
82
- import { unlinkSync as unlinkSync2, writeFileSync as writeFileSync4, chmodSync, rmSync as rmSync2 } from "fs";
84
+ import { unlinkSync as unlinkSync2, writeFileSync as writeFileSync2, chmodSync, rmSync as rmSync2 } from "fs";
83
85
 
84
86
  // src/serve/session-manager.ts
85
87
  import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
@@ -701,8 +703,12 @@ var RelayConnection = class extends EventEmitter {
701
703
  })
702
704
  );
703
705
  });
704
- this.ws.on("message", (data) => {
706
+ this.ws.on("message", (data, isBinary) => {
705
707
  const buf = data;
708
+ if (isBinary) {
709
+ this.emit("binary", buf);
710
+ return;
711
+ }
706
712
  if (buf.length > MAX_JSON_MESSAGE_SIZE) {
707
713
  serviceLogger.warn(
708
714
  { size: buf.length },
@@ -1244,7 +1250,7 @@ function extractConversationPayload(msg) {
1244
1250
  return null;
1245
1251
  }
1246
1252
  async function extractTitleAndCwd(filePath) {
1247
- return new Promise((resolve4) => {
1253
+ return new Promise((resolve3) => {
1248
1254
  const rl = createInterface({
1249
1255
  input: createReadStream(filePath, { encoding: "utf-8" }),
1250
1256
  crlfDelay: Infinity
@@ -1272,10 +1278,10 @@ async function extractTitleAndCwd(filePath) {
1272
1278
  }
1273
1279
  });
1274
1280
  rl.on("close", () => {
1275
- if (!resolved) resolve4({ title, cwd });
1276
- else resolve4({ title, cwd });
1281
+ if (!resolved) resolve3({ title, cwd });
1282
+ else resolve3({ title, cwd });
1277
1283
  });
1278
- rl.on("error", () => resolve4({ title, cwd }));
1284
+ rl.on("error", () => resolve3({ title, cwd }));
1279
1285
  });
1280
1286
  }
1281
1287
  async function collectJsonlFiles(root) {
@@ -1297,7 +1303,7 @@ async function collectJsonlFiles(root) {
1297
1303
  return files;
1298
1304
  }
1299
1305
  async function extractCodexTitleAndCwd(filePath) {
1300
- return new Promise((resolve4) => {
1306
+ return new Promise((resolve3) => {
1301
1307
  const rl = createInterface({
1302
1308
  input: createReadStream(filePath, { encoding: "utf-8" }),
1303
1309
  crlfDelay: Infinity
@@ -1321,8 +1327,8 @@ async function extractCodexTitleAndCwd(filePath) {
1321
1327
  } catch {
1322
1328
  }
1323
1329
  });
1324
- rl.on("close", () => resolve4({ id, title, cwd }));
1325
- rl.on("error", () => resolve4({ id, title, cwd }));
1330
+ rl.on("close", () => resolve3({ id, title, cwd }));
1331
+ rl.on("error", () => resolve3({ id, title, cwd }));
1326
1332
  });
1327
1333
  }
1328
1334
  function extractCodexUserText(payload) {
@@ -2158,7 +2164,7 @@ var WorkerRegistry = class {
2158
2164
  }
2159
2165
  waitForReady(sessionId, timeoutMs = 15e3) {
2160
2166
  if (this.readySessions.has(sessionId)) return Promise.resolve();
2161
- return new Promise((resolve4, reject) => {
2167
+ return new Promise((resolve3, reject) => {
2162
2168
  const timeout = setTimeout(() => {
2163
2169
  const waiters2 = this.readyWaiters.get(sessionId);
2164
2170
  if (waiters2) {
@@ -2168,7 +2174,7 @@ var WorkerRegistry = class {
2168
2174
  reject(new Error(`Worker did not report ready within ${timeoutMs}ms`));
2169
2175
  }, timeoutMs);
2170
2176
  timeout.unref?.();
2171
- const waiter = { resolve: resolve4, reject, timeout };
2177
+ const waiter = { resolve: resolve3, reject, timeout };
2172
2178
  const waiters = this.readyWaiters.get(sessionId) ?? /* @__PURE__ */ new Set();
2173
2179
  waiters.add(waiter);
2174
2180
  this.readyWaiters.set(sessionId, waiters);
@@ -2210,7 +2216,7 @@ var WorkerRegistry = class {
2210
2216
  return workerPid;
2211
2217
  }
2212
2218
  connect(sessionId, sockPath) {
2213
- return new Promise((resolve4) => {
2219
+ return new Promise((resolve3) => {
2214
2220
  const sock = connect(sockPath);
2215
2221
  sock.on("connect", () => {
2216
2222
  this.sockets.set(sessionId, sock);
@@ -2226,9 +2232,9 @@ var WorkerRegistry = class {
2226
2232
  );
2227
2233
  sock.on("close", () => this.onDisconnect(sessionId));
2228
2234
  sock.on("error", () => this.onDisconnect(sessionId));
2229
- resolve4(sock);
2235
+ resolve3(sock);
2230
2236
  });
2231
- sock.on("error", () => resolve4(null));
2237
+ sock.on("error", () => resolve3(null));
2232
2238
  });
2233
2239
  }
2234
2240
  // 枚举 DATA_DIR 下所有 session 目录,尝试连接存活的 worker.sock;失败则清理 stale socket。
@@ -2644,309 +2650,6 @@ function terminateSessionByOwnership(deps, sessionId) {
2644
2650
  return { success: false, action: "not_found" };
2645
2651
  }
2646
2652
 
2647
- // src/serve/clipboard-image-upload.ts
2648
- import { mkdirSync, writeFileSync } from "fs";
2649
- import { tmpdir as tmpdir2 } from "os";
2650
- import { join as join5 } from "path";
2651
- import { nanoid as nanoid3 } from "nanoid";
2652
- var DEFAULT_DATA_DIR = join5(tmpdir2(), "dev-anywhere");
2653
- var MAX_CLIPBOARD_IMAGE_BYTES = 10 * 1024 * 1024;
2654
- var MAX_CLIPBOARD_IMAGE_BASE64_LENGTH = Math.ceil(MAX_CLIPBOARD_IMAGE_BYTES / 3) * 4;
2655
- var IMAGE_EXTENSIONS = /* @__PURE__ */ new Map([
2656
- ["image/png", "png"],
2657
- ["image/jpeg", "jpg"],
2658
- ["image/webp", "webp"],
2659
- ["image/gif", "gif"]
2660
- ]);
2661
- function normalizeBase64(input) {
2662
- return input.replace(/^data:[^;]+;base64,/i, "").replace(/\s/g, "");
2663
- }
2664
- function decodeBase64Image(dataBase64) {
2665
- const normalized = normalizeBase64(dataBase64);
2666
- if (normalized.length > MAX_CLIPBOARD_IMAGE_BASE64_LENGTH) {
2667
- throw new Error("\u56FE\u7247\u8D85\u8FC7 10MB \u9650\u5236");
2668
- }
2669
- if (!normalized || !/^[A-Za-z0-9+/]*={0,2}$/.test(normalized)) {
2670
- throw new Error("\u56FE\u7247\u6570\u636E\u4E0D\u662F\u6709\u6548\u7684 base64");
2671
- }
2672
- const buffer = Buffer.from(normalized, "base64");
2673
- if (buffer.length === 0) throw new Error("\u56FE\u7247\u6570\u636E\u4E3A\u7A7A");
2674
- if (buffer.length > MAX_CLIPBOARD_IMAGE_BYTES) {
2675
- throw new Error("\u56FE\u7247\u8D85\u8FC7 10MB \u9650\u5236");
2676
- }
2677
- return buffer;
2678
- }
2679
- function saveClipboardImageUpload(request, options = {}) {
2680
- const extension = IMAGE_EXTENSIONS.get(request.mimeType);
2681
- if (!extension) {
2682
- return {
2683
- success: false,
2684
- error: "\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F",
2685
- errorCode: ControlErrorCode.UNKNOWN
2686
- };
2687
- }
2688
- try {
2689
- const buffer = decodeBase64Image(request.dataBase64);
2690
- const suffix = options.randomSuffix?.() ?? nanoid3(6);
2691
- const fileName = `paste-${suffix}.${extension}`;
2692
- const dataDir = options.dataDir ?? DEFAULT_DATA_DIR;
2693
- const path = join5(dataDir, fileName);
2694
- mkdirSync(dataDir, { recursive: true });
2695
- writeFileSync(path, buffer, { mode: 384 });
2696
- return { success: true, path };
2697
- } catch (err) {
2698
- return {
2699
- success: false,
2700
- error: err instanceof Error ? err.message : String(err),
2701
- errorCode: ControlErrorCode.UNKNOWN
2702
- };
2703
- }
2704
- }
2705
-
2706
- // src/serve/file-download.ts
2707
- import { readFileSync as readFileSync5, realpathSync, statSync } from "fs";
2708
- import { extname, isAbsolute as isAbsolute3, resolve as resolve2 } from "path";
2709
- var MAX_FILE_DOWNLOAD_BYTES = 100 * 1024 * 1024;
2710
- var EXT_MIME_MAP = {
2711
- ".png": "image/png",
2712
- ".jpg": "image/jpeg",
2713
- ".jpeg": "image/jpeg",
2714
- ".gif": "image/gif",
2715
- ".webp": "image/webp",
2716
- ".svg": "image/svg+xml",
2717
- ".bmp": "image/bmp",
2718
- ".pdf": "application/pdf",
2719
- ".json": "application/json",
2720
- ".xml": "application/xml",
2721
- ".html": "text/html",
2722
- ".htm": "text/html",
2723
- ".txt": "text/plain",
2724
- ".md": "text/markdown",
2725
- ".log": "text/plain",
2726
- ".csv": "text/csv",
2727
- ".js": "application/javascript",
2728
- ".mjs": "application/javascript",
2729
- ".ts": "application/typescript",
2730
- ".tsx": "application/typescript",
2731
- ".zip": "application/zip",
2732
- ".tar": "application/x-tar",
2733
- ".gz": "application/gzip",
2734
- ".mp4": "video/mp4",
2735
- ".mp3": "audio/mpeg",
2736
- ".wav": "audio/wav"
2737
- };
2738
- function guessMimeType(filePath) {
2739
- const ext = extname(filePath).toLowerCase();
2740
- return EXT_MIME_MAP[ext] ?? "application/octet-stream";
2741
- }
2742
- function resolveDownloadPath(rawPath, cwd) {
2743
- const candidate = isAbsolute3(rawPath) ? resolve2(rawPath) : resolve2(cwd, rawPath);
2744
- return realpathSync(candidate);
2745
- }
2746
- function errorCode(err) {
2747
- if (err instanceof Error && "errorCode" in err && typeof err.errorCode === "string") {
2748
- return err.errorCode;
2749
- }
2750
- return classifyPathError(err);
2751
- }
2752
- function loadFileDownload(request, options) {
2753
- try {
2754
- const resolvedPath = resolveDownloadPath(request.path, options.cwd);
2755
- const stat2 = statSync(resolvedPath);
2756
- if (!stat2.isFile()) {
2757
- return {
2758
- success: false,
2759
- sessionId: request.sessionId,
2760
- path: request.path,
2761
- error: "\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6",
2762
- errorCode: ControlErrorCode.INVALID_PATH
2763
- };
2764
- }
2765
- const maxBytes = options.maxBytes ?? MAX_FILE_DOWNLOAD_BYTES;
2766
- if (stat2.size > maxBytes) {
2767
- return {
2768
- success: false,
2769
- sessionId: request.sessionId,
2770
- path: request.path,
2771
- error: `\u6587\u4EF6\u8D85\u8FC7 ${Math.round(maxBytes / 1024 / 1024)}MB \u9650\u5236`,
2772
- errorCode: ControlErrorCode.UNKNOWN
2773
- };
2774
- }
2775
- const buffer = readFileSync5(resolvedPath);
2776
- return {
2777
- success: true,
2778
- sessionId: request.sessionId,
2779
- path: request.path,
2780
- mimeType: guessMimeType(resolvedPath),
2781
- dataBase64: buffer.toString("base64"),
2782
- size: buffer.length
2783
- };
2784
- } catch (err) {
2785
- return {
2786
- success: false,
2787
- sessionId: request.sessionId,
2788
- path: request.path,
2789
- error: err instanceof Error ? err.message : String(err),
2790
- errorCode: errorCode(err)
2791
- };
2792
- }
2793
- }
2794
-
2795
- // src/serve/file-upload.ts
2796
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
2797
- import { tmpdir as tmpdir3 } from "os";
2798
- import { extname as extname2, join as join6 } from "path";
2799
- import { nanoid as nanoid4 } from "nanoid";
2800
- var DEFAULT_DATA_DIR2 = join6(tmpdir3(), "dev-anywhere");
2801
- var MAX_FILE_UPLOAD_BYTES = 100 * 1024 * 1024;
2802
- var MAX_FILE_UPLOAD_BASE64_LENGTH = Math.ceil(MAX_FILE_UPLOAD_BYTES / 3) * 4;
2803
- var SAFE_EXT_RE = /^[A-Za-z0-9]{1,6}$/;
2804
- function normalizeBase642(input) {
2805
- return input.replace(/^data:[^;]+;base64,/i, "").replace(/\s/g, "");
2806
- }
2807
- function decodeBase64File(dataBase64) {
2808
- const normalized = normalizeBase642(dataBase64);
2809
- if (normalized.length > MAX_FILE_UPLOAD_BASE64_LENGTH) {
2810
- throw new Error("\u6587\u4EF6\u8D85\u8FC7 100MB \u9650\u5236");
2811
- }
2812
- if (!normalized || !/^[A-Za-z0-9+/]*={0,2}$/.test(normalized)) {
2813
- throw new Error("\u6587\u4EF6\u6570\u636E\u4E0D\u662F\u6709\u6548\u7684 base64");
2814
- }
2815
- const buffer = Buffer.from(normalized, "base64");
2816
- if (buffer.length === 0) throw new Error("\u6587\u4EF6\u6570\u636E\u4E3A\u7A7A");
2817
- if (buffer.length > MAX_FILE_UPLOAD_BYTES) {
2818
- throw new Error("\u6587\u4EF6\u8D85\u8FC7 100MB \u9650\u5236");
2819
- }
2820
- return buffer;
2821
- }
2822
- function safeExtension(fileName) {
2823
- const raw = extname2(fileName).slice(1).toLowerCase();
2824
- return SAFE_EXT_RE.test(raw) ? `.${raw}` : "";
2825
- }
2826
- async function saveFileUpload(request, options = {}) {
2827
- try {
2828
- const buffer = decodeBase64File(request.dataBase64);
2829
- const suffix = options.randomSuffix?.() ?? nanoid4(6);
2830
- const fileName = `up-${suffix}${safeExtension(request.fileName)}`;
2831
- const dataDir = options.dataDir ?? DEFAULT_DATA_DIR2;
2832
- const path = join6(dataDir, fileName);
2833
- mkdirSync2(dataDir, { recursive: true });
2834
- writeFileSync2(path, buffer, { mode: 384 });
2835
- return { success: true, path };
2836
- } catch (err) {
2837
- return {
2838
- success: false,
2839
- error: err instanceof Error ? err.message : String(err),
2840
- errorCode: ControlErrorCode.UNKNOWN
2841
- };
2842
- }
2843
- }
2844
-
2845
- // src/serve/image-preview.ts
2846
- import { readFileSync as readFileSync6, realpathSync as realpathSync2, statSync as statSync2 } from "fs";
2847
- import { tmpdir as tmpdir4 } from "os";
2848
- import { isAbsolute as isAbsolute4, relative, resolve as resolve3 } from "path";
2849
- var MAX_IMAGE_PREVIEW_BYTES = 10 * 1024 * 1024;
2850
- var DEFAULT_TEMP_PREVIEW_ROOTS = [tmpdir4(), "/tmp", "/private/tmp", "/var/tmp"];
2851
- function isInsideRoot(realFilePath, realRootPath) {
2852
- const rel = relative(realRootPath, realFilePath);
2853
- return rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
2854
- }
2855
- function allowedRoots(options) {
2856
- const tempRoots = options.tmpDir ? [options.tmpDir] : DEFAULT_TEMP_PREVIEW_ROOTS;
2857
- const roots = [options.cwd, ...tempRoots, ...options.previewRoots ?? []];
2858
- return [...new Set(roots)].map((root) => root.trim()).filter(Boolean).flatMap((root) => {
2859
- try {
2860
- return [realpathSync2(root)];
2861
- } catch {
2862
- return [];
2863
- }
2864
- });
2865
- }
2866
- function resolvePreviewPath(rawPath, options) {
2867
- const candidate = isAbsolute4(rawPath) ? resolve3(rawPath) : resolve3(options.cwd, rawPath);
2868
- const realCandidate = realpathSync2(candidate);
2869
- if (!allowedRoots(options).some((root) => isInsideRoot(realCandidate, root))) {
2870
- throw Object.assign(new Error("\u56FE\u7247\u8DEF\u5F84\u4E0D\u5728\u5141\u8BB8\u9884\u89C8\u7684\u76EE\u5F55\u5185"), {
2871
- errorCode: ControlErrorCode.INVALID_PATH
2872
- });
2873
- }
2874
- return realCandidate;
2875
- }
2876
- function detectImageMime(buffer) {
2877
- if (buffer.length >= 8 && buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71 && buffer[4] === 13 && buffer[5] === 10 && buffer[6] === 26 && buffer[7] === 10) {
2878
- return "image/png";
2879
- }
2880
- if (buffer.length >= 3 && buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) {
2881
- return "image/jpeg";
2882
- }
2883
- if (buffer.length >= 12 && buffer.subarray(0, 4).toString("ascii") === "RIFF" && buffer.subarray(8, 12).toString("ascii") === "WEBP") {
2884
- return "image/webp";
2885
- }
2886
- if (buffer.length >= 6 && (buffer.subarray(0, 6).toString("ascii") === "GIF87a" || buffer.subarray(0, 6).toString("ascii") === "GIF89a")) {
2887
- return "image/gif";
2888
- }
2889
- return void 0;
2890
- }
2891
- function errorCode2(err) {
2892
- if (err instanceof Error && "errorCode" in err && typeof err.errorCode === "string") {
2893
- return err.errorCode;
2894
- }
2895
- return classifyPathError(err);
2896
- }
2897
- function loadImagePreview(request, options) {
2898
- try {
2899
- const resolvedPath = resolvePreviewPath(request.path, options);
2900
- const stat2 = statSync2(resolvedPath);
2901
- if (!stat2.isFile()) {
2902
- return {
2903
- success: false,
2904
- sessionId: request.sessionId,
2905
- path: request.path,
2906
- error: "\u8DEF\u5F84\u4E0D\u662F\u56FE\u7247\u6587\u4EF6",
2907
- errorCode: ControlErrorCode.INVALID_PATH
2908
- };
2909
- }
2910
- const maxBytes = options.maxBytes ?? MAX_IMAGE_PREVIEW_BYTES;
2911
- if (stat2.size > maxBytes) {
2912
- return {
2913
- success: false,
2914
- sessionId: request.sessionId,
2915
- path: request.path,
2916
- error: "\u56FE\u7247\u8D85\u8FC7 10MB \u9650\u5236",
2917
- errorCode: ControlErrorCode.UNKNOWN
2918
- };
2919
- }
2920
- const buffer = readFileSync6(resolvedPath);
2921
- const mimeType = detectImageMime(buffer);
2922
- if (!mimeType) {
2923
- return {
2924
- success: false,
2925
- sessionId: request.sessionId,
2926
- path: request.path,
2927
- error: "\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F",
2928
- errorCode: ControlErrorCode.UNKNOWN
2929
- };
2930
- }
2931
- return {
2932
- success: true,
2933
- sessionId: request.sessionId,
2934
- path: request.path,
2935
- mimeType,
2936
- dataBase64: buffer.toString("base64"),
2937
- size: buffer.length
2938
- };
2939
- } catch (err) {
2940
- return {
2941
- success: false,
2942
- sessionId: request.sessionId,
2943
- path: request.path,
2944
- error: err instanceof Error ? err.message : String(err),
2945
- errorCode: errorCode2(err)
2946
- };
2947
- }
2948
- }
2949
-
2950
2653
  // src/serve/pty-input.ts
2951
2654
  function serializeRawPtyInput(sessionId, data, traceId) {
2952
2655
  return serializeIpc({ type: "pty_input", sessionId, data, traceId });
@@ -3028,151 +2731,20 @@ var RelayInputHandlers = class {
3028
2731
  ts.write(serializeRawPtyInput(sessionId, data, traceId));
3029
2732
  serviceLogger.info({ sessionId, traceId, bytes: data.length }, "Raw PTY input forwarded");
3030
2733
  }
3031
- onClipboardImageUpload(msg) {
3032
- const { sessionId, requestId } = msg;
3033
- if (!sessionId) return;
3034
- if (!this.deps.sessionManager.getSession(sessionId)) {
3035
- this.deps.relayConnection.sendRaw(
3036
- serializeControl({
3037
- type: "clipboard_image_upload_response",
3038
- requestId,
3039
- sessionId,
3040
- success: false,
3041
- error: "\u4F1A\u8BDD\u4E0D\u5B58\u5728",
3042
- errorCode: ControlErrorCode.SESSION_NOT_FOUND
3043
- })
3044
- );
3045
- serviceLogger.warn({ sessionId }, "Clipboard image upload rejected: session not found");
3046
- return;
3047
- }
3048
- const result = saveClipboardImageUpload({
3049
- sessionId,
3050
- mimeType: msg.mimeType,
3051
- dataBase64: msg.dataBase64,
3052
- fileName: msg.fileName
3053
- });
3054
- this.deps.relayConnection.sendRaw(
3055
- serializeControl({
3056
- type: "clipboard_image_upload_response",
3057
- requestId,
3058
- sessionId,
3059
- ...result
3060
- })
3061
- );
3062
- serviceLogger.info({ sessionId, success: result.success }, "Clipboard image upload handled");
2734
+ onRemoteFileStreamRequest(msg) {
2735
+ this.deps.remoteFileStreamManager.start(msg);
3063
2736
  }
3064
- onImagePreviewRequest(msg) {
3065
- const { sessionId, requestId, path } = msg;
3066
- if (!sessionId || !path) return;
3067
- const session = this.deps.sessionManager.getSession(sessionId);
3068
- if (!session) {
3069
- this.deps.relayConnection.sendRaw(
3070
- serializeControl({
3071
- type: "image_preview_response",
3072
- requestId,
3073
- sessionId,
3074
- success: false,
3075
- path,
3076
- error: "\u4F1A\u8BDD\u4E0D\u5B58\u5728",
3077
- errorCode: ControlErrorCode.SESSION_NOT_FOUND
3078
- })
3079
- );
3080
- serviceLogger.warn({ sessionId }, "Image preview rejected: session not found");
3081
- return;
3082
- }
3083
- const result = loadImagePreview(
3084
- { sessionId, path },
3085
- {
3086
- cwd: session.cwd,
3087
- previewRoots: this.deps.previewRoots
3088
- }
3089
- );
3090
- this.deps.relayConnection.sendRaw(
3091
- serializeControl({
3092
- type: "image_preview_response",
3093
- requestId,
3094
- ...result
3095
- })
3096
- );
3097
- if (result.success) {
3098
- serviceLogger.info({ sessionId, path, size: result.size }, "Image preview handled");
3099
- } else {
3100
- serviceLogger.warn(
3101
- { sessionId, path, errorCode: result.errorCode, error: result.error },
3102
- "Image preview failed"
3103
- );
3104
- }
2737
+ onRemoteFileStreamCancel(msg) {
2738
+ this.deps.remoteFileStreamManager.cancel(msg);
3105
2739
  }
3106
- onFileDownloadRequest(msg) {
3107
- const { sessionId, requestId, path } = msg;
3108
- if (!sessionId || !path) return;
3109
- const session = this.deps.sessionManager.getSession(sessionId);
3110
- if (!session) {
3111
- this.deps.relayConnection.sendRaw(
3112
- serializeControl({
3113
- type: "file_download_response",
3114
- requestId,
3115
- sessionId,
3116
- success: false,
3117
- path,
3118
- error: "\u4F1A\u8BDD\u4E0D\u5B58\u5728",
3119
- errorCode: ControlErrorCode.SESSION_NOT_FOUND
3120
- })
3121
- );
3122
- serviceLogger.warn({ sessionId }, "File download rejected: session not found");
3123
- return;
3124
- }
3125
- const result = loadFileDownload({ sessionId, path }, { cwd: session.cwd });
3126
- this.deps.relayConnection.sendRaw(
3127
- serializeControl({
3128
- type: "file_download_response",
3129
- requestId,
3130
- ...result
3131
- })
3132
- );
3133
- if (result.success) {
3134
- serviceLogger.info({ sessionId, path, size: result.size }, "File download handled");
3135
- } else {
3136
- serviceLogger.warn(
3137
- { sessionId, path, errorCode: result.errorCode, error: result.error },
3138
- "File download failed"
3139
- );
3140
- }
2740
+ onRemoteFileUploadStreamRequest(msg) {
2741
+ this.deps.remoteFileUploadManager.start(msg);
3141
2742
  }
3142
- async onFileUploadRequest(msg) {
3143
- const { sessionId, requestId, mimeType, dataBase64, fileName } = msg;
3144
- if (!sessionId) return;
3145
- if (!this.deps.sessionManager.getSession(sessionId)) {
3146
- this.deps.relayConnection.sendRaw(
3147
- serializeControl({
3148
- type: "file_upload_response",
3149
- requestId,
3150
- sessionId,
3151
- success: false,
3152
- error: "\u4F1A\u8BDD\u4E0D\u5B58\u5728",
3153
- errorCode: ControlErrorCode.SESSION_NOT_FOUND
3154
- })
3155
- );
3156
- serviceLogger.warn({ sessionId }, "File upload rejected: session not found");
3157
- return;
3158
- }
3159
- const result = await saveFileUpload({ sessionId, mimeType, dataBase64, fileName });
3160
- this.deps.relayConnection.sendRaw(
3161
- serializeControl({
3162
- type: "file_upload_response",
3163
- requestId,
3164
- sessionId,
3165
- ...result
3166
- })
3167
- );
3168
- if (result.success) {
3169
- serviceLogger.info({ sessionId, fileName, path: result.path }, "File upload handled");
3170
- } else {
3171
- serviceLogger.warn(
3172
- { sessionId, fileName, errorCode: result.errorCode, error: result.error },
3173
- "File upload failed"
3174
- );
3175
- }
2743
+ onRemoteFileUploadStreamComplete(msg) {
2744
+ this.deps.remoteFileUploadManager.complete(msg);
2745
+ }
2746
+ onRemoteFileUploadStreamCancel(msg) {
2747
+ this.deps.remoteFileUploadManager.cancel(msg);
3176
2748
  }
3177
2749
  };
3178
2750
 
@@ -3429,14 +3001,14 @@ var RelayPermissionHandlers = class {
3429
3001
 
3430
3002
  // src/serve/relay-resource-handlers.ts
3431
3003
  import { homedir as homedir4 } from "os";
3432
- import { accessSync, constants, statSync as statSync3 } from "fs";
3004
+ import { accessSync, constants, statSync } from "fs";
3433
3005
  function errorMessage(err) {
3434
3006
  return err instanceof Error ? err.message : String(err);
3435
3007
  }
3436
3008
  function validateExecutablePath(path) {
3437
3009
  const normalized = path.trim();
3438
3010
  if (!normalized.startsWith("/")) throw new Error("CLI \u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
3439
- const stat2 = statSync3(normalized);
3011
+ const stat2 = statSync(normalized);
3440
3012
  if (!stat2.isFile()) throw new Error("CLI \u8DEF\u5F84\u4E0D\u662F\u53EF\u6267\u884C\u6587\u4EF6");
3441
3013
  accessSync(normalized, constants.X_OK);
3442
3014
  return normalized;
@@ -3544,10 +3116,10 @@ var RelayResourceHandlers = class {
3544
3116
  };
3545
3117
 
3546
3118
  // src/serve/relay-session-create-handler.ts
3547
- import { rmSync, statSync as statSync4 } from "fs";
3119
+ import { rmSync, statSync as statSync2 } from "fs";
3548
3120
  import { homedir as homedir5 } from "os";
3549
- import { isAbsolute as isAbsolute5 } from "path";
3550
- import { nanoid as nanoid5 } from "nanoid";
3121
+ import { isAbsolute as isAbsolute3 } from "path";
3122
+ import { nanoid as nanoid3 } from "nanoid";
3551
3123
 
3552
3124
  // src/serve/hosted-pty-registry.ts
3553
3125
  import * as pty from "node-pty";
@@ -3879,11 +3451,11 @@ function validateSessionCwd(cwd) {
3879
3451
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
3880
3452
  }
3881
3453
  const trimmed = cwd.trim();
3882
- if (!isAbsolute5(trimmed)) {
3454
+ if (!isAbsolute3(trimmed)) {
3883
3455
  return { message: "\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84", code: ControlErrorCode.INVALID_PATH };
3884
3456
  }
3885
3457
  try {
3886
- const stat2 = statSync4(trimmed);
3458
+ const stat2 = statSync2(trimmed);
3887
3459
  return stat2.isDirectory() ? null : { message: "\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u76EE\u5F55", code: ControlErrorCode.PATH_NOT_DIRECTORY };
3888
3460
  } catch (err) {
3889
3461
  return {
@@ -3900,7 +3472,7 @@ function resolveTerminalCwd() {
3900
3472
  const home = homedir5();
3901
3473
  if (home) {
3902
3474
  try {
3903
- if (statSync4(home).isDirectory()) return home;
3475
+ if (statSync2(home).isDirectory()) return home;
3904
3476
  } catch {
3905
3477
  }
3906
3478
  }
@@ -3966,7 +3538,7 @@ var RelaySessionCreateHandler = class {
3966
3538
  const requestedName = normalizeSessionName(msg.name);
3967
3539
  const name = requestedName ?? tildify(sessionCwd);
3968
3540
  const nameLocked = requestedName !== void 0;
3969
- const pendingId = nanoid5();
3541
+ const pendingId = nanoid3();
3970
3542
  const hook = this.deps.createHookContext(pendingId, provider);
3971
3543
  const workerPid = this.deps.workerRegistry.spawn(pendingId, {
3972
3544
  cwd: sessionCwd,
@@ -4084,7 +3656,7 @@ var RelaySessionCreateHandler = class {
4084
3656
  return;
4085
3657
  }
4086
3658
  const resumeSessionId = msg.resumeSessionId;
4087
- const pendingId = nanoid5();
3659
+ const pendingId = nanoid3();
4088
3660
  const requestedName = normalizeSessionName(msg.name);
4089
3661
  const name = requestedName ?? tildify(cwd);
4090
3662
  const nameLocked = requestedName !== void 0;
@@ -4157,7 +3729,7 @@ var RelaySessionCreateHandler = class {
4157
3729
  }
4158
3730
  }
4159
3731
  createShellTerminalSession(msg) {
4160
- const pendingId = nanoid5();
3732
+ const pendingId = nanoid3();
4161
3733
  const cwd = resolveTerminalCwd();
4162
3734
  const requestedName = normalizeSessionName(msg.name);
4163
3735
  const name = requestedName ?? tildify(cwd);
@@ -4333,7 +3905,7 @@ function buildClaudeSpeechSummaryCommand({
4333
3905
  }
4334
3906
  var runClaudeSpeechSummary = ({ cwd, prompt, env, timeoutMs }) => {
4335
3907
  const { command, args } = buildClaudeSpeechSummaryCommand({ env, prompt });
4336
- return new Promise((resolve4, reject) => {
3908
+ return new Promise((resolve3, reject) => {
4337
3909
  const child = spawn2(command, args, {
4338
3910
  cwd,
4339
3911
  env: { ...process.env, ...env },
@@ -4365,7 +3937,7 @@ var runClaudeSpeechSummary = ({ cwd, prompt, env, timeoutMs }) => {
4365
3937
  clearTimeout(timer);
4366
3938
  const stdout = Buffer.concat(stdoutChunks).toString("utf8").trim();
4367
3939
  if (code === 0 && stdout.length > 0) {
4368
- resolve4(stdout);
3940
+ resolve3(stdout);
4369
3941
  return;
4370
3942
  }
4371
3943
  const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
@@ -4430,7 +4002,7 @@ var VoiceSummaryHandler = class {
4430
4002
  })
4431
4003
  );
4432
4004
  }
4433
- sendFailure(msg, error, errorCode3) {
4005
+ sendFailure(msg, error, errorCode2) {
4434
4006
  this.deps.relaySend(
4435
4007
  serializeControl({
4436
4008
  type: "voice_summary_response",
@@ -4439,7 +4011,7 @@ var VoiceSummaryHandler = class {
4439
4011
  messageId: msg.messageId,
4440
4012
  success: false,
4441
4013
  error,
4442
- errorCode: errorCode3
4014
+ errorCode: errorCode2
4443
4015
  })
4444
4016
  );
4445
4017
  }
@@ -4476,7 +4048,8 @@ var RelayRouter = class {
4476
4048
  terminalSockets: deps.terminalSockets,
4477
4049
  hostedPtyRegistry: deps.hostedPtyRegistry,
4478
4050
  jsonObserver: deps.jsonObserver,
4479
- previewRoots: deps.getPreviewRoots?.()
4051
+ remoteFileStreamManager: deps.remoteFileStreamManager,
4052
+ remoteFileUploadManager: deps.remoteFileUploadManager
4480
4053
  });
4481
4054
  this.resourceHandlers = new RelayResourceHandlers({
4482
4055
  relaySend: deps.relaySend,
@@ -4568,17 +4141,20 @@ var RelayRouter = class {
4568
4141
  case "latency_relay_proxy_ping":
4569
4142
  this.onRelayProxyLatencyPing(msg);
4570
4143
  return;
4571
- case "clipboard_image_upload":
4572
- this.inputHandlers.onClipboardImageUpload(msg);
4144
+ case "remote_file_stream_request":
4145
+ this.inputHandlers.onRemoteFileStreamRequest(msg);
4146
+ return;
4147
+ case "remote_file_stream_cancel":
4148
+ this.inputHandlers.onRemoteFileStreamCancel(msg);
4573
4149
  return;
4574
- case "image_preview_request":
4575
- this.inputHandlers.onImagePreviewRequest(msg);
4150
+ case "remote_file_upload_stream_request":
4151
+ this.inputHandlers.onRemoteFileUploadStreamRequest(msg);
4576
4152
  return;
4577
- case "file_download_request":
4578
- this.inputHandlers.onFileDownloadRequest(msg);
4153
+ case "remote_file_upload_stream_complete":
4154
+ this.inputHandlers.onRemoteFileUploadStreamComplete(msg);
4579
4155
  return;
4580
- case "file_upload_request":
4581
- void this.inputHandlers.onFileUploadRequest(msg);
4156
+ case "remote_file_upload_stream_cancel":
4157
+ this.inputHandlers.onRemoteFileUploadStreamCancel(msg);
4582
4158
  return;
4583
4159
  case "tool_approve":
4584
4160
  this.permissionHandlers.onToolApprove(msg);
@@ -4876,11 +4452,11 @@ var PermissionBroker = class {
4876
4452
  if (this.pending.has(request.requestId)) {
4877
4453
  return Promise.resolve(DUPLICATE_DECISION);
4878
4454
  }
4879
- return new Promise((resolve4) => {
4455
+ return new Promise((resolve3) => {
4880
4456
  this.pending.set(request.requestId, {
4881
4457
  ...request,
4882
4458
  source: "hook",
4883
- resolve: resolve4,
4459
+ resolve: resolve3,
4884
4460
  createdAt: Date.now()
4885
4461
  });
4886
4462
  });
@@ -5282,14 +4858,14 @@ function createEventBridge(deps) {
5282
4858
 
5283
4859
  // src/serve/service-files.ts
5284
4860
  import { execSync } from "child_process";
5285
- import { existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
4861
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
5286
4862
  import { hostname } from "os";
5287
4863
  import { connect as connect2 } from "net";
5288
4864
  function tryConnectSocket(sockPath) {
5289
- return new Promise((resolve4) => {
4865
+ return new Promise((resolve3) => {
5290
4866
  const s = connect2(sockPath);
5291
- s.on("connect", () => resolve4(s));
5292
- s.on("error", () => resolve4(null));
4867
+ s.on("connect", () => resolve3(s));
4868
+ s.on("error", () => resolve3(null));
5293
4869
  });
5294
4870
  }
5295
4871
  function isProcessAlive(pid) {
@@ -5310,7 +4886,7 @@ async function cleanupStaleResources() {
5310
4886
  serviceLogger.info("Removed stale socket file");
5311
4887
  }
5312
4888
  if (existsSync5(PID_PATH)) {
5313
- const pidStr = readFileSync7(PID_PATH, "utf-8").trim();
4889
+ const pidStr = readFileSync5(PID_PATH, "utf-8").trim();
5314
4890
  const pid = parseInt(pidStr, 10);
5315
4891
  const probe = !isNaN(pid) ? probeProcess(pid) : null;
5316
4892
  if (probe?.status === "alive") {
@@ -5657,7 +5233,7 @@ function handleTerminalConnection(socket, deps) {
5657
5233
 
5658
5234
  // src/serve/hook-registry.ts
5659
5235
  import { createHash as createHash2, randomBytes } from "crypto";
5660
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync8, renameSync, writeFileSync as writeFileSync3 } from "fs";
5236
+ import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, renameSync, writeFileSync } from "fs";
5661
5237
  import { dirname } from "path";
5662
5238
  import { z } from "zod";
5663
5239
  var PersistedHookSessionBindingSchema = z.object({
@@ -5721,7 +5297,7 @@ var HookRegistry = class {
5721
5297
  if (!this.persistPath || !existsSync6(this.persistPath)) return;
5722
5298
  try {
5723
5299
  const parsed = PersistedHookRegistrySchema.parse(
5724
- JSON.parse(readFileSync8(this.persistPath, "utf8"))
5300
+ JSON.parse(readFileSync6(this.persistPath, "utf8"))
5725
5301
  );
5726
5302
  this.bindingsBySession.clear();
5727
5303
  for (const binding of parsed.bindings) {
@@ -5737,9 +5313,9 @@ var HookRegistry = class {
5737
5313
  save() {
5738
5314
  if (!this.persistPath) return;
5739
5315
  try {
5740
- mkdirSync3(dirname(this.persistPath), { recursive: true });
5316
+ mkdirSync(dirname(this.persistPath), { recursive: true });
5741
5317
  const tmpPath = `${this.persistPath}.${process.pid}.${Date.now()}.tmp`;
5742
- writeFileSync3(
5318
+ writeFileSync(
5743
5319
  tmpPath,
5744
5320
  JSON.stringify(
5745
5321
  {
@@ -5786,7 +5362,7 @@ var HookServer = class {
5786
5362
  this.writeJson(res, 500, { error: "internal_error" });
5787
5363
  });
5788
5364
  });
5789
- return new Promise((resolve4, reject) => {
5365
+ return new Promise((resolve3, reject) => {
5790
5366
  const onError = (err) => {
5791
5367
  this.server?.off("listening", onListening);
5792
5368
  reject(err);
@@ -5794,7 +5370,7 @@ var HookServer = class {
5794
5370
  const onListening = () => {
5795
5371
  this.server?.off("error", onError);
5796
5372
  serviceLogger.info({ host: this.host, port: this.options.port }, "Hook server listening");
5797
- resolve4();
5373
+ resolve3();
5798
5374
  };
5799
5375
  this.server.once("error", onError);
5800
5376
  this.server.once("listening", onListening);
@@ -5805,8 +5381,8 @@ var HookServer = class {
5805
5381
  if (!this.server) return Promise.resolve();
5806
5382
  const server = this.server;
5807
5383
  this.server = null;
5808
- return new Promise((resolve4, reject) => {
5809
- server.close((err) => err ? reject(err) : resolve4());
5384
+ return new Promise((resolve3, reject) => {
5385
+ server.close((err) => err ? reject(err) : resolve3());
5810
5386
  });
5811
5387
  }
5812
5388
  getListeningPort() {
@@ -5920,7 +5496,7 @@ var HookServer = class {
5920
5496
  this.writeJson(res, 200, payload);
5921
5497
  }
5922
5498
  readBody(req) {
5923
- return new Promise((resolve4, reject) => {
5499
+ return new Promise((resolve3, reject) => {
5924
5500
  let body = "";
5925
5501
  let size = 0;
5926
5502
  req.setEncoding("utf8");
@@ -5933,7 +5509,7 @@ var HookServer = class {
5933
5509
  }
5934
5510
  body += chunk;
5935
5511
  });
5936
- req.on("end", () => resolve4(body));
5512
+ req.on("end", () => resolve3(body));
5937
5513
  req.on("error", reject);
5938
5514
  });
5939
5515
  }
@@ -6022,6 +5598,340 @@ function createServeShutdown(deps) {
6022
5598
  };
6023
5599
  }
6024
5600
 
5601
+ // src/serve/remote-file-upload.ts
5602
+ import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
5603
+ import { tmpdir as tmpdir2 } from "os";
5604
+ import { extname, join as join5 } from "path";
5605
+ import { nanoid as nanoid4 } from "nanoid";
5606
+ var DEFAULT_DATA_DIR = join5(tmpdir2(), "dev-anywhere");
5607
+ var SAFE_EXT_RE = /^[A-Za-z0-9]{1,6}$/;
5608
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Map([
5609
+ ["image/png", "png"],
5610
+ ["image/jpeg", "jpg"],
5611
+ ["image/webp", "webp"],
5612
+ ["image/gif", "gif"]
5613
+ ]);
5614
+ function safeExtension(fileName) {
5615
+ const raw = extname(fileName ?? "").slice(1).toLowerCase();
5616
+ return SAFE_EXT_RE.test(raw) ? `.${raw}` : "";
5617
+ }
5618
+ function uploadPathFor(msg, dataDir, suffix) {
5619
+ if (msg.kind === "clipboard_image") {
5620
+ const extension = IMAGE_EXTENSIONS.get(msg.mimeType);
5621
+ if (!extension) throw new Error("\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F");
5622
+ return join5(dataDir, `paste-${suffix}.${extension}`);
5623
+ }
5624
+ return join5(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
5625
+ }
5626
+ var RemoteFileUploadManager = class {
5627
+ constructor(deps) {
5628
+ this.deps = deps;
5629
+ }
5630
+ deps;
5631
+ activeUploads = /* @__PURE__ */ new Map();
5632
+ start(msg) {
5633
+ const { uploadId, sessionId } = msg;
5634
+ if (this.activeUploads.has(uploadId)) {
5635
+ this.sendResponse({
5636
+ uploadId,
5637
+ sessionId,
5638
+ success: false,
5639
+ error: "\u4E0A\u4F20\u6D41\u5DF2\u5B58\u5728",
5640
+ errorCode: ControlErrorCode.UNKNOWN
5641
+ });
5642
+ return;
5643
+ }
5644
+ const session = this.deps.sessionManager.getSession(sessionId);
5645
+ if (!session) {
5646
+ this.sendResponse({
5647
+ uploadId,
5648
+ sessionId,
5649
+ success: false,
5650
+ error: "\u4F1A\u8BDD\u4E0D\u5B58\u5728",
5651
+ errorCode: ControlErrorCode.SESSION_NOT_FOUND
5652
+ });
5653
+ return;
5654
+ }
5655
+ try {
5656
+ const dataDir = this.deps.dataDir ?? DEFAULT_DATA_DIR;
5657
+ mkdirSync2(dataDir, { recursive: true });
5658
+ const path = uploadPathFor(msg, dataDir, this.deps.randomSuffix?.() ?? nanoid4(6));
5659
+ const stream = createWriteStream(path, { mode: 384 });
5660
+ const active = {
5661
+ sessionId,
5662
+ path,
5663
+ stream,
5664
+ bytes: 0,
5665
+ completed: false
5666
+ };
5667
+ this.activeUploads.set(uploadId, active);
5668
+ stream.on("error", (err) => {
5669
+ this.fail(uploadId, err instanceof Error ? err.message : String(err));
5670
+ });
5671
+ stream.on("finish", () => {
5672
+ if (!active.completed) return;
5673
+ this.activeUploads.delete(uploadId);
5674
+ this.sendResponse({
5675
+ uploadId,
5676
+ sessionId,
5677
+ success: true,
5678
+ path
5679
+ });
5680
+ serviceLogger.info(
5681
+ { uploadId, sessionId, path, bytes: active.bytes },
5682
+ "Remote file upload completed"
5683
+ );
5684
+ });
5685
+ serviceLogger.info(
5686
+ { uploadId, sessionId, path, kind: msg.kind },
5687
+ "Remote file upload started"
5688
+ );
5689
+ } catch (err) {
5690
+ this.sendResponse({
5691
+ uploadId,
5692
+ sessionId,
5693
+ success: false,
5694
+ error: err instanceof Error ? err.message : String(err),
5695
+ errorCode: ControlErrorCode.UNKNOWN
5696
+ });
5697
+ }
5698
+ }
5699
+ handleBinary(data) {
5700
+ const frame = decodeFileStreamFrame(data);
5701
+ if (!frame) return false;
5702
+ const active = this.activeUploads.get(frame.streamId);
5703
+ if (!active || active.completed) return true;
5704
+ const chunk = Buffer.from(frame.data);
5705
+ active.bytes += chunk.length;
5706
+ active.stream.write(chunk);
5707
+ return true;
5708
+ }
5709
+ complete(msg) {
5710
+ const active = this.activeUploads.get(msg.uploadId);
5711
+ if (!active || active.completed) return;
5712
+ active.completed = true;
5713
+ active.stream.end();
5714
+ }
5715
+ cancel(msg) {
5716
+ const active = this.activeUploads.get(msg.uploadId);
5717
+ if (!active) return;
5718
+ active.completed = true;
5719
+ this.activeUploads.delete(msg.uploadId);
5720
+ active.stream.destroy();
5721
+ serviceLogger.info({ uploadId: msg.uploadId }, "Remote file upload canceled");
5722
+ }
5723
+ fail(uploadId, error) {
5724
+ const active = this.activeUploads.get(uploadId);
5725
+ if (!active) return;
5726
+ active.completed = true;
5727
+ this.activeUploads.delete(uploadId);
5728
+ active.stream.destroy();
5729
+ this.sendResponse({
5730
+ uploadId,
5731
+ sessionId: active.sessionId,
5732
+ success: false,
5733
+ error,
5734
+ errorCode: ControlErrorCode.UNKNOWN
5735
+ });
5736
+ }
5737
+ sendResponse(payload) {
5738
+ this.deps.relayConnection.sendRaw(
5739
+ serializeControl({
5740
+ type: "remote_file_upload_stream_response",
5741
+ ...payload
5742
+ })
5743
+ );
5744
+ }
5745
+ };
5746
+
5747
+ // src/serve/remote-file-stream.ts
5748
+ import { createReadStream as createReadStream2, statSync as statSync3 } from "fs";
5749
+ import { basename } from "path";
5750
+
5751
+ // src/serve/remote-file-path.ts
5752
+ import { realpathSync } from "fs";
5753
+ import { extname as extname2, isAbsolute as isAbsolute4, resolve as resolve2 } from "path";
5754
+ var EXT_MIME_MAP = {
5755
+ ".png": "image/png",
5756
+ ".jpg": "image/jpeg",
5757
+ ".jpeg": "image/jpeg",
5758
+ ".gif": "image/gif",
5759
+ ".webp": "image/webp",
5760
+ ".svg": "image/svg+xml",
5761
+ ".bmp": "image/bmp",
5762
+ ".pdf": "application/pdf",
5763
+ ".json": "application/json",
5764
+ ".xml": "application/xml",
5765
+ ".html": "text/html",
5766
+ ".htm": "text/html",
5767
+ ".txt": "text/plain",
5768
+ ".md": "text/markdown",
5769
+ ".log": "text/plain",
5770
+ ".csv": "text/csv",
5771
+ ".js": "application/javascript",
5772
+ ".mjs": "application/javascript",
5773
+ ".ts": "application/typescript",
5774
+ ".tsx": "application/typescript",
5775
+ ".zip": "application/zip",
5776
+ ".tar": "application/x-tar",
5777
+ ".gz": "application/gzip",
5778
+ ".mp4": "video/mp4",
5779
+ ".mp3": "audio/mpeg",
5780
+ ".wav": "audio/wav"
5781
+ };
5782
+ function guessMimeType(filePath) {
5783
+ const ext = extname2(filePath).toLowerCase();
5784
+ return EXT_MIME_MAP[ext] ?? "application/octet-stream";
5785
+ }
5786
+ function resolveRemoteFilePath(rawPath, cwd) {
5787
+ const candidate = isAbsolute4(rawPath) ? resolve2(rawPath) : resolve2(cwd, rawPath);
5788
+ return realpathSync(candidate);
5789
+ }
5790
+
5791
+ // src/serve/remote-file-stream.ts
5792
+ var FILE_STREAM_CHUNK_BYTES = 256 * 1024;
5793
+ function errorCode(err) {
5794
+ if (err instanceof Error && "errorCode" in err && typeof err.errorCode === "string") {
5795
+ return err.errorCode;
5796
+ }
5797
+ return classifyPathError(err);
5798
+ }
5799
+ var RemoteFileStreamManager = class {
5800
+ constructor(deps) {
5801
+ this.deps = deps;
5802
+ }
5803
+ deps;
5804
+ activeStreams = /* @__PURE__ */ new Map();
5805
+ start(msg) {
5806
+ const { streamId, sessionId, path } = msg;
5807
+ if (this.activeStreams.has(streamId)) {
5808
+ this.sendResponse({
5809
+ streamId,
5810
+ sessionId,
5811
+ success: false,
5812
+ error: "\u6587\u4EF6\u6D41\u5DF2\u5B58\u5728",
5813
+ errorCode: ControlErrorCode.UNKNOWN
5814
+ });
5815
+ return;
5816
+ }
5817
+ const session = this.deps.sessionManager.getSession(sessionId);
5818
+ if (!session) {
5819
+ this.sendResponse({
5820
+ streamId,
5821
+ sessionId,
5822
+ success: false,
5823
+ path,
5824
+ error: "\u4F1A\u8BDD\u4E0D\u5B58\u5728",
5825
+ errorCode: ControlErrorCode.SESSION_NOT_FOUND
5826
+ });
5827
+ serviceLogger.warn({ sessionId, streamId }, "Remote file stream rejected: session not found");
5828
+ return;
5829
+ }
5830
+ try {
5831
+ const resolvedPath = resolveRemoteFilePath(path, session.cwd);
5832
+ const stat2 = statSync3(resolvedPath);
5833
+ if (!stat2.isFile()) {
5834
+ this.sendResponse({
5835
+ streamId,
5836
+ sessionId,
5837
+ success: false,
5838
+ path,
5839
+ error: "\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6",
5840
+ errorCode: ControlErrorCode.INVALID_PATH
5841
+ });
5842
+ return;
5843
+ }
5844
+ const stream = createReadStream2(resolvedPath, { highWaterMark: FILE_STREAM_CHUNK_BYTES });
5845
+ const active = {
5846
+ stream,
5847
+ chunkSeq: 0,
5848
+ completed: false,
5849
+ canceled: false
5850
+ };
5851
+ this.activeStreams.set(streamId, active);
5852
+ this.sendResponse({
5853
+ streamId,
5854
+ sessionId,
5855
+ success: true,
5856
+ path,
5857
+ mimeType: guessMimeType(resolvedPath),
5858
+ size: stat2.size,
5859
+ fileName: basename(resolvedPath) || "download"
5860
+ });
5861
+ stream.on("data", (chunk) => {
5862
+ if (active.canceled) return;
5863
+ const data = chunk instanceof Buffer ? chunk : Buffer.from(chunk);
5864
+ this.deps.relayConnection.sendBinary(
5865
+ encodeFileStreamFrame(streamId, active.chunkSeq, data)
5866
+ );
5867
+ active.chunkSeq += 1;
5868
+ });
5869
+ stream.on("end", () => {
5870
+ this.complete(streamId, true);
5871
+ });
5872
+ stream.on("error", (err) => {
5873
+ if (active.canceled) return;
5874
+ this.complete(streamId, false, err instanceof Error ? err.message : String(err));
5875
+ });
5876
+ stream.on("close", () => {
5877
+ if (!active.completed && !active.canceled) {
5878
+ this.complete(streamId, false, "\u6587\u4EF6\u6D41\u63D0\u524D\u5173\u95ED");
5879
+ }
5880
+ });
5881
+ serviceLogger.info(
5882
+ { sessionId, streamId, path, size: stat2.size },
5883
+ "Remote file stream started"
5884
+ );
5885
+ } catch (err) {
5886
+ this.sendResponse({
5887
+ streamId,
5888
+ sessionId,
5889
+ success: false,
5890
+ path,
5891
+ error: err instanceof Error ? err.message : String(err),
5892
+ errorCode: errorCode(err)
5893
+ });
5894
+ serviceLogger.warn(
5895
+ { sessionId, streamId, path, errorCode: errorCode(err), error: String(err) },
5896
+ "Remote file stream failed before start"
5897
+ );
5898
+ }
5899
+ }
5900
+ cancel(msg) {
5901
+ const active = this.activeStreams.get(msg.streamId);
5902
+ if (!active) return;
5903
+ active.canceled = true;
5904
+ active.completed = true;
5905
+ this.activeStreams.delete(msg.streamId);
5906
+ active.stream.destroy();
5907
+ serviceLogger.info({ streamId: msg.streamId }, "Remote file stream canceled");
5908
+ }
5909
+ complete(streamId, success, error) {
5910
+ const active = this.activeStreams.get(streamId);
5911
+ if (active) {
5912
+ active.completed = true;
5913
+ this.activeStreams.delete(streamId);
5914
+ }
5915
+ this.deps.relayConnection.sendRaw(
5916
+ serializeControl({
5917
+ type: "remote_file_stream_complete",
5918
+ streamId,
5919
+ success,
5920
+ ...error ? { error, errorCode: ControlErrorCode.UNKNOWN } : {}
5921
+ })
5922
+ );
5923
+ serviceLogger.info({ streamId, success, error }, "Remote file stream completed");
5924
+ }
5925
+ sendResponse(payload) {
5926
+ this.deps.relayConnection.sendRaw(
5927
+ serializeControl({
5928
+ type: "remote_file_stream_response",
5929
+ ...payload
5930
+ })
5931
+ );
5932
+ }
5933
+ };
5934
+
6025
5935
  // src/serve.ts
6026
5936
  function resolveInterruptedApprovals(permissionBroker, hookEventRouter, relay, sessionId) {
6027
5937
  const approvals = permissionBroker.listSession(sessionId);
@@ -6106,7 +6016,6 @@ async function startService(options) {
6106
6016
  let proxyConfig = loadConfig({ relayName: options?.relayName });
6107
6017
  const getProviderEnv = () => buildProviderEnv(proxyConfig, process.env);
6108
6018
  const getAgentCliSuggestions = () => proxyConfig.agentCliSuggestions;
6109
- const getPreviewRoots = () => proxyConfig.previewRoots;
6110
6019
  const setAgentCliPath = (provider, path) => {
6111
6020
  const field = provider === "claude" ? "claudeBin" : "codexBin";
6112
6021
  const existing = proxyConfig.agentCliSuggestions[provider] ?? [];
@@ -6198,6 +6107,14 @@ async function startService(options) {
6198
6107
  onSessionClosed: eventBridge.cleanupSessionResources
6199
6108
  });
6200
6109
  const terminalWorkerSpawner = new TerminalWorkerSpawner();
6110
+ const remoteFileStreamManager = new RemoteFileStreamManager({
6111
+ relayConnection,
6112
+ sessionManager
6113
+ });
6114
+ const remoteFileUploadManager = new RemoteFileUploadManager({
6115
+ relayConnection,
6116
+ sessionManager
6117
+ });
6201
6118
  relayConnection.connect();
6202
6119
  serviceLogger.info(
6203
6120
  {
@@ -6230,9 +6147,15 @@ async function startService(options) {
6230
6147
  getProviderEnv,
6231
6148
  getAgentCliSuggestions,
6232
6149
  setAgentCliPath,
6233
- getPreviewRoots
6150
+ remoteFileStreamManager,
6151
+ remoteFileUploadManager
6234
6152
  });
6235
6153
  relayConnection.on("message", (msg) => relayRouter.handle(msg));
6154
+ relayConnection.on("binary", (data) => {
6155
+ if (!remoteFileUploadManager.handleBinary(data)) {
6156
+ serviceLogger.warn({ bytes: data.length }, "Relay binary message dropped: unknown frame");
6157
+ }
6158
+ });
6236
6159
  relayConnection.on("connected", () => {
6237
6160
  void controlHandlers.reinitializeOnReconnect().catch((err) => {
6238
6161
  serviceLogger.error(
@@ -6279,7 +6202,7 @@ async function startService(options) {
6279
6202
  });
6280
6203
  });
6281
6204
  server.listen(SOCK_PATH, () => {
6282
- writeFileSync4(PID_PATH, String(process.pid));
6205
+ writeFileSync2(PID_PATH, String(process.pid));
6283
6206
  chmodSync(SOCK_PATH, 384);
6284
6207
  serviceLogger.info({ pid: process.pid, sock: SOCK_PATH }, "Service started");
6285
6208
  });