@karlorz/codexhost-cli-win32-x64 0.18.0-0 → 0.19.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +317 -59
  4. package/app/console-web.js +1889 -141
  5. package/app/cpa-live-voice-hook.js +1938 -428
  6. package/app/desktop-controller.mjs +2081 -212
  7. package/app/host-runtime.mjs +14818 -3381
  8. package/app/overlay-voice-bootstrap.js +1616 -0
  9. package/app/plugins/antigravity/plugin.mjs +963 -324
  10. package/app/plugins/claude-code/plugin.mjs +395 -67
  11. package/app/plugins/codebuddy/plugin.mjs +409 -76
  12. package/app/plugins/codex-usage/plugin.mjs +316 -58
  13. package/app/plugins/copilot/plugin.mjs +316 -58
  14. package/app/plugins/cursor-cli/plugin.mjs +391 -68
  15. package/app/plugins/deepseek-harness/manifest.json +2 -2
  16. package/app/plugins/deepseek-harness/plugin.mjs +343 -63
  17. package/app/plugins/devin/plugin.mjs +316 -58
  18. package/app/plugins/grok/plugin.mjs +1350 -1026
  19. package/app/plugins/hermes/plugin.mjs +395 -70
  20. package/app/plugins/kimi-code/plugin.mjs +316 -58
  21. package/app/plugins/kiro-cli/plugin.mjs +544 -74
  22. package/app/plugins/omp/plugin.mjs +1264 -902
  23. package/app/plugins/opencode/plugin.mjs +316 -58
  24. package/app/plugins/pi/plugin.mjs +1189 -862
  25. package/app/plugins/qoder/plugin.mjs +318 -62
  26. package/app/plugins/qoder-cn/plugin.mjs +318 -62
  27. package/app/plugins/qwen-code/plugin.mjs +425 -150
  28. package/app/plugins/workbuddy/plugin.mjs +409 -76
  29. package/app/plugins/zcode/plugin.mjs +389 -61
  30. package/app/renderer-extension.js +11830 -8531
  31. package/app/voice-profile-pins.json +25 -0
  32. package/app/voice-qualification.json +4 -0
  33. package/app/web/assets/index-BCyiiDDL.js +199 -0
  34. package/app/web/assets/index-BNQIOOHE.css +1 -0
  35. package/app/web/codexhost-settings.js +1895 -190
  36. package/app/web/index.html +2 -2
  37. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  38. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  39. package/app/web/plugins/deepseek-ai__dsh-client-file-upload/client.js +1 -1
  40. package/app/web/plugins/deepseek-ai__dsh-client-locale/client.js +3 -3
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +129 -8
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +65 -63
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +95 -93
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +1 -1
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  49. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.excel.js +1 -1
  50. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-files/client.js +1 -1
  51. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +79 -79
  52. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
  53. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +11 -11
  54. package/app/web-modules/server.mjs +3279 -1676
  55. package/bin/codexhost.exe +0 -0
  56. package/libexec/codexhost-node-repl.exe +0 -0
  57. package/libexec/codexhost-shim.exe +0 -0
  58. package/libexec/codexhost-updater.exe +0 -0
  59. package/package.json +1 -1
  60. package/app/web/assets/index-Bs17Kuah.js +0 -199
  61. package/app/web/assets/index-C3lniEH1.css +0 -1
