@dev-anywhere/proxy 0.9.0 → 0.9.2

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 (73) hide show
  1. package/README.md +25 -3
  2. package/dist/autostart-C3RNQ65S.js +292 -0
  3. package/dist/autostart-C3RNQ65S.js.map +1 -0
  4. package/dist/chunk-2YUDGRJ6.js +379 -0
  5. package/dist/chunk-2YUDGRJ6.js.map +1 -0
  6. package/dist/chunk-74HWO753.js +285 -0
  7. package/dist/chunk-74HWO753.js.map +1 -0
  8. package/dist/chunk-77QVUYU7.js +42 -0
  9. package/dist/chunk-77QVUYU7.js.map +1 -0
  10. package/dist/{chunk-HWPURRXB.js → chunk-7LUBU2WA.js} +10 -2
  11. package/dist/{chunk-HWPURRXB.js.map → chunk-7LUBU2WA.js.map} +1 -1
  12. package/dist/chunk-DAFUSBKJ.js +299 -0
  13. package/dist/chunk-DAFUSBKJ.js.map +1 -0
  14. package/dist/{chunk-HLN3NOD2.js → chunk-GFDOVLGL.js} +70 -1
  15. package/dist/chunk-GFDOVLGL.js.map +1 -0
  16. package/dist/{chunk-SEMZ7GW7.js → chunk-GYL5JKWQ.js} +3 -3
  17. package/dist/{chunk-57LA2LWY.js → chunk-HYDXGNKA.js} +2 -2
  18. package/dist/chunk-ICSO3ZIS.js +658 -0
  19. package/dist/chunk-ICSO3ZIS.js.map +1 -0
  20. package/dist/chunk-JZ7MWN24.js +22 -0
  21. package/dist/chunk-JZ7MWN24.js.map +1 -0
  22. package/dist/chunk-KINQESTO.js +145 -0
  23. package/dist/chunk-KINQESTO.js.map +1 -0
  24. package/dist/{chunk-ZNMJH7BK.js → chunk-KWODOJBK.js} +3 -3
  25. package/dist/chunk-MLE2OKCM.js +116 -0
  26. package/dist/chunk-MLE2OKCM.js.map +1 -0
  27. package/dist/{chunk-UJEZAG57.js → chunk-PCF2R2TG.js} +3 -1
  28. package/dist/{chunk-UJEZAG57.js.map → chunk-PCF2R2TG.js.map} +1 -1
  29. package/dist/{chunk-RN3KQK6E.js → chunk-V4HDLUAQ.js} +770 -774
  30. package/dist/chunk-V4HDLUAQ.js.map +1 -0
  31. package/dist/{chunk-DZ4GXMP5.js → chunk-VHMAUU72.js} +56 -68
  32. package/dist/chunk-VHMAUU72.js.map +1 -0
  33. package/dist/{chunk-K72MFCMC.js → chunk-XADKKDUV.js} +29 -153
  34. package/dist/chunk-XADKKDUV.js.map +1 -0
  35. package/dist/{chunk-WRU3BXW6.js → chunk-YK2XKOP4.js} +26 -10
  36. package/dist/chunk-YK2XKOP4.js.map +1 -0
  37. package/dist/index.js +130 -343
  38. package/dist/index.js.map +1 -1
  39. package/dist/logger-24TGGN76.js +10 -0
  40. package/dist/logger-24TGGN76.js.map +1 -0
  41. package/dist/logger-B7B64O4P.js +14 -0
  42. package/dist/logger-B7B64O4P.js.map +1 -0
  43. package/dist/{quick-tunnel-RI62V2RH.js → quick-tunnel-ZIFTYUUD.js} +3 -3
  44. package/dist/{relay-token-ZP3PAZD2.js → relay-token-N3BSBURG.js} +5 -5
  45. package/dist/serve.js +1290 -371
  46. package/dist/serve.js.map +1 -1
  47. package/dist/session-worker.js +91 -76
  48. package/dist/session-worker.js.map +1 -1
  49. package/dist/{terminal-AHMO45YN.js → terminal-7JY6J3XN.js} +88 -36
  50. package/dist/terminal-7JY6J3XN.js.map +1 -0
  51. package/dist/terminal-worker.js +93 -44
  52. package/dist/terminal-worker.js.map +1 -1
  53. package/dist/update-runner.js +87 -62
  54. package/dist/update-runner.js.map +1 -1
  55. package/package.json +9 -6
  56. package/scripts/postinstall.cjs +22 -0
  57. package/dist/chunk-DZ4GXMP5.js.map +0 -1
  58. package/dist/chunk-HLN3NOD2.js.map +0 -1
  59. package/dist/chunk-K72MFCMC.js.map +0 -1
  60. package/dist/chunk-KGTYU4WO.js +0 -36
  61. package/dist/chunk-KGTYU4WO.js.map +0 -1
  62. package/dist/chunk-RN3KQK6E.js.map +0 -1
  63. package/dist/chunk-WC3KEY7N.js +0 -158
  64. package/dist/chunk-WC3KEY7N.js.map +0 -1
  65. package/dist/chunk-WRU3BXW6.js.map +0 -1
  66. package/dist/chunk-YM74AWYC.js +0 -155
  67. package/dist/chunk-YM74AWYC.js.map +0 -1
  68. package/dist/terminal-AHMO45YN.js.map +0 -1
  69. /package/dist/{chunk-SEMZ7GW7.js.map → chunk-GYL5JKWQ.js.map} +0 -0
  70. /package/dist/{chunk-57LA2LWY.js.map → chunk-HYDXGNKA.js.map} +0 -0
  71. /package/dist/{chunk-ZNMJH7BK.js.map → chunk-KWODOJBK.js.map} +0 -0
  72. /package/dist/{quick-tunnel-RI62V2RH.js.map → quick-tunnel-ZIFTYUUD.js.map} +0 -0
  73. /package/dist/{relay-token-ZP3PAZD2.js.map → relay-token-N3BSBURG.js.map} +0 -0
package/dist/serve.js CHANGED
@@ -1,17 +1,30 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ buildProviderEnv,
4
+ loadConfig,
5
+ saveAgentCliPath
6
+ } from "./chunk-GYL5JKWQ.js";
7
+ import {
8
+ PREVIEW_HEALTH_HEADER,
9
+ PREVIEW_HEALTH_MARKER,
10
+ PREVIEW_HEALTH_PATH,
11
+ probePreviewTunnelEdge,
12
+ startCloudflaredQuickTunnel,
13
+ terminateTunnelChild
14
+ } from "./chunk-C5RUR5MY.js";
2
15
  import {
3
16
  PersistedSessionRecordSchema,
4
17
  extractAgentInvocation,
5
18
  normalizeCliArgs,
6
- probeProcess,
7
- processExistsOrIsInaccessible,
8
19
  readSessionRuntimeIpcVersions,
9
- refreshLoginShellPath,
10
- sessionRuntimeIpcVersionsMatch,
20
+ sessionRuntimeIpcVersionMatches,
11
21
  stripProxyProfileArgs,
12
- unlinkIfPresent,
13
22
  writeSessionRuntimeIpcVersions
14
- } from "./chunk-K72MFCMC.js";
23
+ } from "./chunk-MLE2OKCM.js";
24
+ import {
25
+ processExistsOrIsInaccessible,
26
+ refreshLoginShellPath
27
+ } from "./chunk-XADKKDUV.js";
15
28
  import {
16
29
  ContentBlockDeltaSchema,
17
30
  IGNORED_EVENT_TYPES,
@@ -20,10 +33,14 @@ import {
20
33
  createScopedApprovalRequestIdFactory,
21
34
  disposeSeqCounter,
22
35
  getSeqCounterFor
23
- } from "./chunk-57LA2LWY.js";
36
+ } from "./chunk-HYDXGNKA.js";
37
+ import {
38
+ atomicWriteFileSync
39
+ } from "./chunk-NQDJ6QAM.js";
24
40
  import {
25
- compareStableVersions
26
- } from "./chunk-HWPURRXB.js";
41
+ compareStableVersions,
42
+ selectHighestStableVersion
43
+ } from "./chunk-7LUBU2WA.js";
27
44
  import {
28
45
  PROXY_PACKAGE_ROOT,
29
46
  PROXY_VERSION
@@ -42,19 +59,32 @@ import {
42
59
  KimiPermissionModeUnsupportedError,
43
60
  buildKimiTerminalArgs,
44
61
  detectAgentCliStatus,
45
- findExecutableCandidates,
46
62
  resolveCodexPermissionPolicy,
47
63
  resolveKimiAcpMode
48
- } from "./chunk-DZ4GXMP5.js";
64
+ } from "./chunk-VHMAUU72.js";
49
65
  import {
50
66
  PtyRenderSequencer,
51
67
  PtySynchronizedOutputCoalescer,
68
+ TERMINAL_ADMISSION_FRAME_MAX_BYTES,
69
+ TERMINAL_ADMISSION_VERSION,
52
70
  appendPtySemanticTextTail,
53
71
  extractOscSequences,
54
72
  extractOscSignals,
55
73
  extractOscWorkingDirectory,
56
- extractTextSignals
57
- } from "./chunk-HLN3NOD2.js";
74
+ extractTextSignals,
75
+ isTerminalAdmissionRequestCandidate,
76
+ parseTerminalAdmissionRequest,
77
+ serializeTerminalAdmissionMessage
78
+ } from "./chunk-GFDOVLGL.js";
79
+ import {
80
+ startServiceControl,
81
+ tryAcquireFileLock,
82
+ tryConnectSocket
83
+ } from "./chunk-DAFUSBKJ.js";
84
+ import {
85
+ IS_DEV,
86
+ spawnScript
87
+ } from "./chunk-PCF2R2TG.js";
58
88
  import {
59
89
  ControlErrorCode,
60
90
  DEVICE_PREVIEW_FRAME_MAX_BYTES,
@@ -66,6 +96,8 @@ import {
66
96
  PTY_INITIAL_MIN_COLS,
67
97
  PTY_INITIAL_MIN_ROWS,
68
98
  PreviewSourceSchema,
99
+ ProxyProtocolAdmissionDirection,
100
+ ProxyUpgradeBootstrapResponseSchema,
69
101
  RELAY_CONTROL_PROTOCOL_VERSION,
70
102
  RELAY_JSON_MESSAGE_MAX_BYTES,
71
103
  RelayCloseCode,
@@ -77,6 +109,7 @@ import {
77
109
  WORKER_IPC_PROTOCOL_VERSION,
78
110
  WebPreviewNameSchema,
79
111
  buildMessage,
112
+ compareProxyRelayProtocolVersions,
80
113
  createFSM,
81
114
  createIpcReader,
82
115
  createWorkerReader,
@@ -87,27 +120,33 @@ import {
87
120
  encodeDevicePreviewH264ProxyPacket,
88
121
  encodeFileStreamFrame,
89
122
  isCompactCommandText,
123
+ isProxyProtocolRejectDirection,
90
124
  serializeControl,
91
125
  serializeIpc,
92
126
  serializeWorkerMsg,
93
127
  summarizeToolActivity
94
- } from "./chunk-RN3KQK6E.js";
128
+ } from "./chunk-V4HDLUAQ.js";
129
+ import {
130
+ localIpcEndpointMayExist,
131
+ removeLocalIpcEndpoint,
132
+ setLocalIpcEndpointPermissions,
133
+ unlinkIfPresent
134
+ } from "./chunk-77QVUYU7.js";
95
135
  import {
96
136
  classifyCodexActiveWriterError,
97
137
  codexActiveWriterMessage,
98
138
  sanitizeProviderErrorTail
99
139
  } from "./chunk-J5V2TKSV.js";
100
140
  import {
101
- buildProviderEnv,
102
- loadConfig,
103
- saveAgentCliPath
104
- } from "./chunk-SEMZ7GW7.js";
105
- import {
106
- atomicWriteFileSync
107
- } from "./chunk-NQDJ6QAM.js";
141
+ defaultShell,
142
+ environmentValue,
143
+ findExecutableCandidates,
144
+ normalizeProcessEnvironment,
145
+ prepareCommandLaunch
146
+ } from "./chunk-KINQESTO.js";
108
147
  import {
109
148
  serviceLogger
110
- } from "./chunk-ZNMJH7BK.js";
149
+ } from "./chunk-KWODOJBK.js";
111
150
  import {
112
151
  DATA_DIR,
113
152
  DEFAULT_PROXY_PROFILE,
@@ -118,6 +157,8 @@ import {
118
157
  PREVIEW_RUN_DIR,
119
158
  PROFILE_NAME,
120
159
  PROXY_ID_PATH,
160
+ SERVICE_CONTROL_PATH,
161
+ SERVICE_RUNTIME_LOCK_PATH,
121
162
  SESSIONS_PATH,
122
163
  SESSION_RUNTIME_IPC_VERSION_PATH,
123
164
  SOCK_PATH,
@@ -125,50 +166,142 @@ import {
125
166
  ensureProfileWorkspace,
126
167
  sessionPaths,
127
168
  tildify
128
- } from "./chunk-WRU3BXW6.js";
129
- import {
130
- PREVIEW_HEALTH_HEADER,
131
- PREVIEW_HEALTH_MARKER,
132
- PREVIEW_HEALTH_PATH,
133
- probePreviewTunnelEdge,
134
- startCloudflaredQuickTunnel,
135
- terminateTunnelChild
136
- } from "./chunk-C5RUR5MY.js";
137
- import {
138
- IS_DEV,
139
- spawnScript
140
- } from "./chunk-UJEZAG57.js";
169
+ } from "./chunk-YK2XKOP4.js";
141
170
  import {
142
171
  flushLogger
143
- } from "./chunk-WC3KEY7N.js";
172
+ } from "./chunk-ICSO3ZIS.js";
144
173
 
145
174
  // src/serve.ts
146
175
  import { createServer as createServer4 } from "net";
147
- import { unlinkSync as unlinkSync2, writeFileSync as writeFileSync2, chmodSync, rmSync as rmSync2 } from "fs";
176
+ import { randomUUID } from "crypto";
177
+ import { existsSync as existsSync9, writeFileSync as writeFileSync2, rmSync as rmSync2 } from "fs";
148
178
 
149
179
  // src/serve/session-manager.ts
150
180
  import { readFileSync as readFileSync3, existsSync as existsSync2 } from "fs";
151
- import { isAbsolute, normalize } from "path";
181
+ import { isAbsolute as isAbsolute2, normalize } from "path";
152
182
  import { nanoid } from "nanoid";
153
183
 
154
184
  // src/common/managed-session-process.ts
155
185
  import { execFileSync } from "child_process";
156
- import { basename } from "path";
157
- import { readFileSync } from "fs";
186
+ import { basename, dirname, isAbsolute, join, resolve } from "path";
187
+ import { closeSync, openSync, readFileSync, readSync, realpathSync } from "fs";
188
+
189
+ // src/common/windows-process.ts
190
+ import { spawnSync } from "child_process";
191
+ function readWindowsProcess(pid) {
192
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;
193
+ const script = [
194
+ "$ErrorActionPreference = 'Stop'",
195
+ "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
196
+ `Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' -Property ProcessId,ParentProcessId,CommandLine | Select-Object ProcessId, ParentProcessId, CommandLine | ConvertTo-Json -Compress`
197
+ ].join("; ");
198
+ const result = spawnSync(
199
+ "powershell.exe",
200
+ ["-NoProfile", "-NonInteractive", "-Command", script],
201
+ {
202
+ encoding: "utf8",
203
+ // Include PowerShell/CIM cold startup in the bounded query budget.
204
+ timeout: 5e3,
205
+ maxBuffer: 128 * 1024,
206
+ windowsHide: true,
207
+ stdio: ["ignore", "pipe", "ignore"]
208
+ }
209
+ );
210
+ if (result.error || result.status !== 0) return null;
211
+ try {
212
+ const record = JSON.parse(result.stdout);
213
+ if (typeof record !== "object" || record === null) return null;
214
+ const { ProcessId, ParentProcessId, CommandLine } = record;
215
+ if (ProcessId !== pid || typeof ParentProcessId !== "number" || !Number.isSafeInteger(ParentProcessId) || ParentProcessId < 0 || CommandLine !== null && typeof CommandLine !== "string") {
216
+ return null;
217
+ }
218
+ return { pid, parentPid: ParentProcessId, commandLine: CommandLine };
219
+ } catch {
220
+ return null;
221
+ }
222
+ }
223
+ function parseWindowsCommandLine(command) {
224
+ const argv = [];
225
+ let index = 0;
226
+ while (index < command.length) {
227
+ while (command[index] === " " || command[index] === " ") index += 1;
228
+ if (index >= command.length) break;
229
+ let argument = "";
230
+ let quoted = false;
231
+ while (index < command.length) {
232
+ if (!quoted && (command[index] === " " || command[index] === " ")) break;
233
+ let backslashes = 0;
234
+ while (command[index] === "\\") {
235
+ backslashes += 1;
236
+ index += 1;
237
+ }
238
+ if (command[index] === '"') {
239
+ argument += "\\".repeat(Math.floor(backslashes / 2));
240
+ if (backslashes % 2 === 1) {
241
+ argument += '"';
242
+ } else if (quoted && command[index + 1] === '"') {
243
+ argument += '"';
244
+ index += 1;
245
+ } else {
246
+ quoted = !quoted;
247
+ }
248
+ index += 1;
249
+ } else {
250
+ argument += "\\".repeat(backslashes);
251
+ if (index >= command.length) break;
252
+ if (!quoted && (command[index] === " " || command[index] === " ")) break;
253
+ argument += command[index];
254
+ index += 1;
255
+ }
256
+ }
257
+ if (quoted) return null;
258
+ argv.push(argument);
259
+ }
260
+ return argv.length > 0 ? argv : null;
261
+ }
262
+
263
+ // src/common/managed-session-process.ts
158
264
  function findEntryIndex(argv, name) {
159
265
  return argv.findIndex((arg) => {
160
- const file = basename(arg);
266
+ const file = basename(arg.replaceAll("\\", "/"));
161
267
  return file === name || file === `${name}.js` || file === `${name}.ts`;
162
268
  });
163
269
  }
164
- function findDevAnywhereEntryIndex(argv) {
165
- return argv.findIndex((arg) => {
166
- const file = basename(arg);
167
- if (file === "dev-anywhere") return true;
168
- if (file !== "index.js" && file !== "index.ts") return false;
169
- const pathSegments = arg.replaceAll("\\", "/").split("/");
170
- return pathSegments.includes("dev-anywhere") || pathSegments.includes("@dev-anywhere");
171
- });
270
+ function canonicalEntryPath(path) {
271
+ try {
272
+ const resolved = realpathSync(path);
273
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
274
+ } catch {
275
+ return null;
276
+ }
277
+ }
278
+ function isDevAnywhereCliEntry(path) {
279
+ if (!isAbsolute(path)) return false;
280
+ const entry = canonicalEntryPath(path);
281
+ if (entry === null) return false;
282
+ let directory = dirname(entry);
283
+ for (let depth = 0; depth < 8; depth += 1) {
284
+ let fd;
285
+ try {
286
+ fd = openSync(join(directory, "package.json"), "r");
287
+ const buffer = Buffer.alloc(65537);
288
+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);
289
+ if (bytes > 65536) return false;
290
+ const manifest = JSON.parse(buffer.subarray(0, bytes).toString("utf8"));
291
+ if (manifest?.name !== "@dev-anywhere/proxy") return false;
292
+ const bin = manifest.bin?.["dev-anywhere"];
293
+ if (typeof bin !== "string") return false;
294
+ return entry === canonicalEntryPath(resolve(directory, bin)) || entry === canonicalEntryPath(join(directory, "src", "index.ts"));
295
+ } catch (error) {
296
+ if (fd !== void 0 || error.code !== "ENOENT") return false;
297
+ } finally {
298
+ if (fd !== void 0) closeSync(fd);
299
+ }
300
+ const parent = dirname(directory);
301
+ if (parent === directory) break;
302
+ directory = parent;
303
+ }
304
+ return false;
172
305
  }
