@dev-anywhere/proxy 0.6.1 → 0.6.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.
package/dist/serve.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  probeProcess,
4
4
  processExistsOrIsInaccessible,
5
5
  unlinkIfPresent
6
- } from "./chunk-7R3UDY6R.js";
6
+ } from "./chunk-UHJRVS65.js";
7
7
  import {
8
8
  ContentBlockDeltaSchema,
9
9
  IGNORED_EVENT_TYPES,
@@ -18,12 +18,14 @@ import {
18
18
  decidePtySemanticTransition,
19
19
  shouldReleaseTextApprovalOnInput,
20
20
  shouldStartPtyTurnOnInput
21
- } from "./chunk-UTV3TB7J.js";
21
+ } from "./chunk-77NR262K.js";
22
22
  import {
23
23
  CLAUDE_PROVIDER,
24
24
  CODEX_PROVIDER,
25
- detectAgentCliStatus
26
- } from "./chunk-26JRYTYF.js";
25
+ CodexApprovalPolicyUnsupportedError,
26
+ detectAgentCliStatus,
27
+ resolveCodexPermissionPolicy
28
+ } from "./chunk-WX3ZHKAW.js";
27
29
  import {
28
30
  appendPtySemanticTextTail,
29
31
  capturePtySnapshot,
@@ -32,6 +34,11 @@ import {
32
34
  extractOscWorkingDirectory,
33
35
  extractTextSignals
34
36
  } from "./chunk-6D4UN567.js";
37
+ import {
38
+ classifyCodexActiveWriterError,
39
+ codexActiveWriterMessage,
40
+ sanitizeProviderErrorTail
41
+ } from "./chunk-J5V2TKSV.js";
35
42
  import {
36
43
  ControlErrorCode,
37
44
  MessageEnvelopeSchema,
@@ -57,7 +64,7 @@ import {
57
64
  serializeIpc,
58
65
  serializeWorkerMsg,
59
66
  summarizeToolActivity
60
- } from "./chunk-B6EXJMHW.js";
67
+ } from "./chunk-CWWMDCRM.js";
61
68
  import {
62
69
  buildProviderEnv,
63
70
  loadConfig,
@@ -2711,6 +2718,16 @@ function mapCodexAppServerEvent(sessionId, seq, event) {
2711
2718
  }
2712
2719
 
2713
2720
  // src/serve/worker-registry.ts
2721
+ var WorkerStartupError = class extends Error {
2722
+ constructor(message, errorCode2, nativeSessionId) {
2723
+ super(message);
2724
+ this.errorCode = errorCode2;
2725
+ this.nativeSessionId = nativeSessionId;
2726
+ this.name = "WorkerStartupError";
2727
+ }
2728
+ errorCode;
2729
+ nativeSessionId;
2730
+ };
2714
2731
  var ANSI_ESCAPE_PATTERN2 = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
2715
2732
  function normalizeLocalCommandText2(content) {
2716
2733
  return content.replace(ANSI_ESCAPE_PATTERN2, "").replace(/<\/?local-command-(?:stdout|stderr)>/g, "").trim();
@@ -2743,6 +2760,7 @@ var WorkerRegistry = class {
2743
2760
  readyWaiters = /* @__PURE__ */ new Map();
2744
2761
  pendingNativeSessions = /* @__PURE__ */ new Map();
2745
2762
  assistantSnapshots = /* @__PURE__ */ new Map();
2763
+ startupFailures = /* @__PURE__ */ new Map();
2746
2764
  assistantTurnCounter = 0;
2747
2765
  onEnvelopeDropped(raw) {
2748
2766
  let parsed;
@@ -2770,6 +2788,8 @@ var WorkerRegistry = class {
2770
2788
  );
2771
2789
  }
2772
2790
  waitForReady(sessionId, timeoutMs = 15e3) {
2791
+ const startupFailure = this.startupFailures.get(sessionId);
2792
+ if (startupFailure) return Promise.reject(startupFailure);
2773
2793
  if (this.readySessions.has(sessionId)) return Promise.resolve();
2774
2794
  return new Promise((resolve3, reject) => {
2775
2795
  const timeout = setTimeout(() => {
@@ -2793,7 +2813,9 @@ var WorkerRegistry = class {
2793
2813
  args.push("--provider", options?.provider ?? "claude");
2794
2814
  if (options?.cwd) args.push("--cwd", options.cwd);
2795
2815
  if (options?.resumeSessionId) args.push("--resume", options.resumeSessionId);
2796
- args.push("--permission-mode", options?.permissionMode ?? "default");
2816
+ const provider = options?.provider ?? "claude";
2817
+ const permissionMode = options?.permissionMode ?? (provider === "claude" ? "default" : void 0);
2818
+ if (permissionMode) args.push("--permission-mode", permissionMode);
2797
2819
  if (options?.streamDelta) {
2798
2820
  args.push("--stream-delta");
2799
2821
  }
@@ -2921,6 +2943,9 @@ var WorkerRegistry = class {
2921
2943
  hasProcess(sessionId) {
2922
2944
  return this.children.has(sessionId);
2923
2945
  }
2946
+ getStartupFailure(sessionId) {
2947
+ return this.startupFailures.get(sessionId);
2948
+ }
2924
2949
  delete(sessionId) {
2925
2950
  this.children.delete(sessionId);
2926
2951
  this.sockets.delete(sessionId);
@@ -2940,6 +2965,7 @@ var WorkerRegistry = class {
2940
2965
  this.readySessions.delete(sessionId);
2941
2966
  this.pendingNativeSessions.delete(sessionId);
2942
2967
  this.assistantSnapshots.delete(sessionId);
2968
+ this.startupFailures.delete(sessionId);
2943
2969
  this.children.delete(sessionId);
2944
2970
  this.rejectReadyWaiters(
2945
2971
  new Error(`Worker process terminated before ready: ${sessionId}`),
@@ -2963,11 +2989,13 @@ var WorkerRegistry = class {
2963
2989
  this.readySessions.clear();
2964
2990
  this.pendingNativeSessions.clear();
2965
2991
  this.assistantSnapshots.clear();
2992
+ this.startupFailures.clear();
2966
2993
  this.rejectReadyWaiters(new Error("Worker registry destroyed"));
2967
2994
  }
2968
2995
  handleWorkerMessage(sessionId, msg) {
2969
2996
  switch (msg.type) {
2970
2997
  case "worker_ready":
2998
+ this.startupFailures.delete(sessionId);
2971
2999
  if (msg.nativeSession) {
2972
3000
  this.captureNativeSession(sessionId, msg.nativeSession);
2973
3001
  }
@@ -2975,6 +3003,20 @@ var WorkerRegistry = class {
2975
3003
  this.resolveReadyWaiters(sessionId);
2976
3004
  serviceLogger.info({ sessionId, pid: msg.pid }, "Worker ready");
2977
3005
  break;
3006
+ case "worker_startup_error": {
3007
+ const startupError = new WorkerStartupError(
3008
+ msg.message,
3009
+ msg.errorCode,
3010
+ msg.nativeSessionId
3011
+ );
3012
+ this.startupFailures.set(sessionId, startupError);
3013
+ this.rejectReadyWaiters(startupError, sessionId);
3014
+ serviceLogger.warn(
3015
+ { sessionId, provider: msg.provider, errorCode: msg.errorCode, errorTail: msg.message },
3016
+ "JSON worker provider failed before ready"
3017
+ );
3018
+ break;
3019
+ }
2978
3020
  case "worker_event":
2979
3021
  try {
2980
3022
  this.forwardEvent(sessionId, msg.seq, msg.event);
@@ -2989,7 +3031,14 @@ var WorkerRegistry = class {
2989
3031
  case "worker_exit":
2990
3032
  this.deps.sessionManager.terminateSession(sessionId);
2991
3033
  this.delete(sessionId);
2992
- serviceLogger.info({ sessionId, exitCode: msg.code }, "JSON session exited");
3034
+ serviceLogger[msg.code === 0 ? "info" : "warn"](
3035
+ {
3036
+ sessionId,
3037
+ exitCode: msg.code,
3038
+ ...msg.errorTail ? { errorTail: msg.errorTail } : {}
3039
+ },
3040
+ "JSON session exited"
3041
+ );
2993
3042
  break;
2994
3043
  case "worker_interrupted":
2995
3044
  this.deps.permissionBroker.cleanupSession(sessionId, "Turn interrupted");
@@ -3852,10 +3901,104 @@ var RelayResourceHandlers = class {
3852
3901
 
3853
3902
  // src/serve/relay-session-create-handler.ts
3854
3903
  import { rmSync, statSync as statSync2 } from "fs";
3855
- import { homedir as homedir5 } from "os";
3856
- import { isAbsolute as isAbsolute4 } from "path";
3904
+ import { homedir as homedir6 } from "os";
3905
+ import { isAbsolute as isAbsolute5 } from "path";
3857
3906
  import { nanoid as nanoid3 } from "nanoid";
3858
3907
 
3908
+ // src/common/codex-active-writer.ts
3909
+ import { existsSync as existsSync5 } from "fs";
3910
+ import { homedir as homedir5 } from "os";
3911
+ import { isAbsolute as isAbsolute4, join as join5 } from "path";
3912
+ import { spawnSync } from "child_process";
3913
+ var CODEX_THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
3914
+ var LSOF_TIMEOUT_MS = 1e3;
3915
+ function findCodexActiveWriter(threadId, env = process.env) {
3916
+ if (!CODEX_THREAD_ID_RE.test(threadId)) return null;
3917
+ const configuredHome = env.CODEX_HOME?.trim();
3918
+ const codexHome = configuredHome && isAbsolute4(configuredHome) ? configuredHome : join5(homedir5(), ".codex");
3919
+ const lockPath = join5(codexHome, "thread-writer-locks", `${threadId}.lock`);
3920
+ if (!existsSync5(lockPath)) return null;
3921
+ const commands = process.platform === "darwin" ? ["/usr/sbin/lsof", "lsof"] : ["lsof"];
3922
+ for (const command of commands) {
3923
+ const result = spawnSync(command, ["-t", lockPath], {
3924
+ encoding: "utf8",
3925
+ timeout: LSOF_TIMEOUT_MS,
3926
+ maxBuffer: 64 * 1024,
3927
+ stdio: ["ignore", "pipe", "ignore"]
3928
+ });
3929
+ if (result.error && result.error.code === "ENOENT") continue;
3930
+ const pid = parseFirstPid(result.stdout);
3931
+ if (pid !== null) return { pid };
3932
+ if (!result.error) break;
3933
+ }
3934
+ return null;
3935
+ }
3936
+ function parseFirstPid(output) {
3937
+ const match = String(output ?? "").match(/(?:^|\s)(\d+)(?=\s|$)/);
3938
+ if (!match) return null;
3939
+ const pid = Number(match[1]);
3940
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
3941
+ }
3942
+
3943
+ // src/common/process-ancestry.ts
3944
+ import { spawnSync as spawnSync2 } from "child_process";
3945
+ var PROCESS_QUERY_TIMEOUT_MS = 1e3;
3946
+ var MAX_ANCESTRY_DEPTH = 64;
3947
+ function readParentProcessId(pid) {
3948
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;
3949
+ if (process.platform === "win32") {
3950
+ const script = `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").ParentProcessId`;
3951
+ const result = spawnSync2(
3952
+ "powershell.exe",
3953
+ ["-NoProfile", "-NonInteractive", "-Command", script],
3954
+ {
3955
+ encoding: "utf8",
3956
+ timeout: PROCESS_QUERY_TIMEOUT_MS,
3957
+ maxBuffer: 64 * 1024,
3958
+ stdio: ["ignore", "pipe", "ignore"]
3959
+ }
3960
+ );
3961
+ return result.error ? null : parseParentPid(result.stdout);
3962
+ }
3963
+ const commands = ["/bin/ps", "/usr/bin/ps", "ps"];
3964
+ const tried = /* @__PURE__ */ new Set();
3965
+ for (const command of commands) {
3966
+ if (tried.has(command)) continue;
3967
+ tried.add(command);
3968
+ const result = spawnSync2(command, ["-o", "ppid=", "-p", String(pid)], {
3969
+ encoding: "utf8",
3970
+ timeout: PROCESS_QUERY_TIMEOUT_MS,
3971
+ maxBuffer: 64 * 1024,
3972
+ stdio: ["ignore", "pipe", "ignore"]
3973
+ });
3974
+ if (result.error && result.error.code === "ENOENT") continue;
3975
+ return result.error ? null : parseParentPid(result.stdout);
3976
+ }
3977
+ return null;
3978
+ }
3979
+ function findClosestAncestorPid(processPid, candidatePids, lookupParent = readParentProcessId) {
3980
+ if (!Number.isSafeInteger(processPid) || processPid <= 0) return null;
3981
+ const candidates = new Set(candidatePids.filter((pid) => Number.isSafeInteger(pid) && pid > 0));
3982
+ if (candidates.size === 0) return null;
3983
+ const visited = /* @__PURE__ */ new Set();
3984
+ let current = processPid;
3985
+ for (let depth = 0; depth < MAX_ANCESTRY_DEPTH; depth += 1) {
3986
+ if (candidates.has(current)) return current;
3987
+ if (visited.has(current)) return null;
3988
+ visited.add(current);
3989
+ const parent = lookupParent(current);
3990
+ if (parent === null || parent <= 0 || parent === current) return null;
3991
+ current = parent;
3992
+ }
3993
+ return null;
3994
+ }
3995
+ function parseParentPid(output) {
3996
+ const match = String(output ?? "").match(/\d+/);
3997
+ if (!match) return null;
3998
+ const pid = Number(match[0]);
3999
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
4000
+ }
4001
+
3859
4002
  // src/serve/hosted-pty-registry.ts
3860
4003
  import * as pty from "node-pty";
3861
4004
  import pkg from "@xterm/headless";
@@ -3863,7 +4006,6 @@ import { SerializeAddon } from "@xterm/addon-serialize";
3863
4006
  var { Terminal: HeadlessTerminal } = pkg;
3864
4007
  var IDLE_CHECK_INTERVAL_MS = 3e3;
3865
4008
  var IDLE_THRESHOLD_MS = 3e3;
3866
- var STARTUP_EXIT_DIAGNOSTIC_WINDOW_MS = 1e4;
3867
4009
  var STARTUP_OUTPUT_PREVIEW_LIMIT = 8192;
3868
4010
  var PROVIDERS = {
3869
4011
  claude: CLAUDE_PROVIDER,
@@ -3871,9 +4013,6 @@ var PROVIDERS = {
3871
4013
  };
3872
4014
  var HOSTED_PTY_TERM = "xterm-256color";
3873
4015
  var HOSTED_PTY_COLORTERM = "truecolor";
3874
- var ANSI_OSC_RE = new RegExp(String.raw`\x1b\][^\x07]*(?:\x07|\x1b\\)`, "g");
3875
- var ANSI_CSI_RE = new RegExp(String.raw`\x1b\[[0-?]*[ -/]*[@-~]`, "g");
3876
- var ANSI_CHARSET_RE = new RegExp(String.raw`\x1b[()][A-Za-z0-9]`, "g");
3877
4016
  function buildHostedPtyArgs(provider, resumeSessionId) {
3878
4017
  if (!resumeSessionId) return [];
3879
4018
  return provider === "codex" ? ["resume", resumeSessionId] : ["--resume", resumeSessionId];
@@ -3894,12 +4033,8 @@ function normalizeHostedPtyEnv(env) {
3894
4033
  return normalized;
3895
4034
  }
3896
4035
  function appendStartupOutput(current, data) {
3897
- if (current.length >= STARTUP_OUTPUT_PREVIEW_LIMIT) return current;
3898
4036
  const next = current + data;
3899
- return next.length > STARTUP_OUTPUT_PREVIEW_LIMIT ? next.slice(0, STARTUP_OUTPUT_PREVIEW_LIMIT) : next;
3900
- }
3901
- function cleanPtyOutputPreview(output) {
3902
- return output.replace(ANSI_OSC_RE, "").replace(ANSI_CSI_RE, "").replace(ANSI_CHARSET_RE, "").replace(/\r/g, "\n").replace(/[^\t\n\x20-\x7e\u0080-\uffff]/g, "").replace(/\n{3,}/g, "\n\n").trim();
4037
+ return next.length > STARTUP_OUTPUT_PREVIEW_LIMIT ? next.slice(-STARTUP_OUTPUT_PREVIEW_LIMIT) : next;
3903
4038
  }
3904
4039
  var HostedPtyRegistry = class {
3905
4040
  constructor(deps) {
@@ -3942,6 +4077,8 @@ var HostedPtyRegistry = class {
3942
4077
  });
3943
4078
  const hosted = {
3944
4079
  kind,
4080
+ ...options.kind === "terminal" ? {} : { provider: options.provider },
4081
+ ...options.kind === "terminal" || !options.nativeSessionId ? {} : { nativeSessionId: options.nativeSessionId },
3945
4082
  child,
3946
4083
  terminal,
3947
4084
  serializeAddon,
@@ -3967,16 +4104,29 @@ var HostedPtyRegistry = class {
3967
4104
  const code = signal ? 128 + signal : exitCode;
3968
4105
  const current = this.sessions.get(options.sessionId);
3969
4106
  const uptimeMs = current ? Date.now() - current.startedAt : void 0;
3970
- const outputPreview = current ? cleanPtyOutputPreview(current.startupOutput) : "";
3971
- const shouldIncludeStartupOutput = current && uptimeMs !== void 0 && uptimeMs <= STARTUP_EXIT_DIAGNOSTIC_WINDOW_MS && outputPreview.length > 0;
4107
+ const startupErrorTail = code !== 0 && current ? sanitizeProviderErrorTail(current.startupOutput) : "";
4108
+ const activeWriter = code !== 0 && current?.provider === "codex" ? classifyCodexActiveWriterError(current.startupOutput) : null;
4109
+ const activeWriterThreadId = activeWriter?.threadId ?? (current?.provider === "codex" && current.nativeSessionId && /already has an active writer/i.test(current.startupOutput) ? current.nativeSessionId : null);
4110
+ if (activeWriterThreadId) {
4111
+ const writer = findCodexActiveWriter(activeWriterThreadId, this.deps.getProviderEnv());
4112
+ this.deps.relayConnection.sendRaw(
4113
+ serializeControl({
4114
+ type: "session_runtime_error",
4115
+ sessionId: options.sessionId,
4116
+ errorCode: ControlErrorCode.SESSION_ALREADY_ACTIVE,
4117
+ error: codexActiveWriterMessage(writer?.pid),
4118
+ ...writer ? { activeWriterPid: writer.pid } : {}
4119
+ })
4120
+ );
4121
+ }
3972
4122
  serviceLogger.info(
3973
4123
  {
3974
4124
  sessionId: options.sessionId,
3975
4125
  code,
3976
4126
  ...uptimeMs !== void 0 ? { uptimeMs } : {},
3977
- ...shouldIncludeStartupOutput ? {
3978
- startupOutputChars: current.startupOutput.length,
3979
- startupOutputPreview: outputPreview
4127
+ ...startupErrorTail ? {
4128
+ startupOutputChars: current?.startupOutput.length,
4129
+ startupErrorTail
3980
4130
  } : {}
3981
4131
  },
3982
4132
  "Hosted PTY exited"
@@ -4280,11 +4430,18 @@ async function waitForJsonWorkerStartup(options) {
4280
4430
  throwIfAborted(options.signal);
4281
4431
  }
4282
4432
  if (!socket) {
4433
+ const startupFailure2 = options.workerRegistry.getStartupFailure(options.sessionId);
4434
+ if (startupFailure2) throw startupFailure2;
4283
4435
  if (!options.workerRegistry.hasProcess(options.sessionId)) {
4284
4436
  throw new Error("JSON worker exited before opening its control socket");
4285
4437
  }
4286
4438
  continue;
4287
4439
  }
4440
+ const startupFailure = options.workerRegistry.getStartupFailure(options.sessionId);
4441
+ if (startupFailure) {
4442
+ socket.destroy();
4443
+ throw startupFailure;
4444
+ }
4288
4445
  if (!options.workerRegistry.hasProcess(options.sessionId)) {
4289
4446
  socket.destroy();
4290
4447
  throw new Error("JSON worker exited before reporting ready");
@@ -4313,7 +4470,7 @@ function validateSessionCwd(cwd) {
4313
4470
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
4314
4471
  }
4315
4472
  const trimmed = cwd.trim();
4316
- if (!isAbsolute4(trimmed)) {
4473
+ if (!isAbsolute5(trimmed)) {
4317
4474
  return { message: "\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84", code: ControlErrorCode.INVALID_PATH };
4318
4475
  }
4319
4476
  try {
@@ -4331,7 +4488,7 @@ function normalizeSessionName(name) {
4331
4488
  return trimmed ? trimmed : void 0;
4332
4489
  }
4333
4490
  function resolveTerminalCwd() {
4334
- const home = homedir5();
4491
+ const home = homedir6();
4335
4492
  if (home) {
4336
4493
  try {
4337
4494
  if (statSync2(home).isDirectory()) return home;
@@ -4371,6 +4528,69 @@ var RelaySessionCreateHandler = class {
4371
4528
  return;
4372
4529
  }
4373
4530
  const { requestId, cwd } = msg;
4531
+ const provider = msg.provider ?? "claude";
4532
+ const mode = msg.mode ?? "json";
4533
+ const permissionMode = msg.permissionMode;
4534
+ const resumeSessionId = msg.resumeSessionId;
4535
+ if (provider === "codex") {
4536
+ if (resumeSessionId) {
4537
+ const managedSessions = this.deps.sessionManager.listSessions();
4538
+ const existing = managedSessions.find(
4539
+ (session) => session.provider === "codex" && session.historySessionId === resumeSessionId
4540
+ );
4541
+ if (existing) {
4542
+ this.respondWithExistingSession(requestId, existing);
4543
+ return;
4544
+ }
4545
+ const activeWriter = (this.deps.findCodexActiveWriter ?? findCodexActiveWriter)(
4546
+ resumeSessionId,
4547
+ this.deps.getProviderEnv()
4548
+ );
4549
+ if (activeWriter) {
4550
+ const managedOwnerPid = (this.deps.findClosestAncestorPid ?? findClosestAncestorPid)(
4551
+ activeWriter.pid,
4552
+ managedSessions.map((session) => session.pid)
4553
+ );
4554
+ const managedOwner = managedOwnerPid === null ? void 0 : managedSessions.find((session) => session.pid === managedOwnerPid);
4555
+ if (managedOwner) {
4556
+ this.respondWithExistingSession(requestId, managedOwner);
4557
+ return;
4558
+ }
4559
+ this.deps.relaySend(
4560
+ serializeControl({
4561
+ type: "session_create_response",
4562
+ requestId,
4563
+ errorCode: ControlErrorCode.SESSION_ALREADY_ACTIVE,
4564
+ error: codexActiveWriterMessage(activeWriter.pid),
4565
+ activeWriterPid: activeWriter.pid
4566
+ })
4567
+ );
4568
+ serviceLogger.warn(
4569
+ { provider, nativeSessionId: resumeSessionId, pid: activeWriter.pid },
4570
+ "Codex resume rejected: native session already has an active writer"
4571
+ );
4572
+ return;
4573
+ }
4574
+ }
4575
+ try {
4576
+ resolveCodexPermissionPolicy(permissionMode);
4577
+ } catch (err) {
4578
+ if (!(err instanceof CodexApprovalPolicyUnsupportedError)) throw err;
4579
+ this.deps.relaySend(
4580
+ serializeControl({
4581
+ type: "session_create_response",
4582
+ requestId,
4583
+ errorCode: ControlErrorCode.APPROVAL_POLICY_UNSUPPORTED,
4584
+ error: err.message
4585
+ })
4586
+ );
4587
+ serviceLogger.warn(
4588
+ { provider, permissionMode },
4589
+ "Codex session create rejected: unsupported approval policy"
4590
+ );
4591
+ return;
4592
+ }
4593
+ }
4374
4594
  const cwdError = validateSessionCwd(cwd);
4375
4595
  if (cwdError) {
4376
4596
  this.deps.relaySend(
@@ -4385,9 +4605,6 @@ var RelaySessionCreateHandler = class {
4385
4605
  return;
4386
4606
  }
4387
4607
  const sessionCwd = typeof cwd === "string" ? cwd.trim() : "";
4388
- const provider = msg.provider ?? "claude";
4389
- const mode = msg.mode ?? "json";
4390
- const permissionMode = msg.permissionMode;
4391
4608
  if (mode === "pty") {
4392
4609
  this.createHostedPtySession(msg, sessionCwd, provider ?? "claude", permissionMode);
4393
4610
  return;
@@ -4404,7 +4621,6 @@ var RelaySessionCreateHandler = class {
4404
4621
  serviceLogger.warn({ provider }, "JSON session create rejected for unsupported provider");
4405
4622
  return;
4406
4623
  }
4407
- const resumeSessionId = msg.resumeSessionId;
4408
4624
  const streamDelta = true;
4409
4625
  const requestedName = normalizeSessionName(msg.name);
4410
4626
  const name = requestedName ?? tildify(sessionCwd);
@@ -4455,6 +4671,25 @@ var RelaySessionCreateHandler = class {
4455
4671
  );
4456
4672
  });
4457
4673
  }
4674
+ respondWithExistingSession(requestId, session) {
4675
+ this.deps.relaySend(
4676
+ serializeControl({
4677
+ type: "session_create_response",
4678
+ requestId,
4679
+ sessionId: session.id,
4680
+ ...session.kind !== void 0 ? { kind: session.kind } : {},
4681
+ ...session.name !== void 0 ? { name: session.name } : {},
4682
+ ...session.nameLocked !== void 0 ? { nameLocked: session.nameLocked } : {},
4683
+ mode: session.mode,
4684
+ provider: session.provider,
4685
+ ...session.ptyOwner !== void 0 ? { ptyOwner: session.ptyOwner } : {}
4686
+ })
4687
+ );
4688
+ serviceLogger.info(
4689
+ { sessionId: session.id, nativeSessionId: session.historySessionId },
4690
+ "Codex resume reused an existing DEV Anywhere session"
4691
+ );
4692
+ }
4458
4693
  takePendingJsonCreate(sessionId) {
4459
4694
  if (!this.pendingJsonCreates.has(sessionId)) return false;
4460
4695
  this.pendingJsonCreates.delete(sessionId);
@@ -4518,19 +4753,28 @@ var RelaySessionCreateHandler = class {
4518
4753
  }
4519
4754
  reportJsonStartupFailure(requestId, sessionId, message, reason) {
4520
4755
  this.cleanupPendingJsonSession(sessionId);
4756
+ const reasonText = reason instanceof Error ? reason.message : String(reason);
4757
+ const startupErrorTail = sanitizeProviderErrorTail(reasonText);
4758
+ const activeWriterFailure = reason instanceof WorkerStartupError && reason.errorCode === ControlErrorCode.SESSION_ALREADY_ACTIVE ? reason : null;
4759
+ const activeWriter = activeWriterFailure?.nativeSessionId ? (this.deps.findCodexActiveWriter ?? findCodexActiveWriter)(
4760
+ activeWriterFailure.nativeSessionId,
4761
+ this.deps.getProviderEnv()
4762
+ ) : null;
4521
4763
  this.deps.relaySend(
4522
4764
  serializeControl({
4523
4765
  type: "session_create_response",
4524
4766
  requestId,
4525
4767
  sessionId,
4526
- errorCode: ControlErrorCode.WORKER_START_FAILED,
4527
- error: message
4768
+ errorCode: activeWriterFailure ? ControlErrorCode.SESSION_ALREADY_ACTIVE : ControlErrorCode.WORKER_START_FAILED,
4769
+ error: activeWriterFailure ? codexActiveWriterMessage(activeWriter?.pid) : message,
4770
+ ...activeWriter ? { activeWriterPid: activeWriter.pid } : {}
4528
4771
  })
4529
4772
  );
4530
4773
  serviceLogger.error(
4531
4774
  {
4532
4775
  sessionId,
4533
- error: reason instanceof Error ? reason.message : String(reason),
4776
+ ...startupErrorTail ? { startupErrorTail } : {},
4777
+ errorCode: activeWriterFailure?.errorCode,
4534
4778
  timedOut: message === WORKER_START_TIMEOUT_MESSAGE
4535
4779
  },
4536
4780
  "JSON worker startup failed via relay"
@@ -4575,6 +4819,7 @@ var RelaySessionCreateHandler = class {
4575
4819
  cwd,
4576
4820
  args: buildHostedPtyArgs(provider, resumeSessionId),
4577
4821
  permissionMode,
4822
+ nativeSessionId: resumeSessionId,
4578
4823
  hook,
4579
4824
  ...geometry
4580
4825
  });
@@ -5002,7 +5247,9 @@ var RelayRouter = class {
5002
5247
  createHookContext: deps.createHookContext,
5003
5248
  cleanupHookContext: deps.cleanupHookContext,
5004
5249
  broadcastSessionSync: deps.broadcastSessionSync,
5005
- broadcastSessionList: deps.broadcastSessionList
5250
+ broadcastSessionList: deps.broadcastSessionList,
5251
+ findCodexActiveWriter: deps.findCodexActiveWriter,
5252
+ findClosestAncestorPid: deps.findClosestAncestorPid
5006
5253
  });
5007
5254
  this.voiceSummaryHandler = new VoiceSummaryHandler({
5008
5255
  relaySend: deps.relaySend,
@@ -5810,7 +6057,7 @@ function createEventBridge(deps) {
5810
6057
 
5811
6058
  // src/serve/service-files.ts
5812
6059
  import { execSync } from "child_process";
5813
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
6060
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
5814
6061
  import { hostname } from "os";
5815
6062
  import { connect as connect2 } from "net";
5816
6063
  function tryConnectSocket(sockPath) {
@@ -5824,7 +6071,7 @@ function isProcessAlive(pid) {
5824
6071
  return processExistsOrIsInaccessible(pid);
5825
6072
  }
5826
6073
  async function cleanupStaleResources() {
5827
- if (existsSync5(SOCK_PATH)) {
6074
+ if (existsSync6(SOCK_PATH)) {
5828
6075
  const existing = await tryConnectSocket(SOCK_PATH);
5829
6076
  if (existing) {
5830
6077
  existing.destroy();
@@ -5837,7 +6084,7 @@ async function cleanupStaleResources() {
5837
6084
  unlinkIfPresent(SOCK_PATH);
5838
6085
  serviceLogger.info("Removed stale socket file");
5839
6086
  }
5840
- if (existsSync5(PID_PATH)) {
6087
+ if (existsSync6(PID_PATH)) {
5841
6088
  const pidStr = readFileSync5(PID_PATH, "utf-8").trim();
5842
6089
  const pid = parseInt(pidStr, 10);
5843
6090
  const probe = !isNaN(pid) ? probeProcess(pid) : null;
@@ -6095,7 +6342,14 @@ function handleTerminalConnection(socket, deps) {
6095
6342
  );
6096
6343
  sessionManager.terminateSession(msg.sessionId);
6097
6344
  terminalSockets.delete(msg.sessionId);
6098
- serviceLogger.info({ sessionId: msg.sessionId }, "PTY session deregistered");
6345
+ serviceLogger[msg.exitCode === void 0 || msg.exitCode === 0 ? "info" : "warn"](
6346
+ {
6347
+ sessionId: msg.sessionId,
6348
+ ...msg.exitCode !== void 0 ? { exitCode: msg.exitCode } : {},
6349
+ ...msg.errorTail ? { errorTail: msg.errorTail } : {}
6350
+ },
6351
+ "PTY session deregistered"
6352
+ );
6099
6353
  break;
6100
6354
  }
6101
6355
  case "pty_input": {
@@ -6201,7 +6455,7 @@ function handleTerminalConnection(socket, deps) {
6201
6455
 
6202
6456
  // src/serve/hook-registry.ts
6203
6457
  import { createHash as createHash2, randomBytes } from "crypto";
6204
- import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, renameSync, writeFileSync } from "fs";
6458
+ import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync6, renameSync, writeFileSync } from "fs";
6205
6459
  import { dirname } from "path";
6206
6460
  import { z } from "zod";
6207
6461
  var PersistedHookSessionBindingSchema = z.object({
@@ -6262,7 +6516,7 @@ var HookRegistry = class {
6262
6516
  }
6263
6517
  }
6264
6518
  load() {
6265
- if (!this.persistPath || !existsSync6(this.persistPath)) return;
6519
+ if (!this.persistPath || !existsSync7(this.persistPath)) return;
6266
6520
  try {
6267
6521
  const parsed = PersistedHookRegistrySchema.parse(
6268
6522
  JSON.parse(readFileSync6(this.persistPath, "utf8"))
@@ -6551,9 +6805,9 @@ function createServeShutdown(deps) {
6551
6805
  // src/serve/remote-file-upload.ts
6552
6806
  import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
6553
6807
  import { tmpdir as tmpdir2 } from "os";
6554
- import { extname, join as join5 } from "path";
6808
+ import { extname, join as join6 } from "path";
6555
6809
  import { nanoid as nanoid4 } from "nanoid";
6556
- var DEFAULT_DATA_DIR = join5(tmpdir2(), "dev-anywhere");
6810
+ var DEFAULT_DATA_DIR = join6(tmpdir2(), "dev-anywhere");
6557
6811
  var SAFE_EXT_RE = /^[A-Za-z0-9]{1,6}$/;
6558
6812
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Map([
6559
6813
  ["image/png", "png"],
@@ -6569,9 +6823,9 @@ function uploadPathFor(msg, dataDir, suffix) {
6569
6823
  if (msg.kind === "clipboard_image") {
6570
6824
  const extension = IMAGE_EXTENSIONS.get(msg.mimeType);
6571
6825
  if (!extension) throw new Error("\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F");
6572
- return join5(dataDir, `paste-${suffix}.${extension}`);
6826
+ return join6(dataDir, `paste-${suffix}.${extension}`);
6573
6827
  }
6574
- return join5(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
6828
+ return join6(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
6575
6829
  }
6576
6830
  var RemoteFileUploadManager = class {
6577
6831
  constructor(deps) {
@@ -6716,8 +6970,8 @@ import { basename } from "path";
6716
6970
 
6717
6971
  // src/serve/remote-file-path.ts
6718
6972
  import { realpathSync } from "fs";
6719
- import { homedir as homedir6 } from "os";
6720
- import { extname as extname2, isAbsolute as isAbsolute5, resolve as resolve2 } from "path";
6973
+ import { homedir as homedir7 } from "os";
6974
+ import { extname as extname2, isAbsolute as isAbsolute6, resolve as resolve2 } from "path";
6721
6975
  var EXT_MIME_MAP = {
6722
6976
  ".png": "image/png",
6723
6977
  ".jpg": "image/jpeg",
@@ -6751,8 +7005,8 @@ function guessMimeType(filePath) {
6751
7005
  return EXT_MIME_MAP[ext] ?? "application/octet-stream";
6752
7006
  }
6753
7007
  function resolveRemoteFilePath(rawPath, cwd) {
6754
- const expandedPath = rawPath === "~" || rawPath.startsWith("~/") ? resolve2(homedir6(), rawPath.slice(2)) : rawPath;
6755
- const candidate = isAbsolute5(expandedPath) ? resolve2(expandedPath) : resolve2(cwd, expandedPath);
7008
+ const expandedPath = rawPath === "~" || rawPath.startsWith("~/") ? resolve2(homedir7(), rawPath.slice(2)) : rawPath;
7009
+ const candidate = isAbsolute6(expandedPath) ? resolve2(expandedPath) : resolve2(cwd, expandedPath);
6756
7010
  return realpathSync(candidate);
6757
7011
  }
6758
7012
 
@@ -7038,6 +7292,10 @@ function parseServiceOptions(argv) {
7038
7292
  const relayName = arg.slice("--relay=".length);
7039
7293
  if (!relayName) throw new Error("Missing value for --relay");
7040
7294
  options.relayName = relayName;
7295
+ continue;
7296
+ }
7297
+ if (arg === "--preserve-stopped-marker") {
7298
+ options.preserveStoppedMarker = true;
7041
7299
  }
7042
7300
  }
7043
7301
  return options;
@@ -7045,9 +7303,11 @@ function parseServiceOptions(argv) {
7045
7303
  async function startService(options) {
7046
7304
  ensureProfileWorkspace();
7047
7305
  await cleanupStaleResources();
7048
- try {
7049
- unlinkSync2(STOPPED_PATH);
7050
- } catch {
7306
+ if (!options?.preserveStoppedMarker) {
7307
+ try {
7308
+ unlinkSync2(STOPPED_PATH);
7309
+ } catch {
7310
+ }
7051
7311
  }
7052
7312
  const permissionBroker = new PermissionBroker();
7053
7313
  const agentStatusRegistry = new AgentStatusRegistry();