@karlorz/codexhost-cli-darwin-x64 0.22.0-1 → 0.22.0-2

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.
@@ -47342,6 +47342,7 @@ var RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES = 256 * 1024;
47342
47342
  var RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS = 1e4;
47343
47343
  var RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS = 2e3;
47344
47344
  var RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS = 3e4;
47345
+ var RENDERER_VOICE_HOST_PUBLISH_RETRY_MS = 1e3;
47345
47346
  var RENDERER_VOICE_HOST_METHODS = [
47346
47347
  VOICE_SETTINGS_METHOD,
47347
47348
  VOICE_GATEWAY_STATUS_METHOD,
@@ -47365,7 +47366,7 @@ function cleanupUnconfirmedError(error51) {
47365
47366
  if (error51 instanceof Error && error51.message === RENDERER_VOICE_HOST_CLEANUP_UNCONFIRMED && allowlistedStage(Reflect.get(error51, "stage")) === "cancel")
47366
47367
  return error51;
47367
47368
  }
47368
- function rendererVoiceHostCapabilitySource(owner, generation) {
47369
+ function rendererVoiceHostCapabilitySource(owner, generation, instanceId = "", installationOrder = 0, publisherId2 = "") {
47369
47370
  const guard = rendererVoiceHostDocumentGuardExpression();
47370
47371
  return `(() => {
47371
47372
  if (!${guard}) return true;
@@ -47377,6 +47378,9 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47377
47378
  const maxBytes = ${RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES};
47378
47379
  const ownerId = ${JSON.stringify(owner)};
47379
47380
  const generation = ${generation};
47381
+ const instance = ${JSON.stringify(instanceId)};
47382
+ const order = ${installationOrder};
47383
+ const publisher = ${JSON.stringify(publisherId2)};
47380
47384
  const settingsTimeout = ${RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS};
47381
47385
  const gatewayTimeout = ${RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS};
47382
47386
  const realtimeTimeout = ${RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS};
@@ -47394,6 +47398,8 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47394
47398
  }
47395
47399
  };
47396
47400
  const previous = globalThis[cap];
47401
+ // A publish that outlived its installation must leave a newer installation's state intact.
47402
+ if (previous && previous.publisher === publisher && typeof previous.order === "number" && previous.order > order) return true;
47397
47403
  if (previous && previous.generation !== generation) settleAll(${JSON.stringify(UNAVAILABLE)});
47398
47404
  globalThis[deliver] = (message) => {
47399
47405
  if (!message || typeof message !== "object" || typeof message.id !== "string") return;
@@ -47418,6 +47424,9 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47418
47424
  value: Object.freeze({
47419
47425
  owner: ownerId,
47420
47426
  generation,
47427
+ instance,
47428
+ order,
47429
+ publisher,
47421
47430
  request(method, params) {
47422
47431
  try {
47423
47432
  if (!${guard}) return unavailable();
@@ -47449,7 +47458,7 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47449
47458
  } catch (e) {}
47450
47459
  reject(new Error(${JSON.stringify(UNAVAILABLE)}));
47451
47460
  }, timeoutMs);
47452
- pending.set(id, { resolve, reject, timer, generation });
47461
+ pending.set(id, { resolve, reject, timer, generation, instance });
47453
47462
  try {
47454
47463
  globalThis[binding](payload);
47455
47464
  } catch {
@@ -47481,21 +47490,6 @@ function callIdFromCreateResult(result) {
47481
47490
  const callId = realtimeCallIdFromLocation(location);
47482
47491
  return isRealtimeCallId(callId) ? callId : void 0;
47483
47492
  }
47484
- async function cleanupAbandonedCreate(execution, params, result) {
47485
- let unconfirmed;
47486
- const note = (error51) => {
47487
- unconfirmed ??= cleanupUnconfirmedError(error51);
47488
- };
47489
- const requestId2 = typeof params.requestId === "string" ? params.requestId : void 0;
47490
- if (requestId2) {
47491
- await execution.request(REALTIME_CALL_METHOD, { operation: "cancel", requestId: requestId2 }).catch(note);
47492
- }
47493
- const callId = callIdFromCreateResult(result);
47494
- if (!callId)
47495
- return unconfirmed;
47496
- await execution.request(REALTIME_CALL_METHOD, { operation: "hangup", callId }).catch(note);
47497
- return unconfirmed;
47498
- }
47499
47493
  function captureExecution(host) {
47500
47494
  return host.bindExecution?.() ?? {
47501
47495
  generation: host.generation,
@@ -47532,23 +47526,49 @@ async function deliver(renderer, executionContextId, message2) {
47532
47526
  returnByValue: true
47533
47527
  }).catch(() => void 0);
47534
47528
  }
47535
- async function registerFutureScript(renderer, source, previousId) {
47536
- if (previousId) {
47537
- await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier: previousId }).catch(() => void 0);
47538
- }
47529
+ async function addFutureScript(renderer, source) {
47539
47530
  const added = await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source });
47540
- return isRecord10(added) && typeof added.identifier === "string" ? added.identifier : void 0;
47531
+ if (!isRecord10(added) || typeof added.identifier !== "string")
47532
+ throw new Error("Voice Host future script registration failed");
47533
+ return added.identifier;
47541
47534
  }
47542
47535
  async function removeFutureScript(renderer, identifier) {
47543
47536
  if (!identifier)
47544
47537
  return;
47545
47538
  await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => void 0);
47546
47539
  }
47540
+ function rendererVoiceHostCleanupSource(instanceId) {
47541
+ return `(() => {
47542
+ const instance = ${JSON.stringify(instanceId)};
47543
+ const pending = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
47544
+ if (pending && typeof pending.forEach === "function") {
47545
+ for (const [id, wait] of [...pending.entries()]) {
47546
+ if (!wait || wait.instance !== instance) continue;
47547
+ pending.delete(id);
47548
+ try { clearTimeout(wait.timer); } catch (e) {}
47549
+ try { wait.reject(new Error(${JSON.stringify(UNKNOWN_OUTCOME)})); } catch (e) {}
47550
+ }
47551
+ }
47552
+ const capability = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
47553
+ if (capability && capability.instance === instance) {
47554
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
47555
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}];
47556
+ if (globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}] === pending)
47557
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
47558
+ }
47559
+ return true;
47560
+ })()`;
47561
+ }
47562
+ var publisherId = crypto.randomUUID();
47563
+ var installationSequence = 0;
47547
47564
  async function installRendererVoiceHostBinding(renderer, host, options) {
47565
+ const instance = crypto.randomUUID();
47566
+ const installationOrder = installationSequence += 1;
47548
47567
  let disposed = false;
47568
+ let ready = false;
47549
47569
  let scriptId;
47570
+ let publishedGeneration;
47550
47571
  let publishing = Promise.resolve();
47551
- const inflight = /* @__PURE__ */ new Set();
47552
47572
  const works = /* @__PURE__ */ new Map();
47553
47573
  const abandonedIds = /* @__PURE__ */ new Set();
47554
47574
  const contexts = /* @__PURE__ */ new Map();
@@ -47574,18 +47594,53 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47574
47594
  stage: "cancel"
47575
47595
  });
47576
47596
  };
47577
- const abandonWork = (item) => {
47578
- if (item.abandoned)
47597
+ const reportCleanupUnconfirmed = (item, error51) => {
47598
+ const create = item.create;
47599
+ const unconfirmed = cleanupUnconfirmedError(error51);
47600
+ if (!create || !unconfirmed || create.cleanupReported)
47601
+ return;
47602
+ create.cleanupReported = true;
47603
+ void observeCleanupUnconfirmed(item.contextId, item.pageId, unconfirmed);
47604
+ };
47605
+ const requestCleanup = (item, params) => {
47606
+ try {
47607
+ void item.execution.request(REALTIME_CALL_METHOD, params).catch((error51) => reportCleanupUnconfirmed(item, error51));
47608
+ } catch (error51) {
47609
+ reportCleanupUnconfirmed(item, error51);
47610
+ }
47611
+ };
47612
+ const hangUpLateCreate = (item) => {
47613
+ const create = item.create;
47614
+ if (!create || create.hangupIssued)
47615
+ return;
47616
+ const callId = callIdFromCreateResult(create.result);
47617
+ if (!callId)
47579
47618
  return;
47619
+ create.hangupIssued = true;
47620
+ requestCleanup(item, { operation: "hangup", callId });
47621
+ };
47622
+ const retireWork = (item) => {
47580
47623
  item.abandoned = true;
47581
- if (!item.create)
47624
+ const create = item.create;
47625
+ if (!create)
47626
+ return;
47627
+ if (create.settled) {
47628
+ hangUpLateCreate(item);
47582
47629
  return;
47583
- void cleanupAbandonedCreate(item.execution, { requestId: item.create.requestId, operation: "create" }, item.create.result).then((unconfirmed) => observeCleanupUnconfirmed(item.contextId, item.pageId, unconfirmed));
47630
+ }
47631
+ if (create.cancelIssued)
47632
+ return;
47633
+ create.cancelIssued = true;
47634
+ requestCleanup(item, { operation: "cancel", requestId: create.requestId });
47635
+ };
47636
+ const retireInflight = () => {
47637
+ for (const item of works.values())
47638
+ retireWork(item);
47584
47639
  };
47585
47640
  const abandonMatching = (contextId, uniqueId) => {
47586
47641
  for (const item of works.values()) {
47587
47642
  if (contextId !== void 0 && item.contextId === contextId || uniqueId !== void 0 && item.uniqueId === uniqueId)
47588
- abandonWork(item);
47643
+ retireWork(item);
47589
47644
  }
47590
47645
  };
47591
47646
  const forgetContext = (params) => {
@@ -47613,7 +47668,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47613
47668
  const unsubscribeCleared = renderer.on("Runtime.executionContextsCleared", () => {
47614
47669
  contexts.clear();
47615
47670
  for (const item of works.values())
47616
- abandonWork(item);
47671
+ retireWork(item);
47617
47672
  });
47618
47673
  const contextIsVerified = async (executionContextId, uniqueId) => {
47619
47674
  const tracked = contexts.get(executionContextId);
@@ -47627,41 +47682,75 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47627
47682
  return false;
47628
47683
  return isEligibleVoiceHostUrl(document.href);
47629
47684
  };
47630
- const publishGeneration = async () => {
47631
- if (disposed)
47685
+ let publishRetry;
47686
+ const clearPublishRetry = () => {
47687
+ if (publishRetry === void 0)
47632
47688
  return;
47633
- const startedGeneration = host.generation;
47634
- const source = rendererVoiceHostCapabilitySource(host.owner, startedGeneration);
47635
- const addedId = await registerFutureScript(renderer, source, scriptId);
47636
- if (disposed || host.generation !== startedGeneration) {
47637
- await removeFutureScript(renderer, addedId);
47689
+ clearTimeout(publishRetry);
47690
+ publishRetry = void 0;
47691
+ };
47692
+ const schedulePublishRetry = () => {
47693
+ if (disposed || publishRetry !== void 0)
47638
47694
  return;
47639
- }
47640
- scriptId = addedId;
47641
- await renderer.evaluate(source);
47695
+ publishRetry = setTimeout(() => {
47696
+ publishRetry = void 0;
47697
+ if (disposed)
47698
+ return;
47699
+ void enqueuePublish().catch(() => schedulePublishRetry());
47700
+ }, RENDERER_VOICE_HOST_PUBLISH_RETRY_MS);
47642
47701
  };
47643
- const enqueuePublish = () => {
47644
- publishing = publishing.catch(() => void 0).then(() => publishGeneration()).catch(() => void 0);
47702
+ const cleanupPageState = async () => {
47703
+ try {
47704
+ await renderer.evaluate(rendererVoiceHostCleanupSource(instance));
47705
+ } catch {
47706
+ }
47645
47707
  };
47646
- const cancelInflightCreates = () => {
47647
- for (const item of works.values()) {
47648
- if (!item.create || item.abandoned)
47708
+ const publishGeneration = async () => {
47709
+ for (let attempt = 0; !disposed && attempt < 3; attempt += 1) {
47710
+ const startedGeneration = host.generation;
47711
+ if (startedGeneration === publishedGeneration)
47712
+ return;
47713
+ const source = rendererVoiceHostCapabilitySource(host.owner, startedGeneration, instance, installationOrder, publisherId);
47714
+ const addedId = await addFutureScript(renderer, source);
47715
+ if (disposed || host.generation !== startedGeneration) {
47716
+ await removeFutureScript(renderer, addedId);
47649
47717
  continue;
47650
- void item.execution.request(REALTIME_CALL_METHOD, { operation: "cancel", requestId: item.create.requestId }).catch((error51) => observeCleanupUnconfirmed(item.contextId, item.pageId, cleanupUnconfirmedError(error51)));
47718
+ }
47719
+ const previousId = scriptId;
47720
+ scriptId = addedId;
47721
+ await removeFutureScript(renderer, previousId);
47722
+ if (disposed)
47723
+ return;
47724
+ await renderer.evaluate(source);
47725
+ if (disposed) {
47726
+ await cleanupPageState();
47727
+ return;
47728
+ }
47729
+ publishedGeneration = startedGeneration;
47730
+ if (host.generation === startedGeneration)
47731
+ return;
47651
47732
  }
47652
47733
  };
47653
- if (options?.enableRuntime !== false)
47654
- await renderer.command("Runtime.enable");
47655
- await renderer.command("Page.enable");
47656
- await renderer.command("Runtime.addBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME });
47657
- await publishGeneration();
47734
+ const enqueuePublish = () => {
47735
+ const next = publishing.catch(() => void 0).then(async () => {
47736
+ await publishGeneration();
47737
+ if (!disposed && host.generation !== publishedGeneration)
47738
+ schedulePublishRetry();
47739
+ else
47740
+ clearPublishRetry();
47741
+ });
47742
+ publishing = next.catch(() => void 0);
47743
+ return next;
47744
+ };
47658
47745
  const refresh2 = () => {
47659
47746
  if (disposed)
47660
47747
  return;
47661
- cancelInflightCreates();
47662
- enqueuePublish();
47748
+ retireInflight();
47749
+ if (!ready)
47750
+ return;
47751
+ void enqueuePublish().catch(() => schedulePublishRetry());
47663
47752
  };
47664
- const unsubscribeGeneration = host.onGenerationChange?.(refresh2);
47753
+ let unsubscribeGeneration;
47665
47754
  const unsubscribe = renderer.on("Runtime.bindingCalled", (params) => {
47666
47755
  if (disposed || !isRecord10(params) || params.name !== RENDERER_VOICE_HOST_BINDING_NAME)
47667
47756
  return;
@@ -47672,7 +47761,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47672
47761
  const contextId = params.executionContextId;
47673
47762
  const payloadText = params.payload;
47674
47763
  const startedGeneration = host.generation;
47675
- const work = (async () => {
47764
+ void (async () => {
47676
47765
  let parsed2;
47677
47766
  try {
47678
47767
  parsed2 = JSON.parse(payloadText);
@@ -47685,7 +47774,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47685
47774
  if (parsed2.abandon === true) {
47686
47775
  const existing = works.get(requestId2);
47687
47776
  if (existing)
47688
- abandonWork(existing);
47777
+ retireWork(existing);
47689
47778
  else
47690
47779
  abandonedIds.add(requestId2);
47691
47780
  return;
@@ -47707,14 +47796,21 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47707
47796
  generation: startedGeneration,
47708
47797
  execution,
47709
47798
  abandoned: abandonedIds.has(requestId2),
47710
- ...isCreateOperation(parsed2.method, parsed2.params) && typeof parsed2.params.requestId === "string" ? { create: { requestId: parsed2.params.requestId } } : {}
47799
+ ...isCreateOperation(parsed2.method, parsed2.params) && typeof parsed2.params.requestId === "string" ? {
47800
+ create: {
47801
+ requestId: parsed2.params.requestId,
47802
+ settled: false,
47803
+ cancelIssued: false,
47804
+ hangupIssued: false,
47805
+ cleanupReported: false
47806
+ }
47807
+ } : {}
47711
47808
  };
47712
47809
  works.set(requestId2, item);
47713
47810
  abandonedIds.delete(requestId2);
47714
47811
  try {
47715
47812
  if (item.abandoned) {
47716
- if (item.create)
47717
- await observeCleanupUnconfirmed(contextId, requestId2, await cleanupAbandonedCreate(item.execution, { requestId: item.create.requestId, operation: "create" }, item.create.result));
47813
+ retireWork(item);
47718
47814
  return;
47719
47815
  }
47720
47816
  const method = parsed2.method;
@@ -47722,8 +47818,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47722
47818
  const verified = await contextIsVerified(contextId, uniqueId);
47723
47819
  const still = contexts.get(contextId);
47724
47820
  if (disposed || item.abandoned || host.generation !== startedGeneration || still?.uniqueId !== uniqueId) {
47725
- if (item.create)
47726
- await observeCleanupUnconfirmed(contextId, requestId2, await cleanupAbandonedCreate(item.execution, requestParams, item.create.result));
47821
+ retireWork(item);
47727
47822
  return;
47728
47823
  }
47729
47824
  if (!verified) {
@@ -47737,18 +47832,23 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47737
47832
  }
47738
47833
  try {
47739
47834
  const result = await item.execution.request(method, requestParams);
47740
- if (item.create)
47835
+ if (item.create) {
47741
47836
  item.create.result = result;
47837
+ item.create.settled = true;
47838
+ }
47742
47839
  const after = contexts.get(contextId);
47743
47840
  if (disposed || item.abandoned || host.generation !== startedGeneration || after?.uniqueId !== uniqueId) {
47744
- if (item.create)
47745
- await observeCleanupUnconfirmed(contextId, requestId2, await cleanupAbandonedCreate(item.execution, requestParams, result));
47841
+ retireWork(item);
47746
47842
  return;
47747
47843
  }
47748
47844
  await deliver(renderer, contextId, { id: requestId2, ok: true, result });
47749
47845
  } catch (error51) {
47846
+ if (item.create)
47847
+ item.create.settled = true;
47750
47848
  const unconfirmed = cleanupUnconfirmedError(error51);
47751
47849
  if (unconfirmed && !disposed) {
47850
+ if (item.create)
47851
+ item.create.cleanupReported = true;
47752
47852
  await deliver(renderer, contextId, {
47753
47853
  id: requestId2,
47754
47854
  ok: false,
@@ -47771,43 +47871,35 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47771
47871
  works.delete(requestId2);
47772
47872
  }
47773
47873
  })();
47774
- inflight.add(work);
47775
- void work.finally(() => inflight.delete(work));
47776
47874
  });
47777
- return () => {
47875
+ const dispose = () => {
47778
47876
  if (disposed)
47779
47877
  return;
47780
47878
  disposed = true;
47879
+ clearPublishRetry();
47781
47880
  unsubscribeGeneration?.();
47782
47881
  unsubscribe();
47783
47882
  unsubscribeCreated();
47784
47883
  unsubscribeDestroyed();
47785
47884
  unsubscribeCleared();
47786
- cancelInflightCreates();
47787
- const outstanding = [...inflight];
47788
- const leftover = [...works.values()];
47789
- void Promise.allSettled(outstanding).then(async () => {
47790
- for (const item of leftover)
47791
- if (item.create)
47792
- await observeCleanupUnconfirmed(item.contextId, item.pageId, await cleanupAbandonedCreate(item.execution, { requestId: item.create.requestId, operation: "create" }, item.create.result));
47793
- });
47885
+ retireInflight();
47794
47886
  void removeFutureScript(renderer, scriptId);
47795
47887
  void renderer.command("Runtime.removeBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME }).catch(() => void 0);
47796
- void renderer.evaluate(`(() => {
47797
- const pending = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
47798
- if (pending && typeof pending.forEach === "function") {
47799
- for (const [id, wait] of [...pending.entries()]) {
47800
- pending.delete(id);
47801
- try { clearTimeout(wait.timer); } catch (e) {}
47802
- try { wait.reject(new Error(${JSON.stringify(UNKNOWN_OUTCOME)})); } catch (e) {}
47803
- }
47804
- }
47805
- delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
47806
- delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}];
47807
- delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
47808
- return true;
47809
- })()`).catch(() => void 0);
47888
+ void cleanupPageState();
47810
47889
  };
47890
+ try {
47891
+ unsubscribeGeneration = host.onGenerationChange?.(refresh2);
47892
+ if (options?.enableRuntime !== false)
47893
+ await renderer.command("Runtime.enable");
47894
+ await renderer.command("Page.enable");
47895
+ await renderer.command("Runtime.addBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME });
47896
+ ready = true;
47897
+ await enqueuePublish();
47898
+ } catch (error51) {
47899
+ dispose();
47900
+ throw error51;
47901
+ }
47902
+ return dispose;
47811
47903
  }
47812
47904
 
47813
47905
  // packages/desktop-control/dist/host-client-channel.js
@@ -51104,6 +51196,10 @@ function discoveryTimeoutSignal(timeoutMs, signal) {
51104
51196
  function abortFailure(signal, fallback) {
51105
51197
  return signal.reason instanceof Error ? signal.reason : new Error(fallback);
51106
51198
  }
51199
+ function throwIfCdpAborted(signal, fallback) {
51200
+ if (signal.aborted)
51201
+ throw abortFailure(signal, fallback);
51202
+ }
51107
51203
  function awaitWithSignal(promise2, signal, timeoutMessage) {
51108
51204
  if (signal.aborted)
51109
51205
  return Promise.reject(abortFailure(signal, timeoutMessage));
@@ -51208,6 +51304,38 @@ function unbindRendererVoiceHost(renderer, disposals) {
51208
51304
  disposals.get(renderer)?.();
51209
51305
  disposals.delete(renderer);
51210
51306
  }
51307
+ var VOICE_HOST_ATTACH_TIMEOUT_MS = 15e3;
51308
+ var VOICE_HOST_OVERLAY_RETRY_MS = 5e3;
51309
+ var VOICE_HOST_LIVENESS_INTERVAL_MS = 5e3;
51310
+ var VOICE_HOST_LIVENESS_TIMEOUT_MS = 3e3;
51311
+ async function bindVoiceHostOnNewConnection(target2, voiceHost, operations2, timeoutMs, signal) {
51312
+ const timeout = AbortSignal.timeout(timeoutMs);
51313
+ const deadline = signal ? AbortSignal.any([timeout, signal]) : timeout;
51314
+ const timeoutMessage = "Voice Host attachment timed out";
51315
+ const client = await connectRendererTarget(target2, operations2, deadline, timeoutMessage);
51316
+ const installing2 = installRendererVoiceHostBinding(client, voiceHost);
51317
+ try {
51318
+ const dispose = await awaitWithSignal(installing2, deadline, timeoutMessage);
51319
+ return { targetId: target2.id, client, dispose, verifiedAt: Date.now() };
51320
+ } catch (error51) {
51321
+ client.close();
51322
+ throw error51;
51323
+ }
51324
+ }
51325
+ async function lateVoiceBindingIsLive(binding, signal) {
51326
+ if (Date.now() - binding.verifiedAt < VOICE_HOST_LIVENESS_INTERVAL_MS)
51327
+ return true;
51328
+ if (signal.aborted)
51329
+ return false;
51330
+ const deadline = AbortSignal.any([AbortSignal.timeout(VOICE_HOST_LIVENESS_TIMEOUT_MS), signal]);
51331
+ try {
51332
+ await awaitWithSignal(binding.client.evaluate("1", VOICE_HOST_LIVENESS_TIMEOUT_MS), deadline, "Voice Host binding liveness check timed out");
51333
+ binding.verifiedAt = Date.now();
51334
+ return true;
51335
+ } catch {
51336
+ return false;
51337
+ }
51338
+ }
51211
51339
  async function evaluateSource(renderer, source) {
51212
51340
  const response = await renderer.command("Runtime.evaluate", {
51213
51341
  expression: source,
@@ -51396,6 +51524,7 @@ async function installOverlayHook(target2, overlayHookSource, overlayClients, op
51396
51524
  await run(() => bindRendererVoiceHost(connected, voiceHost, voiceHostDisposals, { enableRuntime: false }));
51397
51525
  await run(() => connected.command("Runtime.enable"));
51398
51526
  await run(() => connected.command("Page.enable"));
51527
+ throwIfCdpAborted(signal, timeoutMessage);
51399
51528
  overlayClients.set(target2.id, connected);
51400
51529
  } else if (voiceHost && voiceHostDisposals && !voiceHostDisposals.has(connected)) {
51401
51530
  await run(() => bindRendererVoiceHost(connected, voiceHost, voiceHostDisposals, { enableRuntime: false }));
@@ -51484,6 +51613,7 @@ async function installBrowserAnnotationStyles(target2, browserClients, operation
51484
51613
  await run(() => connected.command("Page.addScriptToEvaluateOnNewDocument", {
51485
51614
  source: BROWSER_ANNOTATION_STYLE_COMPAT_SOURCE
51486
51615
  }));
51616
+ throwIfCdpAborted(signal, timeoutMessage);
51487
51617
  browserClients.set(target2.id, connected);
51488
51618
  }
51489
51619
  const installed = await run(() => connected.evaluate("globalThis.__codexhostBrowserAnnotationStylesV1?.refresh() === true"));
@@ -51513,7 +51643,7 @@ async function installLocalThreadRenderer(target2, source, enabledAgents, operat
51513
51643
  renderer.close();
51514
51644
  }
51515
51645
  }
51516
- async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations2, signal, voiceHost, voiceHostDisposals) {
51646
+ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations2, signal, voiceHost, voiceHostDisposals, lateVoiceBindings) {
51517
51647
  try {
51518
51648
  const targets = await awaitWithSignal(operations2.listTargets(endpoint, signal), signal, "Auxiliary Renderer CDP target discovery timed out");
51519
51649
  const liveTargets = new Set(targets.map((target2) => target2.id));
@@ -51527,6 +51657,14 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
51527
51657
  }
51528
51658
  }
51529
51659
  }
51660
+ if (lateVoiceBindings)
51661
+ for (const [id2, binding] of lateVoiceBindings) {
51662
+ if (liveTargets.has(id2))
51663
+ continue;
51664
+ binding.dispose();
51665
+ binding.client.close();
51666
+ lateVoiceBindings.delete(id2);
51667
+ }
51530
51668
  await Promise.allSettled([
51531
51669
  ...targets.filter(isBrowserPage).map((target2) => installBrowserAnnotationStyles(target2, browserStyleClients, operations2, signal)),
51532
51670
  ...overlayHookSource ? selectAvatarOverlayRendererTargets(targets).map((overlay) => installOverlayHook(overlay, overlayHookSource, overlayClients, operations2, signal, overlayVoiceBootstrapSource, voiceHost, voiceHostDisposals)) : [],
@@ -51535,20 +51673,22 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
51535
51673
  } catch {
51536
51674
  }
51537
51675
  }
51538
- async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations2, voiceHost, voiceHostDisposals) {
51539
- const renderer = await operations2.connect(target2.webSocketDebuggerUrl);
51676
+ async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations2, voiceHost, voiceHostDisposals, signal) {
51677
+ const timeoutMessage = "Primary Renderer installation timed out";
51678
+ const run = (operation) => signal ? runWithCdpSignal(signal, timeoutMessage, operation) : operation();
51679
+ const renderer = signal ? await connectRendererTarget(target2, operations2, signal, timeoutMessage) : await operations2.connect(target2.webSocketDebuggerUrl);
51540
51680
  let disposeModules;
51541
51681
  try {
51542
51682
  if (voiceHost && voiceHostDisposals)
51543
- await bindRendererVoiceHost(renderer, voiceHost, voiceHostDisposals, {
51683
+ await run(() => bindRendererVoiceHost(renderer, voiceHost, voiceHostDisposals, {
51544
51684
  enableRuntime: false
51545
- });
51546
- disposeModules = await installRendererLoadedModules(renderer);
51547
- await renderer.command("Page.enable");
51548
- await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource });
51549
- await evaluateSource(renderer, rendererSource);
51550
- const draftPrewarmPolicy = await operations2.installDraftPrewarmPolicy(renderer);
51551
- const binding = await waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs);
51685
+ }));
51686
+ disposeModules = await run(() => installRendererLoadedModules(renderer));
51687
+ await run(() => renderer.command("Page.enable"));
51688
+ await run(() => renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource }));
51689
+ await run(() => evaluateSource(renderer, rendererSource));
51690
+ const draftPrewarmPolicy = await run(() => operations2.installDraftPrewarmPolicy(renderer));
51691
+ const binding = await waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs, signal);
51552
51692
  return { renderer, snapshot: { target: target2, draftPrewarmPolicy, binding }, disposeModules };
51553
51693
  } catch (error51) {
51554
51694
  disposeModules?.();
@@ -51575,6 +51715,14 @@ var InstalledRendererCdpControlSession = class {
51575
51715
  voiceHost;
51576
51716
  voiceHostDisposals;
51577
51717
  #closed = false;
51718
+ #lateVoiceHost;
51719
+ #lateVoicePrimaryId;
51720
+ #lateVoiceAttach;
51721
+ #lateVoiceBindings = /* @__PURE__ */ new Map();
51722
+ #overlayVoiceRetryAt = /* @__PURE__ */ new Map();
51723
+ // close() aborts this deadline, so discovery, connects, installs, and
51724
+ // liveness probes in flight stop instead of running to their own timeouts.
51725
+ #shutdown = new AbortController();
51578
51726
  constructor(renderer, rendererCdpEndpoint, rendererSource, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations2, currentSnapshot, disposeModules, voiceHost, voiceHostDisposals) {
51579
51727
  this.renderer = renderer;
51580
51728
  this.rendererCdpEndpoint = rendererCdpEndpoint;
@@ -51596,41 +51744,153 @@ var InstalledRendererCdpControlSession = class {
51596
51744
  return this.currentSnapshot;
51597
51745
  }
51598
51746
  async ensureInstalled() {
51599
- if (this.#closed)
51600
- throw new Error("Renderer CDP Control Session is closed");
51601
- const target2 = await waitForPrimaryTarget(this.rendererCdpEndpoint, this.operations, this.timeoutMs, this.pollIntervalMs, this.currentSnapshot.target.id);
51747
+ this.#assertOpen();
51748
+ const target2 = await waitForPrimaryTarget(this.rendererCdpEndpoint, this.operations, this.timeoutMs, this.pollIntervalMs, this.currentSnapshot.target.id, this.#shutdown.signal);
51749
+ this.#assertOpen();
51602
51750
  if (target2.id !== this.currentSnapshot.target.id) {
51603
- const replacement = await installTarget(target2, this.rendererSource, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.operations, this.voiceHost, this.voiceHostDisposals);
51604
- this.disposeModules();
51605
- unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
51606
- this.renderer.close();
51607
- this.renderer = replacement.renderer;
51608
- this.disposeModules = replacement.disposeModules;
51609
- this.currentSnapshot = replacement.snapshot;
51751
+ this.#disposeLateVoiceBinding(this.currentSnapshot.target.id);
51752
+ await this.#replacePrimary(target2);
51610
51753
  } else {
51611
- try {
51612
- const existing = await readBinding(this.renderer);
51613
- if (existing === null)
51614
- await evaluateSource(this.renderer, this.rendererSource);
51615
- const draftPrewarmPolicy = await this.operations.installDraftPrewarmPolicy(this.renderer);
51616
- const binding = await waitForBinding(this.renderer, this.enabledAgents, this.timeoutMs, this.pollIntervalMs);
51617
- this.currentSnapshot = { target: target2, draftPrewarmPolicy, binding };
51618
- } catch {
51619
- const replacement = await installTarget(target2, this.rendererSource, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.operations, this.voiceHost, this.voiceHostDisposals);
51620
- this.disposeModules();
51621
- unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
51622
- this.renderer.close();
51623
- this.renderer = replacement.renderer;
51624
- this.disposeModules = replacement.disposeModules;
51625
- this.currentSnapshot = replacement.snapshot;
51626
- }
51754
+ await this.#reconcilePrimary(target2);
51627
51755
  }
51628
- await installAuxiliaryRenderers(this.rendererCdpEndpoint, this.rendererSource, this.enabledAgents, this.overlayHookSource, this.overlayVoiceBootstrapSource, this.browserStyleClients, this.overlayClients, this.operations, discoveryTimeoutSignal(this.timeoutMs), this.voiceHost, this.voiceHostDisposals);
51756
+ await installAuxiliaryRenderers(this.rendererCdpEndpoint, this.rendererSource, this.enabledAgents, this.overlayHookSource, this.overlayVoiceBootstrapSource, this.browserStyleClients, this.overlayClients, this.operations, discoveryTimeoutSignal(this.timeoutMs, this.#shutdown.signal), this.voiceHost, this.voiceHostDisposals, this.#lateVoiceBindings);
51757
+ this.#assertOpen();
51629
51758
  return this.currentSnapshot;
51630
51759
  }
51631
- async activateDesktop() {
51760
+ async #reconcilePrimary(target2) {
51761
+ try {
51762
+ const existing = await this.#runWhileOpen(() => readBinding(this.renderer));
51763
+ if (existing === null)
51764
+ await this.#runWhileOpen(() => evaluateSource(this.renderer, this.rendererSource));
51765
+ const draftPrewarmPolicy = await this.#runWhileOpen(() => this.operations.installDraftPrewarmPolicy(this.renderer));
51766
+ const binding = await waitForBinding(this.renderer, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.#shutdown.signal);
51767
+ this.#assertOpen();
51768
+ this.currentSnapshot = { target: target2, draftPrewarmPolicy, binding };
51769
+ } catch {
51770
+ this.#assertOpen();
51771
+ this.#disposeLateVoiceBinding(this.currentSnapshot.target.id);
51772
+ await this.#replacePrimary(target2);
51773
+ }
51774
+ }
51775
+ async #replacePrimary(target2) {
51776
+ const replacement = await installTarget(target2, this.rendererSource, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.operations, this.voiceHost, this.voiceHostDisposals, this.#shutdown.signal);
51777
+ if (this.#closed) {
51778
+ replacement.disposeModules();
51779
+ unbindRendererVoiceHost(replacement.renderer, this.voiceHostDisposals);
51780
+ replacement.renderer.close();
51781
+ throw new Error("Renderer CDP Control Session is closed");
51782
+ }
51783
+ this.disposeModules();
51784
+ unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
51785
+ this.renderer.close();
51786
+ this.renderer = replacement.renderer;
51787
+ this.disposeModules = replacement.disposeModules;
51788
+ this.currentSnapshot = replacement.snapshot;
51789
+ }
51790
+ #assertOpen() {
51632
51791
  if (this.#closed)
51633
51792
  throw new Error("Renderer CDP Control Session is closed");
51793
+ }
51794
+ #runWhileOpen(operation) {
51795
+ return runWithCdpSignal(this.#shutdown.signal, "Renderer CDP Control Session is closed", operation);
51796
+ }
51797
+ async attachVoiceHost(voiceHost) {
51798
+ this.#assertOpen();
51799
+ if (this.voiceHost)
51800
+ return;
51801
+ this.#lateVoiceAttach ??= this.#reconcileVoiceHost(voiceHost).finally(() => {
51802
+ this.#lateVoiceAttach = void 0;
51803
+ });
51804
+ return this.#lateVoiceAttach;
51805
+ }
51806
+ async #reconcileVoiceHost(voiceHost) {
51807
+ const timeoutMs = Math.min(this.timeoutMs, VOICE_HOST_ATTACH_TIMEOUT_MS);
51808
+ if (this.#lateVoiceHost !== void 0 && this.#lateVoiceHost !== voiceHost)
51809
+ this.#disposeLateVoiceBindings();
51810
+ const primaryTarget = this.currentSnapshot.target;
51811
+ if (this.#lateVoicePrimaryId !== void 0 && this.#lateVoicePrimaryId !== primaryTarget.id)
51812
+ this.#disposeLateVoiceBinding(this.#lateVoicePrimaryId);
51813
+ const existingPrimary = this.#lateVoiceBindings.get(primaryTarget.id);
51814
+ if (existingPrimary && !await lateVoiceBindingIsLive(existingPrimary, this.#shutdown.signal))
51815
+ this.#disposeLateVoiceBinding(primaryTarget.id);
51816
+ this.#assertOpen();
51817
+ if (!this.#lateVoiceBindings.has(primaryTarget.id)) {
51818
+ this.#disposeLateVoiceBinding(primaryTarget.id);
51819
+ const binding = await bindVoiceHostOnNewConnection(primaryTarget, voiceHost, this.operations, timeoutMs, this.#shutdown.signal);
51820
+ if (this.#closed) {
51821
+ binding.dispose();
51822
+ binding.client.close();
51823
+ throw new Error("Renderer CDP Control Session is closed");
51824
+ }
51825
+ this.#lateVoiceBindings.set(binding.targetId, binding);
51826
+ }
51827
+ this.#lateVoicePrimaryId = primaryTarget.id;
51828
+ this.#lateVoiceHost = voiceHost;
51829
+ await this.#reconcileOverlayVoiceHost(voiceHost, timeoutMs);
51830
+ this.#assertOpen();
51831
+ }
51832
+ async #reconcileOverlayVoiceHost(voiceHost, timeoutMs) {
51833
+ if (this.#closed || !this.overlayHookSource)
51834
+ return;
51835
+ const deadline = AbortSignal.any([AbortSignal.timeout(timeoutMs), this.#shutdown.signal]);
51836
+ let targets;
51837
+ try {
51838
+ targets = await awaitWithSignal(this.operations.listTargets(this.rendererCdpEndpoint, deadline), deadline, "Late overlay CDP target discovery timed out");
51839
+ } catch {
51840
+ return;
51841
+ }
51842
+ const overlays = selectAvatarOverlayRendererTargets(targets);
51843
+ const live = new Set(overlays.map((target2) => target2.id));
51844
+ for (const id2 of [...this.#lateVoiceBindings.keys()])
51845
+ if (id2 !== this.#lateVoicePrimaryId && !live.has(id2))
51846
+ this.#disposeLateVoiceBinding(id2);
51847
+ for (const id2 of [...this.#overlayVoiceRetryAt.keys()])
51848
+ if (!live.has(id2))
51849
+ this.#overlayVoiceRetryAt.delete(id2);
51850
+ await Promise.allSettled(overlays.map(async (target2) => {
51851
+ if (this.#closed)
51852
+ return;
51853
+ const existing = this.#lateVoiceBindings.get(target2.id);
51854
+ if (existing) {
51855
+ if (await lateVoiceBindingIsLive(existing, this.#shutdown.signal))
51856
+ return;
51857
+ if (this.#closed)
51858
+ return;
51859
+ this.#disposeLateVoiceBinding(target2.id);
51860
+ }
51861
+ if ((this.#overlayVoiceRetryAt.get(target2.id) ?? 0) > Date.now())
51862
+ return;
51863
+ try {
51864
+ const binding = await bindVoiceHostOnNewConnection(target2, voiceHost, this.operations, timeoutMs, this.#shutdown.signal);
51865
+ if (this.#closed) {
51866
+ binding.dispose();
51867
+ binding.client.close();
51868
+ return;
51869
+ }
51870
+ this.#lateVoiceBindings.set(binding.targetId, binding);
51871
+ this.#overlayVoiceRetryAt.delete(binding.targetId);
51872
+ } catch {
51873
+ this.#overlayVoiceRetryAt.set(target2.id, Date.now() + VOICE_HOST_OVERLAY_RETRY_MS);
51874
+ }
51875
+ }));
51876
+ }
51877
+ #disposeLateVoiceBinding(targetId) {
51878
+ const binding = this.#lateVoiceBindings.get(targetId);
51879
+ if (!binding)
51880
+ return;
51881
+ binding.dispose();
51882
+ binding.client.close();
51883
+ this.#lateVoiceBindings.delete(targetId);
51884
+ if (this.#lateVoicePrimaryId === targetId)
51885
+ this.#lateVoicePrimaryId = void 0;
51886
+ this.#overlayVoiceRetryAt.delete(targetId);
51887
+ }
51888
+ #disposeLateVoiceBindings() {
51889
+ for (const targetId of [...this.#lateVoiceBindings.keys()])
51890
+ this.#disposeLateVoiceBinding(targetId);
51891
+ }
51892
+ async activateDesktop() {
51893
+ this.#assertOpen();
51634
51894
  await this.renderer.command("Page.bringToFront");
51635
51895
  return 1;
51636
51896
  }
@@ -51643,6 +51903,7 @@ var InstalledRendererCdpControlSession = class {
51643
51903
  if (this.#closed)
51644
51904
  return;
51645
51905
  this.#closed = true;
51906
+ this.#shutdown.abort(new Error("Renderer CDP Control Session is closed"));
51646
51907
  this.disposeModules();
51647
51908
  unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
51648
51909
  this.renderer.close();
@@ -51657,6 +51918,7 @@ var InstalledRendererCdpControlSession = class {
51657
51918
  for (const dispose of this.voiceHostDisposals.values())
51658
51919
  dispose();
51659
51920
  this.voiceHostDisposals.clear();
51921
+ this.#disposeLateVoiceBindings();
51660
51922
  }
51661
51923
  };
51662
51924
  var defaultOperations = {