173
306
  function readOption(args, name) {
174
307
  const indexes = args.flatMap((arg, index) => arg === name ? [index] : []);
@@ -219,7 +352,7 @@ function processArgvMatchesManagedSession(argv, identity) {
219
352
  if (terminalWorkerIndex >= 0) {
220
353
  return identity.provider === "claude" && terminalWorkerSessionId(argv.slice(terminalWorkerIndex + 1)) === identity.id;
221
354
  }
222
- const entryIndex = findDevAnywhereEntryIndex(argv);
355
+ const entryIndex = argv.findIndex(isDevAnywhereCliEntry);
223
356
  if (entryIndex < 0 || identity.provider === void 0) return false;
224
357
  try {
225
358
  const invocation = extractAgentInvocation(
@@ -269,6 +402,10 @@ function parsePosixCommandLine(command) {
269
402
  }
270
403
  function readProcessArgv(pid) {
271
404
  if (!Number.isSafeInteger(pid) || pid <= 0) return null;
405
+ if (process.platform === "win32") {
406
+ const record = readWindowsProcess(pid);
407
+ return record?.commandLine ? parseWindowsCommandLine(record.commandLine) : null;
408
+ }
272
409
  if (process.platform === "linux") {
273
410
  try {
274
411
  const commandLine = readFileSync(`/proc/${pid}/cmdline`);
@@ -712,7 +849,7 @@ var SessionManager = class {
712
849
  const session = this.sessions.get(id);
713
850
  if (!session || session.mode !== "pty" || session.kind !== "terminal") return false;
714
851
  const nextCwd = normalize(cwd);
715
- if (!isAbsolute(nextCwd) || nextCwd === session.cwd) return false;
852
+ if (!isAbsolute2(nextCwd) || nextCwd === session.cwd) return false;
716
853
  const previousCwd = session.cwd;
717
854
  session.cwd = nextCwd;
718
855
  session.updatedAt = Date.now();
@@ -934,7 +1071,9 @@ var SessionManager = class {
934
1071
  return;
935
1072
  }
936
1073
  for (const item of parsed) {
937
- if (!this.allowSessionRuntimeHandover) {
1074
+ const mode = item !== null && typeof item === "object" && !Array.isArray(item) ? item.mode : void 0;
1075
+ const allowHandover = mode === "json" ? this.allowSessionRuntimeHandover.worker : mode === "pty" ? this.allowSessionRuntimeHandover.terminal : false;
1076
+ if (!allowHandover) {
938
1077
  const sessionId = item !== null && typeof item === "object" && typeof item.id === "string" ? item.id : void 0;
939
1078
  const managedProcessDiscarded = this.discardManagedSessionProcess(
940
1079
  item,
@@ -971,13 +1110,7 @@ var SessionManager = class {
971
1110
  continue;
972
1111
  }
973
1112
  const processAlive2 = this.isProcessAlive(info.pid);
974
- const identityVerified2 = processAlive2 && this.managedSessionProcess(info.pid, {
975
- id: info.id,
976
- mode: "pty",
977
- provider: info.provider,
978
- ptyOwner: "local-terminal"
979
- });
980
- if (identityVerified2) {
1113
+ if (processAlive2) {
981
1114
  this.pendingPtyReconnectMetadata.set(info.id, info);
982
1115
  this.pendingPtyReconnectDeadlines.set(
983
1116
  info.id,
@@ -990,8 +1123,8 @@ var SessionManager = class {
990
1123
  } else {
991
1124
  this.onSessionRemoved?.(info.id);
992
1125
  serviceLogger.info(
993
- { sessionId: info.id, pid: info.pid, processAlive: processAlive2, identityVerified: identityVerified2 },
994
- "PTY session cleaned on load because its process identity is unavailable"
1126
+ { sessionId: info.id, pid: info.pid },
1127
+ "PTY session cleaned on load because its process is no longer alive"
995
1128
  );
996
1129
  }
997
1130
  continue;
@@ -1025,7 +1158,7 @@ var SessionManager = class {
1025
1158
  import WebSocket from "ws";
1026
1159
  import { readFileSync as readFileSync4, existsSync as existsSync3 } from "fs";
1027
1160
  import { homedir } from "os";
1028
- import { join } from "path";
1161
+ import { join as join2 } from "path";
1029
1162
  import { nanoid as nanoid2 } from "nanoid";
1030
1163
  import { EventEmitter } from "events";
1031
1164
 
@@ -1053,12 +1186,13 @@ var MemoryMessageQueue = class {
1053
1186
  };
1054
1187
 
1055
1188
  // src/serve/relay-connection.ts
1056
- var DEFAULT_PROXY_ID_PATH = join(homedir(), ".dev-anywhere", "proxy-id");
1189
+ var DEFAULT_PROXY_ID_PATH = join2(homedir(), ".dev-anywhere", "proxy-id");
1057
1190
  var MAX_BACKOFF_MS = 3e4;
1058
1191
  var BASE_BACKOFF_MS = 1e3;
1059
1192
  var MAX_QUEUE_SIZE = 1e4;
1060
1193
  var DEFAULT_HEARTBEAT_INTERVAL_MS = 15e3;
1061
1194
  var DEFAULT_HEARTBEAT_TIMEOUT_MS = 1e4;
1195
+ var DEFAULT_READY_TIMEOUT_MS = 1e4;
1062
1196
  var RELAY_CONNECTION_WEBSOCKET_OPTIONS = {
1063
1197
  maxPayload: 10 * 1024 * 1024,
1064
1198
  perMessageDeflate: {
@@ -1078,28 +1212,38 @@ var RelayConnectionState = {
1078
1212
  REGISTERING: "registering",
1079
1213
  SYNCED: "synced",
1080
1214
  WAITING_RECONNECT: "waiting_reconnect",
1215
+ BLOCKED_REMOTE: "blocked_remote",
1081
1216
  CLOSED: "closed"
1082
1217
  };
1083
1218
  var RELAY_TRANSITIONS = {
1084
1219
  [RelayConnectionState.DISCONNECTED]: [
1085
1220
  RelayConnectionState.CONNECTING,
1221
+ RelayConnectionState.BLOCKED_REMOTE,
1086
1222
  RelayConnectionState.CLOSED
1087
1223
  ],
1088
1224
  [RelayConnectionState.CONNECTING]: [
1089
1225
  RelayConnectionState.REGISTERING,
1090
1226
  RelayConnectionState.WAITING_RECONNECT,
1227
+ RelayConnectionState.BLOCKED_REMOTE,
1091
1228
  RelayConnectionState.CLOSED
1092
1229
  ],
1093
1230
  [RelayConnectionState.REGISTERING]: [
1094
1231
  RelayConnectionState.SYNCED,
1095
1232
  RelayConnectionState.WAITING_RECONNECT,
1233
+ RelayConnectionState.BLOCKED_REMOTE,
1096
1234
  RelayConnectionState.CLOSED
1097
1235
  ],
1098
1236
  [RelayConnectionState.SYNCED]: [
1099
1237
  RelayConnectionState.WAITING_RECONNECT,
1238
+ RelayConnectionState.BLOCKED_REMOTE,
1100
1239
  RelayConnectionState.CLOSED
1101
1240
  ],
1102
1241
  [RelayConnectionState.WAITING_RECONNECT]: [
1242
+ RelayConnectionState.CONNECTING,
1243
+ RelayConnectionState.BLOCKED_REMOTE,
1244
+ RelayConnectionState.CLOSED
1245
+ ],
1246
+ [RelayConnectionState.BLOCKED_REMOTE]: [
1103
1247
  RelayConnectionState.CONNECTING,
1104
1248
  RelayConnectionState.CLOSED
1105
1249
  ],
@@ -1112,6 +1256,7 @@ var RelayConnection = class extends EventEmitter {
1112
1256
  queue = new MemoryMessageQueue();
1113
1257
  reconnectAttempt = 0;
1114
1258
  reconnectTimer = null;
1259
+ readyTimeout;
1115
1260
  heartbeatTimer = null;
1116
1261
  heartbeatTimeoutTimer = null;
1117
1262
  fsm = createFSM({
@@ -1128,6 +1273,9 @@ var RelayConnection = class extends EventEmitter {
1128
1273
  version;
1129
1274
  heartbeatIntervalMs;
1130
1275
  heartbeatTimeoutMs;
1276
+ readyTimeoutMs;
1277
+ protocolAdmissionDirection = ProxyProtocolAdmissionDirection.COMPATIBLE;
1278
+ disconnectedNotified = false;
1131
1279
  constructor(relayUrl, options) {
1132
1280
  super();
1133
1281
  this.relayUrl = relayUrl;
@@ -1137,6 +1285,8 @@ var RelayConnection = class extends EventEmitter {
1137
1285
  this.version = options?.version ?? PROXY_VERSION;
1138
1286
  this.heartbeatIntervalMs = options?.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
1139
1287
  this.heartbeatTimeoutMs = options?.heartbeatTimeoutMs ?? DEFAULT_HEARTBEAT_TIMEOUT_MS;
1288
+ const configuredReadyTimeoutMs = options?.readyTimeoutMs;
1289
+ this.readyTimeoutMs = typeof configuredReadyTimeoutMs === "number" && Number.isSafeInteger(configuredReadyTimeoutMs) && configuredReadyTimeoutMs > 0 ? configuredReadyTimeoutMs : DEFAULT_READY_TIMEOUT_MS;
1140
1290
  }
1141
1291
  // 从文件读取或生成新的 proxyId,生成后持久化到文件
1142
1292
  loadOrCreateProxyId(idPath) {
@@ -1162,13 +1312,15 @@ var RelayConnection = class extends EventEmitter {
1162
1312
  const url = this.token ? `${base}?token=${encodeURIComponent(this.token)}` : base;
1163
1313
  this.ws = new WebSocket(url, RELAY_CONNECTION_WEBSOCKET_OPTIONS);
1164
1314
  const socket = this.ws;
1165
- this.ws.on("open", () => {
1315
+ this.startReadyTimeout(socket);
1316
+ socket.on("open", () => {
1317
+ if (this.ws !== socket) return;
1166
1318
  if (!this.fsm.tryTransitionTo(RelayConnectionState.REGISTERING)) return;
1167
1319
  serviceLogger.info(
1168
1320
  { proxyId: this.proxyId, url: base, tokenSet: !!this.token },
1169
1321
  "Connected to relay server"
1170
1322
  );
1171
- this.ws.send(
1323
+ socket.send(
1172
1324
  serializeControl({
1173
1325
  type: "proxy_register",
1174
1326
  protocolVersion: RELAY_CONTROL_PROTOCOL_VERSION,
@@ -1178,7 +1330,8 @@ var RelayConnection = class extends EventEmitter {
1178
1330
  })
1179
1331
  );
1180
1332
  });
1181
- this.ws.on("message", (data, isBinary) => {
1333
+ socket.on("message", (data, isBinary) => {
1334
+ if (this.ws !== socket) return;
1182
1335
  const buf = data;
1183
1336
  if (isBinary) {
1184
1337
  if (this.fsm.current() !== RelayConnectionState.SYNCED) {
@@ -1219,21 +1372,32 @@ var RelayConnection = class extends EventEmitter {
1219
1372
  }
1220
1373
  const response = RelayControlSchema.safeParse(msg);
1221
1374
  if (!response.success || response.data.type !== "proxy_register_response") {
1375
+ const direction = compareProxyRelayProtocolVersions(
1376
+ RELAY_CONTROL_PROTOCOL_VERSION,
1377
+ msg.protocolVersion
1378
+ );
1222
1379
  serviceLogger.warn(
1223
- { issues: response.success ? void 0 : response.error.issues },
1380
+ { direction, issues: response.success ? void 0 : response.error.issues },
1224
1381
  "Invalid Proxy registration response; terminating relay connection"
1225
1382
  );
1226
- this.rejectRelayProtocol(socket, "invalid registration response");
1383
+ this.rejectRelayProtocol(
1384
+ socket,
1385
+ "invalid registration response",
1386
+ direction === ProxyProtocolAdmissionDirection.COMPATIBLE ? ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH : direction
1387
+ );
1227
1388
  return;
1228
1389
  }
1229
1390
  const { status, relayVersion, connectionId } = response.data;
1230
1391
  serviceLogger.info({ status, relayVersion }, "Received register response");
1231
1392
  if (!this.fsm.tryTransitionTo(RelayConnectionState.SYNCED)) return;
1393
+ this.clearReadyTimeout(socket);
1232
1394
  this.reconnectAttempt = 0;
1395
+ this.protocolAdmissionDirection = ProxyProtocolAdmissionDirection.COMPATIBLE;
1233
1396
  this.startHeartbeat();
1234
1397
  this.flushQueue();
1235
1398
  this.emit("relay_version", relayVersion);
1236
1399
  this.emit("stream_connection", connectionId);
1400
+ this.disconnectedNotified = false;
1237
1401
  this.emit("connected");
1238
1402
  return;
1239
1403
  }
@@ -1243,27 +1407,33 @@ var RelayConnection = class extends EventEmitter {
1243
1407
  }
1244
1408
  this.emit("message", msg);
1245
1409
  });
1246
- this.ws.on("close", (code, reason) => {
1410
+ socket.on("close", (code, reason) => {
1411
+ if (this.ws !== socket) {
1412
+ serviceLogger.debug({ code }, "Close from inactive Relay socket ignored");
1413
+ return;
1414
+ }
1415
+ this.clearReadyTimeout(socket);
1247
1416
  this.stopHeartbeat();
1248
1417
  this.ws = null;
1249
1418
  const closeMeta = { code, reason: reason.toString() || void 0 };
1250
1419
  if (code === RelayCloseCode.PROXY_PROTOCOL_REJECTED) {
1251
- this.fsm.tryTransitionTo(RelayConnectionState.CLOSED);
1252
- serviceLogger.warn(closeMeta, "Relay rejected Proxy control protocol");
1253
- this.emit("disconnected");
1420
+ const direction = isProxyProtocolRejectDirection(closeMeta.reason) ? closeMeta.reason : ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH;
1421
+ this.applyProtocolRejection(direction, "websocket", closeMeta);
1254
1422
  } else if (this.fsm.current() !== RelayConnectionState.CLOSED) {
1255
1423
  this.fsm.tryTransitionTo(RelayConnectionState.WAITING_RECONNECT);
1256
1424
  serviceLogger.info(closeMeta, "Relay connection closed unexpectedly");
1257
- this.emit("disconnected");
1425
+ this.emitDisconnectedOnce();
1258
1426
  this.scheduleReconnect();
1259
1427
  } else {
1260
1428
  serviceLogger.info(closeMeta, "Relay connection closed");
1261
1429
  }
1262
1430
  });
1263
- this.ws.on("error", (err) => {
1431
+ socket.on("error", (err) => {
1432
+ if (this.ws !== socket) return;
1264
1433
  serviceLogger.error({ error: String(err) }, "Relay connection error");
1265
1434
  });
1266
- this.ws.on("pong", () => {
1435
+ socket.on("pong", () => {
1436
+ if (this.ws !== socket) return;
1267
1437
  this.clearHeartbeatTimeout();
1268
1438
  });
1269
1439
  } catch (err) {
@@ -1274,6 +1444,37 @@ var RelayConnection = class extends EventEmitter {
1274
1444
  }
1275
1445
  }
1276
1446
  }
1447
+ startReadyTimeout(socket) {
1448
+ this.clearReadyTimeout();
1449
+ const timer = setTimeout(() => {
1450
+ if (this.readyTimeout?.socket !== socket) return;
1451
+ this.readyTimeout = void 0;
1452
+ if (this.ws !== socket || this.fsm.current() !== RelayConnectionState.CONNECTING && this.fsm.current() !== RelayConnectionState.REGISTERING) {
1453
+ return;
1454
+ }
1455
+ serviceLogger.warn(
1456
+ { timeoutMs: this.readyTimeoutMs, state: this.fsm.current() },
1457
+ "Relay connection did not become ready in time"
1458
+ );
1459
+ this.stopHeartbeat();
1460
+ this.ws = null;
1461
+ if (!this.fsm.tryTransitionTo(RelayConnectionState.WAITING_RECONNECT)) return;
1462
+ this.emitDisconnectedOnce();
1463
+ this.scheduleReconnect();
1464
+ try {
1465
+ socket.terminate();
1466
+ } catch (error) {
1467
+ serviceLogger.debug({ error: String(error) }, "Timed-out Relay socket was already closed");
1468
+ }
1469
+ }, this.readyTimeoutMs);
1470
+ timer.unref?.();
1471
+ this.readyTimeout = { socket, timer };
1472
+ }
1473
+ clearReadyTimeout(socket) {
1474
+ if (!this.readyTimeout || socket && this.readyTimeout.socket !== socket) return;
1475
+ clearTimeout(this.readyTimeout.timer);
1476
+ this.readyTimeout = void 0;
1477
+ }
1277
1478
  startHeartbeat() {
1278
1479
  this.stopHeartbeat();
1279
1480
  if (this.heartbeatIntervalMs <= 0 || this.heartbeatTimeoutMs <= 0) return;
@@ -1327,12 +1528,65 @@ var RelayConnection = class extends EventEmitter {
1327
1528
  serviceLogger.warn({ reason }, "Relay connection heartbeat failed; terminating stale socket");
1328
1529
  ws.terminate();
1329
1530
  }
1330
- rejectRelayProtocol(ws, reason) {
1531
+ rejectRelayProtocol(ws, detail, direction = ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH) {
1331
1532
  if (this.ws !== ws || this.fsm.current() === RelayConnectionState.CLOSED) return;
1533
+ this.clearReadyTimeout(ws);
1332
1534
  this.stopHeartbeat();
1333
- this.fsm.tryTransitionTo(RelayConnectionState.CLOSED);
1334
- serviceLogger.warn({ reason }, "Relay control protocol rejected");
1335
- ws.close(RelayCloseCode.PROXY_PROTOCOL_REJECTED, reason.slice(0, 123));
1535
+ serviceLogger.warn({ detail, direction }, "Relay control protocol rejected");
1536
+ this.ws = null;
1537
+ ws.close(RelayCloseCode.PROXY_PROTOCOL_REJECTED, direction);
1538
+ this.applyProtocolRejection(direction, "local_validation");
1539
+ }
1540
+ /** Apply a result from the stable HTTP bootstrap channel. */
1541
+ applyProtocolAdmission(direction) {
1542
+ if (direction === ProxyProtocolAdmissionDirection.COMPATIBLE) {
1543
+ if (!this.fsm.is(RelayConnectionState.BLOCKED_REMOTE)) return;
1544
+ this.protocolAdmissionDirection = direction;
1545
+ if (!this.fsm.tryTransitionTo(RelayConnectionState.CONNECTING)) return;
1546
+ serviceLogger.info("Relay control protocol is compatible; reconnecting");
1547
+ this.doConnect();
1548
+ return;
1549
+ }
1550
+ this.applyProtocolRejection(direction, "http_bootstrap");
1551
+ }
1552
+ applyProtocolRejection(direction, source, closeMeta) {
1553
+ const previousState = this.fsm.current();
1554
+ if (previousState === RelayConnectionState.CLOSED) return;
1555
+ if (direction === ProxyProtocolAdmissionDirection.RELAY_OUTDATED && previousState === RelayConnectionState.BLOCKED_REMOTE) {
1556
+ return;
1557
+ }
1558
+ if (this.reconnectTimer) {
1559
+ clearTimeout(this.reconnectTimer);
1560
+ this.reconnectTimer = null;
1561
+ }
1562
+ this.clearReadyTimeout();
1563
+ this.stopHeartbeat();
1564
+ const socket = this.ws;
1565
+ this.ws = null;
1566
+ this.protocolAdmissionDirection = direction;
1567
+ const targetState = direction === ProxyProtocolAdmissionDirection.RELAY_OUTDATED ? RelayConnectionState.BLOCKED_REMOTE : RelayConnectionState.CLOSED;
1568
+ if (!this.fsm.tryTransitionTo(targetState)) return;
1569
+ serviceLogger.warn(
1570
+ { direction, source, previousState, ...closeMeta },
1571
+ direction === ProxyProtocolAdmissionDirection.RELAY_OUTDATED ? "Relay control protocol is older; WebSocket retries paused" : direction === ProxyProtocolAdmissionDirection.PROXY_OUTDATED ? "Proxy control protocol is older; waiting for Proxy update" : "Proxy/Relay control protocol mismatch; retries stopped"
1572
+ );
1573
+ this.emit("protocol_blocked", { direction, source });
1574
+ if (socket) {
1575
+ try {
1576
+ socket.terminate();
1577
+ } catch (error) {
1578
+ serviceLogger.debug(
1579
+ { error: String(error), direction },
1580
+ "Protocol-blocked Relay socket was already closed"
1581
+ );
1582
+ }
1583
+ }
1584
+ if (previousState !== RelayConnectionState.DISCONNECTED) this.emitDisconnectedOnce();
1585
+ }
1586
+ emitDisconnectedOnce() {
1587
+ if (this.disconnectedNotified) return;
1588
+ this.disconnectedNotified = true;
1589
+ this.emit("disconnected");
1336
1590
  }
1337
1591
  // 将队列中缓存的消息依次发送到 relay
1338
1592
  flushQueue() {
@@ -1342,12 +1596,16 @@ var RelayConnection = class extends EventEmitter {
1342
1596
  }
1343
1597
  // 计算全抖动指数退避延迟并调度重连
1344
1598
  scheduleReconnect() {
1599
+ if (this.reconnectTimer || this.fsm.current() !== RelayConnectionState.WAITING_RECONNECT) {
1600
+ return;
1601
+ }
1345
1602
  const backoff = Math.random() * Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * Math.pow(2, this.reconnectAttempt));
1346
1603
  serviceLogger.info(
1347
1604
  { attempt: this.reconnectAttempt + 1, backoffMs: Math.round(backoff) },
1348
1605
  "Scheduling reconnect"
1349
1606
  );
1350
1607
  this.reconnectTimer = setTimeout(() => {
1608
+ this.reconnectTimer = null;
1351
1609
  this.reconnectAttempt++;
1352
1610
  if (!this.fsm.tryTransitionTo(RelayConnectionState.CONNECTING)) return;
1353
1611
  this.doConnect();
@@ -1388,18 +1646,25 @@ var RelayConnection = class extends EventEmitter {
1388
1646
  // 主动关闭连接,发送 proxy_disconnect 通知 relay 立即清理,不触发重连
1389
1647
  close() {
1390
1648
  if (this.fsm.is(RelayConnectionState.CLOSED)) return;
1649
+ const wasSynced = this.fsm.is(RelayConnectionState.SYNCED);
1391
1650
  this.fsm.tryTransitionTo(RelayConnectionState.CLOSED);
1392
1651
  if (this.reconnectTimer) {
1393
1652
  clearTimeout(this.reconnectTimer);
1394
1653
  this.reconnectTimer = null;
1395
1654
  }
1655
+ this.clearReadyTimeout();
1396
1656
  this.stopHeartbeat();
1397
- if (this.ws) {
1398
- if (this.ws.readyState === WebSocket.OPEN) {
1399
- this.ws.send(serializeControl({ type: "proxy_disconnect", proxyId: this.proxyId }));
1657
+ const socket = this.ws;
1658
+ this.ws = null;
1659
+ if (socket) {
1660
+ if (socket.readyState === WebSocket.OPEN) {
1661
+ if (wasSynced) {
1662
+ socket.send(serializeControl({ type: "proxy_disconnect", proxyId: this.proxyId }));
1663
+ }
1664
+ socket.close();
1665
+ } else {
1666
+ socket.terminate();
1400
1667
  }
1401
- this.ws.close();
1402
- this.ws = null;
1403
1668
  }
1404
1669
  }
1405
1670
  // 获取当前 proxyId
@@ -1413,28 +1678,29 @@ var RelayConnection = class extends EventEmitter {
1413
1678
  connectionState: this.fsm.current(),
1414
1679
  proxyId: this.proxyId,
1415
1680
  reconnectAttempt: this.reconnectAttempt,
1416
- queueDepth: this.queue.size()
1681
+ queueDepth: this.queue.size(),
1682
+ protocolAdmissionDirection: this.protocolAdmissionDirection
1417
1683
  };
1418
1684
  }
1419
1685
  };
1420
1686
 
1421
1687
  // src/serve/handlers/control-messages.ts
1422
1688
  import { readdir as readdir2, mkdir } from "fs/promises";
1423
- import { join as join4, isAbsolute as isAbsolute3, normalize as normalize2 } from "path";
1689
+ import { join as join5, isAbsolute as isAbsolute4, normalize as normalize2 } from "path";
1424
1690
 
1425
1691
  // src/serve/session-history.ts
1426
1692
  import { readdir, stat, lstat, access, open, readFile } from "fs/promises";
1427
1693
  import { createReadStream } from "fs";
1428
- import { isAbsolute as isAbsolute2, join as join2, resolve, sep } from "path";
1694
+ import { isAbsolute as isAbsolute3, join as join3, resolve as resolve2, sep } from "path";
1429
1695
  import { homedir as homedir2, tmpdir } from "os";
1430
1696
  import { createInterface } from "readline";
1431
- var claudeProjectsDir = () => join2(homedir2(), ".claude", "projects");
1432
- var codexSessionsDir = () => join2(homedir2(), ".codex", "sessions");
1697
+ var claudeProjectsDir = () => join3(homedir2(), ".claude", "projects");
1698
+ var codexSessionsDir = () => join3(homedir2(), ".codex", "sessions");
1433
1699
  var kimiCodeHome = () => {
1434
1700
  const configured = process.env.KIMI_CODE_HOME?.trim();
1435
- return configured ? resolve(configured) : join2(homedir2(), ".kimi-code");
1701
+ return configured ? resolve2(configured) : join3(homedir2(), ".kimi-code");
1436
1702
  };
1437
- var kimiSessionsDir = () => join2(kimiCodeHome(), "sessions");
1703
+ var kimiSessionsDir = () => join3(kimiCodeHome(), "sessions");
1438
1704
  var UNTITLED_SESSION_TITLE = "\u672A\u547D\u540D\u4F1A\u8BDD";
1439
1705
  var MAX_HISTORY_TITLE_LENGTH = 40;
1440
1706
  var IGNORED_SLASH_COMMANDS = /* @__PURE__ */ new Set([
@@ -1484,8 +1750,8 @@ async function scanSessionHistory(options = {}) {
1484
1750
  }
1485
1751
  function normalizeAbsolutePath(path) {
1486
1752
  const trimmed = path.trim();
1487
- if (!trimmed || !isAbsolute2(trimmed)) return null;
1488
- let resolved = resolve(trimmed);
1753
+ if (!trimmed || !isAbsolute3(trimmed)) return null;
1754
+ let resolved = resolve2(trimmed);
1489
1755
  while (resolved.length > 1 && resolved.endsWith(sep)) {
1490
1756
  resolved = resolved.slice(0, -1);
1491
1757
  }
@@ -1517,7 +1783,7 @@ async function scanClaudeSessionHistory() {
1517
1783
  return [];
1518
1784
  }
1519
1785
  for (const encodedDir of projectDirs) {
1520
- const projectPath = join2(claudeProjectsDir(), encodedDir);
1786
+ const projectPath = join3(claudeProjectsDir(), encodedDir);
1521
1787
  let files;
1522
1788
  try {
1523
1789
  files = await readdir(projectPath);
@@ -1526,7 +1792,7 @@ async function scanClaudeSessionHistory() {
1526
1792
  }
1527
1793
  for (const file of files) {
1528
1794
  if (!file.endsWith(".jsonl")) continue;
1529
- const filePath = join2(projectPath, file);
1795
+ const filePath = join3(projectPath, file);
1530
1796
  try {
1531
1797
  const fileStat = await stat(filePath);
1532
1798
  const sessionId = file.replace(/\.jsonl$/, "");
@@ -1581,7 +1847,7 @@ async function scanKimiSessionHistory() {
1581
1847
  const state = await readKimiSessionState(filePath);
1582
1848
  if (!state || state.archived === true) continue;
1583
1849
  if (typeof state.id !== "string" || !SAFE_SESSION_ID_PATTERN.test(state.id)) continue;
1584
- if (typeof state.cwd !== "string" || !isAbsolute2(state.cwd)) continue;
1850
+ if (typeof state.cwd !== "string" || !isAbsolute3(state.cwd)) continue;
1585
1851
  const rawTitle = typeof state.title === "string" ? state.title : typeof state.lastPrompt === "string" ? state.lastPrompt : "";
1586
1852
  let updatedAt;
1587
1853
  if (typeof state.updatedAt === "number" && Number.isFinite(state.updatedAt)) {
@@ -1636,7 +1902,7 @@ async function findClaudeSessionFile(claudeSessionId) {
1636
1902
  return null;
1637
1903
  }
1638
1904
  for (const encodedDir of projectDirs) {
1639
- const filePath = join2(claudeProjectsDir(), encodedDir, `${claudeSessionId}.jsonl`);
1905
+ const filePath = join3(claudeProjectsDir(), encodedDir, `${claudeSessionId}.jsonl`);
1640
1906
  try {
1641
1907
  await access(filePath);
1642
1908
  return filePath;
@@ -1673,7 +1939,7 @@ async function findKimiSessionFile(kimiSessionId) {
1673
1939
  for (const stateFile of stateFiles) {
1674
1940
  const state = await readKimiSessionState(stateFile);
1675
1941
  if (state?.id !== kimiSessionId) continue;
1676
- const wireFile = join2(stateFile.slice(0, -"state.json".length), "agents", "main", "wire.jsonl");
1942
+ const wireFile = join3(stateFile.slice(0, -"state.json".length), "agents", "main", "wire.jsonl");
1677
1943
  try {
1678
1944
  const wireStat = await lstat(wireFile);
1679
1945
  if (wireStat.isSymbolicLink() || !wireStat.isFile()) continue;
@@ -2412,7 +2678,7 @@ function normalizeConversationText(text) {
2412
2678
  return trimmed;
2413
2679
  }
2414
2680
  async function extractTitleAndCwd(filePath) {
2415
- return new Promise((resolve5) => {
2681
+ return new Promise((resolve6) => {
2416
2682
  const input = createReadStream(filePath, { encoding: "utf-8" });
2417
2683
  const rl = createInterface({
2418
2684
  input,
@@ -2426,7 +2692,7 @@ async function extractTitleAndCwd(filePath) {
2426
2692
  resolved = true;
2427
2693
  rl.close();
2428
2694
  input.destroy();
2429
- resolve5({ title, cwd });
2695
+ resolve6({ title, cwd });
2430
2696
  };
2431
2697
  rl.on("line", (line) => {
2432
2698
  if (resolved) return;
@@ -2460,7 +2726,7 @@ async function collectJsonlFiles(root) {
2460
2726
  }
2461
2727
  const files = [];
2462
2728
  for (const entry of entries) {
2463
- const child = join2(root, entry.name);
2729
+ const child = join3(root, entry.name);
2464
2730
  if (entry.isDirectory()) {
2465
2731
  files.push(...await collectJsonlFiles(child));
2466
2732
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -2478,7 +2744,7 @@ async function collectFilesNamed(root, filename) {
2478
2744
  }
2479
2745
  const files = [];
2480
2746
  for (const entry of entries) {
2481
- const child = join2(root, entry.name);
2747
+ const child = join3(root, entry.name);
2482
2748
  if (entry.isDirectory()) {
2483
2749
  files.push(...await collectFilesNamed(child, filename));
2484
2750
  } else if (entry.isFile() && entry.name === filename) {
@@ -2488,7 +2754,7 @@ async function collectFilesNamed(root, filename) {
2488
2754
  return files;
2489
2755
  }
2490
2756
  async function extractCodexTitleAndCwd(filePath) {
2491
- return new Promise((resolve5) => {
2757
+ return new Promise((resolve6) => {
2492
2758
  const input = createReadStream(filePath, { encoding: "utf-8" });
2493
2759
  const rl = createInterface({
2494
2760
  input,
@@ -2503,7 +2769,7 @@ async function extractCodexTitleAndCwd(filePath) {
2503
2769
  resolved = true;
2504
2770
  rl.close();
2505
2771
  input.destroy();
2506
- resolve5({ id, title, cwd });
2772
+ resolve6({ id, title, cwd });
2507
2773
  };
2508
2774
  rl.on("line", (line) => {
2509
2775
  if (resolved) return;
@@ -2549,7 +2815,7 @@ function isCodexInjectedContextBlock(text) {
2549
2815
  // src/serve/command-discovery.ts
2550
2816
  import { readdirSync, readFileSync as readFileSync5 } from "fs";
2551
2817
  import { homedir as homedir3 } from "os";
2552
- import { join as join3 } from "path";
2818
+ import { join as join4 } from "path";
2553
2819
  var REPL_BUILTINS = [
2554
2820
  { name: "/compact", description: "Compact conversation history", source: "builtin" },
2555
2821
  { name: "/status", description: "Show session status", source: "builtin" },
@@ -2621,7 +2887,7 @@ function scanSkillsDir(dirPath, source) {
2621
2887
  }
2622
2888
  const commands = [];
2623
2889
  for (const name of entries) {
2624
- const skillPath = join3(dirPath, name, "SKILL.md");
2890
+ const skillPath = join4(dirPath, name, "SKILL.md");
2625
2891
  try {
2626
2892
  const content = readFileSync5(skillPath, "utf-8");
2627
2893
  const parsed = parseSkillFrontmatter(content);
@@ -2647,7 +2913,7 @@ function scanCommandsDir(dirPath, source) {
2647
2913
  for (const filename of entries) {
2648
2914
  const cmdName = filename.replace(/\.md$/, "");
2649
2915
  try {
2650
- const content = readFileSync5(join3(dirPath, filename), "utf-8");
2916
+ const content = readFileSync5(join4(dirPath, filename), "utf-8");
2651
2917
  const firstLine2 = content.split("\n")[0].trim();
2652
2918
  commands.push({
2653
2919
  name: `/${cmdName}`,
@@ -2665,7 +2931,7 @@ function scanCommandsDir(dirPath, source) {
2665
2931
  return commands;
2666
2932
  }
2667
2933
  function scanPluginDirs(homeDir) {
2668
- const pluginCacheDir = join3(homeDir, ".claude", "plugins", "cache");
2934
+ const pluginCacheDir = join4(homeDir, ".claude", "plugins", "cache");
2669
2935
  let pluginNames;
2670
2936
  try {
2671
2937
  pluginNames = readdirSync(pluginCacheDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
@@ -2674,9 +2940,9 @@ function scanPluginDirs(homeDir) {
2674
2940
  }
2675
2941
  const commands = [];
2676
2942
  for (const pluginName of pluginNames) {
2677
- const pluginDir = join3(pluginCacheDir, pluginName);
2678
- const skillCmds = scanSkillsDir(join3(pluginDir, "skills"), "plugin-skill");
2679
- const cmdCmds = scanCommandsDir(join3(pluginDir, "commands"), "plugin-command");
2943
+ const pluginDir = join4(pluginCacheDir, pluginName);
2944
+ const skillCmds = scanSkillsDir(join4(pluginDir, "skills"), "plugin-skill");
2945
+ const cmdCmds = scanCommandsDir(join4(pluginDir, "commands"), "plugin-command");
2680
2946
  commands.push(...skillCmds, ...cmdCmds);
2681
2947
  }
2682
2948
  return commands;
@@ -2684,10 +2950,10 @@ function scanPluginDirs(homeDir) {
2684
2950
  async function discoverCommands(workDir, options) {
2685
2951
  const homeDir = options?.homeDir ?? homedir3();
2686
2952
  const builtins = REPL_BUILTINS.filter((c) => !COMMAND_BLACKLIST.has(c.name));
2687
- const userSkills = scanSkillsDir(join3(homeDir, ".claude", "skills"), "user-skill");
2688
- const projectSkills = scanSkillsDir(join3(workDir, ".claude", "skills"), "project-skill");
2689
- const userCommands = scanCommandsDir(join3(homeDir, ".claude", "commands"), "user-command");
2690
- const projectCommands = scanCommandsDir(join3(workDir, ".claude", "commands"), "project-command");
2953
+ const userSkills = scanSkillsDir(join4(homeDir, ".claude", "skills"), "user-skill");
2954
+ const projectSkills = scanSkillsDir(join4(workDir, ".claude", "skills"), "project-skill");
2955
+ const userCommands = scanCommandsDir(join4(homeDir, ".claude", "commands"), "user-command");
2956
+ const projectCommands = scanCommandsDir(join4(workDir, ".claude", "commands"), "project-command");
2691
2957
  const pluginCommands = scanPluginDirs(homeDir);
2692
2958
  const commandMap = /* @__PURE__ */ new Map();
2693
2959
  for (const cmd of builtins) commandMap.set(cmd.name, cmd);
@@ -2836,7 +3102,7 @@ function touchSessionActivity(sessionManager, relay, sessionId, now = Date.now()
2836
3102
  // src/serve/handlers/control-messages.ts
2837
3103
  var COMMAND_REFRESH_MS = 6 * 60 * 60 * 1e3;
2838
3104
  function isPathSafe(path) {
2839
- if (!isAbsolute3(path)) return false;
3105
+ if (!isAbsolute4(path)) return false;
2840
3106
  const normalized = normalize2(path);
2841
3107
  if (normalized.includes("..")) return false;
2842
3108
  return true;
@@ -2864,7 +3130,7 @@ async function getFileTree(rootPath) {
2864
3130
  groups.push({ path: rootPath, entries: rootEntries });
2865
3131
  for (const sub of rootEntries) {
2866
3132
  if (!sub.isDir) continue;
2867
- const subPath = join4(rootPath, sub.name);
3133
+ const subPath = join5(rootPath, sub.name);
2868
3134
  try {
2869
3135
  const subEntries = await scanDir(subPath, { includeHidden: false });
2870
3136
  groups.push({ path: subPath, entries: subEntries });
@@ -3169,7 +3435,7 @@ function createControlMessageHandlers(send, sessionManager) {
3169
3435
 
3170
3436
  // src/serve/worker-registry.ts
3171
3437
  import { connect } from "net";
3172
- import { unlinkSync, existsSync as existsSync4, readdirSync as readdirSync2 } from "fs";
3438
+ import { existsSync as existsSync4, mkdirSync, readdirSync as readdirSync2 } from "fs";
3173
3439
 
3174
3440
  // src/serve/claude-stream-event-mapper.ts
3175
3441
  function mapClaudeStreamEvent(sessionId, seq, options) {
@@ -3788,7 +4054,7 @@ var WorkerRegistry = class {
3788
4054
  const startupFailure = this.startupFailures.get(sessionId);
3789
4055
  if (startupFailure) return Promise.reject(startupFailure);
3790
4056
  if (this.readySessions.has(sessionId)) return Promise.resolve();
3791
- return new Promise((resolve5, reject) => {
4057
+ return new Promise((resolve6, reject) => {
3792
4058
  const timeout = setTimeout(() => {
3793
4059
  const waiters2 = this.readyWaiters.get(sessionId);
3794
4060
  if (waiters2) {
@@ -3798,7 +4064,7 @@ var WorkerRegistry = class {
3798
4064
  reject(new Error(`Worker did not report ready within ${timeoutMs}ms`));
3799
4065
  }, timeoutMs);
3800
4066
  timeout.unref?.();
3801
- const waiter = { resolve: resolve5, reject, timeout };
4067
+ const waiter = { resolve: resolve6, reject, timeout };
3802
4068
  const waiters = this.readyWaiters.get(sessionId) ?? /* @__PURE__ */ new Set();
3803
4069
  waiters.add(waiter);
3804
4070
  this.readyWaiters.set(sessionId, waiters);
@@ -3806,6 +4072,7 @@ var WorkerRegistry = class {
3806
4072
  }
3807
4073
  spawn(sessionId, options) {
3808
4074
  const paths = sessionPaths(sessionId);
4075
+ mkdirSync(paths.dir, { recursive: true });
3809
4076
  const args = [sessionId, paths.workerSock];
3810
4077
  args.push("--provider", options.provider);
3811
4078
  if (options.cwd) args.push("--cwd", options.cwd);
@@ -3852,7 +4119,7 @@ var WorkerRegistry = class {
3852
4119
  return workerPid;
3853
4120
  }
3854
4121
  connect(sessionId, sockPath, timeoutMs) {
3855
- return new Promise((resolve5) => {
4122
+ return new Promise((resolve6) => {
3856
4123
  const sock = connect(sockPath);
3857
4124
  let settled = false;
3858
4125
  let timeout;
@@ -3860,7 +4127,7 @@ var WorkerRegistry = class {
3860
4127
  if (settled) return;
3861
4128
  settled = true;
3862
4129
  if (timeout) clearTimeout(timeout);
3863
- resolve5(result);
4130
+ resolve6(result);
3864
4131
  };
3865
4132
  const onConnectError = () => finish(null);
3866
4133
  sock.once("error", onConnectError);
@@ -4031,7 +4298,7 @@ var WorkerRegistry = class {
4031
4298
  for (const dir of dirs) {
4032
4299
  const sessionId = dir.name;
4033
4300
  const paths = sessionPaths(sessionId);
4034
- if (!existsSync4(paths.workerSock)) continue;
4301
+ if (!localIpcEndpointMayExist(paths.workerSock)) continue;
4035
4302
  const persistedSession = this.deps.sessionManager.getSession(sessionId);
4036
4303
  if (!persistedSession || persistedSession.mode !== "json") {
4037
4304
  await this.terminateOrphanWorker(sessionId, paths.workerSock);
@@ -4050,7 +4317,7 @@ var WorkerRegistry = class {
4050
4317
  serviceLogger.info({ sessionId }, "Reconnected to existing worker");
4051
4318
  } else {
4052
4319
  try {
4053
- unlinkSync(paths.workerSock);
4320
+ removeLocalIpcEndpoint(paths.workerSock);
4054
4321
  } catch {
4055
4322
  }
4056
4323
  serviceLogger.info({ sessionId }, "Cleaned up stale worker socket");
@@ -4223,7 +4490,7 @@ var WorkerRegistry = class {
4223
4490
  }
4224
4491
  }
4225
4492
  terminateOrphanWorker(sessionId, workerSocketPath) {
4226
- return new Promise((resolve5) => {
4493
+ return new Promise((resolve6) => {
4227
4494
  const socket = connect(workerSocketPath);
4228
4495
  let settled = false;
4229
4496
  const finish = (details) => {
@@ -4232,14 +4499,14 @@ var WorkerRegistry = class {
4232
4499
  clearTimeout(timeout);
4233
4500
  socket.destroy();
4234
4501
  try {
4235
- unlinkSync(workerSocketPath);
4502
+ removeLocalIpcEndpoint(workerSocketPath);
4236
4503
  } catch {
4237
4504
  }
4238
4505
  serviceLogger.warn(
4239
4506
  { sessionId, ...details },
4240
4507
  "Orphaned JSON worker removed without session data"
4241
4508
  );
4242
- resolve5();
4509
+ resolve6();
4243
4510
  };
4244
4511
  const timeout = setTimeout(
4245
4512
  () => finish({ terminated: false }),
@@ -4278,6 +4545,14 @@ var WorkerRegistry = class {
4278
4545
  },
4279
4546
  () => finish({ terminated: false })
4280
4547
  );
4548
+ socket.write(
4549
+ serializeWorkerMsg({
4550
+ type: "serve_protocol_hello",
4551
+ protocolVersion: WORKER_IPC_PROTOCOL_VERSION,
4552
+ sessionId,
4553
+ pid: process.pid
4554
+ })
4555
+ );
4281
4556
  });
4282
4557
  });
4283
4558
  }
@@ -5213,12 +5488,13 @@ var RelayPermissionHandlers = class {
5213
5488
  // src/serve/relay-resource-handlers.ts
5214
5489
  import { homedir as homedir4 } from "os";
5215
5490
  import { accessSync, constants, statSync } from "fs";
5491
+ import { isAbsolute as isAbsolute5 } from "path";
5216
5492
  function errorMessage(err) {
5217
5493
  return err instanceof Error ? err.message : String(err);
5218
5494
  }
5219
5495
  function validateExecutablePath(path) {
5220
5496
  const normalized = path.trim();
5221
- if (!normalized.startsWith("/")) throw new Error("CLI \u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
5497
+ if (!isAbsolute5(normalized)) throw new Error("CLI \u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
5222
5498
  const stat5 = statSync(normalized);
5223
5499
  if (!stat5.isFile()) throw new Error("CLI \u8DEF\u5F84\u4E0D\u662F\u53EF\u6267\u884C\u6587\u4EF6");
5224
5500
  accessSync(normalized, constants.X_OK);
@@ -5331,25 +5607,26 @@ var RelayResourceHandlers = class {
5331
5607
  // src/serve/relay-session-create-handler.ts
5332
5608
  import { rmSync, statSync as statSync2 } from "fs";
5333
5609
  import { homedir as homedir6 } from "os";
5334
- import { isAbsolute as isAbsolute5 } from "path";
5610
+ import { isAbsolute as isAbsolute7 } from "path";
5335
5611
  import { nanoid as nanoid3 } from "nanoid";
5336
5612
 
5337
5613
  // src/common/codex-active-writer.ts
5338
5614
  import { existsSync as existsSync5 } from "fs";
5339
5615
  import { homedir as homedir5 } from "os";
5340
- import { isAbsolute as isAbsolute4, join as join5 } from "path";
5341
- import { spawnSync } from "child_process";
5616
+ import { isAbsolute as isAbsolute6, join as join6 } from "path";
5617
+ import { spawnSync as spawnSync2 } from "child_process";
5342
5618
  var CODEX_THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
5343
5619
  var LSOF_TIMEOUT_MS = 1e3;
5344
5620
  function findCodexActiveWriter(threadId, env = process.env) {
5621
+ if (process.platform === "win32") return null;
5345
5622
  if (!CODEX_THREAD_ID_RE.test(threadId)) return null;
5346
5623
  const configuredHome = env.CODEX_HOME?.trim();
5347
- const codexHome = configuredHome && isAbsolute4(configuredHome) ? configuredHome : join5(homedir5(), ".codex");
5348
- const lockPath = join5(codexHome, "thread-writer-locks", `${threadId}.lock`);
5624
+ const codexHome = configuredHome && isAbsolute6(configuredHome) ? configuredHome : join6(homedir5(), ".codex");
5625
+ const lockPath = join6(codexHome, "thread-writer-locks", `${threadId}.lock`);
5349
5626
  if (!existsSync5(lockPath)) return null;
5350
5627
  const commands = process.platform === "darwin" ? ["/usr/sbin/lsof", "lsof"] : ["lsof"];
5351
5628
  for (const command of commands) {
5352
- const result = spawnSync(command, ["-t", lockPath], {
5629
+ const result = spawnSync2(command, ["-t", lockPath], {
5353
5630
  encoding: "utf8",
5354
5631
  timeout: LSOF_TIMEOUT_MS,
5355
5632
  maxBuffer: 64 * 1024,
@@ -5370,38 +5647,28 @@ function parseFirstPid(output) {
5370
5647
  }
5371
5648
 
5372
5649
  // src/common/process-ancestry.ts
5373
- import { spawnSync as spawnSync2 } from "child_process";
5650
+ import { spawnSync as spawnSync3 } from "child_process";
5374
5651
  var PROCESS_QUERY_TIMEOUT_MS = 1e3;
5375
5652
  var MAX_ANCESTRY_DEPTH = 64;
5376
5653
  function readParentProcessId(pid) {
5377
5654
  if (!Number.isSafeInteger(pid) || pid <= 0) return null;
5378
5655
  if (process.platform === "win32") {
5379
- const script = `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").ParentProcessId`;
5380
- const result = spawnSync2(
5381
- "powershell.exe",
5382
- ["-NoProfile", "-NonInteractive", "-Command", script],
5383
- {
5384
- encoding: "utf8",
5385
- timeout: PROCESS_QUERY_TIMEOUT_MS,
5386
- maxBuffer: 64 * 1024,
5387
- stdio: ["ignore", "pipe", "ignore"]
5388
- }
5389
- );
5390
- return result.error ? null : parseParentPid(result.stdout);
5656
+ const parentPid = readWindowsProcess(pid)?.parentPid;
5657
+ return parentPid !== void 0 && parentPid > 0 ? parentPid : null;
5391
5658
  }
5392
5659
  const commands = ["/bin/ps", "/usr/bin/ps", "ps"];
5393
5660
  const tried = /* @__PURE__ */ new Set();
5394
5661
  for (const command of commands) {
5395
5662
  if (tried.has(command)) continue;
5396
5663
  tried.add(command);
5397
- const result = spawnSync2(command, ["-o", "ppid=", "-p", String(pid)], {
5664
+ const result = spawnSync3(command, ["-o", "ppid=", "-p", String(pid)], {
5398
5665
  encoding: "utf8",
5399
5666
  timeout: PROCESS_QUERY_TIMEOUT_MS,
5400
5667
  maxBuffer: 64 * 1024,
5401
5668
  stdio: ["ignore", "pipe", "ignore"]
5402
5669
  });
5403
5670
  if (result.error && result.error.code === "ENOENT") continue;
5404
- return result.error ? null : parseParentPid(result.stdout);
5671
+ return result.error || result.status !== 0 ? null : parseParentPid(result.stdout);
5405
5672
  }
5406
5673
  return null;
5407
5674
  }
@@ -5475,19 +5742,27 @@ var HostedPtyRegistry = class {
5475
5742
  const kind = options.kind;
5476
5743
  const { cols, rows } = options;
5477
5744
  const command = options.kind === "terminal" ? {
5478
- command: options.shell ?? this.deps.getProviderEnv().SHELL ?? "/bin/sh",
5745
+ command: options.shell ?? defaultShell(this.deps.getProviderEnv()),
5479
5746
  args: [],
5480
5747
  env: this.deps.getProviderEnv()
5481
5748
  } : PROVIDERS[options.provider].buildTerminalCommand(
5482
5749
  {
5483
5750
  args: options.args,
5751
+ cwd: options.cwd,
5484
5752
  permissionMode: options.permissionMode,
5485
5753
  hook: options.hook
5486
5754
  },
5487
5755
  this.deps.getProviderEnv()
5488
5756
  );
5489
- const env = normalizeHostedPtyEnv(command.env);
5490
- const child = pty.spawn(command.command, command.args, {
5757
+ const launch = prepareCommandLaunch(
5758
+ command.command,
5759
+ command.args,
5760
+ command.env,
5761
+ process.platform,
5762
+ options.cwd
5763
+ );
5764
+ const env = normalizeHostedPtyEnv(launch.env);
5765
+ const child = pty.spawn(launch.command, launch.ptyArgs ?? launch.args, {
5491
5766
  name: HOSTED_PTY_TERM,
5492
5767
  cols,
5493
5768
  rows,
@@ -5832,7 +6107,7 @@ function throwIfAborted(signal) {
5832
6107
  }
5833
6108
  }
5834
6109
  function wait(delayMs, signal) {
5835
- return new Promise((resolve5, reject) => {
6110
+ return new Promise((resolve6, reject) => {
5836
6111
  throwIfAborted(signal);
5837
6112
  const onAbort = () => {
5838
6113
  clearTimeout(timer);
@@ -5840,7 +6115,7 @@ function wait(delayMs, signal) {
5840
6115
  };
5841
6116
  const timer = setTimeout(() => {
5842
6117
  signal.removeEventListener("abort", onAbort);
5843
- resolve5();
6118
+ resolve6();
5844
6119
  }, delayMs);
5845
6120
  timer.unref?.();
5846
6121
  signal.addEventListener("abort", onAbort, { once: true });
@@ -5913,7 +6188,7 @@ function validateSessionCwd(cwd) {
5913
6188
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
5914
6189
  }
5915
6190
  const trimmed = cwd.trim();
5916
- if (!isAbsolute5(trimmed)) {
6191
+ if (!isAbsolute7(trimmed)) {
5917
6192
  return { message: "\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84", code: ControlErrorCode.INVALID_PATH };
5918
6193
  }
5919
6194
  try {
@@ -6567,7 +6842,7 @@ function buildClaudeSpeechSummaryCommand({
6567
6842
  }
6568
6843
  var runClaudeSpeechSummary = ({ cwd, prompt, env, timeoutMs }) => {
6569
6844
  const { command, args } = buildClaudeSpeechSummaryCommand({ env, prompt });
6570
- return new Promise((resolve5, reject) => {
6845
+ return new Promise((resolve6, reject) => {
6571
6846
  const child = spawn2(command, args, {
6572
6847
  cwd,
6573
6848
  env: { ...process.env, ...env },
@@ -6599,7 +6874,7 @@ var runClaudeSpeechSummary = ({ cwd, prompt, env, timeoutMs }) => {
6599
6874
  clearTimeout(timer);
6600
6875
  const stdout = Buffer.concat(stdoutChunks).toString("utf8").trim();
6601
6876
  if (code === 0 && stdout.length > 0) {
6602
- resolve5(stdout);
6877
+ resolve6(stdout);
6603
6878
  return;
6604
6879
  }
6605
6880
  const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
@@ -6696,7 +6971,7 @@ function containsApprovalRiskEvaluation(summary) {
6696
6971
 
6697
6972
  // src/serve/preview/preview-manager.ts
6698
6973
  import { mkdir as mkdir2, rm as rm2, writeFile } from "fs/promises";
6699
- import { join as join7 } from "path";
6974
+ import { join as join8 } from "path";
6700
6975
  import { nanoid as nanoid4 } from "nanoid";
6701
6976
 
6702
6977
  // src/common/cpolar-quick-tunnel.ts
@@ -6781,8 +7056,8 @@ function createTimedSignal(timeoutMs, timeoutMessage) {
6781
7056
  let settled = false;
6782
7057
  let resolvePromise;
6783
7058
  let rejectPromise;
6784
- const promise = new Promise((resolve5, reject) => {
6785
- resolvePromise = resolve5;
7059
+ const promise = new Promise((resolve6, reject) => {
7060
+ resolvePromise = resolve6;
6786
7061
  rejectPromise = reject;
6787
7062
  });
6788
7063
  const timer = setTimeout(() => {
@@ -7164,7 +7439,7 @@ function normalizeLocalPreviewUrl(raw) {
7164
7439
  };
7165
7440
  }
7166
7441
  async function probeLocalPreviewTarget(target, timeoutMs = 2e3) {
7167
- const probeHost = (host) => new Promise((resolve5, reject) => {
7442
+ const probeHost = (host) => new Promise((resolve6, reject) => {
7168
7443
  const socket = connect2({ host, port: target.port });
7169
7444
  let settled = false;
7170
7445
  const finish = (error) => {
@@ -7173,7 +7448,7 @@ async function probeLocalPreviewTarget(target, timeoutMs = 2e3) {
7173
7448
  clearTimeout(timer);
7174
7449
  socket.destroy();
7175
7450
  if (error) reject(error);
7176
- else resolve5();
7451
+ else resolve6();
7177
7452
  };
7178
7453
  const timer = setTimeout(
7179
7454
  () => finish(new Error("\u65E0\u6CD5\u8FDE\u63A5\u672C\u5730\u7F51\u9875\uFF0C\u8BF7\u786E\u8BA4\u5B83\u6B63\u5728\u8FD0\u884C")),
@@ -7374,7 +7649,7 @@ var LocalPreviewProxy = class {
7374
7649
 
7375
7650
  // src/serve/preview/static-preview-handler.ts
7376
7651
  import { open as open2, realpath, stat as stat2 } from "fs/promises";
7377
- import { extname, isAbsolute as isAbsolute6, relative, resolve as resolve2, sep as sep2 } from "path";
7652
+ import { extname, isAbsolute as isAbsolute8, relative, resolve as resolve3, sep as sep2 } from "path";
7378
7653
  var MIME_TYPES = {
7379
7654
  ".avif": "image/avif",
7380
7655
  ".css": "text/css; charset=utf-8",
@@ -7407,7 +7682,7 @@ var MIME_TYPES = {
7407
7682
  };
7408
7683
  function isWithinRoot(rootPath, targetPath) {
7409
7684
  const rel = relative(rootPath, targetPath);
7410
- return rel === "" || !rel.startsWith(`..${sep2}`) && rel !== ".." && !isAbsolute6(rel);
7685
+ return rel === "" || !rel.startsWith(`..${sep2}`) && rel !== ".." && !isAbsolute8(rel);
7411
7686
  }
7412
7687
  function hiddenOrDependencyPath(path) {
7413
7688
  return path.split("/").filter(Boolean).some((part) => part.startsWith(".") || part.toLowerCase() === "node_modules");
@@ -7472,7 +7747,7 @@ var StaticPreviewHandler = class {
7472
7747
  return;
7473
7748
  }
7474
7749
  const relativePath = decodedPath.replace(/^\/+/, "");
7475
- let candidatePath = resolve2(this.rootPath, relativePath || ".");
7750
+ let candidatePath = resolve3(this.rootPath, relativePath || ".");
7476
7751
  if (!isWithinRoot(this.rootPath, candidatePath)) {
7477
7752
  sendPreviewError(response, 404, "\u9875\u9762\u4E0D\u5B58\u5728");
7478
7753
  return;
@@ -7482,7 +7757,7 @@ var StaticPreviewHandler = class {
7482
7757
  try {
7483
7758
  candidateStat = await stat2(candidatePath);
7484
7759
  if (candidateStat.isDirectory()) {
7485
- candidatePath = resolve2(candidatePath, "index.html");
7760
+ candidatePath = resolve3(candidatePath, "index.html");
7486
7761
  candidateStat = await stat2(candidatePath);
7487
7762
  }
7488
7763
  } catch (error) {
@@ -7490,7 +7765,7 @@ var StaticPreviewHandler = class {
7490
7765
  const firstSegment = relativePath.split("/", 1)[0]?.toLowerCase();
7491
7766
  const documentFallback = this.documentFallback && acceptsHtml && !extname(relativePath) && firstSegment !== "api" && request.headers["sec-fetch-dest"] !== "script" && request.headers["sec-fetch-dest"] !== "style" && request.headers["sec-fetch-dest"] !== "image";
7492
7767
  if (!documentFallback) throw error;
7493
- candidatePath = resolve2(this.rootPath, this.entryPath);
7768
+ candidatePath = resolve3(this.rootPath, this.entryPath);
7494
7769
  candidateStat = await stat2(candidatePath);
7495
7770
  }
7496
7771
  if (!candidateStat.isFile()) throw new Error("not a file");
@@ -7584,7 +7859,7 @@ var StaticPreviewHandler = class {
7584
7859
 
7585
7860
  // src/serve/preview/static-preview.ts
7586
7861
  import { lstat as lstat2, readdir as readdir3, realpath as realpath2, stat as stat3 } from "fs/promises";
7587
- import { basename as basename2, dirname, isAbsolute as isAbsolute7, relative as relative2, resolve as resolve3, sep as sep3 } from "path";
7862
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute9, relative as relative2, resolve as resolve4, sep as sep3 } from "path";
7588
7863
  var MAX_SCAN_ENTRIES = 2e4;
7589
7864
  var MAX_HTML_ENTRIES = 1e3;
7590
7865
  var MAX_SCAN_DEPTH = 64;
@@ -7595,11 +7870,11 @@ function isHiddenOrDependency(name) {
7595
7870
  return name.startsWith(".") || name.toLowerCase() === "node_modules";
7596
7871
  }
7597
7872
  function containsHiddenOrDependencySegment(path) {
7598
- return resolve3(path).split(sep3).filter(Boolean).some(isHiddenOrDependency);
7873
+ return resolve4(path).split(sep3).filter(Boolean).some(isHiddenOrDependency);
7599
7874
  }
7600
7875
  function isWithinRoot2(rootPath, targetPath) {
7601
7876
  const rel = relative2(rootPath, targetPath);
7602
- return rel === "" || !rel.startsWith(`..${sep3}`) && rel !== ".." && !isAbsolute7(rel);
7877
+ return rel === "" || !rel.startsWith(`..${sep3}`) && rel !== ".." && !isAbsolute9(rel);
7603
7878
  }
7604
7879
  function toProtocolPath(path) {
7605
7880
  return path.split(sep3).join("/");
@@ -7631,7 +7906,7 @@ async function collectHtmlEntries(rootPath) {
7631
7906
  throw new Error("\u6587\u4EF6\u5939\u5185\u5BB9\u8FC7\u591A\uFF0C\u65E0\u6CD5\u521B\u5EFA\u9884\u89C8");
7632
7907
  }
7633
7908
  if (isHiddenOrDependency(entry.name)) continue;
7634
- const absolutePath = resolve3(directory, entry.name);
7909
+ const absolutePath = resolve4(directory, entry.name);
7635
7910
  const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;
7636
7911
  let entryIsDirectory = entry.isDirectory();
7637
7912
  let entryIsFile = entry.isFile();
@@ -7666,7 +7941,7 @@ async function collectHtmlEntries(rootPath) {
7666
7941
  }
7667
7942
  async function inspectStaticPreviewPath(path) {
7668
7943
  const selectionPath = path.trim();
7669
- if (!selectionPath || !isAbsolute7(selectionPath) || selectionPath.includes("\0")) {
7944
+ if (!selectionPath || !isAbsolute9(selectionPath) || selectionPath.includes("\0")) {
7670
7945
  throw new Error("\u8BF7\u9009\u62E9\u7EDD\u5BF9\u8DEF\u5F84\u4E0B\u7684\u7F51\u9875\u6587\u4EF6\u6216\u6587\u4EF6\u5939");
7671
7946
  }
7672
7947
  if (containsHiddenOrDependencySegment(selectionPath)) {
@@ -7681,7 +7956,7 @@ async function inspectStaticPreviewPath(path) {
7681
7956
  if (isHiddenOrDependency(basename2(selectionPath))) {
7682
7957
  throw new Error("\u4E0D\u80FD\u516C\u5F00\u9690\u85CF\u6587\u4EF6\u6216 node_modules \u4E2D\u7684\u7F51\u9875");
7683
7958
  }
7684
- const rootPath2 = await realpath2(dirname(selectionPath));
7959
+ const rootPath2 = await realpath2(dirname2(selectionPath));
7685
7960
  const filePath = await realpath2(selectionPath);
7686
7961
  if (containsHiddenOrDependencySegment(rootPath2) || containsHiddenOrDependencySegment(filePath)) {
7687
7962
  throw new Error("\u4E0D\u80FD\u516C\u5F00\u9690\u85CF\u76EE\u5F55\u3001\u9690\u85CF\u6587\u4EF6\u6216 node_modules \u4E2D\u7684\u7F51\u9875");
@@ -7719,7 +7994,7 @@ async function resolveStaticPreviewSource(path, requestedEntryPath) {
7719
7994
 
7720
7995
  // src/serve/preview/preview-gateway.ts
7721
7996
  function listenLoopback(server) {
7722
- return new Promise((resolve5, reject) => {
7997
+ return new Promise((resolve6, reject) => {
7723
7998
  const onError = (error) => {
7724
7999
  server.off("listening", onListening);
7725
8000
  reject(error);
@@ -7731,7 +8006,7 @@ function listenLoopback(server) {
7731
8006
  reject(new Error("\u65E0\u6CD5\u786E\u5B9A\u7F51\u9875\u9884\u89C8 Gateway \u7AEF\u53E3"));
7732
8007
  return;
7733
8008
  }
7734
- resolve5(address.port);
8009
+ resolve6(address.port);
7735
8010
  };
7736
8011
  server.once("error", onError);
7737
8012
  server.once("listening", onListening);
@@ -7811,10 +8086,10 @@ async function startPreviewGateway(options) {
7811
8086
  close() {
7812
8087
  deactivate();
7813
8088
  if (!closePromise) {
7814
- closePromise = new Promise((resolve5, reject) => {
8089
+ closePromise = new Promise((resolve6, reject) => {
7815
8090
  server.close((error) => {
7816
8091
  if (error) reject(error);
7817
- else resolve5();
8092
+ else resolve6();
7818
8093
  });
7819
8094
  }).catch((error) => {
7820
8095
  closePromise = null;
@@ -8000,7 +8275,7 @@ var PreviewStore = class {
8000
8275
  // src/serve/preview/stale-preview-runtime.ts
8001
8276
  import { execFile as execFile3 } from "child_process";
8002
8277
  import { readFile as readFile2, readdir as readdir4, realpath as realpath3, rm } from "fs/promises";
8003
- import { basename as basename3, isAbsolute as isAbsolute8, join as join6 } from "path";
8278
+ import { basename as basename3, isAbsolute as isAbsolute10, join as join7 } from "path";
8004
8279
  import { promisify as promisify3 } from "util";
8005
8280
  import { setTimeout as sleep2 } from "timers/promises";
8006
8281
  var execFileAsync3 = promisify3(execFile3);
@@ -8016,7 +8291,7 @@ function validProcessStartedAt(value) {
8016
8291
  return typeof value === "string" && value.length >= 1 && value.length <= 128;
8017
8292
  }
8018
8293
  function validExecutablePath(value) {
8019
- return typeof value === "string" && value.length <= 4096 && isAbsolute8(value);
8294
+ return typeof value === "string" && value.length <= 4096 && isAbsolute10(value);
8020
8295
  }
8021
8296
  function isCpolarExecutable(path) {
8022
8297
  return /^cpolar(?:\.exe)?$/i.test(basename3(path));
@@ -8044,7 +8319,7 @@ async function darwinExecutablePath(pid) {
8044
8319
  { timeout: 2e3, maxBuffer: 64 * 1024, windowsHide: true }
8045
8320
  );
8046
8321
  const path = result.stdout.split(/\r?\n/).find((line) => line.startsWith("n/"))?.slice(1);
8047
- return path && isAbsolute8(path) ? path : null;
8322
+ return path && isAbsolute10(path) ? path : null;
8048
8323
  } catch {
8049
8324
  return null;
8050
8325
  }
@@ -8093,7 +8368,7 @@ async function captureCpolarRuntimeProcessIdentity(pid) {
8093
8368
  }
8094
8369
  async function readRuntimeIdentity(runtimeDir) {
8095
8370
  try {
8096
- const marker = JSON.parse(await readFile2(join6(runtimeDir, RUNTIME_MARKER_NAME), "utf8"));
8371
+ const marker = JSON.parse(await readFile2(join7(runtimeDir, RUNTIME_MARKER_NAME), "utf8"));
8097
8372
  if (marker && Number.isSafeInteger(marker.pid) && marker.pid > 1) {
8098
8373
  if (marker.version === 1 && marker.provider === "cloudflare") {
8099
8374
  return { pid: marker.pid, provider: "cloudflare" };
@@ -8110,7 +8385,7 @@ async function readRuntimeIdentity(runtimeDir) {
8110
8385
  } catch {
8111
8386
  }
8112
8387
  try {
8113
- const pid = parsePid(await readFile2(join6(runtimeDir, "cloudflared.pid"), "utf8"));
8388
+ const pid = parsePid(await readFile2(join7(runtimeDir, "cloudflared.pid"), "utf8"));
8114
8389
  return pid === null ? null : { pid, provider: "cloudflare" };
8115
8390
  } catch {
8116
8391
  return null;
@@ -8135,8 +8410,8 @@ async function matchesRuntimeIdentity(command, runtimeDir, identity) {
8135
8410
  const observed = await captureCpolarRuntimeProcessIdentity(identity.pid);
8136
8411
  return observed !== null && observed.processStartedAt === identity.processStartedAt && sameExecutablePath(observed.executablePath, identity.executablePath);
8137
8412
  }
8138
- const configPath = join6(runtimeDir, "cloudflared.yml");
8139
- const pidFilePath = join6(runtimeDir, "cloudflared.pid");
8413
+ const configPath = join7(runtimeDir, "cloudflared.yml");
8414
+ const pidFilePath = join7(runtimeDir, "cloudflared.pid");
8140
8415
  return /(?:^|[/\\\s])cloudflared(?:\.exe)?(?:\s|$)/i.test(command) && command.includes(configPath) && command.includes(pidFilePath);
8141
8416
  }
8142
8417
  function isAlive(pid) {
@@ -8187,7 +8462,7 @@ async function cleanupStalePreviewRuntimes(runtimeRoot) {
8187
8462
  await Promise.all(
8188
8463
  entries.map(async (entry) => {
8189
8464
  if (!entry.isDirectory() || entry.isSymbolicLink()) return;
8190
- const runtimeDir = join6(runtimeRoot, entry.name);
8465
+ const runtimeDir = join7(runtimeRoot, entry.name);
8191
8466
  const identity = await readRuntimeIdentity(runtimeDir);
8192
8467
  if (identity === null || !isAlive(identity.pid)) {
8193
8468
  await rm(runtimeDir, { recursive: true, force: true });
@@ -8588,7 +8863,7 @@ var PreviewManager = class {
8588
8863
  await gateway.close();
8589
8864
  return;
8590
8865
  }
8591
- const runtimeDir = join7(
8866
+ const runtimeDir = join8(
8592
8867
  this.options.runtimeRoot,
8593
8868
  `${record.summary.previewId}-${this.epoch}-${runtime.generation}`
8594
8869
  );
@@ -8626,7 +8901,7 @@ var PreviewManager = class {
8626
8901
  throw new Error("Unable to verify the cpolar process identity");
8627
8902
  }
8628
8903
  await writeFile(
8629
- join7(runtimeDir, "runtime.json"),
8904
+ join8(runtimeDir, "runtime.json"),
8630
8905
  serializePreviewRuntimeMarker(
8631
8906
  tunnel.child.pid,
8632
8907
  runtime.provider === "cpolar" ? { provider: "cpolar", ...processIdentity } : { provider: "cloudflare" }
@@ -8680,8 +8955,8 @@ var PreviewManager = class {
8680
8955
  }
8681
8956
  }
8682
8957
  async prepareCloudflareRuntime(runtimeDir) {
8683
- const configPath = join7(runtimeDir, "cloudflared.yml");
8684
- const pidFilePath = join7(runtimeDir, "cloudflared.pid");
8958
+ const configPath = join8(runtimeDir, "cloudflared.yml");
8959
+ const pidFilePath = join8(runtimeDir, "cloudflared.pid");
8685
8960
  await writeFile(configPath, "{}\n", { mode: 384 });
8686
8961
  return { configPath, pidFilePath };
8687
8962
  }
@@ -10833,11 +11108,11 @@ var PermissionBroker = class {
10833
11108
  if (this.pending.has(request.requestId)) {
10834
11109
  return Promise.resolve(DUPLICATE_DECISION);
10835
11110
  }
10836
- return new Promise((resolve5) => {
11111
+ return new Promise((resolve6) => {
10837
11112
  this.pending.set(request.requestId, {
10838
11113
  ...request,
10839
11114
  source: "hook",
10840
- resolve: resolve5,
11115
+ resolve: resolve6,
10841
11116
  createdAt: Date.now()
10842
11117
  });
10843
11118
  });
@@ -11189,53 +11464,33 @@ function createEventBridge(deps) {
11189
11464
 
11190
11465
  // src/serve/service-files.ts
11191
11466
  import { execSync } from "child_process";
11192
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
11467
+ import { existsSync as existsSync7 } from "fs";
11193
11468
  import { hostname } from "os";
11194
- import { connect as connect4 } from "net";
11195
- function tryConnectSocket(sockPath) {
11196
- return new Promise((resolve5) => {
11197
- const s = connect4(sockPath);
11198
- s.on("connect", () => resolve5(s));
11199
- s.on("error", () => resolve5(null));
11200
- });
11201
- }
11202
11469
  function isProcessAlive(pid) {
11203
11470
  return processExistsOrIsInaccessible(pid);
11204
11471
  }
11205
- async function cleanupStaleResources() {
11206
- if (existsSync7(SOCK_PATH)) {
11207
- const existing = await tryConnectSocket(SOCK_PATH);
11208
- if (existing) {
11209
- existing.destroy();
11210
- const msg = `Another service is already running on ${SOCK_PATH}`;
11211
- serviceLogger.error(msg);
11212
- console.error(msg);
11213
- await flushLogger(serviceLogger);
11214
- process.exit(1);
11215
- }
11216
- unlinkIfPresent(SOCK_PATH);
11217
- serviceLogger.info("Removed stale socket file");
11218
- }
11219
- if (existsSync7(PID_PATH)) {
11220
- const pidStr = readFileSync7(PID_PATH, "utf-8").trim();
11221
- const pid = parseInt(pidStr, 10);
11222
- const probe = !isNaN(pid) ? probeProcess(pid) : null;
11223
- if (probe?.status === "alive") {
11224
- const msg = `Another service is already running with PID ${pid}`;
11225
- serviceLogger.error(msg);
11226
- console.error(msg);
11227
- await flushLogger(serviceLogger);
11228
- process.exit(1);
11229
- }
11230
- if (probe?.status === "permission-denied" || probe?.status === "unknown") {
11231
- const msg = probe.status === "permission-denied" ? `Another service may be running with PID ${pid}, but this process cannot probe it (permission denied)` : `Another service may be running with PID ${pid}, but this process cannot verify it (${probe.code ?? "unknown"}: ${probe.message})`;
11232
- serviceLogger.error(msg);
11233
- console.error(msg);
11234
- await flushLogger(serviceLogger);
11235
- process.exit(1);
11472
+ async function claimServiceRuntime() {
11473
+ const lock = tryAcquireFileLock(SERVICE_RUNTIME_LOCK_PATH);
11474
+ if (!lock) throw new Error("Another service is starting or running for this profile");
11475
+ const release = () => lock.release();
11476
+ try {
11477
+ if (existsSync7(STOPPED_PATH)) throw new Error("Service was explicitly stopped");
11478
+ for (const path of [SOCK_PATH, SERVICE_CONTROL_PATH]) {
11479
+ const existing = await tryConnectSocket(path);
11480
+ if (existing) {
11481
+ existing.destroy();
11482
+ throw new Error(
11483
+ "A service is already using this profile. Stop it before starting another service."
11484
+ );
11485
+ }
11236
11486
  }
11487
+ removeLocalIpcEndpoint(SOCK_PATH);
11488
+ removeLocalIpcEndpoint(SERVICE_CONTROL_PATH);
11237
11489
  unlinkIfPresent(PID_PATH);
11238
- serviceLogger.info("Removed stale PID file");
11490
+ process.once("exit", release);
11491
+ } catch (error) {
11492
+ release();
11493
+ throw error;
11239
11494
  }
11240
11495
  }
11241
11496
  function formatProxyNameForProfile(baseName, profileName = PROFILE_NAME) {
@@ -11247,6 +11502,7 @@ function getProxyName() {
11247
11502
  return formatProxyNameForProfile(getComputerName() || hostname());
11248
11503
  }
11249
11504
  function getComputerName() {
11505
+ if (process.platform !== "darwin") return null;
11250
11506
  try {
11251
11507
  return execSync("scutil --get ComputerName", { stdio: ["pipe", "pipe", "ignore"] }).toString().trim() || null;
11252
11508
  } catch {
@@ -11255,10 +11511,9 @@ function getComputerName() {
11255
11511
  }
11256
11512
 
11257
11513
  // src/serve/terminal-ipc.ts
11258
- function handleTerminalConnection(socket, deps) {
11514
+ function handleTerminalConnection(socket, deps, admission) {
11259
11515
  const {
11260
11516
  sessionManager,
11261
- workerRegistry,
11262
11517
  terminalSockets,
11263
11518
  terminalSubscriptionBacklog,
11264
11519
  relayConnection,
@@ -11266,8 +11521,7 @@ function handleTerminalConnection(socket, deps) {
11266
11521
  createHookContext,
11267
11522
  emitAgentStatus,
11268
11523
  updateTerminalCwd,
11269
- resolveInterruptedApprovals: resolveInterruptedApprovals2,
11270
- config
11524
+ resolveInterruptedApprovals: resolveInterruptedApprovals2
11271
11525
  } = deps;
11272
11526
  const bridgeDeps = {
11273
11527
  changeSessionState: (sessionId, next) => changeSessionState(sessionManager, relayConnection, sessionId, next),
@@ -11280,6 +11534,7 @@ function handleTerminalConnection(socket, deps) {
11280
11534
  let protocolRejected = false;
11281
11535
  let acceptedRegistration = null;
11282
11536
  let registeredSessionId = null;
11537
+ let admissionIntentChecked = false;
11283
11538
  const ownsRegisteredSession = (sessionId) => registeredSessionId === sessionId && terminalSockets.get(sessionId) === socket;
11284
11539
  const discardClaimMutation = (claim) => {
11285
11540
  if (claim === null || claim.source === "active") return;
@@ -11302,10 +11557,39 @@ function handleTerminalConnection(socket, deps) {
11302
11557
  })
11303
11558
  );
11304
11559
  };
11560
+ const matchesAdmissionIntent = (msg) => {
11561
+ if (msg.type !== "session_create_request") return false;
11562
+ if (admission.clientKind === "terminal-worker") {
11563
+ return msg.kind === "terminal" && admission.sessionId !== void 0 && msg.sessionId === admission.sessionId;
11564
+ }
11565
+ return msg.kind === "agent" && msg.sessionId === admission.sessionId;
11566
+ };
11567
+ const rejectAdmissionIntent = (msg) => {
11568
+ protocolRejected = true;
11569
+ const error = "Terminal request does not match its admitted connection scope";
11570
+ if (msg.type === "session_create_request") {
11571
+ rejectCreateHandshake(error);
11572
+ return;
11573
+ }
11574
+ socket.end(
11575
+ serializeIpc({
11576
+ type: "error",
11577
+ code: "TERMINAL_ADMISSION_SCOPE_MISMATCH",
11578
+ message: error
11579
+ })
11580
+ );
11581
+ };
11305
11582
  createIpcReader(
11306
11583
  socket,
11307
11584
  (msg) => {
11308
11585
  if (protocolRejected) return;
11586
+ if (!admissionIntentChecked) {
11587
+ admissionIntentChecked = true;
11588
+ if (!matchesAdmissionIntent(msg)) {
11589
+ rejectAdmissionIntent(msg);
11590
+ return;
11591
+ }
11592
+ }
11309
11593
  switch (msg.type) {
11310
11594
  case "session_create_request": {
11311
11595
  if (createHandshakeReceived) {
@@ -11364,28 +11648,6 @@ function handleTerminalConnection(socket, deps) {
11364
11648
  }
11365
11649
  break;
11366
11650
  }
11367
- case "service_status_request": {
11368
- const relayStatus = relayConnection.getStatus();
11369
- const sessions = sessionManager.listSessions();
11370
- socket.end(
11371
- serializeIpc({
11372
- type: "service_status_response",
11373
- protocolVersion: TERMINAL_IPC_PROTOCOL_VERSION,
11374
- config,
11375
- relay: relayStatus,
11376
- sessions: sessions.map((s) => ({
11377
- id: s.id,
11378
- mode: s.mode,
11379
- provider: s.provider,
11380
- state: s.state,
11381
- createdAt: new Date(s.createdAt).toISOString(),
11382
- ...s.name !== void 0 ? { name: s.name } : {},
11383
- hasWorker: workerRegistry.has(s.id)
11384
- }))
11385
- })
11386
- );
11387
- break;
11388
- }
11389
11651
  case "pty_title_change": {
11390
11652
  if (!ownsRegisteredSession(msg.sessionId) || !sessionManager.getSession(msg.sessionId)) {
11391
11653
  break;
@@ -11598,10 +11860,402 @@ function handleTerminalConnection(socket, deps) {
11598
11860
  });
11599
11861
  }
11600
11862
 
11863
+ // src/serve/pre-admission-terminal-retirement.ts
11864
+ var PRE_ADMISSION_PATH_MAX_LENGTH = 4096;
11865
+ var PRE_ADMISSION_SESSION_ID_MAX_LENGTH = 256;
11866
+ var UNVERSIONED_RECONNECT_KEYS = /* @__PURE__ */ new Set([
11867
+ "type",
11868
+ "mode",
11869
+ "provider",
11870
+ "cwd",
11871
+ "name",
11872
+ "pid",
11873
+ "sessionId",
11874
+ "kind"
11875
+ ]);
11876
+ function isRecord3(value) {
11877
+ return value !== null && typeof value === "object" && !Array.isArray(value);
11878
+ }
11879
+ function isBoundedNonEmptyString(value, maximum) {
11880
+ return typeof value === "string" && value.length > 0 && value.length <= maximum;
11881
+ }
11882
+ function parseUnversionedTerminalReconnect(value) {
11883
+ if (!isRecord3(value)) return null;
11884
+ if (Object.keys(value).some((key) => !UNVERSIONED_RECONNECT_KEYS.has(key))) return null;
11885
+ if (value.type !== "session_create_request" || value.mode !== "pty") return null;
11886
+ if (value.provider !== "claude" && value.provider !== "codex" && value.provider !== "kimi") {
11887
+ return null;
11888
+ }
11889
+ if (!isBoundedNonEmptyString(value.cwd, PRE_ADMISSION_PATH_MAX_LENGTH)) return null;
11890
+ if (value.name !== void 0 && (typeof value.name !== "string" || value.name.length > PRE_ADMISSION_PATH_MAX_LENGTH)) {
11891
+ return null;
11892
+ }
11893
+ if (typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid <= 0) {
11894
+ return null;
11895
+ }
11896
+ if (!isBoundedNonEmptyString(value.sessionId, PRE_ADMISSION_SESSION_ID_MAX_LENGTH)) return null;
11897
+ if (value.kind !== void 0 && value.kind !== "agent" && value.kind !== "terminal") return null;
11898
+ return {
11899
+ sessionId: value.sessionId,
11900
+ pid: value.pid,
11901
+ provider: value.provider,
11902
+ ...value.kind !== void 0 ? { kind: value.kind } : {}
11903
+ };
11904
+ }
11905
+ function parseVersionedTerminalReconnect(value) {
11906
+ if (!isRecord3(value)) return null;
11907
+ if (value.type !== "session_create_request" || value.mode !== "pty") return null;
11908
+ if (typeof value.protocolVersion !== "number" || !Number.isSafeInteger(value.protocolVersion) || value.protocolVersion < 0) {
11909
+ return null;
11910
+ }
11911
+ if (!isBoundedNonEmptyString(value.sessionId, PRE_ADMISSION_SESSION_ID_MAX_LENGTH)) return null;
11912
+ if (value.pid !== void 0 && (typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid <= 0)) {
11913
+ return null;
11914
+ }
11915
+ if (value.provider !== void 0 && value.provider !== "claude" && value.provider !== "codex" && value.provider !== "kimi") {
11916
+ return null;
11917
+ }
11918
+ if (value.kind !== void 0 && value.kind !== "agent" && value.kind !== "terminal") {
11919
+ return null;
11920
+ }
11921
+ return {
11922
+ sessionId: value.sessionId,
11923
+ protocolVersion: value.protocolVersion,
11924
+ ...value.pid !== void 0 ? { pid: value.pid } : {},
11925
+ ...value.provider !== void 0 ? { provider: value.provider } : {},
11926
+ ...value.kind !== void 0 ? { kind: value.kind } : {}
11927
+ };
11928
+ }
11929
+ function serializePreAdmissionTerminalRetirement(sessionId, action) {
11930
+ return `${JSON.stringify({
11931
+ type: action === "terminate" ? "pty_terminate" : "pty_detach",
11932
+ sessionId
11933
+ })}
11934
+ `;
11935
+ }
11936
+
11937
+ // src/serve/terminal-ipc-admission.ts
11938
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 5e3;
11939
+ var DEFAULT_REJECTION_DRAIN_MS = 3e4;
11940
+ var DEFAULT_MAX_MANAGED_CONNECTIONS = 128;
11941
+ var DEFAULT_LOG_AGGREGATION_MS = 6e4;
11942
+ function reconnectRetirementKey(generation, sessionId, pid) {
11943
+ return `${generation}\0${pid ?? "unknown"}\0${sessionId}`;
11944
+ }
11945
+ function createTerminalIpcAdmissionController(options) {
11946
+ const handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
11947
+ const rejectionDrainMs = options.rejectionDrainMs ?? DEFAULT_REJECTION_DRAIN_MS;
11948
+ const maxManagedConnections = options.maxManagedConnections ?? DEFAULT_MAX_MANAGED_CONNECTIONS;
11949
+ const logAggregationMs = options.logAggregationMs ?? DEFAULT_LOG_AGGREGATION_MS;
11950
+ const now = options.now ?? Date.now;
11951
+ const managed = /* @__PURE__ */ new Map();
11952
+ const retiringReconnects = /* @__PURE__ */ new Map();
11953
+ const logBuckets = /* @__PURE__ */ new Map();
11954
+ const recordWarning = (key, fields, message) => {
11955
+ const timestamp = now();
11956
+ const existing = logBuckets.get(key);
11957
+ if (!existing) {
11958
+ options.logger.warn(fields, message);
11959
+ logBuckets.set(key, { lastLoggedAt: timestamp, suppressed: 0, fields, message });
11960
+ return;
11961
+ }
11962
+ if (timestamp - existing.lastLoggedAt < logAggregationMs) {
11963
+ existing.suppressed += 1;
11964
+ existing.fields = fields;
11965
+ return;
11966
+ }
11967
+ options.logger.warn({ ...fields, suppressedSinceLastLog: existing.suppressed }, message);
11968
+ existing.lastLoggedAt = timestamp;
11969
+ existing.suppressed = 0;
11970
+ existing.fields = fields;
11971
+ existing.message = message;
11972
+ };
11973
+ const flushWarnings = () => {
11974
+ for (const bucket of logBuckets.values()) {
11975
+ if (bucket.suppressed === 0) continue;
11976
+ options.logger.warn(
11977
+ { ...bucket.fields, suppressedSinceLastLog: bucket.suppressed },
11978
+ bucket.message
11979
+ );
11980
+ bucket.suppressed = 0;
11981
+ }
11982
+ };
11983
+ const removeManaged = (entry) => {
11984
+ if (entry.handshakeTimer) clearTimeout(entry.handshakeTimer);
11985
+ if (entry.drainTimer) clearTimeout(entry.drainTimer);
11986
+ entry.socket.off("data", entry.onData);
11987
+ entry.socket.off("close", entry.onClose);
11988
+ entry.socket.off("end", entry.onEnd);
11989
+ entry.socket.off("error", entry.onError);
11990
+ managed.delete(entry.socket);
11991
+ if (entry.retirementKey) {
11992
+ const sockets = retiringReconnects.get(entry.retirementKey);
11993
+ sockets?.delete(entry.socket);
11994
+ if (sockets?.size === 0) retiringReconnects.delete(entry.retirementKey);
11995
+ }
11996
+ };
11997
+ const destroyRetirementGroup = (key) => {
11998
+ const sockets = retiringReconnects.get(key);
11999
+ if (!sockets) return;
12000
+ retiringReconnects.delete(key);
12001
+ for (const socket of [...sockets]) {
12002
+ const entry = managed.get(socket);
12003
+ if (entry) removeManaged(entry);
12004
+ socket.destroy();
12005
+ }
12006
+ };
12007
+ const startQuietDrain = (entry, phase, timeoutMs = rejectionDrainMs) => {
12008
+ if (entry.handshakeTimer) clearTimeout(entry.handshakeTimer);
12009
+ entry.handshakeTimer = null;
12010
+ entry.phase = phase;
12011
+ entry.buffer = Buffer.alloc(0);
12012
+ entry.socket.off("data", entry.onData);
12013
+ entry.onData = () => {
12014
+ };
12015
+ entry.socket.on("data", entry.onData);
12016
+ entry.socket.resume();
12017
+ entry.drainTimer = setTimeout(() => {
12018
+ if (entry.retirementKey) {
12019
+ destroyRetirementGroup(entry.retirementKey);
12020
+ return;
12021
+ }
12022
+ removeManaged(entry);
12023
+ entry.socket.destroy();
12024
+ }, timeoutMs);
12025
+ entry.drainTimer.unref?.();
12026
+ };
12027
+ const rejectAdmission = (entry, code, action, message) => {
12028
+ entry.socket.write(
12029
+ serializeTerminalAdmissionMessage({
12030
+ type: "terminal_admission_response",
12031
+ admissionVersion: TERMINAL_ADMISSION_VERSION,
12032
+ status: "retired",
12033
+ terminalProtocolVersion: options.terminalProtocolVersion,
12034
+ code,
12035
+ action,
12036
+ message
12037
+ })
12038
+ );
12039
+ recordWarning(code, { code }, "Terminal admission permanently rejected");
12040
+ startQuietDrain(entry, "draining");
12041
+ };
12042
+ const retireReconnect = (entry, request) => {
12043
+ const key = reconnectRetirementKey(request.generation, request.sessionId, request.pid);
12044
+ entry.retirementKey = key;
12045
+ let sockets = retiringReconnects.get(key);
12046
+ if (!sockets) {
12047
+ sockets = /* @__PURE__ */ new Set();
12048
+ retiringReconnects.set(key, sockets);
12049
+ }
12050
+ sockets.add(entry.socket);
12051
+ const action = request.kind === "terminal" ? "terminate" : "detach";
12052
+ entry.socket.write(serializePreAdmissionTerminalRetirement(request.sessionId, action));
12053
+ recordWarning(
12054
+ "pre_admission_terminal_retired",
12055
+ {
12056
+ sessionId: request.sessionId,
12057
+ provider: request.provider,
12058
+ action,
12059
+ generation: request.generation
12060
+ },
12061
+ "Pre-admission terminal remote view retired after reconnect"
12062
+ );
12063
+ startQuietDrain(entry, "retiring_reconnect");
12064
+ };
12065
+ const promote = (entry, accept, context, remainder) => {
12066
+ const socket = entry.socket;
12067
+ socket.pause();
12068
+ removeManaged(entry);
12069
+ try {
12070
+ if (remainder.length > 0) socket.unshift(remainder);
12071
+ accept(context);
12072
+ socket.resume();
12073
+ } catch (error) {
12074
+ recordWarning(
12075
+ "admission_dispatch_failed",
12076
+ { error: error instanceof Error ? error.message : String(error) },
12077
+ "Terminal admission dispatch failed"
12078
+ );
12079
+ socket.destroy();
12080
+ }
12081
+ };
12082
+ const handleFirstLine = (entry, line, remainder, accept) => {
12083
+ let raw;
12084
+ try {
12085
+ raw = JSON.parse(line);
12086
+ } catch {
12087
+ recordWarning(
12088
+ "invalid_first_frame",
12089
+ { lineBytes: Buffer.byteLength(line) },
12090
+ "Terminal connection sent an invalid first frame"
12091
+ );
12092
+ startQuietDrain(entry, "draining");
12093
+ return;
12094
+ }
12095
+ if (isTerminalAdmissionRequestCandidate(raw)) {
12096
+ const request = parseTerminalAdmissionRequest(raw);
12097
+ if (request === null) {
12098
+ const rawAdmissionVersion = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw.admissionVersion : void 0;
12099
+ const rawTerminalProtocolVersion = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw.terminalProtocolVersion : void 0;
12100
+ const serviceIsOutdated = typeof rawAdmissionVersion === "number" && Number.isSafeInteger(rawAdmissionVersion) && rawAdmissionVersion > TERMINAL_ADMISSION_VERSION || typeof rawTerminalProtocolVersion === "number" && Number.isSafeInteger(rawTerminalProtocolVersion) && rawTerminalProtocolVersion > options.terminalProtocolVersion;
12101
+ rejectAdmission(
12102
+ entry,
12103
+ serviceIsOutdated ? "TERMINAL_SERVICE_OUTDATED" : "ADMISSION_REQUEST_INVALID",
12104
+ serviceIsOutdated ? "restart_service" : "restart_terminal",
12105
+ serviceIsOutdated ? "This terminal requires a newer local protocol. Restart the DEV Anywhere service with the current CLI." : "The running DEV Anywhere service could not understand this terminal's admission request. Restart the terminal with the current DEV Anywhere CLI."
12106
+ );
12107
+ return;
12108
+ }
12109
+ if (request.terminalProtocolVersion !== options.terminalProtocolVersion) {
12110
+ const runtimeIsOutdated = request.terminalProtocolVersion < options.terminalProtocolVersion;
12111
+ rejectAdmission(
12112
+ entry,
12113
+ runtimeIsOutdated ? "TERMINAL_RUNTIME_OUTDATED" : "TERMINAL_SERVICE_OUTDATED",
12114
+ runtimeIsOutdated ? "restart_terminal" : "restart_service",
12115
+ runtimeIsOutdated ? `This terminal uses local IPC protocol ${request.terminalProtocolVersion}, but the running DEV Anywhere service requires ${options.terminalProtocolVersion}. Restart the terminal with the current DEV Anywhere CLI.` : `This terminal uses local IPC protocol ${request.terminalProtocolVersion}, but the running DEV Anywhere service only supports ${options.terminalProtocolVersion}. Restart the DEV Anywhere service with the current CLI.`
12116
+ );
12117
+ return;
12118
+ }
12119
+ entry.socket.write(
12120
+ serializeTerminalAdmissionMessage({
12121
+ type: "terminal_admission_response",
12122
+ admissionVersion: TERMINAL_ADMISSION_VERSION,
12123
+ status: "accepted",
12124
+ terminalProtocolVersion: options.terminalProtocolVersion
12125
+ })
12126
+ );
12127
+ promote(
12128
+ entry,
12129
+ accept,
12130
+ {
12131
+ clientKind: request.clientKind,
12132
+ ...request.sessionId !== void 0 ? { sessionId: request.sessionId } : {}
12133
+ },
12134
+ remainder
12135
+ );
12136
+ return;
12137
+ }
12138
+ const unversionedReconnect = parseUnversionedTerminalReconnect(raw);
12139
+ if (unversionedReconnect) {
12140
+ retireReconnect(entry, { ...unversionedReconnect, generation: "unversioned" });
12141
+ return;
12142
+ }
12143
+ const versionedReconnect = parseVersionedTerminalReconnect(raw);
12144
+ if (versionedReconnect) {
12145
+ retireReconnect(entry, {
12146
+ ...versionedReconnect,
12147
+ generation: `protocol-${versionedReconnect.protocolVersion}`
12148
+ });
12149
+ return;
12150
+ }
12151
+ recordWarning(
12152
+ "unsupported_first_frame",
12153
+ {
12154
+ type: raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw.type : void 0
12155
+ },
12156
+ "Terminal connection sent an unsupported first frame"
12157
+ );
12158
+ startQuietDrain(entry, "draining");
12159
+ };
12160
+ return {
12161
+ handle(socket, accept) {
12162
+ if (managed.size >= maxManagedConnections) {
12163
+ recordWarning(
12164
+ "admission_capacity_exceeded",
12165
+ { maxManagedConnections },
12166
+ "Terminal admission connection capacity exceeded"
12167
+ );
12168
+ socket.destroy();
12169
+ return;
12170
+ }
12171
+ const entry = {
12172
+ socket,
12173
+ buffer: Buffer.alloc(0),
12174
+ phase: "awaiting",
12175
+ handshakeTimer: null,
12176
+ drainTimer: null,
12177
+ retirementKey: null,
12178
+ onData: () => {
12179
+ },
12180
+ onClose: () => {
12181
+ },
12182
+ onEnd: () => {
12183
+ },
12184
+ onError: () => {
12185
+ }
12186
+ };
12187
+ const onClose = () => {
12188
+ if (managed.has(socket)) removeManaged(entry);
12189
+ };
12190
+ const onEnd = () => {
12191
+ if (entry.phase === "retiring_reconnect" && entry.retirementKey) {
12192
+ destroyRetirementGroup(entry.retirementKey);
12193
+ }
12194
+ };
12195
+ const onError = () => {
12196
+ };
12197
+ const onData = (chunk) => {
12198
+ if (entry.phase !== "awaiting") return;
12199
+ const incoming = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
12200
+ const newlineIndex = incoming.indexOf(10);
12201
+ const firstFrameBytes = entry.buffer.length + (newlineIndex >= 0 ? newlineIndex : incoming.length);
12202
+ if (firstFrameBytes > TERMINAL_ADMISSION_FRAME_MAX_BYTES) {
12203
+ recordWarning(
12204
+ "admission_frame_too_large",
12205
+ { maxFrameBytes: TERMINAL_ADMISSION_FRAME_MAX_BYTES },
12206
+ "Terminal admission first frame exceeded the byte limit"
12207
+ );
12208
+ startQuietDrain(entry, "draining");
12209
+ return;
12210
+ }
12211
+ if (newlineIndex < 0) {
12212
+ entry.buffer = Buffer.concat([entry.buffer, incoming]);
12213
+ return;
12214
+ }
12215
+ const line = Buffer.concat([entry.buffer, incoming.subarray(0, newlineIndex)]).toString(
12216
+ "utf-8"
12217
+ );
12218
+ const remainder = Buffer.from(incoming.subarray(newlineIndex + 1));
12219
+ handleFirstLine(entry, line, remainder, accept);
12220
+ };
12221
+ entry.onData = onData;
12222
+ entry.onClose = onClose;
12223
+ entry.onEnd = onEnd;
12224
+ entry.onError = onError;
12225
+ managed.set(socket, entry);
12226
+ socket.on("data", onData);
12227
+ socket.once("close", onClose);
12228
+ socket.once("end", onEnd);
12229
+ socket.on("error", onError);
12230
+ entry.handshakeTimer = setTimeout(() => {
12231
+ recordWarning(
12232
+ "admission_timeout",
12233
+ { timeoutMs: handshakeTimeoutMs },
12234
+ "Terminal connection did not send a first frame in time"
12235
+ );
12236
+ removeManaged(entry);
12237
+ socket.destroy();
12238
+ }, handshakeTimeoutMs);
12239
+ entry.handshakeTimer.unref?.();
12240
+ },
12241
+ destroyAll() {
12242
+ flushWarnings();
12243
+ for (const entry of [...managed.values()]) {
12244
+ removeManaged(entry);
12245
+ entry.socket.destroy();
12246
+ }
12247
+ retiringReconnects.clear();
12248
+ },
12249
+ get managedConnectionCount() {
12250
+ return managed.size;
12251
+ }
12252
+ };
12253
+ }
12254
+
11601
12255
  // src/serve/hook-registry.ts
11602
12256
  import { createHash as createHash3, randomBytes } from "crypto";
11603
- import { existsSync as existsSync8, mkdirSync, readFileSync as readFileSync8, renameSync, writeFileSync } from "fs";
11604
- import { dirname as dirname2 } from "path";
12257
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, readFileSync as readFileSync7, renameSync, writeFileSync } from "fs";
12258
+ import { dirname as dirname3 } from "path";
11605
12259
  import { z as z2 } from "zod";
11606
12260
  var PersistedHookSessionBindingSchema = z2.object({
11607
12261
  sessionId: z2.string(),
@@ -11664,7 +12318,7 @@ var HookRegistry = class {
11664
12318
  if (!this.persistPath || !existsSync8(this.persistPath)) return;
11665
12319
  try {
11666
12320
  const parsed = PersistedHookRegistrySchema.parse(
11667
- JSON.parse(readFileSync8(this.persistPath, "utf8"))
12321
+ JSON.parse(readFileSync7(this.persistPath, "utf8"))
11668
12322
  );
11669
12323
  this.bindingsBySession.clear();
11670
12324
  for (const binding of parsed.bindings) {
@@ -11680,7 +12334,7 @@ var HookRegistry = class {
11680
12334
  save() {
11681
12335
  if (!this.persistPath) return;
11682
12336
  try {
11683
- mkdirSync(dirname2(this.persistPath), { recursive: true });
12337
+ mkdirSync2(dirname3(this.persistPath), { recursive: true });
11684
12338
  const tmpPath = `${this.persistPath}.${process.pid}.${Date.now()}.tmp`;
11685
12339
  writeFileSync(
11686
12340
  tmpPath,
@@ -11729,7 +12383,7 @@ var HookServer = class {
11729
12383
  this.writeJson(res, 500, { error: "internal_error" });
11730
12384
  });
11731
12385
  });
11732
- return new Promise((resolve5, reject) => {
12386
+ return new Promise((resolve6, reject) => {
11733
12387
  const onError = (err) => {
11734
12388
  this.server?.off("listening", onListening);
11735
12389
  reject(err);
@@ -11737,7 +12391,7 @@ var HookServer = class {
11737
12391
  const onListening = () => {
11738
12392
  this.server?.off("error", onError);
11739
12393
  serviceLogger.info({ host: this.host, port: this.options.port }, "Hook server listening");
11740
- resolve5();
12394
+ resolve6();
11741
12395
  };
11742
12396
  this.server.once("error", onError);
11743
12397
  this.server.once("listening", onListening);
@@ -11748,8 +12402,8 @@ var HookServer = class {
11748
12402
  if (!this.server) return Promise.resolve();
11749
12403
  const server = this.server;
11750
12404
  this.server = null;
11751
- return new Promise((resolve5, reject) => {
11752
- server.close((err) => err ? reject(err) : resolve5());
12405
+ return new Promise((resolve6, reject) => {
12406
+ server.close((err) => err ? reject(err) : resolve6());
11753
12407
  });
11754
12408
  }
11755
12409
  getListeningPort() {
@@ -11845,7 +12499,7 @@ var HookServer = class {
11845
12499
  res.end();
11846
12500
  }
11847
12501
  readBody(req) {
11848
- return new Promise((resolve5, reject) => {
12502
+ return new Promise((resolve6, reject) => {
11849
12503
  let body = "";
11850
12504
  let size = 0;
11851
12505
  req.setEncoding("utf8");
@@ -11858,7 +12512,7 @@ var HookServer = class {
11858
12512
  }
11859
12513
  body += chunk;
11860
12514
  });
11861
- req.on("end", () => resolve5(body));
12515
+ req.on("end", () => resolve6(body));
11862
12516
  req.on("error", reject);
11863
12517
  });
11864
12518
  }
@@ -11945,20 +12599,24 @@ function createServeShutdown(deps) {
11945
12599
  deps.relayConnectionClose();
11946
12600
  deps.workerRegistryDestroyAll();
11947
12601
  deps.hostedPtyRegistryDestroyAll();
12602
+ deps.terminalAdmissionDestroyAll?.();
11948
12603
  deps.ipcServerClose();
11949
- unlinkIfPresent(deps.sockPath);
11950
- unlinkIfPresent(deps.pidPath);
12604
+ if (deps.runtimeStateCleanup) deps.runtimeStateCleanup();
12605
+ else {
12606
+ removeLocalIpcEndpoint(deps.sockPath);
12607
+ unlinkIfPresent(deps.pidPath);
12608
+ }
11951
12609
  await flushLogger(deps.logger);
11952
12610
  exit(0);
11953
12611
  };
11954
12612
  }
11955
12613
 
11956
12614
  // src/serve/remote-file-upload.ts
11957
- import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
12615
+ import { createWriteStream, mkdirSync as mkdirSync3 } from "fs";
11958
12616
  import { tmpdir as tmpdir2 } from "os";
11959
- import { extname as extname2, join as join8 } from "path";
12617
+ import { extname as extname2, join as join9 } from "path";
11960
12618
  import { nanoid as nanoid6 } from "nanoid";
11961
- var DEFAULT_DATA_DIR = join8(tmpdir2(), "dev-anywhere");
12619
+ var DEFAULT_DATA_DIR = join9(tmpdir2(), "dev-anywhere");
11962
12620
  var SAFE_EXT_RE = /^[A-Za-z0-9]{1,6}$/;
11963
12621
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Map([
11964
12622
  ["image/png", "png"],
@@ -11974,9 +12632,9 @@ function uploadPathFor(msg, dataDir, suffix) {
11974
12632
  if (msg.kind === "clipboard_image") {
11975
12633
  const extension = IMAGE_EXTENSIONS.get(msg.mimeType);
11976
12634
  if (!extension) throw new Error("\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F");
11977
- return join8(dataDir, `paste-${suffix}.${extension}`);
12635
+ return join9(dataDir, `paste-${suffix}.${extension}`);
11978
12636
  }
11979
- return join8(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
12637
+ return join9(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
11980
12638
  }
11981
12639
  var RemoteFileUploadManager = class {
11982
12640
  constructor(deps) {
@@ -12009,7 +12667,7 @@ var RemoteFileUploadManager = class {
12009
12667
  }
12010
12668
  try {
12011
12669
  const dataDir = this.deps.dataDir ?? DEFAULT_DATA_DIR;
12012
- mkdirSync2(dataDir, { recursive: true });
12670
+ mkdirSync3(dataDir, { recursive: true });
12013
12671
  const path = uploadPathFor(msg, dataDir, this.deps.randomSuffix?.() ?? nanoid6(6));
12014
12672
  const stream = createWriteStream(path, { mode: 384 });
12015
12673
  const active = {
@@ -12120,9 +12778,9 @@ import { createReadStream as createReadStream2, statSync as statSync3 } from "fs
12120
12778
  import { basename as basename4 } from "path";
12121
12779
 
12122
12780
  // src/serve/remote-file-path.ts
12123
- import { realpathSync } from "fs";
12781
+ import { realpathSync as realpathSync2 } from "fs";
12124
12782
  import { homedir as homedir7 } from "os";
12125
- import { extname as extname3, isAbsolute as isAbsolute9, resolve as resolve4 } from "path";
12783
+ import { extname as extname3, isAbsolute as isAbsolute11, resolve as resolve5 } from "path";
12126
12784
  var EXT_MIME_MAP = {
12127
12785
  ".png": "image/png",
12128
12786
  ".jpg": "image/jpeg",
@@ -12156,9 +12814,9 @@ function guessMimeType(filePath) {
12156
12814
  return EXT_MIME_MAP[ext] ?? "application/octet-stream";
12157
12815
  }
12158
12816
  function resolveRemoteFilePath(rawPath, cwd) {
12159
- const expandedPath = rawPath === "~" || rawPath.startsWith("~/") ? resolve4(homedir7(), rawPath.slice(2)) : rawPath;
12160
- const candidate = isAbsolute9(expandedPath) ? resolve4(expandedPath) : resolve4(cwd, expandedPath);
12161
- return realpathSync(candidate);
12817
+ const expandedPath = rawPath === "~" || rawPath.startsWith("~/") ? resolve5(homedir7(), rawPath.slice(2)) : rawPath;
12818
+ const candidate = isAbsolute11(expandedPath) ? resolve5(expandedPath) : resolve5(cwd, expandedPath);
12819
+ return realpathSync2(candidate);
12162
12820
  }
12163
12821
 
12164
12822
  // src/serve/remote-file-stream.ts
@@ -12444,8 +13102,6 @@ function createRelayAutoUpdater(options) {
12444
13102
  runnerTargetVersion,
12445
13103
  "--running-version",
12446
13104
  options.runningVersion,
12447
- "--daemon-pid",
12448
- String(options.daemonPid),
12449
13105
  "--relay",
12450
13106
  options.relayName
12451
13107
  ];
@@ -12520,12 +13176,188 @@ function createRelayAutoUpdater(options) {
12520
13176
  };
12521
13177
  }
12522
13178
 
13179
+ // src/relay-upgrade-bootstrap.ts
13180
+ var DEFAULT_BOOTSTRAP_TIMEOUT_MS = 5e3;
13181
+ var DEFAULT_RETRY_INITIAL_MS = 5e3;
13182
+ var DEFAULT_RETRY_MAX_MS = 5 * 6e4;
13183
+ var InvalidRelayUpgradeBootstrapResponseError = class extends Error {
13184
+ };
13185
+ function relayUpgradeBootstrapUrl(relayUrl) {
13186
+ const url = new URL(relayUrl);
13187
+ if (url.protocol === "ws:") url.protocol = "http:";
13188
+ else if (url.protocol === "wss:") url.protocol = "https:";
13189
+ else throw new Error(`Unsupported Relay URL protocol: ${url.protocol}`);
13190
+ url.pathname = `${url.pathname.replace(/\/$/, "")}/api/proxy-upgrade-bootstrap`;
13191
+ url.search = "";
13192
+ url.hash = "";
13193
+ return url;
13194
+ }
13195
+ async function fetchRelayUpgradeBootstrap(options) {
13196
+ const fetchImpl = options.fetchImpl ?? fetch;
13197
+ const headers = options.token ? { authorization: `Bearer ${options.token}` } : void 0;
13198
+ const response = await fetchImpl(relayUpgradeBootstrapUrl(options.relayUrl), {
13199
+ headers,
13200
+ redirect: "error",
13201
+ cache: "no-store",
13202
+ signal: options.signal
13203
+ });
13204
+ if (response.status === 404) return null;
13205
+ if (!response.ok) throw new Error(`Relay upgrade bootstrap returned HTTP ${response.status}`);
13206
+ let body;
13207
+ try {
13208
+ body = await response.json();
13209
+ } catch {
13210
+ throw new InvalidRelayUpgradeBootstrapResponseError(
13211
+ "Relay upgrade bootstrap returned an invalid response"
13212
+ );
13213
+ }
13214
+ const parsed = ProxyUpgradeBootstrapResponseSchema.safeParse(body);
13215
+ if (!parsed.success) {
13216
+ throw new InvalidRelayUpgradeBootstrapResponseError(
13217
+ "Relay upgrade bootstrap returned an invalid response"
13218
+ );
13219
+ }
13220
+ return parsed.data;
13221
+ }
13222
+ function createRelayUpgradeBootstrapMonitor(options) {
13223
+ const localControlProtocolVersion = typeof options.controlProtocolVersion === "number" && Number.isSafeInteger(options.controlProtocolVersion) && options.controlProtocolVersion > 0 ? options.controlProtocolVersion : RELAY_CONTROL_PROTOCOL_VERSION;
13224
+ let disposed = false;
13225
+ let active = false;
13226
+ let inFlight = null;
13227
+ let retryTimer = null;
13228
+ let retryAttempt = 0;
13229
+ let generation = 0;
13230
+ let lastPublishedKey = null;
13231
+ const clearRetry = () => {
13232
+ if (!retryTimer) return;
13233
+ clearTimeout(retryTimer);
13234
+ retryTimer = null;
13235
+ };
13236
+ const suspend = () => {
13237
+ active = false;
13238
+ retryAttempt = 0;
13239
+ generation += 1;
13240
+ clearRetry();
13241
+ inFlight?.abort();
13242
+ inFlight = null;
13243
+ };
13244
+ const publish = (event) => {
13245
+ const key = `${event.direction}:${event.relayVersion ?? ""}:${event.relayControlProtocolVersion ?? ""}`;
13246
+ if (lastPublishedKey === key) return;
13247
+ lastPublishedKey = key;
13248
+ options.onAdmission(event);
13249
+ };
13250
+ const scheduleRetry = () => {
13251
+ if (disposed || !active || inFlight || retryTimer) return;
13252
+ const initial = options.retryInitialMs ?? DEFAULT_RETRY_INITIAL_MS;
13253
+ const maximum = options.retryMaxMs ?? DEFAULT_RETRY_MAX_MS;
13254
+ const delay3 = Math.min(initial * 2 ** Math.min(retryAttempt, 30), maximum);
13255
+ retryAttempt += 1;
13256
+ retryTimer = setTimeout(() => {
13257
+ retryTimer = null;
13258
+ probe();
13259
+ }, delay3);
13260
+ retryTimer.unref?.();
13261
+ };
13262
+ const probe = () => {
13263
+ if (disposed || !active || inFlight) return;
13264
+ const controller = new AbortController();
13265
+ const probeGeneration = generation;
13266
+ const timeout = setTimeout(
13267
+ () => controller.abort(),
13268
+ options.timeoutMs ?? DEFAULT_BOOTSTRAP_TIMEOUT_MS
13269
+ );
13270
+ timeout.unref?.();
13271
+ inFlight = controller;
13272
+ void fetchRelayUpgradeBootstrap({
13273
+ relayUrl: options.relayUrl,
13274
+ token: options.token,
13275
+ signal: controller.signal,
13276
+ fetchImpl: options.fetchImpl
13277
+ }).then((bootstrap) => {
13278
+ if (disposed || !active || controller.signal.aborted || probeGeneration !== generation || inFlight !== controller || !bootstrap) {
13279
+ return;
13280
+ }
13281
+ const direction = compareProxyRelayProtocolVersions(
13282
+ localControlProtocolVersion,
13283
+ bootstrap.controlProtocolVersion
13284
+ );
13285
+ options.logger.info(
13286
+ {
13287
+ relayVersion: bootstrap.relayVersion,
13288
+ controlProtocolVersion: bootstrap.controlProtocolVersion,
13289
+ direction
13290
+ },
13291
+ "Received Relay upgrade bootstrap"
13292
+ );
13293
+ publish({
13294
+ direction,
13295
+ relayVersion: bootstrap.relayVersion,
13296
+ relayControlProtocolVersion: bootstrap.controlProtocolVersion
13297
+ });
13298
+ if (direction === ProxyProtocolAdmissionDirection.RELAY_OUTDATED) {
13299
+ options.logger.warn(
13300
+ {
13301
+ localControlProtocolVersion,
13302
+ relayControlProtocolVersion: bootstrap.controlProtocolVersion
13303
+ },
13304
+ "Relay control protocol is older; waiting for Relay update"
13305
+ );
13306
+ return;
13307
+ }
13308
+ active = false;
13309
+ retryAttempt = 0;
13310
+ clearRetry();
13311
+ }).catch((error) => {
13312
+ if (disposed || !active || controller.signal.aborted || probeGeneration !== generation || inFlight !== controller) {
13313
+ return;
13314
+ }
13315
+ if (error instanceof InvalidRelayUpgradeBootstrapResponseError) {
13316
+ active = false;
13317
+ retryAttempt = 0;
13318
+ clearRetry();
13319
+ options.logger.error(
13320
+ { error: error.message },
13321
+ "Relay upgrade bootstrap protocol mismatch; retries stopped"
13322
+ );
13323
+ publish({ direction: ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH });
13324
+ return;
13325
+ }
13326
+ options.logger.debug(
13327
+ { error: error instanceof Error ? error.message : String(error) },
13328
+ "Relay upgrade bootstrap unavailable"
13329
+ );
13330
+ }).finally(() => {
13331
+ clearTimeout(timeout);
13332
+ if (inFlight === controller) inFlight = null;
13333
+ if (probeGeneration === generation) scheduleRetry();
13334
+ });
13335
+ };
13336
+ return {
13337
+ request() {
13338
+ if (disposed) return;
13339
+ if (!active) {
13340
+ active = true;
13341
+ retryAttempt = 0;
13342
+ }
13343
+ if (!retryTimer) probe();
13344
+ },
13345
+ markControlProtocolConnected() {
13346
+ suspend();
13347
+ },
13348
+ dispose() {
13349
+ disposed = true;
13350
+ suspend();
13351
+ }
13352
+ };
13353
+ }
13354
+
12523
13355
  // src/serve/device-preview/default-device-preview-backend.ts
12524
13356
  import sharp from "sharp";
12525
13357
 
12526
13358
  // src/serve/device-preview/android-adapter.ts
12527
13359
  import { execFile as nodeExecFile } from "child_process";
12528
- import { delimiter, join as join9 } from "path";
13360
+ import { posix, win32 } from "path";
12529
13361
  var ADB_TIMEOUT_MS = 5e3;
12530
13362
  var ADB_OUTPUT_LIMIT_BYTES = 1024 * 1024;
12531
13363
  var AndroidEmulatorAdapterError = class extends Error {
@@ -12537,7 +13369,7 @@ var AndroidEmulatorAdapterError = class extends Error {
12537
13369
  code;
12538
13370
  };
12539
13371
  function defaultExecFile(command, args, options) {
12540
- return new Promise((resolve5, reject) => {
13372
+ return new Promise((resolve6, reject) => {
12541
13373
  nodeExecFile(
12542
13374
  command,
12543
13375
  [...args],
@@ -12547,7 +13379,7 @@ function defaultExecFile(command, args, options) {
12547
13379
  reject(error);
12548
13380
  return;
12549
13381
  }
12550
- resolve5({ stdout, stderr });
13382
+ resolve6({ stdout, stderr });
12551
13383
  }
12552
13384
  );
12553
13385
  });
@@ -12571,25 +13403,34 @@ function validEmulatorSerial(serial) {
12571
13403
  const port = Number(match[1]);
12572
13404
  return Number.isSafeInteger(port) && port <= 65535;
12573
13405
  }
12574
- function adbCandidates(command, env) {
13406
+ function adbCandidates(command, env, platform) {
12575
13407
  const explicit = command?.trim();
12576
13408
  if (explicit) {
12577
13409
  if (!validCommand(explicit)) return [];
12578
13410
  return [explicit];
12579
13411
  }
12580
- const executable = process.platform === "win32" ? "adb.exe" : "adb";
13412
+ const executable = platform === "win32" ? "adb.exe" : "adb";
13413
+ const { join: join11, delimiter } = platform === "win32" ? win32 : posix;
13414
+ const readEnv = (key) => environmentValue(env, key, platform);
12581
13415
  const candidates = [];
12582
- const sdkRoots = [env.ANDROID_SDK_ROOT, env.ANDROID_HOME];
12583
- if (env.HOME) {
13416
+ const sdkRoots = [readEnv("ANDROID_SDK_ROOT"), readEnv("ANDROID_HOME")];
13417
+ const home = readEnv("HOME");
13418
+ const localAppData = readEnv("LOCALAPPDATA");
13419
+ if (platform === "win32") {
13420
+ if (localAppData) sdkRoots.push(join11(localAppData, "Android", "Sdk"));
13421
+ } else if (home) {
12584
13422
  sdkRoots.push(
12585
- process.platform === "darwin" ? join9(env.HOME, "Library", "Android", "sdk") : join9(env.HOME, "Android", "Sdk")
13423
+ platform === "darwin" ? join11(home, "Library", "Android", "sdk") : join11(home, "Android", "Sdk")
12586
13424
  );
12587
13425
  }
12588
13426
  for (const root of sdkRoots) {
12589
- if (root) candidates.push(join9(root, "platform-tools", executable));
13427
+ if (root) candidates.push(join11(root, "platform-tools", executable));
12590
13428
  }
12591
- for (const entry of (env.PATH ?? "").split(delimiter)) {
12592
- if (entry) candidates.push(join9(entry, executable));
13429
+ for (const entry of (readEnv("PATH") ?? "").split(delimiter)) {
13430
+ if (entry)
13431
+ candidates.push(
13432
+ join11(platform === "win32" ? entry.replace(/^"(.*)"$/, "$1") : entry, executable)
13433
+ );
12593
13434
  }
12594
13435
  candidates.push(executable);
12595
13436
  return [...new Set(candidates.filter(validCommand))];
@@ -12646,12 +13487,14 @@ function orientSize(naturalSize, rotation) {
12646
13487
  var AndroidEmulatorAdapter = class {
12647
13488
  env;
12648
13489
  requestedCommand;
13490
+ platform;
12649
13491
  execFile;
12650
13492
  allowedDevices = /* @__PURE__ */ new Map();
12651
13493
  inputQueues = /* @__PURE__ */ new Map();
12652
13494
  locatedCommand = null;
12653
13495
  constructor(options) {
12654
- this.env = { ...options.env ?? process.env };
13496
+ this.platform = options.platform ?? process.platform;
13497
+ this.env = normalizeProcessEnvironment({ ...options.env ?? process.env }, this.platform);
12655
13498
  this.requestedCommand = options.command;
12656
13499
  this.execFile = options.execFile ?? defaultExecFile;
12657
13500
  }
@@ -12659,7 +13502,7 @@ var AndroidEmulatorAdapter = class {
12659
13502
  if (this.locatedCommand) {
12660
13503
  return { available: true, command: this.locatedCommand };
12661
13504
  }
12662
- for (const candidate of adbCandidates(this.requestedCommand, this.env)) {
13505
+ for (const candidate of adbCandidates(this.requestedCommand, this.env, this.platform)) {
12663
13506
  try {
12664
13507
  const result = await this.execFile(candidate, ["version"], {
12665
13508
  env: this.env,
@@ -14022,7 +14865,7 @@ function defaultSpawnRunner(command, args, options) {
14022
14865
  return nodeSpawn2(command, [...args], options);
14023
14866
  }
14024
14867
  async function defaultReserveLoopbackPort() {
14025
- return new Promise((resolve5, reject) => {
14868
+ return new Promise((resolve6, reject) => {
14026
14869
  const server = createServer3();
14027
14870
  server.unref();
14028
14871
  server.once("error", reject);
@@ -14035,7 +14878,7 @@ async function defaultReserveLoopbackPort() {
14035
14878
  }
14036
14879
  server.close((error) => {
14037
14880
  if (error) reject(error);
14038
- else resolve5(address.port);
14881
+ else resolve6(address.port);
14039
14882
  });
14040
14883
  });
14041
14884
  });
@@ -14074,19 +14917,19 @@ function terminateChild(child) {
14074
14917
  }
14075
14918
  function delay2(ms, signal) {
14076
14919
  throwIfAborted4(signal);
14077
- return new Promise((resolve5, reject) => {
14920
+ return new Promise((resolve6, reject) => {
14078
14921
  const onAbort = () => {
14079
14922
  clearTimeout(timer);
14080
14923
  reject(abortError2());
14081
14924
  };
14082
14925
  const timer = setTimeout(() => {
14083
14926
  signal?.removeEventListener("abort", onAbort);
14084
- resolve5();
14927
+ resolve6();
14085
14928
  }, ms);
14086
14929
  signal?.addEventListener("abort", onAbort, { once: true });
14087
14930
  });
14088
14931
  }
14089
- function isRecord3(value) {
14932
+ function isRecord4(value) {
14090
14933
  return typeof value === "object" && value !== null && !Array.isArray(value);
14091
14934
  }
14092
14935
  function normalizeUdid(value) {
@@ -14155,7 +14998,7 @@ function normalizeState(rawState) {
14155
14998
  return "transitioning";
14156
14999
  }
14157
15000
  function processCode(error) {
14158
- if (!isRecord3(error) || typeof error.code !== "string") return void 0;
15001
+ if (!isRecord4(error) || typeof error.code !== "string") return void 0;
14159
15002
  return /^[A-Z][A-Z0-9_]{1,31}$/.test(error.code) ? error.code : void 0;
14160
15003
  }
14161
15004
  function inputFailure(message) {
@@ -14226,14 +15069,14 @@ function parseBaguetteChromeLayout(output) {
14226
15069
  "Baguette chrome layout returned invalid JSON"
14227
15070
  );
14228
15071
  }
14229
- if (!isRecord3(parsed)) {
15072
+ if (!isRecord4(parsed)) {
14230
15073
  throw new IosSimulatorAdapterError(
14231
15074
  "INVALID_TARGET_METADATA",
14232
15075
  "Baguette chrome layout is not an object"
14233
15076
  );
14234
15077
  }
14235
15078
  const screen = parsed.screen;
14236
- if (!isRecord3(screen)) {
15079
+ if (!isRecord4(screen)) {
14237
15080
  throw new IosSimulatorAdapterError(
14238
15081
  "INVALID_TARGET_METADATA",
14239
15082
  "Baguette chrome layout is missing screen geometry"
@@ -14257,7 +15100,7 @@ function parseSimctlDevices(output) {
14257
15100
  } catch {
14258
15101
  throw new IosSimulatorAdapterError("SIMCTL_INVALID_RESPONSE", "simctl returned invalid JSON");
14259
15102
  }
14260
- if (!isRecord3(parsed) || !isRecord3(parsed.devices)) {
15103
+ if (!isRecord4(parsed) || !isRecord4(parsed.devices)) {
14261
15104
  throw new IosSimulatorAdapterError(
14262
15105
  "SIMCTL_INVALID_RESPONSE",
14263
15106
  "simctl response is missing devices"
@@ -14274,7 +15117,7 @@ function parseSimctlDevices(output) {
14274
15117
  "simctl returned too many devices"
14275
15118
  );
14276
15119
  }
14277
- if (!isRecord3(candidate)) continue;
15120
+ if (!isRecord4(candidate)) continue;
14278
15121
  const record = candidate;
14279
15122
  if (typeof record.udid !== "string" || typeof record.name !== "string" || typeof record.deviceTypeIdentifier !== "string" || typeof record.state !== "string" || record.name.length === 0 || record.name.length > 512 || record.isAvailable === false) {
14280
15123
  continue;
@@ -14330,8 +15173,8 @@ var LatestFrameSampler = class {
14330
15173
  next() {
14331
15174
  if (this.error) return Promise.reject(this.error);
14332
15175
  if (this.ended) return Promise.resolve({ done: true, value: void 0 });
14333
- return new Promise((resolve5, reject) => {
14334
- this.waiters.push({ resolve: resolve5, reject });
15176
+ return new Promise((resolve6, reject) => {
15177
+ this.waiters.push({ resolve: resolve6, reject });
14335
15178
  this.flush();
14336
15179
  });
14337
15180
  }
@@ -14375,7 +15218,7 @@ function waitForWebSocketOpen(socket, timeoutMs, signal) {
14375
15218
  if (socket.readyState !== WebSocket2.CONNECTING) {
14376
15219
  return Promise.reject(streamFailure("Baguette stream socket closed before opening"));
14377
15220
  }
14378
- return new Promise((resolve5, reject) => {
15221
+ return new Promise((resolve6, reject) => {
14379
15222
  const cleanup = () => {
14380
15223
  clearTimeout(timer);
14381
15224
  socket.off("open", onOpen);
@@ -14386,7 +15229,7 @@ function waitForWebSocketOpen(socket, timeoutMs, signal) {
14386
15229
  const settle = (error) => {
14387
15230
  cleanup();
14388
15231
  if (error) reject(error);
14389
- else resolve5();
15232
+ else resolve6();
14390
15233
  };
14391
15234
  const onOpen = () => settle();
14392
15235
  const onError = () => settle(streamFailure("Could not connect to Baguette stream"));
@@ -14509,14 +15352,14 @@ var BaguetteInputSession = class {
14509
15352
  () => void 0
14510
15353
  );
14511
15354
  if (!signal) return wireResult;
14512
- return new Promise((resolve5, reject) => {
15355
+ return new Promise((resolve6, reject) => {
14513
15356
  let settled = false;
14514
15357
  const finish = (error) => {
14515
15358
  if (settled) return;
14516
15359
  settled = true;
14517
15360
  signal.removeEventListener("abort", onAbort);
14518
15361
  if (error) reject(error);
14519
- else resolve5();
15362
+ else resolve6();
14520
15363
  };
14521
15364
  const onAbort = () => {
14522
15365
  if (token.acknowledged) {
@@ -14577,7 +15420,7 @@ var BaguetteInputSession = class {
14577
15420
  new IosSimulatorAdapterError("INVALID_INPUT", "Baguette input exceeded the size limit")
14578
15421
  );
14579
15422
  }
14580
- return new Promise((resolve5, reject) => {
15423
+ return new Promise((resolve6, reject) => {
14581
15424
  const timer = setTimeout(() => {
14582
15425
  this.fail(
14583
15426
  new IosSimulatorAdapterError(
@@ -14586,7 +15429,7 @@ var BaguetteInputSession = class {
14586
15429
  )
14587
15430
  );
14588
15431
  }, this.inputAckTimeoutMs);
14589
- this.pendingAck = { token, resolve: resolve5, reject, timer };
15432
+ this.pendingAck = { token, resolve: resolve6, reject, timer };
14590
15433
  try {
14591
15434
  stdin.write(payload, (error) => {
14592
15435
  if (error) this.fail(inputFailure("Could not send input to Baguette"));
@@ -14620,7 +15463,7 @@ var BaguetteInputSession = class {
14620
15463
  );
14621
15464
  return;
14622
15465
  }
14623
- if (!isRecord3(parsed) || typeof parsed.ok !== "boolean") {
15466
+ if (!isRecord4(parsed) || typeof parsed.ok !== "boolean") {
14624
15467
  this.fail(
14625
15468
  new IosSimulatorAdapterError(
14626
15469
  "INPUT_PROTOCOL_ERROR",
@@ -14807,14 +15650,14 @@ var BaguetteServeSession = class {
14807
15650
  return Promise.reject(inputFailure("Baguette preview session is closed"));
14808
15651
  }
14809
15652
  const payload = JSON.stringify(envelope);
14810
- return new Promise((resolve5, reject) => {
15653
+ return new Promise((resolve6, reject) => {
14811
15654
  let settled = false;
14812
15655
  const finish = (error) => {
14813
15656
  if (settled) return;
14814
15657
  settled = true;
14815
15658
  signal?.removeEventListener("abort", onAbort);
14816
15659
  if (error) reject(error);
14817
- else resolve5();
15660
+ else resolve6();
14818
15661
  };
14819
15662
  const onAbort = () => finish(abortError2());
14820
15663
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -14845,7 +15688,7 @@ var BaguetteServeSession = class {
14845
15688
  if (this.closed || this.socket.readyState !== WebSocket2.OPEN) {
14846
15689
  return Promise.reject(inputFailure("Baguette preview session is closed"));
14847
15690
  }
14848
- return new Promise((resolve5, reject) => {
15691
+ return new Promise((resolve6, reject) => {
14849
15692
  const onAbort = () => {
14850
15693
  const pending = this.pendingPaste;
14851
15694
  if (!pending) return;
@@ -14865,7 +15708,7 @@ var BaguetteServeSession = class {
14865
15708
  clearTimeout(timer);
14866
15709
  signal?.removeEventListener("abort", onAbort);
14867
15710
  };
14868
- this.pendingPaste = { resolve: resolve5, reject, cleanup, sent: false, callerSettled: false };
15711
+ this.pendingPaste = { resolve: resolve6, reject, cleanup, sent: false, callerSettled: false };
14869
15712
  signal?.addEventListener("abort", onAbort, { once: true });
14870
15713
  if (signal?.aborted) {
14871
15714
  onAbort();
@@ -14899,7 +15742,7 @@ var BaguetteServeSession = class {
14899
15742
  } catch {
14900
15743
  return;
14901
15744
  }
14902
- if (!isRecord3(parsed) || parsed.type !== "paste_result") return;
15745
+ if (!isRecord4(parsed) || parsed.type !== "paste_result") return;
14903
15746
  if (!this.pendingPaste) return;
14904
15747
  if (typeof parsed.ok !== "boolean") {
14905
15748
  this.completePendingPaste(
@@ -16204,8 +17047,8 @@ var DevicePreviewStreamConnection = class {
16204
17047
  } catch (error) {
16205
17048
  return Promise.reject(error instanceof Error ? error : streamError("\u8BBE\u5907\u753B\u9762\u7F16\u7801\u5931\u8D25"));
16206
17049
  }
16207
- const pending = new Promise((resolve5, reject) => {
16208
- this.pendingFrames.set(streamId, { frame, resolve: resolve5, reject });
17050
+ const pending = new Promise((resolve6, reject) => {
17051
+ this.pendingFrames.set(streamId, { frame, resolve: resolve6, reject });
16209
17052
  });
16210
17053
  this.flushPending();
16211
17054
  return pending;
@@ -16231,8 +17074,8 @@ var DevicePreviewStreamConnection = class {
16231
17074
  } catch (error) {
16232
17075
  return Promise.reject(error instanceof Error ? error : streamError("\u8BBE\u5907\u753B\u9762\u7F16\u7801\u5931\u8D25"));
16233
17076
  }
16234
- const pending = new Promise((resolve5, reject) => {
16235
- this.pendingFrames.set(streamId, { frame, resolve: resolve5, reject });
17077
+ const pending = new Promise((resolve6, reject) => {
17078
+ this.pendingFrames.set(streamId, { frame, resolve: resolve6, reject });
16236
17079
  });
16237
17080
  this.flushPending();
16238
17081
  return pending;
@@ -16417,22 +17260,14 @@ function parseServiceOptions(argv) {
16417
17260
  options.relayName = relayName;
16418
17261
  continue;
16419
17262
  }
16420
- if (arg === "--preserve-stopped-marker") {
16421
- options.preserveStoppedMarker = true;
16422
- }
16423
17263
  }
16424
17264
  return options;
16425
17265
  }
16426
17266
  async function startService(options) {
16427
17267
  ensureProfileWorkspace();
16428
- await cleanupStaleResources();
17268
+ await claimServiceRuntime();
17269
+ const instanceId = randomUUID();
16429
17270
  await cleanupStalePreviewRuntimes(PREVIEW_RUN_DIR);
16430
- if (!options?.preserveStoppedMarker) {
16431
- try {
16432
- unlinkSync2(STOPPED_PATH);
16433
- } catch {
16434
- }
16435
- }
16436
17271
  const permissionBroker = new PermissionBroker();
16437
17272
  const agentStatusRegistry = new AgentStatusRegistry();
16438
17273
  let unregisterHookSession = () => {
@@ -16443,10 +17278,21 @@ async function startService(options) {
16443
17278
  terminal: TERMINAL_IPC_PROTOCOL_VERSION,
16444
17279
  worker: WORKER_IPC_PROTOCOL_VERSION
16445
17280
  };
16446
- const allowSessionRuntimeHandover = sessionRuntimeIpcVersionsMatch(
16447
- readSessionRuntimeIpcVersions(SESSION_RUNTIME_IPC_VERSION_PATH),
16448
- currentSessionRuntimeIpcVersions
17281
+ const previousSessionRuntimeIpcVersions = readSessionRuntimeIpcVersions(
17282
+ SESSION_RUNTIME_IPC_VERSION_PATH
16449
17283
  );
17284
+ const allowSessionRuntimeHandover = {
17285
+ terminal: sessionRuntimeIpcVersionMatches(
17286
+ previousSessionRuntimeIpcVersions,
17287
+ currentSessionRuntimeIpcVersions,
17288
+ "terminal"
17289
+ ),
17290
+ worker: sessionRuntimeIpcVersionMatches(
17291
+ previousSessionRuntimeIpcVersions,
17292
+ currentSessionRuntimeIpcVersions,
17293
+ "worker"
17294
+ )
17295
+ };
16450
17296
  const sessionManager = new SessionManager({
16451
17297
  persistPath: SESSIONS_PATH,
16452
17298
  historyMetadataPath: HISTORY_METADATA_PATH,
@@ -16521,15 +17367,30 @@ async function startService(options) {
16521
17367
  profileName: PROFILE_NAME,
16522
17368
  relayName: proxyConfig.relayName,
16523
17369
  runningVersion: PROXY_VERSION,
16524
- daemonPid: process.pid,
16525
17370
  logger: serviceLogger
16526
17371
  });
16527
17372
  let serviceReadyForAutoUpdate = false;
16528
17373
  let pendingRelayVersion = null;
16529
- relayConnection.on("relay_version", (version) => {
16530
- pendingRelayVersion = version;
17374
+ const considerRelayVersion = (version) => {
17375
+ pendingRelayVersion = selectHighestStableVersion(pendingRelayVersion, version);
16531
17376
  if (serviceReadyForAutoUpdate) autoUpdater.considerRelayVersion(version);
17377
+ };
17378
+ const upgradeBootstrap = createRelayUpgradeBootstrapMonitor({
17379
+ relayUrl,
17380
+ token: relayToken,
17381
+ logger: serviceLogger,
17382
+ onAdmission: (event) => {
17383
+ if (event.relayVersion) considerRelayVersion(event.relayVersion);
17384
+ relayConnection.applyProtocolAdmission(event.direction);
17385
+ }
16532
17386
  });
17387
+ relayConnection.on("relay_version", considerRelayVersion);
17388
+ relayConnection.on("connected", () => upgradeBootstrap.markControlProtocolConnected());
17389
+ relayConnection.on("disconnected", () => upgradeBootstrap.request());
17390
+ relayConnection.on("protocol_blocked", (event) => {
17391
+ if (event.source !== "http_bootstrap") upgradeBootstrap.request();
17392
+ });
17393
+ upgradeBootstrap.request();
16533
17394
  const relaySend = (data) => relayConnection.sendRaw(data);
16534
17395
  const previewManager = new PreviewManager({
16535
17396
  persistPath: PREVIEWS_PATH,
@@ -16722,38 +17583,60 @@ async function startService(options) {
16722
17583
  }
16723
17584
  }
16724
17585
  await workerRegistry.reconnectAll();
16725
- const server = createServer4((socket) => {
16726
- handleTerminalConnection(socket, {
16727
- sessionManager,
16728
- workerRegistry,
16729
- terminalSockets,
16730
- terminalSubscriptionBacklog,
16731
- hostedPtyRegistry,
16732
- relayConnection,
17586
+ const terminalAdmission = createTerminalIpcAdmissionController({
17587
+ terminalProtocolVersion: TERMINAL_IPC_PROTOCOL_VERSION,
17588
+ logger: serviceLogger
17589
+ });
17590
+ const terminalConnectionDeps = {
17591
+ sessionManager,
17592
+ terminalSockets,
17593
+ terminalSubscriptionBacklog,
17594
+ hostedPtyRegistry,
17595
+ relayConnection,
17596
+ permissionBroker,
17597
+ hookEventRouter: hookRuntime.hookEventRouter,
17598
+ createHookContext: hookRuntime.createHookContext,
17599
+ emitAgentStatus: eventBridge.emitAgentStatus,
17600
+ updateTerminalCwd: eventBridge.updateTerminalCwd,
17601
+ resolveInterruptedApprovals: (sessionId) => resolveInterruptedApprovals(
16733
17602
  permissionBroker,
16734
- hookEventRouter: hookRuntime.hookEventRouter,
16735
- createHookContext: hookRuntime.createHookContext,
16736
- emitAgentStatus: eventBridge.emitAgentStatus,
16737
- updateTerminalCwd: eventBridge.updateTerminalCwd,
16738
- config: statusConfig,
16739
- resolveInterruptedApprovals: (sessionId) => resolveInterruptedApprovals(
16740
- permissionBroker,
16741
- hookRuntime.hookEventRouter,
16742
- relayConnection,
16743
- sessionId
16744
- )
17603
+ hookRuntime.hookEventRouter,
17604
+ relayConnection,
17605
+ sessionId
17606
+ )
17607
+ };
17608
+ const server = createServer4({ pauseOnConnect: true }, (socket) => {
17609
+ terminalAdmission.handle(socket, (admission) => {
17610
+ handleTerminalConnection(socket, terminalConnectionDeps, admission);
16745
17611
  });
17612
+ socket.resume();
16746
17613
  });
16747
- server.listen(SOCK_PATH, () => {
16748
- writeFileSync2(PID_PATH, String(process.pid));
16749
- chmodSync(SOCK_PATH, 384);
16750
- serviceLogger.info({ pid: process.pid, sock: SOCK_PATH }, "Service started");
16751
- serviceReadyForAutoUpdate = true;
16752
- if (pendingRelayVersion) autoUpdater.considerRelayVersion(pendingRelayVersion);
17614
+ await new Promise((resolve6, reject) => {
17615
+ const onError = (error) => {
17616
+ server.off("error", onError);
17617
+ reject(error);
17618
+ };
17619
+ server.once("error", onError);
17620
+ server.listen(SOCK_PATH, () => {
17621
+ server.off("error", onError);
17622
+ try {
17623
+ writeFileSync2(PID_PATH, String(process.pid));
17624
+ setLocalIpcEndpointPermissions(SOCK_PATH);
17625
+ serviceLogger.info({ pid: process.pid, sock: SOCK_PATH }, "Service started");
17626
+ resolve6();
17627
+ } catch (error) {
17628
+ reject(error);
17629
+ }
17630
+ });
16753
17631
  });
17632
+ let control = void 0;
17633
+ let stopping = false;
16754
17634
  const shutdown = createServeShutdown({
16755
17635
  logger: serviceLogger,
16756
- autoUpdaterDispose: () => autoUpdater.dispose(),
17636
+ autoUpdaterDispose: () => {
17637
+ upgradeBootstrap.dispose();
17638
+ autoUpdater.dispose();
17639
+ },
16757
17640
  sessionManagerStopReaper: () => sessionManager.stopReaper(),
16758
17641
  relayRouterDestroy: () => relayRouter.destroy(),
16759
17642
  previewManagerShutdown: () => previewManager.shutdown(),
@@ -16763,16 +17646,52 @@ async function startService(options) {
16763
17646
  relayConnectionClose: () => relayConnection.close(),
16764
17647
  workerRegistryDestroyAll: () => workerRegistry.destroyAll(),
16765
17648
  hostedPtyRegistryDestroyAll: () => hostedPtyRegistry.destroyAll(),
17649
+ terminalAdmissionDestroyAll: () => terminalAdmission.destroyAll(),
16766
17650
  ipcServerClose: () => server.close(),
16767
17651
  sockPath: SOCK_PATH,
16768
- pidPath: PID_PATH
16769
- });
16770
- process.on("SIGTERM", () => {
16771
- void shutdown();
17652
+ pidPath: PID_PATH,
17653
+ runtimeStateCleanup: () => {
17654
+ control?.close();
17655
+ removeLocalIpcEndpoint(SERVICE_CONTROL_PATH);
17656
+ removeLocalIpcEndpoint(SOCK_PATH);
17657
+ rmSync2(PID_PATH, { force: true });
17658
+ }
16772
17659
  });
16773
- process.on("SIGINT", () => {
17660
+ const stop = () => {
17661
+ stopping = true;
16774
17662
  void shutdown();
17663
+ };
17664
+ process.on("SIGTERM", stop);
17665
+ process.on("SIGINT", stop);
17666
+ if (existsSync9(STOPPED_PATH)) {
17667
+ await shutdown();
17668
+ return;
17669
+ }
17670
+ control = await startServiceControl({
17671
+ socketPath: SERVICE_CONTROL_PATH,
17672
+ onStop: stop,
17673
+ getStatus: () => ({
17674
+ pid: process.pid,
17675
+ instanceId,
17676
+ profile: PROFILE_NAME,
17677
+ version: PROXY_VERSION,
17678
+ state: stopping ? "stopping" : "ready",
17679
+ info: {
17680
+ config: statusConfig,
17681
+ relay: relayConnection.getStatus(),
17682
+ sessions: sessionManager.listSessions().map((s) => ({
17683
+ id: s.id,
17684
+ mode: s.mode,
17685
+ state: s.state,
17686
+ createdAt: new Date(s.createdAt).toISOString(),
17687
+ ...s.name !== void 0 ? { name: s.name } : {},
17688
+ hasWorker: workerRegistry.has(s.id)
17689
+ }))
17690
+ }
17691
+ })
16775
17692
  });
17693
+ serviceReadyForAutoUpdate = true;
17694
+ if (pendingRelayVersion) autoUpdater.considerRelayVersion(pendingRelayVersion);
16776
17695
  }
16777
17696
  var isMainModule = process.argv[1] && (process.argv[1].endsWith("serve.js") || process.argv[1].endsWith("serve.ts"));
16778
17697
  if (isMainModule) {