@codexhost/cli-win32-x64 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +2 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +191 -9
  4. package/app/console-web.js +930 -168
  5. package/app/desktop-controller.mjs +267 -13
  6. package/app/desktop-mcp-client.mjs +619 -0
  7. package/app/host-runtime.mjs +3254 -2860
  8. package/app/plugins/antigravity/plugin.mjs +409 -22
  9. package/app/plugins/claude-code/plugin.mjs +191 -9
  10. package/app/plugins/codebuddy/plugin.mjs +203 -14
  11. package/app/plugins/codex-usage/plugin.mjs +191 -9
  12. package/app/plugins/copilot/plugin.mjs +191 -9
  13. package/app/plugins/cursor-cli/plugin.mjs +191 -9
  14. package/app/plugins/deepseek-harness/plugin.mjs +191 -9
  15. package/app/plugins/devin/plugin.mjs +191 -9
  16. package/app/plugins/enabled.json +1 -0
  17. package/app/plugins/grok/plugin.mjs +191 -9
  18. package/app/plugins/hermes/plugin.mjs +191 -9
  19. package/app/plugins/kimi-code/plugin.mjs +191 -9
  20. package/app/plugins/kiro-cli/plugin.mjs +191 -9
  21. package/app/plugins/omp/plugin.mjs +1002 -240
  22. package/app/plugins/opencode/plugin.mjs +191 -9
  23. package/app/plugins/pi/plugin.mjs +191 -9
  24. package/app/plugins/qoder/plugin.mjs +191 -9
  25. package/app/plugins/qoder-cn/plugin.mjs +191 -9
  26. package/app/plugins/qwen-code/plugin.mjs +191 -9
  27. package/app/plugins/workbuddy/plugin.mjs +823 -451
  28. package/app/plugins/workbuddy-cn/assets/icon.svg +27 -0
  29. package/app/plugins/workbuddy-cn/manifest.json +32 -0
  30. package/app/plugins/workbuddy-cn/plugin.mjs +36211 -0
  31. package/app/plugins/zcode/plugin.mjs +191 -9
  32. package/app/renderer-extension.js +2479 -229
  33. package/app/web/assets/{abnfDiagram-XWFEHMT6-VnfRaHM6.js → abnfDiagram-XWFEHMT6-Cg-E7mc4.js} +1 -1
  34. package/app/web/assets/{architectureDiagram-CSQXQB3N-BA1ehtvi.js → architectureDiagram-CSQXQB3N-B__CwXjW.js} +1 -1
  35. package/app/web/assets/{blockDiagram-BEDRHYPZ-31BZSfd4.js → blockDiagram-BEDRHYPZ-Bk2gCIVM.js} +1 -1
  36. package/app/web/assets/{c4Diagram-M2UUVUY5-CNzGWc5k.js → c4Diagram-M2UUVUY5-DU_TpjJ3.js} +1 -1
  37. package/app/web/assets/{chunk-2Q5K7J3B-ahAIR-NM.js → chunk-2Q5K7J3B-DnJEi6e4.js} +1 -1
  38. package/app/web/assets/{chunk-3GCGMST5-BIV5YeRJ.js → chunk-3GCGMST5-Dia9jGkf.js} +1 -1
  39. package/app/web/assets/{chunk-5VM5RSS4-CluTMPJG.js → chunk-5VM5RSS4-2PGDiDvK.js} +1 -1
  40. package/app/web/assets/{chunk-7U7NFRK5-4NIQuFbE.js → chunk-7U7NFRK5-BLPm3d5H.js} +1 -1
  41. package/app/web/assets/{chunk-CNRTWJTD-_0bEfGn3.js → chunk-CNRTWJTD-GH_nAEXs.js} +1 -1
  42. package/app/web/assets/{chunk-D5HYT7QG-_kTC6f8F.js → chunk-D5HYT7QG-DnIm-Ely.js} +1 -1
  43. package/app/web/assets/{chunk-EBZ3SEQC-CykaYOrL.js → chunk-EBZ3SEQC-C6N5qLCR.js} +2 -2
  44. package/app/web/assets/{chunk-JWPE2WC7-3vVOQ_py.js → chunk-JWPE2WC7-D_kMgdmr.js} +1 -1
  45. package/app/web/assets/{chunk-KTR4FSNJ-aVg5vgrm.js → chunk-KTR4FSNJ-BRb9femQ.js} +1 -1
  46. package/app/web/assets/{chunk-XXDRQBXY-_gVwGeSp.js → chunk-XXDRQBXY-BFaK95zq.js} +1 -1
  47. package/app/web/assets/{classDiagram-v2-KXABOMEV-fI1LfeBf.js → classDiagram-v2-KXABOMEV--_hR_XrU.js} +1 -1
  48. package/app/web/assets/{cose-bilkent-JH36ORCC-DFXMlWov.js → cose-bilkent-JH36ORCC-C7ghEB3_.js} +1 -1
  49. package/app/web/assets/{cynefin-EF2NZ3EQ-lZy7X6FO.js → cynefin-EF2NZ3EQ-Ce1lURwZ.js} +1 -1
  50. package/app/web/assets/{cynefinDiagram-NJNITYFG-N4DwFSW1.js → cynefinDiagram-NJNITYFG-Cgr5aSTS.js} +1 -1
  51. package/app/web/assets/{dagre-KIHZ2IZ3-B7-8baTH.js → dagre-KIHZ2IZ3-BBFKmRP1.js} +1 -1
  52. package/app/web/assets/{diagram-7YQZDPLS-DLfjiBXV.js → diagram-7YQZDPLS-CJQih32K.js} +1 -1
  53. package/app/web/assets/{diagram-QBROCOUO-CQnRzSTi.js → diagram-QBROCOUO-Cl3S7IUT.js} +1 -1
  54. package/app/web/assets/{diagram-RJJCUUZO-DPnxazRT.js → diagram-RJJCUUZO-B6C8N2cV.js} +1 -1
  55. package/app/web/assets/{diagram-WERXNKYE-BBuEFRvD.js → diagram-WERXNKYE-NkciBSQl.js} +1 -1
  56. package/app/web/assets/{diagram-YHHI257C-BQ92JNJs.js → diagram-YHHI257C-DlEvljeY.js} +1 -1
  57. package/app/web/assets/{diagram-YR4HJLHV-Ce6BQO3J.js → diagram-YR4HJLHV-e4_Gzbt6.js} +1 -1
  58. package/app/web/assets/{ebnfDiagram-N527522P-DYknE2Jy.js → ebnfDiagram-N527522P-WvQEFmPi.js} +1 -1
  59. package/app/web/assets/{elk-O5DQBFGD-4S6_JJFF.js → elk-O5DQBFGD-CkyJsjzf.js} +1 -1
  60. package/app/web/assets/{erDiagram-K3K3BIDK-DRtF7JVQ.js → erDiagram-K3K3BIDK-B93gK3X0.js} +1 -1
  61. package/app/web/assets/{flowDiagram-Z6JWZHQI-7Ho8CyR9.js → flowDiagram-Z6JWZHQI-NFaGX6B4.js} +1 -1
  62. package/app/web/assets/{ganttDiagram-3PRQTZWP-CW8Ig5y4.js → ganttDiagram-3PRQTZWP-Czh68CQm.js} +1 -1
  63. package/app/web/assets/{gitGraphDiagram-VXDFKS5L-CzS8Xg2D.js → gitGraphDiagram-VXDFKS5L-t95UHKja.js} +1 -1
  64. package/app/web/assets/{grid-E2QIVN74-Cq284lCe.js → grid-E2QIVN74-C87DucDN.js} +1 -1
  65. package/app/web/assets/index-CGI50Nfg.css +1 -0
  66. package/app/web/assets/index-Dr6wHi0A.js +208 -0
  67. package/app/web/assets/{infoDiagram-EZ3ZOAHP-BZgN6qlY.js → infoDiagram-EZ3ZOAHP-CxFlfQbY.js} +1 -1
  68. package/app/web/assets/{ishikawaDiagram-S3EKX5GW-BH9YHc-1.js → ishikawaDiagram-S3EKX5GW-D4IwQJde.js} +1 -1
  69. package/app/web/assets/{journeyDiagram-POQNLL5X-D50KYOLe.js → journeyDiagram-POQNLL5X-C0Bf5W4T.js} +1 -1
  70. package/app/web/assets/{kanban-definition-BH5XI6FM-Crw_5mMP.js → kanban-definition-BH5XI6FM-Cda7r2yr.js} +1 -1
  71. package/app/web/assets/{mermaid.core-o2Qjrppc.js → mermaid.core-f4LJm6AC.js} +4 -4
  72. package/app/web/assets/{mindmap-definition-WVAN44T4-B_bEbpAH.js → mindmap-definition-WVAN44T4-DKapinG7.js} +1 -1
  73. package/app/web/assets/{pegDiagram-D4NLKWP3-VecAHoyw.js → pegDiagram-D4NLKWP3-D7iEZGN2.js} +1 -1
  74. package/app/web/assets/{pieDiagram-36ENHN4W-o3ei2T-6.js → pieDiagram-36ENHN4W-CopXZ5qt.js} +1 -1
  75. package/app/web/assets/{quadrantDiagram-ZQUDMS73-DHndOAcn.js → quadrantDiagram-ZQUDMS73-mmkKPDGK.js} +1 -1
  76. package/app/web/assets/{railroadDiagram-JIZHGYPL-DRd_lfii.js → railroadDiagram-JIZHGYPL-BAGwIIkV.js} +1 -1
  77. package/app/web/assets/{render-VIF2ZAQL-awM3hUqB.js → render-VIF2ZAQL-dXxGa09y.js} +2 -2
  78. package/app/web/assets/{requirementDiagram-AXW2TVFA-Ce1ePsOe.js → requirementDiagram-AXW2TVFA-C35tmLFs.js} +1 -1
  79. package/app/web/assets/{sankeyDiagram-FBCJTAIF-cP-LtgW-.js → sankeyDiagram-FBCJTAIF-BbSo5yeK.js} +1 -1
  80. package/app/web/assets/{sequenceDiagram-3LA2ROMG-C3JStTuW.js → sequenceDiagram-3LA2ROMG-Cgm2unNy.js} +1 -1
  81. package/app/web/assets/{sizeCapture-2Q2CQKSF-Dyyelr9K.js → sizeCapture-2Q2CQKSF-DCXFjl2x.js} +1 -1
  82. package/app/web/assets/{stateDiagram-v2-ATKHQDJO-DkYRBVTd.js → stateDiagram-v2-ATKHQDJO-B349iAao.js} +1 -1
  83. package/app/web/assets/{swimlanes-YQL5WMAO-B2FwJU5_.js → swimlanes-YQL5WMAO-6OvL1sEz.js} +1 -1
  84. package/app/web/assets/swimlanesDiagram-UCCPES4V-CIKaQUvP.js +8 -0
  85. package/app/web/assets/{timeline-definition-7Z437IG3-Di-qRIIi.js → timeline-definition-7Z437IG3-Bh1E3mhW.js} +1 -1
  86. package/app/web/assets/{usecaseDiagram-RDK6N6HP-yAImn62t.js → usecaseDiagram-RDK6N6HP-Dr5A05lL.js} +1 -1
  87. package/app/web/assets/{vennDiagram-SHRQU5PJ-BEv8jpfv.js → vennDiagram-SHRQU5PJ-CQPPBa27.js} +1 -1
  88. package/app/web/assets/{wardleyDiagram-F3OXNVQS-7irksA0b.js → wardleyDiagram-F3OXNVQS-BHin00q8.js} +1 -1
  89. package/app/web/assets/{xychartDiagram-GDYJKCDI-BokJGG2y.js → xychartDiagram-GDYJKCDI-D4BAWlQZ.js} +1 -1
  90. package/app/web/codexhost-settings.js +330 -130
  91. package/app/web/index.html +2 -2
  92. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  93. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  94. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
  95. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +160 -77
  96. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +104 -100
  97. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +64 -64
  98. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +5 -5
  99. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +6 -6
  100. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +80 -80
  101. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +70 -70
  102. package/app/web/role-avatars/builtin/advisor-otter.webp +0 -0
  103. package/app/web/role-avatars/builtin/builder-otter.webp +0 -0
  104. package/app/web/role-avatars/builtin/sailor-otter.webp +0 -0
  105. package/app/web/role-avatars/builtin/wizard-otter.webp +0 -0
  106. package/app/web-modules/server.mjs +5794 -2268
  107. package/bin/codexhost.exe +0 -0
  108. package/libexec/codexhost-node-repl.exe +0 -0
  109. package/libexec/codexhost-screenshot.exe +0 -0
  110. package/libexec/codexhost-shell.exe +0 -0
  111. package/libexec/codexhost-shim.exe +0 -0
  112. package/libexec/codexhost-updater.exe +0 -0
  113. package/package.json +1 -1
  114. package/app/web/assets/index-CINZ6P-q.css +0 -1
  115. package/app/web/assets/index-CvV6veuY.js +0 -208
  116. package/app/web/assets/swimlanesDiagram-UCCPES4V-BkMsxCPb.js +0 -8
