@dev-anywhere/proxy 0.6.0 → 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-KESS7BHQ.js";
67
+ } from "./chunk-CWWMDCRM.js";
61
68
  import {
62
69
  buildProviderEnv,
63
70
  loadConfig,
@@ -2173,6 +2180,18 @@ async function getFileTree(rootPath) {
2173
2180
  }
2174
2181
  function createControlMessageHandlers(send, sessionManager) {
2175
2182
  const sessionResources = /* @__PURE__ */ new Map();
2183
+ let sessionHistoryScanInFlight;
2184
+ function getSessionHistory() {
2185
+ if (sessionHistoryScanInFlight) return sessionHistoryScanInFlight;
2186
+ const scan = scanSessionHistory({ metadataPath: HISTORY_METADATA_PATH });
2187
+ const sharedScan = scan.finally(() => {
2188
+ if (sessionHistoryScanInFlight === sharedScan) {
2189
+ sessionHistoryScanInFlight = void 0;
2190
+ }
2191
+ });
2192
+ sessionHistoryScanInFlight = sharedScan;
2193
+ return sharedScan;
2194
+ }
2176
2195
  function getResources(sessionId) {
2177
2196
  let res = sessionResources.get(sessionId);
2178
2197
  if (!res) {
@@ -2284,7 +2303,7 @@ function createControlMessageHandlers(send, sessionManager) {
2284
2303
  },
2285
2304
  async handleSessionHistoryRequest(msg) {
2286
2305
  try {
2287
- const sessions = await scanSessionHistory({ metadataPath: HISTORY_METADATA_PATH });
2306
+ const sessions = await getSessionHistory();
2288
2307
  send(
2289
2308
  serializeControl({
2290
2309
  type: "session_history_response",
@@ -2699,6 +2718,16 @@ function mapCodexAppServerEvent(sessionId, seq, event) {
2699
2718
  }
2700
2719
 
2701
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
+ };
2702
2731
  var ANSI_ESCAPE_PATTERN2 = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
2703
2732
  function normalizeLocalCommandText2(content) {
2704
2733
  return content.replace(ANSI_ESCAPE_PATTERN2, "").replace(/<\/?local-command-(?:stdout|stderr)>/g, "").trim();
@@ -2731,6 +2760,7 @@ var WorkerRegistry = class {
2731
2760
  readyWaiters = /* @__PURE__ */ new Map();
2732
2761
  pendingNativeSessions = /* @__PURE__ */ new Map();
2733
2762
  assistantSnapshots = /* @__PURE__ */ new Map();
2763
+ startupFailures = /* @__PURE__ */ new Map();
2734
2764
  assistantTurnCounter = 0;
2735
2765
  onEnvelopeDropped(raw) {
2736
2766
  let parsed;
@@ -2758,6 +2788,8 @@ var WorkerRegistry = class {
2758
2788
  );
2759
2789
  }
2760
2790
  waitForReady(sessionId, timeoutMs = 15e3) {
2791
+ const startupFailure = this.startupFailures.get(sessionId);
2792
+ if (startupFailure) return Promise.reject(startupFailure);
2761
2793
  if (this.readySessions.has(sessionId)) return Promise.resolve();
2762
2794
  return new Promise((resolve3, reject) => {
2763
2795
  const timeout = setTimeout(() => {
@@ -2781,7 +2813,9 @@ var WorkerRegistry = class {
2781
2813
  args.push("--provider", options?.provider ?? "claude");
2782
2814
  if (options?.cwd) args.push("--cwd", options.cwd);
2783
2815
  if (options?.resumeSessionId) args.push("--resume", options.resumeSessionId);
2784
- 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);
2785
2819
  if (options?.streamDelta) {
2786
2820
  args.push("--stream-delta");
2787
2821
  }
@@ -2909,6 +2943,9 @@ var WorkerRegistry = class {
2909
2943
  hasProcess(sessionId) {
2910
2944
  return this.children.has(sessionId);
2911
2945
  }
2946
+ getStartupFailure(sessionId) {
2947
+ return this.startupFailures.get(sessionId);
2948
+ }
2912
2949
  delete(sessionId) {
2913
2950
  this.children.delete(sessionId);
2914
2951
  this.sockets.delete(sessionId);
@@ -2928,6 +2965,7 @@ var WorkerRegistry = class {
2928
2965
  this.readySessions.delete(sessionId);
2929
2966
  this.pendingNativeSessions.delete(sessionId);
2930
2967
  this.assistantSnapshots.delete(sessionId);
2968
+ this.startupFailures.delete(sessionId);
2931
2969
  this.children.delete(sessionId);
2932
2970
  this.rejectReadyWaiters(
2933
2971
  new Error(`Worker process terminated before ready: ${sessionId}`),
@@ -2951,11 +2989,13 @@ var WorkerRegistry = class {
2951
2989
  this.readySessions.clear();
2952
2990
  this.pendingNativeSessions.clear();
2953
2991
  this.assistantSnapshots.clear();
2992
+ this.startupFailures.clear();
2954
2993
  this.rejectReadyWaiters(new Error("Worker registry destroyed"));
2955
2994
  }
2956
2995
  handleWorkerMessage(sessionId, msg) {
2957
2996
  switch (msg.type) {
2958
2997
  case "worker_ready":
2998
+ this.startupFailures.delete(sessionId);
2959
2999
  if (msg.nativeSession) {
2960
3000
  this.captureNativeSession(sessionId, msg.nativeSession);
2961
3001
  }
@@ -2963,6 +3003,20 @@ var WorkerRegistry = class {
2963
3003
  this.resolveReadyWaiters(sessionId);
2964
3004
  serviceLogger.info({ sessionId, pid: msg.pid }, "Worker ready");
2965
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
+ }
2966
3020
  case "worker_event":
2967
3021
  try {
2968
3022
  this.forwardEvent(sessionId, msg.seq, msg.event);
@@ -2977,7 +3031,14 @@ var WorkerRegistry = class {
2977
3031
  case "worker_exit":
2978
3032
  this.deps.sessionManager.terminateSession(sessionId);
2979
3033
  this.delete(sessionId);
2980
- 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
+ );
2981
3042
  break;
2982
3043
  case "worker_interrupted":
2983
3044
  this.deps.permissionBroker.cleanupSession(sessionId, "Turn interrupted");
@@ -3840,10 +3901,104 @@ var RelayResourceHandlers = class {
3840
3901
 
3841
3902
  // src/serve/relay-session-create-handler.ts
3842
3903
  import { rmSync, statSync as statSync2 } from "fs";
3843
- import { homedir as homedir5 } from "os";
3844
- import { isAbsolute as isAbsolute4 } from "path";
3904
+ import { homedir as homedir6 } from "os";
3905
+ import { isAbsolute as isAbsolute5 } from "path";
3845
3906
  import { nanoid as nanoid3 } from "nanoid";
3846
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
+
3847
4002
  // src/serve/hosted-pty-registry.ts
3848
4003
  import * as pty from "node-pty";
3849
4004
  import pkg from "@xterm/headless";
@@ -3851,7 +4006,6 @@ import { SerializeAddon } from "@xterm/addon-serialize";
3851
4006
  var { Terminal: HeadlessTerminal } = pkg;
3852
4007
  var IDLE_CHECK_INTERVAL_MS = 3e3;
3853
4008
  var IDLE_THRESHOLD_MS = 3e3;
3854
- var STARTUP_EXIT_DIAGNOSTIC_WINDOW_MS = 1e4;
3855
4009
  var STARTUP_OUTPUT_PREVIEW_LIMIT = 8192;
3856
4010
  var PROVIDERS = {
3857
4011
  claude: CLAUDE_PROVIDER,
@@ -3859,9 +4013,6 @@ var PROVIDERS = {
3859
4013
  };
3860
4014
  var HOSTED_PTY_TERM = "xterm-256color";
3861
4015
  var HOSTED_PTY_COLORTERM = "truecolor";
3862
- var ANSI_OSC_RE = new RegExp(String.raw`\x1b\][^\x07]*(?:\x07|\x1b\\)`, "g");
3863
- var ANSI_CSI_RE = new RegExp(String.raw`\x1b\[[0-?]*[ -/]*[@-~]`, "g");
3864
- var ANSI_CHARSET_RE = new RegExp(String.raw`\x1b[()][A-Za-z0-9]`, "g");
3865
4016
  function buildHostedPtyArgs(provider, resumeSessionId) {
3866
4017
  if (!resumeSessionId) return [];
3867
4018
  return provider === "codex" ? ["resume", resumeSessionId] : ["--resume", resumeSessionId];
@@ -3882,12 +4033,8 @@ function normalizeHostedPtyEnv(env) {
3882
4033
  return normalized;
3883
4034
  }
3884
4035
  function appendStartupOutput(current, data) {
3885
- if (current.length >= STARTUP_OUTPUT_PREVIEW_LIMIT) return current;
3886
4036
  const next = current + data;
3887
- return next.length > STARTUP_OUTPUT_PREVIEW_LIMIT ? next.slice(0, STARTUP_OUTPUT_PREVIEW_LIMIT) : next;
3888
- }
3889
- function cleanPtyOutputPreview(output) {
3890
- 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;
3891
4038
  }
3892
4039
  var HostedPtyRegistry = class {
3893
4040
  constructor(deps) {
@@ -3930,6 +4077,8 @@ var HostedPtyRegistry = class {
3930
4077
  });
3931
4078
  const hosted = {
3932
4079
  kind,
4080
+ ...options.kind === "terminal" ? {} : { provider: options.provider },
4081
+ ...options.kind === "terminal" || !options.nativeSessionId ? {} : { nativeSessionId: options.nativeSessionId },
3933
4082
  child,
3934
4083
  terminal,
3935
4084
  serializeAddon,
@@ -3955,16 +4104,29 @@ var HostedPtyRegistry = class {
3955
4104
  const code = signal ? 128 + signal : exitCode;
3956
4105
  const current = this.sessions.get(options.sessionId);
3957
4106
  const uptimeMs = current ? Date.now() - current.startedAt : void 0;
3958
- const outputPreview = current ? cleanPtyOutputPreview(current.startupOutput) : "";
3959
- 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
+ }
3960
4122
  serviceLogger.info(
3961
4123
  {
3962
4124
  sessionId: options.sessionId,
3963
4125
  code,
3964
4126
  ...uptimeMs !== void 0 ? { uptimeMs } : {},
3965
- ...shouldIncludeStartupOutput ? {
3966
- startupOutputChars: current.startupOutput.length,
3967
- startupOutputPreview: outputPreview
4127
+ ...startupErrorTail ? {
4128
+ startupOutputChars: current?.startupOutput.length,
4129
+ startupErrorTail
3968
4130
  } : {}
3969
4131
  },
3970
4132
  "Hosted PTY exited"
@@ -4268,11 +4430,18 @@ async function waitForJsonWorkerStartup(options) {
4268
4430
  throwIfAborted(options.signal);
4269
4431
  }
4270
4432
  if (!socket) {
4433
+ const startupFailure2 = options.workerRegistry.getStartupFailure(options.sessionId);
4434
+ if (startupFailure2) throw startupFailure2;
4271
4435
  if (!options.workerRegistry.hasProcess(options.sessionId)) {
4272
4436
  throw new Error("JSON worker exited before opening its control socket");
4273
4437
  }
4274
4438
  continue;
4275
4439
  }
4440
+ const startupFailure = options.workerRegistry.getStartupFailure(options.sessionId);
4441
+ if (startupFailure) {
4442
+ socket.destroy();
4443
+ throw startupFailure;
4444
+ }
4276
4445
  if (!options.workerRegistry.hasProcess(options.sessionId)) {
4277
4446
  socket.destroy();
4278
4447
  throw new Error("JSON worker exited before reporting ready");
@@ -4301,7 +4470,7 @@ function validateSessionCwd(cwd) {
4301
4470
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
4302
4471
  }
4303
4472
  const trimmed = cwd.trim();
4304
- if (!isAbsolute4(trimmed)) {
4473
+ if (!isAbsolute5(trimmed)) {
4305
4474
  return { message: "\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84", code: ControlErrorCode.INVALID_PATH };
4306
4475
  }
4307
4476
  try {
@@ -4319,7 +4488,7 @@ function normalizeSessionName(name) {
4319
4488
  return trimmed ? trimmed : void 0;
4320
4489
  }
4321
4490
  function resolveTerminalCwd() {
4322
- const home = homedir5();
4491
+ const home = homedir6();
4323
4492
  if (home) {
4324
4493
  try {
4325
4494
  if (statSync2(home).isDirectory()) return home;
@@ -4359,6 +4528,69 @@ var RelaySessionCreateHandler = class {
4359
4528
  return;
4360
4529
  }
4361
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
+ }
4362
4594
  const cwdError = validateSessionCwd(cwd);
4363
4595
  if (cwdError) {
4364
4596
  this.deps.relaySend(
@@ -4373,9 +4605,6 @@ var RelaySessionCreateHandler = class {
4373
4605
  return;
4374
4606
  }
4375
4607
  const sessionCwd = typeof cwd === "string" ? cwd.trim() : "";
4376
- const provider = msg.provider ?? "claude";
4377
- const mode = msg.mode ?? "json";
4378
- const permissionMode = msg.permissionMode;
4379
4608
  if (mode === "pty") {
4380
4609
  this.createHostedPtySession(msg, sessionCwd, provider ?? "claude", permissionMode);
4381
4610
  return;
@@ -4392,7 +4621,6 @@ var RelaySessionCreateHandler = class {
4392
4621
  serviceLogger.warn({ provider }, "JSON session create rejected for unsupported provider");
4393
4622
  return;
4394
4623
  }
4395
- const resumeSessionId = msg.resumeSessionId;
4396
4624
  const streamDelta = true;
4397
4625
  const requestedName = normalizeSessionName(msg.name);
4398
4626
  const name = requestedName ?? tildify(sessionCwd);
@@ -4443,6 +4671,25 @@ var RelaySessionCreateHandler = class {
4443
4671
  );
4444
4672
  });
4445
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
+ }
4446
4693
  takePendingJsonCreate(sessionId) {
4447
4694
  if (!this.pendingJsonCreates.has(sessionId)) return false;
4448
4695
  this.pendingJsonCreates.delete(sessionId);
@@ -4506,19 +4753,28 @@ var RelaySessionCreateHandler = class {
4506
4753
  }
4507
4754
  reportJsonStartupFailure(requestId, sessionId, message, reason) {
4508
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;
4509
4763
  this.deps.relaySend(
4510
4764
  serializeControl({
4511
4765
  type: "session_create_response",
4512
4766
  requestId,
4513
4767
  sessionId,
4514
- errorCode: ControlErrorCode.WORKER_START_FAILED,
4515
- 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 } : {}
4516
4771
  })
4517
4772
  );
4518
4773
  serviceLogger.error(
4519
4774
  {
4520
4775
  sessionId,
4521
- error: reason instanceof Error ? reason.message : String(reason),
4776
+ ...startupErrorTail ? { startupErrorTail } : {},
4777
+ errorCode: activeWriterFailure?.errorCode,
4522
4778
  timedOut: message === WORKER_START_TIMEOUT_MESSAGE
4523
4779
  },
4524
4780
  "JSON worker startup failed via relay"
@@ -4563,6 +4819,7 @@ var RelaySessionCreateHandler = class {
4563
4819
  cwd,
4564
4820
  args: buildHostedPtyArgs(provider, resumeSessionId),
4565
4821
  permissionMode,
4822
+ nativeSessionId: resumeSessionId,
4566
4823
  hook,
4567
4824
  ...geometry
4568
4825
  });
@@ -4990,7 +5247,9 @@ var RelayRouter = class {
4990
5247
  createHookContext: deps.createHookContext,
4991
5248
  cleanupHookContext: deps.cleanupHookContext,
4992
5249
  broadcastSessionSync: deps.broadcastSessionSync,
4993
- broadcastSessionList: deps.broadcastSessionList
5250
+ broadcastSessionList: deps.broadcastSessionList,
5251
+ findCodexActiveWriter: deps.findCodexActiveWriter,
5252
+ findClosestAncestorPid: deps.findClosestAncestorPid
4994
5253
  });
4995
5254
  this.voiceSummaryHandler = new VoiceSummaryHandler({
4996
5255
  relaySend: deps.relaySend,
@@ -5798,7 +6057,7 @@ function createEventBridge(deps) {
5798
6057
 
5799
6058
  // src/serve/service-files.ts
5800
6059
  import { execSync } from "child_process";
5801
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
6060
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
5802
6061
  import { hostname } from "os";
5803
6062
  import { connect as connect2 } from "net";
5804
6063
  function tryConnectSocket(sockPath) {
@@ -5812,7 +6071,7 @@ function isProcessAlive(pid) {
5812
6071
  return processExistsOrIsInaccessible(pid);
5813
6072
  }
5814
6073
  async function cleanupStaleResources() {
5815
- if (existsSync5(SOCK_PATH)) {
6074
+ if (existsSync6(SOCK_PATH)) {
5816
6075
  const existing = await tryConnectSocket(SOCK_PATH);
5817
6076
  if (existing) {
5818
6077
  existing.destroy();
@@ -5825,7 +6084,7 @@ async function cleanupStaleResources() {
5825
6084
  unlinkIfPresent(SOCK_PATH);
5826
6085
  serviceLogger.info("Removed stale socket file");
5827
6086
  }
5828
- if (existsSync5(PID_PATH)) {
6087
+ if (existsSync6(PID_PATH)) {
5829
6088
  const pidStr = readFileSync5(PID_PATH, "utf-8").trim();
5830
6089
  const pid = parseInt(pidStr, 10);
5831
6090
  const probe = !isNaN(pid) ? probeProcess(pid) : null;
@@ -6083,7 +6342,14 @@ function handleTerminalConnection(socket, deps) {
6083
6342
  );
6084
6343
  sessionManager.terminateSession(msg.sessionId);
6085
6344
  terminalSockets.delete(msg.sessionId);
6086
- 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
+ );
6087
6353
  break;
6088
6354
  }
6089
6355
  case "pty_input": {
@@ -6189,7 +6455,7 @@ function handleTerminalConnection(socket, deps) {
6189
6455
 
6190
6456
  // src/serve/hook-registry.ts
6191
6457
  import { createHash as createHash2, randomBytes } from "crypto";
6192
- 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";
6193
6459
  import { dirname } from "path";
6194
6460
  import { z } from "zod";
6195
6461
  var PersistedHookSessionBindingSchema = z.object({
@@ -6250,7 +6516,7 @@ var HookRegistry = class {
6250
6516
  }
6251
6517
  }
6252
6518
  load() {
6253
- if (!this.persistPath || !existsSync6(this.persistPath)) return;
6519
+ if (!this.persistPath || !existsSync7(this.persistPath)) return;
6254
6520
  try {
6255
6521
  const parsed = PersistedHookRegistrySchema.parse(
6256
6522
  JSON.parse(readFileSync6(this.persistPath, "utf8"))
@@ -6539,9 +6805,9 @@ function createServeShutdown(deps) {
6539
6805
  // src/serve/remote-file-upload.ts
6540
6806
  import { createWriteStream, mkdirSync as mkdirSync2 } from "fs";
6541
6807
  import { tmpdir as tmpdir2 } from "os";
6542
- import { extname, join as join5 } from "path";
6808
+ import { extname, join as join6 } from "path";
6543
6809
  import { nanoid as nanoid4 } from "nanoid";
6544
- var DEFAULT_DATA_DIR = join5(tmpdir2(), "dev-anywhere");
6810
+ var DEFAULT_DATA_DIR = join6(tmpdir2(), "dev-anywhere");
6545
6811
  var SAFE_EXT_RE = /^[A-Za-z0-9]{1,6}$/;
6546
6812
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Map([
6547
6813
  ["image/png", "png"],
@@ -6557,9 +6823,9 @@ function uploadPathFor(msg, dataDir, suffix) {
6557
6823
  if (msg.kind === "clipboard_image") {
6558
6824
  const extension = IMAGE_EXTENSIONS.get(msg.mimeType);
6559
6825
  if (!extension) throw new Error("\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F");
6560
- return join5(dataDir, `paste-${suffix}.${extension}`);
6826
+ return join6(dataDir, `paste-${suffix}.${extension}`);
6561
6827
  }
6562
- return join5(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
6828
+ return join6(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
6563
6829
  }
6564
6830
  var RemoteFileUploadManager = class {
6565
6831
  constructor(deps) {
@@ -6704,8 +6970,8 @@ import { basename } from "path";
6704
6970
 
6705
6971
  // src/serve/remote-file-path.ts
6706
6972
  import { realpathSync } from "fs";
6707
- import { homedir as homedir6 } from "os";
6708
- 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";
6709
6975
  var EXT_MIME_MAP = {
6710
6976
  ".png": "image/png",
6711
6977
  ".jpg": "image/jpeg",
@@ -6739,8 +7005,8 @@ function guessMimeType(filePath) {
6739
7005
  return EXT_MIME_MAP[ext] ?? "application/octet-stream";
6740
7006
  }
6741
7007
  function resolveRemoteFilePath(rawPath, cwd) {
6742
- const expandedPath = rawPath === "~" || rawPath.startsWith("~/") ? resolve2(homedir6(), rawPath.slice(2)) : rawPath;
6743
- 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);
6744
7010
  return realpathSync(candidate);
6745
7011
  }
6746
7012
 
@@ -7026,6 +7292,10 @@ function parseServiceOptions(argv) {
7026
7292
  const relayName = arg.slice("--relay=".length);
7027
7293
  if (!relayName) throw new Error("Missing value for --relay");
7028
7294
  options.relayName = relayName;
7295
+ continue;
7296
+ }
7297
+ if (arg === "--preserve-stopped-marker") {
7298
+ options.preserveStoppedMarker = true;
7029
7299
  }
7030
7300
  }
7031
7301
  return options;
@@ -7033,9 +7303,11 @@ function parseServiceOptions(argv) {
7033
7303
  async function startService(options) {
7034
7304
  ensureProfileWorkspace();
7035
7305
  await cleanupStaleResources();
7036
- try {
7037
- unlinkSync2(STOPPED_PATH);
7038
- } catch {
7306
+ if (!options?.preserveStoppedMarker) {
7307
+ try {
7308
+ unlinkSync2(STOPPED_PATH);
7309
+ } catch {
7310
+ }
7039
7311
  }
7040
7312
  const permissionBroker = new PermissionBroker();
7041
7313
  const agentStatusRegistry = new AgentStatusRegistry();