@dev-anywhere/proxy 0.4.84 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +12 -3
  2. package/dist/{chunk-2JSCH6DW.js → chunk-5OJB4FGI.js} +11 -4
  3. package/dist/chunk-5OJB4FGI.js.map +1 -0
  4. package/dist/{chunk-RYUEUDBR.js → chunk-5WZ6B735.js} +9 -6
  5. package/dist/chunk-5WZ6B735.js.map +1 -0
  6. package/dist/{chunk-LWDOXOWY.js → chunk-CN7UT6KW.js} +3 -80
  7. package/dist/chunk-CN7UT6KW.js.map +1 -0
  8. package/dist/{chunk-B3GHP25U.js → chunk-F53HQ6GP.js} +14 -2
  9. package/dist/chunk-F53HQ6GP.js.map +1 -0
  10. package/dist/chunk-NOUZTHUN.js +86 -0
  11. package/dist/chunk-NOUZTHUN.js.map +1 -0
  12. package/dist/{chunk-ENXGI3FO.js → chunk-UT3VNKEC.js} +403 -342
  13. package/dist/chunk-UT3VNKEC.js.map +1 -0
  14. package/dist/{chunk-6ESPTMAZ.js → chunk-UTSTY2XA.js} +6 -6
  15. package/dist/index.js +21 -6
  16. package/dist/index.js.map +1 -1
  17. package/dist/quick-tunnel-MO3U67K3.js +318 -0
  18. package/dist/quick-tunnel-MO3U67K3.js.map +1 -0
  19. package/dist/{relay-token-QD7ULGNS.js → relay-token-X7NWRMKV.js} +4 -3
  20. package/dist/{relay-token-QD7ULGNS.js.map → relay-token-X7NWRMKV.js.map} +1 -1
  21. package/dist/serve.js +479 -220
  22. package/dist/serve.js.map +1 -1
  23. package/dist/session-worker.js +8 -29
  24. package/dist/session-worker.js.map +1 -1
  25. package/dist/{terminal-EUZKQXTH.js → terminal-ME6PDFTF.js} +27 -19
  26. package/dist/terminal-ME6PDFTF.js.map +1 -0
  27. package/dist/terminal-worker.js +55 -12
  28. package/dist/terminal-worker.js.map +1 -1
  29. package/package.json +4 -4
  30. package/dist/chunk-2JSCH6DW.js.map +0 -1
  31. package/dist/chunk-B3GHP25U.js.map +0 -1
  32. package/dist/chunk-ENXGI3FO.js.map +0 -1
  33. package/dist/chunk-LWDOXOWY.js.map +0 -1
  34. package/dist/chunk-RYUEUDBR.js.map +0 -1
  35. package/dist/terminal-EUZKQXTH.js.map +0 -1
  36. /package/dist/{chunk-6ESPTMAZ.js.map → chunk-UTSTY2XA.js.map} +0 -0
package/dist/serve.js CHANGED
@@ -15,8 +15,9 @@ import {
15
15
  } from "./chunk-NXELIU46.js";
16
16
  import {
17
17
  decidePtySemanticTransition,
18
- shouldReleaseTextApprovalOnInput
19
- } from "./chunk-RYUEUDBR.js";
18
+ shouldReleaseTextApprovalOnInput,
19
+ shouldStartPtyTurnOnInput
20
+ } from "./chunk-5WZ6B735.js";
20
21
  import {
21
22
  CLAUDE_PROVIDER,
22
23
  CODEX_PROVIDER,
@@ -26,17 +27,15 @@ import {
26
27
  appendPtySemanticTextTail,
27
28
  extractOscSequences,
28
29
  extractOscSignals,
29
- extractTextSignals,
30
- normalizePtySemanticText
31
- } from "./chunk-B3GHP25U.js";
32
- import {
33
- spawnScript
34
- } from "./chunk-IHUQNJF6.js";
30
+ extractOscWorkingDirectory,
31
+ extractTextSignals
32
+ } from "./chunk-F53HQ6GP.js";
35
33
  import {
36
34
  ControlErrorCode,
37
35
  MessageEnvelopeSchema,
38
36
  RELAY_JSON_MESSAGE_MAX_BYTES,
39
37
  RelayControlSchema,
38
+ SESSION_CREATE_SERVER_DEADLINE_MS,
40
39
  SessionState,
41
40
  buildMessage,
42
41
  createFSM,
@@ -51,19 +50,18 @@ import {
51
50
  serializeControl,
52
51
  serializeIpc,
53
52
  serializeWorkerMsg
54
- } from "./chunk-ENXGI3FO.js";
53
+ } from "./chunk-UT3VNKEC.js";
55
54
  import {
56
55
  buildProviderEnv,
57
56
  loadConfig,
58
57
  saveAgentCliPath
59
- } from "./chunk-2JSCH6DW.js";
58
+ } from "./chunk-5OJB4FGI.js";
60
59
  import {
61
60
  atomicWriteFileSync
62
61
  } from "./chunk-NQDJ6QAM.js";
