@dev-anywhere/proxy 0.9.1 → 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 (71) 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-DAFUSBKJ.js +299 -0
  11. package/dist/chunk-DAFUSBKJ.js.map +1 -0
  12. package/dist/{chunk-HLN3NOD2.js → chunk-GFDOVLGL.js} +70 -1
  13. package/dist/chunk-GFDOVLGL.js.map +1 -0
  14. package/dist/{chunk-SEMZ7GW7.js → chunk-GYL5JKWQ.js} +3 -3
  15. package/dist/{chunk-57LA2LWY.js → chunk-HYDXGNKA.js} +2 -2
  16. package/dist/chunk-ICSO3ZIS.js +658 -0
  17. package/dist/chunk-ICSO3ZIS.js.map +1 -0
  18. package/dist/chunk-JZ7MWN24.js +22 -0
  19. package/dist/chunk-JZ7MWN24.js.map +1 -0
  20. package/dist/chunk-KINQESTO.js +145 -0
  21. package/dist/chunk-KINQESTO.js.map +1 -0
  22. package/dist/{chunk-ZNMJH7BK.js → chunk-KWODOJBK.js} +3 -3
  23. package/dist/chunk-MLE2OKCM.js +116 -0
  24. package/dist/chunk-MLE2OKCM.js.map +1 -0
  25. package/dist/{chunk-UJEZAG57.js → chunk-PCF2R2TG.js} +3 -1
  26. package/dist/{chunk-UJEZAG57.js.map → chunk-PCF2R2TG.js.map} +1 -1
  27. package/dist/{chunk-NTL4CXBA.js → chunk-V4HDLUAQ.js} +27 -42
  28. package/dist/chunk-V4HDLUAQ.js.map +1 -0
  29. package/dist/{chunk-DZ4GXMP5.js → chunk-VHMAUU72.js} +56 -68
  30. package/dist/chunk-VHMAUU72.js.map +1 -0
  31. package/dist/{chunk-OFD4UVPB.js → chunk-XADKKDUV.js} +29 -153
  32. package/dist/chunk-XADKKDUV.js.map +1 -0
  33. package/dist/{chunk-WRU3BXW6.js → chunk-YK2XKOP4.js} +26 -10
  34. package/dist/chunk-YK2XKOP4.js.map +1 -0
  35. package/dist/index.js +130 -343
  36. package/dist/index.js.map +1 -1
  37. package/dist/logger-24TGGN76.js +10 -0
  38. package/dist/logger-24TGGN76.js.map +1 -0
  39. package/dist/logger-B7B64O4P.js +14 -0
  40. package/dist/logger-B7B64O4P.js.map +1 -0
  41. package/dist/{quick-tunnel-RI62V2RH.js → quick-tunnel-ZIFTYUUD.js} +3 -3
  42. package/dist/{relay-token-ZP3PAZD2.js → relay-token-N3BSBURG.js} +5 -5
  43. package/dist/serve.js +1158 -380
  44. package/dist/serve.js.map +1 -1
  45. package/dist/session-worker.js +91 -76
  46. package/dist/session-worker.js.map +1 -1
  47. package/dist/{terminal-BEXDQ5WK.js → terminal-7JY6J3XN.js} +88 -36
  48. package/dist/terminal-7JY6J3XN.js.map +1 -0
  49. package/dist/terminal-worker.js +93 -44
  50. package/dist/terminal-worker.js.map +1 -1
  51. package/dist/update-runner.js +86 -61
  52. package/dist/update-runner.js.map +1 -1
  53. package/package.json +9 -6
  54. package/scripts/postinstall.cjs +22 -0
  55. package/dist/chunk-7SYT65DN.js +0 -155
  56. package/dist/chunk-7SYT65DN.js.map +0 -1
  57. package/dist/chunk-DZ4GXMP5.js.map +0 -1
  58. package/dist/chunk-HLN3NOD2.js.map +0 -1
  59. package/dist/chunk-KGTYU4WO.js +0 -36
  60. package/dist/chunk-KGTYU4WO.js.map +0 -1
  61. package/dist/chunk-NTL4CXBA.js.map +0 -1
  62. package/dist/chunk-OFD4UVPB.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/terminal-BEXDQ5WK.js.map +0 -1
  67. /package/dist/{chunk-SEMZ7GW7.js.map → chunk-GYL5JKWQ.js.map} +0 -0
  68. /package/dist/{chunk-57LA2LWY.js.map → chunk-HYDXGNKA.js.map} +0 -0
  69. /package/dist/{chunk-ZNMJH7BK.js.map → chunk-KWODOJBK.js.map} +0 -0
  70. /package/dist/{quick-tunnel-RI62V2RH.js.map → quick-tunnel-ZIFTYUUD.js.map} +0 -0
  71. /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-OFD4UVPB.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,7 +33,10 @@ 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
41
  compareStableVersions,
26
42
  selectHighestStableVersion
@@ -43,19 +59,32 @@ import {
43
59
  KimiPermissionModeUnsupportedError,
44
60
  buildKimiTerminalArgs,
45
61
  detectAgentCliStatus,
46
- findExecutableCandidates,
47
62
  resolveCodexPermissionPolicy,
48
63
  resolveKimiAcpMode
49
- } from "./chunk-DZ4GXMP5.js";
64
+ } from "./chunk-VHMAUU72.js";
50
65
  import {
51
66
  PtyRenderSequencer,
52
67
  PtySynchronizedOutputCoalescer,
68
+ TERMINAL_ADMISSION_FRAME_MAX_BYTES,
69
+ TERMINAL_ADMISSION_VERSION,
53
70
  appendPtySemanticTextTail,
54
71
  extractOscSequences,
55
72
  extractOscSignals,
56
73
  extractOscWorkingDirectory,
57
- extractTextSignals
58
- } 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";
59
88
  import {
60
89
  ControlErrorCode,
61
90
  DEVICE_PREVIEW_FRAME_MAX_BYTES,
@@ -67,6 +96,7 @@ import {
67
96
  PTY_INITIAL_MIN_COLS,
68
97
  PTY_INITIAL_MIN_ROWS,
69
98
  PreviewSourceSchema,
99
+ ProxyProtocolAdmissionDirection,
70
100
  ProxyUpgradeBootstrapResponseSchema,
71
101
  RELAY_CONTROL_PROTOCOL_VERSION,
72
102
  RELAY_JSON_MESSAGE_MAX_BYTES,
@@ -79,6 +109,7 @@ import {
79
109
  WORKER_IPC_PROTOCOL_VERSION,
80
110
  WebPreviewNameSchema,
81
111
  buildMessage,
112
+ compareProxyRelayProtocolVersions,
82
113
  createFSM,
83
114
  createIpcReader,
84
115
  createWorkerReader,
@@ -89,27 +120,33 @@ import {
89
120
  encodeDevicePreviewH264ProxyPacket,
90
121
  encodeFileStreamFrame,
91
122
  isCompactCommandText,
123
+ isProxyProtocolRejectDirection,
92
124
  serializeControl,
93
125
  serializeIpc,
94
126
  serializeWorkerMsg,
95
127
  summarizeToolActivity
96
- } from "./chunk-NTL4CXBA.js";
128
+ } from "./chunk-V4HDLUAQ.js";
129
+ import {
130
+ localIpcEndpointMayExist,
131
+ removeLocalIpcEndpoint,
132
+ setLocalIpcEndpointPermissions,
133
+ unlinkIfPresent
134
+ } from "./chunk-77QVUYU7.js";
97
135
  import {
98
136
  classifyCodexActiveWriterError,
99
137
  codexActiveWriterMessage,
100
138
  sanitizeProviderErrorTail
101
139
  } from "./chunk-J5V2TKSV.js";
102
140
  import {
103
- buildProviderEnv,
104
- loadConfig,
105
- saveAgentCliPath
106
- } from "./chunk-SEMZ7GW7.js";
107
- import {
108
- atomicWriteFileSync
109
- } from "./chunk-NQDJ6QAM.js";
141
+ defaultShell,
142
+ environmentValue,
143
+ findExecutableCandidates,
144
+ normalizeProcessEnvironment,
145
+ prepareCommandLaunch
146
+ } from "./chunk-KINQESTO.js";
110
147
  import {
111
148
  serviceLogger
112
- } from "./chunk-ZNMJH7BK.js";
149
+ } from "./chunk-KWODOJBK.js";
113
150
  import {
114
151
  DATA_DIR,
115
152
  DEFAULT_PROXY_PROFILE,
@@ -120,6 +157,8 @@ import {
120
157
  PREVIEW_RUN_DIR,
121
158
  PROFILE_NAME,
122
159
  PROXY_ID_PATH,
160
+ SERVICE_CONTROL_PATH,
161
+ SERVICE_RUNTIME_LOCK_PATH,
123
162
  SESSIONS_PATH,
124
163
  SESSION_RUNTIME_IPC_VERSION_PATH,
125
164
  SOCK_PATH,
@@ -127,50 +166,142 @@ import {
127
166
  ensureProfileWorkspace,
128
167
  sessionPaths,
129
168
  tildify
130
- } from "./chunk-WRU3BXW6.js";
131
- import {
132
- PREVIEW_HEALTH_HEADER,
133
- PREVIEW_HEALTH_MARKER,
134
- PREVIEW_HEALTH_PATH,
135
- probePreviewTunnelEdge,
136
- startCloudflaredQuickTunnel,
137
- terminateTunnelChild
138
- } from "./chunk-C5RUR5MY.js";
139
- import {
140
- IS_DEV,
141
- spawnScript
142
- } from "./chunk-UJEZAG57.js";
169
+ } from "./chunk-YK2XKOP4.js";
143
170
  import {
144
171
  flushLogger
145
- } from "./chunk-WC3KEY7N.js";
172
+ } from "./chunk-ICSO3ZIS.js";
146
173
 
147
174
  // src/serve.ts
148
175
  import { createServer as createServer4 } from "net";
149
- 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";
150
178
 
151
179
  // src/serve/session-manager.ts
152
180
  import { readFileSync as readFileSync3, existsSync as existsSync2 } from "fs";
153
- import { isAbsolute, normalize } from "path";
181
+ import { isAbsolute as isAbsolute2, normalize } from "path";
154
182
  import { nanoid } from "nanoid";
155
183
 
156
184
  // src/common/managed-session-process.ts
157
185
  import { execFileSync } from "child_process";
158
- import { basename } from "path";
159
- 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
160
264
  function findEntryIndex(argv, name) {
161
265
  return argv.findIndex((arg) => {
162
- const file = basename(arg);
266
+ const file = basename(arg.replaceAll("\\", "/"));
163
267
  return file === name || file === `${name}.js` || file === `${name}.ts`;
164
268
  });
165
269
  }
166
- function findDevAnywhereEntryIndex(argv) {
167
- return argv.findIndex((arg) => {
168
- const file = basename(arg);
169
- if (file === "dev-anywhere") return true;
170
- if (file !== "index.js" && file !== "index.ts") return false;
171
- const pathSegments = arg.replaceAll("\\", "/").split("/");
172
- return pathSegments.includes("dev-anywhere") || pathSegments.includes("@dev-anywhere");
173
- });
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;
174
305
  }
