@dev-anywhere/proxy 0.4.61 → 0.4.63

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-NSTB3QRJ.js";
6
+ } from "./chunk-7R3UDY6R.js";
7
7
  import {
8
8
  ContentBlockDeltaSchema,
9
9
  IGNORED_EVENT_TYPES,
@@ -45,7 +45,7 @@ import {
45
45
  serializeControl,
46
46
  serializeIpc,
47
47
  serializeWorkerMsg
48
- } from "./chunk-5KUGAC5S.js";
48
+ } from "./chunk-JUW7S24L.js";
49
49
  import {
50
50
  buildProviderEnv,
51
51
  loadConfig,
@@ -1800,25 +1800,142 @@ function createControlMessageHandlers(send, sessionManager) {
1800
1800
  // src/serve/worker-registry.ts
1801
1801
  import { connect } from "net";
1802
1802
  import { unlinkSync, existsSync as existsSync4, readdirSync as readdirSync2 } from "fs";
1803
- var ANSI_ESCAPE_PATTERN2 = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
1804
- function normalizeLocalCommandText2(content) {
1805
- return content.replace(ANSI_ESCAPE_PATTERN2, "").replace(/<\/?local-command-(?:stdout|stderr)>/g, "").trim();
1806
- }
1807
- function parseCompactCommandOutcome(content) {
1808
- const normalized = normalizeLocalCommandText2(content);
1809
- if (!normalized) return null;
1810
- if (content.includes("<local-command-stderr>")) {
1811
- let detail = normalized.replace(/^Error:\s*/i, "").replace(/^Error during compaction:\s*/i, "").trim();
1812
- if (/No messages to compact/i.test(detail)) {
1813
- return { success: true, message: "\u6CA1\u6709\u53EF\u538B\u7F29\u7684\u4E0A\u4E0B\u6587\u3002" };
1803
+
1804
+ // src/serve/claude-stream-event-mapper.ts
1805
+ function mapClaudeStreamEvent(sessionId, seq, options) {
1806
+ const { event, isStreamDeltaSession, isCompactingSession } = options;
1807
+ if (event.type === "stream_event") {
1808
+ const delta = ContentBlockDeltaSchema.safeParse(event.event);
1809
+ if (!delta.success) return [];
1810
+ const d = delta.data.delta;
1811
+ if (d.type === "text_delta" && d.text) {
1812
+ return [
1813
+ {
1814
+ kind: "envelope",
1815
+ envelope: buildMessage(
1816
+ "assistant_message",
1817
+ sessionId,
1818
+ seq,
1819
+ { text: d.text, isPartial: true },
1820
+ "proxy"
1821
+ )
1822
+ }
1823
+ ];
1814
1824
  }
1815
- if (!detail) detail = "\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";
1816
- return { success: false, message: `\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\uFF1A${detail}` };
1825
+ if (d.type === "thinking_delta" && d.thinking) {
1826
+ return [
1827
+ {
1828
+ kind: "envelope",
1829
+ envelope: buildMessage("thinking", sessionId, seq, { text: d.thinking }, "proxy")
1830
+ }
1831
+ ];
1832
+ }
1833
+ return [];
1817
1834
  }
1818
- if (content.includes("<local-command-stdout>") || /\bCompacted\b/i.test(normalized)) {
1819
- return { success: true, message: "\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u3002" };
1835
+ if (event.type === "assistant") {
1836
+ const mapped = [];
1837
+ let forwardedContent = false;
1838
+ for (const raw of event.message.content) {
1839
+ const blockParse = KnownContentBlockSchema.safeParse(raw);
1840
+ if (!blockParse.success) {
1841
+ const blockType = raw && typeof raw === "object" ? raw.type : void 0;
1842
+ mapped.push({ kind: "unknown_assistant_block", blockType: blockType ?? "<missing>" });
1843
+ continue;
1844
+ }
1845
+ const block = blockParse.data;
1846
+ if (block.type === "text") {
1847
+ if (!isStreamDeltaSession && block.text) {
1848
+ forwardedContent = true;
1849
+ mapped.push({
1850
+ kind: "envelope",
1851
+ envelope: buildMessage(
1852
+ "assistant_message",
1853
+ sessionId,
1854
+ seq,
1855
+ { text: block.text, isPartial: true },
1856
+ "proxy"
1857
+ )
1858
+ });
1859
+ }
1860
+ } else if (block.type === "thinking") {
1861
+ if (!isStreamDeltaSession && block.thinking) {
1862
+ forwardedContent = true;
1863
+ mapped.push({
1864
+ kind: "envelope",
1865
+ envelope: buildMessage("thinking", sessionId, seq, { text: block.thinking }, "proxy")
1866
+ });
1867
+ }
1868
+ } else if (block.type === "tool_use") {
1869
+ forwardedContent = true;
1870
+ mapped.push({
1871
+ kind: "envelope",
1872
+ envelope: buildMessage(
1873
+ "assistant_tool_use",
1874
+ sessionId,
1875
+ seq,
1876
+ { toolName: block.name, toolId: block.id, parameters: block.input },
1877
+ "proxy"
1878
+ )
1879
+ });
1880
+ }
1881
+ }
1882
+ if (forwardedContent && isCompactingSession) {
1883
+ mapped.push({
1884
+ kind: "control",
1885
+ raw: serializeControl({
1886
+ type: "turn_result",
1887
+ sessionId,
1888
+ success: true,
1889
+ isError: false
1890
+ }),
1891
+ notifyTurnResult: true
1892
+ });
1893
+ }
1894
+ return mapped;
1820
1895
  }
1821
- return null;
1896
+ if (event.type === "user") {
1897
+ if (typeof event.message.content === "string") return [];
1898
+ return event.message.content.flatMap((raw) => {
1899
+ const blockParse = KnownContentBlockSchema.safeParse(raw);
1900
+ if (!blockParse.success) return [];
1901
+ const block = blockParse.data;
1902
+ if (block.type !== "tool_result") return [];
1903
+ return [
1904
+ {
1905
+ kind: "envelope",
1906
+ envelope: buildMessage(
1907
+ "tool_result",
1908
+ sessionId,
1909
+ seq,
1910
+ { toolId: block.tool_use_id, result: block.content, isError: block.is_error ?? false },
1911
+ "proxy"
1912
+ )
1913
+ }
1914
+ ];
1915
+ });
1916
+ }
1917
+ if (event.type === "result") {
1918
+ const resultText = typeof event.result === "string" ? event.result : void 0;
1919
+ return [
1920
+ {
1921
+ kind: "control",
1922
+ raw: serializeControl({
1923
+ type: "turn_result",
1924
+ sessionId,
1925
+ success: event.subtype === "success",
1926
+ isError: event.is_error ?? false,
1927
+ ...resultText ? { result: resultText } : {}
1928
+ }),
1929
+ notifyTurnResult: true
1930
+ }
1931
+ ];
1932
+ }
1933
+ return [];
1934
+ }
1935
+
1936
+ // src/serve/codex-app-server-event-mapper.ts
1937
+ function isRecord(value) {
1938
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
1822
1939
  }
1823
1940
  function codexPatchKind(kind) {
1824
1941
  if (typeof kind === "string") return { kind };
@@ -1855,6 +1972,135 @@ function codexPatchParameters(item) {
1855
1972
  status: typeof item.status === "string" ? item.status : void 0
1856
1973
  };
1857
1974
  }
1975
+ function mapCodexAppServerEvent(sessionId, seq, event) {
1976
+ const method = typeof event.method === "string" ? event.method : "";
1977
+ const params = isRecord(event.params) ? event.params : {};
1978
+ if (method === "item/agentMessage/delta") {
1979
+ const delta = typeof params.delta === "string" ? params.delta : "";
1980
+ if (!delta) return [];
1981
+ return [
1982
+ {
1983
+ kind: "envelope",
1984
+ envelope: buildMessage(
1985
+ "assistant_message",
1986
+ sessionId,
1987
+ seq,
1988
+ { text: delta, isPartial: true },
1989
+ "proxy"
1990
+ )
1991
+ }
1992
+ ];
1993
+ }
1994
+ const item = isRecord(params.item) ? params.item : null;
1995
+ if ((method === "item/started" || method === "item/completed") && item?.type === "fileChange") {
1996
+ const id = typeof item.id === "string" ? item.id : "";
1997
+ if (!id) return [];
1998
+ const status = typeof item.status === "string" ? item.status : "";
1999
+ const mapped = [
2000
+ {
2001
+ kind: "envelope",
2002
+ envelope: buildMessage(
2003
+ "assistant_tool_use",
2004
+ sessionId,
2005
+ seq,
2006
+ { toolName: "Patch", toolId: id, parameters: codexPatchParameters(item) },
2007
+ "proxy"
2008
+ )
2009
+ }
2010
+ ];
2011
+ if (method === "item/completed") {
2012
+ mapped.push({
2013
+ kind: "envelope",
2014
+ envelope: buildMessage(
2015
+ "tool_result",
2016
+ sessionId,
2017
+ seq,
2018
+ { toolId: id, result: status || "completed", isError: status === "failed" },
2019
+ "proxy"
2020
+ )
2021
+ });
2022
+ }
2023
+ return mapped;
2024
+ }
2025
+ if (method === "item/started" && item?.type === "commandExecution") {
2026
+ const id = typeof item.id === "string" ? item.id : "";
2027
+ if (!id) return [];
2028
+ const command = typeof item.command === "string" ? item.command : "";
2029
+ const cwd = typeof item.cwd === "string" ? item.cwd : "";
2030
+ return [
2031
+ {
2032
+ kind: "envelope",
2033
+ envelope: buildMessage(
2034
+ "assistant_tool_use",
2035
+ sessionId,
2036
+ seq,
2037
+ { toolName: "Bash", toolId: id, parameters: { command, cwd } },
2038
+ "proxy"
2039
+ )
2040
+ }
2041
+ ];
2042
+ }
2043
+ if (method === "item/completed" && item?.type === "commandExecution") {
2044
+ const id = typeof item.id === "string" ? item.id : "";
2045
+ if (!id) return [];
2046
+ const output = typeof item.aggregatedOutput === "string" ? item.aggregatedOutput : "";
2047
+ const exitCode = typeof item.exitCode === "number" ? item.exitCode : null;
2048
+ return [
2049
+ {
2050
+ kind: "envelope",
2051
+ envelope: buildMessage(
2052
+ "tool_result",
2053
+ sessionId,
2054
+ seq,
2055
+ { toolId: id, result: output, isError: exitCode !== null && exitCode !== 0 },
2056
+ "proxy"
2057
+ )
2058
+ }
2059
+ ];
2060
+ }
2061
+ if (method === "turn/completed") {
2062
+ const turn = isRecord(params.turn) ? params.turn : {};
2063
+ const status = turn.status;
2064
+ const error = turn.error;
2065
+ const success = status === "completed";
2066
+ return [
2067
+ {
2068
+ kind: "control",
2069
+ raw: serializeControl({
2070
+ type: "turn_result",
2071
+ sessionId,
2072
+ success,
2073
+ isError: !success,
2074
+ ...error ? { result: String(error) } : {}
2075
+ }),
2076
+ notifyTurnResult: true
2077
+ }
2078
+ ];
2079
+ }
2080
+ return [];
2081
+ }
2082
+
2083
+ // src/serve/worker-registry.ts
2084
+ var ANSI_ESCAPE_PATTERN2 = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
2085
+ function normalizeLocalCommandText2(content) {
2086
+ return content.replace(ANSI_ESCAPE_PATTERN2, "").replace(/<\/?local-command-(?:stdout|stderr)>/g, "").trim();
2087
+ }
2088
+ function parseCompactCommandOutcome(content) {
2089
+ const normalized = normalizeLocalCommandText2(content);
2090
+ if (!normalized) return null;
2091
+ if (content.includes("<local-command-stderr>")) {
2092
+ let detail = normalized.replace(/^Error:\s*/i, "").replace(/^Error during compaction:\s*/i, "").trim();
2093
+ if (/No messages to compact/i.test(detail)) {
2094
+ return { success: true, message: "\u6CA1\u6709\u53EF\u538B\u7F29\u7684\u4E0A\u4E0B\u6587\u3002" };
2095
+ }
2096
+ if (!detail) detail = "\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";
2097
+ return { success: false, message: `\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\uFF1A${detail}` };
2098
+ }
2099
+ if (content.includes("<local-command-stdout>") || /\bCompacted\b/i.test(normalized)) {
2100
+ return { success: true, message: "\u4E0A\u4E0B\u6587\u538B\u7F29\u5B8C\u6210\u3002" };
2101
+ }
2102
+ return null;
2103
+ }
1858
2104
  var WorkerRegistry = class {
1859
2105
  constructor(deps) {
1860
2106
  this.deps = deps;
@@ -1863,6 +2109,8 @@ var WorkerRegistry = class {
1863
2109
  deps;
1864
2110
  sockets = /* @__PURE__ */ new Map();
1865
2111
  children = /* @__PURE__ */ new Map();
2112
+ readySessions = /* @__PURE__ */ new Set();
2113
+ readyWaiters = /* @__PURE__ */ new Map();
1866
2114
  // 记录哪些 session 是 spawn 时带 --stream-delta 的;forwardEvent 据此决定是否跳过 aggregated 去重
1867
2115
  streamDeltaSessions = /* @__PURE__ */ new Set();
1868
2116
  onEnvelopeDropped(raw) {
@@ -1890,6 +2138,24 @@ var WorkerRegistry = class {
1890
2138
  "Tool approval request lost to relay queue overflow, denying worker"
1891
2139
  );
1892
2140
  }
2141
+ waitForReady(sessionId, timeoutMs = 15e3) {
2142
+ if (this.readySessions.has(sessionId)) return Promise.resolve();
2143
+ return new Promise((resolve4, reject) => {
2144
+ const timeout = setTimeout(() => {
2145
+ const waiters2 = this.readyWaiters.get(sessionId);
2146
+ if (waiters2) {
2147
+ waiters2.delete(waiter);
2148
+ if (waiters2.size === 0) this.readyWaiters.delete(sessionId);
2149
+ }
2150
+ reject(new Error(`Worker did not report ready within ${timeoutMs}ms`));
2151
+ }, timeoutMs);
2152
+ timeout.unref?.();
2153
+ const waiter = { resolve: resolve4, reject, timeout };
2154
+ const waiters = this.readyWaiters.get(sessionId) ?? /* @__PURE__ */ new Set();
2155
+ waiters.add(waiter);
2156
+ this.readyWaiters.set(sessionId, waiters);
2157
+ });
2158
+ }
1893
2159
  spawn(sessionId, options) {
1894
2160
  const paths = sessionPaths(sessionId);
1895
2161
  const args = [sessionId, paths.workerSock];
@@ -1982,15 +2248,25 @@ var WorkerRegistry = class {
1982
2248
  delete(sessionId) {
1983
2249
  this.children.delete(sessionId);
1984
2250
  this.sockets.delete(sessionId);
2251
+ this.readySessions.delete(sessionId);
1985
2252
  this.streamDeltaSessions.delete(sessionId);
2253
+ this.rejectReadyWaiters(
2254
+ new Error(`Worker session deleted before ready: ${sessionId}`),
2255
+ sessionId
2256
+ );
1986
2257
  }
1987
2258
  terminateProcess(sessionId, signal = "SIGTERM") {
1988
2259
  const child = this.children.get(sessionId);
1989
2260
  const sock = this.sockets.get(sessionId);
1990
2261
  sock?.destroy();
1991
2262
  this.sockets.delete(sessionId);
2263
+ this.readySessions.delete(sessionId);
1992
2264
  this.streamDeltaSessions.delete(sessionId);
1993
2265
  this.children.delete(sessionId);
2266
+ this.rejectReadyWaiters(
2267
+ new Error(`Worker process terminated before ready: ${sessionId}`),
2268
+ sessionId
2269
+ );
1994
2270
  if (!child || child.killed) return false;
1995
2271
  return child.kill(signal);
1996
2272
  }
@@ -2006,10 +2282,14 @@ var WorkerRegistry = class {
2006
2282
  ws.destroy();
2007
2283
  }
2008
2284
  this.sockets.clear();
2285
+ this.readySessions.clear();
2286
+ this.rejectReadyWaiters(new Error("Worker registry destroyed"));
2009
2287
  }
2010
2288
  handleWorkerMessage(sessionId, msg) {
2011
2289
  switch (msg.type) {
2012
2290
  case "worker_ready":
2291
+ this.readySessions.add(sessionId);
2292
+ this.resolveReadyWaiters(sessionId);
2013
2293
  serviceLogger.info({ sessionId, pid: msg.pid }, "Worker ready");
2014
2294
  break;
2015
2295
  case "worker_event":
@@ -2074,11 +2354,33 @@ var WorkerRegistry = class {
2074
2354
  // worker 连接断开或异常时的统一清理入口。仅记录一份,不再区分 close vs error 语义。
2075
2355
  onDisconnect(sessionId) {
2076
2356
  this.sockets.delete(sessionId);
2357
+ this.readySessions.delete(sessionId);
2358
+ this.rejectReadyWaiters(new Error(`Worker disconnected before ready: ${sessionId}`), sessionId);
2077
2359
  this.deps.permissionBroker.cleanupSession(sessionId, "Worker disconnected");
2078
2360
  if (this.deps.sessionManager.getSession(sessionId)) {
2079
2361
  this.deps.jsonObserver.onChannelBroken(sessionId);
2080
2362
  }
2081
2363
  }
2364
+ resolveReadyWaiters(sessionId) {
2365
+ const waiters = this.readyWaiters.get(sessionId);
2366
+ if (!waiters) return;
2367
+ this.readyWaiters.delete(sessionId);
2368
+ for (const waiter of waiters) {
2369
+ clearTimeout(waiter.timeout);
2370
+ waiter.resolve();
2371
+ }
2372
+ }
2373
+ rejectReadyWaiters(err, sessionId) {
2374
+ const entries = sessionId === void 0 ? [...this.readyWaiters.entries()] : [[sessionId, this.readyWaiters.get(sessionId)]];
2375
+ for (const [sid, waiters] of entries) {
2376
+ if (!waiters) continue;
2377
+ this.readyWaiters.delete(sid);
2378
+ for (const waiter of waiters) {
2379
+ clearTimeout(waiter.timeout);
2380
+ waiter.reject(err);
2381
+ }
2382
+ }
2383
+ }
2082
2384
  // 对齐 Claude CLI stream-json 输出,按 type 分发:
2083
2385
  // stream_event.content_block_delta → 增量 text/thinking envelope(仅 streamDelta 会话产生)
2084
2386
  // assistant.content[].text → assistant_message envelope(streamDelta 下跳过,避免重复)
@@ -2119,206 +2421,40 @@ var WorkerRegistry = class {
2119
2421
  );
2120
2422
  return;
2121
2423
  }
2122
- if (ev.type === "stream_event") {
2123
- const delta = ContentBlockDeltaSchema.safeParse(ev.event);
2124
- if (!delta.success) return;
2125
- const d = delta.data.delta;
2126
- if (d.type === "text_delta" && d.text) {
2127
- relay.sendEnvelope(
2128
- buildMessage(
2129
- "assistant_message",
2130
- sessionId,
2131
- seq,
2132
- { text: d.text, isPartial: true },
2133
- "proxy"
2134
- )
2135
- );
2136
- } else if (d.type === "thinking_delta" && d.thinking) {
2137
- relay.sendEnvelope(buildMessage("thinking", sessionId, seq, { text: d.thinking }, "proxy"));
2138
- }
2139
- return;
2140
- }
2141
- if (ev.type === "assistant") {
2142
- let forwardedContent = false;
2143
- for (const raw of ev.message.content) {
2144
- const blockParse = KnownContentBlockSchema.safeParse(raw);
2145
- if (!blockParse.success) {
2146
- const rawType = raw && typeof raw === "object" ? raw.type : void 0;
2147
- serviceLogger.warn(
2148
- { sessionId, seq, blockType: rawType ?? "<missing>" },
2149
- "Unknown assistant content block; Claude CLI schema may have changed"
2150
- );
2151
- continue;
2152
- }
2153
- const block = blockParse.data;
2154
- if (block.type === "text") {
2155
- if (!isStreamDeltaSession && block.text) {
2156
- forwardedContent = true;
2157
- relay.sendEnvelope(
2158
- buildMessage(
2159
- "assistant_message",
2160
- sessionId,
2161
- seq,
2162
- { text: block.text, isPartial: true },
2163
- "proxy"
2164
- )
2165
- );
2166
- }
2167
- } else if (block.type === "thinking") {
2168
- if (!isStreamDeltaSession && block.thinking) {
2169
- forwardedContent = true;
2170
- relay.sendEnvelope(
2171
- buildMessage("thinking", sessionId, seq, { text: block.thinking }, "proxy")
2172
- );
2173
- }
2174
- } else if (block.type === "tool_use") {
2175
- forwardedContent = true;
2176
- relay.sendEnvelope(
2177
- buildMessage(
2178
- "assistant_tool_use",
2179
- sessionId,
2180
- seq,
2181
- { toolName: block.name, toolId: block.id, parameters: block.input },
2182
- "proxy"
2183
- )
2184
- );
2185
- }
2186
- }
2187
- if (forwardedContent && this.isCompactingSession(sessionId)) {
2188
- this.sendCompactTurnResult(sessionId, true);
2189
- }
2190
- return;
2191
- }
2192
2424
  if (ev.type === "user") {
2193
2425
  if (typeof ev.message.content === "string") {
2194
2426
  this.handleCompactLocalCommandOutput(sessionId, seq, ev.message.content);
2195
2427
  return;
2196
2428
  }
2197
- for (const raw of ev.message.content) {
2198
- const blockParse = KnownContentBlockSchema.safeParse(raw);
2199
- if (!blockParse.success) continue;
2200
- const block = blockParse.data;
2201
- if (block.type !== "tool_result") continue;
2202
- relay.sendEnvelope(
2203
- buildMessage(
2204
- "tool_result",
2205
- sessionId,
2206
- seq,
2207
- { toolId: block.tool_use_id, result: block.content, isError: block.is_error ?? false },
2208
- "proxy"
2209
- )
2429
+ }
2430
+ for (const mapped of mapClaudeStreamEvent(sessionId, seq, {
2431
+ event: ev,
2432
+ isStreamDeltaSession,
2433
+ isCompactingSession: this.isCompactingSession(sessionId)
2434
+ })) {
2435
+ if (mapped.kind === "envelope") {
2436
+ relay.sendEnvelope(mapped.envelope);
2437
+ } else if (mapped.kind === "control") {
2438
+ relay.sendRaw(mapped.raw);
2439
+ if (mapped.notifyTurnResult) this.deps.jsonObserver.onTurnResult(sessionId);
2440
+ } else {
2441
+ serviceLogger.warn(
2442
+ { sessionId, seq, blockType: mapped.blockType },
2443
+ "Unknown assistant content block; Claude CLI schema may have changed"
2210
2444
  );
2211
2445
  }
2212
- return;
2213
- }
2214
- if (ev.type === "result") {
2215
- const resultText = typeof ev.result === "string" ? ev.result : void 0;
2216
- relay.sendRaw(
2217
- serializeControl({
2218
- type: "turn_result",
2219
- sessionId,
2220
- success: ev.subtype === "success",
2221
- isError: ev.is_error ?? false,
2222
- ...resultText ? { result: resultText } : {}
2223
- })
2224
- );
2225
- this.deps.jsonObserver.onTurnResult(sessionId);
2226
2446
  }
2227
2447
  }
2228
2448
  forwardCodexAppServerEvent(sessionId, seq, event) {
2229
2449
  const relay = this.deps.relayConnection;
2230
- const method = typeof event.method === "string" ? event.method : "";
2231
- const params = event.params && typeof event.params === "object" ? event.params : {};
2232
2450
  this.deps.touchSessionActivity?.(sessionId);
2233
- if (method === "item/agentMessage/delta") {
2234
- const delta = typeof params.delta === "string" ? params.delta : "";
2235
- if (!delta) return;
2236
- relay.sendEnvelope(
2237
- buildMessage(
2238
- "assistant_message",
2239
- sessionId,
2240
- seq,
2241
- { text: delta, isPartial: true },
2242
- "proxy"
2243
- )
2244
- );
2245
- return;
2246
- }
2247
- const item = params.item && typeof params.item === "object" ? params.item : null;
2248
- const itemRecord = item;
2249
- if ((method === "item/started" || method === "item/completed") && itemRecord?.type === "fileChange") {
2250
- const id = typeof itemRecord.id === "string" ? itemRecord.id : "";
2251
- if (!id) return;
2252
- const status = typeof itemRecord.status === "string" ? itemRecord.status : "";
2253
- relay.sendEnvelope(
2254
- buildMessage(
2255
- "assistant_tool_use",
2256
- sessionId,
2257
- seq,
2258
- { toolName: "Patch", toolId: id, parameters: codexPatchParameters(itemRecord) },
2259
- "proxy"
2260
- )
2261
- );
2262
- if (method === "item/completed") {
2263
- relay.sendEnvelope(
2264
- buildMessage(
2265
- "tool_result",
2266
- sessionId,
2267
- seq,
2268
- { toolId: id, result: status || "completed", isError: status === "failed" },
2269
- "proxy"
2270
- )
2271
- );
2451
+ for (const mapped of mapCodexAppServerEvent(sessionId, seq, event)) {
2452
+ if (mapped.kind === "envelope") {
2453
+ relay.sendEnvelope(mapped.envelope);
2454
+ } else {
2455
+ relay.sendRaw(mapped.raw);
2456
+ if (mapped.notifyTurnResult) this.deps.jsonObserver.onTurnResult(sessionId);
2272
2457
  }
2273
- return;
2274
- }
2275
- if (method === "item/started" && itemRecord?.type === "commandExecution") {
2276
- const id = typeof itemRecord.id === "string" ? itemRecord.id : "";
2277
- if (!id) return;
2278
- const command = typeof itemRecord.command === "string" ? itemRecord.command : "";
2279
- const cwd = typeof itemRecord.cwd === "string" ? itemRecord.cwd : "";
2280
- relay.sendEnvelope(
2281
- buildMessage(
2282
- "assistant_tool_use",
2283
- sessionId,
2284
- seq,
2285
- { toolName: "Bash", toolId: id, parameters: { command, cwd } },
2286
- "proxy"
2287
- )
2288
- );
2289
- return;
2290
- }
2291
- if (method === "item/completed" && itemRecord?.type === "commandExecution") {
2292
- const id = typeof itemRecord.id === "string" ? itemRecord.id : "";
2293
- if (!id) return;
2294
- const output = typeof itemRecord.aggregatedOutput === "string" ? itemRecord.aggregatedOutput : "";
2295
- const exitCode = typeof itemRecord.exitCode === "number" ? itemRecord.exitCode : null;
2296
- relay.sendEnvelope(
2297
- buildMessage(
2298
- "tool_result",
2299
- sessionId,
2300
- seq,
2301
- { toolId: id, result: output, isError: exitCode !== null && exitCode !== 0 },
2302
- "proxy"
2303
- )
2304
- );
2305
- return;
2306
- }
2307
- if (method === "turn/completed") {
2308
- const turn = params.turn && typeof params.turn === "object" ? params.turn : {};
2309
- const status = turn.status;
2310
- const error = turn.error;
2311
- const success = status === "completed";
2312
- relay.sendRaw(
2313
- serializeControl({
2314
- type: "turn_result",
2315
- sessionId,
2316
- success,
2317
- isError: !success,
2318
- ...error ? { result: String(error) } : {}
2319
- })
2320
- );
2321
- this.deps.jsonObserver.onTurnResult(sessionId);
2322
2458
  }
2323
2459
  }
2324
2460
  handleCompactSystemEvent(sessionId, seq, ev) {
@@ -3378,12 +3514,17 @@ var DEFAULT_COLS = 80;
3378
3514
  var DEFAULT_ROWS = 24;
3379
3515
  var IDLE_CHECK_INTERVAL_MS = 3e3;
3380
3516
  var IDLE_THRESHOLD_MS = 3e3;
3517
+ var STARTUP_EXIT_DIAGNOSTIC_WINDOW_MS = 1e4;
3518
+ var STARTUP_OUTPUT_PREVIEW_LIMIT = 8192;
3381
3519
  var PROVIDERS = {
3382
3520
  claude: CLAUDE_PROVIDER,
3383
3521
  codex: CODEX_PROVIDER
3384
3522
  };
3385
3523
  var HOSTED_PTY_TERM = "xterm-256color";
3386
3524
  var HOSTED_PTY_COLORTERM = "truecolor";
3525
+ var ANSI_OSC_RE = new RegExp(String.raw`\x1b\][^\x07]*(?:\x07|\x1b\\)`, "g");
3526
+ var ANSI_CSI_RE = new RegExp(String.raw`\x1b\[[0-?]*[ -/]*[@-~]`, "g");
3527
+ var ANSI_CHARSET_RE = new RegExp(String.raw`\x1b[()][A-Za-z0-9]`, "g");
3387
3528
  function buildHostedPtyArgs(provider, resumeSessionId) {
3388
3529
  if (!resumeSessionId) return [];
3389
3530
  return provider === "codex" ? ["resume", resumeSessionId] : ["--resume", resumeSessionId];
@@ -3403,6 +3544,14 @@ function normalizeHostedPtyEnv(env) {
3403
3544
  normalized.CLICOLOR = "1";
3404
3545
  return normalized;
3405
3546
  }
3547
+ function appendStartupOutput(current, data) {
3548
+ if (current.length >= STARTUP_OUTPUT_PREVIEW_LIMIT) return current;
3549
+ const next = current + data;
3550
+ return next.length > STARTUP_OUTPUT_PREVIEW_LIMIT ? next.slice(0, STARTUP_OUTPUT_PREVIEW_LIMIT) : next;
3551
+ }
3552
+ function cleanPtyOutputPreview(output) {
3553
+ 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();
3554
+ }
3406
3555
  var HostedPtyRegistry = class {
3407
3556
  constructor(deps) {
3408
3557
  this.deps = deps;
@@ -3443,17 +3592,34 @@ var HostedPtyRegistry = class {
3443
3592
  terminal,
3444
3593
  serializeAddon,
3445
3594
  idleTimer: setInterval(() => this.checkIdle(options.sessionId), IDLE_CHECK_INTERVAL_MS),
3595
+ startedAt: Date.now(),
3446
3596
  lastOutputTime: 0,
3447
3597
  currentState: "turn_complete",
3448
3598
  outputSeq: 0,
3449
3599
  semanticTextTail: "",
3600
+ startupOutput: "",
3450
3601
  textApprovalWaitActive: false
3451
3602
  };
3452
3603
  this.sessions.set(options.sessionId, hosted);
3453
3604
  child.onData((data) => this.handleData(options.sessionId, data));
3454
3605
  child.onExit(({ exitCode, signal }) => {
3455
3606
  const code = signal ? 128 + signal : exitCode;
3456
- serviceLogger.info({ sessionId: options.sessionId, code }, "Hosted PTY exited");
3607
+ const current = this.sessions.get(options.sessionId);
3608
+ const uptimeMs = current ? Date.now() - current.startedAt : void 0;
3609
+ const outputPreview = current ? cleanPtyOutputPreview(current.startupOutput) : "";
3610
+ const shouldIncludeStartupOutput = current && uptimeMs !== void 0 && uptimeMs <= STARTUP_EXIT_DIAGNOSTIC_WINDOW_MS && outputPreview.length > 0;
3611
+ serviceLogger.info(
3612
+ {
3613
+ sessionId: options.sessionId,
3614
+ code,
3615
+ ...uptimeMs !== void 0 ? { uptimeMs } : {},
3616
+ ...shouldIncludeStartupOutput ? {
3617
+ startupOutputChars: current.startupOutput.length,
3618
+ startupOutputPreview: outputPreview
3619
+ } : {}
3620
+ },
3621
+ "Hosted PTY exited"
3622
+ );
3457
3623
  this.close(options.sessionId, { kill: false, notify: true });
3458
3624
  });
3459
3625
  serviceLogger.info(
@@ -3529,6 +3695,7 @@ var HostedPtyRegistry = class {
3529
3695
  if (!hosted) return;
3530
3696
  hosted.lastOutputTime = Date.now();
3531
3697
  hosted.outputSeq += 1;
3698
+ hosted.startupOutput = appendStartupOutput(hosted.startupOutput, data);
3532
3699
  hosted.terminal.write(data);
3533
3700
  this.deps.touchSessionActivity(sessionId);
3534
3701
  this.sendBinary(sessionId, Buffer.from(data, "utf-8"), hosted.outputSeq);
@@ -3643,6 +3810,7 @@ var HostedPtyRegistry = class {
3643
3810
  };
3644
3811
 
3645
3812
  // src/serve/relay-session-create-handler.ts
3813
+ var JSON_WORKER_READY_TIMEOUT_MS = 15e3;
3646
3814
  function validateSessionCwd(cwd) {
3647
3815
  if (typeof cwd !== "string" || !cwd.trim()) {
3648
3816
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
@@ -3743,40 +3911,58 @@ var RelaySessionCreateHandler = class {
3743
3911
  attempt++;
3744
3912
  this.deps.workerRegistry.connect(pendingId, paths.workerSock).then((sock) => {
3745
3913
  if (sock) {
3746
- const session = this.deps.sessionManager.createSession(
3747
- "json",
3748
- sessionCwd,
3749
- workerPid,
3750
- name,
3751
- pendingId,
3752
- provider,
3753
- void 0,
3754
- nameLocked
3755
- );
3756
- if (resumeSessionId) {
3757
- this.deps.sessionManager.setHistorySessionId(session.id, resumeSessionId);
3758
- }
3759
- this.deps.relaySend(
3760
- serializeControl({
3761
- type: "session_create_response",
3762
- requestId,
3763
- sessionId: session.id,
3764
- name: session.name,
3765
- nameLocked: session.nameLocked,
3766
- mode: "json",
3767
- provider
3768
- })
3769
- );
3770
- if (resumeSessionId) {
3771
- this.pushHistoryMessages(session.id, resumeSessionId);
3772
- }
3773
- serviceLogger.info(
3774
- { sessionId: session.id, cwd: sessionCwd },
3775
- "JSON session created via relay"
3776
- );
3777
- this.deps.controlHandlers.pushCommandList(session.id, sessionCwd);
3778
- this.deps.broadcastSessionSync(session);
3779
- this.deps.broadcastSessionList();
3914
+ this.deps.workerRegistry.waitForReady(pendingId, JSON_WORKER_READY_TIMEOUT_MS).then(() => {
3915
+ const session = this.deps.sessionManager.createSession(
3916
+ "json",
3917
+ sessionCwd,
3918
+ workerPid,
3919
+ name,
3920
+ pendingId,
3921
+ provider,
3922
+ void 0,
3923
+ nameLocked
3924
+ );
3925
+ if (resumeSessionId) {
3926
+ this.deps.sessionManager.setHistorySessionId(session.id, resumeSessionId);
3927
+ }
3928
+ this.deps.relaySend(
3929
+ serializeControl({
3930
+ type: "session_create_response",
3931
+ requestId,
3932
+ sessionId: session.id,
3933
+ name: session.name,
3934
+ nameLocked: session.nameLocked,
3935
+ mode: "json",
3936
+ provider
3937
+ })
3938
+ );
3939
+ if (resumeSessionId) {
3940
+ this.pushHistoryMessages(session.id, resumeSessionId);
3941
+ }
3942
+ serviceLogger.info(
3943
+ { sessionId: session.id, cwd: sessionCwd },
3944
+ "JSON session created via relay"
3945
+ );
3946
+ this.deps.controlHandlers.pushCommandList(session.id, sessionCwd);
3947
+ this.deps.broadcastSessionSync(session);
3948
+ this.deps.broadcastSessionList();
3949
+ }).catch((err) => {
3950
+ const error = err instanceof Error ? err.message : String(err);
3951
+ this.cleanupPendingJsonSession(pendingId);
3952
+ this.deps.relaySend(
3953
+ serializeControl({
3954
+ type: "session_create_response",
3955
+ requestId,
3956
+ sessionId: pendingId,
3957
+ errorCode: ControlErrorCode.WORKER_START_FAILED,
3958
+ error
3959
+ })
3960
+ );
3961
+ serviceLogger.error(
3962
+ { sessionId: pendingId, error },
3963
+ "Worker failed to report ready via relay"
3964
+ );
3965
+ });
3780
3966
  } else if (attempt < maxRetries) {
3781
3967
  scheduleAttempt(Math.min(100 * attempt, 2e3));
3782
3968
  } else {