@liberseek/boft-cli-win32-arm64 0.8.4 → 0.8.6

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 (40) hide show
  1. package/README.md +2 -2
  2. package/THIRD_PARTY_NOTICES.txt +6 -2
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +129 -28
  5. package/app/console-web.js +336 -78
  6. package/app/desktop-controller.mjs +1741 -60
  7. package/app/host-runtime.mjs +4983 -2002
  8. package/app/plugins/antigravity/plugin.mjs +423 -63
  9. package/app/plugins/claude-code/plugin.mjs +417 -264
  10. package/app/plugins/codebuddy/plugin.mjs +256 -134
  11. package/app/plugins/codex-usage/plugin.mjs +97 -32
  12. package/app/plugins/copilot/plugin.mjs +122 -57
  13. package/app/plugins/cursor-cli/plugin.mjs +236 -139
  14. package/app/plugins/deepseek-harness/plugin.mjs +584 -86
  15. package/app/plugins/devin/assets/icon.svg +1 -0
  16. package/app/plugins/devin/manifest.json +30 -0
  17. package/app/plugins/devin/plugin.mjs +23425 -0
  18. package/app/plugins/enabled.json +2 -0
  19. package/app/plugins/grok/plugin.mjs +839 -500
  20. package/app/plugins/hermes/plugin.mjs +522 -200
  21. package/app/plugins/kimi-code/plugin.mjs +134 -22
  22. package/app/plugins/kiro-cli/plugin.mjs +84 -19
  23. package/app/plugins/muse/plugin.mjs +74 -9
  24. package/app/plugins/omp/plugin.mjs +104 -39
  25. package/app/plugins/opencode/plugin.mjs +126 -61
  26. package/app/plugins/pi/plugin.mjs +1769 -468
  27. package/app/plugins/qoder/plugin.mjs +9617 -8682
  28. package/app/plugins/qoder-cn/plugin.mjs +9617 -8682
  29. package/app/plugins/qwen-code/assets/icon.svg +1 -0
  30. package/app/plugins/qwen-code/manifest.json +29 -0
  31. package/app/plugins/qwen-code/plugin.mjs +29366 -0
  32. package/app/plugins/workbuddy/plugin.mjs +256 -134
  33. package/app/plugins/zcode/plugin.mjs +265 -42
  34. package/app/renderer-extension.js +3286 -528
  35. package/bin/boft.exe +0 -0
  36. package/libexec/boft-node-repl.exe +0 -0
  37. package/libexec/boft-shim.exe +0 -0
  38. package/libexec/boft-updater.exe +0 -0
  39. package/licenses/Qwen-Code-SDK-LICENSE.txt +203 -0
  40. package/package.json +2 -2
@@ -65,6 +65,12 @@ async function openRendererLocalPage(execute, url2, targets) {
65
65
  }
66
66
 
67
67
  // packages/desktop-control/src/cdp-client.ts
