@codexhost/cli-win32-arm64 0.15.0 → 0.16.1

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.
@@ -14952,6 +14952,8 @@ var usageStatisticsTotalsSchema = external_exports.strictObject({
14952
14952
  cachedInputTokens: count,
14953
14953
  cacheWriteInputTokens: count,
14954
14954
  cacheKnownInputTokens: count,
14955
+ cacheHitCachedInputTokens: count,
14956
+ cacheHitInputTokens: count,
14955
14957
  outputTokens: count,
14956
14958
  reasoningOutputTokens: count,
14957
14959
  /** USD at the public price, summed over the priced requests only. */
@@ -15838,7 +15840,10 @@ var harnessPluginRouteSchema = external_exports.object({
15838
15840
  harnessId: harnessPluginIdSchema,
15839
15841
  model: harnessModelRefSchema.optional(),
15840
15842
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
15841
- permissionModeId: harnessPermissionModeIdSchema.optional()
15843
+ permissionModeId: harnessPermissionModeIdSchema.optional(),
15844
+ /** A draft prewarm create: stays unsubmitted until the user's first Turn.
15845
+ * Desktop forwards only the Model of a main-process prewarm to thread/start. */
15846
+ prewarm: external_exports.literal(true).optional()
15842
15847
  }).strict();
15843
15848
 
15844
15849
  // packages/shared-contracts/dist/harness-launch-settings.js
@@ -16702,8 +16707,99 @@ function retainRendererHostResponses(client, hostId2, target) {
16702
16707
  };
16703
16708
  }
16704
16709
 
16710
+ // packages/desktop-control/src/renderer-prewarm-consumption.ts
16711
+ function isolateRendererPrewarmConsumption(manager, discardExternal) {
16712
+ const record3 = (value) => value !== null && typeof value === "object";
16713
+ if (!record3(manager) || !record3(manager.threadCreation)) return null;
16714
+ const creation = manager.threadCreation;
16715
+ const originalStart = manager.startConversation;
16716
+ const original = creation.createConversation;
16717
+ const params = creation.params;
16718
+ if (typeof originalStart !== "function" || typeof original !== "function" || !record3(params))
16719
+ return null;
16720
+ const prototype = Object.getPrototypeOf(creation);
16721
+ if (!record3(prototype) || typeof prototype.constructor !== "function") return null;
16722
+ if (Object.keys(creation).some((key) => key !== "params" && typeof creation[key] !== "function") || /#[A-Za-z_$]/u.test(Function.prototype.toString.call(prototype.constructor)))
16723
+ return null;
16724
+ const pool = params.prewarmedThreadManager;
16725
+ if (!record3(pool) || typeof pool.hasPrewarmedThread !== "function" || typeof pool.consumePrewarmedThread !== "function" || typeof pool.deletePrewarmedThread !== "function")
16726
+ return null;
16727
+ const consume = pool.consumePrewarmedThread;
16728
+ const hasPrewarm = pool.hasPrewarmedThread;
16729
+ const draftModels = /* @__PURE__ */ new Map();
16730
+ const draftIdentity = /* @__PURE__ */ Symbol("codexhost draft creation");
16731
+ const external = (model2) => typeof model2 === "string" && model2.startsWith("codexhost/");
16732
+ const routedStart = function(input, options, ...args) {
16733
+ const draftId = record3(options) ? options.clientThreadId : null;
16734
+ const mode = record3(input) && record3(input.collaborationMode) ? input.collaborationMode : null;
16735
+ const origin = mode ? Reflect.get(mode, draftIdentity) : void 0;
16736
+ if (mode && record3(mode.settings) && external(mode.settings.model))
16737
+ return originalStart.call(this, input, options, ...args);
16738
+ const model2 = (typeof draftId === "string" ? draftModels.get(draftId) : void 0) ?? (typeof origin === "string" ? draftModels.get(origin) : void 0);
16739
+ if (!model2) return originalStart.call(this, input, options, ...args);
16740
+ if (!record3(input) || !record3(input.collaborationMode) || !record3(input.collaborationMode.settings))
16741
+ throw new Error("External draft creation is missing its native Model settings");
16742
+ const routed = {
16743
+ ...input,
16744
+ collaborationMode: {
16745
+ ...input.collaborationMode,
16746
+ settings: { ...input.collaborationMode.settings, model: model2 }
16747
+ }
16748
+ };
16749
+ return originalStart.call(this, routed, options, ...args);
16750
+ };
16751
+ const wrapped = function(input, ...args) {
16752
+ const mode = record3(input) && record3(input.collaborationMode) ? input.collaborationMode : null;
16753
+ const expected = mode && record3(mode.settings) ? mode.settings.model : null;
16754
+ const scopedPool = Object.create(pool);
16755
+ scopedPool.hasPrewarmedThread = (...parameters) => hasPrewarm.apply(pool, parameters);
16756
+ scopedPool.consumePrewarmedThread = async (...consumeArgs) => {
16757
+ const warmed = await consume.apply(pool, consumeArgs);
16758
+ if (!record3(warmed) || !record3(warmed.response)) return warmed;
16759
+ const response = warmed.response;
16760
+ if (!external(expected) && !external(response.model)) return warmed;
16761
+ if (external(expected) && expected === response.model) return warmed;
16762
+ if (record3(response.thread) && typeof response.thread.id === "string") {
16763
+ const threadId = response.thread.id;
16764
+ if (external(response.model)) discardExternal(threadId);
16765
+ else
16766
+ void Promise.resolve().then(() => pool.deletePrewarmedThread(threadId)).catch(() => void 0);
16767
+ }
16768
+ return null;
16769
+ };
16770
+ const invocation = Object.create(creation);
16771
+ invocation.params = { ...params, prewarmedThreadManager: scopedPool };
16772
+ return original.call(invocation, input, ...args);
16773
+ };
16774
+ creation.createConversation = wrapped;
16775
+ manager.startConversation = routedStart;
16776
+ return {
16777
+ selectDraft(draftId, model2, creationModes = []) {
16778
+ if (draftId === void 0) {
16779
+ if (model2 === null) draftModels.clear();
16780
+ } else if (model2 === null) draftModels.delete(draftId);
16781
+ else {
16782
+ if (!draftId.startsWith("client-new-thread:") || !external(model2))
16783
+ throw new Error("External draft route is missing its client Thread identity");
16784
+ draftModels.set(draftId, model2);
16785
+ for (const mode of creationModes)
16786
+ Object.defineProperty(mode, draftIdentity, {
16787
+ configurable: true,
16788
+ enumerable: true,
16789
+ value: draftId
16790
+ });
16791
+ }
16792
+ },
16793
+ dispose() {
16794
+ draftModels.clear();
16795
+ if (manager.startConversation === routedStart) manager.startConversation = originalStart;
16796
+ if (creation.createConversation === wrapped) creation.createConversation = original;
16797
+ }
16798
+ };
16799
+ }
16800
+
16705
16801
  // packages/desktop-control/src/renderer-draft-prewarm-runtime.ts
16706
- function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewarmedThreadManager, isCurrentManager, retainResponses = retainRendererHostResponses) {
16802
+ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewarmedThreadManager, isCurrentManager, retainResponses = retainRendererHostResponses, isolateConsumption = isolateRendererPrewarmConsumption) {
16707
16803
  let disposed = false;
16708
16804
  const originalSend = bridge.sendRequest;
16709
16805
  const originalPrewarm = bridge.prewarmThreadStart;
@@ -17084,26 +17180,16 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17084
17180
  if (threadId && knownOfficialThreadIds.has(threadId)) return false;
17085
17181
  return selectedModel !== null && (method.startsWith("thread/") || method.startsWith("turn/") || method.startsWith("review/"));
17086
17182
  };
17087
- const routeThreadStart = (parameters) => {
17088
- if (!isRecord3(parameters) || parameters.ephemeral === true) {
17089
- return parameters;
17090
- }
17091
- return {
17092
- ...parameters,
17093
- ...selectedModel === null ? {} : { model: selectedModel }
17094
- };
17095
- };
17096
17183
  const routedSend = (method, parameters, options) => {
17097
17184
  if (method === "turn/start" || method === "thread/resume" || method === "codexhost/thread/command/execute") {
17098
17185
  const threadId = threadIdFromParameters(parameters);
17099
17186
  if (threadId) externalPrewarms.delete(threadId);
17100
17187
  }
17101
- const routedParameters = method === "thread/start" ? routeThreadStart(parameters) : parameters;
17102
17188
  const sendBridged = () => initializeBridge().then(
17103
- () => enqueueBridgeRequest(method, routedParameters, options)
17189
+ () => enqueueBridgeRequest(method, parameters, options)
17104
17190
  );
17105
- const sendDirect = () => options === void 0 ? originalSend.call(bridge, method, routedParameters) : originalSend.call(bridge, method, routedParameters, options);
17106
- const unresolvedThreadId = shouldResolveThreadOwnership(method, routedParameters);
17191
+ const sendDirect = () => options === void 0 ? originalSend.call(bridge, method, parameters) : originalSend.call(bridge, method, parameters, options);
17192
+ const unresolvedThreadId = shouldResolveThreadOwnership(method, parameters);
17107
17193
  if (unresolvedThreadId) {
17108
17194
  return resolveThreadOwnership(unresolvedThreadId).then(
17109
17195
  (owner) => owner === "external" ? sendBridged() : sendDirect(),
@@ -17119,7 +17205,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17119
17205
  }
17120
17206
  );
17121
17207
  }
17122
- return shouldUseBridge(method, routedParameters) ? sendBridged() : sendDirect();
17208
+ return shouldUseBridge(method, parameters) ? sendBridged() : sendDirect();
17123
17209
  };