@@ -6,7 +6,7 @@ var __export = (target2, all) => {
6
6
 
7
7
  // packages/desktop-control/src/production-controller.ts
8
8
  import { readFile } from "node:fs/promises";
9
- import path4 from "node:path";
9
+ import path6 from "node:path";
10
10
 
11
11
  // packages/desktop-control/src/renderer-local-page.ts
12
12
  import { randomUUID } from "node:crypto";
@@ -217,8 +217,7 @@ var CdpClient = class _CdpClient {
217
217
  const id = this.#nextId++;
218
218
  return new Promise((resolve, reject) => {
219
219
  const timeout = setTimeout(() => {
220
- this.#pending.delete(id);
221
- reject(new Error(`CDP command '${method}' timed out`));
220
+ this.#disconnect(new CdpConnectionClosedError(`CDP command '${method}' timed out`));
222
221
  }, this.#commandTimeoutMs);
223
222
  this.#pending.set(id, { resolve, reject, timeout });
224
223
  try {
@@ -327,15 +326,58 @@ async function rendererRemoteSession(target2, operation) {
327
326
  return ids.map((hostId2) => ({ hostId: hostId2, online: !!routing.forHost(hostId2) }));
328
327
  const configured = await api.remoteConnections({ action: "catalog" });
329
328
  const connections = Array.isArray(configured) ? configured : [];
330
- const attempts = state.reconnectAttempts ??= /* @__PURE__ */ new Set();
329
+ const previous = state.reconnectAttempts;
330
+ const attempts = state.reconnectAttempts = previous && !("get" in previous) ? new Map([...previous].map((id) => [id, { failures: 0, retryAt: Infinity }])) : previous ?? /* @__PURE__ */ new Map();
331
331
  return Promise.all(
332
332
  [.../* @__PURE__ */ new Set([...ids, ...connections.map((c) => c.hostId)])].map(async (hostId2) => {
333
333
  const connection = connections.find((c) => c.hostId === hostId2);
334
334
  let status = await api.remoteConnections({ action: "state", hostId: hostId2 }).catch(() => ({ state: "error" }));
335
- if (connection?.autoConnect === false) attempts.delete(hostId2);
336
- if (connection?.autoConnect && status.state === "disconnected" && !attempts.has(hostId2)) {
337
- attempts.add(hostId2);
338
- await api.remoteConnections({ action: "connect", hostId: hostId2, enabled: true }).catch(() => void 0);
335
+ if (connection?.autoConnect === false || status.state === "connected")
336
+ attempts.delete(hostId2);
337
+ if (connection?.autoConnect && status.state === "disconnected") {
338
+ let attempt = attempts.get(hostId2);
339
+ if (!attempt || !attempt.loading && Date.now() >= attempt.retryAt) {
340
+ attempt ??= { failures: 0, retryAt: Infinity };
341
+ const current = attempt;
342
+ current.retryAt = Infinity;
343
+ attempts.set(hostId2, current);
344
+ current.loading = Promise.resolve().then(async () => {
345
+ try {
346
+ const latestStatus = await api.remoteConnections({ action: "state", hostId: hostId2 });
347
+ const latest = await api.remoteConnections({ action: "catalog" });
348
+ if (attempts.get(hostId2) !== current || !Array.isArray(latest) || !latest.some((c) => c.hostId === hostId2 && c.autoConnect === true) || latestStatus.state !== "disconnected") {
349
+ if (attempts.get(hostId2) === current) attempts.delete(hostId2);
350
+ return;
351
+ }
352
+ let acknowledged = false;
353
+ let failureCode;
354
+ try {
355
+ await api.remoteConnections({ action: "connect", hostId: hostId2, enabled: true });
356
+ acknowledged = true;
357
+ } catch (error51) {
358
+ failureCode = error51?.code;
359
+ }
360
+ const result = await api.remoteConnections({ action: "state", hostId: hostId2 });
361
+ const failed = acknowledged || [
362
+ "ECONNREFUSED",
363
+ "ECONNRESET",
364
+ "ENETUNREACH",
365
+ "EHOSTUNREACH",
366
+ "ENOTFOUND",
367
+ "EAI_AGAIN"
368
+ ].includes(String(failureCode));
369
+ if (failed && result.state === "disconnected" && result.error) {
370
+ current.failures = Math.min(current.failures + 1, 4);
371
+ current.retryAt = Date.now() + Math.min(3e4, 5e3 * 2 ** (current.failures - 1));
372
+ }
373
+ } catch {
374
+ } finally {
375
+ delete current.loading;
376
+ }
377
+ });
378
+ attempt = current;
379
+ }
380
+ await attempt.loading;
339
381
  status = await api.remoteConnections({ action: "state", hostId: hostId2 }).catch(() => ({ state: "error" }));
340
382
  }
341
383
  return {
@@ -373,12 +415,128 @@ async function rendererRemoteSession(target2, operation) {
373
415
  return Array.isArray(conversation?.requests) ? conversation.requests : [];
374
416
  };
375
417
  if (operation.kind === "read") {
376
- const result = await manager.sendRequest("thread/read", { threadId, includeTurns: true });
418
+ let result = await manager.sendRequest("thread/read", { threadId, includeTurns: false });
419
+ if (routing.forHost(operation.hostId) !== route)
420
+ throw new Error("Remote connection changed during read");
421
+ const header = result;
422
+ if (header.thread?.historyMode === "paginated") {
423
+ const turns = [], cursors = /* @__PURE__ */ new Set();
424
+ let cursor = null, bytes = 0, complete = false;
425
+ for (let page = 0; page < 100; page++) {
426
+ if (routing.forHost(operation.hostId) !== route)
427
+ throw new Error("Remote connection changed during read");
428
+ const response = await manager.sendRequest("thread/turns/list", {
429
+ threadId,
430
+ cursor,
431
+ limit: 50,
432
+ sortDirection: "asc",
433
+ itemsView: "full"
434
+ });
435
+ if (!Array.isArray(response.data) || response.nextCursor !== null && typeof response.nextCursor !== "string")
436
+ throw new Error("Invalid remote history page");
437
+ bytes += new TextEncoder().encode(JSON.stringify(response.data)).byteLength;
438
+ if (bytes > 14 * 1024 * 1024) throw new Error("Remote history exceeds the snapshot limit");
439
+ turns.push(...response.data);
440
+ cursor = response.nextCursor;
441
+ if (cursor === null) {
442
+ complete = true;
443
+ break;
444
+ }
445
+ if (cursors.has(cursor)) throw new Error("Remote history cursor repeated");
446
+ cursors.add(cursor);
447
+ }
448
+ if (!complete) throw new Error("Remote history exceeds the page limit");
449
+ result = { ...result, thread: { ...header.thread, turns } };
450
+ } else result = await manager.sendRequest("thread/read", { threadId, includeTurns: true });
451
+ if (routing.forHost(operation.hostId) !== route)
452
+ throw new Error("Remote connection changed during read");
453
+ let metadata = {};
454
+ if (header.thread) {
455
+ const cwd = header.thread.cwd;
456
+ try {
457
+ const configuration = await manager.sendRequest("codexhost/thread/inspect", {
458
+ threadId
459
+ });
460
+ if (routing.forHost(operation.hostId) !== route)
461
+ throw new Error("Remote connection changed during read");
462
+ metadata = {
463
+ configuration,
464
+ ...configuration.owner === "codex" ? {
465
+ nativeSettings: {
466
+ model: header.thread.model,
467
+ reasoningEffort: header.thread.reasoningEffort,
468
+ serviceTier: header.thread.serviceTier
469
+ }
470
+ } : {}
471
+ };
472
+ if (configuration.owner === "codex" && manager.getConversation) {
473
+ const conversation = await Promise.resolve().then(() => manager.getConversation?.(threadId)).catch(() => void 0);
474
+ if (routing.forHost(operation.hostId) !== route)
475
+ throw new Error("Remote connection changed during read");
476
+ const settings = conversation?.latestThreadSettings;
477
+ if (settings?.model === header.thread.model && typeof settings?.model === "string")
478
+ metadata.nativeSettings = {
479
+ model: settings.model,
480
+ reasoningEffort: header.thread.reasoningEffort === void 0 ? settings.effort : header.thread.reasoningEffort,
481
+ serviceTier: header.thread.serviceTier === void 0 ? settings.serviceTier : header.thread.serviceTier
482
+ };
483
+ }
484
+ if (configuration.owner === "codex" || configuration.owner === "external" && configuration.harnessId) {
485
+ const harnessId = configuration.owner === "codex" ? "codex" : configuration.harnessId ?? "codex", key = JSON.stringify([harnessId, cwd]);
486
+ const cache = generation.metadata ??= /* @__PURE__ */ new Map();
487
+ let discovery = cache.get(key);
488
+ if (!discovery || Date.now() >= discovery.retryAt) {
489
+ const loading = Promise.all([
490
+ Promise.resolve().then(() => {
491
+ if (routing.forHost(operation.hostId) !== route)
492
+ throw new Error("Remote connection changed during read");
493
+ return manager.sendRequest("codexhost/harness/inspect", {
494
+ harnessId,
495
+ ...cwd ? { cwd } : {}
496
+ });
497
+ }),
498
+ Promise.resolve().then(() => {
499
+ if (routing.forHost(operation.hostId) !== route)
500
+ throw new Error("Remote connection changed during read");
501
+ return manager.sendRequest("codexhost/harness/plugins/list", {});
502
+ }).catch(() => null)
503
+ ]).then(([inspection, catalog]) => {
504
+ if (inspection?.status !== "ready")
505
+ throw new Error("Remote Harness discovery is unavailable");
506
+ return {
507
+ inspection,
508
+ harness: catalog?.plugins?.find(
509
+ (p) => p.id === harnessId
510
+ )
511
+ };
512
+ });
513
+ const attempt = {
514
+ loading,
515
+ failures: discovery?.failures ?? 0,
516
+ retryAt: Infinity
517
+ };
518
+ void loading.catch(() => {
519
+ attempt.failures = Math.min(attempt.failures + 1, 4);
520
+ attempt.retryAt = Date.now() + Math.min(3e4, 5e3 * 2 ** (attempt.failures - 1));
521
+ });
522
+ discovery = attempt;
523
+ if (cache.size >= 64 && !cache.has(key)) {
524
+ const oldest = cache.keys().next().value;
525
+ if (oldest !== void 0) cache.delete(oldest);
526
+ }
527
+ cache.set(key, discovery);
528
+ }
529
+ metadata = { ...metadata, ...await discovery.loading };
530
+ }
531
+ } catch {
532
+ }
533
+ }
377
534
  if (routing.forHost(operation.hostId) !== route)
378
535
  throw new Error("Remote connection changed during read");
379
536
  const requests = await pendingRequests();
380
537
  return {
381
538
  result,
539
+ ...metadata,
382
540
  epoch: generation.epoch,
383
541
  interactionsAvailable: !!manager.getConversation && !!manager.replyWithCommandExecutionApprovalDecision && !!manager.replyWithFileChangeApprovalDecision,
384
542
  requests: requests.filter(
@@ -403,6 +561,34 @@ async function rendererRemoteSession(target2, operation) {
403
561
  return { accepted: true };
404
562
  }
405
563
  switch (operation.kind) {
564
+ case "configure": {
565
+ const configuration = await manager.sendRequest("codexhost/thread/inspect", {
566
+ threadId
567
+ });
568
+ if (routing.forHost(operation.hostId) !== route)
569
+ throw new Error("Remote connection changed during configuration");
570
+ if (configuration.owner !== "external" && configuration.owner !== "codex")
571
+ throw new Error("Remote Thread configuration is unavailable");
572
+ let method, params;
573
+ if (operation.modelId !== void 0) {
574
+ method = "codexhost/thread/model/select";
575
+ params = { threadId, model: { id: operation.modelId } };
576
+ } else if (operation.thinkingOptionId !== void 0) {
577
+ method = "codexhost/thread/thinking/select";
578
+ params = { threadId, thinkingOptionId: operation.thinkingOptionId };
579
+ } else {
580
+ method = "codexhost/thread/permission-mode/select";
581
+ params = { threadId, permissionModeId: operation.permissionModeId };
582
+ }
583
+ try {
584
+ const result = await manager.sendRequest(method, params);
585
+ if (routing.forHost(operation.hostId) !== route)
586
+ throw new Error("Remote connection changed during configuration");
587
+ return result;
588
+ } finally {
589
+ generation.metadata?.clear();
590
+ }
591
+ }
406
592
  case "prompt":
407
593
  await manager.sendRequest("thread/resume", { threadId });
408
594
  if (routing.forHost(operation.hostId) !== route)
@@ -1189,10 +1375,10 @@ function mergeDefs(...defs) {
1189
1375
  function cloneDef(schema) {
1190
1376
  return mergeDefs(schema._zod.def);
1191
1377
  }
1192
- function getElementAtPath(obj, path5) {
1193
- if (!path5)
1378
+ function getElementAtPath(obj, path7) {
1379
+ if (!path7)
1194
1380
  return obj;
1195
- return path5.reduce((acc, key) => acc?.[key], obj);
1381
+ return path7.reduce((acc, key) => acc?.[key], obj);
1196
1382
  }
1197
1383
  function promiseAllObject(promisesObj) {
1198
1384
  const keys = Object.keys(promisesObj);
@@ -1601,11 +1787,11 @@ function explicitlyAborted(x, startIndex = 0) {
1601
1787
  }
1602
1788
  return false;
1603
1789
  }
1604
- function prefixIssues(path5, issues) {
1790
+ function prefixIssues(path7, issues) {
1605
1791
  return issues.map((iss) => {
1606
1792
  var _a3;
1607
1793
  (_a3 = iss).path ?? (_a3.path = []);
1608
- iss.path.unshift(path5);
1794
+ iss.path.unshift(path7);
1609
1795
  return iss;
1610
1796
  });
1611
1797
  }
@@ -1752,16 +1938,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1752
1938
  }
1753
1939
  function formatError(error51, mapper = (issue2) => issue2.message) {
1754
1940
  const fieldErrors = { _errors: [] };
1755
- const processError = (error52, path5 = []) => {
1941
+ const processError = (error52, path7 = []) => {
1756
1942
  for (const issue2 of error52.issues) {
1757
1943
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1758
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
1944
+ issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1759
1945
  } else if (issue2.code === "invalid_key") {
1760
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1946
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1761
1947
  } else if (issue2.code === "invalid_element") {
1762
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1948
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1763
1949
  } else {
1764
- const fullpath = [...path5, ...issue2.path];
1950
+ const fullpath = [...path7, ...issue2.path];
1765
1951
  if (fullpath.length === 0) {
1766
1952
  fieldErrors._errors.push(mapper(issue2));
1767
1953
  } else {
@@ -1788,17 +1974,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1788
1974
  }
1789
1975
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1790
1976
  const result = { errors: [] };
1791
- const processError = (error52, path5 = []) => {
1977
+ const processError = (error52, path7 = []) => {
1792
1978
  var _a3, _b;
1793
1979
  for (const issue2 of error52.issues) {
1794
1980
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1795
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
1981
+ issue2.errors.map((issues) => processError({ issues }, [...path7, ...issue2.path]));
1796
1982
  } else if (issue2.code === "invalid_key") {
1797
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1983
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1798
1984
  } else if (issue2.code === "invalid_element") {
1799
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
1985
+ processError({ issues: issue2.issues }, [...path7, ...issue2.path]);
1800
1986
  } else {
1801
- const fullpath = [...path5, ...issue2.path];
1987
+ const fullpath = [...path7, ...issue2.path];
1802
1988
  if (fullpath.length === 0) {
1803
1989
  result.errors.push(mapper(issue2));
1804
1990
  continue;
@@ -1830,8 +2016,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1830
2016
  }
1831
2017
  function toDotPath(_path) {
1832
2018
  const segs = [];
1833
- const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1834
- for (const seg of path5) {
2019
+ const path7 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
2020
+ for (const seg of path7) {
1835
2021
  if (typeof seg === "number")
1836
2022
  segs.push(`[${seg}]`);
1837
2023
  else if (typeof seg === "symbol")
@@ -14523,13 +14709,13 @@ function resolveRef(ref, ctx) {
14523
14709
  if (!ref.startsWith("#")) {
14524
14710
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14525
14711
  }
14526
- const path5 = ref.slice(1).split("/").filter(Boolean);
14527
- if (path5.length === 0) {
14712
+ const path7 = ref.slice(1).split("/").filter(Boolean);
14713
+ if (path7.length === 0) {
14528
14714
  return ctx.rootSchema;
14529
14715
  }
14530
14716
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14531
- if (path5[0] === defsKey) {
14532
- const key = path5[1];
14717
+ if (path7[0] === defsKey) {
14718
+ const key = path7[1];
14533
14719
  if (!key || !ctx.defs[key]) {
14534
14720
  throw new Error(`Reference not found: ${ref}`);
14535
14721
  }
@@ -14964,7 +15150,8 @@ var harnessGoalSetSchema = external_exports.object({
14964
15150
  origin: goalOriginSchema
14965
15151
  });
14966
15152
 
14967
- // packages/shared-contracts/dist/realtime-call.js
15153
+ // packages/shared-contracts/dist/realtime-call-core.js
15154
+ var REALTIME_CALL_METHOD = "codexhost/realtime/call";
14968
15155
  var REALTIME_CALL_FORWARDED_HEADERS = [
14969
15156
  "openai-alpha",
14970
15157
  "thread-id",
@@ -14973,7 +15160,18 @@ var REALTIME_CALL_FORWARDED_HEADERS = [
14973
15160
  "x-codex-turn-metadata"
14974
15161
  ];
14975
15162
  var FORWARDED_HEADERS = new Set(REALTIME_CALL_FORWARDED_HEADERS);
14976
- var REALTIME_CALL_ID_PATTERN = /^rtc_[A-Za-z0-9_-]{1,128}$/u;
15163
+ var REALTIME_CALL_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
15164
+ function isRealtimeCallId(value) {
15165
+ return typeof value === "string" && REALTIME_CALL_ID_PATTERN.test(value);
15166
+ }
15167
+ function realtimeCallIdFromLocation(location) {
15168
+ const path7 = location.split(/[?#]/u)[0] ?? "";
15169
+ if (/^[A-Za-z0-9_-]{1,128}$/u.test(path7))
15170
+ return path7;
15171
+ return /\/(?:calls|live)\/([A-Za-z0-9_-]{1,128})$/u.exec(path7)?.[1];
15172
+ }
15173
+
15174
+ // packages/shared-contracts/dist/realtime-call.js
14977
15175
  var requestId = external_exports.string().min(1).max(128);
14978
15176
  var realtimeCallParamsSchema = external_exports.discriminatedUnion("operation", [
14979
15177
  external_exports.object({
@@ -15028,12 +15226,6 @@ var RELAY_PUBLIC_ORIGIN = "https://codexhost.karldigi.dev";
15028
15226
  var RELAY_PUBLIC_RESOURCE = `${RELAY_PUBLIC_ORIGIN}/mcp`;
15029
15227
  var RELAY_WAIT_TIMEOUT_MAX_MS = 25e3;
15030
15228
  var RELAY_MAX_BODY_BYTES = 2 * 1024 * 1024;
15031
- var RELAY_ALLOWED_ROUTES = [
15032
- "/v1/enroll/status",
15033
- "/v1/thread/read",
15034
- "/v1/thread/wait",
15035
- "/v1/thread/send"
15036
- ];
15037
15229
  var relayLinkHelloSchema = external_exports.strictObject({
15038
15230
  v: external_exports.literal(RELAY_LINK_PROTOCOL_VERSION),
15039
15231
  secret: external_exports.string().min(1).max(4096)
@@ -15045,8 +15237,11 @@ var relayLinkHelloAckSchema = external_exports.strictObject({
15045
15237
  var relayLinkRequestSchema = external_exports.strictObject({
15046
15238
  requestId: external_exports.string().min(1).max(128),
15047
15239
  deadlineMs: external_exports.number().int().positive(),
15048
- route: external_exports.enum(RELAY_ALLOWED_ROUTES),
15049
- body: external_exports.record(external_exports.string(), external_exports.unknown())
15240
+ route: external_exports.string().min(1).max(128),
15241
+ body: external_exports.record(external_exports.string(), external_exports.unknown()),
15242
+ operationalClient: external_exports.string().min(1).max(64).optional(),
15243
+ oauthClientId: external_exports.string().min(1).max(128).optional(),
15244
+ dispatchGrant: external_exports.enum(["legacy-four", "full-dispatch"]).optional()
15050
15245
  });
15051
15246
  var relayLinkErrorSchema = external_exports.strictObject({
15052
15247
  code: external_exports.string().min(1).max(64),
@@ -15090,6 +15285,204 @@ var relayEnrollStatusResultSchema = external_exports.strictObject({
15090
15285
  runtime: external_exports.enum(["reachable", "unreachable"])
15091
15286
  });
15092
15287
 
15288
+ // packages/shared-contracts/dist/external-clients.js
15289
+ var EXTERNAL_CLIENT_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u;
15290
+ var externalClientNameSchema = external_exports.string().trim().min(1).max(64).regex(EXTERNAL_CLIENT_NAME_PATTERN);
15291
+ var externalClientAccessSchema = external_exports.enum(["all-threads", "selected-workspaces"]);
15292
+ var externalClientConnectionModeSchema = external_exports.enum(["public-relay", "local", "direct"]);
15293
+ var externalClientDispatchGrantSchema = external_exports.enum(["legacy-four", "full-dispatch"]);
15294
+ var workspacePathSchema = external_exports.string().trim().min(1).max(4096);
15295
+ var directUrlSchema = external_exports.string().trim().max(2048);
15296
+ var externalClientPublicViewSchema = external_exports.strictObject({
15297
+ name: externalClientNameSchema,
15298
+ createdAt: external_exports.string().min(1).max(64),
15299
+ access: externalClientAccessSchema,
15300
+ workspaces: external_exports.array(workspacePathSchema).max(64),
15301
+ connectionMode: externalClientConnectionModeSchema,
15302
+ dispatchGrant: externalClientDispatchGrantSchema,
15303
+ oauthClientId: external_exports.string().trim().min(1).max(128).optional(),
15304
+ directUrl: directUrlSchema.optional(),
15305
+ mcpUrl: external_exports.string().min(1).max(2048).optional(),
15306
+ mcpUrlNote: external_exports.string().min(1).max(512).optional()
15307
+ });
15308
+ var externalClientListParamsSchema = external_exports.strictObject({});
15309
+ var externalClientListResultSchema = external_exports.strictObject({
15310
+ clients: external_exports.array(externalClientPublicViewSchema).max(256)
15311
+ });
15312
+ var externalClientWriteFieldsSchema = external_exports.strictObject({
15313
+ access: externalClientAccessSchema.optional(),
15314
+ workspaces: external_exports.array(workspacePathSchema).max(64).optional(),
15315
+ connectionMode: externalClientConnectionModeSchema.optional(),
15316
+ dispatchGrant: externalClientDispatchGrantSchema.optional(),
15317
+ oauthClientId: external_exports.string().trim().min(1).max(128).optional(),
15318
+ directUrl: directUrlSchema.optional()
15319
+ });
15320
+ var externalClientCreateParamsSchema = externalClientWriteFieldsSchema.extend({
15321
+ name: externalClientNameSchema
15322
+ });
15323
+ var externalClientCreateResultSchema = externalClientPublicViewSchema.extend({
15324
+ token: external_exports.string().min(1).max(256).optional()
15325
+ });
15326
+ var externalClientUpdateParamsSchema = externalClientWriteFieldsSchema.extend({
15327
+ name: externalClientNameSchema,
15328
+ clearOauthClientId: external_exports.literal(true).optional()
15329
+ });
15330
+ var externalClientRevokeParamsSchema = external_exports.strictObject({
15331
+ name: externalClientNameSchema
15332
+ });
15333
+ var externalClientRevokeResultSchema = external_exports.strictObject({
15334
+ name: externalClientNameSchema,
15335
+ revoked: external_exports.literal(true)
15336
+ });
15337
+ var stringProp = (description) => ({ type: "string", description });
15338
+ var integerProp = (description) => ({
15339
+ type: "integer",
15340
+ minimum: 0,
15341
+ description
15342
+ });
15343
+ var threadProp = stringProp("Thread id or codex://threads/<id> link");
15344
+ var EXTERNAL_MCP_TOOL_DESCRIPTORS = [
15345
+ {
15346
+ name: "harness_list",
15347
+ description: "List the Harnesses this codexhost can delegate to.",
15348
+ inputSchema: { type: "object", properties: {} }
15349
+ },
15350
+ {
15351
+ name: "harness_inspect",
15352
+ description: "Read a Harness's Models, Thinking options and defaults; use the returned ids when delegating.",
15353
+ inputSchema: {
15354
+ type: "object",
15355
+ properties: {
15356
+ harnessId: stringProp("Harness id from harness_list"),
15357
+ cwd: stringProp("Absolute workspace path"),
15358
+ refresh: { type: "boolean" }
15359
+ },
15360
+ required: ["harnessId"]
15361
+ }
15362
+ },
15363
+ {
15364
+ name: "delegate_start",
15365
+ description: "Start a task in a new Thread and return at once. Without parentThread the work belongs to this client and cwd is required. watch=true records an event for this client when the Thread stops (read it with events_poll or the SSE stream).",
15366
+ inputSchema: {
15367
+ type: "object",
15368
+ properties: {
15369
+ harnessId: stringProp("Harness id from harness_list"),
15370
+ task: stringProp("The full task text"),
15371
+ taskName: stringProp("Short display name"),
15372
+ cwd: stringProp("Absolute workspace path"),
15373
+ model: stringProp("Model id from harness_inspect"),
15374
+ thinking: stringProp("Thinking option id from harness_inspect"),
15375
+ parentThread: stringProp("Optional parent Thread"),
15376
+ requestId: stringProp("Reuse to retry idempotently"),
15377
+ refs: {
15378
+ type: "array",
15379
+ items: { type: "string" },
15380
+ description: "Absolute URIs of where the work came from"
15381
+ },
15382
+ watch: { type: "boolean", description: "Record an event when the Thread stops" },
15383
+ watchTimeoutMs: integerProp("How long to watch; default 29 minutes")
15384
+ },
15385
+ required: ["harnessId", "task"]
15386
+ }
15387
+ },
15388
+ {
15389
+ name: "thread_read",
15390
+ description: "Read a Thread's status and latest result, or page its visible messages (view=messages). Never changes the Thread.",
15391
+ inputSchema: {
15392
+ type: "object",
15393
+ properties: {
15394
+ thread: threadProp,
15395
+ view: { type: "string", enum: ["result", "messages"] },
15396
+ cursor: stringProp("Message cursor"),
15397
+ limit: integerProp("Messages per page, at most 100")
15398
+ },
15399
+ required: ["thread"]
15400
+ }
15401
+ },
15402
+ {
15403
+ name: "thread_wait",
15404
+ description: "Wait up to timeoutMs (at most 60000) for a Thread to stop, then return the same snapshot as thread_read plus timedOut.",
15405
+ inputSchema: {
15406
+ type: "object",
15407
+ properties: {
15408
+ thread: threadProp,
15409
+ timeoutMs: integerProp("At most 60000; default 30000"),
15410
+ view: { type: "string", enum: ["result", "messages"] }
15411
+ },
15412
+ required: ["thread"]
15413
+ }
15414
+ },
15415
+ {
15416
+ name: "thread_list",
15417
+ description: "List Threads: by workspace (cwd), by parent Thread, by the client that started them, or by reference.",
15418
+ inputSchema: {
15419
+ type: "object",
15420
+ properties: {
15421
+ cwd: stringProp("Absolute workspace path"),
15422
+ parent: stringProp("Parent Thread"),
15423
+ client: stringProp("Client name"),
15424
+ ref: stringProp("Reference URI"),
15425
+ limit: integerProp("At most 100; default 25"),
15426
+ cursor: stringProp("Cursor from a previous page"),
15427
+ sort: {
15428
+ type: "string",
15429
+ enum: [
15430
+ "created-asc",
15431
+ "created-desc",
15432
+ "updated-asc",
15433
+ "updated-desc",
15434
+ "recency-asc",
15435
+ "recency-desc"
15436
+ ]
15437
+ }
15438
+ }
15439
+ }
15440
+ },
15441
+ {
15442
+ name: "thread_send",
15443
+ description: "Start a new Turn in an idle Thread. THREAD_BUSY means its current Turn is still running; messages are not queued.",
15444
+ inputSchema: {
15445
+ type: "object",
15446
+ properties: { thread: threadProp, message: stringProp("Message text") },
15447
+ required: ["thread", "message"]
15448
+ }
15449
+ },
15450
+ {
15451
+ name: "thread_cancel",
15452
+ description: "Cancel a Thread's active Turn, keeping the Thread and its history.",
15453
+ inputSchema: { type: "object", properties: { thread: threadProp }, required: ["thread"] }
15454
+ },
15455
+ {
15456
+ name: "thread_watch",
15457
+ description: "Record one event for this client when the Thread stops or the watch expires.",
15458
+ inputSchema: {
15459
+ type: "object",
15460
+ properties: { thread: threadProp, timeoutMs: integerProp("Default 29 minutes") },
15461
+ required: ["thread"]
15462
+ }
15463
+ },
15464
+ {
15465
+ name: "thread_watches",
15466
+ description: "List watches that have not been delivered yet.",
15467
+ inputSchema: { type: "object", properties: {} }
15468
+ },
15469
+ {
15470
+ name: "events_poll",
15471
+ description: "Read this client's events after a cursor (0 for all retained). Waits up to timeoutMs (at most 60000) for the first one. Pass the returned cursor back next time. CURSOR_EXPIRED: reconcile with thread_list client=<this client>.",
15472
+ inputSchema: {
15473
+ type: "object",
15474
+ properties: {
15475
+ after: integerProp("Cursor; 0 for all retained"),
15476
+ timeoutMs: integerProp("At most 60000; default 0"),
15477
+ limit: integerProp("At most 100")
15478
+ }
15479
+ }
15480
+ }
15481
+ ];
15482
+
15483
+ // packages/shared-contracts/dist/external-mcp-map.js
15484
+ var DEFAULT_WATCH_MS = 29 * 6e4;
15485
+
15093
15486
  // packages/shared-contracts/dist/grok-computer-use.js
15094
15487
  var grokComputerUseGetSchema = external_exports.object({}).strict();
15095
15488
  var grokComputerUseSetSchema = external_exports.object({
@@ -15686,11 +16079,63 @@ var threadSteeringInspectResultSchema = external_exports.object({
15686
16079
  delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
15687
16080
  }).strict();
15688
16081
 
16082
+ // packages/shared-contracts/dist/voice-settings.js
16083
+ var VOICE_SETTINGS_METHOD = "codexhost/voice/settings";
16084
+ var VOICE_GATEWAY_STATUS_METHOD = "codexhost/voice/gateway-status";
16085
+ var voiceRoutesSchema = external_exports.strictObject({
16086
+ chatExperience: external_exports.enum(["chatgpt", "codex"]),
16087
+ chatConnection: external_exports.enum(["desktop", "gateway"]),
16088
+ workConnection: external_exports.enum(["desktop", "gateway"])
16089
+ });
16090
+ var DEFAULT_VOICE_ROUTES = Object.freeze({
16091
+ chatExperience: "chatgpt",
16092
+ chatConnection: "desktop",
16093
+ workConnection: "gateway"
16094
+ });
16095
+ var voiceSettingsSchema = voiceRoutesSchema.extend({ inject: external_exports.boolean() });
16096
+ var voiceSettingsRequestSchema = external_exports.discriminatedUnion("operation", [
16097
+ external_exports.strictObject({
16098
+ operation: external_exports.literal("get"),
16099
+ runtime: external_exports.strictObject({
16100
+ id: external_exports.string().uuid(),
16101
+ revision: external_exports.string().max(64),
16102
+ activeCall: external_exports.boolean()
16103
+ }).optional()
16104
+ }),
16105
+ external_exports.strictObject({ operation: external_exports.literal("migrate"), routes: voiceRoutesSchema }),
16106
+ external_exports.strictObject({
16107
+ operation: external_exports.literal("set"),
16108
+ settings: voiceSettingsSchema,
16109
+ revision: external_exports.string().max(64)
16110
+ }),
16111
+ external_exports.strictObject({ operation: external_exports.literal("restart"), confirm: external_exports.literal(true) })
16112
+ ]);
16113
+ var voiceSettingsStateSchema = external_exports.strictObject({
16114
+ settings: voiceSettingsSchema,
16115
+ initialized: external_exports.boolean(),
16116
+ revision: external_exports.string(),
16117
+ activeInject: external_exports.boolean().nullable(),
16118
+ envOverride: external_exports.enum(["0", "1"]).nullable(),
16119
+ activeEnvOverride: external_exports.enum(["0", "1"]).nullable(),
16120
+ routesActive: external_exports.boolean().nullable(),
16121
+ activeCall: external_exports.boolean().nullable(),
16122
+ gatewayReady: external_exports.boolean().nullable(),
16123
+ restartAvailable: external_exports.boolean(),
16124
+ restart: external_exports.strictObject({
16125
+ phase: external_exports.enum(["idle", "restarting", "succeeded", "failed"]),
16126
+ error: external_exports.string().nullable()
16127
+ })
16128
+ });
16129
+
15689
16130
  // packages/shared-contracts/dist/client-channel.js
15690
16131
  var CLIENT_CHANNEL_VERSION = 1;
15691
16132
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
15692
16133
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15693
16134
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
16135
+ var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
16136
+ var clientThreadTreeSchema = external_exports.object({
16137
+ parents: external_exports.record(external_exports.string().min(1), external_exports.string().min(1))
16138
+ }).strict();
15694
16139
  var clientProjectlessWorkspaceSchema = external_exports.object({
15695
16140
  prompt: external_exports.string().max(16384).optional()
15696
16141
  }).strict();
@@ -15707,6 +16152,11 @@ var clientChannelCursorSchema = external_exports.object({
15707
16152
  sequence: external_exports.number().int().nonnegative()
15708
16153
  });
15709
16154
  var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
16155
+ external_exports.object({
16156
+ type: external_exports.literal("skills-changed"),
16157
+ cursor: clientChannelCursorSchema,
16158
+ cwd: external_exports.string().optional()
16159
+ }),
15710
16160
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
15711
16161
  external_exports.object({
15712
16162
  type: external_exports.literal("preferences-changed"),
@@ -15904,6 +16354,28 @@ var voiceTranscribeResultSchema = external_exports.discriminatedUnion("ok", [
15904
16354
  external_exports.object({ ok: external_exports.literal(false), error: external_exports.object({ code: voiceErrorCodeSchema }).strict() }).strict()
15905
16355
  ]);
15906
16356
 
16357
+ // packages/shared-contracts/dist/skills.js
16358
+ var skillsListParamsSchema = external_exports.object({
16359
+ threadId: hostThreadIdSchema.optional(),
16360
+ cwd: external_exports.string().min(1).optional()
16361
+ }).strict().refine((params) => !(params.threadId && params.cwd), {
16362
+ message: "Specify threadId or cwd, not both"
16363
+ });
16364
+ var librarySkillSchema = external_exports.object({
16365
+ name: external_exports.string().min(1).regex(/^[^\s[\]]+$/u),
16366
+ description: external_exports.string().optional(),
16367
+ path: external_exports.string().min(1),
16368
+ scope: external_exports.enum(["project", "global"]),
16369
+ source: external_exports.string().min(1)
16370
+ }).strict();
16371
+ var skillsListResultSchema = external_exports.object({
16372
+ revision: external_exports.number().int().nonnegative(),
16373
+ complete: external_exports.boolean(),
16374
+ skills: external_exports.array(librarySkillSchema),
16375
+ warnings: external_exports.array(external_exports.string()).optional()
16376
+ }).strict();
16377
+ var skillsChangedParamsSchema = external_exports.object({ cwd: external_exports.string().min(1).optional() }).strict();
16378
+
15907
16379
  // packages/shared-contracts/dist/web-access-tokens.js
15908
16380
  var webNetworkAccessUrlSchema = external_exports.object({
15909
16381
  /**
@@ -16010,8 +16482,8 @@ var REMOTE_THREAD_CONTROL_TIMEOUT_MS = 4e4;
16010
16482
  var delegationReadParamsSchema = external_exports.strictObject({
16011
16483
  threadId: external_exports.string().min(1).max(1024),
16012
16484
  view: external_exports.enum(["result", "messages"]),
16013
- cursor: external_exports.string().min(1).max(8192).optional(),
16014
- limit: external_exports.number().int().min(1).max(100).optional()
16485
+ from: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
16486
+ to: external_exports.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional()
16015
16487
  });
16016
16488
 
16017
16489
  // packages/shared-contracts/dist/credential-imports.js
@@ -16463,6 +16935,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
16463
16935
  "codexhost/voice/gateway-status",
16464
16936
  "codexhost/enrollment/list",
16465
16937
  "codexhost/enrollment/revoke",
16938
+ "codexhost/external-clients/list",
16939
+ "codexhost/external-clients/create",
16940
+ "codexhost/external-clients/update",
16941
+ "codexhost/external-clients/revoke",
16466
16942
  "codexhost/console/remote-connections",
16467
16943
  "codexhost/runtime/status",
16468
16944
  "codexhost/remote/ssh-setup",
@@ -16671,10 +17147,20 @@ var harnessLaunchSettingsSchema = external_exports.object({
16671
17147
  }).strict();
16672
17148
 
16673
17149
  // packages/shared-contracts/dist/harness-installation.js
17150
+ var HARNESS_INSTALLATION_METHOD = "codexhost/harness/installation";
17151
+ var HARNESS_INSTALLATION_MUTATION_TIMEOUT_MS = 66e4;
16674
17152
  var harnessInstallationParamsSchema = external_exports.object({
16675
17153
  harnessId: harnessIdSchema,
16676
17154
  action: external_exports.enum(["check", "update", "install"])
16677
17155
  }).strict();
17156
+ function harnessInstallationRequestTimeoutMs(method, params) {
17157
+ if (method !== HARNESS_INSTALLATION_METHOD)
17158
+ return;
17159
+ const parsed = harnessInstallationParamsSchema.safeParse(params);
17160
+ if (!parsed.success || parsed.data.action === "check")
17161
+ return;
17162
+ return HARNESS_INSTALLATION_MUTATION_TIMEOUT_MS;
17163
+ }
16678
17164
  var harnessInstallationStateSchema = external_exports.object({
16679
17165
  currentVersion: external_exports.string().min(1).max(128),
16680
17166
  latestVersion: external_exports.string().min(1).max(128),
@@ -17004,6 +17490,17 @@ var updateStatusResultSchema = external_exports.strictObject({
17004
17490
  status: updateStatusSchema.nullable()
17005
17491
  });
17006
17492
 
17493
+ // packages/shared-contracts/dist/thread-watch-notice.js
17494
+ var THREAD_WATCH_NOTICE_OUTCOMES = [
17495
+ "completed",
17496
+ "failed",
17497
+ "interrupted",
17498
+ "timedOut",
17499
+ "unreadable",
17500
+ "notFound"
17501
+ ];
17502
+ var ENTRY_PATTERN = new RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): ` + `(${THREAD_WATCH_NOTICE_OUTCOMES.join("|")})(?:. (.+))?$`, "u");
17503
+
17007
17504
  // packages/shared-contracts/dist/remote-runtime.js
17008
17505
  var remoteUpdatePhaseSchema = external_exports.enum([
17009
17506
  "idle",
@@ -17051,6 +17548,14 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
17051
17548
  archived: external_exports.boolean()
17052
17549
  }),
17053
17550
  external_exports.strictObject({ kind: external_exports.literal("read"), ...thread }),
17551
+ external_exports.strictObject({
17552
+ kind: external_exports.literal("configure"),
17553
+ ...thread,
17554
+ epoch: identity,
17555
+ modelId: identity.optional(),
17556
+ thinkingOptionId: identity.optional(),
17557
+ permissionModeId: identity.optional()
17558
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
17054
17559
  external_exports.strictObject({
17055
17560
  kind: external_exports.literal("prompt"),
17056
17561
  ...thread,
@@ -17123,6 +17628,13 @@ var remoteConnectionsReplySchema = external_exports.union([
17123
17628
  external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
17124
17629
  ]);
17125
17630
 
17631
+ // packages/shared-contracts/dist/thread-title.js
17632
+ var threadTitleInputSchema = external_exports.strictObject({
17633
+ prompt: external_exports.string().trim().min(1).max(2e3),
17634
+ cwd: external_exports.string().max(4096).nullable()
17635
+ });
17636
+ var threadTitleResultSchema = external_exports.string().trim().min(1).max(60).nullable();
17637
+
17126
17638
  // packages/shared-contracts/dist/web-ui-extensions.js
17127
17639
  var webUiExtensionIdSchema = external_exports.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u);
17128
17640
  var localizedTextSchema2 = external_exports.union([
@@ -17163,52 +17675,6 @@ var webUiExtensionInstallSchema = external_exports.object({
17163
17675
  var webUiExtensionEnabledSchema = external_exports.object({ id: webUiExtensionIdSchema, enabled: external_exports.boolean() }).strict();
17164
17676
  var webUiExtensionRemoveSchema = external_exports.object({ id: webUiExtensionIdSchema }).strict();
17165
17677
 
17166
- // packages/shared-contracts/dist/voice-settings.js
17167
- var voiceRoutesSchema = external_exports.strictObject({
17168
- chatExperience: external_exports.enum(["chatgpt", "codex"]),
17169
- chatConnection: external_exports.enum(["desktop", "gateway"]),
17170
- workConnection: external_exports.enum(["desktop", "gateway"])
17171
- });
17172
- var DEFAULT_VOICE_ROUTES = Object.freeze({
17173
- chatExperience: "chatgpt",
17174
- chatConnection: "desktop",
17175
- workConnection: "gateway"
17176
- });
17177
- var voiceSettingsSchema = voiceRoutesSchema.extend({ inject: external_exports.boolean() });
17178
- var voiceSettingsRequestSchema = external_exports.discriminatedUnion("operation", [
17179
- external_exports.strictObject({
17180
- operation: external_exports.literal("get"),
17181
- runtime: external_exports.strictObject({
17182
- id: external_exports.string().uuid(),
17183
- revision: external_exports.string().max(64),
17184
- activeCall: external_exports.boolean()
17185
- }).optional()
17186
- }),
17187
- external_exports.strictObject({ operation: external_exports.literal("migrate"), routes: voiceRoutesSchema }),
17188
- external_exports.strictObject({
17189
- operation: external_exports.literal("set"),
17190
- settings: voiceSettingsSchema,
17191
- revision: external_exports.string().max(64)
17192
- }),
17193
- external_exports.strictObject({ operation: external_exports.literal("restart"), confirm: external_exports.literal(true) })
17194
- ]);
17195
- var voiceSettingsStateSchema = external_exports.strictObject({
17196
- settings: voiceSettingsSchema,
17197
- initialized: external_exports.boolean(),
17198
- revision: external_exports.string(),
17199
- activeInject: external_exports.boolean().nullable(),
17200
- envOverride: external_exports.enum(["0", "1"]).nullable(),
17201
- activeEnvOverride: external_exports.enum(["0", "1"]).nullable(),
17202
- routesActive: external_exports.boolean().nullable(),
17203
- activeCall: external_exports.boolean().nullable(),
17204
- gatewayReady: external_exports.boolean().nullable(),
17205
- restartAvailable: external_exports.boolean(),
17206
- restart: external_exports.strictObject({
17207
- phase: external_exports.enum(["idle", "restarting", "succeeded", "failed"]),
17208
- error: external_exports.string().nullable()
17209
- })
17210
- });
17211
-
17212
17678
  // packages/shared-contracts/dist/background-activity.js
17213
17679
  var backgroundActivitySchema = external_exports.strictObject({
17214
17680
  id: external_exports.string().min(1),
@@ -17272,7 +17738,7 @@ function isLocalPageUrl(value) {
17272
17738
  return false;
17273
17739
  }
17274
17740
  }
17275
- async function serveLocalPage(socket, url2, open) {
17741
+ async function serveLocalPage(socket, url2, open2) {
17276
17742
  let page;
17277
17743
  let buffer = "";
17278
17744
  let operation = Promise.resolve();
@@ -17304,7 +17770,7 @@ async function serveLocalPage(socket, url2, open) {
17304
17770
  }
17305
17771
  };
17306
17772
  try {
17307
- page = await open(url2);
17773
+ page = await open2(url2);
17308
17774
  if (socket.destroyed) return;
17309
17775
  socket.on("data", receive);
17310
17776
  socket.write("ready\n");
@@ -17563,7 +18029,7 @@ function createControllerStatusPublisher(filePath = defaultControllerStatusPath(
17563
18029
  }
17564
18030
 
17565
18031
  // packages/desktop-control/src/cpa-live-voice-hook.ts
17566
- import { existsSync } from "node:fs";
18032
+ import { existsSync, readFileSync as readFileSync2, unlinkSync } from "node:fs";
17567
18033
  import { execFileSync } from "node:child_process";
17568
18034
  import os3 from "node:os";
17569
18035
  import path3 from "node:path";
@@ -17591,6 +18057,145 @@ var CPA_LIVE_VOICE_HOOK_GLOBAL = "__codexhostCpaLiveVoiceHookV1";
17591
18057
  var AUDITED_CPA_LIVE_VOICE_DESKTOP_VERSION = "26.1007.30912";
17592
18058
  var AUDITED_CPA_LIVE_VOICE_APP_INITIAL_ASSET = "app-initial-6350d04672d0.js";
17593
18059
  var DESKTOP_VERSION_ENV = "CODEXHOST_DESKTOP_VERSION";
18060
+ var DESKTOP_BUILD_ENV = "CODEXHOST_DESKTOP_BUILD";
18061
+ var DESKTOP_ASAR_DIGEST_ENV = "CODEXHOST_DESKTOP_ASAR_DIGEST";
18062
+ var DESKTOP_APP_PATH_ENV = "CODEXHOST_DESKTOP_APP_PATH";
18063
+ var VOICE_ISOLATED_QUALIFICATION_FILE = "voice-isolated-qualification.json";
18064
+ var HASHED_WEBPACK_OVERLAY_VOICE_DESKTOP_VERSION = "26.1106.51428";
18065
+ var OVERLAY_VOICE_HOOK_DESKTOP_VERSIONS = [
18066
+ AUDITED_CPA_LIVE_VOICE_DESKTOP_VERSION,
18067
+ "26.1016.61520",
18068
+ "26.1016.62342",
18069
+ "26.1021.31345",
18070
+ "26.1023.51421",
18071
+ "26.1027.30824",
18072
+ "26.1027.61615",
18073
+ HASHED_WEBPACK_OVERLAY_VOICE_DESKTOP_VERSION
18074
+ ];
18075
+ var ISOLATED_VOICE_PATHS = ["chat", "work-codex", "work-grok"];
18076
+ var PRODUCTION_DESKTOP_APP_PATH = "/Applications/ChatGPT.app";
18077
+ var PRODUCTION_WINDOWS_APPX_PATH = /(?:^|[\\/])WindowsApps[\\/]OpenAI\.(?:Codex|ChatGPT)_/i;
18078
+ function isProductionDesktopAppPath(appPath) {
18079
+ if (typeof appPath !== "string" || appPath.length === 0) return false;
18080
+ if (appPath === PRODUCTION_DESKTOP_APP_PATH) return true;
18081
+ return PRODUCTION_WINDOWS_APPX_PATH.test(appPath);
18082
+ }
18083
+ function isNonEmptyString(value) {
18084
+ return typeof value === "string" && value.length > 0;
18085
+ }
18086
+ function envNonEmpty(environment, key) {
18087
+ const value = environment[key]?.trim();
18088
+ return value ? value : void 0;
18089
+ }
18090
+ function isIsolatedVoicePath(value) {
18091
+ return value === "chat" || value === "work-codex" || value === "work-grok";
18092
+ }
18093
+ function isIsolatedDesktopPlatform(value) {
18094
+ return value === "darwin" || value === "win32" || value === "linux";
18095
+ }
18096
+ function isolatedQualificationExpiresAtMs(expiresAt) {
18097
+ if (typeof expiresAt !== "string" || expiresAt.length === 0) return void 0;
18098
+ const parsed = Date.parse(expiresAt);
18099
+ return Number.isFinite(parsed) ? parsed : void 0;
18100
+ }
18101
+ function isolatedQualificationPathSet(value) {
18102
+ if (value === null || typeof value !== "object") return void 0;
18103
+ const record4 = value;
18104
+ const pathsPresent = record4.paths !== void 0;
18105
+ const pathPresent = record4.path !== void 0;
18106
+ let listed;
18107
+ if (pathsPresent) {
18108
+ const rawPaths = record4.paths;
18109
+ if (!Array.isArray(rawPaths) || rawPaths.length === 0) return void 0;
18110
+ if (rawPaths.some((path7) => !isIsolatedVoicePath(path7))) return void 0;
18111
+ if (new Set(rawPaths).size !== rawPaths.length) return void 0;
18112
+ listed = ISOLATED_VOICE_PATHS.filter((path7) => rawPaths.includes(path7));
18113
+ if (listed.length !== rawPaths.length) return void 0;
18114
+ } else if (pathPresent) {
18115
+ if (!isIsolatedVoicePath(record4.path)) return void 0;
18116
+ listed = [record4.path];
18117
+ } else {
18118
+ return void 0;
18119
+ }
18120
+ if (pathPresent) {
18121
+ if (!isIsolatedVoicePath(record4.path) || !listed.includes(record4.path)) return void 0;
18122
+ }
18123
+ return listed;
18124
+ }
18125
+ function isIsolatedVoiceQualification(value, now = Date.now()) {
18126
+ if (value === null || typeof value !== "object") return false;
18127
+ const parsed = value;
18128
+ const paths = isolatedQualificationPathSet(parsed);
18129
+ if (!paths || paths.length === 0) return false;
18130
+ if (isProductionDesktopAppPath(parsed.appPath)) return false;
18131
+ const expiresAtMs = isolatedQualificationExpiresAtMs(parsed.expiresAt);
18132
+ if (expiresAtMs === void 0 || expiresAtMs <= now) return false;
18133
+ return isNonEmptyString(parsed.run) && isIsolatedDesktopPlatform(parsed.desktopPlatform) && isNonEmptyString(parsed.desktopVersion) && isNonEmptyString(parsed.desktopBuild) && isNonEmptyString(parsed.asarDigest) && isNonEmptyString(parsed.appPath) && isNonEmptyString(parsed.implementationRevision) && parsed.label === "unqualified-isolated";
18134
+ }
18135
+ function readVoiceProfilePins(overlayDir) {
18136
+ const file2 = path3.join(overlayDir, "voice-profile-pins.json");
18137
+ try {
18138
+ const parsed = JSON.parse(readFileSync2(file2, "utf8"));
18139
+ if (!isNonEmptyString(parsed.hashedVersion) || !Array.isArray(parsed.overlayHookDesktopVersions) || parsed.overlayHookDesktopVersions.some((version2) => !isNonEmptyString(version2))) {
18140
+ return void 0;
18141
+ }
18142
+ return parsed;
18143
+ } catch {
18144
+ return void 0;
18145
+ }
18146
+ }
18147
+ function readVoiceQualification(overlayDir) {
18148
+ const file2 = path3.join(overlayDir, "voice-qualification.json");
18149
+ try {
18150
+ const parsed = JSON.parse(readFileSync2(file2, "utf8"));
18151
+ if (!isNonEmptyString(parsed.implementationRevision) || !Array.isArray(parsed.reviewedEvidence)) {
18152
+ return void 0;
18153
+ }
18154
+ return parsed;
18155
+ } catch {
18156
+ return void 0;
18157
+ }
18158
+ }
18159
+ function readVoiceIsolatedQualification(overlayDir, now = Date.now()) {
18160
+ const file2 = path3.join(overlayDir, VOICE_ISOLATED_QUALIFICATION_FILE);
18161
+ try {
18162
+ const parsed = JSON.parse(readFileSync2(file2, "utf8"));
18163
+ if (parsed !== null && typeof parsed === "object") {
18164
+ const expiresAtMs = isolatedQualificationExpiresAtMs(
18165
+ parsed.expiresAt
18166
+ );
18167
+ if (expiresAtMs !== void 0 && expiresAtMs <= now) {
18168
+ try {
18169
+ unlinkSync(file2);
18170
+ } catch {
18171
+ }
18172
+ return void 0;
18173
+ }
18174
+ }
18175
+ if (!isIsolatedVoiceQualification(parsed, now)) return void 0;
18176
+ return parsed;
18177
+ } catch {
18178
+ return void 0;
18179
+ }
18180
+ }
18181
+ function isolatedQualificationMatchesRuntime(isolated, identity2) {
18182
+ if (isProductionDesktopAppPath(isolated.appPath) || isProductionDesktopAppPath(identity2.appPath))
18183
+ return false;
18184
+ if (!isIsolatedDesktopPlatform(isolated.desktopPlatform) || isolated.desktopPlatform !== identity2.desktopPlatform)
18185
+ return false;
18186
+ return isolated.desktopVersion === identity2.desktopVersion && isolated.desktopBuild === identity2.desktopBuild && isolated.asarDigest === identity2.asarDigest && isolated.appPath === identity2.appPath && isolated.implementationRevision === identity2.implementationRevision;
18187
+ }
18188
+ function overlayHookDesktopVersions(overlayDir) {
18189
+ if (!overlayDir) return OVERLAY_VOICE_HOOK_DESKTOP_VERSIONS;
18190
+ return readVoiceProfilePins(overlayDir)?.overlayHookDesktopVersions ?? [];
18191
+ }
18192
+ function hashedOverlayDesktopVersion(overlayDir) {
18193
+ if (!overlayDir) return HASHED_WEBPACK_OVERLAY_VOICE_DESKTOP_VERSION;
18194
+ return readVoiceProfilePins(overlayDir)?.hashedVersion ?? "";
18195
+ }
18196
+ function overlayVoiceBootstrapPreferred(environment = process.env, overlayDir) {
18197
+ return environment[DESKTOP_VERSION_ENV]?.trim() === hashedOverlayDesktopVersion(overlayDir);
18198
+ }
17594
18199
  function cpaLiveVoiceHookEnabled(environment = process.env) {
17595
18200
  const value = environment[CPA_LIVE_VOICE_ENV];
17596
18201
  if (value === "0") return false;
@@ -17627,19 +18232,72 @@ function detectInstalledDesktopVersion(environment = process.env) {
17627
18232
  }
17628
18233
  return void 0;
17629
18234
  }
17630
- function cpaLiveVoiceHookBootstrap(environment = process.env, desktopVersion) {
18235
+ function detectInstalledDesktopBuild(environment = process.env) {
18236
+ const fromEnv = envNonEmpty(environment, DESKTOP_BUILD_ENV);
18237
+ if (fromEnv) return fromEnv;
18238
+ const appPath = envNonEmpty(environment, DESKTOP_APP_PATH_ENV);
18239
+ if (!appPath || process.platform !== "darwin") return void 0;
18240
+ const plist = path3.join(appPath, "Contents/Info.plist");
18241
+ if (!existsSync(plist)) return void 0;
18242
+ try {
18243
+ const build = execFileSync("/usr/bin/defaults", ["read", plist, "CFBundleVersion"], {
18244
+ encoding: "utf8",
18245
+ timeout: 2e3
18246
+ }).trim();
18247
+ return build || void 0;
18248
+ } catch {
18249
+ return void 0;
18250
+ }
18251
+ }
18252
+ function detectInstalledDesktopAsarDigest(environment = process.env) {
18253
+ return envNonEmpty(environment, DESKTOP_ASAR_DIGEST_ENV);
18254
+ }
18255
+ function detectLaunchedDesktopAppPath(environment = process.env) {
18256
+ return envNonEmpty(environment, DESKTOP_APP_PATH_ENV);
18257
+ }
18258
+ function cpaLiveVoiceOverlayHookAllowed(environment = process.env, overlayDir) {
18259
+ if (!cpaLiveVoiceHookEnabled(environment)) return false;
18260
+ const version2 = environment[DESKTOP_VERSION_ENV]?.trim();
18261
+ if (!version2) return true;
18262
+ return overlayHookDesktopVersions(overlayDir).some((pin) => pin === version2);
18263
+ }
18264
+ function cpaLiveVoiceHookBootstrap(environment = process.env, desktopVersion, overlayDir) {
17631
18265
  if (!cpaLiveVoiceHookEnabled(environment)) return "";
17632
18266
  const version2 = environment[DESKTOP_VERSION_ENV]?.trim() || desktopVersion || detectInstalledDesktopVersion(environment);
18267
+ const desktopBuild = detectInstalledDesktopBuild(environment);
18268
+ const asarDigest = detectInstalledDesktopAsarDigest(environment);
18269
+ const desktopAppPath = detectLaunchedDesktopAppPath(environment);
18270
+ const qualification = overlayDir ? readVoiceQualification(overlayDir) : void 0;
18271
+ const isolated = overlayDir ? readVoiceIsolatedQualification(overlayDir) : void 0;
18272
+ const isolatedQualification = isolated && isolatedQualificationMatchesRuntime(isolated, {
18273
+ desktopPlatform: process.platform,
18274
+ ...version2 === void 0 ? {} : { desktopVersion: version2 },
18275
+ ...desktopBuild === void 0 ? {} : { desktopBuild },
18276
+ ...asarDigest === void 0 ? {} : { asarDigest },
18277
+ ...desktopAppPath === void 0 ? {} : { appPath: desktopAppPath },
18278
+ ...qualification === void 0 ? {} : { implementationRevision: qualification.implementationRevision }
18279
+ }) ? isolated : void 0;
17633
18280
  return `globalThis.${CPA_LIVE_VOICE_HOOK_GLOBAL} = Object.freeze(${JSON.stringify({
17634
18281
  enabled: true,
17635
18282
  desktopPlatform: process.platform,
17636
18283
  auditedDesktopVersion: AUDITED_CPA_LIVE_VOICE_DESKTOP_VERSION,
17637
18284
  auditedAppInitialAsset: AUDITED_CPA_LIVE_VOICE_APP_INITIAL_ASSET,
17638
- ...version2 ? { desktopVersion: version2 } : {}
18285
+ ...version2 ? { desktopVersion: version2 } : {},
18286
+ ...desktopBuild ? { desktopBuild } : {},
18287
+ ...asarDigest ? { asarDigest } : {},
18288
+ ...desktopAppPath ? { desktopAppPath } : {},
18289
+ ...qualification ? {
18290
+ implementationRevision: qualification.implementationRevision,
18291
+ voiceEvidence: qualification.reviewedEvidence
18292
+ } : {},
18293
+ ...isolatedQualification ? { isolatedQualification } : {}
17639
18294
  })});
17640
18295
  `;
17641
18296
  }
17642
18297
 
18298
+ // packages/desktop-control/src/renderer-cdp-control-session.ts
18299
+ import { createHash } from "node:crypto";
18300
+
17643
18301
  // packages/desktop-control/src/browser-annotation-style-compat.ts
17644
18302
  var BROWSER_ANNOTATION_STYLE_COMPAT_SOURCE = String.raw`(() => {
17645
18303
  const key = '__codexhostBrowserAnnotationStylesV1';
@@ -17742,13 +18400,13 @@ function committedReactAncestors(value) {
17742
18400
  const current = fiber(rootState.current);
17743
18401
  if (!current) return [];
17744
18402
  const alternate = fiber(first.alternate);
17745
- const path5 = [current];
18403
+ const path7 = [current];
17746
18404
  seen.clear();
17747
18405
  seen.add(current);
17748
18406
  for (let index = previous.length - 2; index >= 0; index -= 1) {
17749
18407
  const expected = previous[index];
17750
18408
  const expectedAlternate = fiber(expected?.alternate);
17751
- let child = fiber(path5.at(-1)?.child);
18409
+ let child = fiber(path7.at(-1)?.child);
17752
18410
  let matched = false;
17753
18411
  while (child && !seen.has(child) && seen.size < MAX_VISITED_FIBERS) {
17754
18412
  seen.add(child);
@@ -17759,10 +18417,10 @@ function committedReactAncestors(value) {
17759
18417
  child = fiber(child.sibling);
17760
18418
  }
17761
18419
  if (!matched || !child) break;
17762
- path5.push(child);
18420
+ path7.push(child);
17763
18421
  }
17764
- if (path5.length === previous.length && (path5.at(-1) === first || path5.at(-1) === alternate)) {
17765
- return path5.reverse();
18422
+ if (path7.length === previous.length && (path7.at(-1) === first || path7.at(-1) === alternate)) {
18423
+ return path7.reverse();
17766
18424
  }
17767
18425
  const stack = [{ node: current, parent: null }];
17768
18426
  seen.clear();
@@ -17790,7 +18448,7 @@ function retainRendererHostResponses(client, hostId2, target2) {
17790
18448
  if (typeof client.addRequestLifecycleListener !== "function" || typeof target2.addEventListener !== "function" || typeof target2.removeEventListener !== "function")
17791
18449
  return () => {
17792
18450
  };
17793
- const isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18451
+ const isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17794
18452
  const pending = /* @__PURE__ */ new Set();
17795
18453
  let retired = false;
17796
18454
  let unsubscribe = () => {
@@ -17804,12 +18462,12 @@ function retainRendererHostResponses(client, hostId2, target2) {
17804
18462
  if (source != null && source !== target2) return;
17805
18463
  const ownOrigin = target2.location?.origin;
17806
18464
  if (source === target2 && ownOrigin && ownOrigin !== "null" && origin !== ownOrigin) return;
17807
- if (!isRecord3(data) || data.type !== "mcp-response" || data.hostId !== hostId2) return;
18465
+ if (!isRecord4(data) || data.type !== "mcp-response" || data.hostId !== hostId2) return;
17808
18466
  const message = data.message;
17809
- if (!isRecord3(message)) return;
18467
+ if (!isRecord4(message)) return;
17810
18468
  const id = message.id;
17811
18469
  if (typeof id !== "string" && typeof id !== "number" || !pending.has(id)) return;
17812
- const hasError = isRecord3(message.error);
18470
+ const hasError = isRecord4(message.error);
17813
18471
  if (!hasError && !Object.prototype.hasOwnProperty.call(message, "result")) return;
17814
18472
  queueMicrotask(() => {
17815
18473
  if (!pending.has(id)) return;
@@ -17819,7 +18477,7 @@ function retainRendererHostResponses(client, hostId2, target2) {
17819
18477
  };
17820
18478
  target2.addEventListener("message", receive);
17821
18479
  unsubscribe = client.addRequestLifecycleListener((event) => {
17822
- if (!isRecord3(event) || event.hostId !== hostId2) return;
18480
+ if (!isRecord4(event) || event.hostId !== hostId2) return;
17823
18481
  const id = event.id;
17824
18482
  if (typeof id !== "string" && typeof id !== "number") return;
17825
18483
  if (!retired && event.type === "started" && typeof event.method === "string" && event.method.startsWith("codexhost/"))
@@ -17937,13 +18595,13 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
17937
18595
  let selectedModel = null;
17938
18596
  let prewarmGeneration = 0;
17939
18597
  const externalPrewarms = /* @__PURE__ */ new Set();
17940
- const isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18598
+ const isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17941
18599
  const isUnsupportedPosixBridgeSpawn = (value) => {
17942
18600
  const marker = "AbsolutePathBuf deserialized without a base path";
17943
18601
  if (typeof value === "string") {
17944
18602
  return value.startsWith("Invalid request:") && value.includes(marker);
17945
18603
  }
17946
- if (!isRecord3(value)) return false;
18604
+ if (!isRecord4(value)) return false;
17947
18605
  if (typeof value.message === "string" && value.message.includes(marker)) {
17948
18606
  if (value.code === -32600 || value.message.startsWith("Invalid request:")) return true;
17949
18607
  }
@@ -18034,14 +18692,14 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18034
18692
  bridgeState = "idle";
18035
18693
  };
18036
18694
  const rememberExternalThread = (value) => {
18037
- if (!isRecord3(value) || typeof value.id !== "string") return;
18695
+ if (!isRecord4(value) || typeof value.id !== "string") return;
18038
18696
  if (value.modelProvider === "codexhost" || value.cliVersion === "codexhost") {
18039
18697
  knownExternalThreadIds.add(value.id);
18040
18698
  knownOfficialThreadIds.delete(value.id);
18041
18699
  }
18042
18700
  };
18043
18701
  const observeBridgeResult = (request, result) => {
18044
- if (!request || !isRecord3(result)) return;
18702
+ if (!request || !isRecord4(result)) return;
18045
18703
  if (request.method === "thread/list" && Array.isArray(result.data)) {
18046
18704
  for (const thread2 of result.data) rememberExternalThread(thread2);
18047
18705
  return;
@@ -18050,7 +18708,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18050
18708
  rememberExternalThread(result.thread);
18051
18709
  return;
18052
18710
  }
18053
- if (request.method === "codexhost/thread/inspect" && isRecord3(request.parameters) && typeof request.parameters.threadId === "string") {
18711
+ if (request.method === "codexhost/thread/inspect" && isRecord4(request.parameters) && typeof request.parameters.threadId === "string") {
18054
18712
  if (result.owner === "external") {
18055
18713
  knownExternalThreadIds.add(request.parameters.threadId);
18056
18714
  knownOfficialThreadIds.delete(request.parameters.threadId);
@@ -18060,18 +18718,18 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18060
18718
  }
18061
18719
  return;
18062
18720
  }
18063
- if (request.method === "thread/delete" && isRecord3(request.parameters) && typeof request.parameters.threadId === "string") {
18721
+ if (request.method === "thread/delete" && isRecord4(request.parameters) && typeof request.parameters.threadId === "string") {
18064
18722
  knownExternalThreadIds.delete(request.parameters.threadId);
18065
18723
  knownOfficialThreadIds.delete(request.parameters.threadId);
18066
18724
  }
18067
18725
  };
18068
18726
  const handleBridgeFrame = (value) => {
18069
- if (!isRecord3(value)) {
18727
+ if (!isRecord4(value)) {
18070
18728
  failBridge("received a non-object app-server frame");
18071
18729
  return;
18072
18730
  }
18073
18731
  if (value.method === bridgeReadyMethod && value.id === void 0) {
18074
- if (isRecord3(value.params) && value.params.protocolVersion === 1) {
18732
+ if (isRecord4(value.params) && value.params.protocolVersion === 1) {
18075
18733
  bridgeState = "ready";
18076
18734
  if (bridgeReadyTimeout !== null) globalThis.clearTimeout(bridgeReadyTimeout);
18077
18735
  bridgeReadyTimeout = null;
@@ -18084,7 +18742,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18084
18742
  return;
18085
18743
  }
18086
18744
  if (typeof value.method === "string" && value.id === void 0) {
18087
- if (value.method === "thread/started" && isRecord3(value.params)) {
18745
+ if (value.method === "thread/started" && isRecord4(value.params)) {
18088
18746
  rememberExternalThread(value.params.thread);
18089
18747
  }
18090
18748
  originalOnNotification.call(manager, value.method, value.params);
@@ -18135,7 +18793,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18135
18793
  }
18136
18794
  };
18137
18795
  const handleOuterNotification = (method, parameters) => {
18138
- if (method === "process/exited" && isRecord3(parameters) && parameters.processHandle === bridgeProcessHandle) {
18796
+ if (method === "process/exited" && isRecord4(parameters) && parameters.processHandle === bridgeProcessHandle) {
18139
18797
  const exitCode = typeof parameters.exitCode === "number" ? parameters.exitCode : "unknown";
18140
18798
  const stderr = typeof parameters.stderr === "string" ? parameters.stderr.trim() : "";
18141
18799
  failBridge(
@@ -18144,7 +18802,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18144
18802
  );
18145
18803
  return true;
18146
18804
  }
18147
- if (method !== "process/outputDelta" || !isRecord3(parameters) || parameters.processHandle !== bridgeProcessHandle || parameters.stream !== "stdout" && parameters.stream !== "stderr" || typeof parameters.deltaBase64 !== "string") {
18805
+ if (method !== "process/outputDelta" || !isRecord4(parameters) || parameters.processHandle !== bridgeProcessHandle || parameters.stream !== "stdout" && parameters.stream !== "stderr" || typeof parameters.deltaBase64 !== "string") {
18148
18806
  return false;
18149
18807
  }
18150
18808
  if (parameters.capReached === true) {
@@ -18249,7 +18907,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18249
18907
  return bridgeInitialization;
18250
18908
  };
18251
18909
  const threadIdFromParameters = (parameters) => {
18252
- if (!isRecord3(parameters)) return null;
18910
+ if (!isRecord4(parameters)) return null;
18253
18911
  const value = parameters.threadId ?? parameters.conversationId;
18254
18912
  return typeof value === "string" ? value : null;
18255
18913
  };
@@ -18264,9 +18922,9 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18264
18922
  threadIds: [threadId]
18265
18923
  })
18266
18924
  ).then((value) => {
18267
- const ownerships = isRecord3(value) && Array.isArray(value.threads) ? value.threads : null;
18925
+ const ownerships = isRecord4(value) && Array.isArray(value.threads) ? value.threads : null;
18268
18926
  const ownership = ownerships?.[0];
18269
- if (!ownerships || !isRecord3(ownership) || ownerships.length !== 1 || ownership.threadId !== threadId || ownership.owner !== "external" && ownership.owner !== "codex") {
18927
+ if (!ownerships || !isRecord4(ownership) || ownerships.length !== 1 || ownership.threadId !== threadId || ownership.owner !== "external" && ownership.owner !== "codex") {
18270
18928
  throw transportError("Thread ownership lookup returned an invalid result");
18271
18929
  }
18272
18930
  if (ownership.owner === "external") {
@@ -18302,7 +18960,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18302
18960
  if (method.startsWith("codexhost/")) return true;
18303
18961
  if (method === "thread/list") return true;
18304
18962
  if (method === "thread/start") {
18305
- return isRecord3(parameters) && typeof parameters.model === "string" && parameters.model.startsWith("codexhost/");
18963
+ return isRecord4(parameters) && typeof parameters.model === "string" && parameters.model.startsWith("codexhost/");
18306
18964
  }
18307
18965
  const threadId = threadIdFromParameters(parameters);
18308
18966
  if (threadId && knownExternalThreadIds.has(threadId)) return true;
@@ -18337,10 +18995,10 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18337
18995
  return shouldUseBridge(method, parameters) ? sendBridged() : sendDirect();
18338
18996
  };
18339
18997
  const publishDraftWorkspace = (parameters) => {
18340
- if (!isRecord3(parameters) || parameters.ephemeral === true) return;
18998
+ if (!isRecord4(parameters) || parameters.ephemeral === true) return;
18341
18999
  const cwd = parameters.cwd;
18342
19000
  if (typeof cwd !== "string" || cwd.length === 0) return;
18343
- const drafts = isRecord3(target2.__codexhostDraftWorkspacesV1) ? target2.__codexhostDraftWorkspacesV1 : {};
19001
+ const drafts = isRecord4(target2.__codexhostDraftWorkspacesV1) ? target2.__codexhostDraftWorkspacesV1 : {};
18344
19002
  drafts[hostId2] = cwd;
18345
19003
  Object.defineProperty(target2, "__codexhostDraftWorkspacesV1", {
18346
19004
  configurable: true,
@@ -18366,16 +19024,16 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18366
19024
  };
18367
19025
  const restoreConsumption = isolateConsumption(manager, discardExternalPrewarm);
18368
19026
  const routedPrewarm = (parameters, options) => {
18369
- const external = isRecord3(parameters) && parameters.ephemeral !== true && typeof parameters.model === "string" && parameters.model.startsWith("codexhost/");
19027
+ const external = isRecord4(parameters) && parameters.ephemeral !== true && typeof parameters.model === "string" && parameters.model.startsWith("codexhost/");
18370
19028
  const routedParameters = external ? { ...parameters, codexhostPrewarm: true } : parameters;
18371
19029
  const generation = prewarmGeneration;
18372
19030
  publishDraftWorkspace(routedParameters);
18373
19031
  const pending = shouldUseBridge("thread/start", routedParameters) ? routedSend("thread/start", routedParameters, options) : options === void 0 ? originalPrewarm.call(bridge, routedParameters) : originalPrewarm.call(bridge, routedParameters, options);
18374
- if (isRecord3(parameters) && parameters.ephemeral === true || typeof pending !== "object" && typeof pending !== "function" || pending === null || typeof Reflect.get(pending, "then") !== "function") {
19032
+ if (isRecord4(parameters) && parameters.ephemeral === true || typeof pending !== "object" && typeof pending !== "function" || pending === null || typeof Reflect.get(pending, "then") !== "function") {
18375
19033
  return pending;
18376
19034
  }
18377
19035
  return Promise.resolve(pending).then((result) => {
18378
- const threadId = external && isRecord3(result) && isRecord3(result.thread) && typeof result.thread.id === "string" ? result.thread.id : null;
19036
+ const threadId = external && isRecord4(result) && isRecord4(result.thread) && typeof result.thread.id === "string" ? result.thread.id : null;
18379
19037
  if (disposed || generation !== prewarmGeneration) {
18380
19038
  if (threadId) discardExternalPrewarm(threadId);
18381
19039
  throw new Error("Renderer draft prewarm was invalidated by a configuration change");
@@ -18389,7 +19047,7 @@ function createDraftPrewarmPolicyBridge(manager, bridge, hostId2, target2, prewa
18389
19047
  bridge.prewarmThreadStart = routedPrewarm;
18390
19048
  const routedWindowMessage = (event) => {
18391
19049
  const message = event.data;
18392
- if (!isRecord3(message) || message.type !== "mcp-notification" || message.hostId !== hostId2 || typeof message.method !== "string") {
19050
+ if (!isRecord4(message) || message.type !== "mcp-notification" || message.hostId !== hostId2 || typeof message.method !== "string") {
18393
19051
  return;
18394
19052
  }
18395
19053
  handleOuterNotification(message.method, message.params);
@@ -18871,15 +19529,15 @@ function installRendererExternalQueuePolicy(root, target2, dependencies) {
18871
19529
  const expression = message[1];
18872
19530
  if (!Array.isArray(expression) || expression.length !== 4 || expression[0] !== "pipeline")
18873
19531
  return message;
18874
- const [, importId, path5, args] = expression;
18875
- if (!Array.isArray(path5) || path5.length !== 1 || path5[0] !== "sendMessage" || !Array.isArray(args))
19532
+ const [, importId, path7, args] = expression;
19533
+ if (!Array.isArray(path7) || path7.length !== 1 || path7[0] !== "sendMessage" || !Array.isArray(args))
18876
19534
  return message;
18877
19535
  const input = args[0];
18878
19536
  if (!record4(input) || typeof input.conversationId !== "string" || !record4(input.message) || !dependencies.usesExternalQueue(store, input.conversationId))
18879
19537
  return message;
18880
19538
  return [
18881
19539
  "push",
18882
- ["pipeline", importId, path5, [{ ...input, queueModeOverride: "queue" }, ...args.slice(1)]]
19540
+ ["pipeline", importId, path7, [{ ...input, queueModeOverride: "queue" }, ...args.slice(1)]]
18883
19541
  ];
18884
19542
  };
18885
19543
  const port = dependencies.portPrototype;
@@ -18946,7 +19604,7 @@ function installRendererHostRpcRouting(root, target2, dependencies) {
18946
19604
  }
18947
19605
  };
18948
19606
  const sameConnection = (previous, current) => previous === void 0 ? current === void 0 : current?.owner === previous.owner && current.revision === previous.revision;
18949
- const isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19607
+ const isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18950
19608
  const externalDrafts = /* @__PURE__ */ new Map();
18951
19609
  const selectedModels = /* @__PURE__ */ new Map();
18952
19610
  const prewarmCarrier = (carrier) => {
@@ -18955,7 +19613,7 @@ function installRendererHostRpcRouting(root, target2, dependencies) {
18955
19613
  try {
18956
19614
  const json2 = carrier.slice(prefix.length).replace(/[a-f0-9]{2}/gu, (byte) => String.fromCharCode(Number.parseInt(byte, 16)));
18957
19615
  const route = JSON.parse(json2);
18958
- if (!isRecord3(route)) return null;
19616
+ if (!isRecord4(route)) return null;
18959
19617
  const payload = [...JSON.stringify({ ...route, prewarm: true })].map((character) => character.charCodeAt(0).toString(16).padStart(2, "0")).join("");
18960
19618
  return `${prefix}${payload}`;
18961
19619
  } catch {
@@ -18964,7 +19622,7 @@ function installRendererHostRpcRouting(root, target2, dependencies) {
18964
19622
  };
18965
19623
  const publishDraftWorkspace = (hostId2, cwd) => {
18966
19624
  if (typeof cwd !== "string" || cwd.length === 0) return;
18967
- const drafts = isRecord3(target2.__codexhostDraftWorkspacesV1) ? target2.__codexhostDraftWorkspacesV1 : {};
19625
+ const drafts = isRecord4(target2.__codexhostDraftWorkspacesV1) ? target2.__codexhostDraftWorkspacesV1 : {};
18968
19626
  if (drafts[hostId2] === cwd) return;
18969
19627
  drafts[hostId2] = cwd;
18970
19628
  Object.defineProperty(target2, "__codexhostDraftWorkspacesV1", {
@@ -18982,35 +19640,37 @@ function installRendererHostRpcRouting(root, target2, dependencies) {
18982
19640
  const expression = message[1];
18983
19641
  if (!Array.isArray(expression) || expression.length !== 4 || expression[0] !== "pipeline")
18984
19642
  return message;
18985
- const [, importId, path5, args] = expression;
18986
- if (!Array.isArray(path5) || path5.length !== 1 || !Array.isArray(args)) return message;
19643
+ const [, importId, path7, args] = expression;
19644
+ if (!Array.isArray(path7) || path7.length !== 1 || !Array.isArray(args)) return message;
18987
19645
  const [input, options] = args;
18988
- if (!isRecord3(input) || !isRecord3(input.collaborationMode)) return message;
19646
+ if (!isRecord4(input) || !isRecord4(input.collaborationMode)) return message;
18989
19647
  const settings = input.collaborationMode.settings;
18990
- if (!isRecord3(settings)) return message;
19648
+ if (!isRecord4(settings)) return message;
18991
19649
  const nativeModel = typeof settings.model === "string" ? settings.model : null;
18992
19650
  let model2 = null;
18993
- if (path5[0] === "startConversation") {
18994
- const draftId = isRecord3(options) ? options.clientThreadId : null;
19651
+ if (path7[0] === "startConversation") {
19652
+ const draftId = isRecord4(options) ? options.clientThreadId : null;
18995
19653
  model2 = typeof draftId === "string" ? externalDrafts.get(draftId)?.model ?? null : null;
18996
- } else if (path5[0] === "prewarmConversation") {
19654
+ } else if (path7[0] === "prewarmConversation") {
18997
19655
  if (input.ephemeral !== true) publishDraftWorkspace("local", input.cwd);
18998
19656
  const selected = selectedModels.get("local") ?? null;
18999
19657
  const carrier = nativeModel?.startsWith("codexhost/") ? nativeModel : selected;
19000
19658
  model2 = carrier ? prewarmCarrier(carrier) : null;
19001
19659
  }
19002
19660
  if (!model2) return message;
19003
- if (path5[0] === "startConversation" && nativeModel?.startsWith("codexhost/") && nativeModel !== model2)
19004
- return message;
19661
+ if (path7[0] === "startConversation" && nativeModel?.startsWith("codexhost/"))
19662
+ model2 = nativeModel;
19663
+ const config2 = input.config == null ? { model: model2 } : isRecord4(input.config) ? { model: model2, ...input.config } : input.config;
19005
19664
  return [
19006
19665
  "push",
19007
19666
  [
19008
19667
  "pipeline",
19009
19668
  importId,
19010
- path5,
19669
+ path7,
19011
19670
  [
19012
19671
  {
19013
19672
  ...input,
19673
+ ...path7[0] === "startConversation" ? { config: config2 } : {},
19014
19674
  collaborationMode: { ...input.collaborationMode, settings: { ...settings, model: model2 } }
19015
19675
  },
19016
19676
  ...args.slice(1)
@@ -19075,7 +19735,7 @@ function installRendererHostRpcRouting(root, target2, dependencies) {
19075
19735
  const onMessage = (event) => {
19076
19736
  const { source, data } = event;
19077
19737
  if (source != null && source !== target2) return;
19078
- if (!isRecord3(data) || data.type !== "mcp-notification" || data.hostId !== hostId2 || typeof data.method !== "string" || !accepted.has(data.method) || !isCurrent())
19738
+ if (!isRecord4(data) || data.type !== "mcp-notification" || data.hostId !== hostId2 || typeof data.method !== "string" || !accepted.has(data.method) || !isCurrent())
19079
19739
  return;
19080
19740
  listener({ method: data.method, params: data.params });
19081
19741
  };
@@ -20269,7 +20929,7 @@ async function installRendererRpcSteeringDirect(client, now = Date.now) {
20269
20929
  try {
20270
20930
  const needed = await client.evaluate(`(() => {
20271
20931
  const steering = window.__codexhostRpcSteeringV1;
20272
- if (steering && steering.controller.forHost === steering.forHost) return false;
20932
+ if (steering && (steering.owns?.() ?? steering.controller.forHost === steering.forHost)) return false;
20273
20933
  steering?.release();
20274
20934
  const routing=window.__codexhostHostRoutingV1;
20275
20935
  return ['local', ...(routing?.knownHostIds?.() ?? [])].some(id => routing?.forHost(id)?.manager.kind === 'main-process-rpc');
@@ -20372,18 +21032,533 @@ async function discoverAndInstall(client) {
20372
21032
  }
20373
21033
  }
20374
21034
 
20375
- // packages/desktop-control/src/renderer-cdp-control-session.ts
20376
- function isRecord2(value) {
20377
- return typeof value === "object" && value !== null && !Array.isArray(value);
20378
- }
20379
- function sleep(milliseconds) {
20380
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
21035
+ // packages/desktop-control/src/renderer-app-url.ts
21036
+ function parseCodexAppUrl(value) {
21037
+ try {
21038
+ const url2 = new URL(value);
21039
+ return url2.protocol === "app:" && url2.hostname === "-" ? url2 : null;
21040
+ } catch {
21041
+ return null;
21042
+ }
20381
21043
  }
20382
- function discoveryTimeoutSignal(timeoutMs, signal) {
20383
- const timeout = AbortSignal.timeout(timeoutMs);
20384
- return signal ? AbortSignal.any([timeout, signal]) : timeout;
21044
+ function isPrimaryRendererUrl(value) {
21045
+ const url2 = parseCodexAppUrl(value);
21046
+ return url2 !== null && url2.pathname === "/index.html" && url2.search === "" && url2.hash === "";
20385
21047
  }
20386
- function abortFailure(signal, fallback) {
21048
+ function isAvatarOverlayRendererUrl(value) {
21049
+ const url2 = parseCodexAppUrl(value);
21050
+ if (!url2) return false;
21051
+ if (url2.pathname === "/avatar-overlay.html") return true;
21052
+ return url2.pathname === "/index.html" && url2.searchParams.get("initialRoute") === "/avatar-overlay";
21053
+ }
21054
+ function isEligibleVoiceHostUrl(value) {
21055
+ return isPrimaryRendererUrl(value) || isAvatarOverlayRendererUrl(value);
21056
+ }
21057
+ function rendererVoiceHostDocumentGuardExpression() {
21058
+ return `(function(){try{
21059
+ if (window.top !== window) return false;
21060
+ var url = new URL(location.href);
21061
+ if (url.protocol !== "app:" || url.hostname !== "-") return false;
21062
+ if (url.pathname === "/avatar-overlay.html") return true;
21063
+ if (url.pathname !== "/index.html") return false;
21064
+ if (url.search === "" && url.hash === "") return true;
21065
+ return url.searchParams.get("initialRoute") === "/avatar-overlay";
21066
+ }catch(e){return false;}})()`;
21067
+ }
21068
+
21069
+ // packages/desktop-control/src/renderer-voice-host-binding.ts
21070
+ var RENDERER_VOICE_HOST_BINDING_NAME = "__codexhostVoiceHostBindingV1";
21071
+ var RENDERER_VOICE_HOST_CAPABILITY_GLOBAL = "__codexhostVoiceHostV1";
21072
+ var RENDERER_VOICE_HOST_DELIVER_GLOBAL = "__codexhostVoiceHostDeliverV1";
21073
+ var RENDERER_VOICE_HOST_PENDING_GLOBAL = "__codexhostVoiceHostPendingV1";
21074
+ var RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES = 256 * 1024;
21075
+ var RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS = 1e4;
21076
+ var RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS = 2e3;
21077
+ var RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS = 3e4;
21078
+ var RENDERER_VOICE_HOST_METHODS = [
21079
+ VOICE_SETTINGS_METHOD,
21080
+ VOICE_GATEWAY_STATUS_METHOD,
21081
+ REALTIME_CALL_METHOD
21082
+ ];
21083
+ var ALLOWED_METHODS = new Set(RENDERER_VOICE_HOST_METHODS);
21084
+ var STALE_CONTEXT = /uniqueContextId not found|Cannot find context with specified id|Execution context was destroyed|Cannot find default execution context/i;
21085
+ var UNAVAILABLE = "Local Host connection is unavailable";
21086
+ var UNKNOWN_OUTCOME = "Host request outcome is unknown. Do not retry automatically.";
21087
+ var RENDERER_VOICE_HOST_CLEANUP_UNCONFIRMED = "Original Host owner is unreachable; cleanup is unconfirmed. Do not retry automatically.";
21088
+ function isRecord2(value) {
21089
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21090
+ }
21091
+ function allowlistedStage(value) {
21092
+ return value === "config" || value === "request" || value === "transport" || value === "identity" || value === "cancel" ? value : void 0;
21093
+ }
21094
+ function isCreateOperation(method, params) {
21095
+ return method === REALTIME_CALL_METHOD && params.operation === "create";
21096
+ }
21097
+ function cleanupUnconfirmedError(error51) {
21098
+ if (error51 instanceof Error && error51.message === RENDERER_VOICE_HOST_CLEANUP_UNCONFIRMED && allowlistedStage(Reflect.get(error51, "stage")) === "cancel")
21099
+ return error51;
21100
+ }
21101
+ function rendererVoiceHostCapabilitySource(owner, generation) {
21102
+ const guard = rendererVoiceHostDocumentGuardExpression();
21103
+ return `(() => {
21104
+ if (!${guard}) return true;
21105
+ const binding = ${JSON.stringify(RENDERER_VOICE_HOST_BINDING_NAME)};
21106
+ const cap = ${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)};
21107
+ const deliver = ${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)};
21108
+ const pendingKey = ${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)};
21109
+ const allowed = ${JSON.stringify([...RENDERER_VOICE_HOST_METHODS])};
21110
+ const maxBytes = ${RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES};
21111
+ const ownerId = ${JSON.stringify(owner)};
21112
+ const generation = ${generation};
21113
+ const settingsTimeout = ${RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS};
21114
+ const gatewayTimeout = ${RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS};
21115
+ const realtimeTimeout = ${RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS};
21116
+ const pending = globalThis[pendingKey] instanceof Map ? globalThis[pendingKey] : new Map();
21117
+ globalThis[pendingKey] = pending;
21118
+ const unavailable = () => Promise.reject(new Error(${JSON.stringify(UNAVAILABLE)}));
21119
+ const settleWait = (wait, message) => {
21120
+ try { clearTimeout(wait.timer); } catch (e) {}
21121
+ try { wait.reject(new Error(message)); } catch (e) {}
21122
+ };
21123
+ const settleAll = (message) => {
21124
+ for (const [id, wait] of [...pending.entries()]) {
21125
+ pending.delete(id);
21126
+ settleWait(wait, message);
21127
+ }
21128
+ };
21129
+ const previous = globalThis[cap];
21130
+ if (previous && previous.generation !== generation) settleAll(${JSON.stringify(UNAVAILABLE)});
21131
+ globalThis[deliver] = (message) => {
21132
+ if (!message || typeof message !== "object" || typeof message.id !== "string") return;
21133
+ const wait = pending.get(message.id);
21134
+ if (!wait) return;
21135
+ pending.delete(message.id);
21136
+ try { clearTimeout(wait.timer); } catch (e) {}
21137
+ if (message.ok) {
21138
+ wait.resolve(message.result);
21139
+ return;
21140
+ }
21141
+ const error = new Error(
21142
+ typeof message.error === "string" && message.error.length > 0 && message.error.length <= 500
21143
+ ? message.error
21144
+ : "Host request failed",
21145
+ );
21146
+ if (typeof message.stage === "string") error.stage = message.stage;
21147
+ wait.reject(error);
21148
+ };
21149
+ Object.defineProperty(globalThis, cap, {
21150
+ configurable: true,
21151
+ value: Object.freeze({
21152
+ owner: ownerId,
21153
+ generation,
21154
+ request(method, params) {
21155
+ try {
21156
+ if (!${guard}) return unavailable();
21157
+ if (typeof method !== "string" || !allowed.includes(method)) return unavailable();
21158
+ const body = params !== null && typeof params === "object" && !Array.isArray(params) ? params : {};
21159
+ const id = crypto.randomUUID();
21160
+ const payload = JSON.stringify({ v: 1, id, owner: ownerId, generation, method, params: body });
21161
+ if (payload.length > maxBytes) return Promise.reject(new Error("Voice request is too large"));
21162
+ const timeoutMs =
21163
+ method === ${JSON.stringify(VOICE_GATEWAY_STATUS_METHOD)}
21164
+ ? gatewayTimeout
21165
+ : method === ${JSON.stringify(REALTIME_CALL_METHOD)}
21166
+ ? realtimeTimeout
21167
+ : settingsTimeout;
21168
+ return new Promise((resolve, reject) => {
21169
+ const timer = setTimeout(() => {
21170
+ if (!pending.has(id)) return;
21171
+ pending.delete(id);
21172
+ try {
21173
+ globalThis[binding](JSON.stringify({
21174
+ v: 1,
21175
+ id,
21176
+ owner: ownerId,
21177
+ generation,
21178
+ abandon: true,
21179
+ method,
21180
+ params: body,
21181
+ }));
21182
+ } catch (e) {}
21183
+ reject(new Error(${JSON.stringify(UNAVAILABLE)}));
21184
+ }, timeoutMs);
21185
+ pending.set(id, { resolve, reject, timer, generation });
21186
+ try {
21187
+ globalThis[binding](payload);
21188
+ } catch {
21189
+ pending.delete(id);
21190
+ try { clearTimeout(timer); } catch (e) {}
21191
+ reject(new Error(${JSON.stringify(UNAVAILABLE)}));
21192
+ }
21193
+ });
21194
+ } catch {
21195
+ return unavailable();
21196
+ }
21197
+ },
21198
+ }),
21199
+ });
21200
+ return true;
21201
+ })()`;
21202
+ }
21203
+ function evaluateResultValue(response) {
21204
+ if (!isRecord2(response) || isRecord2(response.exceptionDetails)) return;
21205
+ return isRecord2(response.result) ? response.result.value : void 0;
21206
+ }
21207
+ function callIdFromCreateResult(result) {
21208
+ if (!isRecord2(result) || !isRecord2(result.headers)) return;
21209
+ const location = result.headers.location;
21210
+ if (typeof location !== "string") return;
21211
+ const callId = realtimeCallIdFromLocation(location);
21212
+ return isRealtimeCallId(callId) ? callId : void 0;
21213
+ }
21214
+ async function cleanupAbandonedCreate(execution, params, result) {
21215
+ let unconfirmed;
21216
+ const note = (error51) => {
21217
+ unconfirmed ??= cleanupUnconfirmedError(error51);
21218
+ };
21219
+ const requestId2 = typeof params.requestId === "string" ? params.requestId : void 0;
21220
+ if (requestId2) {
21221
+ await execution.request(REALTIME_CALL_METHOD, { operation: "cancel", requestId: requestId2 }).catch(note);
21222
+ }
21223
+ const callId = callIdFromCreateResult(result);
21224
+ if (!callId) return unconfirmed;
21225
+ await execution.request(REALTIME_CALL_METHOD, { operation: "hangup", callId }).catch(note);
21226
+ return unconfirmed;
21227
+ }
21228
+ function captureExecution(host) {
21229
+ return host.bindExecution?.() ?? {
21230
+ generation: host.generation,
21231
+ request: (method, params) => host.request(method, params)
21232
+ };
21233
+ }
21234
+ async function readContextDocument(renderer, executionContextId) {
21235
+ try {
21236
+ const response = await renderer.command("Runtime.evaluate", {
21237
+ expression: "(function(){try{return {href:String(location.href),top:window.top===window};}catch(e){return {href:'',top:false};}})()",
21238
+ contextId: executionContextId,
21239
+ returnByValue: true
21240
+ });
21241
+ const value = evaluateResultValue(response);
21242
+ if (!isRecord2(value) || typeof value.href !== "string" || typeof value.top !== "boolean")
21243
+ return;
21244
+ return { href: value.href, top: value.top };
21245
+ } catch (error51) {
21246
+ if (error51 instanceof Error && STALE_CONTEXT.test(error51.message)) return;
21247
+ return;
21248
+ }
21249
+ }
21250
+ async function deliver(renderer, executionContextId, message) {
21251
+ const encoded = JSON.stringify(message);
21252
+ const payload = encoded.length > RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES ? JSON.stringify({
21253
+ id: message.id,
21254
+ ok: false,
21255
+ error: "Host request failed"
21256
+ }) : encoded;
21257
+ await renderer.command("Runtime.evaluate", {
21258
+ expression: `typeof globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}]==='function'&&globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}](${payload})`,
21259
+ contextId: executionContextId,
21260
+ returnByValue: true
21261
+ }).catch(() => void 0);
21262
+ }
21263
+ async function registerFutureScript(renderer, source, previousId) {
21264
+ if (previousId) {
21265
+ await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier: previousId }).catch(() => void 0);
21266
+ }
21267
+ const added = await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source });
21268
+ return isRecord2(added) && typeof added.identifier === "string" ? added.identifier : void 0;
21269
+ }
21270
+ async function removeFutureScript(renderer, identifier) {
21271
+ if (!identifier) return;
21272
+ await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => void 0);
21273
+ }
21274
+ async function installRendererVoiceHostBinding(renderer, host, options) {
21275
+ let disposed = false;
21276
+ let scriptId;
21277
+ let publishing = Promise.resolve();
21278
+ const inflight = /* @__PURE__ */ new Set();
21279
+ const works = /* @__PURE__ */ new Map();
21280
+ const abandonedIds = /* @__PURE__ */ new Set();
21281
+ const contexts = /* @__PURE__ */ new Map();
21282
+ const rememberContext = (params) => {
21283
+ if (!isRecord2(params) || !isRecord2(params.context)) return;
21284
+ const context = params.context;
21285
+ if (typeof context.id !== "number" || typeof context.uniqueId !== "string") return;
21286
+ const aux = isRecord2(context.auxData) ? context.auxData : void 0;
21287
+ contexts.set(context.id, {
21288
+ uniqueId: context.uniqueId,
21289
+ isDefault: aux?.isDefault === true
21290
+ });
21291
+ };
21292
+ const observeCleanupUnconfirmed = async (contextId, pageId, unconfirmed) => {
21293
+ if (!unconfirmed || disposed) return;
21294
+ await deliver(renderer, contextId, {
21295
+ id: pageId,
21296
+ ok: false,
21297
+ error: unconfirmed.message,
21298
+ stage: "cancel"
21299
+ });
21300
+ };
21301
+ const abandonWork = (item) => {
21302
+ if (item.abandoned) return;
21303
+ item.abandoned = true;
21304
+ if (!item.create) return;
21305
+ void cleanupAbandonedCreate(
21306
+ item.execution,
21307
+ { requestId: item.create.requestId, operation: "create" },
21308
+ item.create.result
21309
+ ).then((unconfirmed) => observeCleanupUnconfirmed(item.contextId, item.pageId, unconfirmed));
21310
+ };
21311
+ const abandonMatching = (contextId, uniqueId) => {
21312
+ for (const item of works.values()) {
21313
+ if (contextId !== void 0 && item.contextId === contextId || uniqueId !== void 0 && item.uniqueId === uniqueId)
21314
+ abandonWork(item);
21315
+ }
21316
+ };
21317
+ const forgetContext = (params) => {
21318
+ if (!isRecord2(params)) return;
21319
+ let contextId;
21320
+ let uniqueId;
21321
+ if (typeof params.executionContextId === "number") {
21322
+ contextId = params.executionContextId;
21323
+ uniqueId = contexts.get(contextId)?.uniqueId;
21324
+ contexts.delete(contextId);
21325
+ }
21326
+ if (typeof params.executionContextUniqueId === "string") {
21327
+ uniqueId = params.executionContextUniqueId;
21328
+ for (const [id, record4] of contexts)
21329
+ if (record4.uniqueId === uniqueId) {
21330
+ contextId = id;
21331
+ contexts.delete(id);
21332
+ }
21333
+ }
21334
+ abandonMatching(contextId, uniqueId);
21335
+ };
21336
+ const unsubscribeCreated = renderer.on("Runtime.executionContextCreated", rememberContext);
21337
+ const unsubscribeDestroyed = renderer.on("Runtime.executionContextDestroyed", forgetContext);
21338
+ const unsubscribeCleared = renderer.on("Runtime.executionContextsCleared", () => {
21339
+ contexts.clear();
21340
+ for (const item of works.values()) abandonWork(item);
21341
+ });
21342
+ const contextIsVerified = async (executionContextId, uniqueId) => {
21343
+ const tracked = contexts.get(executionContextId);
21344
+ if (!tracked?.isDefault || tracked.uniqueId !== uniqueId) return false;
21345
+ const document = await readContextDocument(renderer, executionContextId);
21346
+ const still = contexts.get(executionContextId);
21347
+ if (still?.uniqueId !== uniqueId || !still.isDefault) return false;
21348
+ if (!document?.top) return false;
21349
+ return isEligibleVoiceHostUrl(document.href);
21350
+ };
21351
+ const publishGeneration = async () => {
21352
+ if (disposed) return;
21353
+ const startedGeneration = host.generation;
21354
+ const source = rendererVoiceHostCapabilitySource(host.owner, startedGeneration);
21355
+ const addedId = await registerFutureScript(renderer, source, scriptId);
21356
+ if (disposed || host.generation !== startedGeneration) {
21357
+ await removeFutureScript(renderer, addedId);
21358
+ return;
21359
+ }
21360
+ scriptId = addedId;
21361
+ await renderer.evaluate(source);
21362
+ };
21363
+ const enqueuePublish = () => {
21364
+ publishing = publishing.catch(() => void 0).then(() => publishGeneration()).catch(() => void 0);
21365
+ };
21366
+ const cancelInflightCreates = () => {
21367
+ for (const item of works.values()) {
21368
+ if (!item.create || item.abandoned) continue;
21369
+ void item.execution.request(REALTIME_CALL_METHOD, { operation: "cancel", requestId: item.create.requestId }).catch(
21370
+ (error51) => observeCleanupUnconfirmed(item.contextId, item.pageId, cleanupUnconfirmedError(error51))
21371
+ );
21372
+ }
21373
+ };
21374
+ if (options?.enableRuntime !== false) await renderer.command("Runtime.enable");
21375
+ await renderer.command("Page.enable");
21376
+ await renderer.command("Runtime.addBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME });
21377
+ await publishGeneration();
21378
+ const refresh = () => {
21379
+ if (disposed) return;
21380
+ cancelInflightCreates();
21381
+ enqueuePublish();
21382
+ };
21383
+ const unsubscribeGeneration = host.onGenerationChange?.(refresh);
21384
+ const unsubscribe = renderer.on("Runtime.bindingCalled", (params) => {
21385
+ if (disposed || !isRecord2(params) || params.name !== RENDERER_VOICE_HOST_BINDING_NAME) return;
21386
+ if (typeof params.executionContextId !== "number" || typeof params.payload !== "string") return;
21387
+ if (params.payload.length > RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES) return;
21388
+ const contextId = params.executionContextId;
21389
+ const payloadText = params.payload;
21390
+ const startedGeneration = host.generation;
21391
+ const work = (async () => {
21392
+ let parsed;
21393
+ try {
21394
+ parsed = JSON.parse(payloadText);
21395
+ } catch {
21396
+ return;
21397
+ }
21398
+ if (!isRecord2(parsed) || parsed.v !== 1 || typeof parsed.id !== "string" || parsed.id.length === 0 || parsed.id.length > 128 || parsed.owner !== host.owner)
21399
+ return;
21400
+ const requestId2 = parsed.id;
21401
+ if (parsed.abandon === true) {
21402
+ const existing = works.get(requestId2);
21403
+ if (existing) abandonWork(existing);
21404
+ else abandonedIds.add(requestId2);
21405
+ return;
21406
+ }
21407
+ if (parsed.generation !== startedGeneration || parsed.generation !== host.generation || typeof parsed.method !== "string" || !isRecord2(parsed.params)) {
21408
+ await deliver(renderer, contextId, { id: requestId2, ok: false, error: UNAVAILABLE });
21409
+ return;
21410
+ }
21411
+ const tracked = contexts.get(contextId);
21412
+ if (!tracked?.isDefault) {
21413
+ return;
21414
+ }
21415
+ const uniqueId = tracked.uniqueId;
21416
+ const execution = captureExecution(host);
21417
+ const item = {
21418
+ pageId: requestId2,
21419
+ contextId,
21420
+ uniqueId,
21421
+ generation: startedGeneration,
21422
+ execution,
21423
+ abandoned: abandonedIds.has(requestId2),
21424
+ ...isCreateOperation(parsed.method, parsed.params) && typeof parsed.params.requestId === "string" ? { create: { requestId: parsed.params.requestId } } : {}
21425
+ };
21426
+ works.set(requestId2, item);
21427
+ abandonedIds.delete(requestId2);
21428
+ try {
21429
+ if (item.abandoned) {
21430
+ if (item.create)
21431
+ await observeCleanupUnconfirmed(
21432
+ contextId,
21433
+ requestId2,
21434
+ await cleanupAbandonedCreate(
21435
+ item.execution,
21436
+ { requestId: item.create.requestId, operation: "create" },
21437
+ item.create.result
21438
+ )
21439
+ );
21440
+ return;
21441
+ }
21442
+ const method = parsed.method;
21443
+ const requestParams = parsed.params;
21444
+ const verified = await contextIsVerified(contextId, uniqueId);
21445
+ const still = contexts.get(contextId);
21446
+ if (disposed || item.abandoned || host.generation !== startedGeneration || still?.uniqueId !== uniqueId) {
21447
+ if (item.create)
21448
+ await observeCleanupUnconfirmed(
21449
+ contextId,
21450
+ requestId2,
21451
+ await cleanupAbandonedCreate(item.execution, requestParams, item.create.result)
21452
+ );
21453
+ return;
21454
+ }
21455
+ if (!verified) {
21456
+ if (still?.isDefault)
21457
+ await deliver(renderer, contextId, { id: requestId2, ok: false, error: UNAVAILABLE });
21458
+ return;
21459
+ }
21460
+ if (!ALLOWED_METHODS.has(method)) {
21461
+ await deliver(renderer, contextId, { id: requestId2, ok: false, error: UNAVAILABLE });
21462
+ return;
21463
+ }
21464
+ try {
21465
+ const result = await item.execution.request(method, requestParams);
21466
+ if (item.create) item.create.result = result;
21467
+ const after = contexts.get(contextId);
21468
+ if (disposed || item.abandoned || host.generation !== startedGeneration || after?.uniqueId !== uniqueId) {
21469
+ if (item.create)
21470
+ await observeCleanupUnconfirmed(
21471
+ contextId,
21472
+ requestId2,
21473
+ await cleanupAbandonedCreate(item.execution, requestParams, result)
21474
+ );
21475
+ return;
21476
+ }
21477
+ await deliver(renderer, contextId, { id: requestId2, ok: true, result });
21478
+ } catch (error51) {
21479
+ const unconfirmed = cleanupUnconfirmedError(error51);
21480
+ if (unconfirmed && !disposed) {
21481
+ await deliver(renderer, contextId, {
21482
+ id: requestId2,
21483
+ ok: false,
21484
+ error: unconfirmed.message,
21485
+ stage: "cancel"
21486
+ });
21487
+ return;
21488
+ }
21489
+ if (disposed || item.abandoned || host.generation !== startedGeneration) return;
21490
+ const stage = error51 instanceof Error ? allowlistedStage(Reflect.get(error51, "stage")) : void 0;
21491
+ await deliver(renderer, contextId, {
21492
+ id: requestId2,
21493
+ ok: false,
21494
+ error: error51 instanceof Error && error51.message.length > 0 && error51.message.length <= 500 && !/bearer|token|authorization|sdp/i.test(error51.message) ? error51.message : "Host request failed",
21495
+ ...stage ? { stage } : {}
21496
+ });
21497
+ }
21498
+ } finally {
21499
+ works.delete(requestId2);
21500
+ }
21501
+ })();
21502
+ inflight.add(work);
21503
+ void work.finally(() => inflight.delete(work));
21504
+ });
21505
+ return () => {
21506
+ if (disposed) return;
21507
+ disposed = true;
21508
+ unsubscribeGeneration?.();
21509
+ unsubscribe();
21510
+ unsubscribeCreated();
21511
+ unsubscribeDestroyed();
21512
+ unsubscribeCleared();
21513
+ cancelInflightCreates();
21514
+ const outstanding = [...inflight];
21515
+ const leftover = [...works.values()];
21516
+ void Promise.allSettled(outstanding).then(async () => {
21517
+ for (const item of leftover)
21518
+ if (item.create)
21519
+ await observeCleanupUnconfirmed(
21520
+ item.contextId,
21521
+ item.pageId,
21522
+ await cleanupAbandonedCreate(
21523
+ item.execution,
21524
+ { requestId: item.create.requestId, operation: "create" },
21525
+ item.create.result
21526
+ )
21527
+ );
21528
+ });
21529
+ void removeFutureScript(renderer, scriptId);
21530
+ void renderer.command("Runtime.removeBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME }).catch(() => void 0);
21531
+ void renderer.evaluate(
21532
+ `(() => {
21533
+ const pending = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
21534
+ if (pending && typeof pending.forEach === "function") {
21535
+ for (const [id, wait] of [...pending.entries()]) {
21536
+ pending.delete(id);
21537
+ try { clearTimeout(wait.timer); } catch (e) {}
21538
+ try { wait.reject(new Error(${JSON.stringify(UNKNOWN_OUTCOME)})); } catch (e) {}
21539
+ }
21540
+ }
21541
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
21542
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}];
21543
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
21544
+ return true;
21545
+ })()`
21546
+ ).catch(() => void 0);
21547
+ };
21548
+ }
21549
+
21550
+ // packages/desktop-control/src/renderer-cdp-control-session.ts
21551
+ function isRecord3(value) {
21552
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21553
+ }
21554
+ function sleep(milliseconds) {
21555
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
21556
+ }
21557
+ function discoveryTimeoutSignal(timeoutMs, signal) {
21558
+ const timeout = AbortSignal.timeout(timeoutMs);
21559
+ return signal ? AbortSignal.any([timeout, signal]) : timeout;
21560
+ }
21561
+ function abortFailure(signal, fallback) {
20387
21562
  return signal.reason instanceof Error ? signal.reason : new Error(fallback);
20388
21563
  }
20389
21564
  function awaitWithSignal(promise2, signal, timeoutMessage) {
@@ -20426,24 +21601,6 @@ function sameAgents(actual, expected) {
20426
21601
  const expectedSet = new Set(expected);
20427
21602
  return actual.length === expected.length && actual.every((agent) => expectedSet.has(agent));
20428
21603
  }
20429
- function parseCodexAppUrl(value) {
20430
- try {
20431
- const url2 = new URL(value);
20432
- return url2.protocol === "app:" && url2.hostname === "-" ? url2 : null;
20433
- } catch {
20434
- return null;
20435
- }
20436
- }
20437
- function isPrimaryRendererUrl(value) {
20438
- const url2 = parseCodexAppUrl(value);
20439
- return url2 !== null && url2.pathname === "/index.html" && url2.search === "" && url2.hash === "";
20440
- }
20441
- function isAvatarOverlayRendererUrl(value) {
20442
- const url2 = parseCodexAppUrl(value);
20443
- if (!url2) return false;
20444
- if (url2.pathname === "/avatar-overlay.html") return true;
20445
- return url2.pathname === "/index.html" && url2.searchParams.get("initialRoute") === "/avatar-overlay";
20446
- }
20447
21604
  function selectPrimaryRendererTarget(targets, preferredTargetId) {
20448
21605
  const candidates = targets.filter(
20449
21606
  (target2) => target2.type === "page" && isPrimaryRendererUrl(target2.url)
@@ -20464,7 +21621,7 @@ var RendererAdapterReadinessError = class extends Error {
20464
21621
  reason;
20465
21622
  };
20466
21623
  function validateBindingStatus(value, expectedAgents) {
20467
- if (!isRecord2(value) || value.version !== 2 || !Array.isArray(value.enabledAgents) || value.enabledAgents.some((agent) => typeof agent !== "string") || !sameAgents(value.enabledAgents, expectedAgents) || !isRecord2(value.adapter)) {
21624
+ if (!isRecord3(value) || value.version !== 2 || !Array.isArray(value.enabledAgents) || value.enabledAgents.some((agent) => typeof agent !== "string") || !sameAgents(value.enabledAgents, expectedAgents) || !isRecord3(value.adapter)) {
20468
21625
  throw new Error("Production Renderer binding returned an invalid status");
20469
21626
  }
20470
21627
  if (value.adapter.state !== "ready" || typeof value.adapter.reason !== "string") {
@@ -20508,13 +21665,22 @@ async function waitForPrimaryTarget(endpoint, operations, timeoutMs, pollInterva
20508
21665
  const detail = lastError instanceof Error ? `: ${lastError.message}` : "";
20509
21666
  throw new Error(`Primary Codex Renderer CDP target did not become ready${detail}`);
20510
21667
  }
21668
+ async function bindRendererVoiceHost(renderer, voiceHost, disposals, options) {
21669
+ if (!voiceHost) return;
21670
+ disposals.get(renderer)?.();
21671
+ disposals.set(renderer, await installRendererVoiceHostBinding(renderer, voiceHost, options));
21672
+ }
21673
+ function unbindRendererVoiceHost(renderer, disposals) {
21674
+ disposals.get(renderer)?.();
21675
+ disposals.delete(renderer);
21676
+ }
20511
21677
  async function evaluateSource(renderer, source) {
20512
21678
  const response = await renderer.command("Runtime.evaluate", {
20513
21679
  expression: source,
20514
21680
  awaitPromise: true
20515
21681
  });
20516
- if (!isRecord2(response)) throw new Error("Renderer source evaluation returned an invalid result");
20517
- if (isRecord2(response.exceptionDetails)) {
21682
+ if (!isRecord3(response)) throw new Error("Renderer source evaluation returned an invalid result");
21683
+ if (isRecord3(response.exceptionDetails)) {
20518
21684
  throw new Error(
20519
21685
  cdpExceptionMessage(response.exceptionDetails, "Renderer source evaluation failed")
20520
21686
  );
@@ -20547,30 +21713,208 @@ async function waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs
20547
21713
  const detail = lastError instanceof Error ? `: ${lastError.message}` : "";
20548
21714
  throw new Error(`Production Renderer binding did not become ready${detail}`);
20549
21715
  }
20550
- async function overlayHookAlreadyEnabled(renderer) {
21716
+ var overlayInstallState = /* @__PURE__ */ new WeakMap();
21717
+ var OVERLAY_HOOK_SNAPSHOT_EXPRESSION = `(() => { /*__codexhostOverlayHookSnapshot*/
21718
+ const cpa = globalThis.${CPA_LIVE_VOICE_HOOK_GLOBAL};
21719
+ const native = globalThis.__codexhostNativeChatVoiceV1;
21720
+ const labels =
21721
+ typeof document !== "undefined" && document.querySelectorAll
21722
+ ? [...document.querySelectorAll("button")].map((button) =>
21723
+ (button.getAttribute("aria-label") || "").toLowerCase(),
21724
+ )
21725
+ : [];
21726
+ let call = "unknown";
21727
+ if (native && native.activeCall === true) call = "active";
21728
+ else if (labels.some((label) => label === "end voice" || label === "end voice chat"))
21729
+ call = "active";
21730
+ else if (native && native.activeCall === false) call = "idle";
21731
+ else if (labels.some((label) => label.includes("start voice"))) call = "idle";
21732
+ const isolated =
21733
+ cpa && typeof cpa === "object" && "isolatedQualification" in cpa
21734
+ ? cpa.isolatedQualification
21735
+ : undefined;
21736
+ return {
21737
+ enabled: Boolean(cpa && typeof cpa === "object" && cpa.enabled === true),
21738
+ revision: typeof cpa?.implementationRevision === "string" ? cpa.implementationRevision : null,
21739
+ isolatedPath:
21740
+ isolated && typeof isolated === "object" && typeof isolated.path === "string"
21741
+ ? isolated.path
21742
+ : null,
21743
+ isolatedPaths: (() => {
21744
+ if (!isolated || typeof isolated !== "object") return null;
21745
+ const listed = Array.isArray(isolated.paths)
21746
+ ? isolated.paths
21747
+ : typeof isolated.path === "string"
21748
+ ? [isolated.path]
21749
+ : [];
21750
+ const unique = ["chat", "work-codex", "work-grok"].filter((path) => listed.includes(path));
21751
+ return unique.length ? unique : null;
21752
+ })(),
21753
+ isolatedRun:
21754
+ isolated && typeof isolated === "object" && typeof isolated.run === "string"
21755
+ ? isolated.run
21756
+ : null,
21757
+ isolatedExpiresAt:
21758
+ isolated && typeof isolated === "object" && typeof isolated.expiresAt === "string"
21759
+ ? isolated.expiresAt
21760
+ : null,
21761
+ isolatedPlatform:
21762
+ isolated && typeof isolated === "object" && typeof isolated.desktopPlatform === "string"
21763
+ ? isolated.desktopPlatform
21764
+ : null,
21765
+ appPath: typeof cpa?.desktopAppPath === "string" ? cpa.desktopAppPath : null,
21766
+ call,
21767
+ };
21768
+ })()`;
21769
+ function overlaySourceDigest(source) {
21770
+ return createHash("sha256").update(source).digest("hex");
21771
+ }
21772
+ function emptyOverlaySnapshot(enabled, call = "unknown") {
21773
+ return {
21774
+ enabled,
21775
+ revision: null,
21776
+ isolatedPath: null,
21777
+ isolatedPaths: null,
21778
+ isolatedRun: null,
21779
+ isolatedExpiresAt: null,
21780
+ isolatedPlatform: null,
21781
+ appPath: null,
21782
+ call
21783
+ };
21784
+ }
21785
+ function overlayIdentityFromSource(source) {
21786
+ const needle = `globalThis.${CPA_LIVE_VOICE_HOOK_GLOBAL} = Object.freeze(`;
21787
+ const start = source.indexOf(needle);
21788
+ if (start < 0) return;
21789
+ const json2 = source.slice(start + needle.length);
21790
+ const end = json2.indexOf(");");
21791
+ if (end < 0) return;
20551
21792
  try {
20552
- const value = await renderer.evaluate(
20553
- `globalThis.${CPA_LIVE_VOICE_HOOK_GLOBAL}?.enabled === true`
20554
- );
20555
- return value === true;
21793
+ const parsed = JSON.parse(json2.slice(0, end));
21794
+ if (!isRecord3(parsed)) return;
21795
+ const isolated = parsed.isolatedQualification;
21796
+ return {
21797
+ enabled: parsed.enabled === true,
21798
+ revision: typeof parsed.implementationRevision === "string" ? parsed.implementationRevision : null,
21799
+ isolatedPath: isRecord3(isolated) && typeof isolated.path === "string" ? isolated.path : null,
21800
+ isolatedPaths: (() => {
21801
+ if (!isRecord3(isolated)) return null;
21802
+ const listed = Array.isArray(isolated.paths) ? isolated.paths : typeof isolated.path === "string" ? [isolated.path] : [];
21803
+ const unique = ["chat", "work-codex", "work-grok"].filter((path7) => listed.includes(path7));
21804
+ return unique.length ? unique : null;
21805
+ })(),
21806
+ isolatedRun: isRecord3(isolated) && typeof isolated.run === "string" ? isolated.run : null,
21807
+ isolatedExpiresAt: isRecord3(isolated) && typeof isolated.expiresAt === "string" ? isolated.expiresAt : null,
21808
+ isolatedPlatform: isRecord3(isolated) && typeof isolated.desktopPlatform === "string" ? isolated.desktopPlatform : null,
21809
+ appPath: typeof parsed.desktopAppPath === "string" ? parsed.desktopAppPath : null,
21810
+ call: "idle"
21811
+ };
20556
21812
  } catch {
20557
- return false;
21813
+ return;
20558
21814
  }
20559
21815
  }
20560
- async function installOverlayHook(target2, overlayHookSource, operations, signal) {
21816
+ function overlayIsolatedPaths(snapshot) {
21817
+ if (snapshot.isolatedPaths && snapshot.isolatedPaths.length > 0) return snapshot.isolatedPaths;
21818
+ return snapshot.isolatedPath ? [snapshot.isolatedPath] : null;
21819
+ }
21820
+ function overlayIdentitiesMatch(live, desired) {
21821
+ return live.enabled === true && live.revision === desired.revision && live.isolatedPath === desired.isolatedPath && JSON.stringify(overlayIsolatedPaths(live)) === JSON.stringify(overlayIsolatedPaths(desired)) && live.isolatedRun === desired.isolatedRun && live.isolatedExpiresAt === desired.isolatedExpiresAt && live.isolatedPlatform === desired.isolatedPlatform && live.appPath === desired.appPath;
21822
+ }
21823
+ function readOverlayHookSnapshot(value) {
21824
+ if (value === true) return emptyOverlaySnapshot(true);
21825
+ if (value === false || value == null) return emptyOverlaySnapshot(false);
21826
+ if (!isRecord3(value) || typeof value.enabled !== "boolean") return;
21827
+ const call = value.call === "active" || value.call === "idle" ? value.call : "unknown";
21828
+ return {
21829
+ enabled: value.enabled,
21830
+ revision: typeof value.revision === "string" ? value.revision : null,
21831
+ isolatedPath: typeof value.isolatedPath === "string" ? value.isolatedPath : null,
21832
+ isolatedPaths: Array.isArray(value.isolatedPaths) ? value.isolatedPaths.filter((path7) => typeof path7 === "string") : typeof value.isolatedPath === "string" ? [value.isolatedPath] : null,
21833
+ isolatedRun: typeof value.isolatedRun === "string" ? value.isolatedRun : null,
21834
+ isolatedExpiresAt: typeof value.isolatedExpiresAt === "string" ? value.isolatedExpiresAt : null,
21835
+ isolatedPlatform: typeof value.isolatedPlatform === "string" ? value.isolatedPlatform : null,
21836
+ appPath: typeof value.appPath === "string" ? value.appPath : null,
21837
+ call
21838
+ };
21839
+ }
21840
+ async function installOverlayHook(target2, overlayHookSource, overlayClients, operations, signal, overlayVoiceBootstrapSource, voiceHost, voiceHostDisposals) {
20561
21841
  const timeoutMessage = "Overlay hook installation timed out";
21842
+ const currentDocumentSource = overlayVoiceBootstrapSource ?? overlayHookSource;
21843
+ const desiredDigest = overlaySourceDigest(currentDocumentSource);
21844
+ const desiredIdentity = overlayIdentityFromSource(currentDocumentSource);
20562
21845
  const run = (operation) => runWithCdpSignal(signal, timeoutMessage, operation);
20563
- const renderer = await connectRendererTarget(target2, operations, signal, timeoutMessage);
21846
+ let renderer = overlayClients.get(target2.id);
21847
+ const registered = renderer !== void 0;
21848
+ renderer ??= await connectRendererTarget(target2, operations, signal, timeoutMessage);
21849
+ const connected = renderer;
20564
21850
  try {
20565
- await run(() => renderer.command("Runtime.enable"));
20566
- await run(() => renderer.command("Page.enable"));
20567
- if (await run(() => overlayHookAlreadyEnabled(renderer))) return;
20568
- await run(
20569
- () => renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: overlayHookSource })
21851
+ if (!registered) {
21852
+ if (voiceHost && voiceHostDisposals && !voiceHostDisposals.has(connected))
21853
+ await run(
21854
+ () => bindRendererVoiceHost(connected, voiceHost, voiceHostDisposals, { enableRuntime: false })
21855
+ );
21856
+ await run(() => connected.command("Runtime.enable"));
21857
+ await run(() => connected.command("Page.enable"));
21858
+ overlayClients.set(target2.id, connected);
21859
+ } else if (voiceHost && voiceHostDisposals && !voiceHostDisposals.has(connected)) {
21860
+ await run(
21861
+ () => bindRendererVoiceHost(connected, voiceHost, voiceHostDisposals, { enableRuntime: false })
21862
+ );
21863
+ }
21864
+ let inspected = true;
21865
+ const snapshot = readOverlayHookSnapshot(
21866
+ await run(async () => {
21867
+ try {
21868
+ return await connected.evaluate(OVERLAY_HOOK_SNAPSHOT_EXPRESSION);
21869
+ } catch {
21870
+ inspected = false;
21871
+ return void 0;
21872
+ }
21873
+ })
20570
21874
  );
20571
- await run(() => evaluateSource(renderer, overlayHookSource));
20572
- } finally {
20573
- renderer.close();
21875
+ const applied = overlayInstallState.get(connected);
21876
+ const identityMatches = inspected && desiredIdentity !== void 0 && snapshot !== void 0 && overlayIdentitiesMatch(snapshot, desiredIdentity);
21877
+ const digestMatches = applied?.currentDigest === desiredDigest;
21878
+ const currentMatches = inspected && snapshot?.enabled === true && identityMatches && digestMatches;
21879
+ const callKnownIdle = inspected && snapshot?.call === "idle";
21880
+ const futureDocumentMissing = !registered || applied?.futureDigest !== desiredDigest;
21881
+ if (futureDocumentMissing) {
21882
+ if (applied?.scriptId) {
21883
+ try {
21884
+ await run(
21885
+ () => connected.command("Page.removeScriptToEvaluateOnNewDocument", {
21886
+ identifier: applied.scriptId
21887
+ })
21888
+ );
21889
+ } catch {
21890
+ }
21891
+ }
21892
+ const added = await run(
21893
+ () => connected.command("Page.addScriptToEvaluateOnNewDocument", {
21894
+ source: currentDocumentSource
21895
+ })
21896
+ );
21897
+ const addedId = isRecord3(added) && typeof added.identifier === "string" ? added.identifier : void 0;
21898
+ overlayInstallState.set(connected, {
21899
+ futureDigest: desiredDigest,
21900
+ ...applied?.currentDigest ? { currentDigest: applied.currentDigest } : {},
21901
+ ...addedId ? { scriptId: addedId } : {}
21902
+ });
21903
+ }
21904
+ if (currentMatches) return;
21905
+ if (!callKnownIdle) return;
21906
+ await run(() => evaluateSource(connected, currentDocumentSource));
21907
+ const evaluated = overlayInstallState.get(connected);
21908
+ overlayInstallState.set(connected, {
21909
+ futureDigest: desiredDigest,
21910
+ currentDigest: desiredDigest,
21911
+ ...evaluated?.scriptId ? { scriptId: evaluated.scriptId } : {}
21912
+ });
21913
+ } catch (error51) {
21914
+ overlayClients.delete(target2.id);
21915
+ if (voiceHostDisposals) unbindRendererVoiceHost(connected, voiceHostDisposals);
21916
+ connected.close();
21917
+ throw error51;
20574
21918
  }
20575
21919
  }
20576
21920
  function isLocalThreadRenderer(target2) {
@@ -20636,7 +21980,7 @@ async function installLocalThreadRenderer(target2, source, enabledAgents, operat
20636
21980
  renderer.close();
20637
21981
  }
20638
21982
  }
20639
- async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, browserStyleClients, operations, signal) {
21983
+ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations, signal, voiceHost, voiceHostDisposals) {
20640
21984
  try {
20641
21985
  const targets = await awaitWithSignal(
20642
21986
  operations.listTargets(endpoint, signal),
@@ -20644,10 +21988,13 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
20644
21988
  "Auxiliary Renderer CDP target discovery timed out"
20645
21989
  );
20646
21990
  const liveTargets = new Set(targets.map((target2) => target2.id));
20647
- for (const [id, client] of browserStyleClients) {
20648
- if (!liveTargets.has(id)) {
20649
- client.close();
20650
- browserStyleClients.delete(id);
21991
+ for (const clients of [browserStyleClients, overlayClients]) {
21992
+ for (const [id, client] of clients) {
21993
+ if (!liveTargets.has(id)) {
21994
+ if (voiceHostDisposals) unbindRendererVoiceHost(client, voiceHostDisposals);
21995
+ client.close();
21996
+ clients.delete(id);
21997
+ }
20651
21998
  }
20652
21999
  }
20653
22000
  await Promise.allSettled([
@@ -20655,7 +22002,16 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
20655
22002
  (target2) => installBrowserAnnotationStyles(target2, browserStyleClients, operations, signal)
20656
22003
  ),
20657
22004
  ...overlayHookSource ? selectAvatarOverlayRendererTargets(targets).map(
20658
- (overlay) => installOverlayHook(overlay, overlayHookSource, operations, signal)
22005
+ (overlay) => installOverlayHook(
22006
+ overlay,
22007
+ overlayHookSource,
22008
+ overlayClients,
22009
+ operations,
22010
+ signal,
22011
+ overlayVoiceBootstrapSource,
22012
+ voiceHost,
22013
+ voiceHostDisposals
22014
+ )
20659
22015
  ) : [],
20660
22016
  ...targets.filter(isLocalThreadRenderer).map(
20661
22017
  (target2) => installLocalThreadRenderer(target2, rendererSource, enabledAgents, operations, signal)
@@ -20664,10 +22020,14 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
20664
22020
  } catch {
20665
22021
  }
20666
22022
  }
20667
- async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations) {
22023
+ async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, voiceHost, voiceHostDisposals) {
20668
22024
  const renderer = await operations.connect(target2.webSocketDebuggerUrl);
20669
22025
  let disposeModules;
20670
22026
  try {
22027
+ if (voiceHost && voiceHostDisposals)
22028
+ await bindRendererVoiceHost(renderer, voiceHost, voiceHostDisposals, {
22029
+ enableRuntime: false
22030
+ });
20671
22031
  disposeModules = await installRendererLoadedModules(renderer);
20672
22032
  await renderer.command("Page.enable");
20673
22033
  await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource });
@@ -20677,35 +22037,44 @@ async function installTarget(target2, rendererSource, enabledAgents, timeoutMs,
20677
22037
  return { renderer, snapshot: { target: target2, draftPrewarmPolicy, binding }, disposeModules };
20678
22038
  } catch (error51) {
20679
22039
  disposeModules?.();
22040
+ if (voiceHostDisposals) unbindRendererVoiceHost(renderer, voiceHostDisposals);
20680
22041
  renderer.close();
20681
22042
  throw error51;
20682
22043
  }
20683
22044
  }
20684
22045
  var InstalledRendererCdpControlSession = class {
20685
- constructor(renderer, rendererCdpEndpoint2, rendererSource, overlayHookSource, browserStyleClients, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot, disposeModules) {
22046
+ constructor(renderer, rendererCdpEndpoint2, rendererSource, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot, disposeModules, voiceHost, voiceHostDisposals) {
20686
22047
  this.renderer = renderer;
20687
22048
  this.rendererCdpEndpoint = rendererCdpEndpoint2;
20688
22049
  this.rendererSource = rendererSource;
20689
22050
  this.overlayHookSource = overlayHookSource;
22051
+ this.overlayVoiceBootstrapSource = overlayVoiceBootstrapSource;
20690
22052
  this.browserStyleClients = browserStyleClients;
22053
+ this.overlayClients = overlayClients;
20691
22054
  this.enabledAgents = enabledAgents;
20692
22055
  this.timeoutMs = timeoutMs;
20693
22056
  this.pollIntervalMs = pollIntervalMs;
20694
22057
  this.operations = operations;
20695
22058
  this.currentSnapshot = currentSnapshot;
20696
22059
  this.disposeModules = disposeModules;
22060
+ this.voiceHost = voiceHost;
22061
+ this.voiceHostDisposals = voiceHostDisposals;
20697
22062
  }
20698
22063
  renderer;
20699
22064
  rendererCdpEndpoint;
20700
22065
  rendererSource;
20701
22066
  overlayHookSource;
22067
+ overlayVoiceBootstrapSource;
20702
22068
  browserStyleClients;
22069
+ overlayClients;
20703
22070
  enabledAgents;
20704
22071
  timeoutMs;
20705
22072
  pollIntervalMs;
20706
22073
  operations;
20707
22074
  currentSnapshot;
20708
22075
  disposeModules;
22076
+ voiceHost;
22077
+ voiceHostDisposals;
20709
22078
  #closed = false;
20710
22079
  get snapshot() {
20711
22080
  return this.currentSnapshot;
@@ -20726,9 +22095,12 @@ var InstalledRendererCdpControlSession = class {
20726
22095
  this.enabledAgents,
20727
22096
  this.timeoutMs,
20728
22097
  this.pollIntervalMs,
20729
- this.operations
22098
+ this.operations,
22099
+ this.voiceHost,
22100
+ this.voiceHostDisposals
20730
22101
  );
20731
22102
  this.disposeModules();
22103
+ unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
20732
22104
  this.renderer.close();
20733
22105
  this.renderer = replacement.renderer;
20734
22106
  this.disposeModules = replacement.disposeModules;
@@ -20752,9 +22124,12 @@ var InstalledRendererCdpControlSession = class {
20752
22124
  this.enabledAgents,
20753
22125
  this.timeoutMs,
20754
22126
  this.pollIntervalMs,
20755
- this.operations
22127
+ this.operations,
22128
+ this.voiceHost,
22129
+ this.voiceHostDisposals
20756
22130
  );
20757
22131
  this.disposeModules();
22132
+ unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
20758
22133
  this.renderer.close();
20759
22134
  this.renderer = replacement.renderer;
20760
22135
  this.disposeModules = replacement.disposeModules;
@@ -20766,9 +22141,13 @@ var InstalledRendererCdpControlSession = class {
20766
22141
  this.rendererSource,
20767
22142
  this.enabledAgents,
20768
22143
  this.overlayHookSource,
22144
+ this.overlayVoiceBootstrapSource,
20769
22145
  this.browserStyleClients,
22146
+ this.overlayClients,
20770
22147
  this.operations,
20771
- discoveryTimeoutSignal(this.timeoutMs)
22148
+ discoveryTimeoutSignal(this.timeoutMs),
22149
+ this.voiceHost,
22150
+ this.voiceHostDisposals
20772
22151
  );
20773
22152
  return this.currentSnapshot;
20774
22153
  }
@@ -20785,9 +22164,17 @@ var InstalledRendererCdpControlSession = class {
20785
22164
  if (this.#closed) return;
20786
22165
  this.#closed = true;
20787
22166
  this.disposeModules();
22167
+ unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
20788
22168
  this.renderer.close();
20789
22169
  for (const client of this.browserStyleClients.values()) client.close();
20790
22170
  this.browserStyleClients.clear();
22171
+ for (const client of this.overlayClients.values()) {
22172
+ unbindRendererVoiceHost(client, this.voiceHostDisposals);
22173
+ client.close();
22174
+ }
22175
+ this.overlayClients.clear();
22176
+ for (const dispose of this.voiceHostDisposals.values()) dispose();
22177
+ this.voiceHostDisposals.clear();
20791
22178
  }
20792
22179
  };
20793
22180
  var defaultOperations = {
@@ -20813,42 +22200,440 @@ async function createRendererCdpControlSession(options) {
20813
22200
  void 0,
20814
22201
  options.signal
20815
22202
  );
22203
+ const voiceHostDisposals = /* @__PURE__ */ new Map();
20816
22204
  const installed = await installTarget(
20817
22205
  target2,
20818
22206
  options.rendererSource,
20819
22207
  enabledAgents,
20820
22208
  timeoutMs,
20821
22209
  pollIntervalMs,
20822
- operations
22210
+ operations,
22211
+ options.voiceHost,
22212
+ voiceHostDisposals
20823
22213
  );
20824
22214
  const browserStyleClients = /* @__PURE__ */ new Map();
22215
+ const overlayClients = /* @__PURE__ */ new Map();
20825
22216
  await installAuxiliaryRenderers(
20826
22217
  options.rendererCdpEndpoint,
20827
22218
  options.rendererSource,
20828
22219
  enabledAgents,
20829
22220
  options.overlayHookSource,
22221
+ options.overlayVoiceBootstrapSource,
20830
22222
  browserStyleClients,
22223
+ overlayClients,
20831
22224
  operations,
20832
- discoveryTimeoutSignal(timeoutMs, options.signal)
22225
+ discoveryTimeoutSignal(timeoutMs, options.signal),
22226
+ options.voiceHost,
22227
+ voiceHostDisposals
20833
22228
  );
20834
22229
  return new InstalledRendererCdpControlSession(
20835
22230
  installed.renderer,
20836
22231
  options.rendererCdpEndpoint,
20837
22232
  options.rendererSource,
20838
22233
  options.overlayHookSource,
22234
+ options.overlayVoiceBootstrapSource,
20839
22235
  browserStyleClients,
22236
+ overlayClients,
20840
22237
  enabledAgents,
20841
22238
  timeoutMs,
20842
22239
  pollIntervalMs,
20843
22240
  operations,
20844
22241
  installed.snapshot,
20845
- installed.disposeModules
22242
+ installed.disposeModules,
22243
+ options.voiceHost,
22244
+ voiceHostDisposals
20846
22245
  );
20847
22246
  }
20848
22247
  function installRendererCdpControlSession(options) {
20849
22248
  return createRendererCdpControlSession(options);
20850
22249
  }
20851
22250
 
22251
+ // packages/desktop-control/src/renderer-injection-skip.ts
22252
+ var SKIPPED_DESKTOP_VERSION_PREFIXES = ["26.1103.", "26.1106."];
22253
+ var HASHED_RENDERER_CANDIDATE_VERSION = "26.1106.51428";
22254
+ function rendererInjectionSkipReason(desktopVersion, platform = process.platform, options) {
22255
+ const version2 = desktopVersion?.trim();
22256
+ if (!version2) return null;
22257
+ if (platform === "darwin" && version2 === HASHED_RENDERER_CANDIDATE_VERSION) return null;
22258
+ if (SKIPPED_DESKTOP_VERSION_PREFIXES.some((prefix) => version2.startsWith(prefix))) {
22259
+ if (allowsIsolatedHashedInjection(version2, platform, options)) return null;
22260
+ return `Desktop ${version2} is skipped until hashed Renderer bindings are requalified`;
22261
+ }
22262
+ return null;
22263
+ }
22264
+ function suppliedIdentityConflicts(version2, platform, identity2) {
22265
+ if (!identity2) return false;
22266
+ if (identity2.desktopPlatform !== void 0 && identity2.desktopPlatform !== platform) return true;
22267
+ if (identity2.desktopVersion !== void 0 && identity2.desktopVersion.trim() !== version2) {
22268
+ return true;
22269
+ }
22270
+ return false;
22271
+ }
22272
+ function allowsIsolatedHashedInjection(version2, platform, options) {
22273
+ if (!options?.isolated || !options.identity) return false;
22274
+ if (suppliedIdentityConflicts(version2, platform, options.identity)) return false;
22275
+ if (version2 !== HASHED_RENDERER_CANDIDATE_VERSION) return false;
22276
+ if (platform !== "win32") return false;
22277
+ if (!isIsolatedVoiceQualification(options.isolated)) return false;
22278
+ if (isProductionDesktopAppPath(options.identity.appPath) || isProductionDesktopAppPath(options.isolated.appPath)) {
22279
+ return false;
22280
+ }
22281
+ return isolatedQualificationMatchesRuntime(options.isolated, {
22282
+ desktopPlatform: platform,
22283
+ desktopVersion: version2,
22284
+ ...options.identity.desktopBuild ? { desktopBuild: options.identity.desktopBuild } : {},
22285
+ ...options.identity.asarDigest ? { asarDigest: options.identity.asarDigest } : {},
22286
+ ...options.identity.appPath ? { appPath: options.identity.appPath } : {},
22287
+ ...options.identity.implementationRevision ? { implementationRevision: options.identity.implementationRevision } : {}
22288
+ });
22289
+ }
22290
+
22291
+ // packages/desktop-control/src/controller-voice-host.ts
22292
+ import path5 from "node:path";
22293
+
22294
+ // packages/desktop-control/src/host-client-channel.ts
22295
+ import { readdir, open } from "node:fs/promises";
22296
+ import { constants } from "node:fs";
22297
+ import path4 from "node:path";
22298
+ var VOICE_SETTINGS_TIMEOUT_MS = 1e4;
22299
+ var VOICE_GATEWAY_STATUS_TIMEOUT_MS = 2e3;
22300
+ var REALTIME_CALL_TIMEOUT_MS = 3e4;
22301
+ var VOICE_GATEWAY_STAGES = /* @__PURE__ */ new Set(["config", "request", "transport", "identity", "cancel"]);
22302
+ function voiceGatewayStage(value) {
22303
+ return typeof value === "string" && VOICE_GATEWAY_STAGES.has(value) ? value : void 0;
22304
+ }
22305
+ async function discoverHostClientChannel(directory) {
22306
+ const candidates = [];
22307
+ for (const name of await readdir(directory).catch(() => [])) {
22308
+ if (!/^host-\d+(?:-[0-9a-f-]+)?\.json$/u.test(name)) continue;
22309
+ try {
22310
+ const handle = await open(
22311
+ path4.join(directory, name),
22312
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)
22313
+ );
22314
+ try {
22315
+ const stat = await handle.stat();
22316
+ if (!stat.isFile() || stat.size > 4096 || process.platform !== "win32" && (stat.uid !== process.getuid?.() || (stat.mode & 63) !== 0))
22317
+ continue;
22318
+ const descriptor = clientChannelDescriptorSchema.parse(
22319
+ JSON.parse(await handle.readFile("utf8"))
22320
+ );
22321
+ process.kill(descriptor.pid, 0);
22322
+ candidates.push(descriptor);
22323
+ } finally {
22324
+ await handle.close();
22325
+ }
22326
+ } catch {
22327
+ }
22328
+ }
22329
+ return candidates.sort((a, b) => b.startedAt - a.startedAt)[0] ?? null;
22330
+ }
22331
+ var HostClientChannel = class {
22332
+ constructor(directory, descriptor, ensureOwner) {
22333
+ this.directory = directory;
22334
+ this.ensureOwner = ensureOwner;
22335
+ this.descriptor = descriptor;
22336
+ }
22337
+ directory;
22338
+ ensureOwner;
22339
+ descriptor;
22340
+ cursor;
22341
+ history = [];
22342
+ controller;
22343
+ retry;
22344
+ listeners = /* @__PURE__ */ new Set();
22345
+ stopped = false;
22346
+ online = false;
22347
+ generation = 0;
22348
+ ready = Promise.withResolvers();
22349
+ started = false;
22350
+ subscribe(listener, after) {
22351
+ listener({ type: "connection", online: this.online });
22352
+ const cursor = this.cursor;
22353
+ if (this.online && cursor) {
22354
+ const oldest = this.history[0]?.cursor.sequence ?? cursor.sequence + 1;
22355
+ const replay = after?.epoch === cursor.epoch && after.sequence >= oldest - 1 && after.sequence <= cursor.sequence;
22356
+ listener({ type: "hello", version: 1, cursor, reset: !replay });
22357
+ if (replay) {
22358
+ for (const event of this.history)
22359
+ if (event.cursor.sequence > after.sequence) listener(event);
22360
+ }
22361
+ }
22362
+ this.listeners.add(listener);
22363
+ return () => this.listeners.delete(listener);
22364
+ }
22365
+ publish(update) {
22366
+ for (const listener of this.listeners) {
22367
+ try {
22368
+ listener(update);
22369
+ } catch {
22370
+ this.listeners.delete(listener);
22371
+ }
22372
+ }
22373
+ }
22374
+ start() {
22375
+ if (!this.started) {
22376
+ this.started = true;
22377
+ void this.connect();
22378
+ }
22379
+ return this.ready.promise;
22380
+ }
22381
+ async connect() {
22382
+ if (this.stopped) return;
22383
+ const controller = new AbortController();
22384
+ this.controller = controller;
22385
+ this.generation++;
22386
+ let deadline;
22387
+ try {
22388
+ await this.ensureOwner?.();
22389
+ if (this.stopped) return;
22390
+ deadline = setTimeout(() => controller.abort(), 5e3);
22391
+ const descriptor = await discoverHostClientChannel(this.directory);
22392
+ if (!descriptor) throw new Error("Host unavailable");
22393
+ this.descriptor = descriptor;
22394
+ const url2 = new URL(`http://127.0.0.1:${descriptor.port}/v1/events`);
22395
+ if (this.cursor) {
22396
+ url2.searchParams.set("epoch", this.cursor.epoch);
22397
+ url2.searchParams.set("after", String(this.cursor.sequence));
22398
+ }
22399
+ const response = await fetch(url2, {
22400
+ redirect: "error",
22401
+ headers: { authorization: `Bearer ${descriptor.token}` },
22402
+ signal: controller.signal
22403
+ });
22404
+ clearTimeout(deadline);
22405
+ deadline = setTimeout(() => controller.abort(), 45e3);
22406
+ if (!response.ok || !response.body) throw new Error("Host event channel refused");
22407
+ const reader = response.body.getReader();
22408
+ const decoder = new TextDecoder();
22409
+ let buffer = "";
22410
+ for (; ; ) {
22411
+ const chunk = await reader.read();
22412
+ if (chunk.done) throw new Error("Host event channel ended");
22413
+ clearTimeout(deadline);
22414
+ deadline = setTimeout(() => controller.abort(), 45e3);
22415
+ buffer += decoder.decode(chunk.value, { stream: true });
22416
+ if (buffer.length > 256 * 1024) throw new Error("Host event frame exceeds limit");
22417
+ let end;
22418
+ while ((end = buffer.indexOf("\n")) !== -1) {
22419
+ const line = buffer.slice(0, end);
22420
+ buffer = buffer.slice(end + 1);
22421
+ if (!line.trim()) continue;
22422
+ const event = clientChannelEventSchema.parse(JSON.parse(line));
22423
+ if (event.type === "hello") {
22424
+ if (event.cursor.epoch !== descriptor.epoch)
22425
+ throw new Error("Host descriptor generation changed");
22426
+ if (event.reset || !this.cursor) {
22427
+ this.cursor = event.cursor;
22428
+ this.history = [];
22429
+ }
22430
+ this.online = true;
22431
+ this.ready.resolve(void 0);
22432
+ this.publish({ type: "connection", online: true });
22433
+ this.publish(event);
22434
+ } else {
22435
+ if (!this.cursor || event.cursor.epoch !== this.cursor.epoch || event.cursor.sequence !== this.cursor.sequence + 1)
22436
+ throw new Error("Host event sequence gap");
22437
+ this.cursor = event.cursor;
22438
+ this.history.push(event);
22439
+ if (this.history.length > 512) this.history.shift();
22440
+ this.publish(event);
22441
+ }
22442
+ }
22443
+ }
22444
+ } catch {
22445
+ this.ready.reject(new Error("Host event connection unavailable"));
22446
+ if (!this.stopped) {
22447
+ this.online = false;
22448
+ this.publish({ type: "connection", online: false });
22449
+ }
22450
+ } finally {
22451
+ clearTimeout(deadline);
22452
+ controller.abort();
22453
+ if (!this.stopped) {
22454
+ this.retry = setTimeout(() => {
22455
+ void this.connect();
22456
+ }, 1e3);
22457
+ this.retry.unref();
22458
+ }
22459
+ }
22460
+ }
22461
+ bindVoiceExecution() {
22462
+ const generation = this.generation;
22463
+ const port = this.descriptor.port;
22464
+ const token = this.descriptor.token;
22465
+ return {
22466
+ generation,
22467
+ request: (method, params) => this.post(
22468
+ "/v1/rpc",
22469
+ { method, params },
22470
+ method === VOICE_GATEWAY_STATUS_METHOD ? VOICE_GATEWAY_STATUS_TIMEOUT_MS : method === REALTIME_CALL_METHOD ? REALTIME_CALL_TIMEOUT_MS : VOICE_SETTINGS_TIMEOUT_MS,
22471
+ { port, token }
22472
+ )
22473
+ };
22474
+ }
22475
+ async post(route, body, timeoutMs = 12e4, bound) {
22476
+ if (!bound && (this.stopped || !this.online))
22477
+ throw new Error("CH is disconnected; reconnect before submitting an operation");
22478
+ const generation = this.generation;
22479
+ const port = bound?.port ?? this.descriptor.port;
22480
+ const token = bound?.token ?? this.descriptor.token;
22481
+ let response;
22482
+ let value;
22483
+ try {
22484
+ response = await fetch(`http://127.0.0.1:${port}${route}`, {
22485
+ redirect: "error",
22486
+ method: "POST",
22487
+ headers: {
22488
+ authorization: `Bearer ${token}`,
22489
+ "content-type": "application/json"
22490
+ },
22491
+ body: JSON.stringify(body),
22492
+ signal: AbortSignal.timeout(timeoutMs)
22493
+ });
22494
+ const parsed = await response.json();
22495
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
22496
+ throw new Error("Invalid Host reply");
22497
+ value = parsed;
22498
+ } catch (error51) {
22499
+ if (bound)
22500
+ throw Object.assign(new Error(RENDERER_VOICE_HOST_CLEANUP_UNCONFIRMED), {
22501
+ code: -32093,
22502
+ stage: "cancel"
22503
+ });
22504
+ if (error51 && typeof error51 === "object" && "stage" in error51) throw error51;
22505
+ throw Object.assign(
22506
+ new Error(
22507
+ "CH connection lost; operation outcome may be unknown. Do not retry automatically."
22508
+ ),
22509
+ { code: -32093 }
22510
+ );
22511
+ }
22512
+ if (!bound && (generation !== this.generation || !this.online || this.stopped))
22513
+ throw Object.assign(new Error("Obsolete Host reply; resynchronize after reconnecting"), {
22514
+ code: -32094
22515
+ });
22516
+ if (value.error || !response.ok) {
22517
+ const error51 = value.error;
22518
+ const data = error51 && typeof error51 === "object" && "data" in error51 ? error51.data : void 0;
22519
+ const stage = data && typeof data === "object" && data !== null && "stage" in data ? voiceGatewayStage(data.stage) : void 0;
22520
+ throw Object.assign(new Error(error51?.message ?? "Host request failed"), {
22521
+ code: error51?.code ?? -32603,
22522
+ ...stage ? { stage } : {}
22523
+ });
22524
+ }
22525
+ if (!Object.hasOwn(value, "result"))
22526
+ throw new Error("Invalid Host reply; operation outcome may be unknown");
22527
+ return value.result;
22528
+ }
22529
+ request(method, params) {
22530
+ return this.post(
22531
+ "/v1/rpc",
22532
+ { method, params },
22533
+ harnessInstallationRequestTimeoutMs(method, params) ?? 12e4
22534
+ );
22535
+ }
22536
+ requestVoiceSettings(params) {
22537
+ return this.post(
22538
+ "/v1/rpc",
22539
+ { method: VOICE_SETTINGS_METHOD, params },
22540
+ VOICE_SETTINGS_TIMEOUT_MS
22541
+ );
22542
+ }
22543
+ requestVoiceGatewayStatus() {
22544
+ return this.post(
22545
+ "/v1/rpc",
22546
+ { method: VOICE_GATEWAY_STATUS_METHOD, params: {} },
22547
+ VOICE_GATEWAY_STATUS_TIMEOUT_MS
22548
+ );
22549
+ }
22550
+ requestRealtimeCall(params) {
22551
+ return this.post("/v1/rpc", { method: REALTIME_CALL_METHOD, params }, REALTIME_CALL_TIMEOUT_MS);
22552
+ }
22553
+ get epoch() {
22554
+ return this.descriptor.epoch;
22555
+ }
22556
+ get channelGeneration() {
22557
+ return this.generation;
22558
+ }
22559
+ /** Options are opt-in; an older Host ignores them and returns full Turns. */
22560
+ async snapshot(threadId, options = {}) {
22561
+ const generation = this.generation;
22562
+ const snapshot = clientThreadSnapshotSchema.parse(
22563
+ await this.post("/v1/snapshot", { ...options, threadId })
22564
+ );
22565
+ if (snapshot.thread.id !== threadId || snapshot.interactions.some((request) => request.threadId !== threadId))
22566
+ throw new Error("Host snapshot belongs to another Thread");
22567
+ if (generation !== this.generation || !this.online || snapshot.cursor.epoch !== this.descriptor.epoch)
22568
+ throw Object.assign(new Error("Obsolete Host snapshot; resynchronize after reconnecting"), {
22569
+ code: -32094
22570
+ });
22571
+ return snapshot;
22572
+ }
22573
+ respond(input) {
22574
+ return this.post("/v1/respond", input);
22575
+ }
22576
+ close() {
22577
+ this.stopped = true;
22578
+ this.online = false;
22579
+ clearTimeout(this.retry);
22580
+ this.controller?.abort();
22581
+ this.publish({ type: "connection", online: false });
22582
+ this.listeners.clear();
22583
+ }
22584
+ };
22585
+
22586
+ // packages/desktop-control/src/controller-voice-host.ts
22587
+ var ControllerVoiceHost = class {
22588
+ constructor(channel) {
22589
+ this.channel = channel;
22590
+ this.generation = Math.max(1, channel.channelGeneration);
22591
+ channel.subscribe((update) => {
22592
+ if (update.type !== "connection") return;
22593
+ const next = Math.max(1, channel.channelGeneration);
22594
+ if (next === this.generation) return;
22595
+ this.generation = next;
22596
+ for (const listener of this.#listeners) listener();
22597
+ });
22598
+ }
22599
+ channel;
22600
+ owner = crypto.randomUUID();
22601
+ generation = 1;
22602
+ #listeners = /* @__PURE__ */ new Set();
22603
+ onGenerationChange(listener) {
22604
+ this.#listeners.add(listener);
22605
+ return () => this.#listeners.delete(listener);
22606
+ }
22607
+ bindExecution() {
22608
+ return this.channel.bindVoiceExecution();
22609
+ }
22610
+ request(method, params) {
22611
+ if (method === VOICE_SETTINGS_METHOD) return this.channel.requestVoiceSettings(params);
22612
+ if (method === VOICE_GATEWAY_STATUS_METHOD) return this.channel.requestVoiceGatewayStatus();
22613
+ if (method === REALTIME_CALL_METHOD) return this.channel.requestRealtimeCall(params);
22614
+ return Promise.reject(
22615
+ Object.assign(new Error("Voice method is not available"), { code: -32601 })
22616
+ );
22617
+ }
22618
+ close() {
22619
+ this.#listeners.clear();
22620
+ this.channel.close();
22621
+ }
22622
+ };
22623
+ async function connectControllerVoiceHost(dataDirectory) {
22624
+ const directory = path5.join(dataDirectory, "client-hosts");
22625
+ const descriptor = await discoverHostClientChannel(directory);
22626
+ if (!descriptor) return;
22627
+ const channel = new HostClientChannel(directory, descriptor);
22628
+ try {
22629
+ await channel.start();
22630
+ return new ControllerVoiceHost(channel);
22631
+ } catch {
22632
+ channel.close();
22633
+ return;
22634
+ }
22635
+ }
22636
+
20852
22637
  // packages/desktop-control/src/production-controller.ts
20853
22638
  var PRODUCTION_INSTALL_TIMEOUT_MS = 9e4;
20854
22639
  var RENDERER_CSP_BOOTSTRAP = "globalThis.__zod_globalConfig ??= {}; globalThis.__zod_globalConfig.jitless = true;";
@@ -20857,6 +22642,21 @@ var TRANSIENT_INSTALL_ATTEMPTS = 3;
20857
22642
  var TRANSIENT_INSTALL_RETRY_MS = 250;
20858
22643
  var RECOVERY_RETRY_INITIAL_MS = 3e4;
20859
22644
  var RECOVERY_RETRY_MAX_MS = 3e5;
22645
+ var REMOTE_CONNECTION_RECOVERY_INTERVAL_MS = 5e3;
22646
+ var SHUTDOWN_OPERATION_WAIT_MS = 3e3;
22647
+ async function settleWithin(promise2, milliseconds) {
22648
+ let timer;
22649
+ try {
22650
+ await Promise.race([
22651
+ promise2,
22652
+ new Promise((resolve) => {
22653
+ timer = setTimeout(resolve, milliseconds);
22654
+ })
22655
+ ]);
22656
+ } finally {
22657
+ clearTimeout(timer);
22658
+ }
22659
+ }
20860
22660
  var startupTraceStartedAt = Date.now();
20861
22661
  function startupTrace(stage, detail) {
20862
22662
  if (process.env.CODEXHOST_STARTUP_TRACE !== "1") return;
@@ -20899,6 +22699,7 @@ function parseDesktopControllerArguments(arguments_) {
20899
22699
  let rendererPath;
20900
22700
  let attachmentPort;
20901
22701
  let attachmentNonce;
22702
+ let hostDataDirectory;
20902
22703
  for (let index = 0; index < arguments_.length; index += 1) {
20903
22704
  const argument = arguments_[index];
20904
22705
  const value = arguments_[index + 1];
@@ -20914,8 +22715,8 @@ function parseDesktopControllerArguments(arguments_) {
20914
22715
  if (argument === "--renderer") {
20915
22716
  if (rendererPath !== void 0) throw new Error("--renderer may only be provided once");
20916
22717
  if (!value) throw new Error("--renderer requires a value");
20917
- if (!path4.isAbsolute(value)) throw new Error("--renderer must be an absolute path");
20918
- rendererPath = path4.normalize(value);
22718
+ if (!path6.isAbsolute(value)) throw new Error("--renderer must be an absolute path");
22719
+ rendererPath = path6.normalize(value);
20919
22720
  index += 1;
20920
22721
  continue;
20921
22722
  }
@@ -20942,6 +22743,14 @@ function parseDesktopControllerArguments(arguments_) {
20942
22743
  index += 1;
20943
22744
  continue;
20944
22745
  }
22746
+ if (argument === "--host-data") {
22747
+ if (hostDataDirectory !== void 0) throw new Error("--host-data may only be provided once");
22748
+ if (!value) throw new Error("--host-data requires a value");
22749
+ if (!path6.isAbsolute(value)) throw new Error("--host-data must be an absolute path");
22750
+ hostDataDirectory = path6.normalize(value);
22751
+ index += 1;
22752
+ continue;
22753
+ }
20945
22754
  throw new Error(`unknown Desktop Controller option: ${argument}`);
20946
22755
  }
20947
22756
  if (endpoint === void 0) throw new Error("--renderer-cdp-endpoint is required");
@@ -20952,7 +22761,8 @@ function parseDesktopControllerArguments(arguments_) {
20952
22761
  rendererCdpEndpoint: endpoint,
20953
22762
  rendererPath,
20954
22763
  attachmentPort,
20955
- attachmentNonce
22764
+ attachmentNonce,
22765
+ ...hostDataDirectory ? { hostDataDirectory } : {}
20956
22766
  };
20957
22767
  }
20958
22768
  function isTransientRendererInstallError(error51) {
@@ -20984,9 +22794,32 @@ async function installProductionSession(options, dependencies) {
20984
22794
  async function runDesktopController(options, signal, dependencies = defaultDependencies) {
20985
22795
  const now = dependencies.now ?? Date.now;
20986
22796
  let session;
22797
+ let voiceHost;
20987
22798
  let nextRecoveryAt = 0;
20988
22799
  let recoveryDelayMs = RECOVERY_RETRY_INITIAL_MS;
20989
- const bootstrap = cpaLiveVoiceHookBootstrap();
22800
+ const overlayDir = path6.dirname(options.rendererPath);
22801
+ const isolated = readVoiceIsolatedQualification(overlayDir);
22802
+ const qualification = readVoiceQualification(overlayDir);
22803
+ const desktopVersion = process.env.CODEXHOST_DESKTOP_VERSION?.trim();
22804
+ const desktopBuild = process.env.CODEXHOST_DESKTOP_BUILD?.trim();
22805
+ const asarDigest = process.env.CODEXHOST_DESKTOP_ASAR_DIGEST?.trim();
22806
+ const appPath = process.env.CODEXHOST_DESKTOP_APP_PATH?.trim();
22807
+ const skipReason = rendererInjectionSkipReason(
22808
+ process.env.CODEXHOST_DESKTOP_VERSION,
22809
+ process.platform,
22810
+ {
22811
+ ...isolated ? { isolated } : {},
22812
+ identity: {
22813
+ desktopPlatform: process.platform,
22814
+ ...desktopVersion ? { desktopVersion } : {},
22815
+ ...desktopBuild ? { desktopBuild } : {},
22816
+ ...asarDigest ? { asarDigest } : {},
22817
+ ...appPath ? { appPath } : {},
22818
+ ...qualification ? { implementationRevision: qualification.implementationRevision } : {}
22819
+ }
22820
+ }
22821
+ );
22822
+ const bootstrap = cpaLiveVoiceHookBootstrap(process.env, void 0, overlayDir);
20990
22823
  const status = createRendererStatusReporter(
20991
22824
  (document) => dependencies.publishStatus?.({
20992
22825
  ...document,
@@ -21009,18 +22842,30 @@ async function runDesktopController(options, signal, dependencies = defaultDepen
21009
22842
  status.installing();
21010
22843
  startupTrace("reading Renderer bundle");
21011
22844
  const rendererRead = dependencies.readRenderer(options.rendererPath);
21012
- const overlayPath = bootstrap ? path4.join(path4.dirname(options.rendererPath), "cpa-live-voice-hook.js") : void 0;
21013
- const [rendererSource, overlayBundle] = overlayPath ? await Promise.all([rendererRead, dependencies.readRenderer(overlayPath)]) : [await rendererRead, void 0];
22845
+ const overlayPath = bootstrap && cpaLiveVoiceOverlayHookAllowed(process.env, overlayDir) ? path6.join(overlayDir, "cpa-live-voice-hook.js") : void 0;
22846
+ const overlayBootstrapPath = overlayPath && overlayVoiceBootstrapPreferred(process.env, overlayDir) ? path6.join(overlayDir, "overlay-voice-bootstrap.js") : void 0;
22847
+ const [rendererSource, overlayBundle, overlayBootstrapBundle] = overlayPath ? await Promise.all([
22848
+ rendererRead,
22849
+ dependencies.readRenderer(overlayPath),
22850
+ overlayBootstrapPath ? dependencies.readRenderer(overlayBootstrapPath).catch(() => "") : Promise.resolve("")
22851
+ ]) : [await rendererRead, void 0, ""];
21014
22852
  if (rendererSource.trim().length === 0) throw new Error("production Renderer Bundle is empty");
21015
22853
  const overlayHookSource = bootstrap && overlayBundle && overlayBundle.trim().length > 0 ? `${RENDERER_CSP_BOOTSTRAP}
21016
22854
  ${bootstrap}${overlayBundle}` : void 0;
22855
+ const overlayVoiceBootstrapSource = overlayHookSource && overlayBootstrapBundle.trim().length > 0 ? `${RENDERER_CSP_BOOTSTRAP}
22856
+ ${bootstrap}${overlayBootstrapBundle}` : void 0;
21017
22857
  startupTrace("installing Renderer Session");
22858
+ if (!voiceHost && options.hostDataDirectory && !skipReason) {
22859
+ voiceHost = await connectControllerVoiceHost(options.hostDataDirectory);
22860
+ }
21018
22861
  const installed = await installProductionSession(
21019
22862
  {
21020
22863
  rendererCdpEndpoint: options.rendererCdpEndpoint,
21021
22864
  rendererSource: `${RENDERER_CSP_BOOTSTRAP}
21022
22865
  ${bootstrap}${rendererSource}`,
21023
22866
  ...overlayHookSource ? { overlayHookSource } : {},
22867
+ ...overlayVoiceBootstrapSource ? { overlayVoiceBootstrapSource } : {},
22868
+ ...voiceHost ? { voiceHost } : {},
21024
22869
  // External Agents are discovered from each target Host after installation.
21025
22870
  timeoutMs: PRODUCTION_INSTALL_TIMEOUT_MS,
21026
22871
  signal
@@ -21040,16 +22885,33 @@ ${bootstrap}${rendererSource}`,
21040
22885
  );
21041
22886
  return next;
21042
22887
  };
22888
+ let remoteRecovery;
22889
+ let nextRemoteRecoveryAt = 0;
22890
+ const restoreRemoteConnections = (current) => {
22891
+ if (signal.aborted || remoteRecovery || now() < nextRemoteRecoveryAt) return;
22892
+ nextRemoteRecoveryAt = now() + REMOTE_CONNECTION_RECOVERY_INTERVAL_MS;
22893
+ remoteRecovery = Promise.resolve().then(() => {
22894
+ if (!signal.aborted && session === current)
22895
+ return current.executeRenderer(
22896
+ remoteConnectionsExpression({ action: "session", operation: { kind: "hosts" } })
22897
+ );
22898
+ return void 0;
22899
+ }).catch(() => void 0).finally(() => {
22900
+ remoteRecovery = void 0;
22901
+ });
22902
+ };
21043
22903
  const resetSession = () => {
21044
22904
  session?.close();
21045
22905
  session = void 0;
21046
22906
  };
21047
22907
  const ensureSession = async () => {
22908
+ if (skipReason) throw new Error(skipReason);
21048
22909
  if (!session) session = await createSession();
21049
22910
  else await session.ensureInstalled();
21050
22911
  return session;
21051
22912
  };
21052
22913
  const recoverSession = async () => {
22914
+ if (skipReason) throw new Error(skipReason);
21053
22915
  try {
21054
22916
  const current = await ensureSession();
21055
22917
  recordRecoverySuccess();
@@ -21090,11 +22952,16 @@ ${bootstrap}${rendererSource}`,
21090
22952
  state: "compatible",
21091
22953
  issues: []
21092
22954
  });
22955
+ if (skipReason) {
22956
+ nextRecoveryAt = Number.POSITIVE_INFINITY;
22957
+ status.failed(new Error(skipReason));
22958
+ }
21093
22959
  await useSession(async () => {
21094
- if (session) return;
22960
+ if (session || skipReason) return;
21095
22961
  try {
21096
22962
  session = await createSession();
21097
22963
  recordRecoverySuccess();
22964
+ restoreRemoteConnections(session);
21098
22965
  } catch (error51) {
21099
22966
  startupTrace("initial Renderer Session unavailable", error51);
21100
22967
  session = void 0;
@@ -21107,15 +22974,17 @@ ${bootstrap}${rendererSource}`,
21107
22974
  await useSession(async () => {
21108
22975
  if (!session && now() < nextRecoveryAt) return;
21109
22976
  try {
21110
- await recoverSession();
22977
+ restoreRemoteConnections(await recoverSession());
21111
22978
  } catch {
21112
22979
  }
21113
22980
  });
21114
22981
  }
21115
22982
  } finally {
21116
22983
  await attachmentServer?.close();
21117
- await operation;
22984
+ await settleWithin(operation, SHUTDOWN_OPERATION_WAIT_MS);
21118
22985
  resetSession();
22986
+ voiceHost?.close();
22987
+ void operation.then(resetSession);
21119
22988
  }
21120
22989
  }
21121
22990