68
+ var CdpConnectionClosedError = class extends Error {
69
+ constructor(message) {
70
+ super(message);
71
+ this.name = "CdpConnectionClosedError";
72
+ }
73
+ };
68
74
  function cdpExceptionMessage(details, fallback) {
69
75
  const exception = details.exception;
70
76
  if (isRecord(exception) && typeof exception.description === "string" && exception.description) {
@@ -152,8 +158,14 @@ var CdpClient = class _CdpClient {
152
158
  this.#socket = socket;
153
159
  this.#commandTimeoutMs = commandTimeoutMs;
154
160
  socket.addEventListener("message", (event) => this.#onMessage(event));
155
- socket.addEventListener("error", () => this.#fail(new Error("CDP WebSocket failed")));
156
- socket.addEventListener("close", () => this.#fail(new Error("CDP WebSocket closed")));
161
+ socket.addEventListener(
162
+ "error",
163
+ () => this.#disconnect(new CdpConnectionClosedError("CDP WebSocket failed"))
164
+ );
165
+ socket.addEventListener(
166
+ "close",
167
+ () => this.#disconnect(new CdpConnectionClosedError("CDP WebSocket closed"))
168
+ );
157
169
  }
158
170
  static async connect(url2, options = {}) {
159
171
  loopbackUrl(url2, ["ws:", "wss:"]);
@@ -201,7 +213,7 @@ var CdpClient = class _CdpClient {
201
213
  };
202
214
  }
203
215
  #send(method, params, sessionId) {
204
- if (this.#closed) return Promise.reject(new Error("CDP client is closed"));
216
+ if (this.#closed) return Promise.reject(new CdpConnectionClosedError("CDP client is closed"));
205
217
  const id = this.#nextId++;
206
218
  return new Promise((resolve, reject) => {
207
219
  const timeout = setTimeout(() => {
@@ -227,18 +239,40 @@ var CdpClient = class _CdpClient {
227
239
  returnByValue: true
228
240
  });
229
241
  if (!isRecord(response)) throw new Error("Runtime.evaluate returned an invalid result");
230
- if (isRecord(response.exceptionDetails)) {
231
- throw new Error(cdpExceptionMessage(response.exceptionDetails, "Renderer evaluation failed"));
232
- }
233
- if (!isRecord(response.result) || !("value" in response.result)) {
234
- throw new Error("Runtime.evaluate did not return a value");
242
+ try {
243
+ if (isRecord(response.exceptionDetails)) {
244
+ throw new Error(
245
+ cdpExceptionMessage(response.exceptionDetails, "Renderer evaluation failed")
246
+ );
247
+ }
248
+ if (!isRecord(response.result) || !("value" in response.result)) {
249
+ throw new Error("Runtime.evaluate did not return a value");
250
+ }
251
+ return response.result.value;
252
+ } finally {
253
+ const objects = [
254
+ response.result,
255
+ isRecord(response.exceptionDetails) ? response.exceptionDetails.exception : void 0
256
+ ];
257
+ const ids = new Set(
258
+ objects.flatMap(
259
+ (object2) => isRecord(object2) && typeof object2.objectId === "string" ? [object2.objectId] : []
260
+ )
261
+ );
262
+ await Promise.all(
263
+ [...ids].map(
264
+ (objectId) => this.command("Runtime.releaseObject", { objectId }).catch(() => void 0)
265
+ )
266
+ );
235
267
  }
236
- return response.result.value;
237
268
  }
238
269
  close() {
270
+ this.#disconnect(new CdpConnectionClosedError("CDP client closed"));
271
+ }
272
+ #disconnect(error51) {
239
273
  if (this.#closed) return;
240
274
  this.#closed = true;
241
- this.#fail(new Error("CDP client closed"));
275
+ this.#fail(error51);
242
276
  this.#listeners.clear();
243
277
  this.#socket.close();
244
278
  }
@@ -3308,10 +3342,10 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
3308
3342
  const shape = def.shape;
3309
3343
  const propValues = {};
3310
3344
  for (const key in shape) {
3311
- const field = shape[key]._zod;
3312
- if (field.values) {
3345
+ const field2 = shape[key]._zod;
3346
+ if (field2.values) {
3313
3347
  propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
3314
- for (const v of field.values)
3348
+ for (const v of field2.values)
3315
3349
  propValues[key].add(v);
3316
3350
  }
3317
3351
  }
@@ -14952,6 +14986,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
14952
14986
  cachedInputTokens: count,
14953
14987
  cacheWriteInputTokens: count,
14954
14988
  cacheKnownInputTokens: count,
14989
+ cacheHitCachedInputTokens: count,
14990
+ cacheHitInputTokens: count,
14955
14991
  outputTokens: count,
14956
14992
  reasoningOutputTokens: count,
14957
14993
  /** USD at the public price, summed over the priced requests only. */
@@ -15059,6 +15095,51 @@ var hostInteractionIdSchema = opaqueIdSchema.brand();
15059
15095
  var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
15060
15096
  var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
15061
15097
 
15098
+ // packages/shared-contracts/dist/thread-questions.js
15099
+ var field = external_exports.discriminatedUnion("type", [
15100
+ external_exports.object({
15101
+ id: external_exports.string().min(1),
15102
+ type: external_exports.literal("choice"),
15103
+ prompt: external_exports.string(),
15104
+ options: external_exports.array(external_exports.object({
15105
+ value: external_exports.string().min(1),
15106
+ label: external_exports.string(),
15107
+ description: external_exports.string().optional()
15108
+ })).min(1),
15109
+ multiple: external_exports.boolean(),
15110
+ allowOther: external_exports.boolean(),
15111
+ optional: external_exports.boolean()
15112
+ }),
15113
+ external_exports.object({
15114
+ id: external_exports.string().min(1),
15115
+ type: external_exports.literal("text"),
15116
+ prompt: external_exports.string(),
15117
+ multiline: external_exports.boolean(),
15118
+ secret: external_exports.literal(false),
15119
+ optional: external_exports.boolean(),
15120
+ placeholder: external_exports.string().optional(),
15121
+ prefill: external_exports.string().optional()
15122
+ })
15123
+ ]);
15124
+ var threadQuestionSchema = external_exports.object({
15125
+ interactionId: external_exports.string().min(1),
15126
+ turnId: external_exports.string().min(1),
15127
+ title: external_exports.string().optional(),
15128
+ questions: external_exports.array(field).min(1)
15129
+ }).refine(({ questions }) => questions.some((q) => q.type === "choice" && q.multiple), {
15130
+ message: "Shared cards require at least one multi-select question"
15131
+ });
15132
+ var threadQuestionsListParamsSchema = external_exports.strictObject({ threadId: external_exports.string().min(1) });
15133
+ var threadQuestionsResultSchema = external_exports.object({ questions: external_exports.array(threadQuestionSchema) });
15134
+ var threadQuestionRespondParamsSchema = external_exports.strictObject({
15135
+ threadId: external_exports.string().min(1),
15136
+ turnId: external_exports.string().min(1),
15137
+ interactionId: external_exports.string().min(1),
15138
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
15139
+ cancelled: external_exports.boolean().default(false)
15140
+ });
15141
+ var threadQuestionRespondResultSchema = external_exports.object({ accepted: external_exports.literal(true) });
15142
+
15062
15143
  // packages/shared-contracts/dist/harness-plugins.js
15063
15144
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
15064
15145
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -15818,6 +15899,21 @@ var threadSteeringInspectParamsSchema = external_exports.object({
15818
15899
  /** The text about to be steered; a Harness command always stops and restarts. */
15819
15900
  text: external_exports.string().optional()
15820
15901
  }).strict();
15902
+ var threadSteeringContextSchema = external_exports.object({
15903
+ kind: external_exports.literal("application"),
15904
+ value: external_exports.string().transform((text, context) => {
15905
+ try {
15906
+ return JSON.parse(text);
15907
+ } catch {
15908
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
15909
+ return external_exports.NEVER;
15910
+ }
15911
+ }).pipe(external_exports.object({
15912
+ expectedTurnId: hostTurnIdSchema,
15913
+ clientUserMessageId: external_exports.string().min(1),
15914
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
15915
+ }).strict())
15916
+ }).strict().transform((context) => context.value);
15821
15917
  var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
15822
15918
  var threadSteeringInspectResultSchema = external_exports.object({
15823
15919
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
@@ -15828,7 +15924,10 @@ var harnessPluginRouteSchema = external_exports.object({
15828
15924
  harnessId: harnessPluginIdSchema,
15829
15925
  model: harnessModelRefSchema.optional(),
15830
15926
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15831
- permissionModeId: harnessPermissionModeIdSchema.optional()
15927
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
15928
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
15929
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
15930
+ prewarm: external_exports.literal(true).optional()
15832
15931
  }).strict();
15833
15932
 
15834
15933
  // packages/shared-contracts/dist/harness-launch-settings.js
@@ -16704,10 +16803,102 @@ function retainRendererHostResponses(client, hostId2, target) {
16704
16803
  };
16705
16804
  }
16706
16805
 
16806
+ // packages/desktop-control/src/renderer-prewarm-consumption.ts
16807
+ function isolateRendererPrewarmConsumption(manager, discardExternal) {
16808
+ const record3 = (value) => value !== null && typeof value === "object";
16809
+ if (!record3(manager) || !record3(manager.threadCreation)) return null;
16810
+ const creation = manager.threadCreation;
16811
+ const originalStart = manager.startConversation;
16812
+ const original = creation.createConversation;
16813
+ const params = creation.params;
16814
+ if (typeof originalStart !== "function" || typeof original !== "function" || !record3(params))
16815
+ return null;
16816
+ const prototype = Object.getPrototypeOf(creation);
16817
+ if (!record3(prototype) || typeof prototype.constructor !== "function") return null;
16818
+ if (Object.keys(creation).some((key) => key !== "params" && typeof creation[key] !== "function") || /#[A-Za-z_$]/u.test(Function.prototype.toString.call(prototype.constructor)))
16819
+ return null;
16820
+ const pool = params.prewarmedThreadManager;
16821
+ if (!record3(pool) || typeof pool.hasPrewarmedThread !== "function" || typeof pool.consumePrewarmedThread !== "function" || typeof pool.deletePrewarmedThread !== "function")
16822
+ return null;
16823
+ const consume = pool.consumePrewarmedThread;
16824
+ const hasPrewarm = pool.hasPrewarmedThread;
16825
+ const draftModels = /* @__PURE__ */ new Map();
16826
+ const draftIdentity = /* @__PURE__ */ Symbol("codexhost draft creation");
16827
+ const external = (model2) => typeof model2 === "string" && model2.startsWith("codexhost/");
16828
+ const routedStart = function(input, options, ...args) {
16829
+ const draftId = record3(options) ? options.clientThreadId : null;
16830
+ const mode = record3(input) && record3(input.collaborationMode) ? input.collaborationMode : null;
16831
+ const origin = mode ? Reflect.get(mode, draftIdentity) : void 0;
16832
+ if (mode && record3(mode.settings) && external(mode.settings.model))
16833
+ return originalStart.call(this, input, options, ...args);
16834
+ const model2 = (typeof draftId === "string" ? draftModels.get(draftId) : void 0) ?? (typeof origin === "string" ? draftModels.get(origin) : void 0);
16835
+ if (!model2) return originalStart.call(this, input, options, ...args);
16836
+ if (!record3(input) || !record3(input.collaborationMode) || !record3(input.collaborationMode.settings))
16837
+ throw new Error("External draft creation is missing its native Model settings");
16838
+ const routed = {
16839
+ ...input,
16840
+ collaborationMode: {
16841
+ ...input.collaborationMode,
16842
+ settings: { ...input.collaborationMode.settings, model: model2 }
16843
+ }
16844
+ };
16845
+ return originalStart.call(this, routed, options, ...args);
16846
+ };
16847
+ const wrapped = function(input, ...args) {
16848
+ const mode = record3(input) && record3(input.collaborationMode) ? input.collaborationMode : null;
16849
+ const expected = mode && record3(mode.settings) ? mode.settings.model : null;
16850
+ const scopedPool = Object.create(pool);
16851
+ scopedPool.hasPrewarmedThread = (...parameters) => hasPrewarm.apply(pool, parameters);
16852
+ scopedPool.consumePrewarmedThread = async (...consumeArgs) => {
16853
+ const warmed = await consume.apply(pool, consumeArgs);
16854
+ if (!record3(warmed) || !record3(warmed.response)) return warmed;
16855
+ const response = warmed.response;
16856
+ if (!external(expected) && !external(response.model)) return warmed;
16857
+ if (external(expected) && expected === response.model) return warmed;
16858
+ if (record3(response.thread) && typeof response.thread.id === "string") {
16859
+ const threadId = response.thread.id;
16860
+ if (external(response.model)) discardExternal(threadId);
16861
+ else
16862
+ void Promise.resolve().then(() => pool.deletePrewarmedThread(threadId)).catch(() => void 0);
16863
+ }
16864
+ return null;
16865
+ };
16866
+ const invocation = Object.create(creation);
16867
+ invocation.params = { ...params, prewarmedThreadManager: scopedPool };
16868
+ return original.call(invocation, input, ...args);
16869
+ };
16870
+ creation.createConversation = wrapped;
16871
+ manager.startConversation = routedStart;
16872
+ return {
16873
+ selectDraft(draftId, model2, creationModes = []) {
16874
+ if (draftId === void 0) {
16875
+ if (model2 === null) draftModels.clear();
16876
+ } else if (model2 === null) draftModels.delete(draftId);
16877
+ else {
16878
+ if (!draftId.startsWith("client-new-thread:") || !external(model2))
16879
+ throw new Error("External draft route is missing its client Thread identity");
16880
+ draftModels.set(draftId, model2);
16881
+ for (const mode of creationModes)
16882
+ Object.defineProperty(mode, draftIdentity, {
16883
+ configurable: true,
16884
+ enumerable: true,
16885
+ value: draftId
16886
+ });
16887
+ }
16888
+ },
16889
+ dispose() {
16890
+ draftModels.clear();
16891
+ if (manager.startConversation === routedStart) manager.startConversation = originalStart;
16892
+ if (creation.createConversation === wrapped) creation.createConversation = original;
16893
+ }
16894
+ };
16895
+ }
16896
+
16707
16897
  // packages/desktop-control/src/renderer-draft-prewarm-runtime.ts
16708
- function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewarmedThreadManager, isCurrentManager, retainResponses = retainRendererHostResponses) {
16898
+ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewarmedThreadManager, isCurrentManager, retainResponses = retainRendererHostResponses, isolateConsumption = isolateRendererPrewarmConsumption, sendControlRequest) {
16709
16899
  let disposed = false;
16710
16900
  const originalSend = bridge.sendRequest;
16901
+ const controlSend = (method, parameters) => sendControlRequest ? sendControlRequest(method, parameters) : originalSend.call(bridge, method, parameters);
16711
16902
  const originalPrewarm = bridge.prewarmThreadStart;
16712
16903
  const originalOnNotification = manager.onNotification;
16713
16904
  const originalDispatchAppServerResponse = manager.dispatchAppServerResponse;
@@ -16791,7 +16982,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
16791
16982
  bridgeRequests.clear();
16792
16983
  if (isRemoteControlHost && terminate) {
16793
16984
  void Promise.resolve(
16794
- originalSend.call(bridge, "process/kill", { processHandle: failedProcessHandle })
16985
+ controlSend("process/kill", { processHandle: failedProcessHandle })
16795
16986
  ).catch(() => void 0);
16796
16987
  }
16797
16988
  };
@@ -16954,7 +17145,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
16954
17145
  ];
16955
17146
  const startedProcessHandle = bridgeProcessHandle;
16956
17147
  try {
16957
- const started = originalSend.call(bridge, "process/spawn", {
17148
+ const started = controlSend("process/spawn", {
16958
17149
  command,
16959
17150
  processHandle: startedProcessHandle,
16960
17151
  cwd: "C:\\",
@@ -16975,7 +17166,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
16975
17166
  const operation = async () => {
16976
17167
  await startBridge();
16977
17168
  if (bridgeState !== "ready") throw transportError("is not ready");
16978
- await originalSend.call(bridge, "process/writeStdin", {
17169
+ await controlSend("process/writeStdin", {
16979
17170
  processHandle: bridgeProcessHandle,
16980
17171
  deltaBase64: utf8Base64(`${JSON.stringify(value)}
16981
17172
  `)
@@ -17086,26 +17277,16 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17086
17277
  if (threadId && knownOfficialThreadIds.has(threadId)) return false;
17087
17278
  return selectedModel !== null && (method.startsWith("thread/") || method.startsWith("turn/") || method.startsWith("review/"));
17088
17279
  };
17089
- const routeThreadStart = (parameters) => {
17090
- if (!isRecord3(parameters) || parameters.ephemeral === true) {
17091
- return parameters;
17092
- }
17093
- return {
17094
- ...parameters,
17095
- ...selectedModel === null ? {} : { model: selectedModel }
17096
- };
17097
- };
17098
17280
  const routedSend = (method, parameters, options) => {
17099
17281
  if (method === "turn/start" || method === "thread/resume" || method === "codexhost/thread/command/execute") {
17100
17282
  const threadId = threadIdFromParameters(parameters);
17101
17283
  if (threadId) externalPrewarms.delete(threadId);
17102
17284
  }
17103
- const routedParameters = method === "thread/start" ? routeThreadStart(parameters) : parameters;
17104
17285
  const sendBridged = () => initializeBridge().then(
17105
- () => enqueueBridgeRequest(method, routedParameters, options)
17286
+ () => enqueueBridgeRequest(method, parameters, options)
17106
17287
  );
17107
- const sendDirect = () => options === void 0 ? originalSend.call(bridge, method, routedParameters) : originalSend.call(bridge, method, routedParameters, options);
17108
- const unresolvedThreadId = shouldResolveThreadOwnership(method, routedParameters);
17288
+ const sendDirect = () => options === void 0 ? originalSend.call(bridge, method, parameters) : originalSend.call(bridge, method, parameters, options);
17289
+ const unresolvedThreadId = shouldResolveThreadOwnership(method, parameters);
17109
17290
  if (unresolvedThreadId) {
17110
17291
  return resolveThreadOwnership(unresolvedThreadId).then(
17111
17292
  (owner) => owner === "external" ? sendBridged() : sendDirect(),
@@ -17121,7 +17302,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17121
17302
  }
17122
17303
  );
17123
17304
  }
17124
- return shouldUseBridge(method, routedParameters) ? sendBridged() : sendDirect();
17305
+ return shouldUseBridge(method, parameters) ? sendBridged() : sendDirect();
17125
17306
  };
17126
17307
  const publishDraftWorkspace = (parameters) => {
17127
17308
  if (!isRecord3(parameters) || parameters.ephemeral === true) return;
@@ -17151,10 +17332,10 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17151
17332
  const discardExternalPrewarms = () => {
17152
17333
  for (const threadId of externalPrewarms) discardExternalPrewarm(threadId);
17153
17334
  };
17335
+ const restoreConsumption = isolateConsumption(manager, discardExternalPrewarm);
17154
17336
  const routedPrewarm = (parameters, options) => {
17155
- const routed = routeThreadStart(parameters);
17156
- const external = isRecord3(routed) && routed.ephemeral !== true && typeof routed.model === "string" && routed.model.startsWith("codexhost/");
17157
- const routedParameters = external ? { ...routed, codexhostPrewarm: true } : routed;
17337
+ const external = isRecord3(parameters) && parameters.ephemeral !== true && typeof parameters.model === "string" && parameters.model.startsWith("codexhost/");
17338
+ const routedParameters = external ? { ...parameters, codexhostPrewarm: true } : parameters;
17158
17339
  const generation = prewarmGeneration;
17159
17340
  publishDraftWorkspace(routedParameters);
17160
17341
  const pending = shouldUseBridge("thread/start", routedParameters) ? routedSend("thread/start", routedParameters, options) : options === void 0 ? originalPrewarm.call(bridge, routedParameters) : originalPrewarm.call(bridge, routedParameters, options);
@@ -17207,6 +17388,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17207
17388
  const policy = Object.freeze({
17208
17389
  state: "ready",
17209
17390
  hostId: hostId2,
17391
+ scopedCreation: restoreConsumption !== null,
17210
17392
  owns(candidateManager, candidate, candidateHostId, candidatePrewarmedThreadManager, requiresCurrentManager) {
17211
17393
  return !disposed && candidateManager === manager && candidate === bridge && candidateHostId === hostId2 && candidatePrewarmedThreadManager === prewarmedThreadManager && requiresCurrentManager === !!isCurrentManager;
17212
17394
  },
@@ -17215,12 +17397,13 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17215
17397
  throw new Error("Renderer request manager is retired");
17216
17398
  return manager;
17217
17399
  },
17218
- select(model2) {
17400
+ select(model2, draftId, creationModes) {
17219
17401
  if (disposed || isCurrentManager && !isCurrentManager())
17220
17402
  throw new Error("Renderer request manager is retired");
17221
17403
  if (model2 !== null && (typeof model2 !== "string" || !model2.startsWith("codexhost/"))) {
17222
17404
  throw new Error("Draft route Model must be a codexhost transport carrier");
17223
17405
  }
17406
+ restoreConsumption?.selectDraft(draftId, model2, creationModes);
17224
17407
  if (selectedModel === model2) return false;
17225
17408
  selectedModel = model2;
17226
17409
  prewarmGeneration += 1;
@@ -17241,6 +17424,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17241
17424
  disposed = true;
17242
17425
  prewarmGeneration += 1;
17243
17426
  retireResponses();
17427
+ restoreConsumption?.dispose();
17244
17428
  if (bridge.sendRequest === routedSend) bridge.sendRequest = originalSend;
17245
17429
  if (bridge.prewarmThreadStart === routedPrewarm) {
17246
17430
  bridge.prewarmThreadStart = originalPrewarm;
@@ -17257,7 +17441,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17257
17441
  bridgeReadyTimeout = null;
17258
17442
  if (isRemoteControlHost && (bridgeState === "starting" || bridgeState === "ready")) {
17259
17443
  void Promise.resolve(
17260
- originalSend.call(bridge, "process/kill", { processHandle: bridgeProcessHandle })
17444
+ controlSend("process/kill", { processHandle: bridgeProcessHandle })
17261
17445
  ).catch(() => void 0);
17262
17446
  }
17263
17447
  bridgeState = "disposed";
@@ -17277,14 +17461,14 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17277
17461
 
17278
17462
  // packages/desktop-control/src/renderer-host-discovery.ts
17279
17463
  function requestManagerFromHookState(value, hostId2) {
17280
- const record2 = (candidate) => typeof candidate === "object" && candidate !== null;
17464
+ const record3 = (candidate) => typeof candidate === "object" && candidate !== null;
17281
17465
  const manager = (candidate) => {
17282
- if (!record2(candidate) || !record2(candidate.requestClient) || !record2(candidate.prewarmedThreadManager))
17466
+ if (!record3(candidate) || !record3(candidate.requestClient) || !record3(candidate.prewarmedThreadManager))
17283
17467
  return null;
17284
17468
  const bridge = candidate.requestClient;
17285
17469
  return typeof candidate.sendRequest === "function" && typeof bridge.sendRequest === "function" && typeof bridge.prewarmThreadStart === "function" && typeof bridge.enqueueRequest === "function" && typeof candidate.prewarmedThreadManager.discardAllPrewarmedThreads === "function" ? candidate : null;
17286
17470
  };
17287
- if (!record2(value)) return null;
17471
+ if (!record3(value)) return null;
17288
17472
  const direct = manager(value) ?? manager(value.manager);
17289
17473
  if (direct) return direct;
17290
17474
  if (!hostId2 || typeof value.addManager !== "function" || typeof value.getForHostId !== "function")
@@ -17359,10 +17543,11 @@ function resolveRendererHostManager(discovery, hostId2, managerFrom = requestMan
17359
17543
  }
17360
17544
 
17361
17545
  // packages/desktop-control/src/renderer-host-routing.ts
17362
- function installRendererHostRouting(root, target, discover, resolve, createPolicy) {
17546
+ function installRendererHostRouting(root, target, discover, resolve, createPolicy, readConnection, publishRouting = true) {
17363
17547
  const existing = target.__codexhostHostRoutingV1;
17364
- if (existing) return existing;
17365
- target.__codexhostDraftPrewarmPolicyV1?.dispose?.();
17548
+ if (publishRouting && existing) return existing;
17549
+ if (publishRouting)
17550
+ target.__codexhostDraftPrewarmPolicyV1?.dispose?.();
17366
17551
  let disposed = false;
17367
17552
  let lastDiscovery = null;
17368
17553
  const routes = /* @__PURE__ */ new Map();
@@ -17389,10 +17574,20 @@ function installRendererHostRouting(root, target, discover, resolve, createPolic
17389
17574
  routes.delete(hostId2);
17390
17575
  entry?.route.policy.dispose();
17391
17576
  };
17577
+ const connectionFor = (hostId2) => {
17578
+ if (!hostId2.startsWith("remote-control:")) return void 0;
17579
+ try {
17580
+ return readConnection?.(hostId2);
17581
+ } catch {
17582
+ return null;
17583
+ }
17584
+ };
17585
+ const sameConnection = (expected, current) => expected === void 0 ? current === void 0 : current?.owner === expected.owner && current.revision === expected.revision;
17392
17586
  const routeFor = (hostId2, discovery) => {
17393
17587
  const manager = lookup(hostId2, discovery);
17588
+ const connection = connectionFor(hostId2);
17394
17589
  const previous = routes.get(hostId2);
17395
- if (manager && previous?.route.manager === manager && previous.bridge === manager.requestClient && previous.prewarmed === manager.prewarmedThreadManager && previous.route.policy.owns(
17590
+ if (manager && previous?.route.manager === manager && previous.bridge === manager.requestClient && previous.prewarmed === manager.prewarmedThreadManager && sameConnection(previous.connection, connection) && previous.route.policy.owns(
17396
17591
  manager,
17397
17592
  manager.requestClient,
17398
17593
  hostId2,
@@ -17402,7 +17597,7 @@ function installRendererHostRouting(root, target, discover, resolve, createPolic
17402
17597
  return previous.route;
17403
17598
  }
17404
17599
  retire(hostId2);
17405
- if (!manager) return null;
17600
+ if (!manager || connection === null) return null;
17406
17601
  const bridge = manager.requestClient;
17407
17602
  const prewarmed = manager.prewarmedThreadManager;
17408
17603
  const policy = createPolicy(
@@ -17411,13 +17606,14 @@ function installRendererHostRouting(root, target, discover, resolve, createPolic
17411
17606
  hostId2,
17412
17607
  target,
17413
17608
  prewarmed,
17414
- () => lookup(hostId2) === manager && manager.requestClient === bridge && manager.prewarmedThreadManager === prewarmed
17609
+ () => lookup(hostId2) === manager && sameConnection(connection, connectionFor(hostId2)) && manager.requestClient === bridge && manager.prewarmedThreadManager === prewarmed
17415
17610
  );
17416
17611
  const route = { hostId: hostId2, manager, policy };
17417
- routes.set(hostId2, { route, bridge, prewarmed });
17612
+ routes.set(hostId2, { route, bridge, prewarmed, connection });
17418
17613
  return route;
17419
17614
  };
17420
17615
  const publish = (route) => {
17616
+ if (!publishRouting) return;
17421
17617
  const policy = route?.policy;
17422
17618
  if (target.__codexhostDraftPrewarmPolicyV1 === policy) return;
17423
17619
  Object.defineProperty(target, "__codexhostDraftPrewarmPolicyV1", {
@@ -17470,7 +17666,7 @@ function installRendererHostRouting(root, target, discover, resolve, createPolic
17470
17666
  if (!composer) {
17471
17667
  for (const [hostId3, entry] of routes) {
17472
17668
  const manager = lookup(hostId3, discovery);
17473
- if (manager !== entry.route.manager || manager.requestClient !== entry.bridge || manager.prewarmedThreadManager !== entry.prewarmed)
17669
+ if (manager !== entry.route.manager || manager.requestClient !== entry.bridge || manager.prewarmedThreadManager !== entry.prewarmed || !sameConnection(entry.connection, connectionFor(hostId3)))
17474
17670
  retire(hostId3);
17475
17671
  }
17476
17672
  }
@@ -17490,10 +17686,429 @@ function installRendererHostRouting(root, target, discover, resolve, createPolic
17490
17686
  }
17491
17687
  }
17492
17688
  };
17689
+ if (publishRouting)
17690
+ Object.defineProperty(target, "__codexhostHostRoutingV1", {
17691
+ configurable: true,
17692
+ value: routing
17693
+ });
17694
+ return routing;
17695
+ }
17696
+
17697
+ // packages/desktop-control/src/renderer-host-rpc-discovery.ts
17698
+ function findRendererAppScopeStore(root) {
17699
+ const MAX_VISITED_FIBERS = 5e4;
17700
+ const record3 = (value) => typeof value === "object" && value !== null;
17701
+ const container = root.getElementById?.("root");
17702
+ if (!record3(container)) return null;
17703
+ const key = Object.getOwnPropertyNames(container).find(
17704
+ (name) => name.startsWith("__reactContainer$")
17705
+ );
17706
+ const first = key ? container[key] : null;
17707
+ if (!record3(first)) return null;
17708
+ const isScopeHandle = (value) => record3(value) && record3(value.node) && "chain" in value && "scope" in value && typeof value.get === "function" && typeof value.set === "function" && typeof value.watch === "function";
17709
+ const stack = [first];
17710
+ const seen = /* @__PURE__ */ new Set();
17711
+ while (stack.length && seen.size < MAX_VISITED_FIBERS) {
17712
+ const fiber = stack.pop();
17713
+ if (seen.has(fiber)) continue;
17714
+ seen.add(fiber);
17715
+ let hook = fiber.memoizedState;
17716
+ for (let index = 0; record3(hook) && "next" in hook && index < 150; index += 1) {
17717
+ const state = hook.memoizedState;
17718
+ const handle = record3(state) ? state.current : null;
17719
+ if (isScopeHandle(handle)) {
17720
+ let node = handle.node;
17721
+ const nodes = /* @__PURE__ */ new Set();
17722
+ while (record3(node.parent) && !nodes.has(node.parent)) {
17723
+ nodes.add(node);
17724
+ node = node.parent;
17725
+ }
17726
+ const bindings = node.familyBindings;
17727
+ return record3(bindings) && typeof bindings.get === "function" && typeof bindings.entries === "function" ? node : null;
17728
+ }
17729
+ hook = hook.next;
17730
+ }
17731
+ if (record3(fiber.sibling)) stack.push(fiber.sibling);
17732
+ if (record3(fiber.child)) stack.push(fiber.child);
17733
+ }
17734
+ return null;
17735
+ }
17736
+ function findRendererHostRpcFamily(store) {
17737
+ const record3 = (value) => typeof value === "object" && value !== null;
17738
+ const families = /* @__PURE__ */ new Set();
17739
+ for (const [definition, members] of store.familyBindings) {
17740
+ if (!record3(definition) || definition.kind !== "signal-family") continue;
17741
+ if (!record3(members) || typeof members.get !== "function") continue;
17742
+ for (const [hostId2, member] of members) {
17743
+ if (typeof hostId2 !== "string" || !/^(?:local$|durable$|remote[-:])/u.test(hostId2)) continue;
17744
+ if (!record3(member)) continue;
17745
+ const signal = member.value;
17746
+ if (!record3(signal) || typeof signal.get !== "function") continue;
17747
+ let value;
17748
+ try {
17749
+ value = signal.get();
17750
+ } catch {
17751
+ continue;
17752
+ }
17753
+ if (record3(value) && Object.keys(value).length === 2 && typeof value.status === "string" && record3(value.client) && value.client.hostId === hostId2 && "rpc" in value.client) {
17754
+ families.add(members);
17755
+ break;
17756
+ }
17757
+ }
17758
+ }
17759
+ if (families.size !== 1) return null;
17760
+ return { store, family: families.values().next().value };
17761
+ }
17762
+ function resolveRendererHostRpc(discovery, hostId2) {
17763
+ const record3 = (value2) => typeof value2 === "object" && value2 !== null;
17764
+ const signal = discovery.family.get(hostId2)?.value;
17765
+ if (!record3(signal) || typeof signal.get !== "function") return null;
17766
+ let value;
17767
+ try {
17768
+ value = signal.get();
17769
+ } catch {
17770
+ return null;
17771
+ }
17772
+ if (!record3(value) || value.status !== "ready" || !record3(value.client) || value.client.hostId !== hostId2)
17773
+ return null;
17774
+ const rpc = value.client.rpc;
17775
+ return typeof rpc === "function" || record3(rpc) ? rpc : null;
17776
+ }
17777
+ function rendererHostRpcHostIds(discovery) {
17778
+ return [...discovery.family.keys()].filter(
17779
+ (hostId2) => typeof hostId2 === "string"
17780
+ );
17781
+ }
17782
+
17783
+ // packages/desktop-control/src/renderer-host-rpc-routing.ts
17784
+ function installRendererHostRpcRouting(root, target, dependencies) {
17785
+ const existing = target.__codexhostHostRoutingV1;
17786
+ if (existing) return existing;
17787
+ let disposed = false;
17788
+ let nativeRouting = null;
17789
+ let discovery = null;
17790
+ const routes = /* @__PURE__ */ new Map();
17791
+ const read = () => {
17792
+ if (disposed) return null;
17793
+ try {
17794
+ const store = dependencies.findStore(root);
17795
+ const bound = store && discovery?.store === store ? [...store.familyBindings.values()].includes(discovery.family) : false;
17796
+ if (!bound) discovery = store ? dependencies.findFamily(store) : null;
17797
+ } catch {
17798
+ discovery = null;
17799
+ }
17800
+ return discovery;
17801
+ };
17802
+ if (!read()) return null;
17803
+ const discoverComposer = (composer) => {
17804
+ const owners = dependencies.discoverComposer(composer);
17805
+ if (!nativeRouting && (owners.managers.length || owners.registries.length)) {
17806
+ try {
17807
+ nativeRouting = dependencies.installNativeRouting();
17808
+ } catch {
17809
+ }
17810
+ }
17811
+ return owners;
17812
+ };
17813
+ const connectionFor = (hostId2) => {
17814
+ if (!hostId2.startsWith("remote-control:")) return void 0;
17815
+ try {
17816
+ return dependencies.readConnection?.(hostId2);
17817
+ } catch {
17818
+ return null;
17819
+ }
17820
+ };
17821
+ const sameConnection = (previous, current) => previous === void 0 ? current === void 0 : current?.owner === previous.owner && current.revision === previous.revision;
17822
+ const isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17823
+ const externalDrafts = /* @__PURE__ */ new Map();
17824
+ const selectedModels = /* @__PURE__ */ new Map();
17825
+ const prewarmCarrier = (carrier) => {
17826
+ const prefix = "codexhost/plugin-v1@";
17827
+ if (!carrier.startsWith(prefix)) return null;
17828
+ try {
17829
+ const json2 = carrier.slice(prefix.length).replace(/[a-f0-9]{2}/gu, (byte) => String.fromCharCode(Number.parseInt(byte, 16)));
17830
+ const route = JSON.parse(json2);
17831
+ if (!isRecord3(route)) return null;
17832
+ const payload = [...JSON.stringify({ ...route, prewarm: true })].map((character) => character.charCodeAt(0).toString(16).padStart(2, "0")).join("");
17833
+ return `${prefix}${payload}`;
17834
+ } catch {
17835
+ return null;
17836
+ }
17837
+ };
17838
+ const publishDraftWorkspace = (hostId2, cwd) => {
17839
+ if (typeof cwd !== "string" || cwd.length === 0) return;
17840
+ const drafts = isRecord3(target.__codexhostDraftWorkspacesV1) ? target.__codexhostDraftWorkspacesV1 : {};
17841
+ if (drafts[hostId2] === cwd) return;
17842
+ drafts[hostId2] = cwd;
17843
+ Object.defineProperty(target, "__codexhostDraftWorkspacesV1", {
17844
+ configurable: true,
17845
+ value: drafts
17846
+ });
17847
+ if (typeof target.dispatchEvent === "function" && typeof CustomEvent === "function") {
17848
+ target.dispatchEvent(
17849
+ new CustomEvent("codexhost:draft-workspace", { detail: { hostId: hostId2, cwd } })
17850
+ );
17851
+ }
17852
+ };
17853
+ const routeCreationCall = (message) => {
17854
+ if (!Array.isArray(message) || message.length !== 2 || message[0] !== "push") return message;
17855
+ const expression = message[1];
17856
+ if (!Array.isArray(expression) || expression.length !== 4 || expression[0] !== "pipeline")
17857
+ return message;
17858
+ const [, importId, path3, args] = expression;
17859
+ if (!Array.isArray(path3) || path3.length !== 1 || !Array.isArray(args)) return message;
17860
+ const [input, options] = args;
17861
+ if (!isRecord3(input) || !isRecord3(input.collaborationMode)) return message;
17862
+ const settings = input.collaborationMode.settings;
17863
+ if (!isRecord3(settings)) return message;
17864
+ const nativeModel = typeof settings.model === "string" ? settings.model : null;
17865
+ let model2 = null;
17866
+ if (path3[0] === "startConversation") {
17867
+ const draftId = isRecord3(options) ? options.clientThreadId : null;
17868
+ model2 = typeof draftId === "string" ? externalDrafts.get(draftId)?.model ?? null : null;
17869
+ } else if (path3[0] === "prewarmConversation") {
17870
+ if (input.ephemeral !== true) publishDraftWorkspace("local", input.cwd);
17871
+ const selected = selectedModels.get("local") ?? null;
17872
+ const carrier = nativeModel?.startsWith("codexhost/") ? nativeModel : selected;
17873
+ model2 = carrier ? prewarmCarrier(carrier) : null;
17874
+ }
17875
+ if (!model2) return message;
17876
+ if (path3[0] === "startConversation" && nativeModel?.startsWith("codexhost/") && nativeModel !== model2)
17877
+ return message;
17878
+ return [
17879
+ "push",
17880
+ [
17881
+ "pipeline",
17882
+ importId,
17883
+ path3,
17884
+ [
17885
+ {
17886
+ ...input,
17887
+ collaborationMode: { ...input.collaborationMode, settings: { ...settings, model: model2 } }
17888
+ },
17889
+ ...args.slice(1)
17890
+ ]
17891
+ ]
17892
+ ];
17893
+ };
17894
+ const port = dependencies.portPrototype;
17895
+ const originalPostMessage = port.postMessage;
17896
+ const postMessage = function(message, ...rest) {
17897
+ let routed = message;
17898
+ try {
17899
+ routed = disposed || routes.size === 0 ? message : routeCreationCall(message);
17900
+ } catch {
17901
+ routed = message;
17902
+ }
17903
+ return originalPostMessage.call(this, routed, ...rest);
17904
+ };
17905
+ port.postMessage = postMessage;
17906
+ const createRoute = (hostId2, rpc, connection) => {
17907
+ let retired = false;
17908
+ const isCurrent = () => {
17909
+ if (retired || disposed || routes.get(hostId2)?.rpc !== rpc || !sameConnection(connection, connectionFor(hostId2)))
17910
+ return false;
17911
+ try {
17912
+ const current = read();
17913
+ return !!current && dependencies.resolve(current, hostId2) === rpc;
17914
+ } catch {
17915
+ return false;
17916
+ }
17917
+ };
17918
+ const manager = Object.freeze({
17919
+ kind: "main-process-rpc",
17920
+ getHostId: () => hostId2,
17921
+ sendRequest(method, params, options) {
17922
+ if (!isCurrent())
17923
+ return Promise.reject(new Error(`Renderer request manager is retired for ${hostId2}`));
17924
+ return options === void 0 ? rpc.sendRequest(method, params) : rpc.sendRequest(method, params, options);
17925
+ },
17926
+ // The main process broadcasts every app-server notification to its windows,
17927
+ // including codexhost methods Desktop's own notification table drops.
17928
+ addNotificationCallback(methods, listener) {
17929
+ const accepted = new Set(typeof methods === "string" ? [methods] : methods);
17930
+ const onMessage = (event) => {
17931
+ const { source, data } = event;
17932
+ if (source != null && source !== target) return;
17933
+ if (!isRecord3(data) || data.type !== "mcp-notification" || data.hostId !== hostId2 || typeof data.method !== "string" || !accepted.has(data.method) || !isCurrent())
17934
+ return;
17935
+ listener({ method: data.method, params: data.params });
17936
+ };
17937
+ target.addEventListener?.("message", onMessage);
17938
+ return () => target.removeEventListener?.("message", onMessage);
17939
+ }
17940
+ });
17941
+ const clearDrafts = () => {
17942
+ for (const [draftId, draft] of externalDrafts) {
17943
+ if (draft.owner === policy) externalDrafts.delete(draftId);
17944
+ }
17945
+ };
17946
+ const clear = () => isCurrent() ? Promise.resolve(rpc.clearPrewarmedThreads()).then(() => void 0) : Promise.reject(new Error("Renderer request manager is retired"));
17947
+ const policy = Object.freeze({
17948
+ state: "ready",
17949
+ hostId: hostId2,
17950
+ scopedCreation: true,
17951
+ requestTarget: () => {
17952
+ if (!isCurrent()) throw new Error("Renderer request manager is retired");
17953
+ return manager;
17954
+ },
17955
+ select(model2, draftId) {
17956
+ if (!isCurrent()) throw new Error("Renderer request manager is retired");
17957
+ if (model2 !== null && (typeof model2 !== "string" || !model2.startsWith("codexhost/"))) {
17958
+ throw new Error("Draft route Model must be a codexhost transport carrier");
17959
+ }
17960
+ if (draftId === void 0) {
17961
+ if (model2 === null) clearDrafts();
17962
+ } else if (model2 === null) {
17963
+ if (externalDrafts.get(draftId)?.owner === policy) externalDrafts.delete(draftId);
17964
+ } else {
17965
+ if (!draftId.startsWith("client-new-thread:"))
17966
+ throw new Error("External draft route is missing its client Thread identity");
17967
+ externalDrafts.set(draftId, { model: model2, owner: policy });
17968
+ }
17969
+ if ((selectedModels.get(hostId2) ?? null) === model2) return false;
17970
+ if (model2 === null) selectedModels.delete(hostId2);
17971
+ else selectedModels.set(hostId2, model2);
17972
+ void clear().catch(() => void 0);
17973
+ return true;
17974
+ },
17975
+ clear,
17976
+ dispose() {
17977
+ if (retired) return;
17978
+ retired = true;
17979
+ clearDrafts();
17980
+ selectedModels.delete(hostId2);
17981
+ }
17982
+ });
17983
+ return { hostId: hostId2, manager, policy };
17984
+ };
17985
+ const retire = (hostId2) => {
17986
+ const entry = routes.get(hostId2);
17987
+ routes.delete(hostId2);
17988
+ entry?.route.policy.dispose();
17989
+ };
17990
+ const routeFor = (hostId2, nativeRoute) => {
17991
+ if (disposed) return null;
17992
+ const connection = connectionFor(hostId2);
17993
+ const preferred = nativeRoute === void 0 ? nativeRouting?.forHost(hostId2) : nativeRoute;
17994
+ if (connection === null || preferred) {
17995
+ retire(hostId2);
17996
+ return connection === null ? null : preferred ?? null;
17997
+ }
17998
+ const current = read();
17999
+ const rpc = current ? dependencies.resolve(current, hostId2) : null;
18000
+ const previous = routes.get(hostId2);
18001
+ if (rpc && previous?.rpc === rpc && sameConnection(previous.connection, connection))
18002
+ return previous.route;
18003
+ retire(hostId2);
18004
+ if (!rpc) return null;
18005
+ const route = createRoute(hostId2, rpc, connection);
18006
+ routes.set(hostId2, { route, rpc, connection });
18007
+ return route;
18008
+ };
18009
+ const publish = (route) => {
18010
+ const policy = route?.policy;
18011
+ if (target.__codexhostDraftPrewarmPolicyV1 === policy) return;
18012
+ Object.defineProperty(target, "__codexhostDraftPrewarmPolicyV1", {
18013
+ configurable: true,
18014
+ value: policy
18015
+ });
18016
+ if (typeof target.dispatchEvent === "function" && typeof CustomEvent === "function") {
18017
+ target.dispatchEvent(new CustomEvent("codexhost:draft-prewarm-policy-changed"));
18018
+ }
18019
+ };
18020
+ const composerHostId = (owners, composer) => {
18021
+ const nativeHostId = nativeRouting?.hostIdForComposer(composer);
18022
+ if (nativeHostId) return nativeHostId;
18023
+ const hostIds = new Set((owners ?? discoverComposer(composer)).hostIds);
18024
+ const hostId2 = hostIds.size === 1 ? hostIds.values().next().value : null;
18025
+ return typeof hostId2 === "string" && hostId2 ? hostId2 : null;
18026
+ };
18027
+ const routing = {
18028
+ knownHostIds() {
18029
+ if (disposed) return [];
18030
+ try {
18031
+ if (!nativeRouting) discoverComposer();
18032
+ } catch {
18033
+ }
18034
+ const current = read();
18035
+ return [
18036
+ .../* @__PURE__ */ new Set([
18037
+ ...current ? dependencies.hostIds(current) : [],
18038
+ ...nativeRouting?.knownHostIds?.() ?? []
18039
+ ])
18040
+ ];
18041
+ },
18042
+ forHost(hostId2) {
18043
+ return hostId2 && !disposed ? routeFor(hostId2) : null;
18044
+ },
18045
+ hostIdForComposer(composer) {
18046
+ if (disposed) return null;
18047
+ try {
18048
+ return composerHostId(nativeRouting ? null : discoverComposer(composer), composer);
18049
+ } catch {
18050
+ return null;
18051
+ }
18052
+ },
18053
+ forComposer(composer) {
18054
+ if (disposed) return null;
18055
+ let hostId2;
18056
+ let preferred = null;
18057
+ try {
18058
+ const owners = nativeRouting ? null : discoverComposer(composer);
18059
+ preferred = nativeRouting?.forComposer(composer) ?? null;
18060
+ hostId2 = preferred?.hostId ?? composerHostId(owners, composer);
18061
+ } catch {
18062
+ hostId2 = null;
18063
+ }
18064
+ const route = hostId2 ? routeFor(hostId2, preferred) : null;
18065
+ if (!composer) publish(route);
18066
+ return route;
18067
+ },
18068
+ dispose() {
18069
+ if (disposed) return;
18070
+ disposed = true;
18071
+ nativeRouting?.dispose();
18072
+ nativeRouting = null;
18073
+ for (const hostId2 of [...routes.keys()]) retire(hostId2);
18074
+ discovery = null;
18075
+ externalDrafts.clear();
18076
+ selectedModels.clear();
18077
+ if (port.postMessage === postMessage) port.postMessage = originalPostMessage;
18078
+ if (target.__codexhostHostRoutingV1 === routing) {
18079
+ delete target.__codexhostHostRoutingV1;
18080
+ publish(null);
18081
+ }
18082
+ }
18083
+ };
17493
18084
  Object.defineProperty(target, "__codexhostHostRoutingV1", { configurable: true, value: routing });
17494
18085
  return routing;
17495
18086
  }
17496
18087
 
18088
+ // packages/desktop-control/src/renderer-connection-generation.ts
18089
+ function readRendererConnectionGeneration(store, hostId2) {
18090
+ if (!store) return void 0;
18091
+ const record3 = (value) => value !== null && typeof value === "object";
18092
+ const candidates = /* @__PURE__ */ new Set();
18093
+ for (const members of store.familyBindings.values()) {
18094
+ const value = members.get(hostId2)?.value;
18095
+ if (record3(value) && record3(value.state$) && record3(value.revision$) && record3(value.appServerVersion$) && typeof value.state$.get === "function" && typeof value.revision$.get === "function")
18096
+ candidates.add(value);
18097
+ }
18098
+ if (!candidates.size) return void 0;
18099
+ if (candidates.size !== 1) return null;
18100
+ const owner = candidates.values().next().value;
18101
+ if (!owner) return null;
18102
+ const state = owner.state$;
18103
+ const revision = owner.revision$;
18104
+ try {
18105
+ const current = revision.get();
18106
+ return state.get() === "connected" && typeof current === "number" && Number.isSafeInteger(current) ? { owner, revision: current } : null;
18107
+ } catch {
18108
+ return null;
18109
+ }
18110
+ }
18111
+
17497
18112
  // packages/desktop-control/src/renderer-draft-prewarm-policy.ts
17498
18113
  var REQUEST_MANAGER_WAIT_TIMEOUT_MS = 6e4;
17499
18114
  var REQUEST_MANAGER_POLL_INTERVAL_MS = 25;
@@ -17505,20 +18120,59 @@ function directRendererInstaller() {
17505
18120
  const resolveRendererHostManager = ${resolveRendererHostManager.toString()};
17506
18121
  const retainRendererHostResponses = ${retainRendererHostResponses.toString()};
17507
18122
  const createDraftPrewarmPolicyBridge = ${createDraftPrewarmPolicyBridge.toString()};
17508
- const routing = (${installRendererHostRouting.toString()})(
17509
- document, window,
17510
- (root) => discoverRendererHosts(root, committedReactAncestors, requestManagerFromHookState),
18123
+ const isolateRendererPrewarmConsumption = ${isolateRendererPrewarmConsumption.toString()};
18124
+ const findRendererAppScopeStore = ${findRendererAppScopeStore.toString()};
18125
+ const readRendererConnectionGeneration = ${readRendererConnectionGeneration.toString()};
18126
+ const discover = (root) =>
18127
+ discoverRendererHosts(root, committedReactAncestors, requestManagerFromHookState);
18128
+ const installNative = (publishRouting = true) => (${installRendererHostRouting.toString()})(
18129
+ document, window, discover,
17511
18130
  (discovery, hostId) => resolveRendererHostManager(discovery, hostId, requestManagerFromHookState),
17512
18131
  (manager, bridge, hostId, target, prewarmed, isCurrent) => createDraftPrewarmPolicyBridge(
17513
18132
  manager, bridge, hostId, target, prewarmed, isCurrent, retainRendererHostResponses,
18133
+ isolateRendererPrewarmConsumption,
17514
18134
  ),
18135
+ (hostId) => readRendererConnectionGeneration(findRendererAppScopeStore(document), hostId),
18136
+ publishRouting,
17515
18137
  );
18138
+ const installRpc = () => typeof MessagePort !== 'function' ? null : (${installRendererHostRpcRouting.toString()})(document, window, {
18139
+ findStore: ${findRendererAppScopeStore.toString()},
18140
+ findFamily: ${findRendererHostRpcFamily.toString()},
18141
+ resolve: ${resolveRendererHostRpc.toString()},
18142
+ hostIds: ${rendererHostRpcHostIds.toString()},
18143
+ discoverComposer: (composer) => {
18144
+ const source = composer?.matches?.('[data-codex-composer], [contenteditable="true"][role="textbox"]')
18145
+ ? { querySelectorAll: () => [composer] }
18146
+ : (composer ?? document);
18147
+ return discover(source);
18148
+ },
18149
+ portPrototype: MessagePort.prototype,
18150
+ installNativeRouting: () => installNative(false),
18151
+ readConnection: (hostId) => readRendererConnectionGeneration(findRendererAppScopeStore(document), hostId),
18152
+ });
18153
+ const connected = (routing) => routing.forComposer() !== null ||
18154
+ ['local', ...(routing.knownHostIds?.() ?? [])].some((hostId) => routing.forHost(hostId) !== null);
18155
+ let nativeReady = false;
18156
+ // Mixed layouts can expose native managers for only some Hosts. Keep one
18157
+ // router that selects a native owner or the current ready RPC peer per Host.
18158
+ const routing = (() => {
18159
+ if (window.__codexhostHostRoutingV1) return window.__codexhostHostRoutingV1;
18160
+ const rpc = installRpc();
18161
+ if (rpc) return rpc;
18162
+ const native = discover(document);
18163
+ if (native.managers.length || native.registries.length) {
18164
+ const routing = installNative();
18165
+ if (connected(routing)) {
18166
+ nativeReady = true;
18167
+ return routing;
18168
+ }
18169
+ routing.dispose();
18170
+ }
18171
+ throw new Error('Renderer Host request manager is unavailable');
18172
+ })();
17516
18173
  // Publish a default draft policy only when its Host is unambiguous. Host
17517
18174
  // connections can be ready even when multiple Composers coexist.
17518
- const composerRoute = routing.forComposer();
17519
- const connected = composerRoute !== null ||
17520
- ['local', ...(routing.knownHostIds?.() ?? [])].some((hostId) => routing.forHost(hostId) !== null);
17521
- if (!connected) throw new Error('Renderer Host request manager is unavailable');
18175
+ if (!nativeReady && !connected(routing)) throw new Error('Renderer Host request manager is unavailable');
17522
18176
  return { state: 'ready', reason: 'owned-request-bridge' };
17523
18177
  })()`;
17524
18178
  }
@@ -17549,6 +18203,1016 @@ function installRendererDraftPrewarmPolicyDirect(renderer) {
17549
18203
  );
17550
18204
  }
17551
18205
 
18206
+ // packages/desktop-control/src/renderer-loaded-modules.ts
18207
+ var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18208
+ var MAX_MODULES = 4096;
18209
+ var STALE_CONTEXT_ERROR = /uniqueContextId not found|Cannot find context with specified id|Execution context was destroyed|Cannot find default execution context/i;
18210
+ function isStaleContextError(error51) {
18211
+ return error51 instanceof Error && STALE_CONTEXT_ERROR.test(error51.message);
18212
+ }
18213
+ function nativeModuleCatalogExpression(urls, complete, owner) {
18214
+ return `Object.defineProperty(globalThis, '__codexhostLoadedModulesV1', {
18215
+ configurable: true,
18216
+ value: Object.freeze({ owner: ${JSON.stringify(owner)}, documentUrl: location.href, complete: ${complete}, urls: Object.freeze(${JSON.stringify(urls)}) })
18217
+ }); void 0`;
18218
+ }
18219
+ async function installRendererLoadedModules(renderer) {
18220
+ const owner = crypto.randomUUID();
18221
+ const contexts = /* @__PURE__ */ new Map();
18222
+ const contextIds = /* @__PURE__ */ new Map();
18223
+ const dirty = /* @__PURE__ */ new Set();
18224
+ let ready = false;
18225
+ let disposed = false;
18226
+ let timer;
18227
+ let publishing = Promise.resolve();
18228
+ const flush = () => {
18229
+ clearTimeout(timer);
18230
+ timer = void 0;
18231
+ const pending = [...dirty];
18232
+ dirty.clear();
18233
+ publishing = publishing.catch(() => void 0).then(async () => {
18234
+ let failure;
18235
+ for (const uniqueId of pending) {
18236
+ const context = contexts.get(uniqueId);
18237
+ if (!context || disposed) continue;
18238
+ try {
18239
+ const response = await renderer.command("Runtime.evaluate", {
18240
+ expression: nativeModuleCatalogExpression([...context.urls], context.complete, owner),
18241
+ uniqueContextId: uniqueId
18242
+ });
18243
+ if (record2(response) && record2(response.exceptionDetails))
18244
+ throw new Error("Loaded Renderer module catalog publication failed");
18245
+ } catch (error51) {
18246
+ if (contexts.get(uniqueId) !== context) continue;
18247
+ if (isStaleContextError(error51)) {
18248
+ forget(uniqueId);
18249
+ continue;
18250
+ }
18251
+ failure ??= error51;
18252
+ }
18253
+ }
18254
+ if (failure !== void 0) throw failure;
18255
+ });
18256
+ return publishing;
18257
+ };
18258
+ const schedule = (uniqueId) => {
18259
+ dirty.add(uniqueId);
18260
+ if (ready && timer === void 0)
18261
+ timer = setTimeout(() => {
18262
+ void flush().catch((error51) => {
18263
+ console.error("Could not publish loaded Renderer modules", error51);
18264
+ });
18265
+ }, 10);
18266
+ };
18267
+ const forget = (uniqueId) => {
18268
+ contexts.delete(uniqueId);
18269
+ dirty.delete(uniqueId);
18270
+ for (const [id, value] of contextIds) if (value === uniqueId) contextIds.delete(id);
18271
+ };
18272
+ const remove = (params) => {
18273
+ const byId = typeof params.executionContextId === "number" ? contextIds.get(params.executionContextId) : void 0;
18274
+ const uniqueId = typeof params.executionContextUniqueId === "string" ? params.executionContextUniqueId : byId;
18275
+ if (uniqueId) forget(uniqueId);
18276
+ };
18277
+ const listeners = [
18278
+ renderer.on("Runtime.executionContextCreated", (params) => {
18279
+ const context = record2(params) ? params.context : null;
18280
+ if (!record2(context) || typeof context.id !== "number" || typeof context.uniqueId !== "string" || !record2(context.auxData) || context.auxData.isDefault !== true)
18281
+ return;
18282
+ contextIds.set(context.id, context.uniqueId);
18283
+ contexts.set(context.uniqueId, { urls: /* @__PURE__ */ new Set(), complete: true });
18284
+ schedule(context.uniqueId);
18285
+ }),
18286
+ renderer.on("Runtime.executionContextDestroyed", (params) => {
18287
+ if (record2(params)) remove(params);
18288
+ }),
18289
+ renderer.on("Runtime.executionContextsCleared", () => {
18290
+ contextIds.clear();
18291
+ contexts.clear();
18292
+ dirty.clear();
18293
+ }),
18294
+ renderer.on("Debugger.scriptParsed", (params) => {
18295
+ if (!record2(params) || params.isModule !== true || params.hasSourceURL === true || typeof params.url !== "string" || typeof params.executionContextId !== "number")
18296
+ return;
18297
+ const uniqueId = contextIds.get(params.executionContextId);
18298
+ const context = uniqueId ? contexts.get(uniqueId) : null;
18299
+ if (!context || !uniqueId || context.urls.has(params.url)) return;
18300
+ if (context.urls.size >= MAX_MODULES) context.complete = false;
18301
+ else context.urls.add(params.url);
18302
+ schedule(uniqueId);
18303
+ })
18304
+ ];
18305
+ const dispose = () => {
18306
+ disposed = true;
18307
+ clearTimeout(timer);
18308
+ for (const unsubscribe of listeners) unsubscribe();
18309
+ for (const uniqueId of contexts.keys())
18310
+ void renderer.command("Runtime.evaluate", {
18311
+ expression: `if (globalThis.__codexhostLoadedModulesV1 === undefined || globalThis.__codexhostLoadedModulesV1?.owner === ${JSON.stringify(owner)}) { ${nativeModuleCatalogExpression([], false, owner)} }`,
18312
+ uniqueContextId: uniqueId
18313
+ }).catch(() => void 0);
18314
+ contexts.clear();
18315
+ contextIds.clear();
18316
+ dirty.clear();
18317
+ };
18318
+ try {
18319
+ await renderer.command("Runtime.enable");
18320
+ await renderer.command("Debugger.enable");
18321
+ ready = true;
18322
+ await flush();
18323
+ return dispose;
18324
+ } catch (error51) {
18325
+ dispose();
18326
+ throw error51;
18327
+ }
18328
+ }
18329
+
18330
+ // packages/desktop-control/src/renderer-native-rpc-discovery.ts
18331
+ function nativeManagerDependencies(factoryName, callers) {
18332
+ const identifier = "[$A-Z_a-z][$\\w]*";
18333
+ const escaped = factoryName.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
18334
+ const pattern = new RegExp(
18335
+ `${escaped}\\((${identifier}),(${identifier}),\\1\\.get\\((${identifier}),\\2\\),(${identifier})\\.bind\\(null,\\1\\),\\((${identifier}),(${identifier})\\)=>\\5\\((${identifier}),\\6\\)\\)`
18336
+ );
18337
+ const matches = callers.flatMap((source) => {
18338
+ const match = pattern.exec(source);
18339
+ return match?.[3] && match[4] && match[7] ? [
18340
+ {
18341
+ requestDefinition: match[3],
18342
+ isHostForConversation: match[4],
18343
+ imageDefinition: match[7]
18344
+ }
18345
+ ] : [];
18346
+ });
18347
+ return matches.length === 1 ? matches[0] : void 0;
18348
+ }
18349
+ function nativeRpcRole(source) {
18350
+ if (["dispatchMessageFromView", "threadProjectAssignments", "queuedMessageCoordination"].every(
18351
+ (part) => source.includes(part)
18352
+ ))
18353
+ return "createManager";
18354
+ if (["collectAppStateSnapshot", "getReviewPaneSnapshotMetrics", "registerReplayAdmission"].every(
18355
+ (part) => source.includes(part)
18356
+ ))
18357
+ return "createController";
18358
+ if (["getWorkInProgress", "getCachedThreadSearchSnapshot", "registerReplayAdmission"].every(
18359
+ (part) => source.includes(part)
18360
+ ))
18361
+ return "RpcManager";
18362
+ if (["prewarmedThreadManager", "onNotification", "dispatchAppServerResponse"].every(
18363
+ (part) => source.includes(part)
18364
+ ))
18365
+ return "Manager";
18366
+ return void 0;
18367
+ }
18368
+ function nativeRpcObjectShape(value) {
18369
+ if (value === null || typeof value !== "object")
18370
+ return { scope: false, services: false, controller: false };
18371
+ const candidate = value;
18372
+ const own = (keys) => keys.every((key) => Object.hasOwn(candidate, key));
18373
+ const methods = (keys) => keys.every((key) => typeof candidate[key] === "function");
18374
+ return {
18375
+ scope: own(["node", "scope", "get", "set", "watch"]) && methods(["get", "set", "watch"]),
18376
+ services: own(["appServerManagers", "remoteConnections", "applicationMenu"]) && typeof candidate.appServerManagers?.subscribe === "function",
18377
+ controller: own(["forHost", "collectAppStateSnapshot", "getReviewPaneSnapshotMetrics", "dispose"]) && methods(["forHost", "collectAppStateSnapshot", "getReviewPaneSnapshotMetrics", "dispose"])
18378
+ };
18379
+ }
18380
+ async function withNativeRpcComponents(client, install) {
18381
+ const group = `codexhost-native-rpc-${crypto.randomUUID()}`;
18382
+ const command = async (method, params) => client.command(method, params);
18383
+ const evaluate = (expression) => command("Runtime.evaluate", { expression, awaitPromise: true, objectGroup: group });
18384
+ const properties = (objectId) => command("Runtime.getProperties", { objectId, ownProperties: true });
18385
+ const call = (objectId, functionDeclaration, args = []) => command("Runtime.callFunctionOn", {
18386
+ objectId,
18387
+ functionDeclaration,
18388
+ arguments: args,
18389
+ objectGroup: group,
18390
+ returnByValue: true
18391
+ });
18392
+ try {
18393
+ const initial = await evaluate(String.raw`(() => {
18394
+ const catalog = globalThis.__codexhostLoadedModulesV1;
18395
+ if (!catalog?.complete || catalog.documentUrl !== location.href) return null;
18396
+ const urls = catalog.urls.filter(url => /^app:\/\/-\/assets\/(?:renderer-app-server-managers|app-shared)-[^/]+\.js$/.test(url));
18397
+ return { document, urls };
18398
+ })()`);
18399
+ if (!initial.result.objectId) return false;
18400
+ const holder = initial.result.objectId;
18401
+ const catalog = await call(holder, "function(){return this.urls}");
18402
+ const urls = catalog.result.value;
18403
+ if (!Array.isArray(urls) || urls.length !== 2) return false;
18404
+ const managerUrl = urls.find((url2) => url2.includes("renderer-app-server-managers"));
18405
+ const sharedUrl = urls.find((url2) => url2.includes("app-shared"));
18406
+ if (!managerUrl || !sharedUrl) return false;
18407
+ const attach = async (name, objectId) => {
18408
+ const result = await call(
18409
+ holder,
18410
+ "function(name,value){if(this.document!==document)throw Error('Renderer Realm changed');this[name]=value;return true}",
18411
+ [{ value: name }, { objectId }]
18412
+ );
18413
+ if (result.exceptionDetails) throw new Error("Native RPC discovery lost its Renderer Realm");
18414
+ };
18415
+ const imported = await evaluate(`import(${JSON.stringify(managerUrl)})`);
18416
+ if (!imported.result.objectId) return false;
18417
+ const exports = (await properties(imported.result.objectId)).result.filter(
18418
+ (entry) => entry.value?.type === "function"
18419
+ );
18420
+ let bindings = [];
18421
+ for (const entry of exports.slice(0, 3)) {
18422
+ if (!entry.value?.objectId) continue;
18423
+ const scopes = (await properties(entry.value.objectId)).internalProperties?.find(
18424
+ (entry2) => entry2.name === "[[Scopes]]"
18425
+ )?.value?.objectId;
18426
+ if (!scopes) continue;
18427
+ const modules = (await properties(scopes)).result.filter(
18428
+ (entry2) => entry2.value?.description?.startsWith("Module") && entry2.value.objectId
18429
+ );
18430
+ const moduleId = modules[0]?.value?.objectId;
18431
+ if (modules.length !== 1 || !moduleId) continue;
18432
+ bindings = (await properties(moduleId)).result;
18433
+ break;
18434
+ }
18435
+ const functions = bindings.filter((entry) => entry.value?.type === "function");
18436
+ const roles = /* @__PURE__ */ new Map();
18437
+ for (const entry of functions) {
18438
+ const role = nativeRpcRole(entry.value?.description ?? "");
18439
+ if (role) roles.set(role, [...roles.get(role) ?? [], entry]);
18440
+ }
18441
+ if (["createManager", "Manager", "RpcManager", "createController"].some(
18442
+ (role) => roles.get(role)?.length !== 1
18443
+ ))
18444
+ return false;
18445
+ const factory = roles.get("createManager")?.[0];
18446
+ if (!factory) return false;
18447
+ const dependencies = nativeManagerDependencies(
18448
+ factory.name,
18449
+ functions.map((entry) => entry.value?.description ?? "")
18450
+ );
18451
+ if (!dependencies) return false;
18452
+ for (const [role, entries] of roles) {
18453
+ const id = entries[0]?.value?.objectId;
18454
+ if (!id) return false;
18455
+ await attach(role, id);
18456
+ }
18457
+ for (const [role, name] of Object.entries(dependencies)) {
18458
+ const value = bindings.find((entry) => entry.name === name)?.value?.objectId;
18459
+ if (!value) return false;
18460
+ await attach(role, value);
18461
+ }
18462
+ const shared = await evaluate(`import(${JSON.stringify(sharedUrl)})`);
18463
+ if (!shared.result.objectId) return false;
18464
+ const sharedExports = (await properties(shared.result.objectId)).result;
18465
+ const sessions = sharedExports.filter(
18466
+ (entry) => entry.value?.type === "function" && ["getRemoteMain", "getStats", "drain", "getMainImport"].every(
18467
+ (word) => entry.value?.description?.includes(word)
18468
+ )
18469
+ );
18470
+ const sessionId = sessions[0]?.value?.objectId;
18471
+ if (sessions.length !== 1 || !sessionId) return false;
18472
+ await attach("RpcSession", sessionId);
18473
+ const serviceMatches = await command("Runtime.callFunctionOn", {
18474
+ objectId: shared.result.objectId,
18475
+ functionDeclaration: `function(){return [...new Set(Object.values(this).filter(value => (${nativeRpcObjectShape.toString()})(value).services))]}`,
18476
+ objectGroup: group
18477
+ });
18478
+ if (!serviceMatches.result.objectId) return false;
18479
+ const services = (await properties(serviceMatches.result.objectId)).result.flatMap(
18480
+ (entry) => entry.value?.type === "object" && entry.value.objectId ? [entry.value.objectId] : []
18481
+ );
18482
+ const serviceId = services[0];
18483
+ if (services.length !== 1 || !serviceId) return false;
18484
+ await attach("services", serviceId);
18485
+ const prototype = await evaluate("Object.getPrototypeOf(async function(){})");
18486
+ if (!prototype.result.objectId) return false;
18487
+ const objects = await command("Runtime.queryObjects", {
18488
+ prototypeObjectId: prototype.result.objectId,
18489
+ objectGroup: group
18490
+ });
18491
+ if (!objects.objects.objectId) return false;
18492
+ const filtered = await command("Runtime.callFunctionOn", {
18493
+ objectId: objects.objects.objectId,
18494
+ functionDeclaration: 'function(){return this.filter(fn=>fn.name==="collectAppStateSnapshot"&&String(fn).includes("collectSnapshot")).slice(0,9)}',
18495
+ objectGroup: group
18496
+ });
18497
+ if (!filtered.result.objectId) return false;
18498
+ const snapshots = (await properties(filtered.result.objectId)).result.filter(
18499
+ (entry) => entry.value?.type === "function"
18500
+ );
18501
+ if (snapshots.length > 8) return false;
18502
+ const owners = [];
18503
+ for (const snapshot of snapshots) {
18504
+ const fn = snapshot.value?.objectId;
18505
+ if (!fn) continue;
18506
+ const scopes = (await properties(fn)).internalProperties?.find(
18507
+ (entry) => entry.name === "[[Scopes]]"
18508
+ )?.value?.objectId;
18509
+ if (!scopes) continue;
18510
+ for (const scope of (await properties(scopes)).result) {
18511
+ if (!scope.value?.description?.startsWith("Closure") || !scope.value.objectId) continue;
18512
+ const candidates = (await properties(scope.value.objectId)).result;
18513
+ const controllers = [], handles = [];
18514
+ for (const binding of candidates) {
18515
+ if (binding.value?.type !== "object" || !binding.value.objectId) continue;
18516
+ const id = binding.value.objectId;
18517
+ const response = await call(
18518
+ id,
18519
+ `function(){return (${nativeRpcObjectShape.toString()})(this)}`
18520
+ );
18521
+ const shape = response.result.value;
18522
+ if (shape?.scope) handles.push(id);
18523
+ if (shape?.controller && (await call(id, "function(fn){return this.collectAppStateSnapshot===fn}", [
18524
+ { objectId: fn }
18525
+ ])).result.value === true)
18526
+ controllers.push(id);
18527
+ }
18528
+ const controller = controllers[0], handle = handles[0];
18529
+ if (controllers.length === 1 && handles.length === 1 && controller && handle)
18530
+ owners.push({ controller, scope: handle });
18531
+ }
18532
+ }
18533
+ const owner = owners[0];
18534
+ if (owners.length !== 1 || !owner) return false;
18535
+ await attach("controller", owner.controller);
18536
+ await attach("scope", owner.scope);
18537
+ return await install(holder);
18538
+ } finally {
18539
+ await client.command("Runtime.releaseObjectGroup", { objectGroup: group }).catch(() => void 0);
18540
+ }
18541
+ }
18542
+
18543
+ // packages/desktop-control/src/renderer-native-rpc-runtime.ts
18544
+ function installNativeRpcRemoteControl(components, target, dependencies) {
18545
+ if (target.__codexhostNativeRpcRemoteControlV1) return true;
18546
+ const routing = target.__codexhostHostRoutingV1;
18547
+ if (!routing) return false;
18548
+ const adapted = dependencies.createService(
18549
+ components,
18550
+ (hostId2, upstream) => dependencies.createManager(
18551
+ components,
18552
+ hostId2,
18553
+ upstream,
18554
+ target,
18555
+ dependencies.createPolicy,
18556
+ dependencies.createChannel,
18557
+ dependencies.retainInteractions
18558
+ )
18559
+ );
18560
+ const controller = components.controller;
18561
+ const originalHost = routing.forHost, originalComposer = routing.forComposer, originalDispose = routing.dispose;
18562
+ controller.dispose();
18563
+ let replacement;
18564
+ try {
18565
+ replacement = components.createController(components.scope, adapted.service);
18566
+ } catch (error51) {
18567
+ replacement = components.createController(
18568
+ components.scope,
18569
+ components.services.appServerManagers
18570
+ );
18571
+ throw error51;
18572
+ } finally {
18573
+ adapted.service[Symbol.dispose]();
18574
+ controller.forHost = (hostId2) => replacement.forHost(hostId2);
18575
+ controller.collectAppStateSnapshot = (hostId2, options) => replacement.collectAppStateSnapshot(hostId2, options);
18576
+ controller.getReviewPaneSnapshotMetrics = (hostId2) => replacement.getReviewPaneSnapshotMetrics(hostId2);
18577
+ controller.dispose = () => replacement.dispose();
18578
+ }
18579
+ const forHost = (hostId2) => {
18580
+ const route = adapted.route(hostId2);
18581
+ return route === void 0 ? originalHost.call(routing, hostId2) : route;
18582
+ };
18583
+ const forComposer = (composer) => {
18584
+ const hostId2 = routing.hostIdForComposer(composer);
18585
+ return hostId2 ? forHost(hostId2) : originalComposer.call(routing, composer);
18586
+ };
18587
+ routing.forHost = forHost;
18588
+ routing.forComposer = forComposer;
18589
+ const installation = {
18590
+ dispose() {
18591
+ if (target.__codexhostNativeRpcRemoteControlV1 !== installation) return;
18592
+ delete target.__codexhostNativeRpcRemoteControlV1;
18593
+ replacement.dispose();
18594
+ replacement = components.createController(
18595
+ components.scope,
18596
+ components.services.appServerManagers
18597
+ );
18598
+ if (routing.forHost === forHost) routing.forHost = originalHost;
18599
+ if (routing.forComposer === forComposer) routing.forComposer = originalComposer;
18600
+ routing.dispose = originalDispose;
18601
+ }
18602
+ };
18603
+ routing.dispose = () => {
18604
+ installation.dispose();
18605
+ originalDispose.call(routing);
18606
+ };
18607
+ target.__codexhostNativeRpcRemoteControlV1 = installation;
18608
+ return true;
18609
+ }
18610
+
18611
+ // packages/desktop-control/src/renderer-native-remote-manager.ts
18612
+ function createNativeRemoteManager(components, hostId2, original, target, createPolicy, createChannel, retainInteractions) {
18613
+ const source = components.scope.get(components.requestDefinition, hostId2);
18614
+ const upstream = original.dup();
18615
+ let manager;
18616
+ let policy;
18617
+ let interactions;
18618
+ let disposed = false;
18619
+ const pending = /* @__PURE__ */ new Set();
18620
+ const send = (method, params, options) => {
18621
+ const request = upstream.sendRequest(method, params, options);
18622
+ const result = Promise.resolve(request).finally(() => {
18623
+ request[Symbol.dispose]();
18624
+ pending.delete(result);
18625
+ });
18626
+ pending.add(result);
18627
+ return result;
18628
+ };
18629
+ const record3 = (value) => value !== null && typeof value === "object";
18630
+ const dispatch = (type, payload) => {
18631
+ if ((type === "mcp-request" || type === "thread-prewarm-start") && record3(payload) && record3(payload.request)) {
18632
+ const request = payload.request;
18633
+ const options = {};
18634
+ for (const key of ["priority", "timeoutMs", "source", "trace", "threadAccess"])
18635
+ if (payload[key] !== void 0) options[key] = payload[key];
18636
+ void send(String(request.method), request.params, options).then(
18637
+ (result) => {
18638
+ if (!disposed) client.onResult(request.id, result);
18639
+ },
18640
+ (error51) => {
18641
+ if (!disposed)
18642
+ client.onError(request.id, {
18643
+ code: record3(error51) ? error51.jsonRpcCode ?? error51.code ?? -32603 : -32603,
18644
+ message: error51 instanceof Error ? error51.message : String(error51)
18645
+ });
18646
+ }
18647
+ );
18648
+ return;
18649
+ }
18650
+ return source.dispatchMessage(type, payload);
18651
+ };
18652
+ const Constructor = source.constructor;
18653
+ let client;
18654
+ try {
18655
+ client = new Constructor(
18656
+ hostId2,
18657
+ dispatch,
18658
+ false,
18659
+ (id) => manager?.getConversation(id)?.threadAccess
18660
+ );
18661
+ client.setAppServerVersion(source.getAppServerVersion());
18662
+ manager = components.createManager(
18663
+ components.scope,
18664
+ hostId2,
18665
+ client,
18666
+ components.isHostForConversation.bind(null, components.scope),
18667
+ (get, id) => get(components.imageDefinition, id),
18668
+ { dispatchMessageFromView: dispatch }
18669
+ );
18670
+ manager.dispatchAppServerResponse = manager.sendAppServerResponse;
18671
+ const owned = manager;
18672
+ const ownedPolicy = createPolicy(
18673
+ owned,
18674
+ client,
18675
+ hostId2,
18676
+ target,
18677
+ owned.prewarmedThreadManager,
18678
+ () => !disposed,
18679
+ void 0,
18680
+ void 0,
18681
+ (method, params) => send(method, params, { priority: "critical" })
18682
+ );
18683
+ policy = ownedPolicy;
18684
+ owned.sendAppServerResponse = (...args) => owned.dispatchAppServerResponse(...args);
18685
+ const channel = createChannel(components, owned);
18686
+ const nativeInteractions = retainInteractions(upstream, owned, hostId2);
18687
+ interactions = nativeInteractions;
18688
+ const notify = (event) => {
18689
+ const { data, source: source2, origin } = event;
18690
+ if (disposed || source2 != null && source2 !== target || !record3(data) || data.hostId !== hostId2)
18691
+ return;
18692
+ const ownOrigin = record3(target.location) ? target.location.origin : void 0;
18693
+ if (source2 === target && ownOrigin && ownOrigin !== "null" && origin !== ownOrigin) return;
18694
+ if (data.type === "mcp-notification" && typeof data.method === "string" && !data.method.startsWith("process/"))
18695
+ owned.onNotification(data.method, data.params);
18696
+ if (data.type === "mcp-request") owned.onRequest(record3(data.request) ? data.request : data);
18697
+ };
18698
+ target.addEventListener?.("message", notify);
18699
+ return {
18700
+ route: { hostId: hostId2, manager: owned, policy: ownedPolicy },
18701
+ rpc: channel.rpc,
18702
+ ready: nativeInteractions.ready,
18703
+ dispose() {
18704
+ if (disposed) return;
18705
+ disposed = true;
18706
+ target.removeEventListener?.("message", notify);
18707
+ nativeInteractions.dispose();
18708
+ ownedPolicy.dispose();
18709
+ client.queuedRequests.length = 0;
18710
+ for (const id of [...client.requestPromises.keys()])
18711
+ client.onError(id, new Error("Remote Control connection retired"));
18712
+ channel.dispose();
18713
+ components.Manager.dispose(owned);
18714
+ void Promise.allSettled([...pending]).then(() => upstream[Symbol.dispose]());
18715
+ }
18716
+ };
18717
+ } catch (error51) {
18718
+ interactions?.dispose();
18719
+ policy?.dispose();
18720
+ if (manager) components.Manager.dispose(manager);
18721
+ upstream[Symbol.dispose]();
18722
+ throw error51;
18723
+ }
18724
+ }
18725
+
18726
+ // packages/desktop-control/src/renderer-native-rpc-channel.ts
18727
+ function createNativeRpcChannel(components, manager) {
18728
+ const channel = new MessageChannel();
18729
+ const transports = [];
18730
+ const transport = (port) => {
18731
+ const values = [];
18732
+ const readers = [];
18733
+ let closed = false;
18734
+ let failure;
18735
+ port.addEventListener("message", (event) => {
18736
+ const value = JSON.stringify(event.data);
18737
+ const reader = readers.shift();
18738
+ if (reader) reader.resolve(value);
18739
+ else values.push(value);
18740
+ });
18741
+ port.start();
18742
+ const result = {
18743
+ send(message) {
18744
+ if (closed) throw failure;
18745
+ port.postMessage(JSON.parse(message));
18746
+ },
18747
+ receive() {
18748
+ if (closed) return Promise.reject(failure);
18749
+ const value = values.shift();
18750
+ return value !== void 0 ? Promise.resolve(value) : new Promise((resolve, reject) => readers.push({ resolve, reject }));
18751
+ },
18752
+ abort(error51) {
18753
+ if (closed) return;
18754
+ closed = true;
18755
+ failure = error51 ?? new Error("Remote Control RPC manager retired");
18756
+ values.length = 0;
18757
+ for (const reader of readers.splice(0)) reader.reject(failure);
18758
+ port.close();
18759
+ }
18760
+ };
18761
+ transports.push(result);
18762
+ return result;
18763
+ };
18764
+ try {
18765
+ new components.RpcSession(transport(channel.port1), new components.RpcManager(() => manager));
18766
+ const session = new components.RpcSession(transport(channel.port2));
18767
+ const rpc = session.getRemoteMain();
18768
+ return {
18769
+ rpc,
18770
+ dispose() {
18771
+ rpc[Symbol.dispose]();
18772
+ for (const transport2 of transports) transport2.abort();
18773
+ }
18774
+ };
18775
+ } catch (error51) {
18776
+ for (const transport2 of transports) transport2.abort(error51);
18777
+ channel.port1.close();
18778
+ channel.port2.close();
18779
+ throw error51;
18780
+ }
18781
+ }
18782
+
18783
+ // packages/desktop-control/src/renderer-native-rpc-service.ts
18784
+ function createNativeRpcService(components, createRemote) {
18785
+ const source = components.services.appServerManagers.dup();
18786
+ const routes = /* @__PURE__ */ new Map();
18787
+ const subscriptions = /* @__PURE__ */ new Set();
18788
+ let refs = 1;
18789
+ const record3 = (value) => value !== null && typeof value === "object";
18790
+ const connectionSignals = (hostId2) => {
18791
+ let node = components.scope.node;
18792
+ const seen = /* @__PURE__ */ new Set();
18793
+ while (node.parent && !seen.has(node.parent) && seen.size < 100) {
18794
+ seen.add(node);
18795
+ node = node.parent;
18796
+ }
18797
+ const found = [];
18798
+ for (const members of node.familyBindings.values()) {
18799
+ const value = members.get(hostId2)?.value;
18800
+ if (record3(value) && Object.hasOwn(value, "state$") && Object.hasOwn(value, "revision$") && Object.hasOwn(value, "appServerVersion$"))
18801
+ found.push({ state$: value.state$, revision$: value.revision$ });
18802
+ }
18803
+ return found.length === 1 ? found[0] : void 0;
18804
+ };
18805
+ const service = {
18806
+ dup() {
18807
+ refs++;
18808
+ return service;
18809
+ },
18810
+ onRpcBroken(listener) {
18811
+ source.onRpcBroken(listener);
18812
+ },
18813
+ openAccount(hostId2) {
18814
+ return source.openAccount(hostId2);
18815
+ },
18816
+ subscribe(hostId2, listener) {
18817
+ if (!hostId2.startsWith("remote-control:")) return source.subscribe(hostId2, listener);
18818
+ let active = true;
18819
+ let generation = 0;
18820
+ let upstream;
18821
+ let platformRequest;
18822
+ let remote;
18823
+ let stopWatch;
18824
+ let previousRevision;
18825
+ let previousState;
18826
+ const retire = () => {
18827
+ generation++;
18828
+ platformRequest?.[Symbol.dispose]();
18829
+ platformRequest = void 0;
18830
+ remote?.dispose();
18831
+ remote = void 0;
18832
+ routes.set(hostId2, null);
18833
+ };
18834
+ const cleanup = () => {
18835
+ if (!active) return;
18836
+ active = false;
18837
+ stopWatch?.();
18838
+ retire();
18839
+ upstream?.[Symbol.dispose]();
18840
+ upstream = void 0;
18841
+ routes.delete(hostId2);
18842
+ subscriptions.delete(cleanup);
18843
+ };
18844
+ subscriptions.add(cleanup);
18845
+ const publish = async () => {
18846
+ const owner = upstream;
18847
+ const current = generation;
18848
+ if (!owner || !active) return;
18849
+ let request;
18850
+ try {
18851
+ request = owner.getCodexHome();
18852
+ platformRequest = request;
18853
+ const home = await request;
18854
+ if (!active || current !== generation || owner !== upstream) return;
18855
+ if (!/^(?:[A-Za-z]:[\\/]|\\\\)/u.test(home)) {
18856
+ routes.delete(hostId2);
18857
+ listener({ status: "ready", manager: owner });
18858
+ return;
18859
+ }
18860
+ const created = createRemote(hostId2, owner);
18861
+ remote = created;
18862
+ await created.ready;
18863
+ if (!active || current !== generation || owner !== upstream) return;
18864
+ routes.set(hostId2, created.route);
18865
+ listener({ status: "ready", manager: created.rpc });
18866
+ } catch {
18867
+ if (active && current === generation) {
18868
+ remote?.dispose();
18869
+ remote = void 0;
18870
+ routes.delete(hostId2);
18871
+ listener({ status: "ready", manager: owner });
18872
+ }
18873
+ } finally {
18874
+ if (platformRequest === request) {
18875
+ platformRequest = void 0;
18876
+ request?.[Symbol.dispose]();
18877
+ }
18878
+ }
18879
+ };
18880
+ const changed = (state) => {
18881
+ if (!active) return;
18882
+ stopWatch?.();
18883
+ stopWatch = void 0;
18884
+ retire();
18885
+ upstream?.[Symbol.dispose]();
18886
+ upstream = void 0;
18887
+ if (state.status !== "ready") {
18888
+ listener(state);
18889
+ return;
18890
+ }
18891
+ upstream = state.manager.dup();
18892
+ listener({ status: "connecting" });
18893
+ const signals = connectionSignals(hostId2);
18894
+ if (!signals) {
18895
+ void publish();
18896
+ return;
18897
+ }
18898
+ previousState = void 0;
18899
+ previousRevision = void 0;
18900
+ stopWatch = components.scope.watch(({ get }) => {
18901
+ const connection = get(signals.state$), revision = get(signals.revision$);
18902
+ if (connection === previousState && revision === previousRevision) return;
18903
+ previousState = connection;
18904
+ previousRevision = revision;
18905
+ retire();
18906
+ listener({ status: connection === "connected" ? "connecting" : "disconnected" });
18907
+ if (connection === "connected") void publish();
18908
+ });
18909
+ };
18910
+ const original = source.subscribe(hostId2, changed);
18911
+ const result = original.then((lease) => {
18912
+ if (!active) lease[Symbol.dispose]();
18913
+ return {
18914
+ onRpcBroken: (listener2) => lease.onRpcBroken(listener2),
18915
+ [Symbol.dispose]() {
18916
+ cleanup();
18917
+ lease[Symbol.dispose]();
18918
+ }
18919
+ };
18920
+ });
18921
+ Object.assign(result, {
18922
+ onRpcBroken: (listener2) => original.onRpcBroken(listener2),
18923
+ [Symbol.dispose]() {
18924
+ cleanup();
18925
+ original[Symbol.dispose]();
18926
+ }
18927
+ });
18928
+ return result;
18929
+ },
18930
+ [Symbol.dispose]() {
18931
+ if (--refs !== 0) return;
18932
+ for (const cleanup of [...subscriptions]) cleanup();
18933
+ source[Symbol.dispose]();
18934
+ }
18935
+ };
18936
+ return { service, route: (hostId2) => routes.get(hostId2) };
18937
+ }
18938
+
18939
+ // packages/desktop-control/src/renderer-native-rpc-interactions.ts
18940
+ function retainNativeRpcInteractions(upstream, manager, hostId2) {
18941
+ let disposed = false;
18942
+ const retained = /* @__PURE__ */ new Set();
18943
+ const requests = /* @__PURE__ */ new Map();
18944
+ const reads = /* @__PURE__ */ new Map();
18945
+ const record3 = (value) => value !== null && typeof value === "object";
18946
+ const read = (threadId) => {
18947
+ const existing = reads.get(threadId);
18948
+ if (existing) {
18949
+ existing.dirty = true;
18950
+ return existing.promise;
18951
+ }
18952
+ const entry = { promise: Promise.resolve(), dirty: false };
18953
+ reads.set(threadId, entry);
18954
+ entry.promise = Promise.resolve().then(async () => {
18955
+ do {
18956
+ if (disposed) break;
18957
+ entry.dirty = false;
18958
+ const pending = upstream.getConversation(threadId);
18959
+ retained.add(pending);
18960
+ try {
18961
+ const conversation = await pending;
18962
+ if (disposed || entry.dirty || !record3(conversation) || !Array.isArray(conversation.requests))
18963
+ continue;
18964
+ const previous = requests.get(threadId) ?? /* @__PURE__ */ new Set();
18965
+ const next = /* @__PURE__ */ new Set();
18966
+ for (const request of conversation.requests) {
18967
+ if (!record3(request) || typeof request.method !== "string" || !record3(request.params) || (request.params.threadId ?? request.params.conversationId) !== threadId || typeof request.id !== "string" && typeof request.id !== "number")
18968
+ continue;
18969
+ next.add(request.id);
18970
+ if (!previous.has(request.id)) manager.onRequest(request);
18971
+ }
18972
+ if (next.size) requests.set(threadId, next);
18973
+ else requests.delete(threadId);
18974
+ } finally {
18975
+ if (retained.delete(pending)) pending[Symbol.dispose]();
18976
+ }
18977
+ } while (!disposed && entry.dirty);
18978
+ }).finally(() => {
18979
+ reads.delete(threadId);
18980
+ });
18981
+ return entry.promise;
18982
+ };
18983
+ const event = (value) => {
18984
+ if (disposed || !record3(value) || typeof value.conversationId !== "string") return;
18985
+ void read(value.conversationId).catch(() => void 0);
18986
+ };
18987
+ const subscribe = (input) => {
18988
+ const pending = upstream.subscribe(input);
18989
+ retained.add(pending);
18990
+ return Promise.resolve(pending).then((lease) => {
18991
+ if (disposed) lease[Symbol.dispose]();
18992
+ else retained.add(lease);
18993
+ });
18994
+ };
18995
+ const subscriptions = [
18996
+ "approval-request",
18997
+ "user-input-request",
18998
+ "mcp-elicitation-request",
18999
+ "approval-resolved"
19000
+ ].map((name) => subscribe({ type: "event", key: { hostId: hostId2 }, event: name, listener: event }));
19001
+ subscriptions.push(
19002
+ subscribe({
19003
+ type: "notification",
19004
+ key: { hostId: hostId2 },
19005
+ methods: ["serverRequest/resolved"],
19006
+ listener(value) {
19007
+ if (record3(value) && record3(value.params) && typeof value.params.threadId === "string")
19008
+ event({ conversationId: value.params.threadId });
19009
+ }
19010
+ })
19011
+ );
19012
+ const ready = Promise.all(subscriptions).then(async () => {
19013
+ if (disposed) return;
19014
+ const pending = upstream.getWorkInProgress();
19015
+ retained.add(pending);
19016
+ try {
19017
+ const work = await pending;
19018
+ if (disposed) return;
19019
+ if (!Array.isArray(work)) throw new Error("Native RPC interaction snapshot is unavailable");
19020
+ const threadIds = new Set(
19021
+ work.flatMap(
19022
+ (item) => record3(item) && typeof item.conversationId === "string" ? [item.conversationId] : []
19023
+ )
19024
+ );
19025
+ await Promise.all([...threadIds].map(read));
19026
+ } finally {
19027
+ if (retained.delete(pending)) pending[Symbol.dispose]();
19028
+ }
19029
+ });
19030
+ return {
19031
+ ready,
19032
+ dispose() {
19033
+ if (disposed) return;
19034
+ disposed = true;
19035
+ for (const lease of retained) lease[Symbol.dispose]();
19036
+ retained.clear();
19037
+ requests.clear();
19038
+ }
19039
+ };
19040
+ }
19041
+
19042
+ // packages/desktop-control/src/renderer-native-rpc-install.ts
19043
+ async function installNativeRpcRemoteControlDirect(renderer) {
19044
+ let attempt;
19045
+ const probeId = crypto.randomUUID();
19046
+ try {
19047
+ attempt = await renderer.evaluate(`(() => {
19048
+ if (window.__codexhostNativeRpcRemoteControlV1) return null;
19049
+ const routing = window.__codexhostHostRoutingV1;
19050
+ const owner = routing?.forHost('local')?.manager;
19051
+ if (owner?.kind !== 'main-process-rpc') return null;
19052
+ const catalog = window.__codexhostLoadedModulesV1;
19053
+ if (!catalog?.complete) return null;
19054
+ const key = JSON.stringify([catalog.owner, catalog.urls.filter(url => /renderer-app-server-managers|app-shared/.test(url)).sort()]);
19055
+ const previous = window.__codexhostNativeRpcDiscoveryV1;
19056
+ const sameOwner = previous?.key === key && previous.owner === owner;
19057
+ if (sameOwner && (previous.state !== 'unavailable' || previous.attempts >= 3 || Date.now() < previous.nextRetryAt)) return null;
19058
+ const token = ${JSON.stringify(probeId)};
19059
+ window.__codexhostNativeRpcDiscoveryV1 = {
19060
+ key, owner, token, state: 'discovering', attempts: sameOwner ? previous.attempts + 1 : 1,
19061
+ };
19062
+ return token;
19063
+ })()`);
19064
+ } catch {
19065
+ return false;
19066
+ }
19067
+ if (attempt === null) return false;
19068
+ let installed = false;
19069
+ try {
19070
+ installed = await withNativeRpcComponents(renderer, async (objectId) => {
19071
+ const result = await renderer.command("Runtime.callFunctionOn", {
19072
+ objectId,
19073
+ functionDeclaration: `function() {
19074
+ if (this.document !== document) return false;
19075
+ const retainRendererHostResponses = ${retainRendererHostResponses.toString()};
19076
+ const isolateRendererPrewarmConsumption = ${isolateRendererPrewarmConsumption.toString()};
19077
+ return (${installNativeRpcRemoteControl.toString()})(this, window, {
19078
+ createPolicy: ${createDraftPrewarmPolicyBridge.toString()},
19079
+ createManager: ${createNativeRemoteManager.toString()},
19080
+ createChannel: ${createNativeRpcChannel.toString()},
19081
+ createService: ${createNativeRpcService.toString()},
19082
+ retainInteractions: ${retainNativeRpcInteractions.toString()},
19083
+ });
19084
+ }`,
19085
+ returnByValue: true
19086
+ });
19087
+ return !result.exceptionDetails && result.result?.value === true;
19088
+ });
19089
+ return installed;
19090
+ } catch {
19091
+ return false;
19092
+ } finally {
19093
+ await renderer.evaluate(
19094
+ `(() => {
19095
+ const status = window.__codexhostNativeRpcDiscoveryV1;
19096
+ if (status?.token === ${JSON.stringify(attempt)}) {
19097
+ status.state = ${JSON.stringify(installed ? "ready" : "unavailable")};
19098
+ status.nextRetryAt = Date.now() + 5000 * 2 ** (status.attempts - 1);
19099
+ }
19100
+ })()`
19101
+ ).catch(() => void 0);
19102
+ }
19103
+ }
19104
+
19105
+ // packages/desktop-control/src/renderer-rpc-steering.ts
19106
+ var RETRY_BASE_MS = 5e3;
19107
+ var RETRY_MAX_MS = 3e5;
19108
+ var retries = /* @__PURE__ */ new WeakMap();
19109
+ async function installRendererRpcSteeringDirect(client, now = Date.now) {
19110
+ try {
19111
+ const needed = await client.evaluate(`(() => {
19112
+ const steering = window.__codexhostRpcSteeringV1;
19113
+ if (steering && steering.controller.forHost === steering.forHost) return false;
19114
+ steering?.release();
19115
+ const routing=window.__codexhostHostRoutingV1;
19116
+ return ['local', ...(routing?.knownHostIds?.() ?? [])].some(id => routing?.forHost(id)?.manager.kind === 'main-process-rpc');
19117
+ })()`);
19118
+ if (!needed) return false;
19119
+ const retry = retries.get(client);
19120
+ if (retry && now() < retry.nextAt) return false;
19121
+ try {
19122
+ await discoverAndInstall(client);
19123
+ retries.delete(client);
19124
+ return true;
19125
+ } catch (error51) {
19126
+ const attempts = (retry?.attempts ?? 0) + 1;
19127
+ const delay = Math.min(RETRY_BASE_MS * 2 ** (attempts - 1), RETRY_MAX_MS);
19128
+ retries.set(client, { attempts, nextAt: now() + delay });
19129
+ console.error(
19130
+ `codexhost native steering discovery failed (attempt ${attempts}):`,
19131
+ error51 instanceof Error ? error51.message : String(error51)
19132
+ );
19133
+ return false;
19134
+ }
19135
+ } catch {
19136
+ return false;
19137
+ }
19138
+ }
19139
+ async function discoverAndInstall(client) {
19140
+ const group = `codexhost-rpc-steering-${crypto.randomUUID()}`;
19141
+ const command = (method, params) => client.command(method, params);
19142
+ const properties = (objectId) => command("Runtime.getProperties", { objectId, ownProperties: true });
19143
+ const call = (objectId, functionDeclaration, args = []) => command("Runtime.callFunctionOn", {
19144
+ objectId,
19145
+ functionDeclaration,
19146
+ arguments: args,
19147
+ objectGroup: group,
19148
+ returnByValue: true
19149
+ });
19150
+ try {
19151
+ const proto = await command("Runtime.evaluate", {
19152
+ expression: "Object.getPrototypeOf(async function(){})",
19153
+ objectGroup: group
19154
+ });
19155
+ if (!proto.result.objectId) throw new Error("Native RPC steering discovery is unavailable");
19156
+ const objects = await command("Runtime.queryObjects", {
19157
+ prototypeObjectId: proto.result.objectId,
19158
+ objectGroup: group
19159
+ });
19160
+ if (!objects.objects.objectId) throw new Error("Native RPC steering discovery is unavailable");
19161
+ const filtered = await command("Runtime.callFunctionOn", {
19162
+ objectId: objects.objects.objectId,
19163
+ functionDeclaration: 'function(){return this.filter(fn=>fn.name==="collectAppStateSnapshot"&&String(fn).includes("collectSnapshot")).slice(0,9)}',
19164
+ objectGroup: group
19165
+ });
19166
+ if (!filtered.result.objectId) throw new Error("Native RPC Controller is unavailable");
19167
+ const snapshots = (await properties(filtered.result.objectId)).result.flatMap(
19168
+ (entry) => entry.value?.type === "function" && entry.value.objectId ? [entry.value.objectId] : []
19169
+ );
19170
+ if (snapshots.length > 8) throw new Error("Native RPC Controller is ambiguous");
19171
+ const controllers = [];
19172
+ for (const snapshot of snapshots) {
19173
+ const scopes = (await properties(snapshot)).internalProperties?.find(
19174
+ (entry) => entry.name === "[[Scopes]]"
19175
+ )?.value?.objectId;
19176
+ if (!scopes) continue;
19177
+ for (const scope of (await properties(scopes)).result) {
19178
+ if (!scope.value?.objectId || !scope.value.description?.startsWith("Closure")) continue;
19179
+ const bindings = (await properties(scope.value.objectId)).result;
19180
+ const owners = [];
19181
+ let rootScope;
19182
+ for (const binding of bindings) {
19183
+ if (binding.value?.type !== "object" || !binding.value.objectId) continue;
19184
+ const id = binding.value.objectId;
19185
+ const result2 = await call(
19186
+ id,
19187
+ `function(){return (${nativeRpcObjectShape.toString()})(this)}`
19188
+ );
19189
+ const shape = result2.result.value;
19190
+ if (shape?.scope) rootScope = id;
19191
+ if (shape?.controller && (await call(id, "function(fn){return this.collectAppStateSnapshot===fn}", [
19192
+ { objectId: snapshot }
19193
+ ])).result.value === true)
19194
+ owners.push(id);
19195
+ }
19196
+ if (owners.length !== 1 || !rootScope) continue;
19197
+ const root = await call(
19198
+ rootScope,
19199
+ `function(){let node=this.node;const seen=new Set();while(node?.parent&&!seen.has(node.parent)&&seen.size<100){seen.add(node);node=node.parent}return (${findRendererAppScopeStore.toString()})(document)===node}`
19200
+ );
19201
+ if (root.result.value === true) controllers.push(owners[0]);
19202
+ }
19203
+ }
19204
+ if (controllers.length !== 1) throw new Error("Native RPC Controller is missing or ambiguous");
19205
+ const result = await call(
19206
+ controllers[0],
19207
+ "function(){return window.__codexhostInstallRpcSteeringV1?.(this) === true}"
19208
+ );
19209
+ if (result.exceptionDetails || result.result.value !== true)
19210
+ throw new Error("Native RPC steering installation failed");
19211
+ } finally {
19212
+ await client.command("Runtime.releaseObjectGroup", { objectGroup: group }).catch(() => void 0);
19213
+ }
19214
+ }
19215
+
17552
19216
  // packages/desktop-control/src/renderer-cdp-control-session.ts
17553
19217
  function isRecord2(value) {
17554
19218
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -17682,6 +19346,7 @@ async function waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs
17682
19346
  if (value !== null) return validateBindingStatus(value, enabledAgents);
17683
19347
  } catch (error51) {
17684
19348
  lastError = error51;
19349
+ if (error51 instanceof CdpConnectionClosedError) throw error51;
17685
19350
  if (error51 instanceof RendererAdapterReadinessError && error51.state !== "installing") {
17686
19351
  throw error51;
17687
19352
  }
@@ -17693,21 +19358,23 @@ async function waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs
17693
19358
  }
17694
19359
  async function installTarget(target, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations) {
17695
19360
  const renderer = await operations.connect(target.webSocketDebuggerUrl);
19361
+ let disposeModules;
17696
19362
  try {
17697
- await renderer.command("Runtime.enable");
19363
+ disposeModules = await installRendererLoadedModules(renderer);
17698
19364
  await renderer.command("Page.enable");
17699
19365
  await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource });
17700
19366
  await evaluateSource(renderer, rendererSource);
17701
19367
  const draftPrewarmPolicy = await operations.installDraftPrewarmPolicy(renderer);
17702
19368
  const binding = await waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs);
17703
- return { renderer, snapshot: { target, draftPrewarmPolicy, binding } };
19369
+ return { renderer, snapshot: { target, draftPrewarmPolicy, binding }, disposeModules };
17704
19370
  } catch (error51) {
19371
+ disposeModules?.();
17705
19372
  renderer.close();
17706
19373
  throw error51;
17707
19374
  }
17708
19375
  }
17709
19376
  var InstalledRendererCdpControlSession = class {
17710
- constructor(renderer, rendererCdpEndpoint2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot) {
19377
+ constructor(renderer, rendererCdpEndpoint2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot, disposeModules) {
17711
19378
  this.renderer = renderer;
17712
19379
  this.rendererCdpEndpoint = rendererCdpEndpoint2;
17713
19380
  this.rendererSource = rendererSource;
@@ -17716,6 +19383,7 @@ var InstalledRendererCdpControlSession = class {
17716
19383
  this.pollIntervalMs = pollIntervalMs;
17717
19384
  this.operations = operations;
17718
19385
  this.currentSnapshot = currentSnapshot;
19386
+ this.disposeModules = disposeModules;
17719
19387
  }
17720
19388
  renderer;
17721
19389
  rendererCdpEndpoint;
@@ -17725,6 +19393,7 @@ var InstalledRendererCdpControlSession = class {
17725
19393
  pollIntervalMs;
17726
19394
  operations;
17727
19395
  currentSnapshot;
19396
+ disposeModules;
17728
19397
  #closed = false;
17729
19398
  get snapshot() {
17730
19399
  return this.currentSnapshot;
@@ -17747,8 +19416,10 @@ var InstalledRendererCdpControlSession = class {
17747
19416
  this.pollIntervalMs,
17748
19417
  this.operations
17749
19418
  );
19419
+ this.disposeModules();
17750
19420
  this.renderer.close();
17751
19421
  this.renderer = replacement.renderer;
19422
+ this.disposeModules = replacement.disposeModules;
17752
19423
  this.currentSnapshot = replacement.snapshot;
17753
19424
  return this.currentSnapshot;
17754
19425
  }
@@ -17773,8 +19444,10 @@ var InstalledRendererCdpControlSession = class {
17773
19444
  this.pollIntervalMs,
17774
19445
  this.operations
17775
19446
  );
19447
+ this.disposeModules();
17776
19448
  this.renderer.close();
17777
19449
  this.renderer = replacement.renderer;
19450
+ this.disposeModules = replacement.disposeModules;
17778
19451
  this.currentSnapshot = replacement.snapshot;
17779
19452
  return this.currentSnapshot;
17780
19453
  }
@@ -17791,13 +19464,19 @@ var InstalledRendererCdpControlSession = class {
17791
19464
  close() {
17792
19465
  if (this.#closed) return;
17793
19466
  this.#closed = true;
19467
+ this.disposeModules();
17794
19468
  this.renderer.close();
17795
19469
  }
17796
19470
  };
17797
19471
  var defaultOperations = {
17798
19472
  listTargets: (endpoint, signal) => listCdpTargets(endpoint, fetch, signal),
17799
19473
  connect: (webSocketDebuggerUrl) => CdpClient.connect(webSocketDebuggerUrl),
17800
- installDraftPrewarmPolicy: installRendererDraftPrewarmPolicyDirect
19474
+ async installDraftPrewarmPolicy(renderer) {
19475
+ const status = await installRendererDraftPrewarmPolicyDirect(renderer);
19476
+ await installNativeRpcRemoteControlDirect(renderer);
19477
+ await installRendererRpcSteeringDirect(renderer);
19478
+ return status;
19479
+ }
17801
19480
  };
17802
19481
  async function createRendererCdpControlSession(options) {
17803
19482
  const enabledAgents = options.enabledAgents;
@@ -17828,7 +19507,8 @@ async function createRendererCdpControlSession(options) {
17828
19507
  timeoutMs,
17829
19508
  pollIntervalMs,
17830
19509
  operations,
17831
- installed.snapshot
19510
+ installed.snapshot,
19511
+ installed.disposeModules
17832
19512
  );
17833
19513
  }
17834
19514
  function installRendererCdpControlSession(options) {
@@ -17944,6 +19624,7 @@ function parseDesktopControllerArguments(arguments_) {
17944
19624
  function isTransientRendererInstallError(error51) {
17945
19625
  let current = error51;
17946
19626
  for (let depth = 0; depth < 4; depth += 1) {
19627
+ if (current instanceof CdpConnectionClosedError) return true;
17947
19628
  const message = current instanceof Error ? current.message : String(current);
17948
19629
  if (message.includes("Execution context was destroyed") || message.includes("Promise was collected")) {
17949
19630
  return true;