63
62
  import {
64
- flushLogger,
65
63
  serviceLogger
66
- } from "./chunk-LWDOXOWY.js";
64
+ } from "./chunk-NOUZTHUN.js";
67
65
  import {
68
66
  DATA_DIR,
69
67
  DEFAULT_PROXY_PROFILE,
@@ -79,6 +77,12 @@ import {
79
77
  sessionPaths,
80
78
  tildify
81
79
  } from "./chunk-7RSBFN2G.js";
80
+ import {
81
+ spawnScript
82
+ } from "./chunk-IHUQNJF6.js";
83
+ import {
84
+ flushLogger
85
+ } from "./chunk-CN7UT6KW.js";
82
86
 
83
87
  // src/serve.ts
84
88
  import { createServer as createServer2 } from "net";
@@ -86,6 +90,7 @@ import { unlinkSync as unlinkSync2, writeFileSync as writeFileSync2, chmodSync,
86
90
 
87
91
  // src/serve/session-manager.ts
88
92
  import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
93
+ import { isAbsolute, normalize } from "path";
89
94
  import { nanoid } from "nanoid";
90
95
 
91
96
  // src/serve/session-history-metadata.ts
@@ -395,6 +400,21 @@ var SessionManager = class {
395
400
  session.pid = pid;
396
401
  this.save();
397
402
  }
403
+ updateTerminalCwd(id, cwd) {
404
+ const session = this.sessions.get(id);
405
+ if (!session || session.mode !== "pty" || session.kind !== "terminal") return false;
406
+ const nextCwd = normalize(cwd);
407
+ if (!isAbsolute(nextCwd) || nextCwd === session.cwd) return false;
408
+ const previousCwd = session.cwd;
409
+ session.cwd = nextCwd;
410
+ session.updatedAt = Date.now();
411
+ this.save();
412
+ serviceLogger.info(
413
+ { sessionId: id, previousCwd, cwd: nextCwd },
414
+ "Terminal working directory changed"
415
+ );
416
+ return true;
417
+ }
398
418
  renameSession(id, name) {
399
419
  const session = this.sessions.get(id);
400
420
  if (!session) {
@@ -909,12 +929,12 @@ var RelayConnection = class extends EventEmitter {
909
929
 
910
930
  // src/serve/handlers/control-messages.ts
911
931
  import { readdir as readdir2, mkdir } from "fs/promises";
912
- import { join as join4, isAbsolute as isAbsolute2, normalize } from "path";
932
+ import { join as join4, isAbsolute as isAbsolute3, normalize as normalize2 } from "path";
913
933
 
914
934
  // src/serve/session-history.ts
915
935
  import { readdir, stat, access, open } from "fs/promises";
916
936
  import { createReadStream } from "fs";
917
- import { isAbsolute, join as join2, resolve, sep } from "path";
937
+ import { isAbsolute as isAbsolute2, join as join2, resolve, sep } from "path";
918
938
  import { homedir as homedir2, tmpdir } from "os";
919
939
  import { createInterface } from "readline";
920
940
  var claudeProjectsDir = () => join2(homedir2(), ".claude", "projects");
@@ -962,7 +982,7 @@ async function scanSessionHistory(options = {}) {
962
982
  }
963
983
  function normalizeAbsolutePath(path) {
964
984
  const trimmed = path.trim();
965
- if (!trimmed || !isAbsolute(trimmed)) return null;
985
+ if (!trimmed || !isAbsolute2(trimmed)) return null;
966
986
  let resolved = resolve(trimmed);
967
987
  while (resolved.length > 1 && resolved.endsWith(sep)) {
968
988
  resolved = resolved.slice(0, -1);
@@ -1609,8 +1629,8 @@ function classifyPathError(err) {
1609
1629
  // src/serve/handlers/control-messages.ts
1610
1630
  var COMMAND_REFRESH_MS = 6 * 60 * 60 * 1e3;
1611
1631
  function isPathSafe(path) {
1612
- if (!isAbsolute2(path)) return false;
1613
- const normalized = normalize(path);
1632
+ if (!isAbsolute3(path)) return false;
1633
+ const normalized = normalize2(path);
1614
1634
  if (normalized.includes("..")) return false;
1615
1635
  return true;
1616
1636
  }
@@ -2218,6 +2238,7 @@ var WorkerRegistry = class {
2218
2238
  children = /* @__PURE__ */ new Map();
2219
2239
  readySessions = /* @__PURE__ */ new Set();
2220
2240
  readyWaiters = /* @__PURE__ */ new Map();
2241
+ pendingNativeSessions = /* @__PURE__ */ new Map();
2221
2242
  // 记录哪些 session 是 spawn 时带 --stream-delta 的;forwardEvent 据此决定是否跳过 aggregated 去重
2222
2243
  streamDeltaSessions = /* @__PURE__ */ new Set();
2223
2244
  onEnvelopeDropped(raw) {
@@ -2292,32 +2313,75 @@ var WorkerRegistry = class {
2292
2313
  });
2293
2314
  const workerPid = child.pid;
2294
2315
  this.children.set(sessionId, child);
2316
+ child.once("exit", (code, signal) => {
2317
+ const activeSession = this.deps.sessionManager.getSession(sessionId);
2318
+ this.delete(sessionId);
2319
+ if (!activeSession) return;
2320
+ const result = this.deps.sessionManager.terminateSession(sessionId);
2321
+ serviceLogger.warn(
2322
+ { sessionId, workerPid, code, signal, removed: result.success },
2323
+ "JSON worker process exited without worker_exit IPC"
2324
+ );
2325
+ });
2295
2326
  serviceLogger.info(
2296
2327
  { sessionId, workerPid, cwd: options?.cwd, resume: options?.resumeSessionId },
2297
2328
  "Worker process spawned"
2298
2329
  );
2299
2330
  return workerPid;
2300
2331
  }
2301
- connect(sessionId, sockPath) {
2332
+ connect(sessionId, sockPath, timeoutMs) {
2302
2333
  return new Promise((resolve3) => {
2303
2334
  const sock = connect(sockPath);
2304
- sock.on("connect", () => {
2335
+ let settled = false;
2336
+ let timeout;
2337
+ const finish = (result) => {
2338
+ if (settled) return;
2339
+ settled = true;
2340
+ if (timeout) clearTimeout(timeout);
2341
+ resolve3(result);
2342
+ };
2343
+ const onConnectError = () => finish(null);
2344
+ sock.once("error", onConnectError);
2345
+ sock.once("connect", () => {
2346
+ sock.off("error", onConnectError);
2305
2347
  this.sockets.set(sessionId, sock);
2306
2348
  createWorkerReader(
2307
2349
  sock,
2308
- (msg) => this.handleWorkerMessage(sessionId, msg),
2350
+ (msg) => {
2351
+ try {
2352
+ this.handleWorkerMessage(sessionId, msg);
2353
+ } catch (err) {
2354
+ serviceLogger.error(
2355
+ { sessionId, error: err instanceof Error ? err.message : String(err) },
2356
+ "Worker message handler failed"
2357
+ );
2358
+ }
2359
+ },
2309
2360
  (err, line) => {
2310
2361
  serviceLogger.warn(
2311
- { sessionId, err: err.message, lineLen: line.length },
2362
+ {
2363
+ sessionId,
2364
+ err: err.message,
2365
+ lineLen: line.length
2366
+ },
2312
2367
  "Worker IPC message dropped (parse/schema error)"
2313
2368
  );
2314
2369
  }
2315
2370
  );
2316
2371
  sock.on("close", () => this.onDisconnect(sessionId));
2317
2372
  sock.on("error", () => this.onDisconnect(sessionId));
2318
- resolve3(sock);
2373
+ finish(sock);
2319
2374
  });
2320
- sock.on("error", () => resolve3(null));
2375
+ if (timeoutMs !== void 0) {
2376
+ timeout = setTimeout(
2377
+ () => {
2378
+ sock.destroy();
2379
+ finish(null);
2380
+ },
2381
+ Math.max(1, timeoutMs)
2382
+ );
2383
+ timeout.unref?.();
2384
+ }
2321
2385
  });
2322
2386
  }
2323
2387
  // 枚举 DATA_DIR 下所有 session 目录,尝试连接存活的 worker.sock;失败则清理 stale socket。
@@ -2352,11 +2416,15 @@ var WorkerRegistry = class {
2352
2416
  has(sessionId) {
2353
2417
  return this.sockets.has(sessionId);
2354
2418
  }
2419
+ hasProcess(sessionId) {
2420
+ return this.children.has(sessionId);
2421
+ }
2355
2422
  delete(sessionId) {
2356
2423
  this.children.delete(sessionId);
2357
2424
  this.sockets.delete(sessionId);
2358
2425
  this.readySessions.delete(sessionId);
2359
2426
  this.streamDeltaSessions.delete(sessionId);
2427
+ this.pendingNativeSessions.delete(sessionId);
2360
2428
  this.rejectReadyWaiters(
2361
2429
  new Error(`Worker session deleted before ready: ${sessionId}`),
2362
2430
  sessionId
@@ -2369,6 +2437,7 @@ var WorkerRegistry = class {
2369
2437
  this.sockets.delete(sessionId);
2370
2438
  this.readySessions.delete(sessionId);
2371
2439
  this.streamDeltaSessions.delete(sessionId);
2440
+ this.pendingNativeSessions.delete(sessionId);
2372
2441
  this.children.delete(sessionId);
2373
2442
  this.rejectReadyWaiters(
2374
2443
  new Error(`Worker process terminated before ready: ${sessionId}`),
@@ -2390,11 +2459,15 @@ var WorkerRegistry = class {
2390
2459
  }
2391
2460
  this.sockets.clear();
2392
2461
  this.readySessions.clear();
2462
+ this.pendingNativeSessions.clear();
2393
2463
  this.rejectReadyWaiters(new Error("Worker registry destroyed"));
2394
2464
  }
2395
2465
  handleWorkerMessage(sessionId, msg) {
2396
2466
  switch (msg.type) {
2397
2467
  case "worker_ready":
2468
+ if (msg.nativeSession) {
2469
+ this.captureNativeSession(sessionId, msg.nativeSession);
2470
+ }
2398
2471
  this.readySessions.add(sessionId);
2399
2472
  this.resolveReadyWaiters(sessionId);
2400
2473
  serviceLogger.info({ sessionId, pid: msg.pid }, "Worker ready");
@@ -2439,18 +2512,17 @@ var WorkerRegistry = class {
2439
2512
  this.forwardApprovalRequest(sessionId, msg);
2440
2513
  break;
2441
2514
  case "worker_claude_session_id":
2442
- this.deps.sessionManager.setClaudeSessionId(sessionId, msg.sessionId);
2515
+ this.captureNativeSession(sessionId, { provider: "claude", sessionId: msg.sessionId });
2443
2516
  serviceLogger.info(
2444
2517
  { sessionId, claudeSessionId: msg.sessionId },
2445
2518
  "Claude session ID captured"
2446
2519
  );
2447
2520
  break;
2448
2521
  case "worker_native_session_id":
2449
- if (msg.provider === "claude") {
2450
- this.deps.sessionManager.setClaudeSessionId(sessionId, msg.sessionId);
2451
- } else {
2452
- this.deps.sessionManager.setHistorySessionId(sessionId, msg.sessionId);
2453
- }
2522
+ this.captureNativeSession(sessionId, {
2523
+ provider: msg.provider,
2524
+ sessionId: msg.sessionId
2525
+ });
2454
2526
  serviceLogger.info(
2455
2527
  { sessionId, provider: msg.provider, nativeSessionId: msg.sessionId },
2456
2528
  "Native JSON session ID captured"
@@ -2458,6 +2530,22 @@ var WorkerRegistry = class {
2458
2530
  break;
2459
2531
  }
2460
2532
  }
2533
+ takePendingNativeSession(sessionId) {
2534
+ const nativeSession = this.pendingNativeSessions.get(sessionId);
2535
+ this.pendingNativeSessions.delete(sessionId);
2536
+ return nativeSession;
2537
+ }
2538
+ captureNativeSession(sessionId, nativeSession) {
2539
+ if (!this.deps.sessionManager.getSession(sessionId)) {
2540
+ this.pendingNativeSessions.set(sessionId, nativeSession);
2541
+ return;
2542
+ }
2543
+ if (nativeSession.provider === "claude") {
2544
+ this.deps.sessionManager.setClaudeSessionId(sessionId, nativeSession.sessionId);
2545
+ } else {
2546
+ this.deps.sessionManager.setHistorySessionId(sessionId, nativeSession.sessionId);
2547
+ }
2548
+ }
2461
2549
  // worker 连接断开或异常时的统一清理入口。仅记录一份,不再区分 close vs error 语义。
2462
2550
  onDisconnect(sessionId) {
2463
2551
  this.sockets.delete(sessionId);
@@ -2684,9 +2772,6 @@ function terminateSessionByOwnership(deps, sessionId) {
2684
2772
  }
2685
2773
  deps.terminalSockets.delete(sessionId);
2686
2774
  const result = deps.sessionManager.terminateSession(sessionId);
2687
- deps.controlHandlers.cleanup(sessionId);
2688
- deps.agentStatusRegistry.delete(sessionId);
2689
- deps.broadcastSessionList();
2690
2775
  serviceLogger.info(
2691
2776
  { sessionId, success: result.success },
2692
2777
  "Terminal worker session terminated"
@@ -2702,9 +2787,6 @@ function terminateSessionByOwnership(deps, sessionId) {
2702
2787
  const result = deps.sessionManager.terminateSession(sessionId, {
2703
2788
  preserveProviderHooks: true
2704
2789
  });
2705
- deps.controlHandlers.cleanup(sessionId);
2706
- deps.agentStatusRegistry.delete(sessionId);
2707
- deps.broadcastSessionList();
2708
2790
  serviceLogger.info(
2709
2791
  { sessionId, success: result.success },
2710
2792
  "Local terminal session detached from remote view"
@@ -2717,13 +2799,17 @@ function terminateSessionByOwnership(deps, sessionId) {
2717
2799
  return { success, action: "terminate_hosted_pty" };
2718
2800
  }
2719
2801
  if (session?.mode === "json") {
2720
- deps.workerRegistry.send(sessionId, { type: "worker_stop" });
2721
- deps.workerRegistry.delete(sessionId);
2802
+ const stopDelivered = deps.workerRegistry.send(sessionId, { type: "worker_stop" });
2803
+ if (stopDelivered) {
2804
+ deps.workerRegistry.delete(sessionId);
2805
+ } else {
2806
+ deps.workerRegistry.terminateProcess(sessionId);
2807
+ }
2722
2808
  const result = deps.sessionManager.terminateSession(sessionId);
2723
- deps.controlHandlers.cleanup(sessionId);
2724
- deps.agentStatusRegistry.delete(sessionId);
2725
- deps.broadcastSessionList();
2726
- serviceLogger.info({ sessionId, success: result.success }, "JSON worker session terminated");
2809
+ serviceLogger.info(
2810
+ { sessionId, success: result.success, stopDelivered },
2811
+ "JSON worker session terminated"
2812
+ );
2727
2813
  return { success: result.success, action: "terminate_json_worker" };
2728
2814
  }
2729
2815
  const hostedTerminated = deps.hostedPtyRegistry.terminate(sessionId);
@@ -3204,7 +3290,7 @@ var RelayResourceHandlers = class {
3204
3290
  // src/serve/relay-session-create-handler.ts
3205
3291
  import { rmSync, statSync as statSync2 } from "fs";
3206
3292
  import { homedir as homedir5 } from "os";
3207
- import { isAbsolute as isAbsolute3 } from "path";
3293
+ import { isAbsolute as isAbsolute4 } from "path";
3208
3294
  import { nanoid as nanoid3 } from "nanoid";
3209
3295
 
3210
3296
  // src/serve/hosted-pty-registry.ts
@@ -3352,7 +3438,7 @@ var HostedPtyRegistry = class {
3352
3438
  const hosted = this.sessions.get(sessionId);
3353
3439
  if (!hosted) return false;
3354
3440
  if (hosted.kind === "agent") {
3355
- this.releaseTextApprovalOnInput(sessionId, hosted, data);
3441
+ this.updateSemanticStateOnInput(sessionId, hosted, data);
3356
3442
  }
3357
3443
  hosted.child.write(data);
3358
3444
  serviceLogger.debug(
@@ -3396,6 +3482,9 @@ var HostedPtyRegistry = class {
3396
3482
  terminate(sessionId) {
3397
3483
  return this.close(sessionId, { kill: true, notify: true });
3398
3484
  }
3485
+ abortStartup(sessionId) {
3486
+ return this.close(sessionId, { kill: true, notify: false });
3487
+ }
3399
3488
  destroyAll() {
3400
3489
  for (const sessionId of Array.from(this.sessions.keys())) {
3401
3490
  this.close(sessionId, { kill: true, notify: false });
@@ -3411,14 +3500,16 @@ var HostedPtyRegistry = class {
3411
3500
  this.deps.touchSessionActivity(sessionId);
3412
3501
  this.sendBinary(sessionId, Buffer.from(data, "utf-8"), hosted.outputSeq);
3413
3502
  const oscSequences = extractOscSequences(data);
3503
+ const cwd = extractOscWorkingDirectory(data);
3414
3504
  const session = this.deps.sessionManager.getSession(sessionId);
3415
3505
  const oscSignal = extractOscSignals(data, session?.provider);
3416
3506
  if (oscSignal?.title) {
3417
3507
  this.sendTerminalTitle(sessionId, oscSignal.title);
3418
3508
  }
3509
+ if (hosted.kind === "terminal" && cwd) {
3510
+ this.deps.updateTerminalCwd(sessionId, cwd);
3511
+ }
3419
3512
  if (hosted.kind === "terminal") return;
3420
- this.deps.applyPtyStateToSession(sessionId, "working");
3421
- const hasTextActivity = normalizePtySemanticText(data).length > 0;
3422
3513
  hosted.semanticTextTail = appendPtySemanticTextTail(hosted.semanticTextTail, data);
3423
3514
  const textSignal = oscSignal ? null : extractTextSignals(hosted.semanticTextTail, session?.provider);
3424
3515
  const signal = oscSignal ?? textSignal;
@@ -3443,8 +3534,7 @@ var HostedPtyRegistry = class {
3443
3534
  currentState: hosted.currentState,
3444
3535
  signal: signal ?? null,
3445
3536
  sessionStateIsWaitingApproval: session?.state === SessionState.WAITING_APPROVAL,
3446
- allowTitleOnlyApprovalRelease: !hosted.textApprovalWaitActive,
3447
- hasTextActivity
3537
+ allowTitleOnlyApprovalRelease: !hosted.textApprovalWaitActive
3448
3538
  });
3449
3539
  hosted.currentState = decision.nextState;
3450
3540
  if (decision.nextState !== "approval_wait") {
@@ -3454,10 +3544,15 @@ var HostedPtyRegistry = class {
3454
3544
  this.sendPtyState(sessionId, decision.nextState, decision.meta, hosted);
3455
3545
  this.deps.applyPtyStateToSession(sessionId, decision.nextState);
3456
3546
  }
3457
- releaseTextApprovalOnInput(sessionId, hosted, data) {
3458
- if (!hosted.textApprovalWaitActive || hosted.currentState !== "approval_wait") return;
3459
- if (!shouldReleaseTextApprovalOnInput(data)) return;
3460
- hosted.textApprovalWaitActive = false;
3547
+ updateSemanticStateOnInput(sessionId, hosted, data) {
3548
+ if (hosted.textApprovalWaitActive && hosted.currentState === "approval_wait" && shouldReleaseTextApprovalOnInput(data)) {
3549
+ hosted.textApprovalWaitActive = false;
3550
+ hosted.currentState = "working";
3551
+ this.sendPtyState(sessionId, "working", void 0, hosted);
3552
+ this.deps.applyPtyStateToSession(sessionId, "working");
3553
+ return;
3554
+ }
3555
+ if (!shouldStartPtyTurnOnInput(hosted.currentState, data)) return;
3461
3556
  hosted.currentState = "working";
3462
3557
  this.sendPtyState(sessionId, "working", void 0, hosted);
3463
3558
  this.deps.applyPtyStateToSession(sessionId, "working");
@@ -3523,21 +3618,102 @@ var HostedPtyRegistry = class {
3523
3618
  if (options.notify) {
3524
3619
  this.sendPtyState(sessionId, "turn_complete", void 0, hosted);
3525
3620
  this.deps.sessionManager.terminateSession(sessionId);
3526
- this.deps.onSessionClosed(sessionId);
3527
3621
  }
3528
3622
  this.sessions.delete(sessionId);
3529
3623
  return true;
3530
3624
  }
3531
3625
  };
3532
3626
 
3627
+ // src/serve/json-worker-startup.ts
3628
+ var CONNECT_RETRY_BASE_MS = 100;
3629
+ var CONNECT_RETRY_MAX_MS = 1e3;
3630
+ var JsonWorkerStartupTimeoutError = class extends Error {
3631
+ constructor() {
3632
+ super("JSON worker startup deadline reached");
3633
+ this.name = "JsonWorkerStartupTimeoutError";
3634
+ }
3635
+ };
3636
+ function throwIfAborted(signal) {
3637
+ if (signal.aborted) {
3638
+ throw signal.reason instanceof Error ? signal.reason : new Error("JSON worker startup aborted");
3639
+ }
3640
+ }
3641
+ function wait(delayMs, signal) {
3642
+ return new Promise((resolve3, reject) => {
3643
+ throwIfAborted(signal);
3644
+ const onAbort = () => {
3645
+ clearTimeout(timer);
3646
+ reject(signal.reason instanceof Error ? signal.reason : new Error("Startup aborted"));
3647
+ };
3648
+ const timer = setTimeout(() => {
3649
+ signal.removeEventListener("abort", onAbort);
3650
+ resolve3();
3651
+ }, delayMs);
3652
+ timer.unref?.();
3653
+ signal.addEventListener("abort", onAbort, { once: true });
3654
+ });
3655
+ }
3656
+ async function waitForJsonWorkerStartup(options) {
3657
+ let attempt = 0;
3658
+ while (true) {
3659
+ throwIfAborted(options.signal);
3660
+ const remainingBeforeDelay = options.deadlineAt - Date.now();
3661
+ if (remainingBeforeDelay <= 0) throw new JsonWorkerStartupTimeoutError();
3662
+ const delayMs = Math.min(
3663
+ CONNECT_RETRY_BASE_MS * Math.max(1, attempt),
3664
+ CONNECT_RETRY_MAX_MS,
3665
+ remainingBeforeDelay
3666
+ );
3667
+ await wait(delayMs, options.signal);
3668
+ throwIfAborted(options.signal);
3669
+ const connectBudgetMs = options.deadlineAt - Date.now();
3670
+ if (connectBudgetMs <= 0) throw new JsonWorkerStartupTimeoutError();
3671
+ attempt += 1;
3672
+ const socket = await options.workerRegistry.connect(
3673
+ options.sessionId,
3674
+ options.socketPath,
3675
+ connectBudgetMs
3676
+ );
3677
+ if (options.signal.aborted) {
3678
+ socket?.destroy();
3679
+ options.workerRegistry.delete(options.sessionId);
3680
+ throwIfAborted(options.signal);
3681
+ }
3682
+ if (!socket) {
3683
+ if (!options.workerRegistry.hasProcess(options.sessionId)) {
3684
+ throw new Error("JSON worker exited before opening its control socket");
3685
+ }
3686
+ continue;
3687
+ }
3688
+ if (!options.workerRegistry.hasProcess(options.sessionId)) {
3689
+ socket.destroy();
3690
+ throw new Error("JSON worker exited before reporting ready");
3691
+ }
3692
+ const readyBudgetMs = options.deadlineAt - Date.now();
3693
+ if (readyBudgetMs <= 0) throw new JsonWorkerStartupTimeoutError();
3694
+ try {
3695
+ await options.workerRegistry.waitForReady(options.sessionId, readyBudgetMs);
3696
+ } catch (err) {
3697
+ if (Date.now() >= options.deadlineAt) throw new JsonWorkerStartupTimeoutError();
3698
+ throw err;
3699
+ }
3700
+ throwIfAborted(options.signal);
3701
+ if (!options.workerRegistry.has(options.sessionId)) {
3702
+ throw new Error("JSON worker disconnected after reporting ready");
3703
+ }
3704
+ return;
3705
+ }
3706
+ }
3707
+
3533
3708
  // src/serve/relay-session-create-handler.ts
3534
- var JSON_WORKER_READY_TIMEOUT_MS = 15e3;
3709
+ var WORKER_START_FAILED_MESSAGE = "Agent \u8FDB\u7A0B\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 Agent CLI \u914D\u7F6E\u540E\u91CD\u8BD5";
3710
+ var WORKER_START_TIMEOUT_MESSAGE = "Agent \u542F\u52A8\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5 Agent CLI \u914D\u7F6E\u4E0E\u5F00\u53D1\u673A\u8D1F\u8F7D\u540E\u91CD\u8BD5";
3535
3711
  function validateSessionCwd(cwd) {
3536
3712
  if (typeof cwd !== "string" || !cwd.trim()) {
3537
3713
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
3538
3714
  }
3539
3715
  const trimmed = cwd.trim();
3540
- if (!isAbsolute3(trimmed)) {
3716
+ if (!isAbsolute4(trimmed)) {
3541
3717
  return { message: "\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84", code: ControlErrorCode.INVALID_PATH };
3542
3718
  }
3543
3719
  try {
@@ -3569,16 +3745,15 @@ var RelaySessionCreateHandler = class {
3569
3745
  this.deps = deps;
3570
3746
  }
3571
3747
  deps;
3572
- // 跟踪每个 pendingId 当前挂起的 retry timer。SIGTERM 抵达时 destroy() 会 clear
3573
- // 这些 timer 并执行 cleanupPendingJsonSession,否则 worker 子进程在窗口期内可能成为孤儿
3574
- // (setTimeout 回调命中时 workerRegistry 已经 destroyAll,但 worker 进程并未被 kill)。
3575
- pendingTimers = /* @__PURE__ */ new Map();
3748
+ // spawn/connect/ready 共享一个绝对截止时间。pending 在 publish 前不进入
3749
+ // SessionManager,所以失败或 shutdown 都可以作为一个未发布事务统一回收。
3750
+ pendingJsonCreates = /* @__PURE__ */ new Map();
3576
3751
  destroy() {
3577
- for (const [pendingId, timer] of this.pendingTimers) {
3578
- clearTimeout(timer);
3752
+ for (const [pendingId, pending] of this.pendingJsonCreates) {
3753
+ this.pendingJsonCreates.delete(pendingId);
3754
+ pending.controller.abort(new Error("Relay session create handler destroyed"));
3579
3755
  this.cleanupPendingJsonSession(pendingId);
3580
3756
  }
3581
- this.pendingTimers.clear();
3582
3757
  }
3583
3758
  onSessionCreate(msg) {
3584
3759
  if (msg.kind === "terminal") {
@@ -3625,97 +3800,131 @@ var RelaySessionCreateHandler = class {
3625
3800
  const name = requestedName ?? tildify(sessionCwd);
3626
3801
  const nameLocked = requestedName !== void 0;
3627
3802
  const pendingId = nanoid3();
3628
- const hook = this.deps.createHookContext(pendingId, provider);
3629
- const workerPid = this.deps.workerRegistry.spawn(pendingId, {
3630
- cwd: sessionCwd,
3631
- resumeSessionId,
3632
- permissionMode,
3633
- provider,
3634
- streamDelta,
3635
- hook
3636
- });
3637
- const paths = sessionPaths(pendingId);
3638
- let attempt = 0;
3639
- const maxRetries = 20;
3640
- const scheduleAttempt = (delayMs) => {
3641
- const timer = setTimeout(tryConnect, delayMs);
3642
- this.pendingTimers.set(pendingId, timer);
3643
- };
3644
- const tryConnect = () => {
3645
- this.pendingTimers.delete(pendingId);
3646
- attempt++;
3647
- this.deps.workerRegistry.connect(pendingId, paths.workerSock).then((sock) => {
3648
- if (sock) {
3649
- this.deps.workerRegistry.waitForReady(pendingId, JSON_WORKER_READY_TIMEOUT_MS).then(() => {
3650
- const session = this.deps.sessionManager.createSession(
3651
- "json",
3652
- sessionCwd,
3653
- workerPid,
3654
- name,
3655
- pendingId,
3656
- provider,
3657
- void 0,
3658
- nameLocked
3659
- );
3660
- if (resumeSessionId) {
3661
- this.deps.sessionManager.setHistorySessionId(session.id, resumeSessionId);
3662
- }
3663
- this.deps.relaySend(
3664
- serializeControl({
3665
- type: "session_create_response",
3666
- requestId,
3667
- sessionId: session.id,
3668
- name: session.name,
3669
- nameLocked: session.nameLocked,
3670
- mode: "json",
3671
- provider
3672
- })
3673
- );
3674
- if (resumeSessionId) {
3675
- this.pushHistoryMessages(session.id, resumeSessionId);
3676
- }
3677
- serviceLogger.info(
3678
- { sessionId: session.id, cwd: sessionCwd },
3679
- "JSON session created via relay"
3680
- );
3681
- this.deps.controlHandlers.pushCommandList(session.id, sessionCwd);
3682
- this.deps.broadcastSessionSync(session);
3683
- this.deps.broadcastSessionList();
3684
- }).catch((err) => {
3685
- const error = err instanceof Error ? err.message : String(err);
3686
- this.cleanupPendingJsonSession(pendingId);
3687
- this.deps.relaySend(
3688
- serializeControl({
3689
- type: "session_create_response",
3690
- requestId,
3691
- sessionId: pendingId,
3692
- errorCode: ControlErrorCode.WORKER_START_FAILED,
3693
- error
3694
- })
3695
- );
3696
- serviceLogger.error(
3697
- { sessionId: pendingId, error },
3698
- "Worker failed to report ready via relay"
3699
- );
3700
- });
3701
- } else if (attempt < maxRetries) {
3702
- scheduleAttempt(Math.min(100 * attempt, 2e3));
3703
- } else {
3704
- this.cleanupPendingJsonSession(pendingId);
3705
- this.deps.relaySend(
3706
- serializeControl({
3707
- type: "session_create_response",
3708
- requestId,
3709
- sessionId: pendingId,
3710
- errorCode: ControlErrorCode.WORKER_START_FAILED,
3711
- error: "Worker failed to start"
3712
- })
3713
- );
3714
- serviceLogger.error({ sessionId: pendingId }, "Worker connection timeout via relay");
3715
- }
3803
+ const deadlineAt = Date.now() + SESSION_CREATE_SERVER_DEADLINE_MS;
3804
+ let workerPid;
3805
+ try {
3806
+ const hook = this.deps.createHookContext(pendingId, provider);
3807
+ workerPid = this.deps.workerRegistry.spawn(pendingId, {
3808
+ cwd: sessionCwd,
3809
+ resumeSessionId,
3810
+ permissionMode,
3811
+ provider,
3812
+ streamDelta,
3813
+ hook
3716
3814
  });
3717
- };
3718
- scheduleAttempt(100);
3815
+ } catch (err) {
3816
+ this.reportJsonStartupFailure(requestId, pendingId, WORKER_START_FAILED_MESSAGE, err);
3817
+ return;
3818
+ }
3819
+ const controller = new AbortController();
3820
+ this.pendingJsonCreates.set(pendingId, { controller });
3821
+ void waitForJsonWorkerStartup({
3822
+ workerRegistry: this.deps.workerRegistry,
3823
+ sessionId: pendingId,
3824
+ socketPath: sessionPaths(pendingId).workerSock,
3825
+ deadlineAt,
3826
+ signal: controller.signal
3827
+ }).then(
3828
+ () => this.publishJsonSession({
3829
+ requestId,
3830
+ pendingId,
3831
+ workerPid,
3832
+ sessionCwd,
3833
+ name,
3834
+ nameLocked,
3835
+ provider,
3836
+ resumeSessionId
3837
+ })
3838
+ ).catch((err) => {
3839
+ if (!this.takePendingJsonCreate(pendingId)) return;
3840
+ this.reportJsonStartupFailure(
3841
+ requestId,
3842
+ pendingId,
3843
+ err instanceof JsonWorkerStartupTimeoutError ? WORKER_START_TIMEOUT_MESSAGE : WORKER_START_FAILED_MESSAGE,
3844
+ err
3845
+ );
3846
+ });
3847
+ }
3848
+ takePendingJsonCreate(sessionId) {
3849
+ if (!this.pendingJsonCreates.has(sessionId)) return false;
3850
+ this.pendingJsonCreates.delete(sessionId);
3851
+ return true;
3852
+ }
3853
+ publishJsonSession(options) {
3854
+ if (!this.takePendingJsonCreate(options.pendingId)) return;
3855
+ let session;
3856
+ try {
3857
+ session = this.deps.sessionManager.createSession(
3858
+ "json",
3859
+ options.sessionCwd,
3860
+ options.workerPid,
3861
+ options.name,
3862
+ options.pendingId,
3863
+ options.provider,
3864
+ void 0,
3865
+ options.nameLocked
3866
+ );
3867
+ } catch (err) {
3868
+ this.reportJsonStartupFailure(
3869
+ options.requestId,
3870
+ options.pendingId,
3871
+ WORKER_START_FAILED_MESSAGE,
3872
+ err
3873
+ );
3874
+ return;
3875
+ }
3876
+ const nativeSession = this.deps.workerRegistry.takePendingNativeSession(session.id);
3877
+ if (nativeSession) {
3878
+ if (nativeSession.provider === "claude") {
3879
+ this.deps.sessionManager.setClaudeSessionId(session.id, nativeSession.sessionId);
3880
+ } else {
3881
+ this.deps.sessionManager.setHistorySessionId(session.id, nativeSession.sessionId);
3882
+ }
3883
+ }
3884
+ if (options.resumeSessionId) {
3885
+ this.deps.sessionManager.setHistorySessionId(session.id, options.resumeSessionId);
3886
+ }
3887
+ this.deps.relaySend(
3888
+ serializeControl({
3889
+ type: "session_create_response",
3890
+ requestId: options.requestId,
3891
+ sessionId: session.id,
3892
+ name: session.name,
3893
+ nameLocked: session.nameLocked,
3894
+ mode: "json",
3895
+ provider: options.provider
3896
+ })
3897
+ );
3898
+ if (options.resumeSessionId) {
3899
+ this.pushHistoryMessages(session.id, options.resumeSessionId);
3900
+ }
3901
+ serviceLogger.info(
3902
+ { sessionId: session.id, cwd: options.sessionCwd },
3903
+ "JSON session created via relay"
3904
+ );
3905
+ this.deps.controlHandlers.pushCommandList(session.id, options.sessionCwd);
3906
+ this.deps.broadcastSessionSync(session);
3907
+ this.deps.broadcastSessionList();
3908
+ }
3909
+ reportJsonStartupFailure(requestId, sessionId, message, reason) {
3910
+ this.cleanupPendingJsonSession(sessionId);
3911
+ this.deps.relaySend(
3912
+ serializeControl({
3913
+ type: "session_create_response",
3914
+ requestId,
3915
+ sessionId,
3916
+ errorCode: ControlErrorCode.WORKER_START_FAILED,
3917
+ error: message
3918
+ })
3919
+ );
3920
+ serviceLogger.error(
3921
+ {
3922
+ sessionId,
3923
+ error: reason instanceof Error ? reason.message : String(reason),
3924
+ timedOut: message === WORKER_START_TIMEOUT_MESSAGE
3925
+ },
3926
+ "JSON worker startup failed via relay"
3927
+ );
3719
3928
  }
3720
3929
  cleanupPendingJsonSession(sessionId) {
3721
3930
  const killed = this.deps.workerRegistry.terminateProcess(sessionId);
@@ -3746,8 +3955,9 @@ var RelaySessionCreateHandler = class {
3746
3955
  const requestedName = normalizeSessionName(msg.name);
3747
3956
  const name = requestedName ?? tildify(cwd);
3748
3957
  const nameLocked = requestedName !== void 0;
3749
- const hook = this.deps.createHookContext(pendingId, provider);
3958
+ let session;
3750
3959
  try {
3960
+ const hook = this.deps.createHookContext(pendingId, provider);
3751
3961
  const pid = this.deps.hostedPtyRegistry.start({
3752
3962
  sessionId: pendingId,
3753
3963
  provider,
@@ -3756,7 +3966,7 @@ var RelaySessionCreateHandler = class {
3756
3966
  permissionMode,
3757
3967
  hook
3758
3968
  });
3759
- const session = this.deps.sessionManager.createSession(
3969
+ session = this.deps.sessionManager.createSession(
3760
3970
  "pty",
3761
3971
  cwd,
3762
3972
  pid,
@@ -3766,31 +3976,8 @@ var RelaySessionCreateHandler = class {
3766
3976
  "proxy-hosted",
3767
3977
  nameLocked
3768
3978
  );
3769
- if (resumeSessionId) {
3770
- if (provider === "claude") {
3771
- this.deps.sessionManager.setClaudeSessionId(session.id, resumeSessionId);
3772
- } else {
3773
- this.deps.sessionManager.setHistorySessionId(session.id, resumeSessionId);
3774
- }
3775
- }
3776
- this.deps.relaySend(
3777
- serializeControl({
3778
- type: "session_create_response",
3779
- requestId: msg.requestId,
3780
- sessionId: session.id,
3781
- name: session.name,
3782
- nameLocked: session.nameLocked,
3783
- mode: "pty",
3784
- provider,
3785
- ptyOwner: "proxy-hosted"
3786
- })
3787
- );
3788
- this.deps.controlHandlers.pushCommandList(session.id, cwd);
3789
- this.deps.controlHandlers.pushFileTree(session.id, cwd);
3790
- this.deps.broadcastSessionSync(session);
3791
- this.deps.broadcastSessionList();
3792
- serviceLogger.info({ sessionId: session.id, provider, cwd }, "Hosted PTY session created");
3793
3979
  } catch (err) {
3980
+ this.cleanupPendingHostedPtySession(pendingId);
3794
3981
  const error = err instanceof Error ? err.message : String(err);
3795
3982
  this.deps.relaySend(
3796
3983
  serializeControl({
@@ -3812,7 +3999,43 @@ var RelaySessionCreateHandler = class {
3812
3999
  },
3813
4000
  "Hosted PTY session create failed"
3814
4001
  );
4002
+ return;
3815
4003
  }
4004
+ if (resumeSessionId) {
4005
+ if (provider === "claude") {
4006
+ this.deps.sessionManager.setClaudeSessionId(session.id, resumeSessionId);
4007
+ } else {
4008
+ this.deps.sessionManager.setHistorySessionId(session.id, resumeSessionId);
4009
+ }
4010
+ }
4011
+ this.deps.relaySend(
4012
+ serializeControl({
4013
+ type: "session_create_response",
4014
+ requestId: msg.requestId,
4015
+ sessionId: session.id,
4016
+ name: session.name,
4017
+ nameLocked: session.nameLocked,
4018
+ mode: "pty",
4019
+ provider,
4020
+ ptyOwner: "proxy-hosted"
4021
+ })
4022
+ );
4023
+ this.deps.controlHandlers.pushCommandList(session.id, cwd);
4024
+ this.deps.controlHandlers.pushFileTree(session.id, cwd);
4025
+ this.deps.broadcastSessionSync(session);
4026
+ this.deps.broadcastSessionList();
4027
+ serviceLogger.info({ sessionId: session.id, provider, cwd }, "Hosted PTY session created");
4028
+ }
4029
+ cleanupPendingHostedPtySession(sessionId) {
4030
+ const killed = this.deps.hostedPtyRegistry.abortStartup(sessionId);
4031
+ rmSync(sessionPaths(sessionId).dir, { recursive: true, force: true });
4032
+ this.deps.cleanupHookContext(sessionId);
4033
+ this.deps.permissionBroker.cleanupSession(sessionId, "Hosted PTY failed to start");
4034
+ this.deps.agentStatusRegistry.delete(sessionId);
4035
+ serviceLogger.warn(
4036
+ { sessionId, killed },
4037
+ "Cleaned up pending hosted PTY session after startup failure"
4038
+ );
3816
4039
  }
3817
4040
  createShellTerminalSession(msg) {
3818
4041
  const pendingId = nanoid3();
@@ -4466,6 +4689,7 @@ var RelayRouter = class {
4466
4689
  ts.write(serializeIpc({ type: "pty_subscribe", sessionId: sid, requestId }));
4467
4690
  serviceLogger.info({ sessionId: sid, requestId }, "Subscribe forwarded to terminal");
4468
4691
  } else {
4692
+ this.deps.terminalSubscriptionBacklog.add(sid, requestId);
4469
4693
  serviceLogger.warn({ sessionId: sid }, "Subscribe failed: terminal socket not available");
4470
4694
  }
4471
4695
  }
@@ -4753,9 +4977,12 @@ var AgentStatusRegistry = class {
4753
4977
  };
4754
4978
 
4755
4979
  // src/serve/terminal-worker-spawner.ts
4980
+ function buildTerminalWorkerArgs(options, profileName = PROFILE_NAME) {
4981
+ return ["--profile", profileName, options.sessionId, options.cwd, options.name];
4982
+ }
4756
4983
  var TerminalWorkerSpawner = class {
4757
4984
  start(options) {
4758
- const child = spawnScript("terminal-worker", [options.sessionId, options.cwd, options.name], {
4985
+ const child = spawnScript("terminal-worker", buildTerminalWorkerArgs(options), {
4759
4986
  env: { ...process.env },
4760
4987
  logger: serviceLogger
4761
4988
  });
@@ -4887,6 +5114,11 @@ function changeSessionState(sessionManager, relay, sessionId, next) {
4887
5114
  if (changed) pushSessionStatus(relay, sessionManager, sessionId);
4888
5115
  return changed;
4889
5116
  }
5117
+ function changeTerminalCwd(sessionManager, relay, sessionId, cwd) {
5118
+ const changed = sessionManager.updateTerminalCwd(sessionId, cwd);
5119
+ if (changed) broadcastSessionList(relay, sessionManager);
5120
+ return changed;
5121
+ }
4890
5122
  function touchSessionActivity(sessionManager, relay, sessionId, now = Date.now()) {
4891
5123
  const touched = sessionManager.touchSession(sessionId, now, ACTIVITY_STATUS_PUSH_INTERVAL_MS);
4892
5124
  if (touched) pushSessionStatus(relay, sessionManager, sessionId);
@@ -4897,6 +5129,7 @@ function touchSessionActivity(sessionManager, relay, sessionId, now = Date.now()
4897
5129
  function createEventBridge(deps) {
4898
5130
  const changeState = (sessionId, next) => changeSessionState(deps.sessionManager, deps.relayConnection, sessionId, next);
4899
5131
  const touchActivity = (sessionId) => touchSessionActivity(deps.sessionManager, deps.relayConnection, sessionId);
5132
+ const updateTerminalCwd = (sessionId, cwd) => changeTerminalCwd(deps.sessionManager, deps.relayConnection, sessionId, cwd);
4900
5133
  const emitAgentStatus = (sessionId, phase) => {
4901
5134
  const session = deps.sessionManager.getSession(sessionId);
4902
5135
  if (!session) return;
@@ -4940,6 +5173,7 @@ function createEventBridge(deps) {
4940
5173
  return {
4941
5174
  changeSessionState: changeState,
4942
5175
  touchSessionActivity: touchActivity,
5176
+ updateTerminalCwd,
4943
5177
  emitAgentStatus,
4944
5178
  cleanupSessionResources
4945
5179
  };
@@ -5018,15 +5252,14 @@ function handleTerminalConnection(socket, deps) {
5018
5252
  sessionManager,
5019
5253
  workerRegistry,
5020
5254
  terminalSockets,
5255
+ terminalSubscriptionBacklog,
5021
5256
  hostedPtyRegistry,
5022
5257
  relayConnection,
5023
- controlHandlers,
5024
- agentStatusRegistry,
5025
5258
  permissionBroker,
5026
5259
  createHookContext,
5027
5260
  emitAgentStatus,
5261
+ updateTerminalCwd,
5028
5262
  resolveInterruptedApprovals: resolveInterruptedApprovals2,
5029
- cleanupSessionResources,
5030
5263
  config
5031
5264
  } = deps;
5032
5265
  const bridgeDeps = {
@@ -5113,6 +5346,10 @@ function handleTerminalConnection(socket, deps) {
5113
5346
  );
5114
5347
  break;
5115
5348
  }
5349
+ case "pty_cwd_change": {
5350
+ updateTerminalCwd(msg.sessionId, msg.cwd);
5351
+ break;
5352
+ }
5116
5353
  case "pty_semantic_event": {
5117
5354
  if (!sessionManager.getSession(msg.sessionId)) break;
5118
5355
  const logPayload = {
@@ -5159,11 +5396,8 @@ function handleTerminalConnection(socket, deps) {
5159
5396
  {
5160
5397
  sessionManager,
5161
5398
  workerRegistry,
5162
- controlHandlers,
5163
5399
  terminalSockets,
5164
- hostedPtyRegistry,
5165
- agentStatusRegistry,
5166
- broadcastSessionList: () => broadcastSessionList(relayConnection, sessionManager)
5400
+ hostedPtyRegistry
5167
5401
  },
5168
5402
  msg.sessionId
5169
5403
  );
@@ -5201,10 +5435,28 @@ function handleTerminalConnection(socket, deps) {
5201
5435
  broadcastSessionSync(relayConnection, session);
5202
5436
  }
5203
5437
  broadcastSessionList(relayConnection, sessionManager);
5438
+ const pendingSubscribes = terminalSubscriptionBacklog.take(msg.sessionId);
5439
+ for (const pending of pendingSubscribes) {
5440
+ if (!socket.writable) break;
5441
+ socket.write(
5442
+ serializeIpc({
5443
+ type: "pty_subscribe",
5444
+ sessionId: msg.sessionId,
5445
+ requestId: pending.requestId
5446
+ })
5447
+ );
5448
+ }
5449
+ if (pendingSubscribes.length > 0) {
5450
+ serviceLogger.info(
5451
+ { sessionId: msg.sessionId, count: pendingSubscribes.length },
5452
+ "Pending PTY subscribes forwarded to terminal"
5453
+ );
5454
+ }
5204
5455
  serviceLogger.info({ sessionId: msg.sessionId }, "PTY session registered");
5205
5456
  break;
5206
5457
  }
5207
5458
  case "pty_deregister": {
5459
+ terminalSubscriptionBacklog.delete(msg.sessionId);
5208
5460
  relayConnection.sendRaw(
5209
5461
  serializeControl({
5210
5462
  type: "pty_state",
@@ -5214,7 +5466,6 @@ function handleTerminalConnection(socket, deps) {
5214
5466
  );
5215
5467
  sessionManager.terminateSession(msg.sessionId);
5216
5468
  terminalSockets.delete(msg.sessionId);
5217
- cleanupSessionResources(msg.sessionId);
5218
5469
  serviceLogger.info({ sessionId: msg.sessionId }, "PTY session deregistered");
5219
5470
  break;
5220
5471
  }
@@ -5287,6 +5538,7 @@ function handleTerminalConnection(socket, deps) {
5287
5538
  for (const [sessionId, terminalSocket] of terminalSockets) {
5288
5539
  if (terminalSocket === socket) {
5289
5540
  terminalSockets.delete(sessionId);
5541
+ terminalSubscriptionBacklog.delete(sessionId);
5290
5542
  const session = sessionManager.getSession(sessionId);
5291
5543
  if (!session) {
5292
5544
  serviceLogger.info({ sessionId }, "Terminal socket closed, session already cleaned");
@@ -5307,7 +5559,6 @@ function handleTerminalConnection(socket, deps) {
5307
5559
  })
5308
5560
  );
5309
5561
  sessionManager.terminateSession(sessionId);
5310
- cleanupSessionResources(sessionId);
5311
5562
  serviceLogger.info(
5312
5563
  { sessionId },
5313
5564
  "PTY session cleaned up on socket close (crash fallback)"
@@ -5511,7 +5762,7 @@ var HookServer = class {
5511
5762
  { sessionId: binding.sessionId, provider: binding.provider, event: parsed.event },
5512
5763
  "Provider hook ignored for inactive session"
5513
5764
  );
5514
- this.writeProviderResponse(res, this.toNeutralProviderResponse(provider, parsed.event));
5765
+ this.writeNeutralProviderResponse(res);
5515
5766
  return;
5516
5767
  }
5517
5768
  const payload = asRecord(parsed.payload);
@@ -5528,7 +5779,7 @@ var HookServer = class {
5528
5779
  return;
5529
5780
  }
5530
5781
  this.options.onEvent?.(event);
5531
- this.writeProviderResponse(res, this.toNeutralProviderResponse(event.provider, event.event));
5782
+ this.writeNeutralProviderResponse(res);
5532
5783
  }
5533
5784
  async handlePermissionRequest(event, res) {
5534
5785
  const requestId = event.requestId ?? (typeof event.payload.tool_use_id === "string" ? event.payload.tool_use_id : void 0) ?? this.nextFallbackRequestId(event.sessionId);
@@ -5561,28 +5812,10 @@ var HookServer = class {
5561
5812
  }
5562
5813
  };
5563
5814
  }
5564
- toNeutralProviderResponse(provider, eventName) {
5565
- if (eventName === "PreToolUse") {
5566
- if (provider === "codex") {
5567
- return null;
5568
- }
5569
- return {
5570
- hookSpecificOutput: {
5571
- hookEventName: "PreToolUse",
5572
- permissionDecision: "ask"
5573
- }
5574
- };
5575
- }
5576
- return null;
5577
- }
5578
- writeProviderResponse(res, payload) {
5815
+ writeNeutralProviderResponse(res) {
5579
5816
  if (res.headersSent) return;
5580
- if (payload === null) {
5581
- res.writeHead(200);
5582
- res.end();
5583
- return;
5584
- }
5585
- this.writeJson(res, 200, payload);
5817
+ res.writeHead(200);
5818
+ res.end();
5586
5819
  }
5587
5820
  readBody(req) {
5588
5821
  return new Promise((resolve3, reject) => {
@@ -5840,7 +6073,7 @@ import { basename } from "path";
5840
6073
  // src/serve/remote-file-path.ts
5841
6074
  import { realpathSync } from "fs";
5842
6075
  import { homedir as homedir6 } from "os";
5843
- import { extname as extname2, isAbsolute as isAbsolute4, resolve as resolve2 } from "path";
6076
+ import { extname as extname2, isAbsolute as isAbsolute5, resolve as resolve2 } from "path";
5844
6077
  var EXT_MIME_MAP = {
5845
6078
  ".png": "image/png",
5846
6079
  ".jpg": "image/jpeg",
@@ -5875,7 +6108,7 @@ function guessMimeType(filePath) {
5875
6108
  }
5876
6109
  function resolveRemoteFilePath(rawPath, cwd) {
5877
6110
  const expandedPath = rawPath === "~" || rawPath.startsWith("~/") ? resolve2(homedir6(), rawPath.slice(2)) : rawPath;
5878
- const candidate = isAbsolute4(expandedPath) ? resolve2(expandedPath) : resolve2(cwd, expandedPath);
6111
+ const candidate = isAbsolute5(expandedPath) ? resolve2(expandedPath) : resolve2(cwd, expandedPath);
5879
6112
  return realpathSync(candidate);
5880
6113
  }
5881
6114
 
@@ -6088,6 +6321,29 @@ var RemoteFileStreamManager = class {
6088
6321
  }
6089
6322
  };
6090
6323
 
6324
+ // src/serve/terminal-subscription-backlog.ts
6325
+ var MAX_PENDING_SUBSCRIBES_PER_SESSION = 8;
6326
+ var TerminalSubscriptionBacklog = class {
6327
+ pending = /* @__PURE__ */ new Map();
6328
+ add(sessionId, requestId) {
6329
+ const entries = this.pending.get(sessionId) ?? [];
6330
+ if (requestId && entries.some((entry) => entry.requestId === requestId)) return;
6331
+ entries.push({ requestId });
6332
+ if (entries.length > MAX_PENDING_SUBSCRIBES_PER_SESSION) {
6333
+ entries.splice(0, entries.length - MAX_PENDING_SUBSCRIBES_PER_SESSION);
6334
+ }
6335
+ this.pending.set(sessionId, entries);
6336
+ }
6337
+ take(sessionId) {
6338
+ const entries = this.pending.get(sessionId) ?? [];
6339
+ this.pending.delete(sessionId);
6340
+ return entries;
6341
+ }
6342
+ delete(sessionId) {
6343
+ this.pending.delete(sessionId);
6344
+ }
6345
+ };
6346
+
6091
6347
  // src/serve.ts
6092
6348
  function resolveInterruptedApprovals(permissionBroker, hookEventRouter, relay, sessionId) {
6093
6349
  const approvals = permissionBroker.listSession(sessionId);
@@ -6150,6 +6406,8 @@ async function startService(options) {
6150
6406
  const agentStatusRegistry = new AgentStatusRegistry();
6151
6407
  let unregisterHookSession = () => {
6152
6408
  };
6409
+ let cleanupRemovedSessionRuntime = () => {
6410
+ };
6153
6411
  const sessionManager = new SessionManager({
6154
6412
  persistPath: SESSIONS_PATH,
6155
6413
  historyMetadataPath: HISTORY_METADATA_PATH,
@@ -6157,13 +6415,12 @@ async function startService(options) {
6157
6415
  if (!context?.preserveProviderHooks) {
6158
6416
  unregisterHookSession(id);
6159
6417
  }
6160
- permissionBroker.cleanupSession(id, "session removed");
6161
- agentStatusRegistry.delete(id);
6162
6418
  const paths = sessionPaths(id);
6163
6419
  try {
6164
6420
  rmSync2(paths.dir, { recursive: true, force: true });
6165
6421
  } catch {
6166
6422
  }
6423
+ cleanupRemovedSessionRuntime(id);
6167
6424
  }
6168
6425
  });
6169
6426
  sessionManager.startReaper();
@@ -6221,6 +6478,7 @@ async function startService(options) {
6221
6478
  controlHandlers,
6222
6479
  permissionBroker
6223
6480
  });
6481
+ cleanupRemovedSessionRuntime = eventBridge.cleanupSessionResources;
6224
6482
  const jsonObserver = new JsonObserver({
6225
6483
  changeSessionState: eventBridge.changeSessionState,
6226
6484
  emitAgentStatus: eventBridge.emitAgentStatus
@@ -6259,10 +6517,11 @@ async function startService(options) {
6259
6517
  relayConnection,
6260
6518
  getProviderEnv,
6261
6519
  touchSessionActivity: eventBridge.touchSessionActivity,
6262
- applyPtyStateToSession: (sessionId, ptyState) => applyPtyStateToSession(ptyBridgeDeps, sessionId, ptyState),
6263
- onSessionClosed: eventBridge.cleanupSessionResources
6520
+ updateTerminalCwd: eventBridge.updateTerminalCwd,
6521
+ applyPtyStateToSession: (sessionId, ptyState) => applyPtyStateToSession(ptyBridgeDeps, sessionId, ptyState)
6264
6522
  });
6265
6523
  const terminalWorkerSpawner = new TerminalWorkerSpawner();
6524
+ const terminalSubscriptionBacklog = new TerminalSubscriptionBacklog();
6266
6525
  const remoteFileStreamManager = new RemoteFileStreamManager({
6267
6526
  relayConnection,
6268
6527
  sessionManager
@@ -6304,7 +6563,8 @@ async function startService(options) {
6304
6563
  getAgentCliSuggestions,
6305
6564
  setAgentCliPath,
6306
6565
  remoteFileStreamManager,
6307
- remoteFileUploadManager
6566
+ remoteFileUploadManager,
6567
+ terminalSubscriptionBacklog
6308
6568
  });
6309
6569
  relayConnection.on("message", (msg) => relayRouter.handle(msg));
6310
6570
  relayConnection.on("binary", (data) => {
@@ -6339,15 +6599,14 @@ async function startService(options) {
6339
6599
  sessionManager,
6340
6600
  workerRegistry,
6341
6601
  terminalSockets,
6602
+ terminalSubscriptionBacklog,
6342
6603
  hostedPtyRegistry,
6343
6604
  relayConnection,
6344
- controlHandlers,
6345
- agentStatusRegistry,
6346
6605
  permissionBroker,
6347
6606
  hookEventRouter: hookRuntime.hookEventRouter,
6348
6607
  createHookContext: hookRuntime.createHookContext,
6349
6608
  emitAgentStatus: eventBridge.emitAgentStatus,
6350
- cleanupSessionResources: eventBridge.cleanupSessionResources,
6609
+ updateTerminalCwd: eventBridge.updateTerminalCwd,
6351
6610
  config: statusConfig,
6352
6611
  resolveInterruptedApprovals: (sessionId) => resolveInterruptedApprovals(
6353
6612
  permissionBroker,