limixbot 0.3.28 → 0.3.30
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.
- package/dist/assets/{ActivityPanel-DWXoNPQ0.js → ActivityPanel-Ca93mwbG.js} +1 -1
- package/dist/assets/{App-AKtlUFTy.js → App-BNTTjhsV.js} +134 -133
- package/dist/assets/AppEventEditor-cfYkXfeJ.js +1 -0
- package/dist/assets/{BotSettingsDialog--VNs8Ujc.js → BotSettingsDialog-DSlyshDi.js} +2 -2
- package/dist/assets/BrowserPanel-KrCVA3c6.js +3 -0
- package/dist/assets/{BrowserProfilesManager-CYFWUNHq.js → BrowserProfilesManager-C-Vt0eJi.js} +1 -1
- package/dist/assets/CloudAddDialog-D6ATLiSR.js +1 -0
- package/dist/assets/{ComputerFilesPane-1v4DGO6R.js → ComputerFilesPane-DvNcD0u0.js} +1 -1
- package/dist/assets/ComputerPanel-BButaK92.js +2 -0
- package/dist/assets/{DataPanel-CTDfwsgJ.js → DataPanel-iOCJJ-ic.js} +1 -1
- package/dist/assets/{DesktopViewer-CRcjWYHe.js → DesktopViewer-DbEC8oPW.js} +1 -1
- package/dist/assets/{FilesView-GVsVwbHA.js → FilesView-tnqRwvfh.js} +2 -2
- package/dist/assets/{GrokMoveDialog-DV2CsI4-.js → GrokMoveDialog-DcD2N9NJ.js} +3 -3
- package/dist/assets/{InspectorPanel-CU7r0jNs.js → InspectorPanel-neNG3E93.js} +1 -1
- package/dist/assets/KeyboardShortcutsModal-CGzUNFhz.js +1 -0
- package/dist/assets/{LiveDesktop-D99l3t9X.js → LiveDesktop-DJnRvtY5.js} +1 -1
- package/dist/assets/LocalVmWorkspace-B4yOJABf.js +1 -0
- package/dist/assets/{MacLocalControl-DbgKqPjA.js → MacLocalControl-ClcDNzDl.js} +1 -1
- package/dist/assets/{MarkdownFilePreview-CgsVW_ti.js → MarkdownFilePreview-ufl-s03V.js} +1 -1
- package/dist/assets/{MenuMotion-BOUToDZz.js → MenuMotion-Dj4rtEj4.js} +1 -1
- package/dist/assets/NewBotDialog-BniS1lPX.js +1 -0
- package/dist/assets/PhoneAppDialog-CG3KQVI4.js +1 -0
- package/dist/assets/{PlacesRail-dslg5RRJ.js → PlacesRail-bn7tEIBM.js} +2 -2
- package/dist/assets/{PluginsPanel-BVLR1WAH.js → PluginsPanel-DHTTKAon.js} +5 -5
- package/dist/assets/{ProIntroduction-DDKnUNeq.js → ProIntroduction-uJD0s7Me.js} +1 -1
- package/dist/assets/{RemoteAgentSettingsPanel-B56P6Er4.js → RemoteAgentSettingsPanel-DCKwqq0d.js} +1 -1
- package/dist/assets/{RoomPanel-CqhmGYP1.js → RoomPanel-aIa7Diz1.js} +1 -1
- package/dist/assets/{RoutinesPage-BoC8z-Aj.js → RoutinesPage-CLHjhuBJ.js} +2 -2
- package/dist/assets/SettingsModal-Dx_ELHpv.js +19 -0
- package/dist/assets/ShareTeamDialog-BOzHCj2n.js +1 -0
- package/dist/assets/{SignedInSites-CpKq69sj.js → SignedInSites-C-nx8of8.js} +1 -1
- package/dist/assets/TeamLibraryPanel-Bp1ZcEZQ.js +1 -0
- package/dist/assets/TeamMapPage-BL5CHTBF.js +1 -0
- package/dist/assets/{TriggersPage-BY7Vq4y0.js → TriggersPage-BEHK5XH1.js} +1 -1
- package/dist/assets/{VisibilitySection-B9GJNaPh.js → VisibilitySection-DxR_98SK.js} +2 -2
- package/dist/assets/WebhookTrigger-DaoCLzsd.js +1 -0
- package/dist/assets/{WorksOnGrid-DbXKKR-y.js → WorksOnGrid-DrO1qcZh.js} +1 -1
- package/dist/assets/{abnfDiagram-YUKMZFIV-UeQ15ljp.js → abnfDiagram-YUKMZFIV-BcUIfOEe.js} +1 -1
- package/dist/assets/{activity-Rykx5lZJ.js → activity-BNFKxy1b.js} +1 -1
- package/dist/assets/{architectureDiagram-47P4ROYG-Cb42ilBV.js → architectureDiagram-47P4ROYG-C7ht62Bt.js} +1 -1
- package/dist/assets/{blockDiagram-E7TT5TSB-BF1yg64q.js → blockDiagram-E7TT5TSB-CaczmOHs.js} +1 -1
- package/dist/assets/{c4Diagram-CRA5TL53-VaNJpISp.js → c4Diagram-CRA5TL53-DSPaJBwh.js} +1 -1
- package/dist/assets/{calendar-days-kC634hX1.js → calendar-days-DU-aFzFs.js} +1 -1
- package/dist/assets/channel-BXNHTVIL.js +1 -0
- package/dist/assets/{chunk-2Q5K7J3B-NtXjlfnQ.js → chunk-2Q5K7J3B-D4erYHrR.js} +1 -1
- package/dist/assets/{chunk-5VM5RSS4-CYWCBb40.js → chunk-5VM5RSS4-D8syTc7K.js} +1 -1
- package/dist/assets/{chunk-7TKQ45FW-CTx1wLnU.js → chunk-7TKQ45FW-qZ8vN88Y.js} +1 -1
- package/dist/assets/{chunk-AW2ZBBNX-PDrwpbhk.js → chunk-AW2ZBBNX-COZ0RY0p.js} +1 -1
- package/dist/assets/{chunk-FVRAUYC3-CqIp8Ubp.js → chunk-FVRAUYC3-B9WP6gNL.js} +2 -2
- package/dist/assets/{chunk-HTAEGDNF-yA6riuIr.js → chunk-HTAEGDNF-DpLxKDYN.js} +1 -1
- package/dist/assets/{chunk-JWPE2WC7-DEE_S031.js → chunk-JWPE2WC7-CyI6_v_4.js} +1 -1
- package/dist/assets/{chunk-KQW6MTUR-QybxNtsY.js → chunk-KQW6MTUR-C3xLM0DV.js} +1 -1
- package/dist/assets/{chunk-XXDRQBXY-BjchQyqU.js → chunk-XXDRQBXY-C7oc9LKJ.js} +1 -1
- package/dist/assets/{classDiagram-v2-K4WV4PDN-DtOc8Abr.js → classDiagram-v2-K4WV4PDN-DtYcyxMZ.js} +1 -1
- package/dist/assets/{coins-D0wNJCPg.js → coins-C8BnHs7A.js} +1 -1
- package/dist/assets/{core-BPiVxfZh.js → core-CuBqcMgK.js} +1 -1
- package/dist/assets/{cose-bilkent-JH36ORCC-CWHsqn7M.js → cose-bilkent-JH36ORCC-BACClH_n.js} +1 -1
- package/dist/assets/{cynefin-EF2NZ3EQ-BqS-D9jN.js → cynefin-EF2NZ3EQ-DZo-gx9_.js} +1 -1
- package/dist/assets/{cynefinDiagram-3GCD6N5R-Fc51YETb.js → cynefinDiagram-3GCD6N5R-CB9Tufy-.js} +1 -1
- package/dist/assets/{dagre-W4DXFKR2-So1kz52t.js → dagre-W4DXFKR2-QmMefB-F.js} +1 -1
- package/dist/assets/{de-B1J17cai.js → de-BZ9nuzrz.js} +1 -1
- package/dist/assets/{diagram-2UJZ2QOL-DpdA_Lk0.js → diagram-2UJZ2QOL-BB9UdSXb.js} +1 -1
- package/dist/assets/{diagram-OVF4WLC6-BqSu7ih2.js → diagram-OVF4WLC6-BT1xV_u3.js} +1 -1
- package/dist/assets/{diagram-PFPMY2P6-BoM6YcIG.js → diagram-PFPMY2P6-Bb8Gcrwm.js} +1 -1
- package/dist/assets/{diagram-UMYRVEAY-B7wKoLi9.js → diagram-UMYRVEAY-CuhVtw_K.js} +1 -1
- package/dist/assets/{diagram-YEKJPTXX-BEXKw540.js → diagram-YEKJPTXX-BKeM2V-v.js} +1 -1
- package/dist/assets/{diagram-ZIFT7M5P-BAD7sJRi.js → diagram-ZIFT7M5P-CWJdSX39.js} +1 -1
- package/dist/assets/{ebnfDiagram-VR2GEFS7-DILoqvy-.js → ebnfDiagram-VR2GEFS7-CQt0qwgC.js} +1 -1
- package/dist/assets/{elk-IJKZMXRS-BHW-Cxin.js → elk-IJKZMXRS-DTpYboxu.js} +1 -1
- package/dist/assets/{erDiagram-O2IAPWRE-Blp0Wwq0.js → erDiagram-O2IAPWRE-CRmD7TiT.js} +1 -1
- package/dist/assets/es-BxLq0ePd.js +6 -0
- package/dist/assets/{file-up-CEuHjVBK.js → file-up-DA-MGVqh.js} +1 -1
- package/dist/assets/{flowDiagram-OXPTDLAJ-6SkVmYje.js → flowDiagram-OXPTDLAJ-C3OIuz51.js} +1 -1
- package/dist/assets/{fr-Dn65EJNi.js → fr-BoXnQ5F8.js} +1 -1
- package/dist/assets/{ganttDiagram-R7TSEDQI-DFDwj8QX.js → ganttDiagram-R7TSEDQI-DRztzQgb.js} +1 -1
- package/dist/assets/{gitGraphDiagram-XJZIOB7I-mtJG-sis.js → gitGraphDiagram-XJZIOB7I-DljlrTI8.js} +1 -1
- package/dist/assets/{hi-CHU0sl7u.js → hi-CcIxinfW.js} +1 -1
- package/dist/assets/{import-name-DmpyAnTM.js → import-name-D7OVVg4a.js} +1 -1
- package/dist/assets/{index-BPNGi-6U.js → index-Bt5WwBKC.js} +2 -2
- package/dist/assets/{index-6y27F-UC.js → index-C6I9mMp7.js} +1 -1
- package/dist/assets/{infoDiagram-5W2HQ5XZ-CmyXB17U.js → infoDiagram-5W2HQ5XZ-sZgtYSBR.js} +1 -1
- package/dist/assets/{ishikawaDiagram-K3B6WC7H-BKFtIESa.js → ishikawaDiagram-K3B6WC7H-C3hf18HZ.js} +1 -1
- package/dist/assets/it-I6t2VEkh.js +13 -0
- package/dist/assets/ja-XTlk5V47.js +13 -0
- package/dist/assets/{journeyDiagram-COXZFDF6-DuXMREdz.js → journeyDiagram-COXZFDF6-Cx7iVI1Y.js} +1 -1
- package/dist/assets/{kanban-definition-P3RFRI5V-B9mWvKdh.js → kanban-definition-P3RFRI5V-BCfPOAwE.js} +1 -1
- package/dist/assets/ko-BplWTKGd.js +13 -0
- package/dist/assets/{mcp-servers-B3q18o5s.js → mcp-servers-byTznZvJ.js} +1 -1
- package/dist/assets/{mermaid.core-3c-Lql2y.js → mermaid.core-u5mM9R6c.js} +4 -4
- package/dist/assets/{mindmap-definition-LZFPQGKD-BmLt9bkD.js → mindmap-definition-LZFPQGKD-Bl1ss-w7.js} +1 -1
- package/dist/assets/{minimize-BfKI3Nbu.js → minimize-CQhJEKJt.js} +1 -1
- package/dist/assets/{monitor-C-EBTsrK.js → monitor-DUalxLhV.js} +1 -1
- package/dist/assets/{new-bot-CfgTtkz8.js → new-bot-B_nigkqj.js} +1 -1
- package/dist/assets/{org-library-CUElcBwL.js → org-library-tjVQPsZw.js} +1 -1
- package/dist/assets/{package-format-BFiYSYhD.js → package-format-TOf-oPLr.js} +1 -1
- package/dist/assets/{pegDiagram-BGZESJAR-5w1MTtLg.js → pegDiagram-BGZESJAR-DYVS4bK_.js} +1 -1
- package/dist/assets/{pieDiagram-CAPJLFHJ-C4etNvsK.js → pieDiagram-CAPJLFHJ-Dd2OI03J.js} +1 -1
- package/dist/assets/pl-Bv2R8H4r.js +13 -0
- package/dist/assets/{pt-br-BtcqPDCE.js → pt-br-CM02ONwa.js} +1 -1
- package/dist/assets/{quadrantDiagram-GDMTTRAM-k4cDUeIN.js → quadrantDiagram-GDMTTRAM-DftvCum7.js} +1 -1
- package/dist/assets/{rail-C6qkoJbO.js → rail-5xabqdtQ.js} +1 -1
- package/dist/assets/{railroadDiagram-SM67HX2B-B9d0qasL.js → railroadDiagram-SM67HX2B-CMUXYZoX.js} +1 -1
- package/dist/assets/{remote-desktop-panel-BfQEsoFh.js → remote-desktop-panel-CnvMPI4j.js} +1 -1
- package/dist/assets/{requirementDiagram-X7JNWC4A-BlYV4z86.js → requirementDiagram-X7JNWC4A-TUFFobBi.js} +1 -1
- package/dist/assets/ru-CJcyvxC6.js +13 -0
- package/dist/assets/{sankeyDiagram-UM26HJRW-DaIVWJEd.js → sankeyDiagram-UM26HJRW-BoWUtM1O.js} +1 -1
- package/dist/assets/{sequenceDiagram-ZO4K6R2Y-CAnXpud0.js → sequenceDiagram-ZO4K6R2Y-BJGhu1J3.js} +1 -1
- package/dist/assets/{sizeCapture-INFHLROL-BIeqIcHi.js → sizeCapture-INFHLROL-BjWOwFei.js} +1 -1
- package/dist/assets/{stateDiagram-v2-TBUQTH76-7ql5dn9y.js → stateDiagram-v2-TBUQTH76-BHnqACBE.js} +1 -1
- package/dist/assets/styles-BxpHDI63.css +1 -0
- package/dist/assets/{styles-BRMaHK08.js → styles-DnwnyZpR.js} +1 -1
- package/dist/assets/{swimlanes-N4OXWK64-CItt-UlU.js → swimlanes-N4OXWK64-w7Jh9mLp.js} +1 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-zIHpuU63.js +8 -0
- package/dist/assets/{team-share-2OjfOHsk.js → team-share-iEP9Zjr-.js} +1 -1
- package/dist/assets/{timeline-definition-YOQAKGHF-8Xn9QBNo.js → timeline-definition-YOQAKGHF-D0trOSBD.js} +1 -1
- package/dist/assets/{tr-3Jw0E4fc.js → tr-CTl25e95.js} +1 -1
- package/dist/assets/{uk-B_Q6nXm0.js → uk-B_psMXqm.js} +1 -1
- package/dist/assets/{usecaseDiagram-VIAY4XPW-B6LxotkO.js → usecaseDiagram-VIAY4XPW-A_NiPbx_.js} +1 -1
- package/dist/assets/{vennDiagram-BLWOH2XV-Ciex0LDC.js → vennDiagram-BLWOH2XV-iEyMv06N.js} +1 -1
- package/dist/assets/{wardleyDiagram-YMQ3BMBF-B_TbpQlN.js → wardleyDiagram-YMQ3BMBF-yIcnyDG1.js} +1 -1
- package/dist/assets/{xychartDiagram-TAQBALBS-Dz_iIYt1.js → xychartDiagram-TAQBALBS-BbKfuPA4.js} +1 -1
- package/dist/assets/zh-BPHbGe7C.js +13 -0
- package/dist/assets/{zh-tw-CWDGum-b.js → zh-tw-BMYbS8NC.js} +1 -1
- package/dist/index.html +3 -3
- package/dist/rail.html +5 -5
- package/dist-server/container-mcp.js +4 -4
- package/dist-server/index.js +3047 -3002
- package/dist-server/openmausbot.js +312 -311
- package/dist-server/package.json +1 -1
- package/dist-server/pair-cli.js +312 -311
- package/dist-server/server/config.js +4 -0
- package/dist-server/server/container-computer.js +73 -4
- package/dist-server/server/drivers/chatgpt-plan-auth.js +1 -1
- package/dist-server/server/harness/registry.js +8 -3
- package/dist-server/server/index.js +11 -8
- package/dist-server/server/limix-bot-library.js +9 -6
- package/dist-server/server/limix-skill-requirements.js +324 -0
- package/dist-server/server/limix-vm-capacity.js +64 -0
- package/dist-server/server/local-vm-settings.js +10 -3
- package/dist-server/server/routes/bot-skills.js +11 -0
- package/dist-server/server/routes/computers.js +12 -13
- package/dist-server/server/routes/instances.js +12 -2
- package/dist-server/shared/limix-vm-capacity.js +1 -0
- package/dist-server/vps-container-mcp.js +4 -4
- package/dist-server/workspace-backup.worker.js +3 -3
- package/package.json +1 -1
- package/dist/assets/AppEventEditor-BbiQKfDF.js +0 -1
- package/dist/assets/BrowserPanel-BL-QulSx.js +0 -3
- package/dist/assets/CloudAddDialog-CIQAIQtu.js +0 -1
- package/dist/assets/ComputerPanel-qgolre5n.js +0 -2
- package/dist/assets/KeyboardShortcutsModal-CwzNonqy.js +0 -1
- package/dist/assets/LocalVmWorkspace-QFZ4nJ8z.js +0 -1
- package/dist/assets/NewBotDialog-DjykSVLq.js +0 -1
- package/dist/assets/PhoneAppDialog-BPplMkUl.js +0 -1
- package/dist/assets/SettingsModal-Tet7aBPK.js +0 -19
- package/dist/assets/ShareTeamDialog-ovqh9ly2.js +0 -1
- package/dist/assets/TeamLibraryPanel-B5OwB3qN.js +0 -1
- package/dist/assets/TeamMapPage-BGCgxtM7.js +0 -1
- package/dist/assets/WebhookTrigger-BfyyC34L.js +0 -1
- package/dist/assets/channel-Di74R1Kh.js +0 -1
- package/dist/assets/es-CS_V7OdX.js +0 -6
- package/dist/assets/it-CbDr93sA.js +0 -13
- package/dist/assets/ja-CJbW-M3a.js +0 -13
- package/dist/assets/ko-ZQvzPil_.js +0 -13
- package/dist/assets/pl-tZIDksyW.js +0 -13
- package/dist/assets/ru-Bfcy52OT.js +0 -13
- package/dist/assets/styles-Di_mG4l3.css +0 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-DAZsljU6.js +0 -8
- package/dist/assets/zh-BwjuB8Xo.js +0 -13
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { availableParallelism, totalmem } from "node:os";
|
|
2
|
+
const GIB = 1024 ** 3;
|
|
3
|
+
const TTL_MS = 30_000;
|
|
4
|
+
let machine = null;
|
|
5
|
+
let cached = null;
|
|
6
|
+
let generation = 0;
|
|
7
|
+
let startQueue = Promise.resolve();
|
|
8
|
+
export function serializeLimixVmStart(work) {
|
|
9
|
+
const next = startQueue.then(work, work);
|
|
10
|
+
startQueue = next.catch(() => undefined);
|
|
11
|
+
return next;
|
|
12
|
+
}
|
|
13
|
+
export function calculateLimixVmCapacity(host, resources) {
|
|
14
|
+
const reservedMemoryGb = Math.min(host.memoryGb, Math.max(2, host.memoryGb * 0.2));
|
|
15
|
+
const reservedCpus = Math.min(host.cpus, Math.max(1, Math.ceil(host.cpus * 0.1)));
|
|
16
|
+
const memorySlots = Math.max(0, Math.floor((host.memoryGb - reservedMemoryGb) / resources.memoryGb));
|
|
17
|
+
const cpuSlots = Math.max(0, Math.floor((host.cpus - reservedCpus) / resources.cpus));
|
|
18
|
+
return {
|
|
19
|
+
limit: Math.min(memorySlots, cpuSlots), source: host.source,
|
|
20
|
+
memoryGb: host.memoryGb, cpus: host.cpus, reservedMemoryGb, reservedCpus,
|
|
21
|
+
perVmMemoryGb: resources.memoryGb, perVmCpus: resources.cpus,
|
|
22
|
+
constrainedBy: memorySlots <= cpuSlots ? "memory" : "cpu",
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function limixVmCapacity(resources) {
|
|
26
|
+
return calculateLimixVmCapacity(machine ?? { memoryGb: totalmem() / GIB, cpus: availableParallelism(), source: "host" }, resources);
|
|
27
|
+
}
|
|
28
|
+
export function parseLimixRuntimeResources(runtime, raw) {
|
|
29
|
+
try {
|
|
30
|
+
const info = JSON.parse(raw);
|
|
31
|
+
const memory = Number(runtime === "podman" ? info.host?.memTotal : info.MemTotal);
|
|
32
|
+
const cpus = Number(runtime === "podman" ? info.host?.cpus : info.NCPU);
|
|
33
|
+
if (!Number.isFinite(memory) || !Number.isFinite(cpus) || memory <= 0 || cpus < 1 || runtime === "container")
|
|
34
|
+
return null;
|
|
35
|
+
return { memoryGb: memory / GIB, cpus: Math.floor(cpus), source: runtime };
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function refreshLimixVmCapacity(runtime, runner) {
|
|
42
|
+
if (!runtime) {
|
|
43
|
+
generation++;
|
|
44
|
+
machine = null;
|
|
45
|
+
cached = null;
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (cached?.runtime === runtime && cached.expires > Date.now())
|
|
49
|
+
return cached.pending;
|
|
50
|
+
if (cached?.runtime !== runtime)
|
|
51
|
+
machine = null;
|
|
52
|
+
const current = ++generation;
|
|
53
|
+
const pending = (async () => {
|
|
54
|
+
try {
|
|
55
|
+
const result = await runner(runtime, ["info", "--format", runtime === "podman" ? "json" : "{{json .}}"], 5000);
|
|
56
|
+
const detected = parseLimixRuntimeResources(runtime, result.stdout);
|
|
57
|
+
if (detected && current === generation)
|
|
58
|
+
machine = detected;
|
|
59
|
+
}
|
|
60
|
+
catch { }
|
|
61
|
+
})();
|
|
62
|
+
cached = { runtime, expires: Date.now() + TTL_MS, pending };
|
|
63
|
+
await pending;
|
|
64
|
+
}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
// The Local VM's settings, read from the config the server loaded.
|
|
2
2
|
import { z } from "zod";
|
|
3
|
+
import { limixVmCapacity } from "./limix-vm-capacity.js";
|
|
3
4
|
import { DEFAULT_DESKTOP_RESOURCES, MAX_DESKTOP_CPUS, MAX_DESKTOP_MEMORY_GB, MIN_DESKTOP_CPUS, MIN_DESKTOP_MEMORY_GB, } from "./container-limits.js";
|
|
4
5
|
export const DEFAULT_LOCAL_VM_MODE = "shared";
|
|
5
6
|
export const DEFAULT_LOCAL_VM_MAX_INSTANCES = 2;
|
|
6
7
|
export const MIN_LOCAL_VM_MAX_INSTANCES = 1;
|
|
7
|
-
export const MAX_LOCAL_VM_MAX_INSTANCES =
|
|
8
|
+
export const MAX_LOCAL_VM_MAX_INSTANCES = 1024;
|
|
8
9
|
export const DEFAULT_LOCAL_VM_IDLE_TIMEOUT_MINUTES = 480;
|
|
9
10
|
export const MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES = 5;
|
|
10
11
|
export const MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES = 1_440;
|
|
11
|
-
/** Bot desktop isolation, default "shared"; `maxInstances`
|
|
12
|
+
/** Bot desktop isolation, default "shared"; `maxInstances` limits running desktops in manual mode. Created, stopped per-bot desktops do not consume a running slot. */
|
|
12
13
|
export const localVmConfigSchema = z.object({
|
|
13
14
|
mode: z.enum(["shared", "per-bot", "pool"]).optional(),
|
|
15
|
+
automaticCapacity: z.boolean().optional(),
|
|
14
16
|
maxInstances: z
|
|
15
17
|
.number()
|
|
16
18
|
.int()
|
|
@@ -33,7 +35,12 @@ export function localVmMode(cfg) {
|
|
|
33
35
|
return cfg.localVm?.mode ?? DEFAULT_LOCAL_VM_MODE;
|
|
34
36
|
}
|
|
35
37
|
export function localVmMaxInstances(cfg) {
|
|
36
|
-
|
|
38
|
+
if (!localVmAutomaticCapacity(cfg))
|
|
39
|
+
return cfg.localVm.maxInstances ?? DEFAULT_LOCAL_VM_MAX_INSTANCES;
|
|
40
|
+
return limixVmCapacity(localVmResources(cfg)).limit;
|
|
41
|
+
}
|
|
42
|
+
export function localVmAutomaticCapacity(cfg) {
|
|
43
|
+
return cfg.localVm?.automaticCapacity ?? cfg.localVm?.maxInstances === undefined;
|
|
37
44
|
}
|
|
38
45
|
export function localVmIdleTimeoutMinutes(cfg) {
|
|
39
46
|
return cfg.localVm?.idleTimeoutMinutes ?? DEFAULT_LOCAL_VM_IDLE_TIMEOUT_MINUTES;
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
2
3
|
import { handleLimixBotLibrary } from "../limix-bot-library.js";
|
|
3
4
|
import { setImportedSkillEnabled } from "../imported-skills.js";
|
|
4
5
|
import { setNativeSkillEnabled } from "../native-skill-choices.js";
|
|
5
6
|
import { botSkillTemplateSchema } from "../new-bot-defaults.js";
|
|
6
7
|
import { fetchSkillFromSource } from "../skill-fetch.js";
|
|
7
8
|
import { readLocalSkills } from "../limix-skill-folder.js";
|
|
9
|
+
import { scanSkillRequirements } from "../limix-skill-requirements.js";
|
|
8
10
|
import { loadBundledSkills } from "../skill-library.js";
|
|
9
11
|
import { handleLimixHub } from "../limix-skill-hub.js";
|
|
10
12
|
import { proxyLimixGateway } from "../limix-gateway-sidecar.js";
|
|
@@ -17,6 +19,15 @@ export function createBotSkillsRoutes(deps) {
|
|
|
17
19
|
const { store, cfg, listBotSkills, readBotSkillFile, stagedSkillListing } = deps;
|
|
18
20
|
return async ({ req, res, url, path, method, json, readBody }) => {
|
|
19
21
|
let m = null;
|
|
22
|
+
if (method === "GET" && path === "/api/limix/skill-requirements") {
|
|
23
|
+
return json(res, 200, await scanSkillRequirements(store.bots, cfg.mcpServers));
|
|
24
|
+
}
|
|
25
|
+
if (method === "POST" && path === "/api/limix/skill-requirements/scan") {
|
|
26
|
+
const input = z.object({ projects: z.array(z.string().max(4096).refine(isAbsolute)).max(200) }).safeParse(await readBody(req));
|
|
27
|
+
if (!input.success)
|
|
28
|
+
return json(res, 400, { error: "Choose valid project folders" });
|
|
29
|
+
return json(res, 200, await scanSkillRequirements(store.bots, cfg.mcpServers, input.data.projects));
|
|
30
|
+
}
|
|
20
31
|
if (path.startsWith("/api/limix/gateway") && proxyLimixGateway(req, res, path))
|
|
21
32
|
return;
|
|
22
33
|
if (path.startsWith("/api/limix/bots")) {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import * as boat from "../boat.js";
|
|
3
|
+
import { limixVmCapacity } from "../limix-vm-capacity.js";
|
|
4
|
+
import { localVmAutomaticCapacity } from "../local-vm-settings.js";
|
|
3
5
|
import { isValidSshAlias, localVmMaxInstances, localVmMode, localVmResources } from "../config.js";
|
|
4
|
-
import { containerComputerAction,
|
|
6
|
+
import { containerComputerAction, containerComputerScreenshot, containerComputerStatus, runningLocalVmCount, SHARED_LOCAL_VM_TARGET, setupCommands, } from "../container-computer.js";
|
|
5
7
|
import { viewerTargetId } from "../../shared/desktop-viewer.js";
|
|
6
8
|
import { localVmViewerStatus } from "../desktop-viewer-targets.js";
|
|
7
9
|
import { keepFirefoxProfileBeforeRemove } from "../local-vm-profiles.js";
|
|
@@ -19,7 +21,7 @@ async function keepSignInsBeforeRemove(target) {
|
|
|
19
21
|
await keepFirefoxProfileBeforeRemove(target, before, () => containerComputerAction("stop", undefined, undefined, target));
|
|
20
22
|
}
|
|
21
23
|
export function createComputerRoutes(deps) {
|
|
22
|
-
const { store, cfg, sessions, teamComputers, computerControl, controlLeaseIdSchema, boatLifecycleBusyBots, computerProviderConfigTransitions, localVmActiveThreads, localVmLifecycleBusy, localVmSeen, localVmImageBusy, localVmProvisionBusy, localVmModeChangeBusy, localVmOwnerBusy, localVmIdleMs, localVmLeaseFor, localVmIdleFor, localVmTargetForBot, localVmTargetForStatus, localVmPayload, localVmInventoryPayload,
|
|
24
|
+
const { store, cfg, sessions, teamComputers, computerControl, controlLeaseIdSchema, boatLifecycleBusyBots, computerProviderConfigTransitions, localVmActiveThreads, localVmLifecycleBusy, localVmSeen, localVmImageBusy, localVmProvisionBusy, localVmModeChangeBusy, localVmOwnerBusy, localVmIdleMs, localVmLeaseFor, localVmIdleFor, localVmTargetForBot, localVmTargetForStatus, localVmPayload, localVmInventoryPayload, teamComputersPayload, teamComputerInUse, managedBoatOwners, providerTransitionMessage, botHasActiveTurn, botComputerControlKey, botComputerControlSnapshot, computerPreviewBot, computerPreviewSurface, claimTeamComputerLifecycle, claimBotComputerLifecycle, claimBoatInventoryRequest, claimManagedBoatMutation, claimManagedVpsMutation, cloudComputerUsed, } = deps;
|
|
23
25
|
const usage = createComputerUsageRoutes(deps);
|
|
24
26
|
const frames = createComputerFramesRoutes(deps);
|
|
25
27
|
return async (context) => {
|
|
@@ -263,7 +265,7 @@ export function createComputerRoutes(deps) {
|
|
|
263
265
|
try {
|
|
264
266
|
if (action === "remove")
|
|
265
267
|
await keepSignInsBeforeRemove(SHARED_LOCAL_VM_TARGET);
|
|
266
|
-
const status = await containerComputerAction(action, undefined, undefined, SHARED_LOCAL_VM_TARGET, localVmResources(cfg));
|
|
268
|
+
const status = await containerComputerAction(action, undefined, undefined, SHARED_LOCAL_VM_TARGET, localVmResources(cfg), () => localVmMaxInstances(cfg));
|
|
267
269
|
if (action === "run" || action === "start") {
|
|
268
270
|
localVmSeen.add(SHARED_LOCAL_VM_TARGET.key);
|
|
269
271
|
localVmIdleFor(SHARED_LOCAL_VM_TARGET).touch();
|
|
@@ -276,6 +278,9 @@ export function createComputerRoutes(deps) {
|
|
|
276
278
|
idle_timeout_ms: localVmIdleMs(),
|
|
277
279
|
mode: localVmMode(cfg),
|
|
278
280
|
max_instances: localVmMaxInstances(cfg),
|
|
281
|
+
automatic_capacity: localVmAutomaticCapacity(cfg),
|
|
282
|
+
capacity: limixVmCapacity(localVmResources(cfg)),
|
|
283
|
+
running_instances: status.runtime ? await runningLocalVmCount(status.runtime) : 0,
|
|
279
284
|
});
|
|
280
285
|
}
|
|
281
286
|
finally {
|
|
@@ -327,7 +332,6 @@ export function createComputerRoutes(deps) {
|
|
|
327
332
|
if ((action === "stop" || action === "remove") && (localVmActiveThreads.has(target.key) || localVmLifecycleBusy.has(target.key))) {
|
|
328
333
|
return json(res, 409, { error: localVmActiveThreads.has(target.key) ? "this bot is using its Local VM — stop the turn first" : "this bot's Local VM setup action is still running" });
|
|
329
334
|
}
|
|
330
|
-
// Fenced before the first await, so two requests cannot both pass the limit.
|
|
331
335
|
localVmLifecycleBusy.add(target.key);
|
|
332
336
|
if (action === "run")
|
|
333
337
|
localVmProvisionBusy.set(true);
|
|
@@ -336,18 +340,10 @@ export function createComputerRoutes(deps) {
|
|
|
336
340
|
const before = await containerComputerStatus(undefined, undefined, target);
|
|
337
341
|
if (!before.runtime)
|
|
338
342
|
return json(res, 409, { error: before.problem ?? "No container runtime is installed" });
|
|
339
|
-
if (!(await containerComputerExists(before.runtime, target))) {
|
|
340
|
-
const count = await existingPerBotLocalVmCount(before.runtime);
|
|
341
|
-
if (count >= localVmMaxInstances(cfg)) {
|
|
342
|
-
return json(res, 409, {
|
|
343
|
-
error: `The per-bot Local VM limit is ${localVmMaxInstances(cfg)} — delete an unused bot VM or raise the limit in App Settings`,
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
343
|
}
|
|
348
344
|
if (action === "remove")
|
|
349
345
|
await keepSignInsBeforeRemove(target);
|
|
350
|
-
const status = await containerComputerAction(action, undefined, undefined, target, localVmResources(cfg));
|
|
346
|
+
const status = await containerComputerAction(action, undefined, undefined, target, localVmResources(cfg), () => localVmMaxInstances(cfg));
|
|
351
347
|
if (action === "run" || action === "start") {
|
|
352
348
|
localVmSeen.add(target.key);
|
|
353
349
|
localVmIdleFor(target).touch();
|
|
@@ -360,6 +356,9 @@ export function createComputerRoutes(deps) {
|
|
|
360
356
|
idle_timeout_ms: localVmIdleMs(),
|
|
361
357
|
mode: localVmMode(cfg),
|
|
362
358
|
max_instances: localVmMaxInstances(cfg),
|
|
359
|
+
automatic_capacity: localVmAutomaticCapacity(cfg),
|
|
360
|
+
capacity: limixVmCapacity(localVmResources(cfg)),
|
|
361
|
+
running_instances: status.runtime ? await runningLocalVmCount(status.runtime) : 0,
|
|
363
362
|
});
|
|
364
363
|
}
|
|
365
364
|
finally {
|
|
@@ -349,11 +349,21 @@ export function createInstanceRoutes(deps) {
|
|
|
349
349
|
return json(res, 200, { instances: await describeInstances() });
|
|
350
350
|
}
|
|
351
351
|
if (action === "install") {
|
|
352
|
-
const
|
|
352
|
+
const updating = url.searchParams.get("update") === "1";
|
|
353
|
+
const installed = await registry.installRuntime(instanceId, { update: updating });
|
|
353
354
|
if (!installed)
|
|
354
355
|
return json(res, 404, { error: "Installing this engine from Settings is not available on this server. Use the install command on the machine running Limix Bot." });
|
|
355
356
|
const usingAppCopy = installed !== true && await useAppCopy(instanceId, installed.useCli);
|
|
356
|
-
|
|
357
|
+
if (updating && installed !== true && !usingAppCopy)
|
|
358
|
+
return json(res, 409, { error: "The new CLI was installed, but this engine is busy. Wait for its current task to finish, then retry the update to switch to the new copy." });
|
|
359
|
+
const instances = await describeInstances();
|
|
360
|
+
if (installed !== true && installed.expectedVersion) {
|
|
361
|
+
const active = await registry.get(instanceId)?.snapshot();
|
|
362
|
+
if (active?.state !== "available" || active.version?.match(/\b\d+\.\d+\.\d+(?:-[\w.-]+)?\b/)?.[0] !== installed.expectedVersion) {
|
|
363
|
+
return json(res, 502, { error: `The new CLI was downloaded, but its active version could not be verified as ${installed.expectedVersion}. Current version: ${active?.version ?? "unknown"}.` });
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return json(res, 200, { instances, ...(usingAppCopy ? { usingAppCopy: true } : {}) });
|
|
357
367
|
}
|
|
358
368
|
if (action === "auth/start") {
|
|
359
369
|
const instance = registry.get(instanceId);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1472,8 +1472,8 @@ let address=raw.split("%",1)[0];return isIP(address)!==0&&list.check(address,fam
|
|
|
1472
1472
|
let match=/^\[([^\]]+)\](?:\/(\d{1,3}))?(?::(\d{1,5}))?$/.exec(entry)??(entry.split(":").length>2?/^([^/]+)(?:\/(\d{1,3}))?()$/.exec(entry):/^([^/:]+)(?:\/(\d{1,3}))?(?::(\d{1,5}))?$/.exec(entry));if(!match)return null;let[,network="",prefixText,portText]=match,kind=isIP2(network);if(!kind)return null;let max=kind===6?128:32,prefix=prefixText===void 0?max:Number(prefixText),port=portText?Number(portText):null;return!Number.isInteger(prefix)||prefix<0||prefix>max||port!==null&&(!Number.isInteger(
|
|
1473
1473
|
port)||port<1||port>65535)?null:{network,prefix,port}}async function refusalFor(target,addresses,rules,own2=ownAddresses()){let{host,port}=target;for(let{address}of addresses){let kind=addressClass(address,own2);if(kind==="reserved"&&rules.host==="desktop"&&listed(FAKE_IP,address)){if(rules.ownPort(port))return"omb";kind=listed(own2,address)?"this-machine":"private"}if(kind!=="public"){if(kind==="metadata"||kind==="link-local"||kind==="reserved")return kind;if(kind==="private"){if(rules.host==="desktop"?rules.localNetwork:rules.host==="server"&&rules.
|
|
1474
1474
|
allowed(address,port))continue;if(rules.host==="server"&&rules.localNetwork){if(rules.ownPort(port))return"omb";continue}return"local-network"}if(rules.ownPort(port))return"omb";if(rules.host==="desktop"){if(namesThisMachine(host))continue;return"rebinding"}if(!(rules.host==="server"&&rules.localNetwork&&(kind==="this-machine"||namesThisMachine(host)))&&!(rules.host==="server"&&rules.allowed(address,port))&&!await rules.botPort(port))return"this-computer"}}return null}var CDP_PORT=/^[0-9]{1,5}$/,CDP_URL=/^(https?|wss?):\/\/\S+$/i;function isValidCdpTarget(value){if(typeof value!="string"||value==="")return!1;if(CDP_PORT.test(value)){let port=Number(value);return port>=1&&port<=65535}return CDP_URL.test(value)}var browserEngineConfigSchema=external_exports.object({attachCdpUrl:external_exports.string().trim().max(2048).refine(value=>value===""||isValidCdpTarget(value),{message:"browserEngine.attachCdpUrl must be a CDP port (1-65535) or an http(s)/ws(s) URL"}).
|
|
1475
|
-
optional(),idleTimeoutMinutes:external_exports.number().int().min(1).max(60).optional(),egress:browserEgressConfigSchema.optional(),engine:external_exports.enum(["agent-browser","chrome"]).optional()});var roomContextSettings={roomCompactAt:external_exports.number().positive().max(1e7).optional(),roomSessions:external_exports.boolean().optional()};var MIN_DESKTOP_MEMORY_GB=2,MAX_DESKTOP_MEMORY_GB=128,MIN_DESKTOP_CPUS=1,MAX_DESKTOP_CPUS=64;var MIN_LOCAL_VM_MAX_INSTANCES=1,MAX_LOCAL_VM_MAX_INSTANCES=
|
|
1476
|
-
optional(),memoryGb:external_exports.number().int().min(MIN_DESKTOP_MEMORY_GB).max(MAX_DESKTOP_MEMORY_GB).optional(),cpus:external_exports.number().int().min(MIN_DESKTOP_CPUS).max(MAX_DESKTOP_CPUS).optional()});var optionalText2=external_exports.string().optional(),SSH_ALIAS=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/,LEGACY_BROWSER_PROFILE_ID=/^[A-Za-z0-9_-]{1,40}$/,BROWSER_PROFILE_ID=/^[a-z0-9_-]{1,40}$/,FISH_TTS_MODELS=["s2.1-pro","s2.1-pro-free"];var MIN_ROOM_TURN_TIMEOUT_MINUTES=1,MAX_ROOM_TURN_TIMEOUT_MINUTES=1440;var MIN_MCP_CALL_TIMEOUT_MINUTES=1,MAX_MCP_CALL_TIMEOUT_MINUTES=60,MIN_THREAD_EVENT_LOG_BYTES=256*1024,MAX_THREAD_EVENT_LOG_BYTES=4*1024*1024*1024;function isValidSshAlias(value){return typeof value=="string"&&SSH_ALIAS.test(value)}var vpsConfigSchema=external_exports.object({sshAlias:external_exports.string().refine(value=>value===""||isValidSshAlias(value),{message:"must be a simple SSH config alias"}).optional()}),roomConfigSchema=external_exports.object({turnTimeoutMinutes:external_exports.number().int().min(MIN_ROOM_TURN_TIMEOUT_MINUTES).max(MAX_ROOM_TURN_TIMEOUT_MINUTES)}),mcpConfigSchema=external_exports.object({callTimeoutMinutes:external_exports.number().int().min(MIN_MCP_CALL_TIMEOUT_MINUTES).max(MAX_MCP_CALL_TIMEOUT_MINUTES).
|
|
1475
|
+
optional(),idleTimeoutMinutes:external_exports.number().int().min(1).max(60).optional(),egress:browserEgressConfigSchema.optional(),engine:external_exports.enum(["agent-browser","chrome"]).optional()});var roomContextSettings={roomCompactAt:external_exports.number().positive().max(1e7).optional(),roomSessions:external_exports.boolean().optional()};var GIB=1024**3;var startQueue=Promise.resolve();var MIN_DESKTOP_MEMORY_GB=2,MAX_DESKTOP_MEMORY_GB=128,MIN_DESKTOP_CPUS=1,MAX_DESKTOP_CPUS=64;var MIN_LOCAL_VM_MAX_INSTANCES=1,MAX_LOCAL_VM_MAX_INSTANCES=1024;var MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES=5,MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES=1440,localVmConfigSchema=external_exports.object({mode:external_exports.enum(["shared","per-bot","pool"]).optional(),automaticCapacity:external_exports.boolean().optional(),maxInstances:external_exports.number().int().min(MIN_LOCAL_VM_MAX_INSTANCES).max(MAX_LOCAL_VM_MAX_INSTANCES).optional(),idleTimeoutMinutes:external_exports.number().int().min(MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES).max(MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES).optional(),
|
|
1476
|
+
preserveInstalledApps:external_exports.boolean().optional(),memoryGb:external_exports.number().int().min(MIN_DESKTOP_MEMORY_GB).max(MAX_DESKTOP_MEMORY_GB).optional(),cpus:external_exports.number().int().min(MIN_DESKTOP_CPUS).max(MAX_DESKTOP_CPUS).optional()});var optionalText2=external_exports.string().optional(),SSH_ALIAS=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/,LEGACY_BROWSER_PROFILE_ID=/^[A-Za-z0-9_-]{1,40}$/,BROWSER_PROFILE_ID=/^[a-z0-9_-]{1,40}$/,FISH_TTS_MODELS=["s2.1-pro","s2.1-pro-free"];var MIN_ROOM_TURN_TIMEOUT_MINUTES=1,MAX_ROOM_TURN_TIMEOUT_MINUTES=1440;var MIN_MCP_CALL_TIMEOUT_MINUTES=1,MAX_MCP_CALL_TIMEOUT_MINUTES=60,MIN_THREAD_EVENT_LOG_BYTES=256*1024,MAX_THREAD_EVENT_LOG_BYTES=4*1024*1024*1024;function isValidSshAlias(value){return typeof value=="string"&&SSH_ALIAS.test(value)}var vpsConfigSchema=external_exports.object({sshAlias:external_exports.string().refine(value=>value===""||isValidSshAlias(value),{message:"must be a simple SSH config alias"}).optional()}),roomConfigSchema=external_exports.object({turnTimeoutMinutes:external_exports.number().int().min(MIN_ROOM_TURN_TIMEOUT_MINUTES).max(MAX_ROOM_TURN_TIMEOUT_MINUTES)}),mcpConfigSchema=external_exports.object({callTimeoutMinutes:external_exports.number().int().min(MIN_MCP_CALL_TIMEOUT_MINUTES).max(MAX_MCP_CALL_TIMEOUT_MINUTES).
|
|
1477
1477
|
optional()}).strict(),browserProfileSchema=external_exports.object({id:external_exports.string().regex(BROWSER_PROFILE_ID).refine(id=>id!=="guest","guest is reserved"),name:external_exports.string().trim().min(1).max(40),browser:external_exports.literal("chrome").optional()}).strict(),legacyBrowserProfileSchema=external_exports.object({id:external_exports.string().regex(LEGACY_BROWSER_PROFILE_ID).refine(id=>id!=="guest","guest is reserved"),name:external_exports.string().trim().min(1).max(40),partitionId:external_exports.
|
|
1478
1478
|
string().regex(LEGACY_BROWSER_PROFILE_ID).refine(id=>id!=="guest","guest is reserved").optional(),browser:external_exports.literal("chrome").optional()}).strict();function suffixedBrowserProfileId(base,unavailable){for(let suffix=2;;suffix+=1){let ending=`-${suffix}`,candidate=`${base.slice(0,40-ending.length)}${ending}`;if(candidate!=="guest"&&!unavailable.has(candidate))return candidate}}function migrateStoredBrowserProfiles(profiles){let requestedPartitions=profiles.map(profile=>profile.partitionId??
|
|
1479
1479
|
profile.id),rawBases=profiles.map(profile=>profile.id.toLowerCase()),canonicalIds=Array(profiles.length).fill(void 0),used=new Set,baseOwner=new Map;rawBases.forEach((base,index)=>{if(base==="guest")return;let current=baseOwner.get(base);(current===void 0||profiles[index].id===base&&profiles[current].id!==base)&&baseOwner.set(base,index)});for(let[base,index]of baseOwner)canonicalIds[index]=base,used.add(base);let reserved=new Set(["guest",...rawBases,...requestedPartitions.map(partitionId=>partitionId.
|
|
@@ -1501,11 +1501,11 @@ computerName:external_exports.string().trim().max(63).optional(),rooms:roomConfi
|
|
|
1501
1501
|
0).max(23).optional()}).strict().optional(),threads:threadsConfigSchema.optional(),burst:external_exports.object({maxParallel:external_exports.number().int().min(1).max(100).optional()}).strict().optional(),decisions:external_exports.object({retentionDays:external_exports.number().int().min(1).max(3650).optional()}).strict().optional(),loopGuard:loopGuardConfigSchema.optional(),safetyFloor:external_exports.object({enabled:external_exports.boolean().optional()}).strict().optional(),localVm:localVmConfigSchema.
|
|
1502
1502
|
optional(),features:featureConfigSchema.optional(),onboarding:onboardingConfigSchema.optional(),browserEngine:browserEngineConfigSchema.optional(),browserProfiles:browserProfilesSchema.optional(),instances:instanceConfigMapSchema.optional(),mcpServers:external_exports.record(external_exports.string(),external_exports.unknown()).optional()}),storedAppConfigSchema=appConfigSchema.extend(helperStoredShape).extend({browserProfiles:storedBrowserProfilesSchema.optional(),opencodeGo:external_exports.object(
|
|
1503
1503
|
{apiKey:optionalText2,providerKeys:external_exports.record(external_exports.string(),external_exports.unknown()).catch({}).transform(keys=>Object.fromEntries(Object.entries(keys).filter(entry=>typeof entry[1]=="string"))).optional()}).optional()}),appConfigPatchSchema=appConfigSchema.omit({instances:!0,mcpServers:!0,cliStartup:!0,customDomain:!0}).extend({threads:threadsPatchSchema.optional(),newBots:newBotsPatchSchema.optional(),imageGen:imageGenPatchSchema.optional()}),jsonObjectSchema2=external_exports.
|
|
1504
|
-
record(external_exports.string(),external_exports.json());function parseStoredConfig(value){let parsed=storedAppConfigSchema.safeParse(value);if(!parsed.success)throw new Error(schemaIssue(parsed.error,"Invalid stored configuration"));return parsed.data}var DEFAULT_CAPTURE_QUIET_MS=2*6e4;var DATA_DIR=process.env.OMB_DATA_DIR||join5(dataHome(),".limixbot"),LEGACY_DATA_DIR=join5(dataHome(),".opengrokbot"),EVENTS_DIR=join5(DATA_DIR,"events"),NATIVE_DIR=join5(DATA_DIR,"native");var storedConfig=settledFileCache(()=>join5(DATA_DIR,"config.json"),()=>parseStoredConfig(parseJson(readFileSync3(join5(DATA_DIR,"config.json"),"utf8"))));var
|
|
1504
|
+
record(external_exports.string(),external_exports.json());function parseStoredConfig(value){let parsed=storedAppConfigSchema.safeParse(value);if(!parsed.success)throw new Error(schemaIssue(parsed.error,"Invalid stored configuration"));return parsed.data.localVm&&parsed.data.localVm.automaticCapacity===void 0&&(parsed.data.localVm.automaticCapacity=!0),parsed.data}var DEFAULT_CAPTURE_QUIET_MS=2*6e4;var DATA_DIR=process.env.OMB_DATA_DIR||join5(dataHome(),".limixbot"),LEGACY_DATA_DIR=join5(dataHome(),".opengrokbot"),EVENTS_DIR=join5(DATA_DIR,"events"),NATIVE_DIR=join5(DATA_DIR,"native");var storedConfig=settledFileCache(()=>join5(DATA_DIR,"config.json"),()=>parseStoredConfig(parseJson(readFileSync3(join5(DATA_DIR,"config.json"),"utf8"))));var GIB2=1024*1024*1024;var SUPERVISOR_CAPS=["SETGID","SETUID"],PACKAGE_INSTALL_CAPS=["CHOWN","DAC_OVERRIDE","FOWNER","FSETID",...SUPERVISOR_CAPS];var SUPERVISORD="/usr/bin/supervisord -c /etc/supervisor/supervisord.conf",GUEST_IDS_SCRIPT=["set -eu",'uid="$1"; gid="$2"; old_uid="$(id -u cua)"; old_gid="$(id -g cua)"','if [ "$old_uid:$old_gid" != "$uid:$gid" ]; then',' find / -xdev -uid "$old_uid" -exec chown -h "$uid" {} +',' find / -xdev -gid "$old_gid" -exec chgrp -h "$gid" {} +',' sed -i "s/^cua:x:$old_uid:$old_gid:/cua:x:$uid:$gid:/" /etc/passwd',' sed -i "s/^cua:x:$old_gid:/cua:x:$gid:/" /etc/group',' [ "$(id -u cua):$(id -g cua)\
|
|
1505
1505
|
" = "$uid:$gid" ] || { echo "cua did not take uid $uid gid $gid" >&2; exit 1; }',"fi",`exec ${SUPERVISORD}`].join(`
|
|
1506
1506
|
`);import{existsSync as existsSync4}from"node:fs";import{dirname as dirname3,join as join6}from"node:path";import{fileURLToPath}from"node:url";var SERVER_ROOT=dirname3(fileURLToPath(import.meta.url));function resolveProxy(relative5){let source=join6(SERVER_ROOT,`${relative5}.ts`);return existsSync4(source)?source:join6(SERVER_ROOT,`${relative5}.js`)}var SPAWNED_PROXIES={harnessMcp:resolveProxy("harness-mcp-proxy"),localComputer:resolveProxy("local-computer-proxy"),permission:resolveProxy("permissio\
|
|
1507
1507
|
n-proxy"),containerMcp:resolveProxy("container-mcp"),vpsContainerMcp:resolveProxy("vps-container-mcp"),agents:resolveProxy("drivers/agents-proxy"),dweb:resolveProxy("drivers/dweb-proxy"),connectors:resolveProxy("connector-proxy"),mcpGate:resolveProxy("mcp-gate"),mcpRemote:resolveProxy("mcp-remote-proxy"),phone:resolveProxy("drivers/phone-proxy"),chatgptPlanToken:resolveProxy("drivers/chatgpt-plan-token-command"),hook:resolveProxy("hooks/omb-hook"),piMcpExtension:resolveProxy("drivers/pi-mcp-exte\
|
|
1508
|
-
nsion")};var run=promisify(execFile2);var CUA_DRIVER_VERSION="0.37.0",BASE_IMAGE_REPOSITORY="docker.io/trycua/xfce-cua",BASE_IMAGE_DIGEST="sha256:274eb636f5cf3fc58f705916ee72b7a701270b3877369d08533a385c5325be9b",BASE_IMAGE=`${BASE_IMAGE_REPOSITORY}@${BASE_IMAGE_DIGEST}`,IMAGE_REPOSITORY="localhost/limixbot/cua-local-vm",IMAGE_LAYER_VERSION="9";var IMAGE=`${IMAGE_REPOSITORY}:driver-${CUA_DRIVER_VERSION}-v${IMAGE_LAYER_VERSION}`,CONTAINER="
|
|
1508
|
+
nsion")};var run=promisify(execFile2);var CUA_DRIVER_VERSION="0.37.0",BASE_IMAGE_REPOSITORY="docker.io/trycua/xfce-cua",BASE_IMAGE_DIGEST="sha256:274eb636f5cf3fc58f705916ee72b7a701270b3877369d08533a385c5325be9b",BASE_IMAGE=`${BASE_IMAGE_REPOSITORY}@${BASE_IMAGE_DIGEST}`,IMAGE_REPOSITORY="localhost/limixbot/cua-local-vm",IMAGE_LAYER_VERSION="9";var IMAGE=`${IMAGE_REPOSITORY}:driver-${CUA_DRIVER_VERSION}-v${IMAGE_LAYER_VERSION}`,CONTAINER="limixbot-computer";var VM_WORKSPACE_DIR=join7(DATA_DIR,"vm-home");var DISPLAY=":1",CUA_SOCKET="/run/user/1000/limixbot-cua.sock",CUA_EXECUTABLE="/usr/local/libexec/limixbot/cua-driver";function cuaExecArgs(args2,options={}){return["exec",...options.interactive?["-i"]:[],"-u","cua","-e","HOME=/home/cua","-e",`DISPLAY=${DISPLAY}`,"-e","CUA_DRIVER_INSTALL_CHANNEL=python_package","-e","CUA_DRIVER_RS_TELEMETRY_ENABLED=0",options.container??CONTAINER,CUA_EXECUTABLE,...args2]}var containerMcpPath=SPAWNED_PROXIES.containerMcp;import{randomBytes as randomBytes2}from"node:crypto";import{closeSync as closeSync2,existsSync as existsSync6,mkdirSync as mkdirSync2,openSync as openSync2,rmSync as rmSync2,statSync as statSync4,writeFileSync}from"node:fs";import{dirname as dirname4,join as join10,resolve as resolve5}from"node:path";import{join as join8}from"node:path";function npmEnginesPrefix(dataDir){return join8(dataDir,"tools","npm")}function antigravityRuntimesRoot(dataDir){return join8(dataDir,"tools","antigravity-acp")}function standaloneEnginesRoot(dataDir){return join8(dataDir,"tools","standalone")}function engineInstallRoots(dataDir){return[npmEnginesPrefix(dataDir),antigravityRuntimesRoot(dataDir),standaloneEnginesRoot(dataDir)]}function bridgedCommand(tools,bridges,command,args2,relay){if(!bridges.length&&!relay)return{command,args:[...args2]};if(tools.socat&&!relay){let lines=bridges.map(bridge=>`${shellWord(tools.socat)} TCP4-LISTEN:${bridge.port},bind=127.0.0.1,reuseaddr,fork UNIX-CONNECT:${shellWord(inBoxSocket(bridge.name))} </dev/null >/dev/null 2>&1 &`),first=bridges[0],wait=`n=0; until ${shellWord(tools.socat)} -u OPEN:/dev/null TCP4:127.0.0.1:${first.port},connect-timeout=0.2 2>/dev/null || [ "$n" -ge 100 ]; d\
|
|
1509
1509
|
o n=$((n+1)); sleep 0.01; done`;return{command:"/bin/sh",args:["-c",[...lines,wait,'exec "$0" "$@"'].join(`
|
|
1510
1510
|
`),command,...args2]}}return{command:tools.node,args:[tools.bridgeScript,...bridges.map(bridge=>`--bridge=${bridge.port}=${inBoxSocket(bridge.name)}`),...relay?[`--relay=${relay}`]:[],"--",command,...args2]}}function shellWord(value){return`'${value.replaceAll("'","'\\''")}'`}import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{createServer,request as httpRequest}from"node:http";import{request as httpsRequest}from"node:https";function refusedCallAnswer(server,sentCredentials,body){let frame;try{frame=JSON.parse(body)}catch{return null}let{id,method}=frame&&typeof frame=="object"&&!Array.isArray(frame)?frame:{};if(method!=="tools/call"||typeof id!="string"&&typeof id!="number")return null;let text=sentCredentials?`The MCP server "${server}" refused the sign-in or key it was sent (HTTP 401), so nothing ran. Don't retry. If it signs in, call mcp_server with action sign_in and name ${server}, then end your turn; otherwis\
|
|
1511
1511
|
e tell the person to update its key in Apps, MCP servers.`:`The MCP server "${server}" needs a sign-in before its tools work, and nobody has signed in (HTTP 401), so nothing ran. Don't retry. Call mcp_server with action sign_in and name ${server}, then end your turn; if you can't, tell the person to sign in to ${server} in Apps, MCP servers.`;return JSON.stringify({jsonrpc:"2.0",id,result:{content:[{type:"text",text}],isError:!0}})}var BROKER_TOKEN_PREFIX="omb_t0_",BROKER_PROCESS_TTL_MS=1440*6e4,BROKER_THREAD_TTL_MS=1440*6e4,MAX_TOKENS=1e4,CREDENTIAL_HEADERS=new Set(["authorization","x-api-key","x-goog-api-key","proxy-authorization","cookie"]),HOP_BY_HOP=new Set(["connection","keep-alive","transfer-encoding","te","trailer","upgrade","proxy-connection","host"]),TOKEN=/^omb_t0_[a-f0-9]{48}$/,GRANT=/^[a-z][a-z0-9_-]{0,63}$/;function brokerUrl(port,token,grant){return`http://127.0.0.1:${port}/b/${token}/${grant}`}function upstreamUrl(upstream,path,query){
|
|
@@ -1520,8 +1520,8 @@ string().trim().max(2048).refine(value=>!value||/^https?:\/\//i.test(value),"the
|
|
|
1520
1520
|
optional(),idleMinutes:external_exports.number().int().min(1).max(60).optional()});import{BlockList as BlockList2,isIP as isIP2}from"node:net";import{BlockList,isIP}from"node:net";var family=address=>isIP(address)===6?"ipv6":"ipv4";function subnets(entries){let list=new BlockList;for(let[network,prefix]of entries)list.addSubnet(network,prefix,family(network));return list}var LOOPBACK=subnets([["127.0.0.0",8],["::1",128]]),RESERVED=subnets([["0.0.0.0",8],["198.18.0.0",15],["224.0.0.0",3],["::",96],["64:ff9b:1::",48],["2001::",32],["ff00::",8]]),LINK_LOCAL=subnets([["169.254.0.0",16],["fe80::",10]]),PRIVATE=subnets([["10.0.0.0",8],["100.64.0.0",10],["172.16.0.0",12],["192.1\
|
|
1521
1521
|
68.0.0",16],["fc00::",7]]),METADATA=new BlockList;for(let address of["169.254.169.254","fd00:ec2::254","100.100.100.200"])METADATA.addAddress(address,family(address));var NAT64=subnets([["64:ff9b::",96]]),SIX_TO_FOUR=subnets([["2002::",16]]);var FAKE_IP=new BlockList2;FAKE_IP.addSubnet("198.18.0.0",15,"ipv4");var browserEgressConfigSchema=external_exports.object({allow:external_exports.array(external_exports.string().trim().max(64).refine(entry=>parseAllowEntry(entry)!==null,{message:"must be an IP address or CIDR range, with an optional :port"})).max(64).optional(),localNetwork:external_exports.boolean().optional()});function parseAllowEntry(entry){let match=/^\[([^\]]+)\](?:\/(\d{1,3}))?(?::(\d{1,5}))?$/.exec(entry)??(entry.split(":").length>2?/^([^/]+)(?:\/(\d{1,3}))?()$/.exec(entry):/^([^/:]+)(?:\/(\d{1,3}))?(?::(\d{1,5}))?$/.
|
|
1522
1522
|
exec(entry));if(!match)return null;let[,network="",prefixText,portText]=match,kind=isIP2(network);if(!kind)return null;let max=kind===6?128:32,prefix=prefixText===void 0?max:Number(prefixText),port=portText?Number(portText):null;return!Number.isInteger(prefix)||prefix<0||prefix>max||port!==null&&(!Number.isInteger(port)||port<1||port>65535)?null:{network,prefix,port}}var CDP_PORT=/^[0-9]{1,5}$/,CDP_URL=/^(https?|wss?):\/\/\S+$/i;function isValidCdpTarget(value){if(typeof value!="string"||value==="")return!1;if(CDP_PORT.test(value)){let port=Number(value);return port>=1&&port<=65535}return CDP_URL.test(value)}var browserEngineConfigSchema=external_exports.object({attachCdpUrl:external_exports.string().trim().max(2048).refine(value=>value===""||isValidCdpTarget(value),{message:"browserEngine.attachCdpUrl must be a CDP port (1-65535) or an http(s)/ws(s) URL"}).
|
|
1523
|
-
optional(),idleTimeoutMinutes:external_exports.number().int().min(1).max(60).optional(),egress:browserEgressConfigSchema.optional(),engine:external_exports.enum(["agent-browser","chrome"]).optional()});var roomContextSettings={roomCompactAt:external_exports.number().positive().max(1e7).optional(),roomSessions:external_exports.boolean().optional()};var MIN_DESKTOP_MEMORY_GB=2,MAX_DESKTOP_MEMORY_GB=128,MIN_DESKTOP_CPUS=1,MAX_DESKTOP_CPUS=64;var MIN_LOCAL_VM_MAX_INSTANCES=1,MAX_LOCAL_VM_MAX_INSTANCES=
|
|
1524
|
-
optional(),memoryGb:external_exports.number().int().min(MIN_DESKTOP_MEMORY_GB).max(MAX_DESKTOP_MEMORY_GB).optional(),cpus:external_exports.number().int().min(MIN_DESKTOP_CPUS).max(MAX_DESKTOP_CPUS).optional()});var optionalText2=external_exports.string().optional(),SSH_ALIAS=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/,LEGACY_BROWSER_PROFILE_ID=/^[A-Za-z0-9_-]{1,40}$/,BROWSER_PROFILE_ID=/^[a-z0-9_-]{1,40}$/,FISH_TTS_MODELS=["s2.1-pro","s2.1-pro-free"];var MIN_ROOM_TURN_TIMEOUT_MINUTES=1,MAX_ROOM_TURN_TIMEOUT_MINUTES=1440;var MIN_MCP_CALL_TIMEOUT_MINUTES=1,MAX_MCP_CALL_TIMEOUT_MINUTES=60,MIN_THREAD_EVENT_LOG_BYTES=256*1024,MAX_THREAD_EVENT_LOG_BYTES=4*1024*1024*1024;function isValidSshAlias(value){return typeof value=="string"&&SSH_ALIAS.test(value)}var vpsConfigSchema=external_exports.object({sshAlias:external_exports.string().refine(value=>value===""||isValidSshAlias(value),{message:"must be a simple SSH config alias"}).optional()}),roomConfigSchema=external_exports.object({turnTimeoutMinutes:external_exports.number().int().min(MIN_ROOM_TURN_TIMEOUT_MINUTES).max(MAX_ROOM_TURN_TIMEOUT_MINUTES)}),mcpConfigSchema=external_exports.object({callTimeoutMinutes:external_exports.number().int().min(MIN_MCP_CALL_TIMEOUT_MINUTES).max(MAX_MCP_CALL_TIMEOUT_MINUTES).
|
|
1523
|
+
optional(),idleTimeoutMinutes:external_exports.number().int().min(1).max(60).optional(),egress:browserEgressConfigSchema.optional(),engine:external_exports.enum(["agent-browser","chrome"]).optional()});var roomContextSettings={roomCompactAt:external_exports.number().positive().max(1e7).optional(),roomSessions:external_exports.boolean().optional()};var GIB=1024**3;var startQueue=Promise.resolve();var MIN_DESKTOP_MEMORY_GB=2,MAX_DESKTOP_MEMORY_GB=128,MIN_DESKTOP_CPUS=1,MAX_DESKTOP_CPUS=64;var MIN_LOCAL_VM_MAX_INSTANCES=1,MAX_LOCAL_VM_MAX_INSTANCES=1024;var MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES=5,MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES=1440,localVmConfigSchema=external_exports.object({mode:external_exports.enum(["shared","per-bot","pool"]).optional(),automaticCapacity:external_exports.boolean().optional(),maxInstances:external_exports.number().int().min(MIN_LOCAL_VM_MAX_INSTANCES).max(MAX_LOCAL_VM_MAX_INSTANCES).optional(),idleTimeoutMinutes:external_exports.number().int().min(MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES).max(MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES).optional(),
|
|
1524
|
+
preserveInstalledApps:external_exports.boolean().optional(),memoryGb:external_exports.number().int().min(MIN_DESKTOP_MEMORY_GB).max(MAX_DESKTOP_MEMORY_GB).optional(),cpus:external_exports.number().int().min(MIN_DESKTOP_CPUS).max(MAX_DESKTOP_CPUS).optional()});var optionalText2=external_exports.string().optional(),SSH_ALIAS=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/,LEGACY_BROWSER_PROFILE_ID=/^[A-Za-z0-9_-]{1,40}$/,BROWSER_PROFILE_ID=/^[a-z0-9_-]{1,40}$/,FISH_TTS_MODELS=["s2.1-pro","s2.1-pro-free"];var MIN_ROOM_TURN_TIMEOUT_MINUTES=1,MAX_ROOM_TURN_TIMEOUT_MINUTES=1440;var MIN_MCP_CALL_TIMEOUT_MINUTES=1,MAX_MCP_CALL_TIMEOUT_MINUTES=60,MIN_THREAD_EVENT_LOG_BYTES=256*1024,MAX_THREAD_EVENT_LOG_BYTES=4*1024*1024*1024;function isValidSshAlias(value){return typeof value=="string"&&SSH_ALIAS.test(value)}var vpsConfigSchema=external_exports.object({sshAlias:external_exports.string().refine(value=>value===""||isValidSshAlias(value),{message:"must be a simple SSH config alias"}).optional()}),roomConfigSchema=external_exports.object({turnTimeoutMinutes:external_exports.number().int().min(MIN_ROOM_TURN_TIMEOUT_MINUTES).max(MAX_ROOM_TURN_TIMEOUT_MINUTES)}),mcpConfigSchema=external_exports.object({callTimeoutMinutes:external_exports.number().int().min(MIN_MCP_CALL_TIMEOUT_MINUTES).max(MAX_MCP_CALL_TIMEOUT_MINUTES).
|
|
1525
1525
|
optional()}).strict(),browserProfileSchema=external_exports.object({id:external_exports.string().regex(BROWSER_PROFILE_ID).refine(id2=>id2!=="guest","guest is reserved"),name:external_exports.string().trim().min(1).max(40),browser:external_exports.literal("chrome").optional()}).strict(),legacyBrowserProfileSchema=external_exports.object({id:external_exports.string().regex(LEGACY_BROWSER_PROFILE_ID).refine(id2=>id2!=="guest","guest is reserved"),name:external_exports.string().trim().min(1).max(40),
|
|
1526
1526
|
partitionId:external_exports.string().regex(LEGACY_BROWSER_PROFILE_ID).refine(id2=>id2!=="guest","guest is reserved").optional(),browser:external_exports.literal("chrome").optional()}).strict();function suffixedBrowserProfileId(base,unavailable){for(let suffix=2;;suffix+=1){let ending=`-${suffix}`,candidate=`${base.slice(0,40-ending.length)}${ending}`;if(candidate!=="guest"&&!unavailable.has(candidate))return candidate}}function migrateStoredBrowserProfiles(profiles){let requestedPartitions=profiles.
|
|
1527
1527
|
map(profile=>profile.partitionId??profile.id),rawBases=profiles.map(profile=>profile.id.toLowerCase()),canonicalIds=Array(profiles.length).fill(void 0),used=new Set,baseOwner=new Map;rawBases.forEach((base,index)=>{if(base==="guest")return;let current=baseOwner.get(base);(current===void 0||profiles[index].id===base&&profiles[current].id!==base)&&baseOwner.set(base,index)});for(let[base,index]of baseOwner)canonicalIds[index]=base,used.add(base);let reserved=new Set(["guest",...rawBases,...requestedPartitions.
|
|
@@ -1549,7 +1549,7 @@ language:optionalText2,computerName:external_exports.string().trim().max(63).opt
|
|
|
1549
1549
|
number().int().min(0).max(23).optional()}).strict().optional(),threads:threadsConfigSchema.optional(),burst:external_exports.object({maxParallel:external_exports.number().int().min(1).max(100).optional()}).strict().optional(),decisions:external_exports.object({retentionDays:external_exports.number().int().min(1).max(3650).optional()}).strict().optional(),loopGuard:loopGuardConfigSchema.optional(),safetyFloor:external_exports.object({enabled:external_exports.boolean().optional()}).strict().optional(),
|
|
1550
1550
|
localVm:localVmConfigSchema.optional(),features:featureConfigSchema.optional(),onboarding:onboardingConfigSchema.optional(),browserEngine:browserEngineConfigSchema.optional(),browserProfiles:browserProfilesSchema.optional(),instances:instanceConfigMapSchema.optional(),mcpServers:external_exports.record(external_exports.string(),external_exports.unknown()).optional()}),storedAppConfigSchema=appConfigSchema.extend(helperStoredShape).extend({browserProfiles:storedBrowserProfilesSchema.optional(),opencodeGo:external_exports.
|
|
1551
1551
|
object({apiKey:optionalText2,providerKeys:external_exports.record(external_exports.string(),external_exports.unknown()).catch({}).transform(keys=>Object.fromEntries(Object.entries(keys).filter(entry=>typeof entry[1]=="string"))).optional()}).optional()}),appConfigPatchSchema=appConfigSchema.omit({instances:!0,mcpServers:!0,cliStartup:!0,customDomain:!0}).extend({threads:threadsPatchSchema.optional(),newBots:newBotsPatchSchema.optional(),imageGen:imageGenPatchSchema.optional()}),jsonObjectSchema2=external_exports.
|
|
1552
|
-
record(external_exports.string(),external_exports.json());function parseStoredConfig(value){let parsed=storedAppConfigSchema.safeParse(value);if(!parsed.success)throw new Error(schemaIssue(parsed.error,"Invalid stored configuration"));return parsed.data}var DEFAULT_CAPTURE_QUIET_MS=2*6e4;var DATA_DIR=process.env.OMB_DATA_DIR||join3(dataHome(),".limixbot"),LEGACY_DATA_DIR=join3(dataHome(),".opengrokbot"),EVENTS_DIR=join3(DATA_DIR,"events"),NATIVE_DIR=join3(DATA_DIR,"native");var storedConfig=settledFileCache(()=>join3(DATA_DIR,"config.json"),()=>parseStoredConfig(parseJson(readFileSync3(join3(DATA_DIR,"config.json"),"utf8"))));var SECRET_FOLDER=".limixbot-secrets";function inSecretFolder(path){return path.split(/[\\/]/).includes(SECRET_FOLDER)}var PORTABLE_CONFIG_KEYS=["profile","language","budgets","billing","rooms","threads","localVm","features","browserProfiles"];function portableWorkspaceConfig(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid workspace configuration in backup.");let config2=parseStoredConfig(value);return Object.fromEntries(PORTABLE_CONFIG_KEYS.filter(key=>config2[key]!==void 0).map(key=>[key,config2[key]]))}function excludedWorkspaceAuthPath(path){return inSecretFolder(path)||/^command-allowlist\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^mcp-oauth\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^(?:logins\.json\.enc|logins-key|webhook-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^connected-apps-installation\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^team-policy\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^people-connections(?:\/|$)/.test(path)?!0:/^(?:(?:providers|caddy|chrome-profile|\.agent-browser)(?:\/|$)|workspace-credentials\.json$|external-runtimes\.json$|browser-engine-key$)/.
|
|
1552
|
+
record(external_exports.string(),external_exports.json());function parseStoredConfig(value){let parsed=storedAppConfigSchema.safeParse(value);if(!parsed.success)throw new Error(schemaIssue(parsed.error,"Invalid stored configuration"));return parsed.data.localVm&&parsed.data.localVm.automaticCapacity===void 0&&(parsed.data.localVm.automaticCapacity=!0),parsed.data}var DEFAULT_CAPTURE_QUIET_MS=2*6e4;var DATA_DIR=process.env.OMB_DATA_DIR||join3(dataHome(),".limixbot"),LEGACY_DATA_DIR=join3(dataHome(),".opengrokbot"),EVENTS_DIR=join3(DATA_DIR,"events"),NATIVE_DIR=join3(DATA_DIR,"native");var storedConfig=settledFileCache(()=>join3(DATA_DIR,"config.json"),()=>parseStoredConfig(parseJson(readFileSync3(join3(DATA_DIR,"config.json"),"utf8"))));var SECRET_FOLDER=".limixbot-secrets";function inSecretFolder(path){return path.split(/[\\/]/).includes(SECRET_FOLDER)}var PORTABLE_CONFIG_KEYS=["profile","language","budgets","billing","rooms","threads","localVm","features","browserProfiles"];function portableWorkspaceConfig(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid workspace configuration in backup.");let config2=parseStoredConfig(value);return Object.fromEntries(PORTABLE_CONFIG_KEYS.filter(key=>config2[key]!==void 0).map(key=>[key,config2[key]]))}function excludedWorkspaceAuthPath(path){return inSecretFolder(path)||/^command-allowlist\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^mcp-oauth\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^(?:logins\.json\.enc|logins-key|webhook-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^connected-apps-installation\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^team-policy\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^people-connections(?:\/|$)/.test(path)?!0:/^(?:(?:providers|caddy|chrome-profile|\.agent-browser)(?:\/|$)|workspace-credentials\.json$|external-runtimes\.json$|browser-engine-key$)/.
|
|
1553
1553
|
test(path)||/^(?:config\.json|webhooks\.json|workspace-credentials\.json|external-runtimes\.json|browser-engine-key|sessions\.json|tunnel-account\.json)\.\d+(?:\.[0-9a-f-]+)?\.tmp$/.test(path)||/^(?:vm-home|vm-homes\/[^/]+)\/\.browser-profiles(?:\/|$)/.test(path)}function redownloadedOrgLibraryPath(path){return/^org-library\/(?:catalog\.json(?:\.[0-9a-f-]{36}\.tmp)?$|blobs(?:\/|$))/.test(path)}function ephemeralWorkspaceTokenPath(path){return/^(?:hook-tokens(?:\/|$)|sessions\.json\.open$)/.test(
|
|
1554
1554
|
path)}function liveDataEnginePath(path){return/^bots\/[^/]+\/(?:data\.duckdb(?:\.wal)?$|data-tmp(?:\/|$))/.test(path)}function managedTaskSkillLink(source,path,roots){let match=/^task-workspaces\/([^/]+)\/[^/]+\/\.(?:claude|agents|grok)\/skills\/([^/]+)$/.exec(path);if(!match)return!1;let target;try{target=resolve(dirname(source),readlinkSync(source).replace(/^\\\\\?\\/,""))}catch{return!1}return roots.some(root=>{let rel=relative(join4(root,"workspaces",match[1],"skills"),target);return rel!==""&&
|
|
1555
1555
|
!rel.startsWith("..")&&!isAbsolute2(rel)||relative(join4(root,"imported-skills",match[2]),target)===""})}import{existsSync as existsSync2,readdirSync as readdirSync2,readFileSync as readFileSync4}from"node:fs";import{join as join12}from"node:path";import{DatabaseSync as DatabaseSync2}from"node:sqlite";import{createHash}from"node:crypto";var CLOUD_OUTSIDE_KEY=`p_${createHash("sha256").update("cloud-outside").digest("base64url").slice(0,22)}`,CLOUD_NOBODY_KEY=`p_${createHash("sha256").update("cloud-nobody").digest("base64url").slice(0,22)}`;import{join as join11}from"node:path";import{appendFileSync}from"node:fs";import{join as join5}from"node:path";import{closeSync as closeSync2,fstatSync as fstatSync2,openSync as openSync2,readSync,renameSync as renameSync3,rmSync,statSync as statSync2,writeSync}from"node:fs";var capProvider=()=>null;function currentThreadLogCap(){try{return capProvider()}catch{return null}}function capThreadLog(file2,maxBytes){if(typeof maxBytes!="number"||!Number.isFinite(maxBytes)||maxBytes<=0)return;let size;try{size=statSync2(file2).size}catch{return}size<=maxBytes||trimToTail(file2,Math.max(1,Math.floor(maxBytes/2)))}function trimToTail(file2,keepBytes){let staging=`${file2}.trim`;try{let source=openSync2(file2,"r");try{let size=fstatSync2(source).size,start=Math.max(0,size-keepBytes),window=Buffer.allocUnsafe(
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as l,t as s,j as t,X as $,a as X}from"./styles-BRMaHK08.js";import{c as ee,B as te,L as G}from"./PlacesRail-dslg5RRJ.js";import{u as ae,z as F,D as L}from"./App-AKtlUFTy.js";import{suggestedName as H}from"./WebhookTrigger-BfyyC34L.js";import"./monitor-C-EBTsrK.js";import"./index-BPNGi-6U.js";import"./MenuMotion-BOUToDZz.js";import"./remote-desktop-DDRRx8uY.js";const N="w-full rounded-xl border border-hairline/60 bg-panel px-3.5 py-2.5 text-[13px] text-ink outline-none placeholder:text-ink-tertiary focus:border-accent/70",m="mb-1.5 block text-[12px] font-medium text-ink-secondary";function de({trigger:a,bots:x,initialBotId:y,onClose:u,onSaved:J}){const{dispatch:K}=ae(),[i,Q]=l.useState(a?.botId??(y&&x.some(e=>e.id===y)?y:x[0]?.id)??""),[r,O]=l.useState(null),[v,B]=l.useState(a?.app??""),[b,g]=l.useState(a?.event??""),[k,U]=l.useState(a?.accountId??""),[D,V]=l.useState(a?.filter??{}),[f,E]=l.useState({}),[h,W]=l.useState(a?.prompt??""),[w,Y]=l.useState(a?.name??""),[I,P]=l.useState(!1),[S,C]=l.useState(""),R=l.useRef(null);ee(R,u),l.useEffect(()=>{if(a||!i)return;let e=!0;return O(null),F.events(i).then(n=>{if(!e)return;O(n);const o=n.apps.find(d=>d.events.length);B(d=>n.apps.some(A=>A.app===d)?d:o?.app??"")}).catch(n=>{e&&C(n instanceof Error?n.message:String(n))}),()=>{e=!1}},[i,a]);const p=r?.apps.find(e=>e.app===v),z=p?.events??[],c=z.find(e=>e.event===b)??(a?void 0:z[0]);l.useEffect(()=>{!a&&c&&c.event!==b&&g(c.event)},[c,b,a]);const T=(c?.configFields??[]).filter(e=>e.required),Z=v==="gmail",q=a?.delivery??c?.delivery,_=async()=>{const e=x.find(o=>o.id===i),n=Object.fromEntries(Object.entries(D).filter(([,o])=>typeof o=="string"&&o.trim()));P(!0),C("");try{const o=a?await F.update(a.id,{name:w.trim()||a.name,prompt:h.trim(),filter:Object.keys(n).length?n:null}):await F.create({botId:i,app:v,event:c?.event??b,prompt:h.trim(),name:w.trim()||H(h,e),...k?{account:k}:{},...Object.keys(n).length?{filter:n}:{},...Object.keys(f).length?{config:f}:{}});J?.(o),u()}catch(o){C(o instanceof Error?o.message:String(o))}finally{P(!1)}},j=(e,n,o)=>t.jsxs("label",{className:"block",children:[t.jsx("span",{className:m,children:n}),t.jsx("input",{value:D[e]??"",onChange:d=>V(A=>({...A,[e]:d.target.value})),placeholder:o,className:N})]},e),M=a?s("automations.editor.app.editTitle"):s("automations.editor.appEvent.title");return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-5",onMouseDown:e=>e.target===e.currentTarget&&u(),children:t.jsxs("div",{ref:R,role:"dialog","aria-modal":"true","aria-label":M,tabIndex:-1,className:"flex max-h-[90vh] w-full max-w-[560px] flex-col overflow-hidden rounded-2xl border border-hairline/60 bg-panel shadow-2xl",children:[t.jsxs("div",{className:"flex items-start justify-between border-b border-hairline/40 px-5 py-4",children:[t.jsx("div",{className:"text-[17px] font-semibold text-ink",children:M}),t.jsx("button",{type:"button",onClick:u,"aria-label":s("automations.newBox.cancel"),className:"rounded-lg p-2 text-ink-secondary hover:bg-raised hover:text-ink",children:t.jsx($,{size:18})})]}),t.jsxs("div",{className:"min-h-0 flex-1 space-y-5 overflow-y-auto p-5",children:[!a&&t.jsxs("div",{children:[t.jsx("div",{className:"mb-2 text-[13px] font-medium text-ink",children:s("automations.editor.app.who")}),t.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3",children:x.map(e=>t.jsxs("button",{type:"button",onClick:()=>Q(e.id),className:X("flex min-w-0 items-center gap-2 rounded-xl border px-3 py-2 text-left",i===e.id?"border-accent/70 bg-accent/10":"border-hairline/50 bg-inset hover:bg-raised/60"),children:[t.jsx(te,{bot:e,state:i===e.id?"happy":"idle",size:32,animated:!1}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] font-medium text-ink",children:e.name})]},e.id))})]}),!a&&!r&&!S&&t.jsxs("p",{className:"flex items-center gap-2 text-[13px] text-ink-secondary",children:[t.jsx(G,{size:14,className:"animate-spin"}),s("automations.editor.appEvent.loading")]}),!a&&r&&(r.unavailable||!r.apps.some(e=>e.events.length))&&t.jsxs("div",{className:"rounded-xl border border-hairline/45 bg-inset/50 p-3.5 text-[13px] text-ink-secondary",children:[t.jsx("p",{children:r.unavailable??s("automations.editor.appEvent.noApps")}),!r.unavailable&&t.jsx("button",{type:"button",onClick:()=>K({type:"togglePlugins",open:!0,surface:"apps"}),className:"mt-2.5 rounded-lg bg-accent px-3 py-1.5 text-[13px] font-medium text-accent-ink hover:brightness-110",children:s("automations.editor.appEvent.connect")})]}),!a&&r&&p&&t.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[t.jsxs("label",{className:"block",children:[t.jsx("span",{className:m,children:s("automations.editor.appEvent.app")}),t.jsx(L,{value:v,onChange:e=>{B(e.target.value),g(""),E({})},"aria-label":s("automations.editor.appEvent.app"),className:"w-full",children:r.apps.filter(e=>e.events.length).map(e=>t.jsx("option",{value:e.app,children:e.name},e.app))})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:m,children:s("automations.editor.appEvent.event")}),t.jsx(L,{value:c?.event??"",onChange:e=>{g(e.target.value),E({})},"aria-label":s("automations.editor.appEvent.event"),className:"w-full",children:z.map(e=>t.jsx("option",{value:e.event,children:e.name},e.event))})]}),p.accounts.length>1&&t.jsxs("label",{className:"block sm:col-span-2",children:[t.jsx("span",{className:m,children:s("automations.editor.appEvent.account")}),t.jsxs(L,{value:k,onChange:e=>U(e.target.value),"aria-label":s("automations.editor.appEvent.account"),className:"w-full",children:[t.jsx("option",{value:""}),p.accounts.map(e=>t.jsx("option",{value:e.id,children:e.alias??e.id},e.id))]})]}),T.map(e=>t.jsxs("label",{className:"block sm:col-span-2",children:[t.jsx("span",{className:m,children:e.name}),t.jsx("input",{value:f[e.name]??"",onChange:n=>E(o=>({...o,[e.name]:n.target.value})),placeholder:e.description,className:N})]},e.name))]}),(a||p)&&t.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[Z?[j("from",s("automations.editor.appEvent.from"),"acme.com"),j("subject",s("automations.editor.appEvent.subject"),"order"),j("label",s("automations.editor.appEvent.label"),"Customers")]:j("text",s("automations.editor.appEvent.text"),"urgent"),q&&t.jsx("p",{className:"self-end text-[12px] text-ink-secondary sm:col-span-2",children:q==="poll"?s("automations.editor.appEvent.checks"):s("automations.editor.appEvent.instant")})]}),(a||p)&&t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"mb-2 block text-[13px] font-medium text-ink",children:s("automations.editor.app.what")}),t.jsx("textarea",{value:h,onChange:e=>W(e.target.value),rows:3,placeholder:s("automations.editor.appEvent.whatPlaceholder"),className:X(N,"resize-y py-3 leading-relaxed")})]}),(a||p)&&t.jsxs("details",{className:"rounded-xl border border-hairline/45 bg-inset/45 px-4 py-3",children:[t.jsx("summary",{className:"cursor-pointer text-[13px] font-medium text-ink",children:s("automations.more")}),t.jsxs("label",{className:"mt-4 block",children:[t.jsx("span",{className:m,children:s("automations.editor.app.name")}),t.jsx("input",{value:w,onChange:e=>Y(e.target.value),placeholder:H(h,x.find(e=>e.id===i)),className:N})]})]}),S&&t.jsx("div",{role:"alert",className:"rounded-xl border border-danger/30 bg-danger/10 px-3.5 py-3 text-[12px] text-danger",children:S})]}),t.jsxs("div",{className:"flex justify-end gap-2 border-t border-hairline/40 px-5 py-4",children:[t.jsx("button",{type:"button",onClick:u,className:"rounded-xl px-4 py-2 text-[13px] text-ink-secondary hover:bg-raised hover:text-ink",children:s("automations.newBox.cancel")}),t.jsxs("button",{type:"button",disabled:I||!i||!a&&!c||T.some(e=>!f[e.name]?.trim()),onClick:()=>{_()},className:"flex items-center gap-2 rounded-xl bg-accent px-4 py-2 text-[13px] font-medium text-accent-ink hover:brightness-110 disabled:opacity-40",children:[I&&t.jsx(G,{size:14,className:"animate-spin"}),a?s("automations.editor.app.save"):s("automations.editor.app.create")]})]})]})})}export{de as AppEventEditor};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{c as Tt,r as a,j as n,t as s,X as Ue,f as Mt,al as Kt}from"./styles-BRMaHK08.js";import{G as lt,Z as Rt,d3 as Vt,bH as qt,dj as Gt,cI as Xt,eb as Yt,ec as Jt,dk as Zt,W as Qt,u as dt,ed as en,J as tn,ee as nn,n as Ge,ef as It,P as rn,bO as sn}from"./App-AKtlUFTy.js";import{w as zt,b as on,B as an}from"./BrowserProfilesManager-CYFWUNHq.js";import{P as At,L as Xe,Z as ln,K as ht,X as cn}from"./PlacesRail-dslg5RRJ.js";import{M as un,a as dn}from"./minimize-BfKI3Nbu.js";import{F as fn}from"./file-up-CEuHjVBK.js";const pn=[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]],hn=Tt("mouse-pointer-2",pn);const mn=[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8",key:"17vawe"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6",key:"chjx8e"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6",key:"lav6yq"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3",key:"1pxi2q"}]],bn=Tt("shrink",mn);function xn(){const[e,t]=a.useState(()=>document.visibilityState==="visible");return a.useEffect(()=>{const r=()=>t(document.visibilityState==="visible");return document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[]),e}const je="rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink disabled:cursor-not-allowed disabled:opacity-40";function wn(e,t,r){return!e||!t?"connecting":r==="pending"?"taking":r==="slow"?"waiting":t.controller==="you"?"yours":t.owned?"held":t.controller==="another-viewer"?"elsewhere":t.controller==="agent"?"bot":"watching"}const mt={connecting:()=>s("browser.panel.connecting"),watching:()=>s("browser.control.watching"),bot:e=>s("browser.control.botHas",{name:e}),yours:()=>s("vm.workspace.youHaveControl"),held:e=>s("browser.control.held",{name:e}),elsewhere:()=>s("browser.control.elsewhere"),taking:()=>s("browser.control.taking"),waiting:e=>s("browser.control.waiting",{name:e})},yn=a.forwardRef(function(t,r){const{botName:o,tabs:i,nav:c,connected:u,control:w,takeStatus:v,commandsReady:m}=t,[d,g]=a.useState(""),[y,E]=a.useState(!1),k=wn(u,w,v),C=k==="yours",T=C||k==="held",b=c.url==="about:blank"?"":c.url;return n.jsxs("div",{className:"shrink-0 border-b border-hairline/40",children:[n.jsxs("div",{className:"flex min-h-10 items-center gap-1 px-2 pt-1",children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto",role:"tablist","aria-label":s("browser.panel.tabs"),children:[i.length?i.map(j=>n.jsxs("div",{className:`flex max-w-52 shrink-0 items-center gap-1 rounded-xl px-1 text-[12px] ${j.active?"bg-inset text-ink":"text-ink-secondary"}`,children:[n.jsx(lt,{size:13,className:"ml-1.5 shrink-0 opacity-60","aria-hidden":"true"}),n.jsx("button",{role:"tab","aria-selected":j.active,className:"truncate px-1 py-1.5 text-left disabled:cursor-default",disabled:!m,onClick:()=>t.onCommand({type:"tabSelect",tabId:j.tabId}),title:j.title||j.url,children:j.title||s("browser.panel.newTab")}),n.jsx("button",{className:je,"aria-label":s("browser.panel.closeTab",{title:j.title||s("browser.panel.tab")}),disabled:!m,onClick:()=>t.onCommand({type:"tabClose",tabId:j.tabId}),children:n.jsx(Ue,{size:13})})]},j.tabId)):n.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-inset px-3 py-1.5 text-[12px] text-ink-secondary",children:[n.jsx(lt,{size:13,"aria-hidden":"true"}),s("browser.panel.newTab")]}),n.jsx("button",{className:`${je} shrink-0`,disabled:!m,"aria-label":s("browser.panel.newTab"),title:s("browser.panel.newTab"),onClick:()=>t.onCommand({type:"tabNew"}),children:n.jsx(At,{size:16})})]}),n.jsxs("button",{type:"button","aria-pressed":T,"aria-label":`${mt[k](o)}. ${s(T?"browser.control.handBack":"browser.control.take")}`,"aria-description":C?t.hint:void 0,title:C&&t.hint?t.hint:s(T?"browser.control.handBack":"browser.control.take"),disabled:!u||k==="elsewhere"||k==="connecting"||k==="taking"||k==="waiting",onClick:T?t.onHandBack:t.onTake,className:`flex max-w-56 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border px-2.5 py-1 text-[11px] disabled:cursor-default ${T?"border-accent-border bg-accent/15 text-accent-text":"border-hairline text-ink-secondary hover:bg-inset hover:text-ink"}`,"data-pill":k,children:[k==="taking"||k==="waiting"||k==="connecting"?n.jsx(Xe,{size:12,className:"shrink-0 animate-spin","aria-hidden":"true"}):n.jsx(Rt,{size:12,className:"shrink-0","aria-hidden":"true"}),n.jsx("span",{className:"truncate",children:mt[k](o)}),k==="bot"||k==="watching"?n.jsxs("span",{className:"shrink-0 text-ink",children:["· ",s("browser.control.take")]}):T?n.jsxs("span",{className:"shrink-0",children:["· ",s("browser.control.handBack")]}):null]}),n.jsx("button",{className:je,title:s(t.maximized?"browser.panel.restore":"browser.panel.maximizeHint"),"aria-label":s(t.maximized?"browser.panel.restore":"browser.panel.maximize"),onClick:t.onMaximize,children:t.maximized?n.jsx(bn,{size:15}):n.jsx(Vt,{size:15})}),n.jsx("button",{className:je,title:s(t.fullscreen?"browser.panel.exitFullscreen":"browser.panel.fullscreenHint"),"aria-label":s(t.fullscreen?"browser.panel.exitFullscreen":"browser.panel.fullscreen"),onClick:t.onFullscreen,children:t.fullscreen?n.jsx(un,{size:15}):n.jsx(dn,{size:15})}),n.jsx("button",{className:`${je} rounded-xl bg-inset p-1.5`,title:s("browser.panel.profileTitle",{name:t.profileName}),"aria-label":s("browser.panel.profiles"),onClick:t.onProfiles,children:n.jsx(ln,{size:15})})]}),n.jsxs("form",{className:"relative flex h-10 items-center gap-1 px-2",onSubmit:j=>{j.preventDefault(),t.onAddress(d),(r&&typeof r=="object"?r.current:null)?.blur()},children:[n.jsxs("div",{className:"flex shrink-0 items-center",role:"group","aria-label":s("browser.panel.navigation"),children:[n.jsx("button",{type:"button",className:je,disabled:!m||!c.canGoBack,"aria-label":s("browser.panel.back"),title:s("browser.panel.back"),onClick:()=>t.onCommand({type:"history",delta:-1}),children:n.jsx(qt,{size:16})}),n.jsx("button",{type:"button",className:je,disabled:!m||!c.canGoForward,"aria-label":s("browser.panel.forward"),title:s("browser.panel.forward"),onClick:()=>t.onCommand({type:"history",delta:1}),children:n.jsx(Gt,{size:16})}),n.jsx("button",{type:"button",className:je,disabled:!m,"aria-label":s(c.loading?"browser.panel.loadingReload":"browser.panel.reload"),title:s("browser.panel.reloadShort"),onClick:()=>t.onCommand({type:"reload"}),children:c.loading?n.jsx(Xe,{size:16,className:"animate-spin"}):n.jsx(Xt,{size:16})})]}),n.jsx("input",{ref:r,"aria-label":s("browser.panel.address"),readOnly:!m,value:y?d:b,onChange:j=>g(j.target.value),onFocus:j=>{g(b),E(!0),m&&queueMicrotask(()=>j.target.select())},onBlur:()=>E(!1),onKeyDown:j=>{j.key==="Escape"&&(j.preventDefault(),g(b),j.currentTarget.blur())},placeholder:s(u?"browser.panel.searchOrAddress":"browser.panel.connecting"),spellCheck:!1,className:"mx-1 min-w-0 flex-1 rounded-lg bg-transparent px-2 py-1.5 text-center text-[12px] outline-none placeholder:text-ink-secondary focus:bg-inset focus:text-left"}),t.menu,n.jsx("div",{"aria-hidden":"true","data-loading":c.loading,className:`pointer-events-none absolute bottom-0 left-0 h-0.5 bg-accent transition-[width,opacity] duration-500 ${c.loading?"w-2/3 opacity-100":"w-full opacity-0"}`})]})]})});function gn(e){return Array.isArray(e)?e.flatMap(t=>{const{id:r,name:o}=t??{};return typeof r=="string"&&typeof o=="string"?[{id:r,name:o}]:[]}):[]}const kn="flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left hover:bg-inset disabled:cursor-not-allowed disabled:opacity-40";function vn({ready:e,extensions:t,onList:r,onOpen:o}){const i=a.useRef(null);return a.useEffect(()=>{e&&i.current?.open&&r()},[e]),n.jsxs("details",{ref:i,className:"relative shrink-0",onToggle:c=>{c.currentTarget.open&&e&&r()},children:[n.jsx("summary",{className:"list-none cursor-pointer rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink [&::-webkit-details-marker]:hidden","aria-label":s("browser.extensions.title"),title:s("browser.extensions.title"),children:n.jsx(Yt,{size:16})}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-2 flex max-h-80 w-56 flex-col overflow-y-auto rounded-xl border border-hairline/50 bg-card p-1 text-[12px] text-ink shadow-xl",role:"menu",children:[n.jsx("div",{className:"px-3 pb-1 pt-1.5 text-[11px] text-ink-tertiary",children:s("browser.extensions.title")}),e?t&&t.length===0?n.jsx("div",{className:"px-3 py-1.5 text-ink-secondary",children:s("browser.extensions.empty")}):(t??[]).map(c=>n.jsx("button",{type:"button",role:"menuitem",className:kn,onClick:()=>{i.current?.removeAttribute("open"),o(c.id)},children:n.jsx("span",{className:"truncate",children:c.name})},c.id)):n.jsx("div",{className:"px-3 py-1.5 text-ink-secondary",children:s("browser.extensions.takeControl")})]})]})}const _e=[.25,.33,.5,.67,.75,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3,4,5];function bt(e,t){return t>0?_e.find(r=>r>e+.001)??_e.at(-1):[..._e].reverse().find(r=>r<e-.001)??_e[0]}const Cn=[{label:"browser.viewport.fill",setting:{mode:"fill"}},{label:"browser.viewport.fullHd",setting:{mode:"preset",preset:"fullHd"}},{label:"browser.viewport.desktop",setting:{mode:"preset",preset:"desktop"}},{label:"browser.viewport.tablet",setting:{mode:"preset",preset:"tablet"}},{label:"browser.viewport.phone",setting:{mode:"preset",preset:"phone"}}],xt=(e,t)=>e.mode===t.mode&&(e.mode!=="preset"||t.mode==="preset"&&e.preset===t.preset),Ae="flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left hover:bg-inset disabled:cursor-not-allowed disabled:opacity-40",Qe="rounded-md border border-hairline p-1 text-ink-secondary hover:bg-inset hover:text-ink disabled:opacity-40";function Sn({stream:e,ready:t,typing:r,setting:o,zoom:i,pip:c,onViewport:u,onZoom:w,onPip:v,onType:m,onSecret:d,onReconnect:g,onRestart:y}){const E=a.useRef(null),k=T=>()=>{E.current?.removeAttribute("open"),T()},C=T=>n.jsx("div",{className:"border-b border-hairline/40 py-1 last:border-b-0",children:T});return n.jsxs("details",{ref:E,className:"relative shrink-0",children:[n.jsx("summary",{className:"list-none cursor-pointer rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink [&::-webkit-details-marker]:hidden","aria-label":s("browser.panel.menu"),title:s("browser.panel.menu"),children:n.jsx(Jt,{size:16})}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-2 flex w-56 flex-col rounded-xl border border-hairline/50 bg-card p-1 text-[12px] text-ink shadow-xl",role:"menu",children:[e?C(n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"px-3 pb-1 pt-1.5 text-[11px] text-ink-tertiary",children:s("browser.viewport.title")}),Cn.map(T=>n.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":xt(T.setting,o),className:Ae,disabled:!t,onClick:k(()=>u(T.setting)),children:[n.jsx("span",{className:"w-3.5 shrink-0",children:xt(T.setting,o)?n.jsx(Mt,{size:13,"aria-hidden":"true"}):null}),s(T.label)]},T.label)),n.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[n.jsx("span",{children:s("settings.profile.avatar.zoom")}),n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("button",{type:"button",className:Qe,"aria-label":s("browser.zoom.out"),disabled:!t||i<=_e[0],onClick:()=>w(bt(i,-1)),children:n.jsx(Zt,{size:12})}),n.jsxs("span",{className:"min-w-11 text-center tabular-nums text-ink-secondary","aria-live":"polite",children:[Math.round(i*100),"%"]}),n.jsx("button",{type:"button",className:Qe,"aria-label":s("browser.zoom.in"),disabled:!t||i>=_e.at(-1),onClick:()=>w(bt(i,1)),children:n.jsx(At,{size:12})}),n.jsx("button",{type:"button",className:Qe,"aria-label":s("browser.zoom.reset"),disabled:!t||i===1,onClick:()=>w(1),children:n.jsx(Qt,{size:12})})]})]})]})):null,C(n.jsxs(n.Fragment,{children:[e&&c?n.jsx("button",{type:"button",role:"menuitem",className:Ae,onClick:k(v),children:s(c.open?"browser.pip.close":"browser.pip.open")}):null,n.jsx("button",{type:"button",role:"menuitem",className:Ae,disabled:!r,onClick:k(m),children:s("browser.panel.typeTextMenu")}),n.jsx("button",{type:"button",role:"menuitem",className:Ae,disabled:!r,onClick:k(d),children:s("browser.typeSecret")})]})),C(n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",role:"menuitem",className:Ae,onClick:k(g),children:s("browser.panel.reconnectView")}),n.jsx("button",{type:"button",role:"menuitem",className:Ae,onClick:k(y),children:s("browser.panel.restartBrowser")})]}))]})]})}function jn(e){const[t,r]=a.useState(null);return a.useEffect(()=>{if(!e)return;let o=!0;return Ge("/api/shared-computers").then(i=>{o&&r(i.computers?.find(c=>c.online&&c.scopes?.screen)?.name??null)}).catch(()=>{}),()=>{o=!1}},[e]),t}function En({wall:e,botName:t,onDismiss:r}){const{state:o,dispatch:i}=dt(),c=o.config?.cloudHome===!0,u=jn(c),w=e==="google"?"Google":"Microsoft";return n.jsx("section",{role:"status","aria-label":s("browser.passkey.title"),className:"shrink-0 border-b border-hairline/30 bg-inset/60 px-3 py-2.5 text-[12px] leading-relaxed text-ink-secondary",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(en,{size:14,className:"mt-0.5 shrink-0 text-accent-text","aria-hidden":"true"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"font-medium text-ink",children:s("browser.passkey.title")}),n.jsx("p",{children:s("browser.passkey.body",{provider:w})}),n.jsxs("ol",{className:"mt-1 list-decimal space-y-1 pl-4",children:[n.jsxs("li",{children:[s(e==="google"?"browser.passkey.appsGoogle":"browser.passkey.appsMicrosoft",{name:t})," ",n.jsx("button",{type:"button",className:"text-accent-text underline",onClick:()=>i({type:"togglePlugins",open:!0,surface:"apps"}),children:s("browser.passkey.connect")})]}),n.jsx("li",{children:s(e==="google"?"browser.passkey.otherWayGoogle":"browser.passkey.otherWayMicrosoft")}),c&&n.jsx("li",{children:u?s("browser.passkey.lentPc",{computer:u,name:t}):s("browser.passkey.lendPc",{name:t})})]}),n.jsx("button",{type:"button",className:"mt-1 text-accent-text underline",onClick:()=>{tn(nn)},children:s("browser.passkey.learnMore")})]}),n.jsx("button",{type:"button",className:"rounded-md p-1 text-ink-tertiary hover:bg-inset hover:text-ink","aria-label":s("browser.passkey.dismiss"),onClick:r,children:n.jsx(Ue,{size:14})})]})})}const Nn=4503,Pn=4404,Tn="sudo limixbot browser install --with-deps",Mn="https://github.com/milind-soni/OpenMausBot/blob/main/docs/deploy-vps.md#ubuntu-2404-browser-sandbox",ft=(e,t)=>{const r=Object.entries(t.query);if(r.length===0)return e;const o=e.includes("?")?"&":"?";return`${e}${o}${new URLSearchParams(r).toString()}`};function Lt(e,t=window.location,r={}){const o=`/api/bots/${encodeURIComponent(e)}/browser`;return{httpBase:`${t.protocol}//${t.host}${o}`,wsBase:`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}${o}`,query:{...r},credentials:!0}}const Rn=e=>e===null||typeof e=="object"&&"type"in e&&typeof e.type=="string"&&"message"in e&&typeof e.message=="string"&&"defaultValue"in e&&typeof e.defaultValue=="string",In=(e,t)=>ft(`${e.access.httpBase}/upload?${new URLSearchParams({chooser:t}).toString()}`,e.access);async function zn(e,t){const r=new FormData;for(const i of t)r.append("file",i,i.name??"file");const o=await fetch(e.uploadUrl,{method:"POST",body:r,credentials:e.credentials?"include":"omit"});if(!o.ok){const i=await o.text();let c=i;try{c=JSON.parse(i).error??i}catch{}throw new Error(c||s("browser.page.uploadRefused"))}}const An=(e,t)=>ft(`${e.access.httpBase}/download/${encodeURIComponent(t)}`,e.access),et=e=>(e.altKey?1:0)|(e.ctrlKey?2:0)|(e.metaKey?4:0)|(e.shiftKey?8:0),Ln=(e,t)=>e.type==="takeControl"||e.type==="resize"||e.type==="frameCap"||e.type==="restart"||e.type==="wake"||e.type==="releaseControl"&&t.owned===!0||t.controller==="you",_n=JSON.stringify({type:"ack"});function _t(e,t){let r={width:e.maxWidth,height:e.maxHeight},o=e.width!==void 0&&e.height!==void 0?{width:e.width,height:e.height}:null;const i=()=>{const y=new URLSearchParams({maxWidth:String(Math.max(1,Math.round(r.width))),maxHeight:String(Math.max(1,Math.round(r.height)))});return o&&(y.set("width",String(Math.round(o.width))),y.set("height",String(Math.round(o.height)))),e.interactive===!1&&y.set("interactive","false"),ft(`${e.access.wsBase}/stream?${y.toString()}`,e.access)};let c=!1,u=null,w=null,v=0,m=null,d=null;const g=()=>{if(c)return;const y={cap:r,size:o},E=new WebSocket(i());E.binaryType="arraybuffer",u=E;let k=!1;E.addEventListener("open",()=>{u===E&&(k=!0,t.onConnectedChange(!0))}),E.addEventListener("message",C=>{if(u!==E)return;if(C.data instanceof ArrayBuffer){v=0,E.send(_n),t.onFrame(C.data);return}if(typeof C.data!="string")return;let T;try{T=JSON.parse(C.data)}catch{return}if(typeof T!="object"||T===null)return;const{type:b,x:j,y:O,width:H,height:le,editable:re,canOperate:J,controller:Y,generation:$,dialog:x,stale:K,owned:B,text:V,id:Z,fileName:W,sizeBytes:te,multiple:P,accept:R,phase:D,sequence:U,tabId:q}=T;if(b==="fileChooser"&&typeof Z=="string"&&typeof P=="boolean"&&typeof R=="string")d=Z,t.onFileChooser?.({multiple:P,accept:R,uploadUrl:In(e,Z),credentials:e.access.credentials});else if(b==="fileChooserClosed"&&typeof Z=="string"){if(d!==Z)return;d=null,t.onFileChooser?.(null)}else if(b==="pointer"&&(D==="move"||D==="click")&&typeof j=="number"&&typeof O=="number"&&typeof U=="number")t.onPointer?.({phase:D,x:j,y:O,sequence:U});else if(b==="popup"&&typeof q=="string")t.onPopup?.(q);else if(b==="clipboard"&&typeof V=="string")t.onClipboard?.(V);else if(b==="download"&&typeof Z=="string"&&typeof W=="string"&&typeof te=="number")t.onDownload?.({fileName:W,sizeBytes:te,url:An(e,Z)});else if(b==="viewport"&&typeof H=="number"&&typeof le=="number")v=0,t.onViewport({width:H,height:le}),t.onMessage?.(T);else if(b==="probe"&&typeof j=="number"&&typeof O=="number"&&typeof re=="boolean")t.onProbe?.({x:j,y:O,editable:re});else if(b==="control"&&typeof J=="boolean"&&(Y==="agent"||Y==="you"||Y==="another-viewer"||Y==="unclaimed")&&typeof $=="number"&&Rn(x)){const N={canOperate:J,controller:Y,generation:$,dialog:x,...K===!0?{stale:!0}:{},...B===!0?{owned:!0}:{}},A=m===null;m=N,A&&J&&r!==y.cap&&E.send(JSON.stringify({type:"frameCap",maxWidth:r.width,maxHeight:r.height})),A&&J&&o&&o!==y.size&&E.send(JSON.stringify({type:"resize",...o})),t.onControl?.(N)}else typeof b=="string"&&t.onMessage?.(T)}),E.addEventListener("close",C=>{if(u===E&&(u=null,m=null,k&&t.onConnectedChange(!1),!c)){if(t.onClose?.(C.code,C.reason),C.code===Pn){c=!0,t.onGone?.();return}if(C.code===Nn){c=!0,t.onHostSetup?.(Bn(C.reason));return}if(C.code===1008||C.code===4401||!k&&C.code===1006){c=!0,t.onUnauthorized();return}w=setTimeout(g,Math.min(500*2**v++,1e4))}}),E.addEventListener("error",()=>E.close())};return g(),{send:y=>(y.type==="resize"?o={width:y.width,height:y.height}:y.type==="frameCap"&&(r={width:y.maxWidth,height:y.maxHeight}),u?.readyState!==WebSocket.OPEN||!m?.canOperate||!Ln(y,m)?!1:(u.send(JSON.stringify(y)),!0)),stop:()=>{c=!0,w!==null&&clearTimeout(w);const y=u;u=null,m=null,y?.close()}}}function Bt(e,t){const r=e.getContext("2d");let o=!1,i=!1,c=null;const u=w=>{i=!0,createImageBitmap(new Blob([w],{type:"image/jpeg"})).then(v=>{if(o||!r){v.close();return}(e.width!==v.width||e.height!==v.height)&&(e.width=v.width,e.height=v.height),r.drawImage(v,0,0),v.close(),t?.()}).catch(()=>{}).finally(()=>{i=!1;const v=c;c=null,v&&!o&&u(v)})};return{paint:w=>{o||(i?c=w:u(w))},stop:()=>{o=!0,c=null}}}const Bn=e=>{try{if(JSON.parse(e).need==="libraries")return{need:"libraries",command:Tn}}catch{}return{need:"sandbox"}},On=e=>e.need==="sandbox"?"This server's host blocks the sandbox its browser runs in. An administrator can allow it for one copy of Chrome with these steps, then try again:":"This server's host is missing libraries its browser needs. Run this once on the host, then try again:",Dn=700;function Hn(e,t){return e?1:t==="human"?.18:.35}function Fn({phase:e,sequence:t,left:r,top:o,controller:i}){const[c,u]=a.useState(null),w=c!==t;return a.useEffect(()=>{const v=window.setTimeout(()=>u(t),Dn);return()=>window.clearTimeout(v)},[t]),n.jsxs("div",{className:"pointer-events-none absolute left-0 top-0 z-30 transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none",style:{opacity:Hn(w,i),transform:`translate3d(${r}px, ${o}px, 0)`},"aria-hidden":"true","data-agent-cursor":!0,children:[e==="click"?n.jsx("span",{className:"absolute left-0.5 top-0.5 size-4 animate-ping rounded-full bg-accent/25 motion-reduce:animate-none"},t):null,n.jsx(hn,{className:"relative size-5 -translate-x-0.5 -translate-y-0.5 fill-card text-accent drop-shadow-sm",strokeWidth:2})]})}function $n({origin:e,realm:t,onAnswer:r}){const o=i=>{i.preventDefault();const c=i.currentTarget,u=c.elements.namedItem("username"),w=c.elements.namedItem("password");r({username:u.value,password:w.value}),u.value="",w.value=""};return n.jsxs("form",{role:"dialog","aria-label":s("browser.auth.label"),onSubmit:o,className:"absolute inset-x-3 top-3 z-20 mx-auto flex max-w-sm flex-col gap-2.5 rounded-xl border border-hairline/60 bg-card p-4 text-ink shadow-xl",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium",children:[n.jsx(It,{size:14,"aria-hidden":"true"}),s("browser.auth.signIn")]}),n.jsx("p",{className:"break-words text-[12px] text-ink-secondary",children:t?s("browser.auth.asks",{origin:e,realm:t}):e}),n.jsx("input",{name:"username","aria-label":s("browser.auth.username"),autoComplete:"off",spellCheck:!1,maxLength:1024,placeholder:s("browser.auth.username"),className:"rounded-lg bg-inset px-3 py-2 text-[13px] outline-none focus:ring-1 focus:ring-accent"}),n.jsx("input",{name:"password",type:"password","aria-label":s("logins.password"),autoComplete:"new-password",maxLength:1024,placeholder:s("logins.password"),className:"rounded-lg bg-inset px-3 py-2 text-[13px] outline-none focus:ring-1 focus:ring-accent"}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>r(null),className:"rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-inset",children:s("common.cancel")}),n.jsx("button",{type:"submit",className:"rounded-lg bg-accent px-3 py-1.5 text-[12px] text-accent-ink",children:s("browser.auth.signIn")})]})]})}function Un({options:e,selectedIndex:t,anchor:r,bounds:o,onChoose:i,onClose:c}){const[u,w]=a.useState(()=>t>=0?t:e.findIndex(b=>!b.disabled)),v=a.useRef(null);a.useEffect(()=>{v.current?.focus({preventScroll:!0})},[]),a.useEffect(()=>{v.current?.querySelector(`[data-index="${u}"]`)?.scrollIntoView?.({block:"nearest"})},[u]);const m=o.height-(r.top+r.height),d=r.top,g=m<160&&d>m,y=Math.max(96,Math.min(320,(g?d:m)-8)),E=Math.max(0,Math.min(r.left,o.width-Math.max(r.width,160))),k=(b,j)=>{for(let O=b+j;O>=0&&O<e.length;O+=j)if(!e[O].disabled)return O;return b},C=b=>{b.key==="ArrowDown"||b.key==="ArrowUp"?(b.preventDefault(),w(j=>k(j,b.key==="ArrowDown"?1:-1))):b.key==="Home"||b.key==="End"?(b.preventDefault(),w(b.key==="Home"?k(-1,1):k(e.length,-1))):b.key==="Enter"||b.key===" "?(b.preventDefault(),e[u]&&!e[u].disabled&&i(u)):(b.key==="Escape"||b.key==="Tab")&&(b.preventDefault(),b.stopPropagation(),c())};let T;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute inset-0 z-30","aria-hidden":"true",onPointerDown:b=>{b.preventDefault(),c()}}),n.jsx("div",{ref:v,role:"listbox","aria-label":s("browser.select.label"),"aria-activedescendant":u>=0?`select-option-${u}`:void 0,tabIndex:0,onKeyDown:C,onBlur:b=>{b.currentTarget.contains(b.relatedTarget)||c()},className:"absolute z-40 overflow-y-auto rounded-lg border border-hairline/60 bg-menu py-1 text-[13px] text-ink shadow-xl outline-none",style:{left:E,minWidth:Math.max(r.width,160),maxHeight:y,...g?{bottom:o.height-r.top+2}:{top:r.top+r.height+2}},children:e.map((b,j)=>{const O=b.group!==void 0&&b.group!==T?b.group:null;return T=b.group,n.jsxs("div",{children:[O!==null?n.jsx("div",{className:"px-3 pb-0.5 pt-1.5 text-[11px] font-medium text-ink-tertiary",role:"presentation",children:O}):null,n.jsxs("div",{id:`select-option-${j}`,"data-index":j,role:"option","aria-selected":j===t,"aria-disabled":b.disabled||void 0,onPointerEnter:()=>{b.disabled||w(j)},onPointerDown:H=>H.preventDefault(),onClick:()=>{b.disabled||i(j)},className:`flex cursor-default items-center gap-2 px-3 py-1.5 ${b.group!==void 0?"pl-5":""} ${b.disabled?"text-ink-tertiary":j===u?"bg-accent text-accent-ink":""}`,children:[n.jsx("span",{className:"min-w-0 flex-1 truncate",children:b.label||" "}),j===t?n.jsx(Mt,{size:13,"aria-hidden":"true"}):null]})]},j)})})]})}const wt=150,Wn=24,Kn=1e4,$e="",Vn={key:"Backspace",code:"Backspace",keyCode:8},qn={key:"Delete",code:"Delete",keyCode:46},Gn=8,Xn=500,Yn=4,Jn=16,yt=e=>e===0?"left":e===1?"middle":e===2?"right":"none",gt=e=>e&1?"left":e&2?"right":e&4?"middle":"none",Le=e=>e!==null&&e.canOperate&&e.controller!=="another-viewer";function Ot(e,t){const r=Math.min(e.width/t.width,e.height/t.height),o=t.width*r,i=t.height*r;return{width:o,height:i,left:(e.width-o)/2,top:(e.height-i)/2}}function Zn(e,t,r,o,i,c){const u=Ot(e,t);if(!(u.width>0&&u.height>0))return null;const w=r.width/u.width,v=(o-e.left-u.left)*w,m=(i-e.top-u.top)*(r.height/u.height);return!(v>=0&&m>=0&&v<=r.width&&m<=r.height)&&!c?null:{x:Math.min(Math.max(v,0),r.width),y:Math.min(Math.max(m,0),r.height),scale:w}}function kt(e,t,r,o){const i=Ot(t,r),c=i.width/o.width,u=i.height/o.height;return{left:i.left+e.x*c,top:i.top+e.y*u,width:e.width*c,height:e.height*u}}function Qn(e){const t=document.createElement("a");t.href=e.url,t.download=e.fileName,t.rel="noopener",t.click()}function er(e){const{connect:t,ref:r}=e,o=a.useRef(e);o.current=e;const i=a.useRef(null),c=a.useRef(null),u=a.useRef(!1),w=a.useRef(null),v=a.useRef(null),m=a.useRef(null),d=a.useRef(!1),g=a.useRef(null),[y,E]=a.useState(null),[k,C]=a.useState(!1),[T,b]=a.useState(!1),[j,O]=a.useState(""),[H,le]=a.useState(null),[re,J]=a.useState(null),[Y,$]=a.useState(null),[x,K]=a.useState("default"),[B,V]=a.useState(null),[Z,W]=a.useState([]),[te,P]=a.useState(null),R=a.useRef(0),D=a.useRef(null),U=a.useRef(null),q=a.useRef(null),N=a.useRef(null),A=a.useRef(0),G=a.useRef({left:1,middle:1,right:1,none:1}),ie=a.useRef(null),pe=a.useRef(null),F=a.useRef(null),Ee=a.useRef(null),Oe=a.useRef(null),[We,Ke]=a.useState(!1),Ne=a.useCallback(l=>{const p=++R.current;W(S=>[...S.slice(-2),{...l,id:p}])},[]),ue=l=>W(p=>p.filter(S=>S.id!==l)),Q=a.useCallback(l=>{o.current.input(l)},[]),Re=a.useCallback(()=>{N.current!==null&&cancelAnimationFrame(N.current),N.current=null,U.current=q.current=null,A.current=0,G.current={left:1,middle:1,right:1,none:1},ie.current=null,pe.current=F.current=Ee.current=null,u.current=!1,c.current&&(c.current.value=$e)},[]),be=a.useCallback(()=>{N.current!==null&&cancelAnimationFrame(N.current),N.current=null;const l=U.current,p=q.current;U.current=null,q.current=null,l&&Q(l),p&&Q(p)},[Q]),ve=a.useCallback(()=>{N.current??=requestAnimationFrame(be)},[be]),de=a.useCallback((l,p,S,z)=>{const I=q.current;q.current={type:"wheel",x:l.x,y:l.y,deltaX:(I?.deltaX??0)+p,deltaY:(I?.deltaY??0)+S,modifiers:z},ve()},[ve]),he=a.useCallback((l,p,S)=>{const z=i.current,I=v.current;return!z||!I||!d.current||!Le(g.current)?null:Zn(z.getBoundingClientRect(),z,I,l,p,S)},[]),Ie=(l,p,S,z)=>{const I=ie.current,X=I&&I.button===l&&z-I.time<Xn&&Math.hypot(p-I.x,S-I.y)<Yn?I.count+1:1;return ie.current={button:l,time:z,x:p,y:S,count:X},X},ee=()=>c.current?.focus({preventScroll:!0});a.useImperativeHandle(r,()=>({canvas:()=>d.current?i.current:null,focusPage:ee}),[]),a.useEffect(()=>{const l=i.current?.parentElement;if(!l||typeof ResizeObserver>"u")return;let p=null,S=null;const z=()=>{S=null;const f=m.current;if(!f)return;const M=window.devicePixelRatio||1,se=Math.round(f.width*M),ye=Math.round(f.height*M),ae=Oe.current;if(ae!==null&&ae.width>=se&&ae.height>=ye)return;const _={width:Math.max(se,ae?.width??0),height:Math.max(ye,ae?.height??0)};Oe.current=_,ae===null?Ke(!0):w.current?.send({type:"frameCap",maxWidth:_.width,maxHeight:_.height})},I=()=>{p=null;const f=l.getBoundingClientRect();if(f.width<1||f.height<1)return;const M={width:Math.round(f.width),height:Math.round(f.height)},se=m.current;se?.width===M.width&&se.height===M.height||(m.current=M,w.current?.send({type:"resize",...M}),S!==null&&clearTimeout(S),S=setTimeout(z,se===null?0:wt*2))},X=new ResizeObserver(()=>{p===null&&(p=setTimeout(I,m.current===null?0:wt))});return X.observe(l),()=>{X.disconnect(),p!==null&&clearTimeout(p),S!==null&&clearTimeout(S)}},[]),a.useEffect(()=>{const l=i.current,p=m.current,S=Oe.current;if(te||!We||!S||!l||!p)return;d.current=!1,b(!1);const z=Bt(l,()=>{d.current||(d.current=!0,b(!0),o.current.onFirstFrame?.())}),I=f=>{const M=g.current;g.current=f,E(f),o.current.onControl?.(f),(f?.dialog?.message!==M?.dialog?.message||f?.dialog?.defaultValue!==M?.dialog?.defaultValue)&&O(f?.dialog?.defaultValue??""),f?.controller!=="you"?$(null):M?.controller!=="you"&&m.current&&w.current?.send({type:"resize",...m.current}),Le(f)||(Re(),c.current?.blur())},X=t({maxWidth:S.width,maxHeight:S.height,width:p.width,height:p.height},{onFrame:f=>z.paint(f),onProbe:f=>{if(g.current?.controller!=="you")return;Ee.current={...f,at:performance.now()};const M=F.current;!M||M.x!==f.x||M.y!==f.y||(M.editable=f.editable,M.answered=!0,M.tapped&&(F.current=null,f.editable?c.current?.focus({preventScroll:!0}):c.current?.blur()))},onPointer:f=>{const M=i.current,se=v.current;if(!M||!se||M.width<1||M.height<1)return;const ye={width:M.clientWidth,height:M.clientHeight},ae=kt({x:f.x,y:f.y,width:0,height:0},ye,M,se);J({...ae,phase:f.phase,sequence:f.sequence})},onClipboard:f=>{ht(f).then(M=>{M==="failed"&&Ne({kind:"clipboard",text:f})})},onDownload:f=>Ne({kind:"download",download:f}),onPopup:()=>{},onFileChooser:le,onViewport:f=>{v.current=f},onControl:I,onMessage:f=>{if(f.type==="selectPopup"&&typeof f.id=="string"&&Array.isArray(f.options)){const M=f.rect;M&&$({id:f.id,options:f.options,selectedIndex:Number(f.selectedIndex),rect:M})}else f.type==="cursor"&&typeof f.shape=="string"?K(f.shape):f.type==="authPrompt"&&typeof f.tabId=="string"&&typeof f.id=="string"&&typeof f.origin=="string"?V({tabId:f.tabId,id:f.id,origin:f.origin,realm:typeof f.realm=="string"?f.realm:""}):f.type==="authPromptClosed"?V(M=>M&&M.id!==f.id?M:null):f.type==="notice"&&typeof f.message=="string"&&Ne({kind:"error",message:Kt(f,f.message)});o.current.onMessage?.(f)},onConnectedChange:f=>{C(f),o.current.onConnectedChange?.(f),!f&&(le(null),$(null),V(null),I(null))},onHostSetup:P,onUnauthorized:()=>o.current.onUnauthorized?.(),onGone:()=>o.current.onGone?.(),onClose:(f,M)=>o.current.onClose?.(f,M)});return w.current=X,o.current.onClient?.(X),()=>{z.stop(),X.stop(),w.current===X&&(w.current=null),o.current.onClient?.(null),I(null),C(!1),J(null),Re()}},[We,Re,t,te,Ne]),a.useEffect(()=>{const l=i.current;if(!l)return;const p=S=>{const z=he(S.clientX,S.clientY,!1);if(!z)return;S.preventDefault();const I=S.deltaMode===WheelEvent.DOM_DELTA_LINE?Jn:S.deltaMode===WheelEvent.DOM_DELTA_PAGE?v.current?.height??0:1;de(z,S.deltaX*I,S.deltaY*I,et(S))};return l.addEventListener("wheel",p,{passive:!1}),()=>l.removeEventListener("wheel",p)},[he,de]),a.useEffect(()=>()=>{N.current!==null&&cancelAnimationFrame(N.current)},[]);const Ce=l=>{if(!Le(g.current))return;const{type:p,pointerId:S,clientX:z,clientY:I}=l,X=p==="pointercancel",f=pe.current;if(X&&f?.pointerId===S){pe.current=F.current=null;return}if(l.pointerType==="touch"&&!X){const _=he(z,I,p==="pointermove");if(p==="pointerdown"){if(!l.isPrimary)return;pe.current={pointerId:S,startX:z,startY:I,lastX:z,lastY:I,panning:!1};const Se=Ee.current,Te=_&&Se&&performance.now()-Se.at<Kn&&Math.hypot(_.x-Se.x,_.y-Se.y)<Wn;F.current=_?{x:_.x,y:_.y,editable:Te?Se.editable:null,answered:!1,tapped:!1}:null,_&&Q({type:"probe",x:_.x,y:_.y});return}if(!f||f.pointerId!==S)return;if(p==="pointermove"){if(!f.panning&&Math.hypot(z-f.startX,I-f.startY)<Gn)return;f.panning=!0,_&&de(_,(f.lastX-z)*_.scale,(f.lastY-I)*_.scale,0),f.lastX=z,f.lastY=I;return}pe.current=null;const oe=F.current;if(f.panning){F.current=null;return}if(!_)return;oe?.editable===!0?ee():oe?.editable===!1&&c.current?.blur(),oe&&!oe.answered?oe.tapped=!0:F.current=null,be();const ge=Ie("left",z,I,l.timeStamp),ne={x:_.x,y:_.y,modifiers:0};Q({type:"mouse",action:"move",...ne,button:"none",buttons:0,clickCount:0}),Q({type:"mouse",action:"down",...ne,button:"left",buttons:1,clickCount:ge}),Q({type:"mouse",action:"up",...ne,button:"left",buttons:0,clickCount:ge});return}const M=A.current;if((X||p==="pointerup")&&M===0)return;(X||p==="pointerup")&&(A.current=X?0:l.buttons&7);const se=he(z,I,p!=="pointerdown"&&(X||p==="pointerup"||M!==0||l.buttons!==0));if(!se)return;const ye={x:se.x,y:se.y,modifiers:et(l)},ae=(_,oe,ge)=>{_==="down"&&(G.current[oe]=Ie(oe,z,I,l.timeStamp)),Q({type:"mouse",action:_,...ye,button:oe,buttons:ge,clickCount:G.current[oe]})};if(p==="pointerdown")ee(),l.currentTarget.setPointerCapture(S),be(),A.current=l.buttons&7,ae("down",yt(l.button),l.buttons);else if(p==="pointerup")be(),ae("up",yt(l.button),l.buttons);else{const _=X?0:l.buttons&7,oe=M^_;if(M!==0&&oe!==0){be();let ge=M;for(const ne of[1,2,4])oe&ne&&(ge^=ne,ae(_&ne?"down":"up",gt(ne),ge));A.current=_}if(X)return;U.current={type:"mouse",action:"move",...ye,button:gt(l.buttons),buttons:l.buttons,clickCount:0},ve()}},ze=l=>{u.current=!1,l.value=$e,l.setSelectionRange($e.length,$e.length)},De=l=>{Q({type:"key",action:"down",...l,modifiers:0}),Q({type:"key",action:"up",...l,modifiers:0})},He=(l,p)=>{if(!Le(g.current)||(u.current=!1,p.nativeEvent.isComposing||p.keyCode===229||p.key==="Process"||p.key==="Unidentified"))return;if(p.key==="Escape"&&p.shiftKey){p.preventDefault(),p.stopPropagation(),l==="down"&&(p.currentTarget.blur(),o.current.onLeave?.());return}const S=p.ctrlKey||p.metaKey;if(S&&p.key.toLowerCase()==="v"||p.shiftKey&&p.key==="Insert")return;const z=S?void 0:[...p.key].length===1?p.key:p.key==="Enter"?"\r":void 0;Q({type:"key",action:l,key:p.key,code:p.code,keyCode:p.keyCode,...l==="down"&&z!==void 0?{text:z}:{},modifiers:et(p)}),u.current=l==="down"&&!S&&(z!==void 0||p.key==="Backspace"||p.key==="Delete"),!S&&(p.preventDefault(),p.stopPropagation())},Fe=l=>{const p=l.nativeEvent;if(p instanceof InputEvent&&p.isComposing)return;const S=l.currentTarget,z=p instanceof InputEvent?p.inputType:"";if(u.current)u.current=!1;else if(z==="deleteContentBackward")De(Vn);else if(z==="deleteContentForward")De(qn);else{const I=S.value.replace(/^/,"");I&&Q({type:"text",text:I})}ze(S)},xe=l=>{const p=H;p&&(le(null),zn(p,l).catch(S=>Ne({kind:"error",message:s("browser.page.uploadFailed",{error:S instanceof Error?S.message:String(S)})})))},me=l=>w.current?.send(l),ce=i.current,we=Y&&ce&&v.current&&ce.width>0?kt(Y.rect,{width:ce.clientWidth,height:ce.clientHeight},ce,v.current):null,Pe=y?.controller==="you";return n.jsxs("div",{className:`relative flex min-h-0 flex-1 flex-col overflow-hidden ${e.className??""}`,"data-browser-surface":!0,children:[n.jsxs("div",{className:"relative min-h-0 flex-1",children:[n.jsx("canvas",{ref:i,"aria-hidden":"true",className:"block size-full touch-none object-contain",style:{cursor:Le(y)?Pe?x:"default":"not-allowed"},onPointerDown:Ce,onPointerMove:Ce,onPointerUp:Ce,onPointerCancel:Ce,onMouseDown:l=>l.preventDefault(),onContextMenu:l=>l.preventDefault()}),re&&!Pe?n.jsx(Fn,{...re,controller:y?.controller==="agent"?"agent":"none"}):null,n.jsx("textarea",{ref:c,"aria-label":e.label??s("browser.page.label"),"aria-description":s("browser.page.keysHint"),"aria-keyshortcuts":"Shift+Escape",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:!Le(y),defaultValue:$e,onFocus:l=>ze(l.currentTarget),className:"sr-only left-0 top-0 text-base",onKeyDown:l=>He("down",l),onKeyUp:l=>He("up",l),onInput:Fe,onCompositionEnd:l=>{const p=l.data.replace(/^/,"");p&&Q({type:"text",text:p}),ze(l.currentTarget)},onCopy:l=>l.preventDefault(),onCut:l=>l.preventDefault(),onPaste:l=>{l.preventDefault();const p=l.clipboardData.getData("text/plain");p&&Q({type:"text",text:p})}}),k&&!T&&!te?n.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center text-ink-secondary","aria-hidden":"true",children:n.jsx(Xe,{size:22,className:"animate-spin"})}):null,Y&&we&&ce?n.jsx(Un,{options:Y.options,selectedIndex:Y.selectedIndex,anchor:we,bounds:{width:ce.clientWidth,height:ce.clientHeight},onChoose:l=>{me({type:"selectChoose",id:Y.id,index:l}),$(null),ee()},onClose:()=>{$(null),ee()}},Y.id):null,H&&Pe?n.jsxs("div",{className:"absolute inset-x-3 top-3 z-20 mx-auto flex max-w-sm flex-col gap-2 rounded-xl border border-hairline/60 bg-card p-3 text-ink shadow-xl",role:"dialog","aria-label":s("browser.page.chooseFilesLabel"),children:[n.jsxs("p",{className:"flex items-center gap-2 text-[13px]",children:[n.jsx(fn,{size:14,"aria-hidden":"true"}),s(H.multiple?"browser.page.asksFiles":"browser.page.asksFile")]}),n.jsx("input",{ref:D,type:"file",className:"hidden",multiple:H.multiple,accept:H.accept,onChange:l=>{const p=[...l.currentTarget.files??[]];l.currentTarget.value="",p.length>0&&xe(p)}}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",className:"rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-inset",onClick:()=>xe([]),children:s("common.cancel")}),n.jsx("button",{type:"button",className:"rounded-lg bg-accent px-3 py-1.5 text-[12px] text-accent-ink",onClick:()=>D.current?.click(),children:s(H.multiple?"browser.page.chooseFiles":"browser.page.chooseFile")})]})]}):null,y?.dialog&&y.controller!=="another-viewer"?n.jsxs("div",{className:"absolute inset-x-3 top-3 z-20 mx-auto flex max-w-sm flex-col gap-2 rounded-xl border border-hairline/60 bg-card p-3 text-ink shadow-xl",role:"dialog","aria-label":s("browser.dialog.label"),children:[n.jsx("p",{className:"break-words text-[13px]",children:y.dialog.message}),Pe?n.jsxs(n.Fragment,{children:[y.dialog.type==="prompt"?n.jsx("input",{"aria-label":s("browser.dialog.response"),value:j,onChange:l=>O(l.target.value),className:"rounded-lg bg-inset px-3 py-2 text-[13px] outline-none focus:ring-1 focus:ring-accent"}):null,n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",className:"rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-inset",onClick:()=>me({type:"dialog",accept:!1}),children:s("browser.dialog.dismiss")}),n.jsx("button",{type:"button",className:"rounded-lg bg-accent px-3 py-1.5 text-[12px] text-accent-ink",onClick:()=>me({type:"dialog",accept:!0,...y.dialog?.type==="prompt"?{promptText:j}:{}}),children:s("browser.dialog.accept")})]})]}):n.jsx("p",{className:"text-[12px] text-ink-secondary",children:s("browser.dialog.takeControl")})]}):null,B&&Pe?n.jsx($n,{origin:B.origin,realm:B.realm,onAnswer:l=>{const p={tabId:B.tabId,id:B.id};me(l?{type:"authAnswer",...p,username:l.username,password:l.password}:{type:"authAnswer",...p}),V(null)}}):null,Z.length?n.jsx("div",{className:"absolute inset-x-3 bottom-3 z-20 flex flex-col items-center gap-2",role:"status",children:Z.map(l=>n.jsxs("div",{className:"flex max-w-full items-center gap-2 rounded-xl border border-hairline/60 bg-card px-3 py-2 text-[12px] text-ink shadow-lg",children:[l.kind==="download"?n.jsxs(n.Fragment,{children:[n.jsx(rn,{size:13,"aria-hidden":"true",className:"shrink-0"}),n.jsx("span",{className:"min-w-0 truncate",children:s("browser.notice.downloaded",{name:l.download.fileName})}),n.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-accent px-2 py-0.5 text-accent-ink",onClick:()=>{Qn(l.download),ue(l.id)},children:s("common.save")})]}):l.kind==="clipboard"?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"min-w-0 truncate",children:s("browser.notice.copied")}),n.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-accent px-2 py-0.5 text-accent-ink",onClick:()=>{ht(l.text),ue(l.id)},children:s("common.copy")})]}):n.jsx("span",{role:"alert",className:"min-w-0 text-danger",children:l.message}),n.jsx("button",{type:"button","aria-label":s("browser.dialog.dismiss"),className:"shrink-0 rounded-md p-0.5 text-ink-secondary hover:bg-inset",onClick:()=>ue(l.id),children:n.jsx(Ue,{size:12})})]},l.id))}):null]}),te?n.jsxs("div",{className:"absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 bg-card p-4 text-center",children:[n.jsx("p",{role:"alert",className:"max-w-sm text-[13px] text-ink-secondary",children:On(te)}),te.need==="libraries"?n.jsx("code",{className:"max-w-md select-all break-all rounded-lg bg-inset px-3 py-2 text-left text-[12px] text-ink",children:te.command}):n.jsx("a",{href:Mn,target:"_blank",rel:"noopener noreferrer",className:"text-[12px] text-ink underline",children:"Browser sandbox setup steps"}),n.jsx("button",{type:"button",className:"rounded-lg border border-hairline px-3 py-1.5 text-[12px] text-ink hover:bg-inset",onClick:()=>P(null),children:s("common.tryAgain")})]}):null]})}const tr=8e3,nr=300,rr=2e4,sr=16,Dt=new Set(["Alt","Control","Meta","Shift"]),or=new Set(["Backspace","Enter","Tab","Escape","Delete","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"]),qe=new Set(["navigate","history","reload","tabSelect","tabNew","tabClose"]),ar=new Set(["navigate","tabNew"]);function tt(e){return qe.has(e.type)?!0:e.type==="mouse"?e.action==="down":e.type==="key"?e.action==="down"&&!Dt.has(e.key):e.type==="wheel"||e.type==="text"}const nt=e=>e.type==="key"?`key:${e.code||e.key}`:e.type==="mouse"?`mouse:${e.button}`:e.type,vt=e=>(e.type==="key"||e.type==="mouse")&&e.action==="down",Ct=e=>(e.type==="key"||e.type==="mouse")&&e.action==="up";function lr(e){return e.type!=="key"||Dt.has(e.key)?!0:or.has(e.key)?!1:!e.modifiers||e.modifiers===8&&[...e.key].length===1}function ir(e){const t=e.transport;let r="bot",o="",i=[],c=!1,u=!1,w=!1,v=!1,m=!1,d=!1,g=0,y=Promise.resolve(),E,k;const C=new Set,T=new Set,b=x=>{o=x,e.onTakeStatus(x)},j=x=>{vt(x)&&lr(x)?C.add(nt(x)):Ct(x)&&C.delete(nt(x))},O=()=>!u&&!w&&(m||!v)&&!c&&!C.size&&(r==="held"||r==="bot"&&e.owned()),H=()=>{clearTimeout(E),E=u?void 0:setTimeout(()=>{E=void 0,re()},m?0:tr)},le=()=>{r="releasing",o==="stale"&&b(""),y=y.then(()=>u?void 0:t.release()).catch(()=>{}).then(()=>{r==="releasing"&&(r="bot")})},re=async()=>{if(!O())return;const x=g;await t.drain(),x===g&&O()&&le()},J=()=>{const x=i.filter(B=>ar.has(B.type)),K=i.some(B=>!x.includes(B)&&tt(B));i=x;for(const B of C)T.add(B);return C.clear(),K},Y=async()=>{c=!0;try{for(let x=i.shift();x&&!u;x=i.shift())t.send(x),t.size()>=sr&&await t.settle()}finally{c=!1,i=[]}},$=()=>{r="taking",e.onError(""),b("pending"),clearTimeout(k),k=setTimeout(()=>{!u&&r==="taking"&&b("slow")},nr),y=y.then(async()=>{if(u)return;const x=await t.take().then(K=>({reply:K}),K=>(u||e.onError(K instanceof Error?K.message:String(K)),null));clearTimeout(k),!u&&(x?(r="held",b(x.reply?.waited===!0&&J()?"stale":""),await Y()):(b(""),r="bot",i=[],C.clear()),H())}).catch(()=>{})};return{interact(x){if(u)return;const K=nt(x);if(Ct(x)&&T.delete(K))return;vt(x)&&T.delete(K);const B=r==="taking"||c;if(r!=="held"&&!B){if(!tt(x))return;if(t.stopped()&&!qe.has(x.type)){e.onHalted();return}}if(!(qe.has(x.type)&&B&&i.some(V=>qe.has(V.type)))){if(tt(x)&&(m=!1,o==="stale"&&b("")),j(x),g++,H(),r==="held"&&!B){t.send(x);return}i.push(x),B||$()}},observe(){if(u)return;const x=e.owned();d&&!x&&r==="held"&&!c&&(r="bot",C.clear(),T.clear(),clearTimeout(E),E=void 0),d=x,E===void 0&&x&&H()},takeControl(){u||r==="held"||r==="taking"||c||(m=!1,$())},keep(x){u||v===x||(v=x,x||H())},handBack(){if(!u){if(r==="bot"&&!e.owned()&&e.mine?.()){le();return}m=!0,H()}},hold(x){u||w===x||(w=x,x||H())},leave(){!O()||t.size()||(r="releasing",t.release().catch(()=>{}))},close(){u=!0,clearTimeout(E),clearTimeout(k),i=[],C.clear(),T.clear()}}}function cr(e,t,r){return{send:o=>{e.send(o)},drain:async()=>{},settle:async()=>{},size:()=>0,stopped:()=>!1,take:()=>new Promise((o,i)=>{const c=t.current();if(c?.controller==="you"){o({waited:!1});return}if(!e.send({type:"takeControl"})){i(new Error(s("browser.panel.notConnected")));return}const u=c?.controller==="agent",w=d=>{clearTimeout(v),m(),d()},v=setTimeout(()=>w(()=>i(new Error(s("browser.panel.takeFailed")))),rr),m=t.watch(d=>{d?.controller==="you"?w(()=>o({waited:u})):d?.controller==="another-viewer"?w(()=>i(new Error(r))):d===null&&w(()=>i(new Error(s("browser.panel.viewDisconnected"))))})}),release:async()=>{e.send({type:"releaseControl"})}}}const ur="https://duckduckgo.com/?q=",dr=/^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i,fr=/^[^/?#:@]+:\d+(?:[/?#]|$)/,pr=/^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i,hr=new Set(["about:","blob:","chrome:","data:","file:","ftp:","javascript:","mailto:","sms:","ssh:","tel:","view-source:","ws:","wss:"]);function mr(e){return/^([A-Za-z][A-Za-z\d+.-]*):/.exec(e)?.[1]?.toLowerCase().concat(":")}function rt(e){const t=e.includes("://")?e:`${pr.test(e)?"http":"https"}://${e}`;try{const r=new URL(t);return r.protocol==="http:"||r.protocol==="https:"?r.href:null}catch{return null}}function br(e){const t=e.trim();if(!t)return null;if(/^[a-z][a-z\d+.-]*:\/\//i.test(t))return rt(t);if(!/\s/.test(t)){const r=mr(t);if(r!==void 0&&(hr.has(r)||!fr.test(t)))return r==="http:"||r==="https:"?rt(t):null;const o=(t.split(/[/?#]/,1)[0]??"").replace(/^[^@]*@/,""),i=o.replace(/:\d+$/,"");if(i.length<o.length||dr.test(i)||/^[^.]+(?:\.[^.]+)+\.?$/.test(i)){const u=rt(t);if(u)return u}}return`${ur}${encodeURIComponent(t)}`}const xr=5;let Be=null;const it=new Set,Ht=()=>{for(const e of it)e()},wr=e=>(it.add(e),()=>it.delete(e));function yr(){if(typeof document>"u"||typeof HTMLCanvasElement.prototype.captureStream!="function")return!1;const e=HTMLVideoElement.prototype;return document.pictureInPictureEnabled&&typeof e.requestPictureInPicture=="function"||typeof e.webkitSetPresentationMode=="function"}function gr(){return a.useSyncExternalStore(wr,()=>Be?.key??null,()=>null)}function ct(){const e=Be;Be=null,e?.stop(),Ht()}async function kr(e){ct();const t=document.createElement("canvas"),r=t.getContext("2d"),o=e.seed&&e.seed.width>0&&e.seed.height>0?e.seed:null;t.width=o?.width??640,t.height=o?.height??400;const i=t.captureStream();o?r?.drawImage(o,0,0):r?.fillRect(0,0,t.width,t.height);const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.srcObject=i,c.style.cssText="position:fixed;right:0;bottom:0;width:1px;height:1px;opacity:0;pointer-events:none",document.body.append(c);const u=Bt(t);let w=null,v=!1,m=0,d=null;const g=()=>{Be===k&&ct()},y=()=>{v||(w=_t({access:Lt(e.botId),maxWidth:1280,maxHeight:1280,interactive:!1},{onFrame:C=>{m=0,u.paint(C)},onViewport:()=>{},onConnectedChange:()=>{},onUnauthorized:()=>{if(!v){if(m>=xr){g();return}d=setTimeout(y,1e3*2**m++)}},onGone:g}))},E=()=>{c.webkitPresentationMode!=="picture-in-picture"&&g()},k={key:e.botId,stop:()=>{v=!0,d!==null&&clearTimeout(d),w?.stop(),u.stop(),c.removeEventListener("leavepictureinpicture",g),c.removeEventListener("webkitpresentationmodechanged",E),document.pictureInPictureElement===c?document.exitPictureInPicture().catch(()=>{}):c.webkitPresentationMode==="picture-in-picture"&&c.webkitSetPresentationMode?.("inline");for(const C of i.getTracks())C.stop();c.srcObject=null,c.remove()}};Be=k,Ht();try{await c.play(),c.readyState<HTMLMediaElement.HAVE_METADATA&&await new Promise(C=>c.addEventListener("loadedmetadata",C,{once:!0})),document.pictureInPictureEnabled&&typeof c.requestPictureInPicture=="function"?(c.addEventListener("leavepictureinpicture",g),await c.requestPictureInPicture()):(c.addEventListener("webkitpresentationmodechanged",E),c.webkitSetPresentationMode?.("picture-in-picture"))}catch(C){throw g(),C}Be===k&&y()}const vr=[1e3,2e3,4e3,8e3,15e3],Cr=25e3,Sr=5e3,St=32,jt=4096,jr=24e3,Me=(e,t,r)=>Math.max(t,Math.min(r,Number.isFinite(e)?e:0)),Ye=e=>Me(e,-1e4,1e4);function Er(e,t,r,o){const i=t*r/e;return Math.abs(i-o)<=Math.max(1,r/e)?{width:r,height:o}:{width:r,height:Math.round(i)}}function Nr(e){for(let t=2;t+9<e.length;){if(e[t]!==255)return null;const r=e[t+1];if(r>=192&&r<=194)return{height:e[t+5]<<8|e[t+6],width:e[t+7]<<8|e[t+8]};t+=2+(e[t+2]<<8|e[t+3])}return null}function Et(e){switch(e.type){case"mouse":return{type:"input_mouse",eventType:e.action==="down"?"mousePressed":e.action==="up"?"mouseReleased":"mouseMoved",x:Me(e.x,0,8192),y:Me(e.y,0,8192),button:e.button,clickCount:Math.round(Me(e.clickCount,0,3)),modifiers:e.modifiers};case"wheel":return{type:"input_mouse",eventType:"mouseWheel",x:Me(e.x,0,8192),y:Me(e.y,0,8192),button:"none",deltaX:Ye(e.deltaX),deltaY:Ye(e.deltaY),modifiers:e.modifiers};case"key":return e.key?{type:"input_keyboard",eventType:e.action==="up"?"keyUp":"keyDown",key:e.key.slice(0,64),code:e.code.slice(0,64),windowsVirtualKeyCode:Math.round(Me(e.keyCode??0,0,255)),modifiers:e.modifiers,...e.text!==void 0?{text:e.text}:{}}:null;case"text":{const t=[];for(let r=0;r<e.text.length;r+=jt)t.push({type:"input_keyboard",eventType:"char",text:e.text.slice(r,r+jt)});return t}case"navigate":return{type:"navigate",url:e.url};case"history":return{type:e.delta<0?"back":"forward"};case"reload":return{type:"reload"};case"tabSelect":return{type:"tab-select",tabId:e.tabId};case"tabClose":return{type:"tab-close",tabId:e.tabId};case"tabNew":return e.url?{type:"tab-new",url:e.url}:{type:"tab-new"};case"restart":return{type:"restart"};case"dialog":return{type:"dialog",accept:e.accept,...e.promptText!==void 0?{promptText:e.promptText.slice(0,4096)}:{}};default:return null}}const Ve=e=>e.type==="input_mouse"&&(e.eventType==="mouseMoved"||e.eventType==="mouseWheel"),ut=e=>e.type==="input_mouse"||e.type==="input_keyboard",Ft=e=>e.type==="input_mouse"&&e.eventType==="mouseReleased"||e.type==="input_keyboard"&&e.eventType==="keyUp",st=e=>Ft(e)||!ut(e);function Pr(e,t,r=()=>1){let o=[],i=null,c=0,u=!1;const w=d=>{o=o.filter(st),u||(u=!0,t(d))},v=()=>{const d=[o.shift()],g=u?1:r();let y=JSON.stringify(d[0]).length;for(;ut(d[0])&&d.length<g&&o.length&&ut(o[0]);){const E=JSON.stringify(o[0]).length;if(y+E>jr)break;y+=E,d.push(o.shift())}return d},m=()=>{if(i||!o.length)return;const d=c;i=(async()=>{for(;d===c&&o.length;){const g=v();try{await e(g.length===1?g[0]:{type:"input_batch",events:g})}catch(y){if(d!==c)continue;g.length>1&&o.unshift(...g.slice(1).filter(Ft)),w(y)}}})().finally(()=>{i=null,m()})};return{enqueue(d){if(u&&!st(d))return;const g=o.at(-1);if(g&&Ve(d)&&g.type===d.type&&g.eventType===d.eventType&&g.modifiers===d.modifiers&&g.button===d.button){o[o.length-1]=d.eventType==="mouseWheel"?{...d,deltaX:Ye(Number(g.deltaX??0)+Number(d.deltaX??0)),deltaY:Ye(Number(g.deltaY??0)+Number(d.deltaY??0))}:{...d};return}if(o.length>=St){if(Ve(d))return;const y=o.findIndex(Ve);if(y>=0)o.splice(y,1);else if(w(new Error(s("browser.input.tooSlow"))),!st(d)||o.length>=St)return}o.push({...d}),m()},async drain(){for(o=o.filter(d=>!Ve(d));i||o.length;)m(),await i},async settle(){for(;i||o.length;)m(),await i},size:()=>o.length+(i?1:0),stopped:()=>u,clear(){c++,o=[],u=!1}}}function Nt(e,t){const r=e.owned===!0?e.controlling===!0?"you":"agent":e.held===!0?"another-viewer":"unclaimed",o=e.dialog,i=o&&typeof o.type=="string"&&typeof o.message=="string"&&typeof o.defaultValue=="string"?{type:o.type,message:o.message,defaultValue:o.defaultValue}:null;return{canOperate:!0,controller:r,generation:t,dialog:i,...e.owned===!0?{owned:!0}:{}}}function Tr(e,t,r,o={viewer:""},i={},c=null){let u=!1,w=!1,v=!1,m=null,d="",g=0,y=0,E=0,k=null,C=null,T=null,b=1,j=c,O=null;const H=(P,R)=>{P.close(),m=null;const D=d!=="";if(D&&(o.viewer=d),d="",k=null,$.clear(),D&&t.onConnectedChange(!1),u)return;const U=R?vr[y++]:void 0;if(U===void 0){u=!0,w=R,t.onGone?.();return}T=setTimeout(K,U)},le=(P,R)=>P?.status!==404||!m||!R||d!==R?!1:(H(m,!0),!0),re=(P,R)=>r(P,R).catch(D=>{throw le(D,R),D}),J=P=>t.onMessage?.({type:"notice",message:P}),Y=P=>{const R=P?.notice;typeof R=="string"&&R&&J(R)},$=Pr(P=>d?re(P,d).then(Y):Promise.reject(new Error(s("browser.panel.connectionFirst"))),P=>{J(P instanceof Error?P.message:String(P))},()=>b),x=()=>{const P=j,R=d;O||!P||!R||(O=P,r({type:"resize",width:Math.round(P.width),height:Math.round(P.height)},R).catch(()=>{}).finally(()=>{O=null,j!==P&&d===R&&x()}))},K=()=>{if(T=null,u)return;const P=new URLSearchParams(o.viewer?{resume:o.viewer}:{}),R=j;j&&(P.set("width",String(Math.round(j.width))),P.set("height",String(Math.round(j.height))));const D=zt(P.size?`?${P.toString()}`:"",i),U=new EventSource(`/api/bots/${encodeURIComponent(e)}/browser/live${D}`);m=U,g=Date.now();const q=(N,A)=>U.addEventListener(N,G=>{if(m===U){g=Date.now();try{A(JSON.parse(G.data))}catch{}}});q("waiting",()=>t.onMessage?.({type:"starting"})),q("ready",N=>{typeof N.viewerId!="string"||!N.viewerId||(d=N.viewerId,b=Number.isSafeInteger(N.inputBatch)?Math.max(1,Math.min(Number(N.inputBatch),64)):1,o.viewer="",t.onConnectedChange(!0),j!==R&&x())}),q("heartbeat",()=>{y=0}),q("frame",N=>{if(!d||typeof N.data!="string"||typeof N.seq!="number")return;const A=atob(N.data),G=new Uint8Array(A.length);for(let F=0;F<A.length;F++)G[F]=A.charCodeAt(F);const ie=N.metadata??{},pe=Nr(G);if(pe&&ie.deviceWidth&&ie.deviceHeight){const F=Er(pe.width,pe.height,ie.deviceWidth,ie.deviceHeight);(F.width!==C?.width||F.height!==C.height)&&(C=F,t.onViewport(F))}t.onFrame(G.buffer),r({type:"ack",seq:N.seq},d).catch(()=>{})}),q("tabs",N=>{Array.isArray(N.tabs)&&t.onMessage?.({type:"tabs",tabs:N.tabs})}),q("url",N=>{typeof N.url=="string"&&t.onMessage?.({type:"url",url:N.url})}),q("status",N=>{C||!(Number(N.viewportWidth)>0&&Number(N.viewportHeight)>0)||(C={width:Number(N.viewportWidth),height:Number(N.viewportHeight)},t.onViewport(C))}),q("control",N=>{const A=Nt(N,E);k&&A.controller===k.controller&&A.owned===k.owned&&JSON.stringify(A.dialog)===JSON.stringify(k.dialog)||(k=A.controller===k?.controller?A:Nt(N,++E),t.onControl?.(k))}),U.addEventListener("error",N=>{if(m!==U)return;let A=!(N instanceof MessageEvent);if(N instanceof MessageEvent)try{const G=JSON.parse(N.data);A=G.retryable===!0,G.asleep===!0?t.onMessage?.({type:"asleep"}):typeof G.message=="string"&&t.onMessage?.({type:"notice",message:G.message,...typeof G.errorKey=="string"?{errorKey:G.errorKey,...G.errorParams!==void 0?{errorParams:G.errorParams}:{}}:{}})}catch{}H(U,A)})};K();const B=P=>{v||(m&&d&&Date.now()-g>Cr&&H(m,!0),!(!P||T===null&&!(u&&w))&&(T!==null&&clearTimeout(T),u=!1,w=!1,y=0,K()))},V=()=>{document.visibilityState!=="hidden"&&B(!0)},Z=setInterval(()=>B(!1),Sr),W=typeof window>"u"?null:window;return W?.addEventListener("focus",V),W?.addEventListener("online",V),W&&document.addEventListener("visibilitychange",V),{send:P=>{if(P.type==="resize")return j={width:P.width,height:P.height},x(),!0;if(!d||!k?.canOperate||!["takeControl","restart"].includes(P.type)&&k.controller!=="you")return!1;const R=Et(P);if(!R)return!1;if(P.type==="dialog"&&!Array.isArray(R))return re(R,d).catch(D=>J(D instanceof Error?D.message:String(D))),!0;for(const D of Array.isArray(R)?R:[R])$.enqueue(D);return!0},stop:()=>{u=!0,v=!0,clearInterval(Z),W?.removeEventListener("focus",V),W?.removeEventListener("online",V),W&&document.removeEventListener("visibilitychange",V),T!==null&&clearTimeout(T),m?.close(),m=null,d&&(o.viewer=d),d="",$.clear()},transport:{send:P=>{const R=d?Et(P):null;if(R)for(const D of Array.isArray(R)?R:[R])$.enqueue(D)},drain:()=>$.drain(),settle:()=>$.settle(),size:()=>$.size(),stopped:()=>$.stopped(),take:async()=>{if(!d)throw new Error(s("browser.panel.notConnected"));return{waited:(await re({type:"take"},d))?.waited===!0}},release:async()=>{d&&await re({type:"release"},d)}}}}const ot="Another window or device controls this browser. Hand control back there to use it here.",Mr=/^\/(?:v\d+\/)?signin\/(?:v\d+\/)?challenge\/(?:pk|sk)(?:\/|$)/u;function Rr(e){let t;try{t=new URL(e)}catch{return null}return t.hostname==="accounts.google.com"&&Mr.test(t.pathname)?"google":null}const Pt="rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink disabled:opacity-40 disabled:cursor-not-allowed",at={url:"",loading:!1,canGoBack:!1,canGoForward:!1};function Ir(e){return Array.isArray(e)?e.flatMap(t=>t&&typeof t=="object"&&typeof t.tabId=="string"?[{tabId:t.tabId,title:typeof t.title=="string"?t.title:"",url:typeof t.url=="string"?t.url:"",active:t.active===!0}]:[]):[]}function zr({bot:e,signIn:t,page:r}){const{state:o}=dt(),[i,c]=a.useState(!1),u=o.config?.browserEngine?.engine==="chrome"&&!i,[w,v]=a.useState(0),[m,d]=a.useState(!1),[g,y]=a.useState(null),[E,k]=a.useState([]),[C,T]=a.useState(at),[b,j]=a.useState({mode:"fill"}),[O,H]=a.useState(1),[le,re]=a.useState(null),[J,Y]=a.useState(""),[$,x]=a.useState(""),[K,B]=a.useState(!1),[V,Z]=a.useState(!1),[W,te]=a.useState(""),[P,R]=a.useState(!1),[D,U]=a.useState(!1),[q,N]=a.useState(!1),[A,G]=a.useState(!1),[ie,pe]=a.useState(!1),[F,Ee]=a.useState(!1),[Oe,We]=a.useState(""),Ke=gr(),Ne=xn(),ue=a.useRef(null),Q=a.useRef(null),Re=a.useRef(null),be=a.useRef(null),ve=a.useRef(null),de=a.useRef(null),he=a.useRef(null),Ie=a.useRef(new Set),ee=a.useRef(null),Ce=a.useRef({key:"",viewer:""}),ze=a.useRef(!1),De=a.useRef(0),He=a.useRef(0),Fe=a.useRef(null),xe=a.useRef(null),me=a.useRef({openSignInPage:()=>{},takeControl:()=>{}}),ce=o.computerControl?.[e.id]?.help?.place==="browser",we=on(o.config?.team,e.threadId).threadId;ze.current=P||ce;const Pe=e.browserProfile==="guest"?s("browser.panel.temporary"):o.config?.browserProfiles?.find(h=>h.id===e.browserProfile)?.name??s("browser.panel.ownBrowser",{name:e.name});a.useEffect(()=>{D?be.current?.showModal():be.current?.close()},[D]),a.useEffect(()=>{ee.current?.hold(q),q?ve.current?.showModal():ve.current?.close()},[q]);const l=a.useCallback(()=>{Z(!1),x(""),c(!1),v(h=>h+1)},[]);a.useEffect(()=>{c(!1)},[e.id,e.browserProfile,we]),a.useEffect(()=>{k([]),re(null),T(u?at:{...at,canGoBack:!0,canGoForward:!0}),B(!1),Z(!1),te(""),xe.current=null},[e.id,e.browserProfile,we,w,u]);const p=a.useCallback((h,L)=>{const fe=we?{threadId:we}:{};if(u)return _t({access:Lt(e.id,window.location,fe),...h},L);const ke=`${e.id}
|
|
2
|
-
${e.browserProfile??""}${we?`
|
|
3
|
-
${we}`:""}`;return Ce.current.key!==ke&&(Ce.current={key:ke,viewer:""}),Tr(e.id,L,(Ut,Wt)=>Ge(zt(`/api/bots/${encodeURIComponent(e.id)}/browser/action`,fe),{method:"POST",body:JSON.stringify({...Ut,viewerId:Wt}),timeoutMs:12e4}),Ce.current,fe,{width:h.width,height:h.height})},[e.id,e.browserProfile,we,u]),S=a.useCallback(h=>{if(he.current?.controller==="another-viewer"){x(ot);return}ee.current?.interact(h)},[]),z=a.useCallback(h=>{if(de.current=h,ee.current?.close(),ee.current=null,!h)return;const L="transport"in h?h.transport:cr(h,{current:()=>he.current,watch:ke=>(Ie.current.add(ke),()=>{Ie.current.delete(ke)})},ot),fe=ir({transport:L,owned:()=>he.current?.controller==="you",mine:()=>he.current?.owned===!0,onTakeStatus:Y,onError:x,onHalted:()=>x(s("browser.input.tooSlow"))});fe.keep(ze.current),ee.current=fe},[]),I=a.useCallback(h=>{const L=he.current;he.current=h,y(h),L?.controller==="you"&&h?.controller!=="you"&&R(!1),h===null&&Y("");for(const fe of Ie.current)fe(h);ee.current?.observe()},[]),X=a.useCallback(h=>{if(h.type==="tabs"){const L=Ir(h.tabs);k(L);const fe=L.find(ke=>ke.active);fe&&(T(ke=>({...ke,url:fe.url})),xe.current=fe.url,me.current.openSignInPage())}else if(h.type==="nav"&&typeof h.url=="string")T({url:h.url,loading:h.loading===!0,canGoBack:h.canGoBack===!0,canGoForward:h.canGoForward===!0}),xe.current=h.url,me.current.openSignInPage();else if(h.type==="url"&&typeof h.url=="string")T(L=>({...L,url:h.url})),xe.current=h.url,me.current.openSignInPage();else if(h.type==="extensions")re(gn(h.extensions));else if(h.type==="viewport"){const L=h.setting;L&&(L.mode==="fill"||L.mode==="preset")&&j(L),typeof h.zoom=="number"&&H(h.zoom)}else h.type==="starting"?B(!0):(h.type==="asleep"||h.type==="awake")&&te(h.type==="asleep"?"asleep":"")},[]);a.useEffect(()=>{ee.current?.keep(P||ce)},[P,ce]);const f=()=>{R(!0),ee.current?.keep(!0),ee.current?.takeControl()},M=()=>{R(!1),ee.current?.handBack()},se=()=>{const h=Fe.current;!h||xe.current===null||(Fe.current=null,(!xe.current||xe.current==="about:blank")&&S({type:"navigate",url:h}))};me.current={openSignInPage:se,takeControl:f},a.useEffect(()=>{!t||!m||De.current===t.nonce||(De.current=t.nonce,Fe.current=t.url,me.current.takeControl(),me.current.openSignInPage())},[t,m]),a.useEffect(()=>{if(!(!r||!m||He.current===r.nonce)){if(W){W==="asleep"&&de.current?.send({type:"wake"})&&te("waking");return}He.current=r.nonce,S({type:"tabNew",url:r.url})}},[r,m,W,S]),a.useEffect(()=>{const h=()=>pe(!!ue.current&&document.fullscreenElement===ue.current);return document.addEventListener("fullscreenchange",h),()=>document.removeEventListener("fullscreenchange",h)},[]);const ye=()=>{const h=!!ue.current&&document.fullscreenElement===ue.current;h&&F&&Ee(!1),(h?document.exitFullscreen():ue.current?.requestFullscreen())?.catch(()=>x(s(h?"browser.panel.exitFullscreenFailed":"browser.panel.fullscreenUnavailable")))},ae=()=>{ie&&document.fullscreenElement===ue.current&&document.exitFullscreen().catch(()=>{}),Ee(h=>!h)};a.useEffect(()=>{if(!F)return;const h=L=>{L.key!=="Escape"||L.defaultPrevented||(L.preventDefault(),ie&&document.fullscreenElement===ue.current&&document.exitFullscreen().catch(()=>{}),Ee(!1))};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[F,ie]);const _=()=>{window.confirm(s("browser.panel.confirmRestart"))&&(x(""),de.current?.send({type:"restart"})||x(s("browser.panel.notConnected")))},oe=()=>{m&&de.current?.send({type:"wake"})?te("waking"):l()},ge=()=>{if(Ke===e.id){ct();return}kr({botId:e.id,seed:Re.current?.canvas()??null}).catch(()=>x(s("browser.panel.pipUnavailable")))},ne=g?.controller==="another-viewer",Se=m&&!ne,Te=g?.controller==="you",Je=Ne||Te;a.useEffect(()=>{Je||(d(!1),x(""))},[Je]);const Ze=m&&Te,$t=u&&yr(),pt=Rr(C.url);return n.jsxs("div",{ref:ue,className:F?"fixed inset-0 z-50 flex flex-col overflow-hidden bg-card text-ink":"flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-hairline/40 bg-card text-ink","data-browser-transport":u?"stream":"live",children:[n.jsx(yn,{ref:Q,botName:e.name,tabs:E,nav:C,connected:m,control:g,takeStatus:J,hint:s(P||ce?"browser.control.keptHint":"browser.control.yoursHint",{name:e.name}),commandsReady:Se,profileName:Pe,fullscreen:ie,maximized:F,onCommand:S,onAddress:h=>{const L=br(h);Se&&L?S({type:"navigate",url:L}):h.trim()&&x(s("browser.panel.enterAddress"))},onTake:f,onHandBack:M,onFullscreen:ye,onMaximize:ae,onProfiles:()=>{ee.current?.handBack(),U(!0)},menu:n.jsxs(n.Fragment,{children:[u?n.jsx(vn,{ready:m&&Te,extensions:le,onList:()=>de.current?.send({type:"extensions"}),onOpen:h=>de.current?.send({type:"openExtension",id:h})}):null,n.jsx(Sn,{stream:u,ready:m&&Te,typing:Ze,setting:b,zoom:O,pip:$t?{open:Ke===e.id}:null,onViewport:h=>de.current?.send({type:"viewport",setting:h}),onZoom:h=>de.current?.send({type:"zoom",factor:h}),onPip:ge,onType:()=>{G(!1),N(!0)},onSecret:()=>{G(!0),N(!0)},onReconnect:l,onRestart:_})]})}),$&&n.jsxs("div",{role:"alert",className:"flex shrink-0 items-center justify-between gap-2 border-b border-hairline/30 px-3 py-2 text-[12px] text-danger",children:[n.jsx("span",{children:$}),!m&&n.jsx("button",{className:"shrink-0 underline",onClick:l,children:s("browser.panel.reconnect")})]}),J==="stale"&&n.jsx("div",{role:"status",className:"shrink-0 border-b border-hairline/30 px-3 py-1.5 text-[12px] text-accent-text",children:s("browser.control.stale",{name:e.name})}),pt&&Oe!==C.url&&n.jsx(En,{wall:pt,botName:e.name,onDismiss:()=>We(C.url)}),n.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col bg-inset/40",children:[Je?n.jsx(er,{ref:Re,connect:p,input:S,label:s("browser.panel.pageLabel",{name:e.name}),onClient:z,onControl:I,onMessage:X,onConnectedChange:h=>{d(h),h&&(B(!1),Z(!1),x(""))},onFirstFrame:()=>B(!1),onUnauthorized:()=>{u?c(!0):Z(!0)},onGone:()=>Z(!0),onClose:(h,L)=>{h===1013&&L&&x(L)},onLeave:()=>Q.current?.focus()},`${w}:${u?"stream":"live"}:${e.browserProfile??""}`):null,W||ne||V||!m||K?n.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-card/95 p-6 text-center text-[13px] text-ink-secondary",children:[W?n.jsx(cn,{size:24}):ne?n.jsx(Rt,{size:24}):V?n.jsx(lt,{size:24}):n.jsx(Xe,{size:24,className:"animate-spin"}),n.jsx("span",{children:W?s("browser.panel.asleep"):ne?ot:V?s("browser.panel.disconnected"):K?u?s("browser.panel.starting"):s("browser.live.botBusy",{name:e.name}):s("browser.panel.opening")}),W?n.jsx("button",{type:"button",disabled:W==="waking",className:"rounded-lg border border-hairline px-3 py-1.5 text-[12px] text-ink hover:bg-inset disabled:opacity-60",onClick:oe,children:s(W==="waking"?"browser.panel.waking":"browser.panel.wake")}):V?n.jsx("button",{type:"button",className:"rounded-lg border border-hairline px-3 py-1.5 text-[12px] text-ink hover:bg-inset",onClick:l,children:s("browser.panel.reconnect")}):null]}):null]}),n.jsxs("dialog",{ref:be,onClose:()=>U(!1),onClick:h=>{h.target===h.currentTarget&&U(!1)},className:"m-auto w-[min(420px,calc(100%-32px))] max-h-[80vh] overflow-auto rounded-2xl border border-hairline/50 bg-card p-5 text-ink shadow-2xl backdrop:bg-black/40",children:[n.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[n.jsx("h2",{className:"text-[15px] font-medium",children:s("browser.panel.profiles")}),n.jsx("button",{className:Pt,"aria-label":s("browser.panel.closeProfiles"),onClick:()=>U(!1),children:n.jsx(Ue,{size:16})})]}),(ne||Te&&J!=="")&&n.jsx("p",{className:"mb-3 text-[12px] text-ink-secondary",children:s(ne?"browser.profiles.heldElsewhere":"browser.profiles.busy")}),n.jsx(an,{bot:e,disabled:ne||J==="pending"||J==="slow",onProfileChanged:()=>{U(!1),l()}})]}),n.jsxs("dialog",{ref:ve,onClose:()=>{const h=ve.current?.querySelector("input");h&&(h.value=""),N(!1)},className:"m-auto w-[min(420px,calc(100%-32px))] rounded-2xl border border-hairline/50 bg-card p-5 text-ink shadow-2xl backdrop:bg-black/40",children:[n.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[n.jsx("h2",{className:"text-[14px] font-medium",children:A?s("browser.typeSecret.title"):s("browser.panel.typeTextTitle")}),n.jsx("button",{className:Pt,"aria-label":s("browser.panel.closeTyping"),onClick:()=>N(!1),children:n.jsx(Ue,{size:16})})]}),n.jsxs("form",{className:"flex flex-col gap-3",onSubmit:h=>{h.preventDefault();const L=h.currentTarget.elements.namedItem("pageText");Ze&&L.value&&(S({type:"text",text:L.value}),L.value="",N(!1))},children:[n.jsx("input",{name:"pageText",type:A?"password":"text","aria-label":A?s("browser.typeSecret.field"):s("browser.panel.typeTextField"),autoComplete:A?"new-password":"off",spellCheck:!1,maxLength:4096,placeholder:A?"••••••••":s("browser.panel.typeTextPlaceholder"),className:"rounded-lg bg-inset px-3 py-2 text-[13px] outline-none focus:ring-1 focus:ring-accent"},A?"secret":"text"),A&&n.jsxs("p",{className:"flex items-center gap-1 text-[12px] text-ink-tertiary",children:[n.jsx(It,{size:11,"aria-hidden":"true"}),s("browser.typeSecret.note")]}),n.jsx("button",{disabled:!Ze,className:"self-end rounded-lg bg-accent px-4 py-2 text-[12px] text-accent-ink disabled:opacity-40",children:s("browser.panel.typeButton")})]})]})]})}function Hr({bot:e,signIn:t,page:r}){const{state:o}=dt(),i=o.config?.browserEngine,[c,u]=a.useState(!1),[w,v]=a.useState(null),[m,d]=a.useState(null);a.useEffect(()=>{let E=!0;return Ge("/api/auth/session").then(k=>{E&&d(k.scopes.includes("admin"))}).catch(()=>{E&&d(!1)}),()=>{E=!1}},[]);const g=c||i?.installing===!0,y=async()=>{v(null),u(!0);try{await Ge("/api/browser-engine/install",{method:"POST"})}catch(E){v(E instanceof Error?E.message:String(E))}finally{u(!1)}};return e.browser===!1?n.jsx("div",{className:"p-5 text-[13px] text-ink-secondary",children:s("browser.panel.enableBot")}):i?.kind==="engine"&&!g&&!i.installError?n.jsx(zr,{bot:e,signIn:t,page:r},e.id):n.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-start justify-center gap-3 rounded-xl bg-card p-5",children:[n.jsx("div",{className:"text-[15px] font-medium text-ink",children:i?.kind==="engine"?s("browser.panel.installIncomplete"):s("browser.panel.engineNotInstalled")}),n.jsx("p",{className:"text-[13px] leading-relaxed text-ink-secondary",children:i?.kind==="engine"?s("browser.panel.installIncompleteHelp"):i?.installable&&m!==!1?s("browser.panel.engineNotInstalledHelp",{name:e.name}):sn(o.config)}),i?.installable||i?.kind==="engine"?n.jsx("button",{type:"button",onClick:()=>{y()},disabled:g||m!==!0,className:"rounded-lg bg-accent px-3 py-1.5 text-[13px] font-medium text-accent-ink disabled:opacity-60",children:g?s("browser.panel.installing"):i?.kind==="engine"?s("browser.panel.retryInstall"):s("browser.panel.installEngine")}):null,(i?.installError||w)&&n.jsx("p",{role:"alert",className:"text-[12px] text-danger",children:w??i?.installError})]})}export{Hr as B,xn as u};
|