@karlorz/codexhost-cli-linux-x64 0.22.0-1 → 0.22.0-5

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.
@@ -33585,7 +33585,9 @@ var storedTurnMappingV1Schema = external_exports.object({
33585
33585
  nativeTurnRef: nativeTurnRefSchema,
33586
33586
  nativeCheckpointRef: nativeCheckpointRefSchema.optional(),
33587
33587
  /** Desktop presentation for work completed during an external voice call. */
33588
- realtimeInline: external_exports.literal(true).optional()
33588
+ realtimeInline: external_exports.literal(true).optional(),
33589
+ /** Voice-originated input uses Desktop's native delegation presentation. */
33590
+ realtimeDelegation: external_exports.literal(true).optional()
33589
33591
  }).strict();
33590
33592
  var storedGitInfoV1Schema = external_exports.object({
33591
33593
  branch: nonBlankTextSchema6.max(4096).optional(),
@@ -34903,6 +34905,8 @@ var MappingStore = class {
34903
34905
  }
34904
34906
  if (update.realtimeInline)
34905
34907
  hostMatch.realtimeInline = true;
34908
+ if (update.realtimeDelegation)
34909
+ hostMatch.realtimeDelegation = true;
34906
34910
  continue;
34907
34911
  }
34908
34912
  const added = { ...update };
@@ -47342,6 +47346,7 @@ var RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES = 256 * 1024;
47342
47346
  var RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS = 1e4;
47343
47347
  var RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS = 2e3;
47344
47348
  var RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS = 3e4;
47349
+ var RENDERER_VOICE_HOST_PUBLISH_RETRY_MS = 1e3;
47345
47350
  var RENDERER_VOICE_HOST_METHODS = [
47346
47351
  VOICE_SETTINGS_METHOD,
47347
47352
  VOICE_GATEWAY_STATUS_METHOD,
@@ -47365,7 +47370,7 @@ function cleanupUnconfirmedError(error51) {
47365
47370
  if (error51 instanceof Error && error51.message === RENDERER_VOICE_HOST_CLEANUP_UNCONFIRMED && allowlistedStage(Reflect.get(error51, "stage")) === "cancel")
47366
47371
  return error51;
47367
47372
  }
47368
- function rendererVoiceHostCapabilitySource(owner, generation) {
47373
+ function rendererVoiceHostCapabilitySource(owner, generation, instanceId = "", installationOrder = 0, publisherId2 = "") {
47369
47374
  const guard = rendererVoiceHostDocumentGuardExpression();
47370
47375
  return `(() => {
47371
47376
  if (!${guard}) return true;
@@ -47377,6 +47382,9 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47377
47382
  const maxBytes = ${RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES};
47378
47383
  const ownerId = ${JSON.stringify(owner)};
47379
47384
  const generation = ${generation};
47385
+ const instance = ${JSON.stringify(instanceId)};
47386
+ const order = ${installationOrder};
47387
+ const publisher = ${JSON.stringify(publisherId2)};
47380
47388
  const settingsTimeout = ${RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS};
47381
47389
  const gatewayTimeout = ${RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS};
47382
47390
  const realtimeTimeout = ${RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS};
@@ -47394,6 +47402,8 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47394
47402
  }
47395
47403
  };
47396
47404
  const previous = globalThis[cap];
47405
+ // A publish that outlived its installation must leave a newer installation's state intact.
47406
+ if (previous && previous.publisher === publisher && typeof previous.order === "number" && previous.order > order) return true;
47397
47407
  if (previous && previous.generation !== generation) settleAll(${JSON.stringify(UNAVAILABLE)});
47398
47408
  globalThis[deliver] = (message) => {
47399
47409
  if (!message || typeof message !== "object" || typeof message.id !== "string") return;
@@ -47418,6 +47428,9 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47418
47428
  value: Object.freeze({
47419
47429
  owner: ownerId,
47420
47430
  generation,
47431
+ instance,
47432
+ order,
47433
+ publisher,
47421
47434
  request(method, params) {
47422
47435
  try {
47423
47436
  if (!${guard}) return unavailable();
@@ -47449,7 +47462,7 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
47449
47462
  } catch (e) {}
47450
47463
  reject(new Error(${JSON.stringify(UNAVAILABLE)}));
47451
47464
  }, timeoutMs);
47452
- pending.set(id, { resolve, reject, timer, generation });
47465
+ pending.set(id, { resolve, reject, timer, generation, instance });
47453
47466
  try {
47454
47467
  globalThis[binding](payload);
47455
47468
  } catch {
@@ -47481,21 +47494,6 @@ function callIdFromCreateResult(result) {
47481
47494
  const callId = realtimeCallIdFromLocation(location);
47482
47495
  return isRealtimeCallId(callId) ? callId : void 0;
47483
47496
  }
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
47497
  function captureExecution(host) {
47500
47498
  return host.bindExecution?.() ?? {
47501
47499
  generation: host.generation,
@@ -47532,23 +47530,49 @@ async function deliver(renderer, executionContextId, message2) {
47532
47530
  returnByValue: true
47533
47531
  }).catch(() => void 0);
47534
47532
  }
47535
- async function registerFutureScript(renderer, source, previousId) {
47536
- if (previousId) {
47537
- await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier: previousId }).catch(() => void 0);
47538
- }
47533
+ async function addFutureScript(renderer, source) {
47539
47534
  const added = await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source });
47540
- return isRecord10(added) && typeof added.identifier === "string" ? added.identifier : void 0;
47535
+ if (!isRecord10(added) || typeof added.identifier !== "string")
47536
+ throw new Error("Voice Host future script registration failed");
47537
+ return added.identifier;
47541
47538
  }
47542
47539
  async function removeFutureScript(renderer, identifier) {
47543
47540
  if (!identifier)
47544
47541
  return;
47545
47542
  await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => void 0);
47546
47543
  }
47544
+ function rendererVoiceHostCleanupSource(instanceId) {
47545
+ return `(() => {
47546
+ const instance = ${JSON.stringify(instanceId)};
47547
+ const pending = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
47548
+ if (pending && typeof pending.forEach === "function") {
47549
+ for (const [id, wait] of [...pending.entries()]) {
47550
+ if (!wait || wait.instance !== instance) continue;
47551
+ pending.delete(id);
47552
+ try { clearTimeout(wait.timer); } catch (e) {}
47553
+ try { wait.reject(new Error(${JSON.stringify(UNKNOWN_OUTCOME)})); } catch (e) {}
47554
+ }
47555
+ }
47556
+ const capability = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
47557
+ if (capability && capability.instance === instance) {
47558
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
47559
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}];
47560
+ if (globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}] === pending)
47561
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
47562
+ }
47563
+ return true;
47564
+ })()`;
47565
+ }
47566
+ var publisherId = crypto.randomUUID();
47567
+ var installationSequence = 0;
47547
47568
  async function installRendererVoiceHostBinding(renderer, host, options) {
47569
+ const instance = crypto.randomUUID();
47570
+ const installationOrder = installationSequence += 1;
47548
47571
  let disposed = false;
47572
+ let ready = false;
47549
47573
  let scriptId;
47574
+ let publishedGeneration;
47550
47575
  let publishing = Promise.resolve();
47551
- const inflight = /* @__PURE__ */ new Set();
47552
47576
  const works = /* @__PURE__ */ new Map();
47553
47577
  const abandonedIds = /* @__PURE__ */ new Set();
47554
47578
  const contexts = /* @__PURE__ */ new Map();
@@ -47574,18 +47598,53 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47574
47598
  stage: "cancel"
47575
47599
  });
47576
47600
  };
47577
- const abandonWork = (item) => {
47578
- if (item.abandoned)
47601
+ const reportCleanupUnconfirmed = (item, error51) => {
47602
+ const create = item.create;
47603
+ const unconfirmed = cleanupUnconfirmedError(error51);
47604
+ if (!create || !unconfirmed || create.cleanupReported)
47605
+ return;
47606
+ create.cleanupReported = true;
47607
+ void observeCleanupUnconfirmed(item.contextId, item.pageId, unconfirmed);
47608
+ };
47609
+ const requestCleanup = (item, params) => {
47610
+ try {
47611
+ void item.execution.request(REALTIME_CALL_METHOD, params).catch((error51) => reportCleanupUnconfirmed(item, error51));
47612
+ } catch (error51) {
47613
+ reportCleanupUnconfirmed(item, error51);
47614
+ }
47615
+ };
47616
+ const hangUpLateCreate = (item) => {
47617
+ const create = item.create;
47618
+ if (!create || create.hangupIssued)
47579
47619
  return;
47620
+ const callId = callIdFromCreateResult(create.result);
47621
+ if (!callId)
47622
+ return;
47623
+ create.hangupIssued = true;
47624
+ requestCleanup(item, { operation: "hangup", callId });
47625
+ };
47626
+ const retireWork = (item) => {
47580
47627
  item.abandoned = true;
47581
- if (!item.create)
47628
+ const create = item.create;
47629
+ if (!create)
47630
+ return;
47631
+ if (create.settled) {
47632
+ hangUpLateCreate(item);
47582
47633
  return;
47583
- void cleanupAbandonedCreate(item.execution, { requestId: item.create.requestId, operation: "create" }, item.create.result).then((unconfirmed) => observeCleanupUnconfirmed(item.contextId, item.pageId, unconfirmed));
47634
+ }
47635
+ if (create.cancelIssued)
47636
+ return;
47637
+ create.cancelIssued = true;
47638
+ requestCleanup(item, { operation: "cancel", requestId: create.requestId });
47639
+ };
47640
+ const retireInflight = () => {
47641
+ for (const item of works.values())
47642
+ retireWork(item);
47584
47643
  };
47585
47644
  const abandonMatching = (contextId, uniqueId) => {
47586
47645
  for (const item of works.values()) {
47587
47646
  if (contextId !== void 0 && item.contextId === contextId || uniqueId !== void 0 && item.uniqueId === uniqueId)
47588
- abandonWork(item);
47647
+ retireWork(item);
47589
47648
  }
47590
47649
  };
47591
47650
  const forgetContext = (params) => {
@@ -47613,7 +47672,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47613
47672
  const unsubscribeCleared = renderer.on("Runtime.executionContextsCleared", () => {
47614
47673
  contexts.clear();
47615
47674
  for (const item of works.values())
47616
- abandonWork(item);
47675
+ retireWork(item);
47617
47676
  });
47618
47677
  const contextIsVerified = async (executionContextId, uniqueId) => {
47619
47678
  const tracked = contexts.get(executionContextId);
@@ -47627,41 +47686,75 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47627
47686
  return false;
47628
47687
  return isEligibleVoiceHostUrl(document.href);
47629
47688
  };
47630
- const publishGeneration = async () => {
47631
- if (disposed)
47689
+ let publishRetry;
47690
+ const clearPublishRetry = () => {
47691
+ if (publishRetry === void 0)
47632
47692
  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);
47693
+ clearTimeout(publishRetry);
47694
+ publishRetry = void 0;
47695
+ };
47696
+ const schedulePublishRetry = () => {
47697
+ if (disposed || publishRetry !== void 0)
47638
47698
  return;
47639
- }
47640
- scriptId = addedId;
47641
- await renderer.evaluate(source);
47699
+ publishRetry = setTimeout(() => {
47700
+ publishRetry = void 0;
47701
+ if (disposed)
47702
+ return;
47703
+ void enqueuePublish().catch(() => schedulePublishRetry());
47704
+ }, RENDERER_VOICE_HOST_PUBLISH_RETRY_MS);
47642
47705
  };
47643
- const enqueuePublish = () => {
47644
- publishing = publishing.catch(() => void 0).then(() => publishGeneration()).catch(() => void 0);
47706
+ const cleanupPageState = async () => {
47707
+ try {
47708
+ await renderer.evaluate(rendererVoiceHostCleanupSource(instance));
47709
+ } catch {
47710
+ }
47645
47711
  };
47646
- const cancelInflightCreates = () => {
47647
- for (const item of works.values()) {
47648
- if (!item.create || item.abandoned)
47712
+ const publishGeneration = async () => {
47713
+ for (let attempt = 0; !disposed && attempt < 3; attempt += 1) {
47714
+ const startedGeneration = host.generation;
47715
+ if (startedGeneration === publishedGeneration)
47716
+ return;
47717
+ const source = rendererVoiceHostCapabilitySource(host.owner, startedGeneration, instance, installationOrder, publisherId);
47718
+ const addedId = await addFutureScript(renderer, source);
47719
+ if (disposed || host.generation !== startedGeneration) {
47720
+ await removeFutureScript(renderer, addedId);
47649
47721
  continue;
47650
- void item.execution.request(REALTIME_CALL_METHOD, { operation: "cancel", requestId: item.create.requestId }).catch((error51) => observeCleanupUnconfirmed(item.contextId, item.pageId, cleanupUnconfirmedError(error51)));
47722
+ }
47723
+ const previousId = scriptId;
47724
+ scriptId = addedId;
47725
+ await removeFutureScript(renderer, previousId);
47726
+ if (disposed)
47727
+ return;
47728
+ await renderer.evaluate(source);
47729
+ if (disposed) {
47730
+ await cleanupPageState();
47731
+ return;
47732
+ }
47733
+ publishedGeneration = startedGeneration;
47734
+ if (host.generation === startedGeneration)
47735
+ return;
47651
47736
  }
47652
47737
  };
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();
47738
+ const enqueuePublish = () => {
47739
+ const next = publishing.catch(() => void 0).then(async () => {
47740
+ await publishGeneration();
47741
+ if (!disposed && host.generation !== publishedGeneration)
47742
+ schedulePublishRetry();
47743
+ else
47744
+ clearPublishRetry();
47745
+ });
47746
+ publishing = next.catch(() => void 0);
47747
+ return next;
47748
+ };
47658
47749
  const refresh2 = () => {
47659
47750
  if (disposed)
47660
47751
  return;
47661
- cancelInflightCreates();
47662
- enqueuePublish();
47752
+ retireInflight();
47753
+ if (!ready)
47754
+ return;
47755
+ void enqueuePublish().catch(() => schedulePublishRetry());
47663
47756
  };
47664
- const unsubscribeGeneration = host.onGenerationChange?.(refresh2);
47757
+ let unsubscribeGeneration;
47665
47758
  const unsubscribe = renderer.on("Runtime.bindingCalled", (params) => {
47666
47759
  if (disposed || !isRecord10(params) || params.name !== RENDERER_VOICE_HOST_BINDING_NAME)
47667
47760
  return;
@@ -47672,7 +47765,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47672
47765
  const contextId = params.executionContextId;
47673
47766
  const payloadText = params.payload;
47674
47767
  const startedGeneration = host.generation;
47675
- const work = (async () => {
47768
+ void (async () => {
47676
47769
  let parsed2;
47677
47770
  try {
47678
47771
  parsed2 = JSON.parse(payloadText);
@@ -47685,7 +47778,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47685
47778
  if (parsed2.abandon === true) {
47686
47779
  const existing = works.get(requestId2);
47687
47780
  if (existing)
47688
- abandonWork(existing);
47781
+ retireWork(existing);
47689
47782
  else
47690
47783
  abandonedIds.add(requestId2);
47691
47784
  return;
@@ -47707,14 +47800,21 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47707
47800
  generation: startedGeneration,
47708
47801
  execution,
47709
47802
  abandoned: abandonedIds.has(requestId2),
47710
- ...isCreateOperation(parsed2.method, parsed2.params) && typeof parsed2.params.requestId === "string" ? { create: { requestId: parsed2.params.requestId } } : {}
47803
+ ...isCreateOperation(parsed2.method, parsed2.params) && typeof parsed2.params.requestId === "string" ? {
47804
+ create: {
47805
+ requestId: parsed2.params.requestId,
47806
+ settled: false,
47807
+ cancelIssued: false,
47808
+ hangupIssued: false,
47809
+ cleanupReported: false
47810
+ }
47811
+ } : {}
47711
47812
  };
47712
47813
  works.set(requestId2, item);
47713
47814
  abandonedIds.delete(requestId2);
47714
47815
  try {
47715
47816
  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));
47817
+ retireWork(item);
47718
47818
  return;
47719
47819
  }
47720
47820
  const method = parsed2.method;
@@ -47722,8 +47822,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47722
47822
  const verified = await contextIsVerified(contextId, uniqueId);
47723
47823
  const still = contexts.get(contextId);
47724
47824
  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));
47825
+ retireWork(item);
47727
47826
  return;
47728
47827
  }
47729
47828
  if (!verified) {
@@ -47737,18 +47836,23 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47737
47836
  }
47738
47837
  try {
47739
47838
  const result = await item.execution.request(method, requestParams);
47740
- if (item.create)
47839
+ if (item.create) {
47741
47840
  item.create.result = result;
47841
+ item.create.settled = true;
47842
+ }
47742
47843
  const after = contexts.get(contextId);
47743
47844
  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));
47845
+ retireWork(item);
47746
47846
  return;
47747
47847
  }
47748
47848
  await deliver(renderer, contextId, { id: requestId2, ok: true, result });
47749
47849
  } catch (error51) {
47850
+ if (item.create)
47851
+ item.create.settled = true;
47750
47852
  const unconfirmed = cleanupUnconfirmedError(error51);
47751
47853
  if (unconfirmed && !disposed) {
47854
+ if (item.create)
47855
+ item.create.cleanupReported = true;
47752
47856
  await deliver(renderer, contextId, {
47753
47857
  id: requestId2,
47754
47858
  ok: false,
@@ -47771,43 +47875,35 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
47771
47875
  works.delete(requestId2);
47772
47876
  }
47773
47877
  })();
47774
- inflight.add(work);
47775
- void work.finally(() => inflight.delete(work));
47776
47878
  });
47777
- return () => {
47879
+ const dispose = () => {
47778
47880
  if (disposed)
47779
47881
  return;
47780
47882
  disposed = true;
47883
+ clearPublishRetry();
47781
47884
  unsubscribeGeneration?.();
47782
47885
  unsubscribe();
47783
47886
  unsubscribeCreated();
47784
47887
  unsubscribeDestroyed();
47785
47888
  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
- });
47889
+ retireInflight();
47794
47890
  void removeFutureScript(renderer, scriptId);
47795
47891
  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);
47892
+ void cleanupPageState();
47810
47893
  };
47894
+ try {
47895
+ unsubscribeGeneration = host.onGenerationChange?.(refresh2);
47896
+ if (options?.enableRuntime !== false)
47897
+ await renderer.command("Runtime.enable");
47898
+ await renderer.command("Page.enable");
47899
+ await renderer.command("Runtime.addBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME });
47900
+ ready = true;
47901
+ await enqueuePublish();
47902
+ } catch (error51) {
47903
+ dispose();
47904
+ throw error51;
47905
+ }
47906
+ return dispose;
47811
47907
  }
47812
47908
 
47813
47909
  // packages/desktop-control/dist/host-client-channel.js
@@ -51104,6 +51200,39 @@ function discoveryTimeoutSignal(timeoutMs, signal) {
51104
51200
  function abortFailure(signal, fallback) {
51105
51201
  return signal.reason instanceof Error ? signal.reason : new Error(fallback);
51106
51202
  }
51203
+ function isRendererDocumentLoadEvent(params) {
51204
+ if (!isRecord12(params) || typeof params.name !== "string")
51205
+ return false;
51206
+ return params.name === "DOMContentLoaded" || params.name === "load" || params.name === "networkIdle";
51207
+ }
51208
+ async function waitForRendererDocumentLoad(renderer, run, signal, timeoutMessage) {
51209
+ await run(() => renderer.command("Page.enable"));
51210
+ let finished = false;
51211
+ const loaded = new Promise((resolve3) => {
51212
+ const complete = () => {
51213
+ if (finished)
51214
+ return;
51215
+ finished = true;
51216
+ unsubscribeLoad();
51217
+ unsubscribeLifecycle();
51218
+ resolve3();
51219
+ };
51220
+ const unsubscribeLoad = renderer.on("Page.loadEventFired", complete);
51221
+ const unsubscribeLifecycle = renderer.on("Page.lifecycleEvent", (params) => {
51222
+ if (isRendererDocumentLoadEvent(params))
51223
+ complete();
51224
+ });
51225
+ });
51226
+ await run(() => renderer.command("Page.setLifecycleEventsEnabled", { enabled: true }));
51227
+ if (signal)
51228
+ await awaitWithSignal(loaded, signal, timeoutMessage);
51229
+ else
51230
+ await loaded;
51231
+ }
51232
+ function throwIfCdpAborted(signal, fallback) {
51233
+ if (signal.aborted)
51234
+ throw abortFailure(signal, fallback);
51235
+ }
51107
51236
  function awaitWithSignal(promise2, signal, timeoutMessage) {
51108
51237
  if (signal.aborted)
51109
51238
  return Promise.reject(abortFailure(signal, timeoutMessage));
@@ -51208,6 +51337,38 @@ function unbindRendererVoiceHost(renderer, disposals) {
51208
51337
  disposals.get(renderer)?.();
51209
51338
  disposals.delete(renderer);
51210
51339
  }
51340
+ var VOICE_HOST_ATTACH_TIMEOUT_MS = 15e3;
51341
+ var VOICE_HOST_OVERLAY_RETRY_MS = 5e3;
51342
+ var VOICE_HOST_LIVENESS_INTERVAL_MS = 5e3;
51343
+ var VOICE_HOST_LIVENESS_TIMEOUT_MS = 3e3;
51344
+ async function bindVoiceHostOnNewConnection(target2, voiceHost, operations2, timeoutMs, signal) {
51345
+ const timeout = AbortSignal.timeout(timeoutMs);
51346
+ const deadline = signal ? AbortSignal.any([timeout, signal]) : timeout;
51347
+ const timeoutMessage = "Voice Host attachment timed out";
51348
+ const client = await connectRendererTarget(target2, operations2, deadline, timeoutMessage);
51349
+ const installing2 = installRendererVoiceHostBinding(client, voiceHost);
51350
+ try {
51351
+ const dispose = await awaitWithSignal(installing2, deadline, timeoutMessage);
51352
+ return { targetId: target2.id, client, dispose, verifiedAt: Date.now() };
51353
+ } catch (error51) {
51354
+ client.close();
51355
+ throw error51;
51356
+ }
51357
+ }
51358
+ async function lateVoiceBindingIsLive(binding, signal) {
51359
+ if (Date.now() - binding.verifiedAt < VOICE_HOST_LIVENESS_INTERVAL_MS)
51360
+ return true;
51361
+ if (signal.aborted)
51362
+ return false;
51363
+ const deadline = AbortSignal.any([AbortSignal.timeout(VOICE_HOST_LIVENESS_TIMEOUT_MS), signal]);
51364
+ try {
51365
+ await awaitWithSignal(binding.client.evaluate("1", VOICE_HOST_LIVENESS_TIMEOUT_MS), deadline, "Voice Host binding liveness check timed out");
51366
+ binding.verifiedAt = Date.now();
51367
+ return true;
51368
+ } catch {
51369
+ return false;
51370
+ }
51371
+ }
51211
51372
  async function evaluateSource(renderer, source) {
51212
51373
  const response = await renderer.command("Runtime.evaluate", {
51213
51374
  expression: source,
@@ -51396,6 +51557,7 @@ async function installOverlayHook(target2, overlayHookSource, overlayClients, op
51396
51557
  await run(() => bindRendererVoiceHost(connected, voiceHost, voiceHostDisposals, { enableRuntime: false }));
51397
51558
  await run(() => connected.command("Runtime.enable"));
51398
51559
  await run(() => connected.command("Page.enable"));
51560
+ throwIfCdpAborted(signal, timeoutMessage);
51399
51561
  overlayClients.set(target2.id, connected);
51400
51562
  } else if (voiceHost && voiceHostDisposals && !voiceHostDisposals.has(connected)) {
51401
51563
  await run(() => bindRendererVoiceHost(connected, voiceHost, voiceHostDisposals, { enableRuntime: false }));
@@ -51484,6 +51646,7 @@ async function installBrowserAnnotationStyles(target2, browserClients, operation
51484
51646
  await run(() => connected.command("Page.addScriptToEvaluateOnNewDocument", {
51485
51647
  source: BROWSER_ANNOTATION_STYLE_COMPAT_SOURCE
51486
51648
  }));
51649
+ throwIfCdpAborted(signal, timeoutMessage);
51487
51650
  browserClients.set(target2.id, connected);
51488
51651
  }
51489
51652
  const installed = await run(() => connected.evaluate("globalThis.__codexhostBrowserAnnotationStylesV1?.refresh() === true"));
@@ -51513,7 +51676,7 @@ async function installLocalThreadRenderer(target2, source, enabledAgents, operat
51513
51676
  renderer.close();
51514
51677
  }
51515
51678
  }
51516
- async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations2, signal, voiceHost, voiceHostDisposals) {
51679
+ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations2, signal, voiceHost, voiceHostDisposals, lateVoiceBindings) {
51517
51680
  try {
51518
51681
  const targets = await awaitWithSignal(operations2.listTargets(endpoint, signal), signal, "Auxiliary Renderer CDP target discovery timed out");
51519
51682
  const liveTargets = new Set(targets.map((target2) => target2.id));
@@ -51527,6 +51690,14 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
51527
51690
  }
51528
51691
  }
51529
51692
  }
51693
+ if (lateVoiceBindings)
51694
+ for (const [id2, binding] of lateVoiceBindings) {
51695
+ if (liveTargets.has(id2))
51696
+ continue;
51697
+ binding.dispose();
51698
+ binding.client.close();
51699
+ lateVoiceBindings.delete(id2);
51700
+ }
51530
51701
  await Promise.allSettled([
51531
51702
  ...targets.filter(isBrowserPage).map((target2) => installBrowserAnnotationStyles(target2, browserStyleClients, operations2, signal)),
51532
51703
  ...overlayHookSource ? selectAvatarOverlayRendererTargets(targets).map((overlay) => installOverlayHook(overlay, overlayHookSource, overlayClients, operations2, signal, overlayVoiceBootstrapSource, voiceHost, voiceHostDisposals)) : [],
@@ -51535,20 +51706,26 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
51535
51706
  } catch {
51536
51707
  }
51537
51708
  }
51538
- async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations2, voiceHost, voiceHostDisposals) {
51539
- const renderer = await operations2.connect(target2.webSocketDebuggerUrl);
51709
+ async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations2, voiceHost, voiceHostDisposals, signal, waitForDocumentLoad) {
51710
+ const timeoutMessage = "Primary Renderer installation timed out";
51711
+ const loadSignal = signal ?? (waitForDocumentLoad ? AbortSignal.timeout(timeoutMs) : void 0);
51712
+ const run = (operation) => loadSignal ? runWithCdpSignal(loadSignal, timeoutMessage, operation) : operation();
51713
+ const renderer = loadSignal ? await connectRendererTarget(target2, operations2, loadSignal, timeoutMessage) : await operations2.connect(target2.webSocketDebuggerUrl);
51540
51714
  let disposeModules;
51541
51715
  try {
51542
51716
  if (voiceHost && voiceHostDisposals)
51543
- await bindRendererVoiceHost(renderer, voiceHost, voiceHostDisposals, {
51717
+ await run(() => bindRendererVoiceHost(renderer, voiceHost, voiceHostDisposals, {
51544
51718
  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);
51719
+ }));
51720
+ if (waitForDocumentLoad) {
51721
+ await waitForRendererDocumentLoad(renderer, run, loadSignal, timeoutMessage);
51722
+ }
51723
+ disposeModules = await run(() => installRendererLoadedModules(renderer));
51724
+ await run(() => renderer.command("Page.enable"));
51725
+ await run(() => renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource }));
51726
+ await run(() => evaluateSource(renderer, rendererSource));
51727
+ const draftPrewarmPolicy = await run(() => operations2.installDraftPrewarmPolicy(renderer));
51728
+ const binding = await waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs, signal);
51552
51729
  return { renderer, snapshot: { target: target2, draftPrewarmPolicy, binding }, disposeModules };
51553
51730
  } catch (error51) {
51554
51731
  disposeModules?.();
@@ -51574,8 +51751,17 @@ var InstalledRendererCdpControlSession = class {
51574
51751
  disposeModules;
51575
51752
  voiceHost;
51576
51753
  voiceHostDisposals;
51754
+ waitForDocumentLoad;
51577
51755
  #closed = false;
51578
- constructor(renderer, rendererCdpEndpoint, rendererSource, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations2, currentSnapshot, disposeModules, voiceHost, voiceHostDisposals) {
51756
+ #lateVoiceHost;
51757
+ #lateVoicePrimaryId;
51758
+ #lateVoiceAttach;
51759
+ #lateVoiceBindings = /* @__PURE__ */ new Map();
51760
+ #overlayVoiceRetryAt = /* @__PURE__ */ new Map();
51761
+ // close() aborts this deadline, so discovery, connects, installs, and
51762
+ // liveness probes in flight stop instead of running to their own timeouts.
51763
+ #shutdown = new AbortController();
51764
+ constructor(renderer, rendererCdpEndpoint, rendererSource, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations2, currentSnapshot, disposeModules, voiceHost, voiceHostDisposals, waitForDocumentLoad) {
51579
51765
  this.renderer = renderer;
51580
51766
  this.rendererCdpEndpoint = rendererCdpEndpoint;
51581
51767
  this.rendererSource = rendererSource;
@@ -51591,46 +51777,159 @@ var InstalledRendererCdpControlSession = class {
51591
51777
  this.disposeModules = disposeModules;
51592
51778
  this.voiceHost = voiceHost;
51593
51779
  this.voiceHostDisposals = voiceHostDisposals;
51780
+ this.waitForDocumentLoad = waitForDocumentLoad;
51594
51781
  }
51595
51782
  get snapshot() {
51596
51783
  return this.currentSnapshot;
51597
51784
  }
51598
51785
  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);
51786
+ this.#assertOpen();
51787
+ const target2 = await waitForPrimaryTarget(this.rendererCdpEndpoint, this.operations, this.timeoutMs, this.pollIntervalMs, this.currentSnapshot.target.id, this.#shutdown.signal);
51788
+ this.#assertOpen();
51602
51789
  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;
51790
+ this.#disposeLateVoiceBinding(this.currentSnapshot.target.id);
51791
+ await this.#replacePrimary(target2);
51610
51792
  } 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
- }
51793
+ await this.#reconcilePrimary(target2);
51627
51794
  }
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);
51795
+ 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);
51796
+ this.#assertOpen();
51629
51797
  return this.currentSnapshot;
51630
51798
  }
51631
- async activateDesktop() {
51799
+ async #reconcilePrimary(target2) {
51800
+ try {
51801
+ const existing = await this.#runWhileOpen(() => readBinding(this.renderer));
51802
+ if (existing === null)
51803
+ await this.#runWhileOpen(() => evaluateSource(this.renderer, this.rendererSource));
51804
+ const draftPrewarmPolicy = await this.#runWhileOpen(() => this.operations.installDraftPrewarmPolicy(this.renderer));
51805
+ const binding = await waitForBinding(this.renderer, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.#shutdown.signal);
51806
+ this.#assertOpen();
51807
+ this.currentSnapshot = { target: target2, draftPrewarmPolicy, binding };
51808
+ } catch {
51809
+ this.#assertOpen();
51810
+ this.#disposeLateVoiceBinding(this.currentSnapshot.target.id);
51811
+ await this.#replacePrimary(target2);
51812
+ }
51813
+ }
51814
+ async #replacePrimary(target2) {
51815
+ const replacement = await installTarget(target2, this.rendererSource, this.enabledAgents, this.timeoutMs, this.pollIntervalMs, this.operations, this.voiceHost, this.voiceHostDisposals, this.#shutdown.signal, this.waitForDocumentLoad);
51816
+ if (this.#closed) {
51817
+ replacement.disposeModules();
51818
+ unbindRendererVoiceHost(replacement.renderer, this.voiceHostDisposals);
51819
+ replacement.renderer.close();
51820
+ throw new Error("Renderer CDP Control Session is closed");
51821
+ }
51822
+ this.disposeModules();
51823
+ unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
51824
+ this.renderer.close();
51825
+ this.renderer = replacement.renderer;
51826
+ this.disposeModules = replacement.disposeModules;
51827
+ this.currentSnapshot = replacement.snapshot;
51828
+ }
51829
+ #assertOpen() {
51632
51830
  if (this.#closed)
51633
51831
  throw new Error("Renderer CDP Control Session is closed");
51832
+ }
51833
+ #runWhileOpen(operation) {
51834
+ return runWithCdpSignal(this.#shutdown.signal, "Renderer CDP Control Session is closed", operation);
51835
+ }
51836
+ async attachVoiceHost(voiceHost) {
51837
+ this.#assertOpen();
51838
+ if (this.voiceHost)
51839
+ return;
51840
+ this.#lateVoiceAttach ??= this.#reconcileVoiceHost(voiceHost).finally(() => {
51841
+ this.#lateVoiceAttach = void 0;
51842
+ });
51843
+ return this.#lateVoiceAttach;
51844
+ }
51845
+ async #reconcileVoiceHost(voiceHost) {
51846
+ const timeoutMs = Math.min(this.timeoutMs, VOICE_HOST_ATTACH_TIMEOUT_MS);
51847
+ if (this.#lateVoiceHost !== void 0 && this.#lateVoiceHost !== voiceHost)
51848
+ this.#disposeLateVoiceBindings();
51849
+ const primaryTarget = this.currentSnapshot.target;
51850
+ if (this.#lateVoicePrimaryId !== void 0 && this.#lateVoicePrimaryId !== primaryTarget.id)
51851
+ this.#disposeLateVoiceBinding(this.#lateVoicePrimaryId);
51852
+ const existingPrimary = this.#lateVoiceBindings.get(primaryTarget.id);
51853
+ if (existingPrimary && !await lateVoiceBindingIsLive(existingPrimary, this.#shutdown.signal))
51854
+ this.#disposeLateVoiceBinding(primaryTarget.id);
51855
+ this.#assertOpen();
51856
+ if (!this.#lateVoiceBindings.has(primaryTarget.id)) {
51857
+ this.#disposeLateVoiceBinding(primaryTarget.id);
51858
+ const binding = await bindVoiceHostOnNewConnection(primaryTarget, voiceHost, this.operations, timeoutMs, this.#shutdown.signal);
51859
+ if (this.#closed) {
51860
+ binding.dispose();
51861
+ binding.client.close();
51862
+ throw new Error("Renderer CDP Control Session is closed");
51863
+ }
51864
+ this.#lateVoiceBindings.set(binding.targetId, binding);
51865
+ }
51866
+ this.#lateVoicePrimaryId = primaryTarget.id;
51867
+ this.#lateVoiceHost = voiceHost;
51868
+ await this.#reconcileOverlayVoiceHost(voiceHost, timeoutMs);
51869
+ this.#assertOpen();
51870
+ }
51871
+ async #reconcileOverlayVoiceHost(voiceHost, timeoutMs) {
51872
+ if (this.#closed || !this.overlayHookSource)
51873
+ return;
51874
+ const deadline = AbortSignal.any([AbortSignal.timeout(timeoutMs), this.#shutdown.signal]);
51875
+ let targets;
51876
+ try {
51877
+ targets = await awaitWithSignal(this.operations.listTargets(this.rendererCdpEndpoint, deadline), deadline, "Late overlay CDP target discovery timed out");
51878
+ } catch {
51879
+ return;
51880
+ }
51881
+ const overlays = selectAvatarOverlayRendererTargets(targets);
51882
+ const live = new Set(overlays.map((target2) => target2.id));
51883
+ for (const id2 of [...this.#lateVoiceBindings.keys()])
51884
+ if (id2 !== this.#lateVoicePrimaryId && !live.has(id2))
51885
+ this.#disposeLateVoiceBinding(id2);
51886
+ for (const id2 of [...this.#overlayVoiceRetryAt.keys()])
51887
+ if (!live.has(id2))
51888
+ this.#overlayVoiceRetryAt.delete(id2);
51889
+ await Promise.allSettled(overlays.map(async (target2) => {
51890
+ if (this.#closed)
51891
+ return;
51892
+ const existing = this.#lateVoiceBindings.get(target2.id);
51893
+ if (existing) {
51894
+ if (await lateVoiceBindingIsLive(existing, this.#shutdown.signal))
51895
+ return;
51896
+ if (this.#closed)
51897
+ return;
51898
+ this.#disposeLateVoiceBinding(target2.id);
51899
+ }
51900
+ if ((this.#overlayVoiceRetryAt.get(target2.id) ?? 0) > Date.now())
51901
+ return;
51902
+ try {
51903
+ const binding = await bindVoiceHostOnNewConnection(target2, voiceHost, this.operations, timeoutMs, this.#shutdown.signal);
51904
+ if (this.#closed) {
51905
+ binding.dispose();
51906
+ binding.client.close();
51907
+ return;
51908
+ }
51909
+ this.#lateVoiceBindings.set(binding.targetId, binding);
51910
+ this.#overlayVoiceRetryAt.delete(binding.targetId);
51911
+ } catch {
51912
+ this.#overlayVoiceRetryAt.set(target2.id, Date.now() + VOICE_HOST_OVERLAY_RETRY_MS);
51913
+ }
51914
+ }));
51915
+ }
51916
+ #disposeLateVoiceBinding(targetId) {
51917
+ const binding = this.#lateVoiceBindings.get(targetId);
51918
+ if (!binding)
51919
+ return;
51920
+ binding.dispose();
51921
+ binding.client.close();
51922
+ this.#lateVoiceBindings.delete(targetId);
51923
+ if (this.#lateVoicePrimaryId === targetId)
51924
+ this.#lateVoicePrimaryId = void 0;
51925
+ this.#overlayVoiceRetryAt.delete(targetId);
51926
+ }
51927
+ #disposeLateVoiceBindings() {
51928
+ for (const targetId of [...this.#lateVoiceBindings.keys()])
51929
+ this.#disposeLateVoiceBinding(targetId);
51930
+ }
51931
+ async activateDesktop() {
51932
+ this.#assertOpen();
51634
51933
  await this.renderer.command("Page.bringToFront");
51635
51934
  return 1;
51636
51935
  }
@@ -51643,6 +51942,7 @@ var InstalledRendererCdpControlSession = class {
51643
51942
  if (this.#closed)
51644
51943
  return;
51645
51944
  this.#closed = true;
51945
+ this.#shutdown.abort(new Error("Renderer CDP Control Session is closed"));
51646
51946
  this.disposeModules();
51647
51947
  unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
51648
51948
  this.renderer.close();
@@ -51657,6 +51957,7 @@ var InstalledRendererCdpControlSession = class {
51657
51957
  for (const dispose of this.voiceHostDisposals.values())
51658
51958
  dispose();
51659
51959
  this.voiceHostDisposals.clear();
51960
+ this.#disposeLateVoiceBindings();
51660
51961
  }
51661
51962
  };
51662
51963
  var defaultOperations = {
@@ -51676,11 +51977,11 @@ async function createRendererCdpControlSession(options) {
51676
51977
  const operations2 = options.operations ?? defaultOperations;
51677
51978
  const target2 = await waitForPrimaryTarget(options.rendererCdpEndpoint, operations2, timeoutMs, pollIntervalMs, void 0, options.signal);
51678
51979
  const voiceHostDisposals = /* @__PURE__ */ new Map();
51679
- const installed = await installTarget(target2, options.rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations2, options.voiceHost, voiceHostDisposals);
51980
+ const installed = await installTarget(target2, options.rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations2, options.voiceHost, voiceHostDisposals, options.signal, options.waitForDocumentLoad);
51680
51981
  const browserStyleClients = /* @__PURE__ */ new Map();
51681
51982
  const overlayClients = /* @__PURE__ */ new Map();
51682
51983
  await installAuxiliaryRenderers(options.rendererCdpEndpoint, options.rendererSource, enabledAgents, options.overlayHookSource, options.overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations2, discoveryTimeoutSignal(timeoutMs, options.signal), options.voiceHost, voiceHostDisposals);
51683
- return new InstalledRendererCdpControlSession(installed.renderer, options.rendererCdpEndpoint, options.rendererSource, options.overlayHookSource, options.overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations2, installed.snapshot, installed.disposeModules, options.voiceHost, voiceHostDisposals);
51984
+ return new InstalledRendererCdpControlSession(installed.renderer, options.rendererCdpEndpoint, options.rendererSource, options.overlayHookSource, options.overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations2, installed.snapshot, installed.disposeModules, options.voiceHost, voiceHostDisposals, options.waitForDocumentLoad === true);
51684
51985
  }
51685
51986
  function installRendererCdpControlSession(options) {
51686
51987
  return createRendererCdpControlSession(options);
@@ -52163,29 +52464,67 @@ import { createHash as createHash10, randomUUID as randomUUID10 } from "node:cry
52163
52464
  // packages/host-runtime/src/external-voice-presentation.ts
52164
52465
  var INLINE_MARKDOWN = "::codex-realtime-inline{}\n";
52165
52466
  var inlineMarker = /^::codex-realtime-inline\{\}\r?\n/u;
52467
+ var delegationInput = /^<realtime_delegation>\n <input>([\s\S]*)<\/input>\n<\/realtime_delegation>$/u;
52468
+ function externalVoiceUserInputText(text4) {
52469
+ const captured = delegationInput.exec(text4)?.[1];
52470
+ return captured === void 0 ? text4 : captured.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
52471
+ }
52472
+ function presentUserInput(text4) {
52473
+ if (delegationInput.test(text4)) return text4;
52474
+ const escaped = text4.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
52475
+ return `<realtime_delegation>
52476
+ <input>${escaped}</input>
52477
+ </realtime_delegation>`;
52478
+ }
52166
52479
  function externalVoiceContentText(text4) {
52167
52480
  return text4.replace(inlineMarker, "");
52168
52481
  }
52169
52482
  function object5(value2) {
52170
52483
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
52171
52484
  }
52172
- function presentItem(item) {
52485
+ function presentItem(item, delegatedInput = false) {
52486
+ if (delegatedInput && object5(item) && item.type === "userMessage" && Array.isArray(item.content)) {
52487
+ return {
52488
+ ...item,
52489
+ codexhostNativeInput: item.codexhostNativeInput ?? item.content,
52490
+ content: item.content.map(
52491
+ (part) => object5(part) && part.type === "text" && typeof part.text === "string" ? { ...part, text: presentUserInput(part.text) } : part
52492
+ )
52493
+ };
52494
+ }
52173
52495
  if (!object5(item) || item.type !== "agentMessage" || typeof item.text !== "string") return item;
52174
52496
  if (!item.text.trim() || inlineMarker.test(item.text)) return item;
52175
52497
  return { ...item, text: INLINE_MARKDOWN + item.text };
52176
52498
  }
52177
- function presentExternalVoiceTurn(turn) {
52499
+ function presentExternalVoiceTurn(turn, realtimeDelegation = false) {
52178
52500
  if (!Array.isArray(turn.items)) return turn;
52179
- return { ...turn, items: turn.items.map(presentItem) };
52501
+ return {
52502
+ ...turn,
52503
+ items: turn.items.map(
52504
+ (item) => presentItem(item, realtimeDelegation && object5(item) && item.id === `${turn.id}-user`)
52505
+ )
52506
+ };
52180
52507
  }
52181
- function presentExternalVoiceMessage(message2) {
52508
+ function presentExternalVoiceMessage(message2, realtimeDelegation = false) {
52182
52509
  const params = message2.params;
52183
52510
  if (!object5(params)) return message2;
52184
52511
  if ((message2.method === "item/started" || message2.method === "item/completed") && params.item) {
52185
- return { ...message2, params: { ...params, item: presentItem(params.item) } };
52512
+ return {
52513
+ ...message2,
52514
+ params: {
52515
+ ...params,
52516
+ item: presentItem(
52517
+ params.item,
52518
+ realtimeDelegation && object5(params.item) && params.item.id === `${params.turnId}-user`
52519
+ )
52520
+ }
52521
+ };
52186
52522
  }
52187
52523
  if ((message2.method === "turn/started" || message2.method === "turn/completed") && object5(params.turn)) {
52188
- return { ...message2, params: { ...params, turn: presentExternalVoiceTurn(params.turn) } };
52524
+ return {
52525
+ ...message2,
52526
+ params: { ...params, turn: presentExternalVoiceTurn(params.turn, realtimeDelegation) }
52527
+ };
52189
52528
  }
52190
52529
  return message2;
52191
52530
  }
@@ -52340,7 +52679,9 @@ async function projectExternalSnapshot(store, record7, snapshot2, previousParent
52340
52679
  cwd: record7.cwd,
52341
52680
  snapshot: { ...turn, input: withoutInjectedText(turn.input, injected), items }
52342
52681
  });
52343
- turns.push(mapping.realtimeInline ? presentExternalVoiceTurn(projected) : projected);
52682
+ turns.push(
52683
+ mapping.realtimeInline || mapping.realtimeDelegation ? presentExternalVoiceTurn(projected, mapping.realtimeDelegation) : projected
52684
+ );
52344
52685
  }
52345
52686
  return turns;
52346
52687
  }
@@ -52473,7 +52814,7 @@ var ExternalThreadRepository = class {
52473
52814
  if (!record7.nativeSessionRef || !this.store.saveUsageMeasurements) return record7;
52474
52815
  return this.store.saveUsageMeasurements(record7.hostThreadId, record7.nativeSessionRef, values);
52475
52816
  }
52476
- async persistTurn(record7, hostTurnId, nativeTurnRef, nativeCheckpointRef, realtimeInline) {
52817
+ async persistTurn(record7, hostTurnId, nativeTurnRef, nativeCheckpointRef, realtimeInline, realtimeDelegation) {
52477
52818
  if (record7.state !== "ready" || !record7.nativeSessionRef || nativeTurnRef.harnessId !== record7.harnessId || nativeTurnRef.nativeSessionId !== record7.nativeSessionRef.nativeSessionId || nativeCheckpointRef && (nativeCheckpointRef.harnessId !== record7.harnessId || nativeCheckpointRef.nativeSessionId !== record7.nativeSessionRef.nativeSessionId)) {
52478
52819
  throw new Error("Live Turn identity does not belong to the stored Thread");
52479
52820
  }
@@ -52482,7 +52823,8 @@ var ExternalThreadRepository = class {
52482
52823
  hostTurnId,
52483
52824
  nativeTurnRef,
52484
52825
  ...nativeCheckpointRef ? { nativeCheckpointRef } : {},
52485
- ...realtimeInline ? { realtimeInline } : {}
52826
+ ...realtimeInline ? { realtimeInline } : {},
52827
+ ...realtimeDelegation ? { realtimeDelegation } : {}
52486
52828
  }
52487
52829
  ]);
52488
52830
  }
@@ -52529,6 +52871,7 @@ var ExternalThreadRepository = class {
52529
52871
  return {
52530
52872
  hostTurnId: previous.hostTurnId,
52531
52873
  ...previous.realtimeInline ? { realtimeInline: true } : {},
52874
+ ...previous.realtimeDelegation ? { realtimeDelegation: true } : {},
52532
52875
  nativeTurnRef: turn.nativeTurnRef,
52533
52876
  ...turn.checkpoint ? { nativeCheckpointRef: turn.checkpoint } : {}
52534
52877
  };
@@ -52561,6 +52904,7 @@ var ExternalThreadRepository = class {
52561
52904
  return {
52562
52905
  hostTurnId: previous.hostTurnId,
52563
52906
  ...previous.realtimeInline ? { realtimeInline: true } : {},
52907
+ ...previous.realtimeDelegation ? { realtimeDelegation: true } : {},
52564
52908
  nativeTurnRef: turn.nativeTurnRef,
52565
52909
  ...turn.checkpoint ? { nativeCheckpointRef: turn.checkpoint } : {}
52566
52910
  };
@@ -52620,6 +52964,7 @@ var ExternalThreadRepository = class {
52620
52964
  mapping: {
52621
52965
  hostTurnId: mapping.hostTurnId,
52622
52966
  ...mapping.realtimeInline ? { realtimeInline: true } : {},
52967
+ ...mapping.realtimeDelegation ? { realtimeDelegation: true } : {},
52623
52968
  nativeTurnRef: turn.nativeTurnRef,
52624
52969
  ...turn.checkpoint ? { nativeCheckpointRef: turn.checkpoint } : {}
52625
52970
  }
@@ -53771,7 +54116,9 @@ function isRecord15(value2) {
53771
54116
  }
53772
54117
  function userMessageText(item) {
53773
54118
  if (!Array.isArray(item.content)) return "";
53774
- return item.content.filter(isRecord15).map((part) => part.type === "text" && typeof part.text === "string" ? part.text.trim() : "").filter((text4) => text4.length > 0).join("\n");
54119
+ return item.content.filter(isRecord15).map(
54120
+ (part) => part.type === "text" && typeof part.text === "string" ? externalVoiceUserInputText(part.text).trim() : ""
54121
+ ).filter((text4) => text4.length > 0).join("\n");
53775
54122
  }
53776
54123
  function clip(text4) {
53777
54124
  return text4.length <= MAX_MESSAGE_CHARS ? text4 : text4.slice(0, MAX_MESSAGE_CHARS);
@@ -59559,7 +59906,8 @@ var ExternalThreadRuntime = class {
59559
59906
  event.turnId,
59560
59907
  event.nativeTurnRef,
59561
59908
  event.outcome.checkpoint,
59562
- thread3.projectedTurns.get(event.turnId)?.realtimeInline
59909
+ thread3.projectedTurns.get(event.turnId)?.realtimeInline,
59910
+ thread3.projectedTurns.get(event.turnId)?.realtimeDelegation
59563
59911
  );
59564
59912
  thread3.persistenceError = null;
59565
59913
  await this.persistUsageMeasurements(thread3);
@@ -69069,8 +69417,17 @@ var AppServerHost = class {
69069
69417
  this.#unregisterDelegationApi = typeof unregisterDelegationApi === "function" ? unregisterDelegationApi : void 0;
69070
69418
  this.#turnProjection = new ExternalTurnProjection({
69071
69419
  writeJson: (value2) => {
69072
- if (isRecord29(value2) && isRecord29(value2.params) && typeof value2.params.threadId === "string" && this.#externalVoice.has(value2.params.threadId)) {
69073
- return this.#writer.json(presentExternalVoiceMessage(value2));
69420
+ if (isRecord29(value2) && isRecord29(value2.params) && typeof value2.params.threadId === "string") {
69421
+ const threadId3 = value2.params.threadId;
69422
+ const thread3 = this.#externalRuntime.get(threadId3);
69423
+ const turnId = isRecord29(value2.params.turn) ? value2.params.turn.id : value2.params.turnId;
69424
+ const realtimeDelegation = typeof turnId === "string" && (thread3?.projectedTurns.get(turnId)?.realtimeDelegation === true || thread3?.record.turnMappings.some(
69425
+ (mapping) => mapping.hostTurnId === turnId && mapping.realtimeDelegation
69426
+ ) === true);
69427
+ if (realtimeDelegation || this.#externalVoice.has(threadId3))
69428
+ return this.#writer.json(
69429
+ presentExternalVoiceMessage(value2, realtimeDelegation)
69430
+ );
69074
69431
  }
69075
69432
  return this.#writer.json(value2);
69076
69433
  },
@@ -72552,7 +72909,9 @@ var AppServerHost = class {
72552
72909
  if (!thread3.activeTurnId || forClient2 && thread3.ephemeralTurnIds.has(thread3.activeTurnId))
72553
72910
  return turns;
72554
72911
  const active2 = thread3.projectedTurns.get(thread3.activeTurnId);
72555
- return active2 ? [...turns, forClient2 ? active2.projector.snapshotTurn() : active2.projector.pendingTurn()] : turns;
72912
+ if (!active2) return turns;
72913
+ const turn = forClient2 ? active2.projector.snapshotTurn() : active2.projector.pendingTurn();
72914
+ return [...turns, active2.realtimeDelegation ? presentExternalVoiceTurn(turn, true) : turn];
72556
72915
  }
72557
72916
  /**
72558
72917
  * Background commands whose native task has not settled overlay their live
@@ -72668,7 +73027,8 @@ var AppServerHost = class {
72668
73027
  if (signal.aborted) throw new Error("Voice session ended");
72669
73028
  const thread3 = this.#externalRuntime.get(threadId3);
72670
73029
  if (!thread3 || this.#closeRequested) throw new Error("External chat is unavailable");
72671
- const started = await this.#beginExternalInputTurn(thread3, text4);
73030
+ const started = await this.#beginExternalInputTurn(thread3, text4, void 0, void 0, true);
73031
+ projectedTurn(thread3, started.turnId).realtimeDelegation = true;
72672
73032
  answer = this.#externalVoiceResults.watch(threadId3, started.turnId, signal);
72673
73033
  void answer.catch(() => void 0);
72674
73034
  started.gate.resolve();
@@ -73589,11 +73949,12 @@ var AppServerHost = class {
73589
73949
  this.#followExternalVoiceTurn(thread3.id, event.turnId);
73590
73950
  }
73591
73951
  const ephemeralTurn = event.type === "turn.completed" && (event.ephemeral === true || thread3.ephemeralTurnIds.has(event.turnId));
73952
+ const realtimeDelegation = thread3.projectedTurns.get(event.turnId)?.realtimeDelegation;
73592
73953
  await this.#turnProjection.project(thread3, event);
73593
- if (event.type === "turn.completed" && this.#externalVoice.has(thread3.id) && !ephemeralTurn) {
73954
+ if (event.type === "turn.completed" && (realtimeDelegation || this.#externalVoice.has(thread3.id)) && !ephemeralTurn) {
73594
73955
  const last = thread3.turns.at(-1);
73595
73956
  if (last && isRecord29(last)) {
73596
- thread3.turns[thread3.turns.length - 1] = presentExternalVoiceTurn(last);
73957
+ thread3.turns[thread3.turns.length - 1] = presentExternalVoiceTurn(last, realtimeDelegation);
73597
73958
  }
73598
73959
  }
73599
73960
  this.#externalVoiceResults.observe(