@dev-anywhere/proxy 0.4.62 → 0.4.64

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-LWEEIGOF.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) {
@@ -3386,6 +3522,9 @@ var PROVIDERS = {
3386
3522
  };
3387
3523
  var HOSTED_PTY_TERM = "xterm-256color";
3388
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");
3389
3528
  function buildHostedPtyArgs(provider, resumeSessionId) {
3390
3529
  if (!resumeSessionId) return [];
3391
3530
  return provider === "codex" ? ["resume", resumeSessionId] : ["--resume", resumeSessionId];
@@ -3411,7 +3550,7 @@ function appendStartupOutput(current, data) {
3411
3550
  return next.length > STARTUP_OUTPUT_PREVIEW_LIMIT ? next.slice(0, STARTUP_OUTPUT_PREVIEW_LIMIT) : next;
3412
3551
  }
3413
3552
  function cleanPtyOutputPreview(output) {
3414
- return output.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/\x1b[()][A-Za-z0-9]/g, "").replace(/\r/g, "\n").replace(/[^\t\n\x20-\x7e\u0080-\uffff]/g, "").replace(/\n{3,}/g, "\n\n").trim();
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();
3415
3554
  }
3416
3555
  var HostedPtyRegistry = class {
3417
3556
  constructor(deps) {
@@ -3457,6 +3596,7 @@ var HostedPtyRegistry = class {
3457
3596
  lastOutputTime: 0,
3458
3597
  currentState: "turn_complete",
3459
3598
  outputSeq: 0,
3599
+ ptyStateSeq: 0,
3460
3600
  semanticTextTail: "",
3461
3601
  startupOutput: "",
3462
3602
  textApprovalWaitActive: false
@@ -3594,7 +3734,7 @@ var HostedPtyRegistry = class {
3594
3734
  hosted.textApprovalWaitActive = false;
3595
3735
  }
3596
3736
  if (!decision.emit) return;
3597
- this.sendPtyState(sessionId, decision.nextState, decision.meta);
3737
+ this.sendPtyState(sessionId, decision.nextState, decision.meta, hosted);
3598
3738
  this.deps.applyPtyStateToSession(sessionId, decision.nextState);
3599
3739
  }
3600
3740
  releaseTextApprovalOnInput(sessionId, hosted, data) {
@@ -3602,7 +3742,7 @@ var HostedPtyRegistry = class {
3602
3742
  if (!shouldReleaseTextApprovalOnInput(data)) return;
3603
3743
  hosted.textApprovalWaitActive = false;
3604
3744
  hosted.currentState = "working";
3605
- this.sendPtyState(sessionId, "working");
3745
+ this.sendPtyState(sessionId, "working", void 0, hosted);
3606
3746
  this.deps.applyPtyStateToSession(sessionId, "working");
3607
3747
  }
3608
3748
  checkIdle(sessionId) {
@@ -3614,12 +3754,14 @@ var HostedPtyRegistry = class {
3614
3754
  hosted.lastOutputTime = 0;
3615
3755
  if (hosted.currentState !== "working") return;
3616
3756
  hosted.currentState = "turn_complete";
3617
- this.sendPtyState(sessionId, "turn_complete");
3757
+ this.sendPtyState(sessionId, "turn_complete", void 0, hosted);
3618
3758
  this.deps.applyPtyStateToSession(sessionId, "turn_complete");
3619
3759
  }
3620
- sendPtyState(sessionId, state, meta) {
3760
+ sendPtyState(sessionId, state, meta, hosted = this.sessions.get(sessionId)) {
3761
+ const seq = hosted ? ++hosted.ptyStateSeq : void 0;
3621
3762
  const payload = {
3622
3763
  state,
3764
+ ...seq !== void 0 ? { seq } : {},
3623
3765
  ...meta?.title !== void 0 ? { title: meta.title } : {},
3624
3766
  ...meta?.tool !== void 0 ? { tool: meta.tool } : {}
3625
3767
  };
@@ -3652,7 +3794,6 @@ var HostedPtyRegistry = class {
3652
3794
  close(sessionId, options) {
3653
3795
  const hosted = this.sessions.get(sessionId);
3654
3796
  if (!hosted) return false;
3655
- this.sessions.delete(sessionId);
3656
3797
  clearInterval(hosted.idleTimer);
3657
3798
  if (options.kill) {
3658
3799
  try {
@@ -3662,15 +3803,17 @@ var HostedPtyRegistry = class {
3662
3803
  }
3663
3804
  hosted.terminal.dispose();
3664
3805
  if (options.notify) {
3665
- this.sendPtyState(sessionId, "turn_complete");
3806
+ this.sendPtyState(sessionId, "turn_complete", void 0, hosted);
3666
3807
  this.deps.sessionManager.terminateSession(sessionId);
3667
3808
  this.deps.onSessionClosed(sessionId);
3668
3809
  }
3810
+ this.sessions.delete(sessionId);
3669
3811
  return true;
3670
3812
  }
3671
3813
  };
3672
3814
 
3673
3815
  // src/serve/relay-session-create-handler.ts
3816
+ var JSON_WORKER_READY_TIMEOUT_MS = 15e3;
3674
3817
  function validateSessionCwd(cwd) {
3675
3818
  if (typeof cwd !== "string" || !cwd.trim()) {
3676
3819
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
@@ -3771,40 +3914,58 @@ var RelaySessionCreateHandler = class {
3771
3914
  attempt++;
3772
3915
  this.deps.workerRegistry.connect(pendingId, paths.workerSock).then((sock) => {
3773
3916
  if (sock) {
3774
- const session = this.deps.sessionManager.createSession(
3775
- "json",
3776
- sessionCwd,
3777
- workerPid,
3778
- name,
3779
- pendingId,
3780
- provider,
3781
- void 0,
3782
- nameLocked
3783
- );
3784
- if (resumeSessionId) {
3785
- this.deps.sessionManager.setHistorySessionId(session.id, resumeSessionId);
3786
- }
3787
- this.deps.relaySend(
3788
- serializeControl({
3789
- type: "session_create_response",
3790
- requestId,
3791
- sessionId: session.id,
3792
- name: session.name,
3793
- nameLocked: session.nameLocked,
3794
- mode: "json",
3795
- provider
3796
- })
3797
- );
3798
- if (resumeSessionId) {
3799
- this.pushHistoryMessages(session.id, resumeSessionId);
3800
- }
3801
- serviceLogger.info(
3802
- { sessionId: session.id, cwd: sessionCwd },
3803
- "JSON session created via relay"
3804
- );
3805
- this.deps.controlHandlers.pushCommandList(session.id, sessionCwd);
3806
- this.deps.broadcastSessionSync(session);
3807
- this.deps.broadcastSessionList();
3917
+ this.deps.workerRegistry.waitForReady(pendingId, JSON_WORKER_READY_TIMEOUT_MS).then(() => {
3918
+ const session = this.deps.sessionManager.createSession(
3919
+ "json",
3920
+ sessionCwd,
3921
+ workerPid,
3922
+ name,
3923
+ pendingId,
3924
+ provider,
3925
+ void 0,
3926
+ nameLocked
3927
+ );
3928
+ if (resumeSessionId) {
3929
+ this.deps.sessionManager.setHistorySessionId(session.id, resumeSessionId);
3930
+ }
3931
+ this.deps.relaySend(
3932
+ serializeControl({
3933
+ type: "session_create_response",
3934
+ requestId,
3935
+ sessionId: session.id,
3936
+ name: session.name,
3937
+ nameLocked: session.nameLocked,
3938
+ mode: "json",
3939
+ provider
3940
+ })
3941
+ );
3942
+ if (resumeSessionId) {
3943
+ this.pushHistoryMessages(session.id, resumeSessionId);
3944
+ }
3945
+ serviceLogger.info(
3946
+ { sessionId: session.id, cwd: sessionCwd },
3947
+ "JSON session created via relay"
3948
+ );
3949
+ this.deps.controlHandlers.pushCommandList(session.id, sessionCwd);
3950
+ this.deps.broadcastSessionSync(session);
3951
+ this.deps.broadcastSessionList();
3952
+ }).catch((err) => {
3953
+ const error = err instanceof Error ? err.message : String(err);
3954
+ this.cleanupPendingJsonSession(pendingId);
3955
+ this.deps.relaySend(
3956
+ serializeControl({
3957
+ type: "session_create_response",
3958
+ requestId,
3959
+ sessionId: pendingId,
3960
+ errorCode: ControlErrorCode.WORKER_START_FAILED,
3961
+ error
3962
+ })
3963
+ );
3964
+ serviceLogger.error(
3965
+ { sessionId: pendingId, error },
3966
+ "Worker failed to report ready via relay"
3967
+ );
3968
+ });
3808
3969
  } else if (attempt < maxRetries) {
3809
3970
  scheduleAttempt(Math.min(100 * attempt, 2e3));
3810
3971
  } else {
@@ -5132,6 +5293,7 @@ function handleTerminalConnection(socket, deps) {
5132
5293
  const logPayload = {
5133
5294
  sessionId: msg.sessionId,
5134
5295
  state: msg.state,
5296
+ seq: msg.seq,
5135
5297
  ...msg.title !== void 0 ? { title: msg.title } : {},
5136
5298
  ...msg.tool !== void 0 ? { tool: msg.tool } : {}
5137
5299
  };
@@ -5147,6 +5309,7 @@ function handleTerminalConnection(socket, deps) {
5147
5309
  sessionId: msg.sessionId,
5148
5310
  payload: {
5149
5311
  state: msg.state,
5312
+ seq: msg.seq,
5150
5313
  ...msg.title !== void 0 ? { title: msg.title } : {},
5151
5314
  ...msg.tool !== void 0 ? { tool: msg.tool } : {}
5152
5315
  }