175
306
  function readOption(args, name) {
176
307
  const indexes = args.flatMap((arg, index) => arg === name ? [index] : []);
@@ -221,7 +352,7 @@ function processArgvMatchesManagedSession(argv, identity) {
221
352
  if (terminalWorkerIndex >= 0) {
222
353
  return identity.provider === "claude" && terminalWorkerSessionId(argv.slice(terminalWorkerIndex + 1)) === identity.id;
223
354
  }
224
- const entryIndex = findDevAnywhereEntryIndex(argv);
355
+ const entryIndex = argv.findIndex(isDevAnywhereCliEntry);
225
356
  if (entryIndex < 0 || identity.provider === void 0) return false;
226
357
  try {
227
358
  const invocation = extractAgentInvocation(
@@ -271,6 +402,10 @@ function parsePosixCommandLine(command) {
271
402
  }
272
403
  function readProcessArgv(pid) {
273
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
+ }
274
409
  if (process.platform === "linux") {
275
410
  try {
276
411
  const commandLine = readFileSync(`/proc/${pid}/cmdline`);
@@ -714,7 +849,7 @@ var SessionManager = class {
714
849
  const session = this.sessions.get(id);
715
850
  if (!session || session.mode !== "pty" || session.kind !== "terminal") return false;
716
851
  const nextCwd = normalize(cwd);
717
- if (!isAbsolute(nextCwd) || nextCwd === session.cwd) return false;
852
+ if (!isAbsolute2(nextCwd) || nextCwd === session.cwd) return false;
718
853
  const previousCwd = session.cwd;
719
854
  session.cwd = nextCwd;
720
855
  session.updatedAt = Date.now();
@@ -936,7 +1071,9 @@ var SessionManager = class {
936
1071
  return;
937
1072
  }
938
1073
  for (const item of parsed) {
939
- 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) {
940
1077
  const sessionId = item !== null && typeof item === "object" && typeof item.id === "string" ? item.id : void 0;
941
1078
  const managedProcessDiscarded = this.discardManagedSessionProcess(
942
1079
  item,
@@ -973,13 +1110,7 @@ var SessionManager = class {
973
1110
  continue;
974
1111
  }
975
1112
  const processAlive2 = this.isProcessAlive(info.pid);
976
- const identityVerified2 = processAlive2 && this.managedSessionProcess(info.pid, {
977
- id: info.id,
978
- mode: "pty",
979
- provider: info.provider,
980
- ptyOwner: "local-terminal"
981
- });
982
- if (identityVerified2) {
1113
+ if (processAlive2) {
983
1114
  this.pendingPtyReconnectMetadata.set(info.id, info);
984
1115
  this.pendingPtyReconnectDeadlines.set(
985
1116
  info.id,
@@ -992,8 +1123,8 @@ var SessionManager = class {
992
1123
  } else {
993
1124
  this.onSessionRemoved?.(info.id);
994
1125
  serviceLogger.info(
995
- { sessionId: info.id, pid: info.pid, processAlive: processAlive2, identityVerified: identityVerified2 },
996
- "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"
997
1128
  );
998
1129
  }
999
1130
  continue;
@@ -1027,7 +1158,7 @@ var SessionManager = class {
1027
1158
  import WebSocket from "ws";
1028
1159
  import { readFileSync as readFileSync4, existsSync as existsSync3 } from "fs";
1029
1160
  import { homedir } from "os";
1030
- import { join } from "path";
1161
+ import { join as join2 } from "path";
1031
1162
  import { nanoid as nanoid2 } from "nanoid";
1032
1163
  import { EventEmitter } from "events";
1033
1164
 
@@ -1055,12 +1186,13 @@ var MemoryMessageQueue = class {
1055
1186
  };
1056
1187
 
1057
1188
  // src/serve/relay-connection.ts
1058
- var DEFAULT_PROXY_ID_PATH = join(homedir(), ".dev-anywhere", "proxy-id");
1189
+ var DEFAULT_PROXY_ID_PATH = join2(homedir(), ".dev-anywhere", "proxy-id");
1059
1190
  var MAX_BACKOFF_MS = 3e4;
1060
1191
  var BASE_BACKOFF_MS = 1e3;
1061
1192
  var MAX_QUEUE_SIZE = 1e4;
1062
1193
  var DEFAULT_HEARTBEAT_INTERVAL_MS = 15e3;
1063
1194
  var DEFAULT_HEARTBEAT_TIMEOUT_MS = 1e4;
1195
+ var DEFAULT_READY_TIMEOUT_MS = 1e4;
1064
1196
  var RELAY_CONNECTION_WEBSOCKET_OPTIONS = {
1065
1197
  maxPayload: 10 * 1024 * 1024,
1066
1198
  perMessageDeflate: {
@@ -1080,28 +1212,38 @@ var RelayConnectionState = {
1080
1212
  REGISTERING: "registering",
1081
1213
  SYNCED: "synced",
1082
1214
  WAITING_RECONNECT: "waiting_reconnect",
1215
+ BLOCKED_REMOTE: "blocked_remote",
1083
1216
  CLOSED: "closed"
1084
1217
  };
1085
1218
  var RELAY_TRANSITIONS = {
1086
1219
  [RelayConnectionState.DISCONNECTED]: [
1087
1220
  RelayConnectionState.CONNECTING,
1221
+ RelayConnectionState.BLOCKED_REMOTE,
1088
1222
  RelayConnectionState.CLOSED
1089
1223
  ],
1090
1224
  [RelayConnectionState.CONNECTING]: [
1091
1225
  RelayConnectionState.REGISTERING,
1092
1226
  RelayConnectionState.WAITING_RECONNECT,
1227
+ RelayConnectionState.BLOCKED_REMOTE,
1093
1228
  RelayConnectionState.CLOSED
1094
1229
  ],
1095
1230
  [RelayConnectionState.REGISTERING]: [
1096
1231
  RelayConnectionState.SYNCED,
1097
1232
  RelayConnectionState.WAITING_RECONNECT,
1233
+ RelayConnectionState.BLOCKED_REMOTE,
1098
1234
  RelayConnectionState.CLOSED
1099
1235
  ],
1100
1236
  [RelayConnectionState.SYNCED]: [
1101
1237
  RelayConnectionState.WAITING_RECONNECT,
1238
+ RelayConnectionState.BLOCKED_REMOTE,
1102
1239
  RelayConnectionState.CLOSED
1103
1240
  ],
1104
1241
  [RelayConnectionState.WAITING_RECONNECT]: [
1242
+ RelayConnectionState.CONNECTING,
1243
+ RelayConnectionState.BLOCKED_REMOTE,
1244
+ RelayConnectionState.CLOSED
1245
+ ],
1246
+ [RelayConnectionState.BLOCKED_REMOTE]: [
1105
1247
  RelayConnectionState.CONNECTING,
1106
1248
  RelayConnectionState.CLOSED
1107
1249
  ],
@@ -1114,6 +1256,7 @@ var RelayConnection = class extends EventEmitter {
1114
1256
  queue = new MemoryMessageQueue();
1115
1257
  reconnectAttempt = 0;
1116
1258
  reconnectTimer = null;
1259
+ readyTimeout;
1117
1260
  heartbeatTimer = null;
1118
1261
  heartbeatTimeoutTimer = null;
1119
1262
  fsm = createFSM({
@@ -1130,6 +1273,9 @@ var RelayConnection = class extends EventEmitter {
1130
1273
  version;
1131
1274
  heartbeatIntervalMs;
1132
1275
  heartbeatTimeoutMs;
1276
+ readyTimeoutMs;
1277
+ protocolAdmissionDirection = ProxyProtocolAdmissionDirection.COMPATIBLE;
1278
+ disconnectedNotified = false;
1133
1279
  constructor(relayUrl, options) {
1134
1280
  super();
1135
1281
  this.relayUrl = relayUrl;
@@ -1139,6 +1285,8 @@ var RelayConnection = class extends EventEmitter {
1139
1285
  this.version = options?.version ?? PROXY_VERSION;
1140
1286
  this.heartbeatIntervalMs = options?.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
1141
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;
1142
1290
  }
1143
1291
  // 从文件读取或生成新的 proxyId,生成后持久化到文件
1144
1292
  loadOrCreateProxyId(idPath) {
@@ -1164,13 +1312,15 @@ var RelayConnection = class extends EventEmitter {
1164
1312
  const url = this.token ? `${base}?token=${encodeURIComponent(this.token)}` : base;
1165
1313
  this.ws = new WebSocket(url, RELAY_CONNECTION_WEBSOCKET_OPTIONS);
1166
1314
  const socket = this.ws;
1167
- this.ws.on("open", () => {
1315
+ this.startReadyTimeout(socket);
1316
+ socket.on("open", () => {
1317
+ if (this.ws !== socket) return;
1168
1318
  if (!this.fsm.tryTransitionTo(RelayConnectionState.REGISTERING)) return;
1169
1319
  serviceLogger.info(
1170
1320
  { proxyId: this.proxyId, url: base, tokenSet: !!this.token },
1171
1321
  "Connected to relay server"
1172
1322
  );
1173
- this.ws.send(
1323
+ socket.send(
1174
1324
  serializeControl({
1175
1325
  type: "proxy_register",
1176
1326
  protocolVersion: RELAY_CONTROL_PROTOCOL_VERSION,
@@ -1180,7 +1330,8 @@ var RelayConnection = class extends EventEmitter {
1180
1330
  })
1181
1331
  );
1182
1332
  });
1183
- this.ws.on("message", (data, isBinary) => {
1333
+ socket.on("message", (data, isBinary) => {
1334
+ if (this.ws !== socket) return;
1184
1335
  const buf = data;
1185
1336
  if (isBinary) {
1186
1337
  if (this.fsm.current() !== RelayConnectionState.SYNCED) {
@@ -1221,21 +1372,32 @@ var RelayConnection = class extends EventEmitter {
1221
1372
  }
1222
1373
  const response = RelayControlSchema.safeParse(msg);
1223
1374
  if (!response.success || response.data.type !== "proxy_register_response") {
1375
+ const direction = compareProxyRelayProtocolVersions(
1376
+ RELAY_CONTROL_PROTOCOL_VERSION,
1377
+ msg.protocolVersion
1378
+ );
1224
1379
  serviceLogger.warn(
1225
- { issues: response.success ? void 0 : response.error.issues },
1380
+ { direction, issues: response.success ? void 0 : response.error.issues },
1226
1381
  "Invalid Proxy registration response; terminating relay connection"
1227
1382
  );
1228
- this.rejectRelayProtocol(socket, "invalid registration response");
1383
+ this.rejectRelayProtocol(
1384
+ socket,
1385
+ "invalid registration response",
1386
+ direction === ProxyProtocolAdmissionDirection.COMPATIBLE ? ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH : direction
1387
+ );
1229
1388
  return;
1230
1389
  }
1231
1390
  const { status, relayVersion, connectionId } = response.data;
1232
1391
  serviceLogger.info({ status, relayVersion }, "Received register response");
1233
1392
  if (!this.fsm.tryTransitionTo(RelayConnectionState.SYNCED)) return;
1393
+ this.clearReadyTimeout(socket);
1234
1394
  this.reconnectAttempt = 0;
1395
+ this.protocolAdmissionDirection = ProxyProtocolAdmissionDirection.COMPATIBLE;
1235
1396
  this.startHeartbeat();
1236
1397
  this.flushQueue();
1237
1398
  this.emit("relay_version", relayVersion);
1238
1399
  this.emit("stream_connection", connectionId);
1400
+ this.disconnectedNotified = false;
1239
1401
  this.emit("connected");
1240
1402
  return;
1241
1403
  }
@@ -1245,27 +1407,33 @@ var RelayConnection = class extends EventEmitter {
1245
1407
  }
1246
1408
  this.emit("message", msg);
1247
1409
  });
1248
- 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);
1249
1416
  this.stopHeartbeat();
1250
1417
  this.ws = null;
1251
1418
  const closeMeta = { code, reason: reason.toString() || void 0 };
1252
1419
  if (code === RelayCloseCode.PROXY_PROTOCOL_REJECTED) {
1253
- this.fsm.tryTransitionTo(RelayConnectionState.CLOSED);
1254
- serviceLogger.warn(closeMeta, "Relay rejected Proxy control protocol");
1255
- this.emit("disconnected");
1420
+ const direction = isProxyProtocolRejectDirection(closeMeta.reason) ? closeMeta.reason : ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH;
1421
+ this.applyProtocolRejection(direction, "websocket", closeMeta);
1256
1422
  } else if (this.fsm.current() !== RelayConnectionState.CLOSED) {
1257
1423
  this.fsm.tryTransitionTo(RelayConnectionState.WAITING_RECONNECT);
1258
1424
  serviceLogger.info(closeMeta, "Relay connection closed unexpectedly");
1259
- this.emit("disconnected");
1425
+ this.emitDisconnectedOnce();
1260
1426
  this.scheduleReconnect();
1261
1427
  } else {
1262
1428
  serviceLogger.info(closeMeta, "Relay connection closed");
1263
1429
  }
1264
1430
  });
1265
- this.ws.on("error", (err) => {
1431
+ socket.on("error", (err) => {
1432
+ if (this.ws !== socket) return;
1266
1433
  serviceLogger.error({ error: String(err) }, "Relay connection error");
1267
1434
  });
1268
- this.ws.on("pong", () => {
1435
+ socket.on("pong", () => {
1436
+ if (this.ws !== socket) return;
1269
1437
  this.clearHeartbeatTimeout();
1270
1438
  });
1271
1439
  } catch (err) {
@@ -1276,6 +1444,37 @@ var RelayConnection = class extends EventEmitter {
1276
1444
  }
1277
1445
  }
1278
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
+ }
1279
1478
  startHeartbeat() {
1280
1479
  this.stopHeartbeat();
1281
1480
  if (this.heartbeatIntervalMs <= 0 || this.heartbeatTimeoutMs <= 0) return;
@@ -1329,12 +1528,65 @@ var RelayConnection = class extends EventEmitter {
1329
1528
  serviceLogger.warn({ reason }, "Relay connection heartbeat failed; terminating stale socket");
1330
1529
  ws.terminate();
1331
1530
  }
1332
- rejectRelayProtocol(ws, reason) {
1531
+ rejectRelayProtocol(ws, detail, direction = ProxyProtocolAdmissionDirection.PROTOCOL_MISMATCH) {
1333
1532
  if (this.ws !== ws || this.fsm.current() === RelayConnectionState.CLOSED) return;
1533
+ this.clearReadyTimeout(ws);
1334
1534
  this.stopHeartbeat();
1335
- this.fsm.tryTransitionTo(RelayConnectionState.CLOSED);
1336
- serviceLogger.warn({ reason }, "Relay control protocol rejected");
1337
- 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");
1338
1590
  }
1339
1591
  // 将队列中缓存的消息依次发送到 relay
1340
1592
  flushQueue() {
@@ -1344,12 +1596,16 @@ var RelayConnection = class extends EventEmitter {
1344
1596
  }
1345
1597
  // 计算全抖动指数退避延迟并调度重连
1346
1598
  scheduleReconnect() {
1599
+ if (this.reconnectTimer || this.fsm.current() !== RelayConnectionState.WAITING_RECONNECT) {
1600
+ return;
1601
+ }
1347
1602
  const backoff = Math.random() * Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * Math.pow(2, this.reconnectAttempt));
1348
1603
  serviceLogger.info(
1349
1604
  { attempt: this.reconnectAttempt + 1, backoffMs: Math.round(backoff) },
1350
1605
  "Scheduling reconnect"
1351
1606
  );
1352
1607
  this.reconnectTimer = setTimeout(() => {
1608
+ this.reconnectTimer = null;
1353
1609
  this.reconnectAttempt++;
1354
1610
  if (!this.fsm.tryTransitionTo(RelayConnectionState.CONNECTING)) return;
1355
1611
  this.doConnect();
@@ -1390,18 +1646,25 @@ var RelayConnection = class extends EventEmitter {
1390
1646
  // 主动关闭连接,发送 proxy_disconnect 通知 relay 立即清理,不触发重连
1391
1647
  close() {
1392
1648
  if (this.fsm.is(RelayConnectionState.CLOSED)) return;
1649
+ const wasSynced = this.fsm.is(RelayConnectionState.SYNCED);
1393
1650
  this.fsm.tryTransitionTo(RelayConnectionState.CLOSED);
1394
1651
  if (this.reconnectTimer) {
1395
1652
  clearTimeout(this.reconnectTimer);
1396
1653
  this.reconnectTimer = null;
1397
1654
  }
1655
+ this.clearReadyTimeout();
1398
1656
  this.stopHeartbeat();
1399
- if (this.ws) {
1400
- if (this.ws.readyState === WebSocket.OPEN) {
1401
- 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();
1402
1667
  }
1403
- this.ws.close();
1404
- this.ws = null;
1405
1668
  }
1406
1669
  }
1407
1670
  // 获取当前 proxyId
@@ -1415,28 +1678,29 @@ var RelayConnection = class extends EventEmitter {
1415
1678
  connectionState: this.fsm.current(),
1416
1679
  proxyId: this.proxyId,
1417
1680
  reconnectAttempt: this.reconnectAttempt,
1418
- queueDepth: this.queue.size()
1681
+ queueDepth: this.queue.size(),
1682
+ protocolAdmissionDirection: this.protocolAdmissionDirection
1419
1683
  };
1420
1684
  }
1421
1685
  };
1422
1686
 
1423
1687
  // src/serve/handlers/control-messages.ts
1424
1688
  import { readdir as readdir2, mkdir } from "fs/promises";
1425
- 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";
1426
1690
 
1427
1691
  // src/serve/session-history.ts
1428
1692
  import { readdir, stat, lstat, access, open, readFile } from "fs/promises";
1429
1693
  import { createReadStream } from "fs";
1430
- 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";
1431
1695
  import { homedir as homedir2, tmpdir } from "os";
1432
1696
  import { createInterface } from "readline";
1433
- var claudeProjectsDir = () => join2(homedir2(), ".claude", "projects");
1434
- var codexSessionsDir = () => join2(homedir2(), ".codex", "sessions");
1697
+ var claudeProjectsDir = () => join3(homedir2(), ".claude", "projects");
1698
+ var codexSessionsDir = () => join3(homedir2(), ".codex", "sessions");
1435
1699
  var kimiCodeHome = () => {
1436
1700
  const configured = process.env.KIMI_CODE_HOME?.trim();
1437
- return configured ? resolve(configured) : join2(homedir2(), ".kimi-code");
1701
+ return configured ? resolve2(configured) : join3(homedir2(), ".kimi-code");
1438
1702
  };
1439
- var kimiSessionsDir = () => join2(kimiCodeHome(), "sessions");
1703
+ var kimiSessionsDir = () => join3(kimiCodeHome(), "sessions");
1440
1704
  var UNTITLED_SESSION_TITLE = "\u672A\u547D\u540D\u4F1A\u8BDD";
1441
1705
  var MAX_HISTORY_TITLE_LENGTH = 40;
1442
1706
  var IGNORED_SLASH_COMMANDS = /* @__PURE__ */ new Set([
@@ -1486,8 +1750,8 @@ async function scanSessionHistory(options = {}) {
1486
1750
  }
1487
1751
  function normalizeAbsolutePath(path) {
1488
1752
  const trimmed = path.trim();
1489
- if (!trimmed || !isAbsolute2(trimmed)) return null;
1490
- let resolved = resolve(trimmed);
1753
+ if (!trimmed || !isAbsolute3(trimmed)) return null;
1754
+ let resolved = resolve2(trimmed);
1491
1755
  while (resolved.length > 1 && resolved.endsWith(sep)) {
1492
1756
  resolved = resolved.slice(0, -1);
1493
1757
  }
@@ -1519,7 +1783,7 @@ async function scanClaudeSessionHistory() {
1519
1783
  return [];
1520
1784
  }
1521
1785
  for (const encodedDir of projectDirs) {
1522
- const projectPath = join2(claudeProjectsDir(), encodedDir);
1786
+ const projectPath = join3(claudeProjectsDir(), encodedDir);
1523
1787
  let files;
1524
1788
  try {
1525
1789
  files = await readdir(projectPath);
@@ -1528,7 +1792,7 @@ async function scanClaudeSessionHistory() {
1528
1792
  }
1529
1793
  for (const file of files) {
1530
1794
  if (!file.endsWith(".jsonl")) continue;
1531
- const filePath = join2(projectPath, file);
1795
+ const filePath = join3(projectPath, file);
1532
1796
  try {
1533
1797
  const fileStat = await stat(filePath);
1534
1798
  const sessionId = file.replace(/\.jsonl$/, "");
@@ -1583,7 +1847,7 @@ async function scanKimiSessionHistory() {
1583
1847
  const state = await readKimiSessionState(filePath);
1584
1848
  if (!state || state.archived === true) continue;
1585
1849
  if (typeof state.id !== "string" || !SAFE_SESSION_ID_PATTERN.test(state.id)) continue;
1586
- if (typeof state.cwd !== "string" || !isAbsolute2(state.cwd)) continue;
1850
+ if (typeof state.cwd !== "string" || !isAbsolute3(state.cwd)) continue;
1587
1851
  const rawTitle = typeof state.title === "string" ? state.title : typeof state.lastPrompt === "string" ? state.lastPrompt : "";
1588
1852
  let updatedAt;
1589
1853
  if (typeof state.updatedAt === "number" && Number.isFinite(state.updatedAt)) {
@@ -1638,7 +1902,7 @@ async function findClaudeSessionFile(claudeSessionId) {
1638
1902
  return null;
1639
1903
  }
1640
1904
  for (const encodedDir of projectDirs) {
1641
- const filePath = join2(claudeProjectsDir(), encodedDir, `${claudeSessionId}.jsonl`);
1905
+ const filePath = join3(claudeProjectsDir(), encodedDir, `${claudeSessionId}.jsonl`);
1642
1906
  try {
1643
1907
  await access(filePath);
1644
1908
  return filePath;
@@ -1675,7 +1939,7 @@ async function findKimiSessionFile(kimiSessionId) {
1675
1939
  for (const stateFile of stateFiles) {
1676
1940
  const state = await readKimiSessionState(stateFile);
1677
1941
  if (state?.id !== kimiSessionId) continue;
1678
- 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");
1679
1943
  try {
1680
1944
  const wireStat = await lstat(wireFile);
1681
1945
  if (wireStat.isSymbolicLink() || !wireStat.isFile()) continue;
@@ -2414,7 +2678,7 @@ function normalizeConversationText(text) {
2414
2678
  return trimmed;
2415
2679
  }
2416
2680
  async function extractTitleAndCwd(filePath) {
2417
- return new Promise((resolve5) => {
2681
+ return new Promise((resolve6) => {
2418
2682
  const input = createReadStream(filePath, { encoding: "utf-8" });
2419
2683
  const rl = createInterface({
2420
2684
  input,
@@ -2428,7 +2692,7 @@ async function extractTitleAndCwd(filePath) {
2428
2692
  resolved = true;
2429
2693
  rl.close();
2430
2694
  input.destroy();
2431
- resolve5({ title, cwd });
2695
+ resolve6({ title, cwd });
2432
2696
  };
2433
2697
  rl.on("line", (line) => {
2434
2698
  if (resolved) return;
@@ -2462,7 +2726,7 @@ async function collectJsonlFiles(root) {
2462
2726
  }
2463
2727
  const files = [];
2464
2728
  for (const entry of entries) {
2465
- const child = join2(root, entry.name);
2729
+ const child = join3(root, entry.name);
2466
2730
  if (entry.isDirectory()) {
2467
2731
  files.push(...await collectJsonlFiles(child));
2468
2732
  } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
@@ -2480,7 +2744,7 @@ async function collectFilesNamed(root, filename) {
2480
2744
  }
2481
2745
  const files = [];
2482
2746
  for (const entry of entries) {
2483
- const child = join2(root, entry.name);
2747
+ const child = join3(root, entry.name);
2484
2748
  if (entry.isDirectory()) {
2485
2749
  files.push(...await collectFilesNamed(child, filename));
2486
2750
  } else if (entry.isFile() && entry.name === filename) {
@@ -2490,7 +2754,7 @@ async function collectFilesNamed(root, filename) {
2490
2754
  return files;
2491
2755
  }
2492
2756
  async function extractCodexTitleAndCwd(filePath) {
2493
- return new Promise((resolve5) => {
2757
+ return new Promise((resolve6) => {
2494
2758
  const input = createReadStream(filePath, { encoding: "utf-8" });
2495
2759
  const rl = createInterface({
2496
2760
  input,
@@ -2505,7 +2769,7 @@ async function extractCodexTitleAndCwd(filePath) {
2505
2769
  resolved = true;
2506
2770
  rl.close();
2507
2771
  input.destroy();
2508
- resolve5({ id, title, cwd });
2772
+ resolve6({ id, title, cwd });
2509
2773
  };
2510
2774
  rl.on("line", (line) => {
2511
2775
  if (resolved) return;
@@ -2551,7 +2815,7 @@ function isCodexInjectedContextBlock(text) {
2551
2815
  // src/serve/command-discovery.ts
2552
2816
  import { readdirSync, readFileSync as readFileSync5 } from "fs";
2553
2817
  import { homedir as homedir3 } from "os";
2554
- import { join as join3 } from "path";
2818
+ import { join as join4 } from "path";
2555
2819
  var REPL_BUILTINS = [
2556
2820
  { name: "/compact", description: "Compact conversation history", source: "builtin" },
2557
2821
  { name: "/status", description: "Show session status", source: "builtin" },
@@ -2623,7 +2887,7 @@ function scanSkillsDir(dirPath, source) {
2623
2887
  }
2624
2888
  const commands = [];
2625
2889
  for (const name of entries) {
2626
- const skillPath = join3(dirPath, name, "SKILL.md");
2890
+ const skillPath = join4(dirPath, name, "SKILL.md");
2627
2891
  try {
2628
2892
  const content = readFileSync5(skillPath, "utf-8");
2629
2893
  const parsed = parseSkillFrontmatter(content);
@@ -2649,7 +2913,7 @@ function scanCommandsDir(dirPath, source) {
2649
2913
  for (const filename of entries) {
2650
2914
  const cmdName = filename.replace(/\.md$/, "");
2651
2915
  try {
2652
- const content = readFileSync5(join3(dirPath, filename), "utf-8");
2916
+ const content = readFileSync5(join4(dirPath, filename), "utf-8");
2653
2917
  const firstLine2 = content.split("\n")[0].trim();
2654
2918
  commands.push({
2655
2919
  name: `/${cmdName}`,
@@ -2667,7 +2931,7 @@ function scanCommandsDir(dirPath, source) {
2667
2931
  return commands;
2668
2932
  }
2669
2933
  function scanPluginDirs(homeDir) {
2670
- const pluginCacheDir = join3(homeDir, ".claude", "plugins", "cache");
2934
+ const pluginCacheDir = join4(homeDir, ".claude", "plugins", "cache");
2671
2935
  let pluginNames;
2672
2936
  try {
2673
2937
  pluginNames = readdirSync(pluginCacheDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
@@ -2676,9 +2940,9 @@ function scanPluginDirs(homeDir) {
2676
2940
  }
2677
2941
  const commands = [];
2678
2942
  for (const pluginName of pluginNames) {
2679
- const pluginDir = join3(pluginCacheDir, pluginName);
2680
- const skillCmds = scanSkillsDir(join3(pluginDir, "skills"), "plugin-skill");
2681
- 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");
2682
2946
  commands.push(...skillCmds, ...cmdCmds);
2683
2947
  }
2684
2948
  return commands;
@@ -2686,10 +2950,10 @@ function scanPluginDirs(homeDir) {
2686
2950
  async function discoverCommands(workDir, options) {
2687
2951
  const homeDir = options?.homeDir ?? homedir3();
2688
2952
  const builtins = REPL_BUILTINS.filter((c) => !COMMAND_BLACKLIST.has(c.name));
2689
- const userSkills = scanSkillsDir(join3(homeDir, ".claude", "skills"), "user-skill");
2690
- const projectSkills = scanSkillsDir(join3(workDir, ".claude", "skills"), "project-skill");
2691
- const userCommands = scanCommandsDir(join3(homeDir, ".claude", "commands"), "user-command");
2692
- 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");
2693
2957
  const pluginCommands = scanPluginDirs(homeDir);
2694
2958
  const commandMap = /* @__PURE__ */ new Map();
2695
2959
  for (const cmd of builtins) commandMap.set(cmd.name, cmd);
@@ -2838,7 +3102,7 @@ function touchSessionActivity(sessionManager, relay, sessionId, now = Date.now()
2838
3102
  // src/serve/handlers/control-messages.ts
2839
3103
  var COMMAND_REFRESH_MS = 6 * 60 * 60 * 1e3;
2840
3104
  function isPathSafe(path) {
2841
- if (!isAbsolute3(path)) return false;
3105
+ if (!isAbsolute4(path)) return false;
2842
3106
  const normalized = normalize2(path);
2843
3107
  if (normalized.includes("..")) return false;
2844
3108
  return true;
@@ -2866,7 +3130,7 @@ async function getFileTree(rootPath) {
2866
3130
  groups.push({ path: rootPath, entries: rootEntries });
2867
3131
  for (const sub of rootEntries) {
2868
3132
  if (!sub.isDir) continue;
2869
- const subPath = join4(rootPath, sub.name);
3133
+ const subPath = join5(rootPath, sub.name);
2870
3134
  try {
2871
3135
  const subEntries = await scanDir(subPath, { includeHidden: false });
2872
3136
  groups.push({ path: subPath, entries: subEntries });
@@ -3171,7 +3435,7 @@ function createControlMessageHandlers(send, sessionManager) {
3171
3435
 
3172
3436
  // src/serve/worker-registry.ts
3173
3437
  import { connect } from "net";
3174
- import { unlinkSync, existsSync as existsSync4, readdirSync as readdirSync2 } from "fs";
3438
+ import { existsSync as existsSync4, mkdirSync, readdirSync as readdirSync2 } from "fs";
3175
3439
 
3176
3440
  // src/serve/claude-stream-event-mapper.ts
3177
3441
  function mapClaudeStreamEvent(sessionId, seq, options) {
@@ -3790,7 +4054,7 @@ var WorkerRegistry = class {
3790
4054
  const startupFailure = this.startupFailures.get(sessionId);
3791
4055
  if (startupFailure) return Promise.reject(startupFailure);
3792
4056
  if (this.readySessions.has(sessionId)) return Promise.resolve();
3793
- return new Promise((resolve5, reject) => {
4057
+ return new Promise((resolve6, reject) => {
3794
4058
  const timeout = setTimeout(() => {
3795
4059
  const waiters2 = this.readyWaiters.get(sessionId);
3796
4060
  if (waiters2) {
@@ -3800,7 +4064,7 @@ var WorkerRegistry = class {
3800
4064
  reject(new Error(`Worker did not report ready within ${timeoutMs}ms`));
3801
4065
  }, timeoutMs);
3802
4066
  timeout.unref?.();
3803
- const waiter = { resolve: resolve5, reject, timeout };
4067
+ const waiter = { resolve: resolve6, reject, timeout };
3804
4068
  const waiters = this.readyWaiters.get(sessionId) ?? /* @__PURE__ */ new Set();
3805
4069
  waiters.add(waiter);
3806
4070
  this.readyWaiters.set(sessionId, waiters);
@@ -3808,6 +4072,7 @@ var WorkerRegistry = class {
3808
4072
  }
3809
4073
  spawn(sessionId, options) {
3810
4074
  const paths = sessionPaths(sessionId);
4075
+ mkdirSync(paths.dir, { recursive: true });
3811
4076
  const args = [sessionId, paths.workerSock];
3812
4077
  args.push("--provider", options.provider);
3813
4078
  if (options.cwd) args.push("--cwd", options.cwd);
@@ -3854,7 +4119,7 @@ var WorkerRegistry = class {
3854
4119
  return workerPid;
3855
4120
  }
3856
4121
  connect(sessionId, sockPath, timeoutMs) {
3857
- return new Promise((resolve5) => {
4122
+ return new Promise((resolve6) => {
3858
4123
  const sock = connect(sockPath);
3859
4124
  let settled = false;
3860
4125
  let timeout;
@@ -3862,7 +4127,7 @@ var WorkerRegistry = class {
3862
4127
  if (settled) return;
3863
4128
  settled = true;
3864
4129
  if (timeout) clearTimeout(timeout);
3865
- resolve5(result);
4130
+ resolve6(result);
3866
4131
  };
3867
4132
  const onConnectError = () => finish(null);
3868
4133
  sock.once("error", onConnectError);
@@ -4033,7 +4298,7 @@ var WorkerRegistry = class {
4033
4298
  for (const dir of dirs) {
4034
4299
  const sessionId = dir.name;
4035
4300
  const paths = sessionPaths(sessionId);
4036
- if (!existsSync4(paths.workerSock)) continue;
4301
+ if (!localIpcEndpointMayExist(paths.workerSock)) continue;
4037
4302
  const persistedSession = this.deps.sessionManager.getSession(sessionId);
4038
4303
  if (!persistedSession || persistedSession.mode !== "json") {
4039
4304
  await this.terminateOrphanWorker(sessionId, paths.workerSock);
@@ -4052,7 +4317,7 @@ var WorkerRegistry = class {
4052
4317
  serviceLogger.info({ sessionId }, "Reconnected to existing worker");
4053
4318
  } else {
4054
4319
  try {
4055
- unlinkSync(paths.workerSock);
4320
+ removeLocalIpcEndpoint(paths.workerSock);
4056
4321
  } catch {
4057
4322
  }
4058
4323
  serviceLogger.info({ sessionId }, "Cleaned up stale worker socket");
@@ -4225,7 +4490,7 @@ var WorkerRegistry = class {
4225
4490
  }
4226
4491
  }
4227
4492
  terminateOrphanWorker(sessionId, workerSocketPath) {
4228
- return new Promise((resolve5) => {
4493
+ return new Promise((resolve6) => {
4229
4494
  const socket = connect(workerSocketPath);
4230
4495
  let settled = false;
4231
4496
  const finish = (details) => {
@@ -4234,14 +4499,14 @@ var WorkerRegistry = class {
4234
4499
  clearTimeout(timeout);
4235
4500
  socket.destroy();
4236
4501
  try {
4237
- unlinkSync(workerSocketPath);
4502
+ removeLocalIpcEndpoint(workerSocketPath);
4238
4503
  } catch {
4239
4504
  }
4240
4505
  serviceLogger.warn(
4241
4506
  { sessionId, ...details },
4242
4507
  "Orphaned JSON worker removed without session data"
4243
4508
  );
4244
- resolve5();
4509
+ resolve6();
4245
4510
  };
4246
4511
  const timeout = setTimeout(
4247
4512
  () => finish({ terminated: false }),
@@ -4280,6 +4545,14 @@ var WorkerRegistry = class {
4280
4545
  },
4281
4546
  () => finish({ terminated: false })
4282
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
+ );
4283
4556
  });
4284
4557
  });
4285
4558
  }
@@ -5215,12 +5488,13 @@ var RelayPermissionHandlers = class {
5215
5488
  // src/serve/relay-resource-handlers.ts
5216
5489
  import { homedir as homedir4 } from "os";
5217
5490
  import { accessSync, constants, statSync } from "fs";
5491
+ import { isAbsolute as isAbsolute5 } from "path";
5218
5492
  function errorMessage(err) {
5219
5493
  return err instanceof Error ? err.message : String(err);
5220
5494
  }
5221
5495
  function validateExecutablePath(path) {
5222
5496
  const normalized = path.trim();
5223
- 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");
5224
5498
  const stat5 = statSync(normalized);
5225
5499
  if (!stat5.isFile()) throw new Error("CLI \u8DEF\u5F84\u4E0D\u662F\u53EF\u6267\u884C\u6587\u4EF6");
5226
5500
  accessSync(normalized, constants.X_OK);
@@ -5333,25 +5607,26 @@ var RelayResourceHandlers = class {
5333
5607
  // src/serve/relay-session-create-handler.ts
5334
5608
  import { rmSync, statSync as statSync2 } from "fs";
5335
5609
  import { homedir as homedir6 } from "os";
5336
- import { isAbsolute as isAbsolute5 } from "path";
5610
+ import { isAbsolute as isAbsolute7 } from "path";
5337
5611
  import { nanoid as nanoid3 } from "nanoid";
5338
5612
 
5339
5613
  // src/common/codex-active-writer.ts
5340
5614
  import { existsSync as existsSync5 } from "fs";
5341
5615
  import { homedir as homedir5 } from "os";
5342
- import { isAbsolute as isAbsolute4, join as join5 } from "path";
5343
- import { spawnSync } from "child_process";
5616
+ import { isAbsolute as isAbsolute6, join as join6 } from "path";
5617
+ import { spawnSync as spawnSync2 } from "child_process";
5344
5618
  var CODEX_THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
5345
5619
  var LSOF_TIMEOUT_MS = 1e3;
5346
5620
  function findCodexActiveWriter(threadId, env = process.env) {
5621
+ if (process.platform === "win32") return null;
5347
5622
  if (!CODEX_THREAD_ID_RE.test(threadId)) return null;
5348
5623
  const configuredHome = env.CODEX_HOME?.trim();
5349
- const codexHome = configuredHome && isAbsolute4(configuredHome) ? configuredHome : join5(homedir5(), ".codex");
5350
- 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`);
5351
5626
  if (!existsSync5(lockPath)) return null;
5352
5627
  const commands = process.platform === "darwin" ? ["/usr/sbin/lsof", "lsof"] : ["lsof"];
5353
5628
  for (const command of commands) {
5354
- const result = spawnSync(command, ["-t", lockPath], {
5629
+ const result = spawnSync2(command, ["-t", lockPath], {
5355
5630
  encoding: "utf8",
5356
5631
  timeout: LSOF_TIMEOUT_MS,
5357
5632
  maxBuffer: 64 * 1024,
@@ -5372,38 +5647,28 @@ function parseFirstPid(output) {
5372
5647
  }
5373
5648
 
5374
5649
  // src/common/process-ancestry.ts
5375
- import { spawnSync as spawnSync2 } from "child_process";
5650
+ import { spawnSync as spawnSync3 } from "child_process";
5376
5651
  var PROCESS_QUERY_TIMEOUT_MS = 1e3;
5377
5652
  var MAX_ANCESTRY_DEPTH = 64;
5378
5653
  function readParentProcessId(pid) {
5379
5654
  if (!Number.isSafeInteger(pid) || pid <= 0) return null;
5380
5655
  if (process.platform === "win32") {
5381
- const script = `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").ParentProcessId`;
5382
- const result = spawnSync2(
5383
- "powershell.exe",
5384
- ["-NoProfile", "-NonInteractive", "-Command", script],
5385
- {
5386
- encoding: "utf8",
5387
- timeout: PROCESS_QUERY_TIMEOUT_MS,
5388
- maxBuffer: 64 * 1024,
5389
- stdio: ["ignore", "pipe", "ignore"]
5390
- }
5391
- );
5392
- return result.error ? null : parseParentPid(result.stdout);
5656
+ const parentPid = readWindowsProcess(pid)?.parentPid;
5657
+ return parentPid !== void 0 && parentPid > 0 ? parentPid : null;
5393
5658
  }
5394
5659
  const commands = ["/bin/ps", "/usr/bin/ps", "ps"];
5395
5660
  const tried = /* @__PURE__ */ new Set();
5396
5661
  for (const command of commands) {
5397
5662
  if (tried.has(command)) continue;
5398
5663
  tried.add(command);
5399
- const result = spawnSync2(command, ["-o", "ppid=", "-p", String(pid)], {
5664
+ const result = spawnSync3(command, ["-o", "ppid=", "-p", String(pid)], {
5400
5665
  encoding: "utf8",
5401
5666
  timeout: PROCESS_QUERY_TIMEOUT_MS,
5402
5667
  maxBuffer: 64 * 1024,
5403
5668
  stdio: ["ignore", "pipe", "ignore"]
5404
5669
  });
5405
5670
  if (result.error && result.error.code === "ENOENT") continue;
5406
- return result.error ? null : parseParentPid(result.stdout);
5671
+ return result.error || result.status !== 0 ? null : parseParentPid(result.stdout);
5407
5672
  }
5408
5673
  return null;
5409
5674
  }
@@ -5477,19 +5742,27 @@ var HostedPtyRegistry = class {
5477
5742
  const kind = options.kind;
5478
5743
  const { cols, rows } = options;
5479
5744
  const command = options.kind === "terminal" ? {
5480
- command: options.shell ?? this.deps.getProviderEnv().SHELL ?? "/bin/sh",
5745
+ command: options.shell ?? defaultShell(this.deps.getProviderEnv()),
5481
5746
  args: [],
5482
5747
  env: this.deps.getProviderEnv()
5483
5748
  } : PROVIDERS[options.provider].buildTerminalCommand(
5484
5749
  {
5485
5750
  args: options.args,
5751
+ cwd: options.cwd,
5486
5752
  permissionMode: options.permissionMode,
5487
5753
  hook: options.hook
5488
5754
  },
5489
5755
  this.deps.getProviderEnv()
5490
5756
  );
5491
- const env = normalizeHostedPtyEnv(command.env);
5492
- 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, {
5493
5766
  name: HOSTED_PTY_TERM,
5494
5767
  cols,
5495
5768
  rows,
@@ -5834,7 +6107,7 @@ function throwIfAborted(signal) {
5834
6107
  }
5835
6108
  }
5836
6109
  function wait(delayMs, signal) {
5837
- return new Promise((resolve5, reject) => {
6110
+ return new Promise((resolve6, reject) => {
5838
6111
  throwIfAborted(signal);
5839
6112
  const onAbort = () => {
5840
6113
  clearTimeout(timer);
@@ -5842,7 +6115,7 @@ function wait(delayMs, signal) {
5842
6115
  };
5843
6116
  const timer = setTimeout(() => {
5844
6117
  signal.removeEventListener("abort", onAbort);
5845
- resolve5();
6118
+ resolve6();
5846
6119
  }, delayMs);
5847
6120
  timer.unref?.();
5848
6121
  signal.addEventListener("abort", onAbort, { once: true });
@@ -5915,7 +6188,7 @@ function validateSessionCwd(cwd) {
5915
6188
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
5916
6189
  }
5917
6190
  const trimmed = cwd.trim();
5918
- if (!isAbsolute5(trimmed)) {
6191
+ if (!isAbsolute7(trimmed)) {
5919
6192
  return { message: "\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84", code: ControlErrorCode.INVALID_PATH };
5920
6193
  }
5921
6194
  try {
@@ -6569,7 +6842,7 @@ function buildClaudeSpeechSummaryCommand({
6569
6842
  }
6570
6843
  var runClaudeSpeechSummary = ({ cwd, prompt, env, timeoutMs }) => {
6571
6844
  const { command, args } = buildClaudeSpeechSummaryCommand({ env, prompt });
6572
- return new Promise((resolve5, reject) => {
6845
+ return new Promise((resolve6, reject) => {
6573
6846
  const child = spawn2(command, args, {
6574
6847
  cwd,
6575
6848
  env: { ...process.env, ...env },
@@ -6601,7 +6874,7 @@ var runClaudeSpeechSummary = ({ cwd, prompt, env, timeoutMs }) => {
6601
6874
  clearTimeout(timer);
6602
6875
  const stdout = Buffer.concat(stdoutChunks).toString("utf8").trim();
6603
6876
  if (code === 0 && stdout.length > 0) {
6604
- resolve5(stdout);
6877
+ resolve6(stdout);
6605
6878
  return;
6606
6879
  }
6607
6880
  const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
@@ -6698,7 +6971,7 @@ function containsApprovalRiskEvaluation(summary) {
6698
6971
 
6699
6972
  // src/serve/preview/preview-manager.ts
6700
6973
  import { mkdir as mkdir2, rm as rm2, writeFile } from "fs/promises";
6701
- import { join as join7 } from "path";
6974
+ import { join as join8 } from "path";
6702
6975
  import { nanoid as nanoid4 } from "nanoid";
6703
6976
 
6704
6977
  // src/common/cpolar-quick-tunnel.ts
@@ -6783,8 +7056,8 @@ function createTimedSignal(timeoutMs, timeoutMessage) {
6783
7056
  let settled = false;
6784
7057
  let resolvePromise;
6785
7058
  let rejectPromise;
6786
- const promise = new Promise((resolve5, reject) => {
6787
- resolvePromise = resolve5;
7059
+ const promise = new Promise((resolve6, reject) => {
7060
+ resolvePromise = resolve6;
6788
7061
  rejectPromise = reject;
6789
7062
  });
6790
7063
  const timer = setTimeout(() => {
@@ -7166,7 +7439,7 @@ function normalizeLocalPreviewUrl(raw) {
7166
7439
  };
7167
7440
  }
7168
7441
  async function probeLocalPreviewTarget(target, timeoutMs = 2e3) {
7169
- const probeHost = (host) => new Promise((resolve5, reject) => {
7442
+ const probeHost = (host) => new Promise((resolve6, reject) => {
7170
7443
  const socket = connect2({ host, port: target.port });
7171
7444
  let settled = false;
7172
7445
  const finish = (error) => {
@@ -7175,7 +7448,7 @@ async function probeLocalPreviewTarget(target, timeoutMs = 2e3) {
7175
7448
  clearTimeout(timer);
7176
7449
  socket.destroy();
7177
7450
  if (error) reject(error);
7178
- else resolve5();
7451
+ else resolve6();
7179
7452
  };
7180
7453
  const timer = setTimeout(
7181
7454
  () => finish(new Error("\u65E0\u6CD5\u8FDE\u63A5\u672C\u5730\u7F51\u9875\uFF0C\u8BF7\u786E\u8BA4\u5B83\u6B63\u5728\u8FD0\u884C")),
@@ -7376,7 +7649,7 @@ var LocalPreviewProxy = class {
7376
7649
 
7377
7650
  // src/serve/preview/static-preview-handler.ts
7378
7651
  import { open as open2, realpath, stat as stat2 } from "fs/promises";
7379
- 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";
7380
7653
  var MIME_TYPES = {
7381
7654
  ".avif": "image/avif",
7382
7655
  ".css": "text/css; charset=utf-8",
@@ -7409,7 +7682,7 @@ var MIME_TYPES = {
7409
7682
  };
7410
7683
  function isWithinRoot(rootPath, targetPath) {
7411
7684
  const rel = relative(rootPath, targetPath);
7412
- return rel === "" || !rel.startsWith(`..${sep2}`) && rel !== ".." && !isAbsolute6(rel);
7685
+ return rel === "" || !rel.startsWith(`..${sep2}`) && rel !== ".." && !isAbsolute8(rel);
7413
7686
  }
7414
7687
  function hiddenOrDependencyPath(path) {
7415
7688
  return path.split("/").filter(Boolean).some((part) => part.startsWith(".") || part.toLowerCase() === "node_modules");
@@ -7474,7 +7747,7 @@ var StaticPreviewHandler = class {
7474
7747
  return;
7475
7748
  }
7476
7749
  const relativePath = decodedPath.replace(/^\/+/, "");
7477
- let candidatePath = resolve2(this.rootPath, relativePath || ".");
7750
+ let candidatePath = resolve3(this.rootPath, relativePath || ".");
7478
7751
  if (!isWithinRoot(this.rootPath, candidatePath)) {
7479
7752
  sendPreviewError(response, 404, "\u9875\u9762\u4E0D\u5B58\u5728");
7480
7753
  return;
@@ -7484,7 +7757,7 @@ var StaticPreviewHandler = class {
7484
7757
  try {
7485
7758
  candidateStat = await stat2(candidatePath);
7486
7759
  if (candidateStat.isDirectory()) {
7487
- candidatePath = resolve2(candidatePath, "index.html");
7760
+ candidatePath = resolve3(candidatePath, "index.html");
7488
7761
  candidateStat = await stat2(candidatePath);
7489
7762
  }
7490
7763
  } catch (error) {
@@ -7492,7 +7765,7 @@ var StaticPreviewHandler = class {
7492
7765
  const firstSegment = relativePath.split("/", 1)[0]?.toLowerCase();
7493
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";
7494
7767
  if (!documentFallback) throw error;
7495
- candidatePath = resolve2(this.rootPath, this.entryPath);
7768
+ candidatePath = resolve3(this.rootPath, this.entryPath);
7496
7769
  candidateStat = await stat2(candidatePath);
7497
7770
  }
7498
7771
  if (!candidateStat.isFile()) throw new Error("not a file");
@@ -7586,7 +7859,7 @@ var StaticPreviewHandler = class {
7586
7859
 
7587
7860
  // src/serve/preview/static-preview.ts
7588
7861
  import { lstat as lstat2, readdir as readdir3, realpath as realpath2, stat as stat3 } from "fs/promises";
7589
- 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";
7590
7863
  var MAX_SCAN_ENTRIES = 2e4;
7591
7864
  var MAX_HTML_ENTRIES = 1e3;
7592
7865
  var MAX_SCAN_DEPTH = 64;
@@ -7597,11 +7870,11 @@ function isHiddenOrDependency(name) {
7597
7870
  return name.startsWith(".") || name.toLowerCase() === "node_modules";
7598
7871
  }
7599
7872
  function containsHiddenOrDependencySegment(path) {
7600
- return resolve3(path).split(sep3).filter(Boolean).some(isHiddenOrDependency);
7873
+ return resolve4(path).split(sep3).filter(Boolean).some(isHiddenOrDependency);
7601
7874
  }
7602
7875
  function isWithinRoot2(rootPath, targetPath) {
7603
7876
  const rel = relative2(rootPath, targetPath);
7604
- return rel === "" || !rel.startsWith(`..${sep3}`) && rel !== ".." && !isAbsolute7(rel);
7877
+ return rel === "" || !rel.startsWith(`..${sep3}`) && rel !== ".." && !isAbsolute9(rel);
7605
7878
  }
7606
7879
  function toProtocolPath(path) {
7607
7880
  return path.split(sep3).join("/");
@@ -7633,7 +7906,7 @@ async function collectHtmlEntries(rootPath) {
7633
7906
  throw new Error("\u6587\u4EF6\u5939\u5185\u5BB9\u8FC7\u591A\uFF0C\u65E0\u6CD5\u521B\u5EFA\u9884\u89C8");
7634
7907
  }
7635
7908
  if (isHiddenOrDependency(entry.name)) continue;
7636
- const absolutePath = resolve3(directory, entry.name);
7909
+ const absolutePath = resolve4(directory, entry.name);
7637
7910
  const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;
7638
7911
  let entryIsDirectory = entry.isDirectory();
7639
7912
  let entryIsFile = entry.isFile();
@@ -7668,7 +7941,7 @@ async function collectHtmlEntries(rootPath) {
7668
7941
  }
7669
7942
  async function inspectStaticPreviewPath(path) {
7670
7943
  const selectionPath = path.trim();
7671
- if (!selectionPath || !isAbsolute7(selectionPath) || selectionPath.includes("\0")) {
7944
+ if (!selectionPath || !isAbsolute9(selectionPath) || selectionPath.includes("\0")) {
7672
7945
  throw new Error("\u8BF7\u9009\u62E9\u7EDD\u5BF9\u8DEF\u5F84\u4E0B\u7684\u7F51\u9875\u6587\u4EF6\u6216\u6587\u4EF6\u5939");
7673
7946
  }
7674
7947
  if (containsHiddenOrDependencySegment(selectionPath)) {
@@ -7683,7 +7956,7 @@ async function inspectStaticPreviewPath(path) {
7683
7956
  if (isHiddenOrDependency(basename2(selectionPath))) {
7684
7957
  throw new Error("\u4E0D\u80FD\u516C\u5F00\u9690\u85CF\u6587\u4EF6\u6216 node_modules \u4E2D\u7684\u7F51\u9875");
7685
7958
  }
7686
- const rootPath2 = await realpath2(dirname(selectionPath));
7959
+ const rootPath2 = await realpath2(dirname2(selectionPath));
7687
7960
  const filePath = await realpath2(selectionPath);
7688
7961
  if (containsHiddenOrDependencySegment(rootPath2) || containsHiddenOrDependencySegment(filePath)) {
7689
7962
  throw new Error("\u4E0D\u80FD\u516C\u5F00\u9690\u85CF\u76EE\u5F55\u3001\u9690\u85CF\u6587\u4EF6\u6216 node_modules \u4E2D\u7684\u7F51\u9875");
@@ -7721,7 +7994,7 @@ async function resolveStaticPreviewSource(path, requestedEntryPath) {
7721
7994
 
7722
7995
  // src/serve/preview/preview-gateway.ts
7723
7996
  function listenLoopback(server) {
7724
- return new Promise((resolve5, reject) => {
7997
+ return new Promise((resolve6, reject) => {
7725
7998
  const onError = (error) => {
7726
7999
  server.off("listening", onListening);
7727
8000
  reject(error);
@@ -7733,7 +8006,7 @@ function listenLoopback(server) {
7733
8006
  reject(new Error("\u65E0\u6CD5\u786E\u5B9A\u7F51\u9875\u9884\u89C8 Gateway \u7AEF\u53E3"));
7734
8007
  return;
7735
8008
  }
7736
- resolve5(address.port);
8009
+ resolve6(address.port);
7737
8010
  };
7738
8011
  server.once("error", onError);
7739
8012
  server.once("listening", onListening);
@@ -7813,10 +8086,10 @@ async function startPreviewGateway(options) {
7813
8086
  close() {
7814
8087
  deactivate();
7815
8088
  if (!closePromise) {
7816
- closePromise = new Promise((resolve5, reject) => {
8089
+ closePromise = new Promise((resolve6, reject) => {
7817
8090
  server.close((error) => {
7818
8091
  if (error) reject(error);
7819
- else resolve5();
8092
+ else resolve6();
7820
8093
  });
7821
8094
  }).catch((error) => {
7822
8095
  closePromise = null;
@@ -8002,7 +8275,7 @@ var PreviewStore = class {
8002
8275
  // src/serve/preview/stale-preview-runtime.ts
8003
8276
  import { execFile as execFile3 } from "child_process";
8004
8277
  import { readFile as readFile2, readdir as readdir4, realpath as realpath3, rm } from "fs/promises";
8005
- 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";
8006
8279
  import { promisify as promisify3 } from "util";
8007
8280
  import { setTimeout as sleep2 } from "timers/promises";
8008
8281
  var execFileAsync3 = promisify3(execFile3);
@@ -8018,7 +8291,7 @@ function validProcessStartedAt(value) {
8018
8291
  return typeof value === "string" && value.length >= 1 && value.length <= 128;
8019
8292
  }
8020
8293
  function validExecutablePath(value) {
8021
- return typeof value === "string" && value.length <= 4096 && isAbsolute8(value);
8294
+ return typeof value === "string" && value.length <= 4096 && isAbsolute10(value);
8022
8295
  }
8023
8296
  function isCpolarExecutable(path) {
8024
8297
  return /^cpolar(?:\.exe)?$/i.test(basename3(path));
@@ -8046,7 +8319,7 @@ async function darwinExecutablePath(pid) {
8046
8319
  { timeout: 2e3, maxBuffer: 64 * 1024, windowsHide: true }
8047
8320
  );
8048
8321
  const path = result.stdout.split(/\r?\n/).find((line) => line.startsWith("n/"))?.slice(1);
8049
- return path && isAbsolute8(path) ? path : null;
8322
+ return path && isAbsolute10(path) ? path : null;
8050
8323
  } catch {
8051
8324
  return null;
8052
8325
  }
@@ -8095,7 +8368,7 @@ async function captureCpolarRuntimeProcessIdentity(pid) {
8095
8368
  }
8096
8369
  async function readRuntimeIdentity(runtimeDir) {
8097
8370
  try {
8098
- 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"));
8099
8372
  if (marker && Number.isSafeInteger(marker.pid) && marker.pid > 1) {
8100
8373
  if (marker.version === 1 && marker.provider === "cloudflare") {
8101
8374
  return { pid: marker.pid, provider: "cloudflare" };
@@ -8112,7 +8385,7 @@ async function readRuntimeIdentity(runtimeDir) {
8112
8385
  } catch {
8113
8386
  }
8114
8387
  try {
8115
- const pid = parsePid(await readFile2(join6(runtimeDir, "cloudflared.pid"), "utf8"));
8388
+ const pid = parsePid(await readFile2(join7(runtimeDir, "cloudflared.pid"), "utf8"));
8116
8389
  return pid === null ? null : { pid, provider: "cloudflare" };
8117
8390
  } catch {
8118
8391
  return null;
@@ -8137,8 +8410,8 @@ async function matchesRuntimeIdentity(command, runtimeDir, identity) {
8137
8410
  const observed = await captureCpolarRuntimeProcessIdentity(identity.pid);
8138
8411
  return observed !== null && observed.processStartedAt === identity.processStartedAt && sameExecutablePath(observed.executablePath, identity.executablePath);
8139
8412
  }
8140
- const configPath = join6(runtimeDir, "cloudflared.yml");
8141
- const pidFilePath = join6(runtimeDir, "cloudflared.pid");
8413
+ const configPath = join7(runtimeDir, "cloudflared.yml");
8414
+ const pidFilePath = join7(runtimeDir, "cloudflared.pid");
8142
8415
  return /(?:^|[/\\\s])cloudflared(?:\.exe)?(?:\s|$)/i.test(command) && command.includes(configPath) && command.includes(pidFilePath);
8143
8416
  }
8144
8417
  function isAlive(pid) {
@@ -8189,7 +8462,7 @@ async function cleanupStalePreviewRuntimes(runtimeRoot) {
8189
8462
  await Promise.all(
8190
8463
  entries.map(async (entry) => {
8191
8464
  if (!entry.isDirectory() || entry.isSymbolicLink()) return;
8192
- const runtimeDir = join6(runtimeRoot, entry.name);
8465
+ const runtimeDir = join7(runtimeRoot, entry.name);
8193
8466
  const identity = await readRuntimeIdentity(runtimeDir);
8194
8467
  if (identity === null || !isAlive(identity.pid)) {
8195
8468
  await rm(runtimeDir, { recursive: true, force: true });
@@ -8590,7 +8863,7 @@ var PreviewManager = class {
8590
8863
  await gateway.close();
8591
8864
  return;
8592
8865
  }
8593
- const runtimeDir = join7(
8866
+ const runtimeDir = join8(
8594
8867
  this.options.runtimeRoot,
8595
8868
  `${record.summary.previewId}-${this.epoch}-${runtime.generation}`
8596
8869
  );
@@ -8628,7 +8901,7 @@ var PreviewManager = class {
8628
8901
  throw new Error("Unable to verify the cpolar process identity");
8629
8902
  }
8630
8903
  await writeFile(
8631
- join7(runtimeDir, "runtime.json"),
8904
+ join8(runtimeDir, "runtime.json"),
8632
8905
  serializePreviewRuntimeMarker(
8633
8906
  tunnel.child.pid,
8634
8907
  runtime.provider === "cpolar" ? { provider: "cpolar", ...processIdentity } : { provider: "cloudflare" }
@@ -8682,8 +8955,8 @@ var PreviewManager = class {
8682
8955
  }
8683
8956
  }
8684
8957
  async prepareCloudflareRuntime(runtimeDir) {
8685
- const configPath = join7(runtimeDir, "cloudflared.yml");
8686
- const pidFilePath = join7(runtimeDir, "cloudflared.pid");
8958
+ const configPath = join8(runtimeDir, "cloudflared.yml");
8959
+ const pidFilePath = join8(runtimeDir, "cloudflared.pid");
8687
8960
  await writeFile(configPath, "{}\n", { mode: 384 });
8688
8961
  return { configPath, pidFilePath };
8689
8962
  }
@@ -10835,11 +11108,11 @@ var PermissionBroker = class {
10835
11108
  if (this.pending.has(request.requestId)) {
10836
11109
  return Promise.resolve(DUPLICATE_DECISION);
10837
11110
  }
10838
- return new Promise((resolve5) => {
11111
+ return new Promise((resolve6) => {
10839
11112
  this.pending.set(request.requestId, {
10840
11113
  ...request,
10841
11114
  source: "hook",
10842
- resolve: resolve5,
11115
+ resolve: resolve6,
10843
11116
  createdAt: Date.now()
10844
11117
  });
10845
11118
  });
@@ -11191,53 +11464,33 @@ function createEventBridge(deps) {
11191
11464
 
11192
11465
  // src/serve/service-files.ts
11193
11466
  import { execSync } from "child_process";
11194
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
11467
+ import { existsSync as existsSync7 } from "fs";
11195
11468
  import { hostname } from "os";
11196
- import { connect as connect4 } from "net";
11197
- function tryConnectSocket(sockPath) {
11198
- return new Promise((resolve5) => {
11199
- const s = connect4(sockPath);
11200
- s.on("connect", () => resolve5(s));
11201
- s.on("error", () => resolve5(null));
11202
- });
11203
- }
11204
11469
  function isProcessAlive(pid) {
11205
11470
  return processExistsOrIsInaccessible(pid);
11206
11471
  }
11207
- async function cleanupStaleResources() {
11208
- if (existsSync7(SOCK_PATH)) {
11209
- const existing = await tryConnectSocket(SOCK_PATH);
11210
- if (existing) {
11211
- existing.destroy();
11212
- const msg = `Another service is already running on ${SOCK_PATH}`;
11213
- serviceLogger.error(msg);
11214
- console.error(msg);
11215
- await flushLogger(serviceLogger);
11216
- process.exit(1);
11217
- }
11218
- unlinkIfPresent(SOCK_PATH);
11219
- serviceLogger.info("Removed stale socket file");
11220
- }
11221
- if (existsSync7(PID_PATH)) {
11222
- const pidStr = readFileSync7(PID_PATH, "utf-8").trim();
11223
- const pid = parseInt(pidStr, 10);
11224
- const probe = !isNaN(pid) ? probeProcess(pid) : null;
11225
- if (probe?.status === "alive") {
11226
- const msg = `Another service is already running with PID ${pid}`;
11227
- serviceLogger.error(msg);
11228
- console.error(msg);
11229
- await flushLogger(serviceLogger);
11230
- process.exit(1);
11231
- }
11232
- if (probe?.status === "permission-denied" || probe?.status === "unknown") {
11233
- 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})`;
11234
- serviceLogger.error(msg);
11235
- console.error(msg);
11236
- await flushLogger(serviceLogger);
11237
- 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
+ }
11238
11486
  }
11487
+ removeLocalIpcEndpoint(SOCK_PATH);
11488
+ removeLocalIpcEndpoint(SERVICE_CONTROL_PATH);
11239
11489
  unlinkIfPresent(PID_PATH);
11240
- serviceLogger.info("Removed stale PID file");
11490
+ process.once("exit", release);
11491
+ } catch (error) {
11492
+ release();
11493
+ throw error;
11241
11494
  }
11242
11495
  }
11243
11496
  function formatProxyNameForProfile(baseName, profileName = PROFILE_NAME) {
@@ -11249,6 +11502,7 @@ function getProxyName() {
11249
11502
  return formatProxyNameForProfile(getComputerName() || hostname());
11250
11503
  }
11251
11504
  function getComputerName() {
11505
+ if (process.platform !== "darwin") return null;
11252
11506
  try {
11253
11507
  return execSync("scutil --get ComputerName", { stdio: ["pipe", "pipe", "ignore"] }).toString().trim() || null;
11254
11508
  } catch {
@@ -11257,10 +11511,9 @@ function getComputerName() {
11257
11511
  }
11258
11512
 
11259
11513
  // src/serve/terminal-ipc.ts
11260
- function handleTerminalConnection(socket, deps) {
11514
+ function handleTerminalConnection(socket, deps, admission) {
11261
11515
  const {
11262
11516
  sessionManager,
11263
- workerRegistry,
11264
11517
  terminalSockets,
11265
11518
  terminalSubscriptionBacklog,
11266
11519
  relayConnection,
@@ -11268,8 +11521,7 @@ function handleTerminalConnection(socket, deps) {
11268
11521
  createHookContext,
11269
11522
  emitAgentStatus,
11270
11523
  updateTerminalCwd,
11271
- resolveInterruptedApprovals: resolveInterruptedApprovals2,
11272
- config
11524
+ resolveInterruptedApprovals: resolveInterruptedApprovals2
11273
11525
  } = deps;
11274
11526
  const bridgeDeps = {
11275
11527
  changeSessionState: (sessionId, next) => changeSessionState(sessionManager, relayConnection, sessionId, next),
@@ -11282,6 +11534,7 @@ function handleTerminalConnection(socket, deps) {
11282
11534
  let protocolRejected = false;
11283
11535
  let acceptedRegistration = null;
11284
11536
  let registeredSessionId = null;
11537
+ let admissionIntentChecked = false;
11285
11538
  const ownsRegisteredSession = (sessionId) => registeredSessionId === sessionId && terminalSockets.get(sessionId) === socket;
11286
11539
  const discardClaimMutation = (claim) => {
11287
11540
  if (claim === null || claim.source === "active") return;
@@ -11304,10 +11557,39 @@ function handleTerminalConnection(socket, deps) {
11304
11557
  })
11305
11558
  );
11306
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
+ };
11307
11582
  createIpcReader(
11308
11583
  socket,
11309
11584
  (msg) => {
11310
11585
  if (protocolRejected) return;
11586
+ if (!admissionIntentChecked) {
11587
+ admissionIntentChecked = true;
11588
+ if (!matchesAdmissionIntent(msg)) {
11589
+ rejectAdmissionIntent(msg);
11590
+ return;
11591
+ }
11592
+ }
11311
11593
  switch (msg.type) {
11312
11594
  case "session_create_request": {
11313
11595
  if (createHandshakeReceived) {
@@ -11366,28 +11648,6 @@ function handleTerminalConnection(socket, deps) {
11366
11648
  }
11367
11649
  break;
11368
11650
  }
11369
- case "service_status_request": {
11370
- const relayStatus = relayConnection.getStatus();
11371
- const sessions = sessionManager.listSessions();
11372
- socket.end(
11373
- serializeIpc({
11374
- type: "service_status_response",
11375
- protocolVersion: TERMINAL_IPC_PROTOCOL_VERSION,
11376
- config,
11377
- relay: relayStatus,
11378
- sessions: sessions.map((s) => ({
11379
- id: s.id,
11380
- mode: s.mode,
11381
- provider: s.provider,
11382
- state: s.state,
11383
- createdAt: new Date(s.createdAt).toISOString(),
11384
- ...s.name !== void 0 ? { name: s.name } : {},
11385
- hasWorker: workerRegistry.has(s.id)
11386
- }))
11387
- })
11388
- );
11389
- break;
11390
- }
11391
11651
  case "pty_title_change": {
11392
11652
  if (!ownsRegisteredSession(msg.sessionId) || !sessionManager.getSession(msg.sessionId)) {
11393
11653
  break;
@@ -11600,10 +11860,402 @@ function handleTerminalConnection(socket, deps) {
11600
11860
  });
11601
11861
  }
11602
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
+
11603
12255
  // src/serve/hook-registry.ts
11604
12256
  import { createHash as createHash3, randomBytes } from "crypto";
11605
- import { existsSync as existsSync8, mkdirSync, readFileSync as readFileSync8, renameSync, writeFileSync } from "fs";
11606
- 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";
11607
12259
  import { z as z2 } from "zod";
11608
12260
  var PersistedHookSessionBindingSchema = z2.object({
11609
12261
  sessionId: z2.string(),
@@ -11666,7 +12318,7 @@ var HookRegistry = class {
11666
12318
  if (!this.persistPath || !existsSync8(this.persistPath)) return;
11667
12319
  try {
11668
12320
  const parsed = PersistedHookRegistrySchema.parse(
11669
- JSON.parse(readFileSync8(this.persistPath, "utf8"))
12321
+ JSON.parse(readFileSync7(this.persistPath, "utf8"))
11670
12322
  );
11671
12323
  this.bindingsBySession.clear();
11672
12324
  for (const binding of parsed.bindings) {
@@ -11682,7 +12334,7 @@ var HookRegistry = class {
11682
12334
  save() {
11683
12335
  if (!this.persistPath) return;
11684
12336
  try {
11685
- mkdirSync(dirname2(this.persistPath), { recursive: true });
12337
+ mkdirSync2(dirname3(this.persistPath), { recursive: true });
11686
12338
  const tmpPath = `${this.persistPath}.${process.pid}.${Date.now()}.tmp`;
11687
12339
  writeFileSync(
11688
12340
  tmpPath,
@@ -11731,7 +12383,7 @@ var HookServer = class {
11731
12383
  this.writeJson(res, 500, { error: "internal_error" });
11732
12384
  });
11733
12385
  });
11734
- return new Promise((resolve5, reject) => {
12386
+ return new Promise((resolve6, reject) => {
11735
12387
  const onError = (err) => {
11736
12388
  this.server?.off("listening", onListening);
11737
12389
  reject(err);
@@ -11739,7 +12391,7 @@ var HookServer = class {
11739
12391
  const onListening = () => {
11740
12392
  this.server?.off("error", onError);
11741
12393
  serviceLogger.info({ host: this.host, port: this.options.port }, "Hook server listening");
11742
- resolve5();
12394
+ resolve6();
11743
12395
  };
11744
12396
  this.server.once("error", onError);
11745
12397
  this.server.once("listening", onListening);
@@ -11750,8 +12402,8 @@ var HookServer = class {
11750
12402
  if (!this.server) return Promise.resolve();
11751
12403
  const server = this.server;
11752
12404
  this.server = null;
11753
- return new Promise((resolve5, reject) => {
11754
- server.close((err) => err ? reject(err) : resolve5());
12405
+ return new Promise((resolve6, reject) => {
12406
+ server.close((err) => err ? reject(err) : resolve6());
11755
12407
  });
11756
12408
  }
11757
12409
  getListeningPort() {
@@ -11847,7 +12499,7 @@ var HookServer = class {
11847
12499
  res.end();
11848
12500
  }
11849
12501
  readBody(req) {
11850
- return new Promise((resolve5, reject) => {
12502
+ return new Promise((resolve6, reject) => {
11851
12503
  let body = "";
11852
12504
  let size = 0;
11853
12505
  req.setEncoding("utf8");
@@ -11860,7 +12512,7 @@ var HookServer = class {
11860
12512
  }
11861
12513
  body += chunk;
11862
12514
  });
11863
- req.on("end", () => resolve5(body));
12515
+ req.on("end", () => resolve6(body));
11864
12516
  req.on("error", reject);
11865
12517
  });
11866
12518
  }
@@ -11947,20 +12599,24 @@ function createServeShutdown(deps) {
11947
12599
  deps.relayConnectionClose();
11948
12600
  deps.workerRegistryDestroyAll();
11949
12601
  deps.hostedPtyRegistryDestroyAll();
12602
+ deps.terminalAdmissionDestroyAll?.();
11950
12603
  deps.ipcServerClose();
11951
- unlinkIfPresent(deps.sockPath);
11952
- unlinkIfPresent(deps.pidPath);
12604
+ if (deps.runtimeStateCleanup) deps.runtimeStateCleanup();
12605
+ else {
12606
+ removeLocalIpcEndpoint(deps.sockPath);
12607
+ unlinkIfPresent(deps.pidPath);
12608
+ }
11953
12609
  await flushLogger(deps.logger);
11954
12610
  exit(0);
11955
12611
  };
11956
12612
  }
11957
12613
 
11958
12614
  // src/serve/remote-file-upload.ts
11959
- import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
12615
+ import { createWriteStream, mkdirSync as mkdirSync3 } from "fs";
11960
12616
  import { tmpdir as tmpdir2 } from "os";
11961
- import { extname as extname2, join as join8 } from "path";
12617
+ import { extname as extname2, join as join9 } from "path";
11962
12618
  import { nanoid as nanoid6 } from "nanoid";
11963
- var DEFAULT_DATA_DIR = join8(tmpdir2(), "dev-anywhere");
12619
+ var DEFAULT_DATA_DIR = join9(tmpdir2(), "dev-anywhere");
11964
12620
  var SAFE_EXT_RE = /^[A-Za-z0-9]{1,6}$/;
11965
12621
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Map([
11966
12622
  ["image/png", "png"],
@@ -11976,9 +12632,9 @@ function uploadPathFor(msg, dataDir, suffix) {
11976
12632
  if (msg.kind === "clipboard_image") {
11977
12633
  const extension = IMAGE_EXTENSIONS.get(msg.mimeType);
11978
12634
  if (!extension) throw new Error("\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F");
11979
- return join8(dataDir, `paste-${suffix}.${extension}`);
12635
+ return join9(dataDir, `paste-${suffix}.${extension}`);
11980
12636
  }
11981
- return join8(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
12637
+ return join9(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
11982
12638
  }
11983
12639
  var RemoteFileUploadManager = class {
11984
12640
  constructor(deps) {
@@ -12011,7 +12667,7 @@ var RemoteFileUploadManager = class {
12011
12667
  }
12012
12668
  try {
12013
12669
  const dataDir = this.deps.dataDir ?? DEFAULT_DATA_DIR;
12014
- mkdirSync2(dataDir, { recursive: true });
12670
+ mkdirSync3(dataDir, { recursive: true });
12015
12671
  const path = uploadPathFor(msg, dataDir, this.deps.randomSuffix?.() ?? nanoid6(6));
12016
12672
  const stream = createWriteStream(path, { mode: 384 });
12017
12673
  const active = {
@@ -12122,9 +12778,9 @@ import { createReadStream as createReadStream2, statSync as statSync3 } from "fs
12122
12778
  import { basename as basename4 } from "path";
12123
12779
 
12124
12780
  // src/serve/remote-file-path.ts
12125
- import { realpathSync } from "fs";
12781
+ import { realpathSync as realpathSync2 } from "fs";
12126
12782
  import { homedir as homedir7 } from "os";
12127
- 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";
12128
12784
  var EXT_MIME_MAP = {
12129
12785
  ".png": "image/png",
12130
12786
  ".jpg": "image/jpeg",
@@ -12158,9 +12814,9 @@ function guessMimeType(filePath) {
12158
12814
  return EXT_MIME_MAP[ext] ?? "application/octet-stream";
12159
12815
  }
12160
12816
  function resolveRemoteFilePath(rawPath, cwd) {
12161
- const expandedPath = rawPath === "~" || rawPath.startsWith("~/") ? resolve4(homedir7(), rawPath.slice(2)) : rawPath;
12162
- const candidate = isAbsolute9(expandedPath) ? resolve4(expandedPath) : resolve4(cwd, expandedPath);
12163
- 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);
12164
12820
  }
12165
12821
 
12166
12822
  // src/serve/remote-file-stream.ts
@@ -12446,8 +13102,6 @@ function createRelayAutoUpdater(options) {
12446
13102
  runnerTargetVersion,
12447
13103
  "--running-version",
12448
13104
  options.runningVersion,
12449
- "--daemon-pid",
12450
- String(options.daemonPid),
12451
13105
  "--relay",
12452
13106
  options.relayName
12453
13107
  ];
@@ -12526,6 +13180,8 @@ function createRelayAutoUpdater(options) {
12526
13180
  var DEFAULT_BOOTSTRAP_TIMEOUT_MS = 5e3;
12527
13181
  var DEFAULT_RETRY_INITIAL_MS = 5e3;
12528
13182
  var DEFAULT_RETRY_MAX_MS = 5 * 6e4;
13183
+ var InvalidRelayUpgradeBootstrapResponseError = class extends Error {
13184
+ };
12529
13185
  function relayUpgradeBootstrapUrl(relayUrl) {
12530
13186
  const url = new URL(relayUrl);
12531
13187
  if (url.protocol === "ws:") url.protocol = "http:";
@@ -12547,16 +13203,31 @@ async function fetchRelayUpgradeBootstrap(options) {
12547
13203
  });
12548
13204
  if (response.status === 404) return null;
12549
13205
  if (!response.ok) throw new Error(`Relay upgrade bootstrap returned HTTP ${response.status}`);
12550
- const parsed = ProxyUpgradeBootstrapResponseSchema.safeParse(await response.json());
12551
- if (!parsed.success) throw new Error("Relay upgrade bootstrap returned an invalid response");
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
+ }
12552
13220
  return parsed.data;
12553
13221
  }
12554
13222
  function createRelayUpgradeBootstrapMonitor(options) {
13223
+ const localControlProtocolVersion = typeof options.controlProtocolVersion === "number" && Number.isSafeInteger(options.controlProtocolVersion) && options.controlProtocolVersion > 0 ? options.controlProtocolVersion : RELAY_CONTROL_PROTOCOL_VERSION;
12555
13224
  let disposed = false;
12556
13225
  let active = false;
12557
13226
  let inFlight = null;
12558
13227
  let retryTimer = null;
12559
13228
  let retryAttempt = 0;
13229
+ let generation = 0;
13230
+ let lastPublishedKey = null;
12560
13231
  const clearRetry = () => {
12561
13232
  if (!retryTimer) return;
12562
13233
  clearTimeout(retryTimer);
@@ -12565,10 +13236,17 @@ function createRelayUpgradeBootstrapMonitor(options) {
12565
13236
  const suspend = () => {
12566
13237
  active = false;
12567
13238
  retryAttempt = 0;
13239
+ generation += 1;
12568
13240
  clearRetry();
12569
13241
  inFlight?.abort();
12570
13242
  inFlight = null;
12571
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
+ };
12572
13250
  const scheduleRetry = () => {
12573
13251
  if (disposed || !active || inFlight || retryTimer) return;
12574
13252
  const initial = options.retryInitialMs ?? DEFAULT_RETRY_INITIAL_MS;
@@ -12584,6 +13262,7 @@ function createRelayUpgradeBootstrapMonitor(options) {
12584
13262
  const probe = () => {
12585
13263
  if (disposed || !active || inFlight) return;
12586
13264
  const controller = new AbortController();
13265
+ const probeGeneration = generation;
12587
13266
  const timeout = setTimeout(
12588
13267
  () => controller.abort(),
12589
13268
  options.timeoutMs ?? DEFAULT_BOOTSTRAP_TIMEOUT_MS
@@ -12596,29 +13275,54 @@ function createRelayUpgradeBootstrapMonitor(options) {
12596
13275
  signal: controller.signal,
12597
13276
  fetchImpl: options.fetchImpl
12598
13277
  }).then((bootstrap) => {
12599
- if (disposed || !active || !bootstrap) return;
12600
- active = false;
12601
- retryAttempt = 0;
12602
- clearRetry();
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
+ );
12603
13285
  options.logger.info(
12604
13286
  {
12605
13287
  relayVersion: bootstrap.relayVersion,
12606
- controlProtocolVersion: bootstrap.controlProtocolVersion
13288
+ controlProtocolVersion: bootstrap.controlProtocolVersion,
13289
+ direction
12607
13290
  },
12608
13291
  "Received Relay upgrade bootstrap"
12609
13292
  );
12610
- options.onVersion(bootstrap.relayVersion);
12611
- if (bootstrap.controlProtocolVersion !== RELAY_CONTROL_PROTOCOL_VERSION) {
13293
+ publish({
13294
+ direction,
13295
+ relayVersion: bootstrap.relayVersion,
13296
+ relayControlProtocolVersion: bootstrap.controlProtocolVersion
13297
+ });
13298
+ if (direction === ProxyProtocolAdmissionDirection.RELAY_OUTDATED) {
12612
13299
  options.logger.warn(
12613
13300
  {
12614
- localControlProtocolVersion: RELAY_CONTROL_PROTOCOL_VERSION,
13301
+ localControlProtocolVersion,
12615
13302
  relayControlProtocolVersion: bootstrap.controlProtocolVersion
12616
13303
  },
12617
- "Relay control protocol differs; waiting for Proxy update"
13304
+ "Relay control protocol is older; waiting for Relay update"
12618
13305
  );
13306
+ return;
12619
13307
  }
13308
+ active = false;
13309
+ retryAttempt = 0;
13310
+ clearRetry();
12620
13311
  }).catch((error) => {
12621
- if (disposed || !active || controller.signal.aborted) return;
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
+ }
12622
13326
  options.logger.debug(
12623
13327
  { error: error instanceof Error ? error.message : String(error) },
12624
13328
  "Relay upgrade bootstrap unavailable"
@@ -12626,7 +13330,7 @@ function createRelayUpgradeBootstrapMonitor(options) {
12626
13330
  }).finally(() => {
12627
13331
  clearTimeout(timeout);
12628
13332
  if (inFlight === controller) inFlight = null;
12629
- scheduleRetry();
13333
+ if (probeGeneration === generation) scheduleRetry();
12630
13334
  });
12631
13335
  };
12632
13336
  return {
@@ -12653,7 +13357,7 @@ import sharp from "sharp";
12653
13357
 
12654
13358
  // src/serve/device-preview/android-adapter.ts
12655
13359
  import { execFile as nodeExecFile } from "child_process";
12656
- import { delimiter, join as join9 } from "path";
13360
+ import { posix, win32 } from "path";
12657
13361
  var ADB_TIMEOUT_MS = 5e3;
12658
13362
  var ADB_OUTPUT_LIMIT_BYTES = 1024 * 1024;
12659
13363
  var AndroidEmulatorAdapterError = class extends Error {
@@ -12665,7 +13369,7 @@ var AndroidEmulatorAdapterError = class extends Error {
12665
13369
  code;
12666
13370
  };
12667
13371
  function defaultExecFile(command, args, options) {
12668
- return new Promise((resolve5, reject) => {
13372
+ return new Promise((resolve6, reject) => {
12669
13373
  nodeExecFile(
12670
13374
  command,
12671
13375
  [...args],
@@ -12675,7 +13379,7 @@ function defaultExecFile(command, args, options) {
12675
13379
  reject(error);
12676
13380
  return;
12677
13381
  }
12678
- resolve5({ stdout, stderr });
13382
+ resolve6({ stdout, stderr });
12679
13383
  }
12680
13384
  );
12681
13385
  });
@@ -12699,25 +13403,34 @@ function validEmulatorSerial(serial) {
12699
13403
  const port = Number(match[1]);
12700
13404
  return Number.isSafeInteger(port) && port <= 65535;
12701
13405
  }
12702
- function adbCandidates(command, env) {
13406
+ function adbCandidates(command, env, platform) {
12703
13407
  const explicit = command?.trim();
12704
13408
  if (explicit) {
12705
13409
  if (!validCommand(explicit)) return [];
12706
13410
  return [explicit];
12707
13411
  }
12708
- 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);
12709
13415
  const candidates = [];
12710
- const sdkRoots = [env.ANDROID_SDK_ROOT, env.ANDROID_HOME];
12711
- 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) {
12712
13422
  sdkRoots.push(
12713
- 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")
12714
13424
  );
12715
13425
  }
12716
13426
  for (const root of sdkRoots) {
12717
- if (root) candidates.push(join9(root, "platform-tools", executable));
13427
+ if (root) candidates.push(join11(root, "platform-tools", executable));
12718
13428
  }
12719
- for (const entry of (env.PATH ?? "").split(delimiter)) {
12720
- 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
+ );
12721
13434
  }
12722
13435
  candidates.push(executable);
12723
13436
  return [...new Set(candidates.filter(validCommand))];
@@ -12774,12 +13487,14 @@ function orientSize(naturalSize, rotation) {
12774
13487
  var AndroidEmulatorAdapter = class {
12775
13488
  env;
12776
13489
  requestedCommand;
13490
+ platform;
12777
13491
  execFile;
12778
13492
  allowedDevices = /* @__PURE__ */ new Map();
12779
13493
  inputQueues = /* @__PURE__ */ new Map();
12780
13494
  locatedCommand = null;
12781
13495
  constructor(options) {
12782
- this.env = { ...options.env ?? process.env };
13496
+ this.platform = options.platform ?? process.platform;
13497
+ this.env = normalizeProcessEnvironment({ ...options.env ?? process.env }, this.platform);
12783
13498
  this.requestedCommand = options.command;
12784
13499
  this.execFile = options.execFile ?? defaultExecFile;
12785
13500
  }
@@ -12787,7 +13502,7 @@ var AndroidEmulatorAdapter = class {
12787
13502
  if (this.locatedCommand) {
12788
13503
  return { available: true, command: this.locatedCommand };
12789
13504
  }
12790
- for (const candidate of adbCandidates(this.requestedCommand, this.env)) {
13505
+ for (const candidate of adbCandidates(this.requestedCommand, this.env, this.platform)) {
12791
13506
  try {
12792
13507
  const result = await this.execFile(candidate, ["version"], {
12793
13508
  env: this.env,
@@ -14150,7 +14865,7 @@ function defaultSpawnRunner(command, args, options) {
14150
14865
  return nodeSpawn2(command, [...args], options);
14151
14866
  }
14152
14867
  async function defaultReserveLoopbackPort() {
14153
- return new Promise((resolve5, reject) => {
14868
+ return new Promise((resolve6, reject) => {
14154
14869
  const server = createServer3();
14155
14870
  server.unref();
14156
14871
  server.once("error", reject);
@@ -14163,7 +14878,7 @@ async function defaultReserveLoopbackPort() {
14163
14878
  }
14164
14879
  server.close((error) => {
14165
14880
  if (error) reject(error);
14166
- else resolve5(address.port);
14881
+ else resolve6(address.port);
14167
14882
  });
14168
14883
  });
14169
14884
  });
@@ -14202,19 +14917,19 @@ function terminateChild(child) {
14202
14917
  }
14203
14918
  function delay2(ms, signal) {
14204
14919
  throwIfAborted4(signal);
14205
- return new Promise((resolve5, reject) => {
14920
+ return new Promise((resolve6, reject) => {
14206
14921
  const onAbort = () => {
14207
14922
  clearTimeout(timer);
14208
14923
  reject(abortError2());
14209
14924
  };
14210
14925
  const timer = setTimeout(() => {
14211
14926
  signal?.removeEventListener("abort", onAbort);
14212
- resolve5();
14927
+ resolve6();
14213
14928
  }, ms);
14214
14929
  signal?.addEventListener("abort", onAbort, { once: true });
14215
14930
  });
14216
14931
  }
14217
- function isRecord3(value) {
14932
+ function isRecord4(value) {
14218
14933
  return typeof value === "object" && value !== null && !Array.isArray(value);
14219
14934
  }
14220
14935
  function normalizeUdid(value) {
@@ -14283,7 +14998,7 @@ function normalizeState(rawState) {
14283
14998
  return "transitioning";
14284
14999
  }
14285
15000
  function processCode(error) {
14286
- if (!isRecord3(error) || typeof error.code !== "string") return void 0;
15001
+ if (!isRecord4(error) || typeof error.code !== "string") return void 0;
14287
15002
  return /^[A-Z][A-Z0-9_]{1,31}$/.test(error.code) ? error.code : void 0;
14288
15003
  }
14289
15004
  function inputFailure(message) {
@@ -14354,14 +15069,14 @@ function parseBaguetteChromeLayout(output) {
14354
15069
  "Baguette chrome layout returned invalid JSON"
14355
15070
  );
14356
15071
  }
14357
- if (!isRecord3(parsed)) {
15072
+ if (!isRecord4(parsed)) {
14358
15073
  throw new IosSimulatorAdapterError(
14359
15074
  "INVALID_TARGET_METADATA",
14360
15075
  "Baguette chrome layout is not an object"
14361
15076
  );
14362
15077
  }
14363
15078
  const screen = parsed.screen;
14364
- if (!isRecord3(screen)) {
15079
+ if (!isRecord4(screen)) {
14365
15080
  throw new IosSimulatorAdapterError(
14366
15081
  "INVALID_TARGET_METADATA",
14367
15082
  "Baguette chrome layout is missing screen geometry"
@@ -14385,7 +15100,7 @@ function parseSimctlDevices(output) {
14385
15100
  } catch {
14386
15101
  throw new IosSimulatorAdapterError("SIMCTL_INVALID_RESPONSE", "simctl returned invalid JSON");
14387
15102
  }
14388
- if (!isRecord3(parsed) || !isRecord3(parsed.devices)) {
15103
+ if (!isRecord4(parsed) || !isRecord4(parsed.devices)) {
14389
15104
  throw new IosSimulatorAdapterError(
14390
15105
  "SIMCTL_INVALID_RESPONSE",
14391
15106
  "simctl response is missing devices"
@@ -14402,7 +15117,7 @@ function parseSimctlDevices(output) {
14402
15117
  "simctl returned too many devices"
14403
15118
  );
14404
15119
  }
14405
- if (!isRecord3(candidate)) continue;
15120
+ if (!isRecord4(candidate)) continue;
14406
15121
  const record = candidate;
14407
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) {
14408
15123
  continue;
@@ -14458,8 +15173,8 @@ var LatestFrameSampler = class {
14458
15173
  next() {
14459
15174
  if (this.error) return Promise.reject(this.error);
14460
15175
  if (this.ended) return Promise.resolve({ done: true, value: void 0 });
14461
- return new Promise((resolve5, reject) => {
14462
- this.waiters.push({ resolve: resolve5, reject });
15176
+ return new Promise((resolve6, reject) => {
15177
+ this.waiters.push({ resolve: resolve6, reject });
14463
15178
  this.flush();
14464
15179
  });
14465
15180
  }
@@ -14503,7 +15218,7 @@ function waitForWebSocketOpen(socket, timeoutMs, signal) {
14503
15218
  if (socket.readyState !== WebSocket2.CONNECTING) {
14504
15219
  return Promise.reject(streamFailure("Baguette stream socket closed before opening"));
14505
15220
  }
14506
- return new Promise((resolve5, reject) => {
15221
+ return new Promise((resolve6, reject) => {
14507
15222
  const cleanup = () => {
14508
15223
  clearTimeout(timer);
14509
15224
  socket.off("open", onOpen);
@@ -14514,7 +15229,7 @@ function waitForWebSocketOpen(socket, timeoutMs, signal) {
14514
15229
  const settle = (error) => {
14515
15230
  cleanup();
14516
15231
  if (error) reject(error);
14517
- else resolve5();
15232
+ else resolve6();
14518
15233
  };
14519
15234
  const onOpen = () => settle();
14520
15235
  const onError = () => settle(streamFailure("Could not connect to Baguette stream"));
@@ -14637,14 +15352,14 @@ var BaguetteInputSession = class {
14637
15352
  () => void 0
14638
15353
  );
14639
15354
  if (!signal) return wireResult;
14640
- return new Promise((resolve5, reject) => {
15355
+ return new Promise((resolve6, reject) => {
14641
15356
  let settled = false;
14642
15357
  const finish = (error) => {
14643
15358
  if (settled) return;
14644
15359
  settled = true;
14645
15360
  signal.removeEventListener("abort", onAbort);
14646
15361
  if (error) reject(error);
14647
- else resolve5();
15362
+ else resolve6();
14648
15363
  };
14649
15364
  const onAbort = () => {
14650
15365
  if (token.acknowledged) {
@@ -14705,7 +15420,7 @@ var BaguetteInputSession = class {
14705
15420
  new IosSimulatorAdapterError("INVALID_INPUT", "Baguette input exceeded the size limit")
14706
15421
  );
14707
15422
  }
14708
- return new Promise((resolve5, reject) => {
15423
+ return new Promise((resolve6, reject) => {
14709
15424
  const timer = setTimeout(() => {
14710
15425
  this.fail(
14711
15426
  new IosSimulatorAdapterError(
@@ -14714,7 +15429,7 @@ var BaguetteInputSession = class {
14714
15429
  )
14715
15430
  );
14716
15431
  }, this.inputAckTimeoutMs);
14717
- this.pendingAck = { token, resolve: resolve5, reject, timer };
15432
+ this.pendingAck = { token, resolve: resolve6, reject, timer };
14718
15433
  try {
14719
15434
  stdin.write(payload, (error) => {
14720
15435
  if (error) this.fail(inputFailure("Could not send input to Baguette"));
@@ -14748,7 +15463,7 @@ var BaguetteInputSession = class {
14748
15463
  );
14749
15464
  return;
14750
15465
  }
14751
- if (!isRecord3(parsed) || typeof parsed.ok !== "boolean") {
15466
+ if (!isRecord4(parsed) || typeof parsed.ok !== "boolean") {
14752
15467
  this.fail(
14753
15468
  new IosSimulatorAdapterError(
14754
15469
  "INPUT_PROTOCOL_ERROR",
@@ -14935,14 +15650,14 @@ var BaguetteServeSession = class {
14935
15650
  return Promise.reject(inputFailure("Baguette preview session is closed"));
14936
15651
  }
14937
15652
  const payload = JSON.stringify(envelope);
14938
- return new Promise((resolve5, reject) => {
15653
+ return new Promise((resolve6, reject) => {
14939
15654
  let settled = false;
14940
15655
  const finish = (error) => {
14941
15656
  if (settled) return;
14942
15657
  settled = true;
14943
15658
  signal?.removeEventListener("abort", onAbort);
14944
15659
  if (error) reject(error);
14945
- else resolve5();
15660
+ else resolve6();
14946
15661
  };
14947
15662
  const onAbort = () => finish(abortError2());
14948
15663
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -14973,7 +15688,7 @@ var BaguetteServeSession = class {
14973
15688
  if (this.closed || this.socket.readyState !== WebSocket2.OPEN) {
14974
15689
  return Promise.reject(inputFailure("Baguette preview session is closed"));
14975
15690
  }
14976
- return new Promise((resolve5, reject) => {
15691
+ return new Promise((resolve6, reject) => {
14977
15692
  const onAbort = () => {
14978
15693
  const pending = this.pendingPaste;
14979
15694
  if (!pending) return;
@@ -14993,7 +15708,7 @@ var BaguetteServeSession = class {
14993
15708
  clearTimeout(timer);
14994
15709
  signal?.removeEventListener("abort", onAbort);
14995
15710
  };
14996
- this.pendingPaste = { resolve: resolve5, reject, cleanup, sent: false, callerSettled: false };
15711
+ this.pendingPaste = { resolve: resolve6, reject, cleanup, sent: false, callerSettled: false };
14997
15712
  signal?.addEventListener("abort", onAbort, { once: true });
14998
15713
  if (signal?.aborted) {
14999
15714
  onAbort();
@@ -15027,7 +15742,7 @@ var BaguetteServeSession = class {
15027
15742
  } catch {
15028
15743
  return;
15029
15744
  }
15030
- if (!isRecord3(parsed) || parsed.type !== "paste_result") return;
15745
+ if (!isRecord4(parsed) || parsed.type !== "paste_result") return;
15031
15746
  if (!this.pendingPaste) return;
15032
15747
  if (typeof parsed.ok !== "boolean") {
15033
15748
  this.completePendingPaste(
@@ -16332,8 +17047,8 @@ var DevicePreviewStreamConnection = class {
16332
17047
  } catch (error) {
16333
17048
  return Promise.reject(error instanceof Error ? error : streamError("\u8BBE\u5907\u753B\u9762\u7F16\u7801\u5931\u8D25"));
16334
17049
  }
16335
- const pending = new Promise((resolve5, reject) => {
16336
- this.pendingFrames.set(streamId, { frame, resolve: resolve5, reject });
17050
+ const pending = new Promise((resolve6, reject) => {
17051
+ this.pendingFrames.set(streamId, { frame, resolve: resolve6, reject });
16337
17052
  });
16338
17053
  this.flushPending();
16339
17054
  return pending;
@@ -16359,8 +17074,8 @@ var DevicePreviewStreamConnection = class {
16359
17074
  } catch (error) {
16360
17075
  return Promise.reject(error instanceof Error ? error : streamError("\u8BBE\u5907\u753B\u9762\u7F16\u7801\u5931\u8D25"));
16361
17076
  }
16362
- const pending = new Promise((resolve5, reject) => {
16363
- this.pendingFrames.set(streamId, { frame, resolve: resolve5, reject });
17077
+ const pending = new Promise((resolve6, reject) => {
17078
+ this.pendingFrames.set(streamId, { frame, resolve: resolve6, reject });
16364
17079
  });
16365
17080
  this.flushPending();
16366
17081
  return pending;
@@ -16545,22 +17260,14 @@ function parseServiceOptions(argv) {
16545
17260
  options.relayName = relayName;
16546
17261
  continue;
16547
17262
  }
16548
- if (arg === "--preserve-stopped-marker") {
16549
- options.preserveStoppedMarker = true;
16550
- }
16551
17263
  }
16552
17264
  return options;
16553
17265
  }
16554
17266
  async function startService(options) {
16555
17267
  ensureProfileWorkspace();
16556
- await cleanupStaleResources();
17268
+ await claimServiceRuntime();
17269
+ const instanceId = randomUUID();
16557
17270
  await cleanupStalePreviewRuntimes(PREVIEW_RUN_DIR);
16558
- if (!options?.preserveStoppedMarker) {
16559
- try {
16560
- unlinkSync2(STOPPED_PATH);
16561
- } catch {
16562
- }
16563
- }
16564
17271
  const permissionBroker = new PermissionBroker();
16565
17272
  const agentStatusRegistry = new AgentStatusRegistry();
16566
17273
  let unregisterHookSession = () => {
@@ -16571,10 +17278,21 @@ async function startService(options) {
16571
17278
  terminal: TERMINAL_IPC_PROTOCOL_VERSION,
16572
17279
  worker: WORKER_IPC_PROTOCOL_VERSION
16573
17280
  };
16574
- const allowSessionRuntimeHandover = sessionRuntimeIpcVersionsMatch(
16575
- readSessionRuntimeIpcVersions(SESSION_RUNTIME_IPC_VERSION_PATH),
16576
- currentSessionRuntimeIpcVersions
17281
+ const previousSessionRuntimeIpcVersions = readSessionRuntimeIpcVersions(
17282
+ SESSION_RUNTIME_IPC_VERSION_PATH
16577
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
+ };
16578
17296
  const sessionManager = new SessionManager({
16579
17297
  persistPath: SESSIONS_PATH,
16580
17298
  historyMetadataPath: HISTORY_METADATA_PATH,
@@ -16649,7 +17367,6 @@ async function startService(options) {
16649
17367
  profileName: PROFILE_NAME,
16650
17368
  relayName: proxyConfig.relayName,
16651
17369
  runningVersion: PROXY_VERSION,
16652
- daemonPid: process.pid,
16653
17370
  logger: serviceLogger
16654
17371
  });
16655
17372
  let serviceReadyForAutoUpdate = false;
@@ -16662,11 +17379,17 @@ async function startService(options) {
16662
17379
  relayUrl,
16663
17380
  token: relayToken,
16664
17381
  logger: serviceLogger,
16665
- onVersion: considerRelayVersion
17382
+ onAdmission: (event) => {
17383
+ if (event.relayVersion) considerRelayVersion(event.relayVersion);
17384
+ relayConnection.applyProtocolAdmission(event.direction);
17385
+ }
16666
17386
  });
16667
17387
  relayConnection.on("relay_version", considerRelayVersion);
16668
17388
  relayConnection.on("connected", () => upgradeBootstrap.markControlProtocolConnected());
16669
17389
  relayConnection.on("disconnected", () => upgradeBootstrap.request());
17390
+ relayConnection.on("protocol_blocked", (event) => {
17391
+ if (event.source !== "http_bootstrap") upgradeBootstrap.request();
17392
+ });
16670
17393
  upgradeBootstrap.request();
16671
17394
  const relaySend = (data) => relayConnection.sendRaw(data);
16672
17395
  const previewManager = new PreviewManager({
@@ -16860,35 +17583,54 @@ async function startService(options) {
16860
17583
  }
16861
17584
  }
16862
17585
  await workerRegistry.reconnectAll();
16863
- const server = createServer4((socket) => {
16864
- handleTerminalConnection(socket, {
16865
- sessionManager,
16866
- workerRegistry,
16867
- terminalSockets,
16868
- terminalSubscriptionBacklog,
16869
- hostedPtyRegistry,
16870
- 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(
16871
17602
  permissionBroker,
16872
- hookEventRouter: hookRuntime.hookEventRouter,
16873
- createHookContext: hookRuntime.createHookContext,
16874
- emitAgentStatus: eventBridge.emitAgentStatus,
16875
- updateTerminalCwd: eventBridge.updateTerminalCwd,
16876
- config: statusConfig,
16877
- resolveInterruptedApprovals: (sessionId) => resolveInterruptedApprovals(
16878
- permissionBroker,
16879
- hookRuntime.hookEventRouter,
16880
- relayConnection,
16881
- sessionId
16882
- )
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);
16883
17611
  });
17612
+ socket.resume();
16884
17613
  });
16885
- server.listen(SOCK_PATH, () => {
16886
- writeFileSync2(PID_PATH, String(process.pid));
16887
- chmodSync(SOCK_PATH, 384);
16888
- serviceLogger.info({ pid: process.pid, sock: SOCK_PATH }, "Service started");
16889
- serviceReadyForAutoUpdate = true;
16890
- 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
+ });
16891
17631
  });
17632
+ let control = void 0;
17633
+ let stopping = false;
16892
17634
  const shutdown = createServeShutdown({
16893
17635
  logger: serviceLogger,
16894
17636
  autoUpdaterDispose: () => {
@@ -16904,16 +17646,52 @@ async function startService(options) {
16904
17646
  relayConnectionClose: () => relayConnection.close(),
16905
17647
  workerRegistryDestroyAll: () => workerRegistry.destroyAll(),
16906
17648
  hostedPtyRegistryDestroyAll: () => hostedPtyRegistry.destroyAll(),
17649
+ terminalAdmissionDestroyAll: () => terminalAdmission.destroyAll(),
16907
17650
  ipcServerClose: () => server.close(),
16908
17651
  sockPath: SOCK_PATH,
16909
- pidPath: PID_PATH
16910
- });
16911
- process.on("SIGTERM", () => {
16912
- 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
+ }
16913
17659
  });
16914
- process.on("SIGINT", () => {
17660
+ const stop = () => {
17661
+ stopping = true;
16915
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
+ })
16916
17692
  });
17693
+ serviceReadyForAutoUpdate = true;
17694
+ if (pendingRelayVersion) autoUpdater.considerRelayVersion(pendingRelayVersion);
16917
17695
  }
16918
17696
  var isMainModule = process.argv[1] && (process.argv[1].endsWith("serve.js") || process.argv[1].endsWith("serve.ts"));
16919
17697
  if (isMainModule) {