17124
17210
  const publishDraftWorkspace = (parameters) => {
17125
17211
  if (!isRecord3(parameters) || parameters.ephemeral === true) return;
@@ -17149,10 +17235,10 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17149
17235
  const discardExternalPrewarms = () => {
17150
17236
  for (const threadId of externalPrewarms) discardExternalPrewarm(threadId);
17151
17237
  };
17238
+ const restoreConsumption = isolateConsumption(manager, discardExternalPrewarm);
17152
17239
  const routedPrewarm = (parameters, options) => {
17153
- const routed = routeThreadStart(parameters);
17154
- const external = isRecord3(routed) && routed.ephemeral !== true && typeof routed.model === "string" && routed.model.startsWith("codexhost/");
17155
- const routedParameters = external ? { ...routed, codexhostPrewarm: true } : routed;
17240
+ const external = isRecord3(parameters) && parameters.ephemeral !== true && typeof parameters.model === "string" && parameters.model.startsWith("codexhost/");
17241
+ const routedParameters = external ? { ...parameters, codexhostPrewarm: true } : parameters;
17156
17242
  const generation = prewarmGeneration;
17157
17243
  publishDraftWorkspace(routedParameters);
17158
17244
  const pending = shouldUseBridge("thread/start", routedParameters) ? routedSend("thread/start", routedParameters, options) : options === void 0 ? originalPrewarm.call(bridge, routedParameters) : originalPrewarm.call(bridge, routedParameters, options);
@@ -17205,6 +17291,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17205
17291
  const policy = Object.freeze({
17206
17292
  state: "ready",
17207
17293
  hostId: hostId2,
17294
+ scopedCreation: restoreConsumption !== null,
17208
17295
  owns(candidateManager, candidate, candidateHostId, candidatePrewarmedThreadManager, requiresCurrentManager) {
17209
17296
  return !disposed && candidateManager === manager && candidate === bridge && candidateHostId === hostId2 && candidatePrewarmedThreadManager === prewarmedThreadManager && requiresCurrentManager === !!isCurrentManager;
17210
17297
  },
@@ -17213,12 +17300,13 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17213
17300
  throw new Error("Renderer request manager is retired");
17214
17301
  return manager;
17215
17302
  },
17216
- select(model2) {
17303
+ select(model2, draftId, creationModes) {
17217
17304
  if (disposed || isCurrentManager && !isCurrentManager())
17218
17305
  throw new Error("Renderer request manager is retired");
17219
17306
  if (model2 !== null && (typeof model2 !== "string" || !model2.startsWith("codexhost/"))) {
17220
17307
  throw new Error("Draft route Model must be a codexhost transport carrier");
17221
17308
  }
17309
+ restoreConsumption?.selectDraft(draftId, model2, creationModes);
17222
17310
  if (selectedModel === model2) return false;
17223
17311
  selectedModel = model2;
17224
17312
  prewarmGeneration += 1;
@@ -17239,6 +17327,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17239
17327
  disposed = true;
17240
17328
  prewarmGeneration += 1;
17241
17329
  retireResponses();
17330
+ restoreConsumption?.dispose();
17242
17331
  if (bridge.sendRequest === routedSend) bridge.sendRequest = originalSend;
17243
17332
  if (bridge.prewarmThreadStart === routedPrewarm) {
17244
17333
  bridge.prewarmThreadStart = originalPrewarm;
@@ -17275,14 +17364,14 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target, prewar
17275
17364
 
17276
17365
  // packages/desktop-control/src/renderer-host-discovery.ts
17277
17366
  function requestManagerFromHookState(value, hostId2) {
17278
- const record2 = (candidate) => typeof candidate === "object" && candidate !== null;
17367
+ const record3 = (candidate) => typeof candidate === "object" && candidate !== null;
17279
17368
  const manager = (candidate) => {
17280
- if (!record2(candidate) || !record2(candidate.requestClient) || !record2(candidate.prewarmedThreadManager))
17369
+ if (!record3(candidate) || !record3(candidate.requestClient) || !record3(candidate.prewarmedThreadManager))
17281
17370
  return null;
17282
17371
  const bridge = candidate.requestClient;
17283
17372
  return typeof candidate.sendRequest === "function" && typeof bridge.sendRequest === "function" && typeof bridge.prewarmThreadStart === "function" && typeof bridge.enqueueRequest === "function" && typeof candidate.prewarmedThreadManager.discardAllPrewarmedThreads === "function" ? candidate : null;
17284
17373
  };
17285
- if (!record2(value)) return null;
17374
+ if (!record3(value)) return null;
17286
17375
  const direct = manager(value) ?? manager(value.manager);
17287
17376
  if (direct) return direct;
17288
17377
  if (!hostId2 || typeof value.addManager !== "function" || typeof value.getForHostId !== "function")
@@ -17492,6 +17581,335 @@ function installRendererHostRouting(root, target, discover, resolve, createPolic
17492
17581
  return routing;
17493
17582
  }
17494
17583
 
17584
+ // packages/desktop-control/src/renderer-host-rpc-discovery.ts
17585
+ function findRendererAppScopeStore(root) {
17586
+ const MAX_VISITED_FIBERS = 5e4;
17587
+ const record3 = (value) => typeof value === "object" && value !== null;
17588
+ const container = root.getElementById?.("root");
17589
+ if (!record3(container)) return null;
17590
+ const key = Object.getOwnPropertyNames(container).find(
17591
+ (name) => name.startsWith("__reactContainer$")
17592
+ );
17593
+ const first = key ? container[key] : null;
17594
+ if (!record3(first)) return null;
17595
+ 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";
17596
+ const stack = [first];
17597
+ const seen = /* @__PURE__ */ new Set();
17598
+ while (stack.length && seen.size < MAX_VISITED_FIBERS) {
17599
+ const fiber = stack.pop();
17600
+ if (seen.has(fiber)) continue;
17601
+ seen.add(fiber);
17602
+ let hook = fiber.memoizedState;
17603
+ for (let index = 0; record3(hook) && "next" in hook && index < 150; index += 1) {
17604
+ const state = hook.memoizedState;
17605
+ const handle = record3(state) ? state.current : null;
17606
+ if (isScopeHandle(handle)) {
17607
+ let node = handle.node;
17608
+ const nodes = /* @__PURE__ */ new Set();
17609
+ while (record3(node.parent) && !nodes.has(node.parent)) {
17610
+ nodes.add(node);
17611
+ node = node.parent;
17612
+ }
17613
+ const bindings = node.familyBindings;
17614
+ return record3(bindings) && typeof bindings.get === "function" && typeof bindings.entries === "function" ? node : null;
17615
+ }
17616
+ hook = hook.next;
17617
+ }
17618
+ if (record3(fiber.sibling)) stack.push(fiber.sibling);
17619
+ if (record3(fiber.child)) stack.push(fiber.child);
17620
+ }
17621
+ return null;
17622
+ }
17623
+ function findRendererHostRpcFamily(store) {
17624
+ const record3 = (value) => typeof value === "object" && value !== null;
17625
+ const families = /* @__PURE__ */ new Set();
17626
+ for (const [definition, members] of store.familyBindings) {
17627
+ if (!record3(definition) || definition.kind !== "signal-family") continue;
17628
+ if (!record3(members) || typeof members.get !== "function") continue;
17629
+ for (const [hostId2, member] of members) {
17630
+ if (typeof hostId2 !== "string" || !record3(member)) continue;
17631
+ const signal = member.value;
17632
+ if (!record3(signal) || typeof signal.get !== "function") continue;
17633
+ let value;
17634
+ try {
17635
+ value = signal.get();
17636
+ } catch {
17637
+ continue;
17638
+ }
17639
+ if (record3(value) && Object.keys(value).length === 2 && typeof value.status === "string" && record3(value.client) && value.client.hostId === hostId2 && "rpc" in value.client) {
17640
+ families.add(members);
17641
+ break;
17642
+ }
17643
+ }
17644
+ }
17645
+ if (families.size !== 1) return null;
17646
+ return { store, family: families.values().next().value };
17647
+ }
17648
+ function resolveRendererHostRpc(discovery, hostId2) {
17649
+ const record3 = (value2) => typeof value2 === "object" && value2 !== null;
17650
+ const signal = discovery.family.get(hostId2)?.value;
17651
+ if (!record3(signal) || typeof signal.get !== "function") return null;
17652
+ let value;
17653
+ try {
17654
+ value = signal.get();
17655
+ } catch {
17656
+ return null;
17657
+ }
17658
+ if (!record3(value) || value.status !== "ready" || !record3(value.client) || value.client.hostId !== hostId2)
17659
+ return null;
17660
+ const rpc = value.client.rpc;
17661
+ return typeof rpc === "function" || record3(rpc) ? rpc : null;
17662
+ }
17663
+ function rendererHostRpcHostIds(discovery) {
17664
+ return [...discovery.family.keys()].filter(
17665
+ (hostId2) => typeof hostId2 === "string"
17666
+ );
17667
+ }
17668
+
17669
+ // packages/desktop-control/src/renderer-host-rpc-routing.ts
17670
+ function installRendererHostRpcRouting(root, target, dependencies) {
17671
+ const existing = target.__codexhostHostRoutingV1;
17672
+ if (existing) return existing;
17673
+ let disposed = false;
17674
+ let discovery = null;
17675
+ const routes = /* @__PURE__ */ new Map();
17676
+ const read = () => {
17677
+ if (disposed) return null;
17678
+ if (!discovery) {
17679
+ const store = dependencies.findStore(root);
17680
+ discovery = store ? dependencies.findFamily(store) : null;
17681
+ }
17682
+ return discovery;
17683
+ };
17684
+ if (!read()) return null;
17685
+ const isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17686
+ const externalDrafts = /* @__PURE__ */ new Map();
17687
+ const selectedModels = /* @__PURE__ */ new Map();
17688
+ const prewarmCarrier = (carrier) => {
17689
+ const prefix = "codexhost/plugin-v1@";
17690
+ if (!carrier.startsWith(prefix)) return null;
17691
+ try {
17692
+ const json2 = carrier.slice(prefix.length).replace(/[a-f0-9]{2}/gu, (byte) => String.fromCharCode(Number.parseInt(byte, 16)));
17693
+ const route = JSON.parse(json2);
17694
+ if (!isRecord3(route)) return null;
17695
+ const payload = [...JSON.stringify({ ...route, prewarm: true })].map((character) => character.charCodeAt(0).toString(16).padStart(2, "0")).join("");
17696
+ return `${prefix}${payload}`;
17697
+ } catch {
17698
+ return null;
17699
+ }
17700
+ };
17701
+ const publishDraftWorkspace = (hostId2, cwd) => {
17702
+ if (typeof cwd !== "string" || cwd.length === 0) return;
17703
+ const drafts = isRecord3(target.__codexhostDraftWorkspacesV1) ? target.__codexhostDraftWorkspacesV1 : {};
17704
+ if (drafts[hostId2] === cwd) return;
17705
+ drafts[hostId2] = cwd;
17706
+ Object.defineProperty(target, "__codexhostDraftWorkspacesV1", {
17707
+ configurable: true,
17708
+ value: drafts
17709
+ });
17710
+ if (typeof target.dispatchEvent === "function" && typeof CustomEvent === "function") {
17711
+ target.dispatchEvent(
17712
+ new CustomEvent("codexhost:draft-workspace", { detail: { hostId: hostId2, cwd } })
17713
+ );
17714
+ }
17715
+ };
17716
+ const routeCreationCall = (message) => {
17717
+ if (!Array.isArray(message) || message.length !== 2 || message[0] !== "push") return message;
17718
+ const expression = message[1];
17719
+ if (!Array.isArray(expression) || expression.length !== 4 || expression[0] !== "pipeline")
17720
+ return message;
17721
+ const [, importId, path3, args] = expression;
17722
+ if (!Array.isArray(path3) || path3.length !== 1 || !Array.isArray(args)) return message;
17723
+ const [input, options] = args;
17724
+ if (!isRecord3(input) || !isRecord3(input.collaborationMode)) return message;
17725
+ const settings = input.collaborationMode.settings;
17726
+ if (!isRecord3(settings)) return message;
17727
+ let model2 = null;
17728
+ if (path3[0] === "startConversation") {
17729
+ const draftId = isRecord3(options) ? options.clientThreadId : null;
17730
+ model2 = typeof draftId === "string" ? externalDrafts.get(draftId)?.model ?? null : null;
17731
+ } else if (path3[0] === "prewarmConversation") {
17732
+ if (input.ephemeral !== true) publishDraftWorkspace("local", input.cwd);
17733
+ const selected = selectedModels.get("local");
17734
+ model2 = selected ? prewarmCarrier(selected) : null;
17735
+ }
17736
+ if (!model2) return message;
17737
+ return [
17738
+ "push",
17739
+ [
17740
+ "pipeline",
17741
+ importId,
17742
+ path3,
17743
+ [
17744
+ {
17745
+ ...input,
17746
+ collaborationMode: { ...input.collaborationMode, settings: { ...settings, model: model2 } }
17747
+ },
17748
+ ...args.slice(1)
17749
+ ]
17750
+ ]
17751
+ ];
17752
+ };
17753
+ const port = dependencies.portPrototype;
17754
+ const originalPostMessage = port.postMessage;
17755
+ const postMessage = function(message, ...rest) {
17756
+ let routed = message;
17757
+ try {
17758
+ routed = disposed ? message : routeCreationCall(message);
17759
+ } catch {
17760
+ routed = message;
17761
+ }
17762
+ return originalPostMessage.call(this, routed, ...rest);
17763
+ };
17764
+ port.postMessage = postMessage;
17765
+ const createRoute = (hostId2, rpc) => {
17766
+ let retired = false;
17767
+ const isCurrent = () => !retired && !disposed && routes.get(hostId2)?.rpc === rpc;
17768
+ const manager = Object.freeze({
17769
+ kind: "main-process-rpc",
17770
+ getHostId: () => hostId2,
17771
+ sendRequest(method, params, options) {
17772
+ if (!isCurrent())
17773
+ return Promise.reject(new Error(`Renderer request manager is retired for ${hostId2}`));
17774
+ return options === void 0 ? rpc.sendRequest(method, params) : rpc.sendRequest(method, params, options);
17775
+ },
17776
+ // The main process broadcasts every app-server notification to its windows,
17777
+ // including codexhost methods Desktop's own notification table drops.
17778
+ addNotificationCallback(methods, listener) {
17779
+ const accepted = new Set(typeof methods === "string" ? [methods] : methods);
17780
+ const onMessage = (event) => {
17781
+ const { source, data } = event;
17782
+ if (source != null && source !== target) return;
17783
+ if (!isRecord3(data) || data.type !== "mcp-notification" || data.hostId !== hostId2 || typeof data.method !== "string" || !accepted.has(data.method) || !isCurrent())
17784
+ return;
17785
+ listener({ method: data.method, params: data.params });
17786
+ };
17787
+ target.addEventListener?.("message", onMessage);
17788
+ return () => target.removeEventListener?.("message", onMessage);
17789
+ }
17790
+ });
17791
+ const clearDrafts = () => {
17792
+ for (const [draftId, draft] of externalDrafts) {
17793
+ if (draft.owner === policy) externalDrafts.delete(draftId);
17794
+ }
17795
+ };
17796
+ const clear = () => isCurrent() ? Promise.resolve(rpc.clearPrewarmedThreads()).then(() => void 0) : Promise.reject(new Error("Renderer request manager is retired"));
17797
+ const policy = Object.freeze({
17798
+ state: "ready",
17799
+ hostId: hostId2,
17800
+ scopedCreation: true,
17801
+ requestTarget: () => {
17802
+ if (!isCurrent()) throw new Error("Renderer request manager is retired");
17803
+ return manager;
17804
+ },
17805
+ select(model2, draftId) {
17806
+ if (!isCurrent()) throw new Error("Renderer request manager is retired");
17807
+ if (model2 !== null && (typeof model2 !== "string" || !model2.startsWith("codexhost/"))) {
17808
+ throw new Error("Draft route Model must be a codexhost transport carrier");
17809
+ }
17810
+ if (draftId === void 0) {
17811
+ if (model2 === null) clearDrafts();
17812
+ } else if (model2 === null) {
17813
+ if (externalDrafts.get(draftId)?.owner === policy) externalDrafts.delete(draftId);
17814
+ } else {
17815
+ if (!draftId.startsWith("client-new-thread:"))
17816
+ throw new Error("External draft route is missing its client Thread identity");
17817
+ externalDrafts.set(draftId, { model: model2, owner: policy });
17818
+ }
17819
+ if ((selectedModels.get(hostId2) ?? null) === model2) return false;
17820
+ if (model2 === null) selectedModels.delete(hostId2);
17821
+ else selectedModels.set(hostId2, model2);
17822
+ void clear().catch(() => void 0);
17823
+ return true;
17824
+ },
17825
+ clear,
17826
+ dispose() {
17827
+ if (retired) return;
17828
+ retired = true;
17829
+ clearDrafts();
17830
+ selectedModels.delete(hostId2);
17831
+ }
17832
+ });
17833
+ return { hostId: hostId2, manager, policy };
17834
+ };
17835
+ const retire = (hostId2) => {
17836
+ const entry = routes.get(hostId2);
17837
+ routes.delete(hostId2);
17838
+ entry?.route.policy.dispose();
17839
+ };
17840
+ const routeFor = (hostId2) => {
17841
+ const current = read();
17842
+ const rpc = current ? dependencies.resolve(current, hostId2) : null;
17843
+ const previous = routes.get(hostId2);
17844
+ if (rpc && previous?.rpc === rpc) return previous.route;
17845
+ retire(hostId2);
17846
+ if (!rpc) return null;
17847
+ const route = createRoute(hostId2, rpc);
17848
+ routes.set(hostId2, { route, rpc });
17849
+ return route;
17850
+ };
17851
+ const publish = (route) => {
17852
+ const policy = route?.policy;
17853
+ if (target.__codexhostDraftPrewarmPolicyV1 === policy) return;
17854
+ Object.defineProperty(target, "__codexhostDraftPrewarmPolicyV1", {
17855
+ configurable: true,
17856
+ value: policy
17857
+ });
17858
+ if (typeof target.dispatchEvent === "function" && typeof CustomEvent === "function") {
17859
+ target.dispatchEvent(new CustomEvent("codexhost:draft-prewarm-policy-changed"));
17860
+ }
17861
+ };
17862
+ const composerHostId = (composer) => {
17863
+ const hostIds = new Set(dependencies.composerHostIds(composer).hostIds);
17864
+ const hostId2 = hostIds.size === 1 ? hostIds.values().next().value : null;
17865
+ return typeof hostId2 === "string" && hostId2 ? hostId2 : null;
17866
+ };
17867
+ const routing = {
17868
+ knownHostIds() {
17869
+ const current = read();
17870
+ return current ? dependencies.hostIds(current) : [];
17871
+ },
17872
+ forHost(hostId2) {
17873
+ return hostId2 && !disposed ? routeFor(hostId2) : null;
17874
+ },
17875
+ hostIdForComposer(composer) {
17876
+ if (disposed) return null;
17877
+ try {
17878
+ return composerHostId(composer);
17879
+ } catch {
17880
+ return null;
17881
+ }
17882
+ },
17883
+ forComposer(composer) {
17884
+ if (disposed) return null;
17885
+ let hostId2;
17886
+ try {
17887
+ hostId2 = composerHostId(composer);
17888
+ } catch {
17889
+ hostId2 = null;
17890
+ }
17891
+ const route = hostId2 ? routeFor(hostId2) : null;
17892
+ if (!composer) publish(route);
17893
+ return route;
17894
+ },
17895
+ dispose() {
17896
+ if (disposed) return;
17897
+ disposed = true;
17898
+ for (const hostId2 of [...routes.keys()]) retire(hostId2);
17899
+ discovery = null;
17900
+ externalDrafts.clear();
17901
+ selectedModels.clear();
17902
+ if (port.postMessage === postMessage) port.postMessage = originalPostMessage;
17903
+ if (target.__codexhostHostRoutingV1 === routing) {
17904
+ delete target.__codexhostHostRoutingV1;
17905
+ publish(null);
17906
+ }
17907
+ }
17908
+ };
17909
+ Object.defineProperty(target, "__codexhostHostRoutingV1", { configurable: true, value: routing });
17910
+ return routing;
17911
+ }
17912
+
17495
17913
  // packages/desktop-control/src/renderer-draft-prewarm-policy.ts
17496
17914
  var REQUEST_MANAGER_WAIT_TIMEOUT_MS = 6e4;
17497
17915
  var REQUEST_MANAGER_POLL_INTERVAL_MS = 25;
@@ -17503,14 +17921,41 @@ function directRendererInstaller() {
17503
17921
  const resolveRendererHostManager = ${resolveRendererHostManager.toString()};
17504
17922
  const retainRendererHostResponses = ${retainRendererHostResponses.toString()};
17505
17923
  const createDraftPrewarmPolicyBridge = ${createDraftPrewarmPolicyBridge.toString()};
17506
- const routing = (${installRendererHostRouting.toString()})(
17507
- document, window,
17508
- (root) => discoverRendererHosts(root, committedReactAncestors, requestManagerFromHookState),
17924
+ const isolateRendererPrewarmConsumption = ${isolateRendererPrewarmConsumption.toString()};
17925
+ const discover = (root) =>
17926
+ discoverRendererHosts(root, committedReactAncestors, requestManagerFromHookState);
17927
+ const installNative = () => (${installRendererHostRouting.toString()})(
17928
+ document, window, discover,
17509
17929
  (discovery, hostId) => resolveRendererHostManager(discovery, hostId, requestManagerFromHookState),
17510
17930
  (manager, bridge, hostId, target, prewarmed, isCurrent) => createDraftPrewarmPolicyBridge(
17511
17931
  manager, bridge, hostId, target, prewarmed, isCurrent, retainRendererHostResponses,
17932
+ isolateRendererPrewarmConsumption,
17512
17933
  ),
17513
17934
  );
17935
+ const installRpc = () => typeof MessagePort !== 'function' ? null : (${installRendererHostRpcRouting.toString()})(document, window, {
17936
+ findStore: ${findRendererAppScopeStore.toString()},
17937
+ findFamily: ${findRendererHostRpcFamily.toString()},
17938
+ resolve: ${resolveRendererHostRpc.toString()},
17939
+ hostIds: ${rendererHostRpcHostIds.toString()},
17940
+ composerHostIds: (composer) => {
17941
+ const source = composer?.matches?.('[data-codex-composer], [contenteditable="true"][role="textbox"]')
17942
+ ? { querySelectorAll: () => [composer] }
17943
+ : (composer ?? document);
17944
+ return discover(source);
17945
+ },
17946
+ portPrototype: MessagePort.prototype,
17947
+ });
17948
+ // Desktop 26.1027 moved AppServerManagers to the main process. Older builds
17949
+ // expose native managers in Renderer hook state; the main-process mode only
17950
+ // applies when none is visible and its per-Host RPC store is identified.
17951
+ const routing = (() => {
17952
+ if (window.__codexhostHostRoutingV1) return window.__codexhostHostRoutingV1;
17953
+ const native = discover(document);
17954
+ if (native.managers.length || native.registries.length) return installNative();
17955
+ const rpc = installRpc();
17956
+ if (rpc) return rpc;
17957
+ throw new Error('Renderer Host request manager is unavailable');
17958
+ })();
17514
17959
  // Publish a default draft policy only when its Host is unambiguous. Host
17515
17960
  // connections can be ready even when multiple Composers coexist.
17516
17961
  const composerRoute = routing.forComposer();
@@ -17547,6 +17992,114 @@ function installRendererDraftPrewarmPolicyDirect(renderer) {
17547
17992
  );
17548
17993
  }
17549
17994
 
17995
+ // packages/desktop-control/src/renderer-loaded-modules.ts
17996
+ var record2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17997
+ var MAX_MODULES = 4096;
17998
+ function nativeModuleCatalogExpression(urls, complete, owner) {
17999
+ return `Object.defineProperty(globalThis, '__codexhostLoadedModulesV1', {
18000
+ configurable: true,
18001
+ value: Object.freeze({ owner: ${JSON.stringify(owner)}, documentUrl: location.href, complete: ${complete}, urls: Object.freeze(${JSON.stringify(urls)}) })
18002
+ }); void 0`;
18003
+ }
18004
+ async function installRendererLoadedModules(renderer) {
18005
+ const owner = crypto.randomUUID();
18006
+ const contexts = /* @__PURE__ */ new Map();
18007
+ const contextIds = /* @__PURE__ */ new Map();
18008
+ const dirty = /* @__PURE__ */ new Set();
18009
+ let ready = false;
18010
+ let disposed = false;
18011
+ let timer;
18012
+ let publishing = Promise.resolve();
18013
+ const flush = () => {
18014
+ clearTimeout(timer);
18015
+ timer = void 0;
18016
+ const pending = [...dirty];
18017
+ dirty.clear();
18018
+ publishing = publishing.catch(() => void 0).then(async () => {
18019
+ for (const uniqueId of pending) {
18020
+ const context = contexts.get(uniqueId);
18021
+ if (!context || disposed) continue;
18022
+ const response = await renderer.command("Runtime.evaluate", {
18023
+ expression: nativeModuleCatalogExpression([...context.urls], context.complete, owner),
18024
+ uniqueContextId: uniqueId
18025
+ });
18026
+ if (record2(response) && record2(response.exceptionDetails))
18027
+ throw new Error("Loaded Renderer module catalog publication failed");
18028
+ }
18029
+ });
18030
+ return publishing;
18031
+ };
18032
+ const schedule = (uniqueId) => {
18033
+ dirty.add(uniqueId);
18034
+ if (ready && timer === void 0)
18035
+ timer = setTimeout(() => {
18036
+ void flush().catch((error51) => {
18037
+ console.error("Could not publish loaded Renderer modules", error51);
18038
+ });
18039
+ }, 10);
18040
+ };
18041
+ const remove = (id) => {
18042
+ const uniqueId = contextIds.get(id);
18043
+ contextIds.delete(id);
18044
+ if (uniqueId) {
18045
+ contexts.delete(uniqueId);
18046
+ dirty.delete(uniqueId);
18047
+ }
18048
+ };
18049
+ const listeners = [
18050
+ renderer.on("Runtime.executionContextCreated", (params) => {
18051
+ const context = record2(params) ? params.context : null;
18052
+ if (!record2(context) || typeof context.id !== "number" || typeof context.uniqueId !== "string" || !record2(context.auxData) || context.auxData.isDefault !== true)
18053
+ return;
18054
+ contextIds.set(context.id, context.uniqueId);
18055
+ contexts.set(context.uniqueId, { urls: /* @__PURE__ */ new Set(), complete: true });
18056
+ schedule(context.uniqueId);
18057
+ }),
18058
+ renderer.on("Runtime.executionContextDestroyed", (params) => {
18059
+ if (record2(params) && typeof params.executionContextId === "number")
18060
+ remove(params.executionContextId);
18061
+ }),
18062
+ renderer.on("Runtime.executionContextsCleared", () => {
18063
+ contextIds.clear();
18064
+ contexts.clear();
18065
+ dirty.clear();
18066
+ }),
18067
+ renderer.on("Debugger.scriptParsed", (params) => {
18068
+ if (!record2(params) || params.isModule !== true || params.hasSourceURL === true || typeof params.url !== "string" || typeof params.executionContextId !== "number")
18069
+ return;
18070
+ const uniqueId = contextIds.get(params.executionContextId);
18071
+ const context = uniqueId ? contexts.get(uniqueId) : null;
18072
+ if (!context || !uniqueId || context.urls.has(params.url)) return;
18073
+ if (context.urls.size >= MAX_MODULES) context.complete = false;
18074
+ else context.urls.add(params.url);
18075
+ schedule(uniqueId);
18076
+ })
18077
+ ];
18078
+ const dispose = () => {
18079
+ disposed = true;
18080
+ clearTimeout(timer);
18081
+ for (const unsubscribe of listeners) unsubscribe();
18082
+ for (const uniqueId of contexts.keys())
18083
+ void renderer.command("Runtime.evaluate", {
18084
+ expression: `if (globalThis.__codexhostLoadedModulesV1 === undefined || globalThis.__codexhostLoadedModulesV1?.owner === ${JSON.stringify(owner)}) { ${nativeModuleCatalogExpression([], false, owner)} }`,
18085
+ uniqueContextId: uniqueId
18086
+ }).catch(() => void 0);
18087
+ contexts.clear();
18088
+ contextIds.clear();
18089
+ dirty.clear();
18090
+ };
18091
+ try {
18092
+ await renderer.command("Runtime.enable");
18093
+ await renderer.command("Debugger.enable");
18094
+ ready = true;
18095
+ await flush();
18096
+ return dispose;
18097
+ } catch (error51) {
18098
+ dispose();
18099
+ throw error51;
18100
+ }
18101
+ }
18102
+
17550
18103
  // packages/desktop-control/src/renderer-cdp-control-session.ts
17551
18104
  function isRecord2(value) {
17552
18105
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -17691,21 +18244,23 @@ async function waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs
17691
18244
  }
17692
18245
  async function installTarget(target, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations) {
17693
18246
  const renderer = await operations.connect(target.webSocketDebuggerUrl);
18247
+ let disposeModules;
17694
18248
  try {
17695
- await renderer.command("Runtime.enable");
18249
+ disposeModules = await installRendererLoadedModules(renderer);
17696
18250
  await renderer.command("Page.enable");
17697
18251
  await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource });
17698
18252
  await evaluateSource(renderer, rendererSource);
17699
18253
  const draftPrewarmPolicy = await operations.installDraftPrewarmPolicy(renderer);
17700
18254
  const binding = await waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs);
17701
- return { renderer, snapshot: { target, draftPrewarmPolicy, binding } };
18255
+ return { renderer, snapshot: { target, draftPrewarmPolicy, binding }, disposeModules };
17702
18256
  } catch (error51) {
18257
+ disposeModules?.();
17703
18258
  renderer.close();
17704
18259
  throw error51;
17705
18260
  }
17706
18261
  }
17707
18262
  var InstalledRendererCdpControlSession = class {
17708
- constructor(renderer, rendererCdpEndpoint2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot) {
18263
+ constructor(renderer, rendererCdpEndpoint2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot, disposeModules) {
17709
18264
  this.renderer = renderer;
17710
18265
  this.rendererCdpEndpoint = rendererCdpEndpoint2;
17711
18266
  this.rendererSource = rendererSource;
@@ -17714,6 +18269,7 @@ var InstalledRendererCdpControlSession = class {
17714
18269
  this.pollIntervalMs = pollIntervalMs;
17715
18270
  this.operations = operations;
17716
18271
  this.currentSnapshot = currentSnapshot;
18272
+ this.disposeModules = disposeModules;
17717
18273
  }
17718
18274
  renderer;
17719
18275
  rendererCdpEndpoint;
@@ -17723,6 +18279,7 @@ var InstalledRendererCdpControlSession = class {
17723
18279
  pollIntervalMs;
17724
18280
  operations;
17725
18281
  currentSnapshot;
18282
+ disposeModules;
17726
18283
  #closed = false;
17727
18284
  get snapshot() {
17728
18285
  return this.currentSnapshot;
@@ -17745,8 +18302,10 @@ var InstalledRendererCdpControlSession = class {
17745
18302
  this.pollIntervalMs,
17746
18303
  this.operations
17747
18304
  );
18305
+ this.disposeModules();
17748
18306
  this.renderer.close();
17749
18307
  this.renderer = replacement.renderer;
18308
+ this.disposeModules = replacement.disposeModules;
17750
18309
  this.currentSnapshot = replacement.snapshot;
17751
18310
  return this.currentSnapshot;
17752
18311
  }
@@ -17771,8 +18330,10 @@ var InstalledRendererCdpControlSession = class {
17771
18330
  this.pollIntervalMs,
17772
18331
  this.operations
17773
18332
  );
18333
+ this.disposeModules();
17774
18334
  this.renderer.close();
17775
18335
  this.renderer = replacement.renderer;
18336
+ this.disposeModules = replacement.disposeModules;
17776
18337
  this.currentSnapshot = replacement.snapshot;
17777
18338
  return this.currentSnapshot;
17778
18339
  }
@@ -17789,6 +18350,7 @@ var InstalledRendererCdpControlSession = class {
17789
18350
  close() {
17790
18351
  if (this.#closed) return;
17791
18352
  this.#closed = true;
18353
+ this.disposeModules();
17792
18354
  this.renderer.close();
17793
18355
  }
17794
18356
  };
@@ -17826,7 +18388,8 @@ async function createRendererCdpControlSession(options) {
17826
18388
  timeoutMs,
17827
18389
  pollIntervalMs,
17828
18390
  operations,
17829
- installed.snapshot
18391
+ installed.snapshot,
18392
+ installed.disposeModules
17830
18393
  );
17831
18394
  }
17832
18395
  function installRendererCdpControlSession(options) {