@@ -0,0 +1,619 @@
1
+ // packages/host-runtime/src/desktop-mcp-client.ts
2
+ import { Agent, request as httpRequest } from "node:http";
3
+ var MAX_MCP_REQUEST_BYTES = 16 * 1024 * 1024;
4
+ var TERMINATE_SESSION_TIMEOUT_MS = 2e3;
5
+ var SSE_RECONNECT_DEFAULT_MS = 1e3;
6
+ var SSE_RECONNECT_MAX_MS = 5e3;
7
+ var SSE_RECONNECT_MAX_ATTEMPTS = 5;
8
+ function isRecord(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10
+ }
11
+ function headerValue(headers, name) {
12
+ const value = headers[name];
13
+ if (typeof value === "string") return value;
14
+ if (Array.isArray(value)) return value[0];
15
+ return void 0;
16
+ }
17
+ function createSseParser(onEvent, onOverflow, onRetry, maxBytes = MAX_MCP_REQUEST_BYTES) {
18
+ const decoder = new TextDecoder("utf-8");
19
+ let remainder = "";
20
+ let remainderBytes = 0;
21
+ let dataLines = [];
22
+ let dataBytes = 0;
23
+ let eventId;
24
+ let overflowed = false;
25
+ const failOverflow = () => {
26
+ overflowed = true;
27
+ remainder = "";
28
+ remainderBytes = 0;
29
+ dataLines = [];
30
+ dataBytes = 0;
31
+ eventId = void 0;
32
+ onOverflow();
33
+ };
34
+ const dispatch = () => {
35
+ if (dataLines.length > 0) {
36
+ onEvent({
37
+ data: dataLines.join("\n"),
38
+ ...eventId !== void 0 ? { id: eventId } : {}
39
+ });
40
+ }
41
+ dataLines = [];
42
+ dataBytes = 0;
43
+ eventId = void 0;
44
+ };
45
+ const processLine = (rawLine) => {
46
+ if (overflowed) return;
47
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
48
+ if (line.length === 0) {
49
+ dispatch();
50
+ return;
51
+ }
52
+ if (line.startsWith(":")) return;
53
+ const colon = line.indexOf(":");
54
+ const field = colon === -1 ? line : line.slice(0, colon);
55
+ let value = colon === -1 ? "" : line.slice(colon + 1);
56
+ if (value.startsWith(" ")) value = value.slice(1);
57
+ if (field === "data") {
58
+ dataBytes += (dataLines.length > 0 ? 1 : 0) + Buffer.byteLength(value, "utf8");
59
+ if (dataBytes > maxBytes) {
60
+ failOverflow();
61
+ return;
62
+ }
63
+ dataLines.push(value);
64
+ } else if (field === "id" && !value.includes("\0")) {
65
+ eventId = value;
66
+ } else if (field === "retry" && /^\d+$/u.test(value)) {
67
+ onRetry?.(Number(value));
68
+ }
69
+ };
70
+ return {
71
+ push(chunk) {
72
+ if (overflowed) return;
73
+ const decoded = decoder.decode(chunk, { stream: true });
74
+ remainder += decoded;
75
+ remainderBytes += Buffer.byteLength(decoded, "utf8");
76
+ let start = 0;
77
+ let index;
78
+ while ((index = remainder.indexOf("\n", start)) !== -1) {
79
+ processLine(remainder.slice(start, index));
80
+ if (overflowed) return;
81
+ start = index + 1;
82
+ }
83
+ if (start > 0) {
84
+ remainder = remainder.slice(start);
85
+ remainderBytes = Buffer.byteLength(remainder, "utf8");
86
+ }
87
+ if (remainderBytes > maxBytes) {
88
+ failOverflow();
89
+ }
90
+ },
91
+ end() {
92
+ decoder.decode();
93
+ remainder = "";
94
+ remainderBytes = 0;
95
+ dataLines = [];
96
+ dataBytes = 0;
97
+ eventId = void 0;
98
+ }
99
+ };
100
+ }
101
+ function writeLine(stream, line, signal) {
102
+ return new Promise((resolve, reject) => {
103
+ if (signal.aborted) {
104
+ resolve();
105
+ return;
106
+ }
107
+ if (stream.destroyed || stream.writableEnded) {
108
+ reject(new Error("Desktop MCP output stream is closed"));
109
+ return;
110
+ }
111
+ const onError = (error) => {
112
+ cleanup();
113
+ reject(error);
114
+ };
115
+ const onClose = () => {
116
+ cleanup();
117
+ reject(new Error("Desktop MCP output stream closed"));
118
+ };
119
+ const onDrain = () => {
120
+ cleanup();
121
+ resolve();
122
+ };
123
+ const onAbort = () => {
124
+ cleanup();
125
+ resolve();
126
+ };
127
+ const cleanup = () => {
128
+ stream.off("error", onError);
129
+ stream.off("close", onClose);
130
+ stream.off("drain", onDrain);
131
+ signal.removeEventListener("abort", onAbort);
132
+ };
133
+ stream.once("error", onError);
134
+ stream.once("close", onClose);
135
+ const ok = stream.write(`${line}
136
+ `, "utf8");
137
+ if (ok) {
138
+ cleanup();
139
+ resolve();
140
+ } else {
141
+ signal.addEventListener("abort", onAbort, { once: true });
142
+ stream.once("drain", onDrain);
143
+ }
144
+ });
145
+ }
146
+ async function runDesktopMcpClient(arguments_2, streams = {
147
+ input: process.stdin,
148
+ output: process.stdout
149
+ }, options = {}) {
150
+ const [rawUrl, authorization] = arguments_2;
151
+ if (!rawUrl || !authorization) throw new Error("Desktop MCP connection is unavailable");
152
+ const targetUrl = new URL(rawUrl);
153
+ if (targetUrl.protocol !== "http:" || !["127.0.0.1", "localhost", "::1", "[::1]"].includes(targetUrl.hostname))
154
+ throw new Error("Desktop MCP client requires a loopback HTTP endpoint");
155
+ const agent = new Agent({ keepAlive: true });
156
+ const activeRequests = /* @__PURE__ */ new Set();
157
+ const activeResponses = /* @__PURE__ */ new Set();
158
+ const shutdownController = new AbortController();
159
+ const done = Promise.withResolvers();
160
+ let closed = false;
161
+ let sessionId;
162
+ let protocolVersion;
163
+ let lastEventId;
164
+ let initializing;
165
+ let standaloneRequest;
166
+ let standaloneReconnectTimer;
167
+ let standaloneAttempts = 0;
168
+ let standaloneRetryMs = SSE_RECONNECT_DEFAULT_MS;
169
+ let pendingWrites = 0;
170
+ let outputPaused = false;
171
+ let outputChain = Promise.resolve();
172
+ const finish = (code) => {
173
+ if (closed) return;
174
+ closed = true;
175
+ done.resolve(code);
176
+ };
177
+ const fail = () => finish(1);
178
+ const pauseResponses = () => {
179
+ if (outputPaused) return;
180
+ outputPaused = true;
181
+ for (const res of activeResponses) res.pause();
182
+ };
183
+ const resumeResponses = () => {
184
+ if (!outputPaused) return;
185
+ outputPaused = false;
186
+ for (const res of activeResponses) {
187
+ if (!res.destroyed) res.resume();
188
+ }
189
+ };
190
+ const trackResponse = (res) => {
191
+ activeResponses.add(res);
192
+ if (outputPaused) res.pause();
193
+ const untrack = () => activeResponses.delete(res);
194
+ res.once("end", untrack);
195
+ res.once("close", untrack);
196
+ res.once("error", untrack);
197
+ };
198
+ const emitPayload = (rawJson, isInitialize, onItem) => {
199
+ const trimmed = rawJson.trim();
200
+ if (!trimmed) return;
201
+ let parsed;
202
+ try {
203
+ parsed = JSON.parse(trimmed);
204
+ } catch {
205
+ fail();
206
+ return;
207
+ }
208
+ const items = Array.isArray(parsed) ? parsed : [parsed];
209
+ for (const item of items) {
210
+ onItem?.(item);
211
+ if (isInitialize && isRecord(item) && isRecord(item.result)) {
212
+ const version = item.result.protocolVersion;
213
+ if (typeof version === "string" && version.length > 0) protocolVersion = version;
214
+ }
215
+ const serialized = JSON.stringify(item);
216
+ pendingWrites += 1;
217
+ if (pendingWrites > 1) pauseResponses();
218
+ outputChain = outputChain.then(() => {
219
+ if (shutdownController.signal.aborted) return void 0;
220
+ const writing = writeLine(streams.output, serialized, shutdownController.signal);
221
+ if (streams.output.writableNeedDrain) pauseResponses();
222
+ return writing;
223
+ }).catch(fail).finally(() => {
224
+ pendingWrites -= 1;
225
+ if (pendingWrites === 0 && !closed) resumeResponses();
226
+ });
227
+ }
228
+ };
229
+ const baseHeaders = () => ({
230
+ Authorization: authorization,
231
+ ...sessionId !== void 0 ? { "Mcp-Session-Id": sessionId } : {},
232
+ ...protocolVersion !== void 0 ? { "MCP-Protocol-Version": protocolVersion } : {}
233
+ });
234
+ const openStandaloneSse = () => {
235
+ if (closed || !sessionId || standaloneRequest) return;
236
+ clearTimeout(standaloneReconnectTimer);
237
+ standaloneReconnectTimer = void 0;
238
+ const req = httpRequest(
239
+ targetUrl,
240
+ {
241
+ method: "GET",
242
+ agent,
243
+ headers: {
244
+ ...baseHeaders(),
245
+ Accept: "text/event-stream",
246
+ ...lastEventId !== void 0 ? { "Last-Event-ID": lastEventId } : {}
247
+ }
248
+ },
249
+ (res) => {
250
+ if (closed) {
251
+ res.resume();
252
+ return;
253
+ }
254
+ const status = res.statusCode ?? 0;
255
+ if (status === 405) {
256
+ res.resume();
257
+ standaloneRequest = void 0;
258
+ return;
259
+ }
260
+ if (status === 401 || status === 403 || status === 404) {
261
+ res.resume();
262
+ standaloneRequest = void 0;
263
+ finish(1);
264
+ return;
265
+ }
266
+ const contentType = (headerValue(res.headers, "content-type") ?? "").toLowerCase();
267
+ if (status !== 200 || !contentType.includes("text/event-stream")) {
268
+ res.resume();
269
+ standaloneRequest = void 0;
270
+ scheduleStandaloneReconnect();
271
+ return;
272
+ }
273
+ standaloneAttempts = 0;
274
+ trackResponse(res);
275
+ const parser = createSseParser(
276
+ (event) => {
277
+ if (event.id !== void 0) lastEventId = event.id;
278
+ emitPayload(event.data, false);
279
+ },
280
+ () => {
281
+ fail();
282
+ res.destroy();
283
+ },
284
+ (retryMs) => {
285
+ standaloneRetryMs = retryMs;
286
+ }
287
+ );
288
+ res.on("data", (chunk) => {
289
+ if (!closed) parser.push(chunk);
290
+ });
291
+ res.once("end", () => {
292
+ parser.end();
293
+ if (standaloneRequest === req) standaloneRequest = void 0;
294
+ if (!closed) scheduleStandaloneReconnect();
295
+ });
296
+ res.once("close", () => {
297
+ if (standaloneRequest === req) standaloneRequest = void 0;
298
+ if (!closed) scheduleStandaloneReconnect();
299
+ });
300
+ res.once("error", () => {
301
+ if (standaloneRequest === req) standaloneRequest = void 0;
302
+ if (!closed) scheduleStandaloneReconnect();
303
+ });
304
+ }
305
+ );
306
+ standaloneRequest = req;
307
+ req.on("error", () => {
308
+ if (standaloneRequest === req) standaloneRequest = void 0;
309
+ if (!closed) scheduleStandaloneReconnect();
310
+ });
311
+ req.end();
312
+ };
313
+ const scheduleStandaloneReconnect = () => {
314
+ if (closed || !sessionId || standaloneRequest || standaloneReconnectTimer) return;
315
+ if (standaloneAttempts >= SSE_RECONNECT_MAX_ATTEMPTS) {
316
+ fail();
317
+ return;
318
+ }
319
+ const delayMs = Math.min(standaloneRetryMs * 2 ** standaloneAttempts, SSE_RECONNECT_MAX_MS);
320
+ standaloneAttempts += 1;
321
+ standaloneReconnectTimer = setTimeout(() => {
322
+ standaloneReconnectTimer = void 0;
323
+ openStandaloneSse();
324
+ }, delayMs);
325
+ standaloneReconnectTimer.unref();
326
+ };
327
+ const postMessage = (body, method, expectedResponseId) => new Promise((resolve, reject) => {
328
+ if (closed) {
329
+ resolve();
330
+ return;
331
+ }
332
+ const isInitialize = method === "initialize";
333
+ const req = httpRequest(
334
+ targetUrl,
335
+ {
336
+ method: "POST",
337
+ agent,
338
+ headers: {
339
+ ...baseHeaders(),
340
+ "Content-Type": "application/json",
341
+ Accept: "application/json, text/event-stream",
342
+ "Content-Length": String(body.length)
343
+ }
344
+ },
345
+ (res) => {
346
+ const status = res.statusCode ?? 0;
347
+ const sid = headerValue(res.headers, "mcp-session-id");
348
+ if (sid) sessionId = sid;
349
+ if (status === 202) {
350
+ res.resume();
351
+ if (expectedResponseId !== void 0) {
352
+ reject(new Error("Desktop MCP HTTP POST returned 202 for a request"));
353
+ return;
354
+ }
355
+ res.once("end", () => {
356
+ if (!closed && method === "notifications/initialized" && sessionId) {
357
+ openStandaloneSse();
358
+ }
359
+ resolve();
360
+ });
361
+ res.once("close", () => {
362
+ if (!res.complete) reject(new Error("Desktop MCP HTTP response closed prematurely"));
363
+ else resolve();
364
+ });
365
+ res.once("error", reject);
366
+ return;
367
+ }
368
+ if (status < 200 || status >= 300) {
369
+ res.resume();
370
+ reject(new Error(`Desktop MCP HTTP POST failed with status ${status}`));
371
+ return;
372
+ }
373
+ const matchesExpectedResponse = (item) => expectedResponseId !== void 0 && isRecord(item) && item.id === expectedResponseId && ("result" in item || "error" in item);
374
+ const contentType = (headerValue(res.headers, "content-type") ?? "").toLowerCase();
375
+ if (contentType.includes("text/event-stream")) {
376
+ let sawResponse = false;
377
+ trackResponse(res);
378
+ const parser = createSseParser(
379
+ (event) => emitPayload(event.data, isInitialize, (item) => {
380
+ if (matchesExpectedResponse(item)) sawResponse = true;
381
+ }),
382
+ () => {
383
+ fail();
384
+ res.destroy();
385
+ reject(new Error("Desktop MCP SSE buffer exceeded its limit"));
386
+ }
387
+ );
388
+ res.on("data", (chunk) => {
389
+ if (!closed) parser.push(chunk);
390
+ });
391
+ res.once("end", () => {
392
+ parser.end();
393
+ if (!closed && expectedResponseId !== void 0 && !sawResponse) {
394
+ reject(new Error("Desktop MCP HTTP SSE stream ended before returning a response"));
395
+ } else {
396
+ resolve();
397
+ }
398
+ });
399
+ res.once("close", () => {
400
+ if (!res.complete) reject(new Error("Desktop MCP HTTP response closed prematurely"));
401
+ else resolve();
402
+ });
403
+ res.once("error", reject);
404
+ return;
405
+ }
406
+ if (contentType.includes("application/json")) {
407
+ const chunks = [];
408
+ let totalBytes = 0;
409
+ let overflowed = false;
410
+ res.on("data", (chunk) => {
411
+ if (closed || overflowed) return;
412
+ totalBytes += chunk.length;
413
+ if (totalBytes > MAX_MCP_REQUEST_BYTES) {
414
+ overflowed = true;
415
+ chunks.length = 0;
416
+ fail();
417
+ res.destroy();
418
+ reject(new Error("Desktop MCP HTTP JSON response exceeded its limit"));
419
+ return;
420
+ }
421
+ chunks.push(chunk);
422
+ });
423
+ res.once("end", () => {
424
+ if (overflowed) return;
425
+ let sawResponse = false;
426
+ if (!closed) {
427
+ emitPayload(
428
+ Buffer.concat(chunks, totalBytes).toString("utf8"),
429
+ isInitialize,
430
+ (item) => {
431
+ if (matchesExpectedResponse(item)) sawResponse = true;
432
+ }
433
+ );
434
+ }
435
+ if (!closed && expectedResponseId !== void 0 && !sawResponse) {
436
+ reject(
437
+ new Error("Desktop MCP HTTP JSON response did not include a matching response")
438
+ );
439
+ } else {
440
+ resolve();
441
+ }
442
+ });
443
+ res.once("close", () => {
444
+ if (overflowed) return;
445
+ if (!res.complete) reject(new Error("Desktop MCP HTTP response closed prematurely"));
446
+ else resolve();
447
+ });
448
+ res.once("error", reject);
449
+ return;
450
+ }
451
+ res.resume();
452
+ reject(new Error(`Desktop MCP returned unexpected content type: ${contentType}`));
453
+ }
454
+ );
455
+ activeRequests.add(req);
456
+ const untrack = () => activeRequests.delete(req);
457
+ req.once("close", untrack);
458
+ req.once("error", (error) => {
459
+ untrack();
460
+ reject(error);
461
+ });
462
+ req.end(body);
463
+ });
464
+ const handleFrame = (frame) => {
465
+ if (closed) return;
466
+ const body = frame.at(-1) === 13 ? frame.subarray(0, -1) : frame;
467
+ if (body.length > MAX_MCP_REQUEST_BYTES) {
468
+ fail();
469
+ return;
470
+ }
471
+ if (body.length === 0) {
472
+ fail();
473
+ return;
474
+ }
475
+ let parsed;
476
+ try {
477
+ parsed = JSON.parse(body.toString("utf8"));
478
+ } catch {
479
+ fail();
480
+ return;
481
+ }
482
+ if (!isRecord(parsed)) {
483
+ fail();
484
+ return;
485
+ }
486
+ const method = typeof parsed.method === "string" ? parsed.method : void 0;
487
+ const expectedResponseId = method !== void 0 && (typeof parsed.id === "string" || typeof parsed.id === "number") ? parsed.id : void 0;
488
+ const payload = Buffer.from(body);
489
+ if (method === "initialize") {
490
+ const init = postMessage(payload, method, expectedResponseId).catch(fail).finally(() => {
491
+ if (initializing === init) initializing = void 0;
492
+ });
493
+ initializing = init;
494
+ return;
495
+ }
496
+ const send = () => postMessage(payload, method, expectedResponseId).catch(fail);
497
+ if (initializing) {
498
+ void initializing.then(() => {
499
+ if (!closed) return send();
500
+ });
501
+ } else {
502
+ void send();
503
+ }
504
+ };
505
+ let pendingChunks = [];
506
+ let pendingLength = 0;
507
+ const maxLineBytes = MAX_MCP_REQUEST_BYTES + 1;
508
+ const onData = (chunk) => {
509
+ if (closed) return;
510
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
511
+ let frameStart = 0;
512
+ let newlineIndex = bytes.indexOf(10);
513
+ while (newlineIndex >= 0) {
514
+ const tail = bytes.subarray(frameStart, newlineIndex);
515
+ const frameLength = pendingLength + tail.length;
516
+ if (frameLength > maxLineBytes) {
517
+ fail();
518
+ return;
519
+ }
520
+ const frame = pendingLength === 0 ? tail : Buffer.concat([...pendingChunks, tail], frameLength);
521
+ pendingChunks = [];
522
+ pendingLength = 0;
523
+ handleFrame(frame);
524
+ if (closed) return;
525
+ frameStart = newlineIndex + 1;
526
+ newlineIndex = bytes.indexOf(10, frameStart);
527
+ }
528
+ if (frameStart < bytes.length) {
529
+ const remainder = bytes.subarray(frameStart);
530
+ pendingChunks.push(remainder);
531
+ pendingLength += remainder.length;
532
+ if (pendingLength > maxLineBytes) {
533
+ fail();
534
+ }
535
+ }
536
+ };
537
+ const inputClosed = () => finish(pendingLength > 0 ? 1 : 0);
538
+ const onSignal = () => finish(0);
539
+ const listenSignals = streams.input === process.stdin;
540
+ if (listenSignals) {
541
+ process.once("SIGINT", onSignal);
542
+ process.once("SIGTERM", onSignal);
543
+ }
544
+ streams.input.on("data", onData);
545
+ streams.input.once("end", inputClosed);
546
+ streams.input.once("close", inputClosed);
547
+ streams.input.once("error", fail);
548
+ streams.output.on("error", fail);
549
+ if (streams.input.readableEnded || streams.input.destroyed) inputClosed();
550
+ const terminateSession = async (timeoutMs) => {
551
+ if (!sessionId) return;
552
+ let timer;
553
+ let req;
554
+ try {
555
+ await Promise.race([
556
+ new Promise((resolve) => {
557
+ req = httpRequest(
558
+ targetUrl,
559
+ {
560
+ method: "DELETE",
561
+ agent,
562
+ headers: baseHeaders()
563
+ },
564
+ (res) => {
565
+ res.resume();
566
+ res.once("end", resolve);
567
+ res.once("close", resolve);
568
+ }
569
+ );
570
+ req.once("error", () => resolve());
571
+ req.end();
572
+ }),
573
+ new Promise((resolve) => {
574
+ timer = setTimeout(resolve, timeoutMs);
575
+ timer.unref();
576
+ })
577
+ ]);
578
+ } finally {
579
+ clearTimeout(timer);
580
+ req?.destroy();
581
+ }
582
+ };
583
+ try {
584
+ return await done.promise;
585
+ } finally {
586
+ closed = true;
587
+ clearTimeout(standaloneReconnectTimer);
588
+ standaloneReconnectTimer = void 0;
589
+ streams.input.off("data", onData);
590
+ streams.input.off("end", inputClosed);
591
+ streams.input.off("close", inputClosed);
592
+ streams.input.off("error", fail);
593
+ if (listenSignals) {
594
+ process.off("SIGINT", onSignal);
595
+ process.off("SIGTERM", onSignal);
596
+ }
597
+ try {
598
+ standaloneRequest?.destroy();
599
+ standaloneRequest = void 0;
600
+ for (const req of activeRequests) req.destroy();
601
+ activeRequests.clear();
602
+ for (const res of activeResponses) res.destroy();
603
+ activeResponses.clear();
604
+ await terminateSession(options.terminateTimeoutMs ?? TERMINATE_SESSION_TIMEOUT_MS);
605
+ } finally {
606
+ shutdownController.abort();
607
+ agent.destroy();
608
+ streams.input.destroy();
609
+ await outputChain.catch(() => void 0);
610
+ streams.output.off("error", fail);
611
+ }
612
+ }
613
+ }
614
+
615
+ // packages/host-runtime/src/desktop-mcp-client-main.ts
616
+ var arguments_ = process.argv.slice(2);
617
+ process.exitCode = await runDesktopMcpClient(
618
+ arguments_[0] === "--codexhost-desktop-mcp-client" ? arguments_.slice(1) : arguments_
619
+ );