Spaces:
Running

File size: 5,663 Bytes
1d919a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// duck.ai and Gemini answer when their own pages send the chat.
// The IWA's controlled frame reads that page. A submit does not open a tab.
(function () {
  var DUCK = "https://duck.ai/";
  var GEMINI = "https://gemini.google.com/app";

  var DUCK_RUN = `async function run(question) {
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    for (let i = 0; i < 30; i++) {
      if (document.querySelector("textarea")) break;
      await sleep(400);
    }
    const ta = document.querySelector("textarea");
    if (!ta) return "";
    ta.focus();
    ta.value = question;
    ta.dispatchEvent(new Event("input", { bubbles: true }));
    await sleep(300);
    const btn = [...document.querySelectorAll("button")].find((b) => {
      const a = b.getAttribute("aria-label") || "";
      const t = (b.innerText || "").replace(/\\s+/g, " ").trim();
      return a === "Send" || a === "Ask" || t === "Ask" || t === "Send";
    });
    if (!btn) return "";
    btn.click();
    const until = Date.now() + 40000;
    while (Date.now() < until) {
      await sleep(1000);
      const loc = [...document.querySelectorAll("button")].find((b) => (b.innerText || "").trim() === "Don't Use");
      if (loc) loc.click();
      const stop = [...document.querySelectorAll("button")].some((b) => b.getAttribute("aria-label") === "Stop generating" && !b.disabled);
      if (stop) continue;
      let s = (document.body.innerText || "").replace(/\\s+/g, " ").trim();
      const said = s.search(/Duck\\.ai said/i);
      if (said < 0) continue;
      s = s.slice(said).replace(/^Duck\\.ai said\\s+/i, "");
      const end = s.search(/Duck\\.ai works best|Jump to latest|All chats are private|AI can make mistakes/i);
      if (end > 0) s = s.slice(0, end);
      s = s.replace(/\\s+/g, " ").trim();
      if (s.length > 12) return s.slice(0, 1500);
    }
    return "";
  }`;

  var GEMINI_RUN = `async function run(question) {
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    let box = null;
    for (let i = 0; i < 30; i++) {
      box = document.querySelector("rich-textarea textarea, textarea, div[contenteditable='true']");
      if (box) break;
      await sleep(400);
    }
    if (!box) return "";
    box.focus();
    if (box.tagName === "TEXTAREA" || box.tagName === "INPUT") {
      box.value = question;
      box.dispatchEvent(new Event("input", { bubbles: true }));
    } else {
      box.textContent = question;
      box.dispatchEvent(new InputEvent("input", { bubbles: true, data: question }));
    }
    await sleep(300);
    const btn = [...document.querySelectorAll("button")].find((b) => /send/i.test(b.getAttribute("aria-label") || b.innerText || ""));
    if (btn) btn.click();
    else box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", code: "Enter", bubbles: true }));
    const until = Date.now() + 40000;
    let last = "";
    let stable = 0;
    while (Date.now() < until) {
      await sleep(1000);
      const nodes = document.querySelectorAll("message-content, .model-response-text, .markdown");
      const raw = nodes.length ? nodes[nodes.length - 1].innerText : "";
      const s = String(raw || "").replace(/\\s+/g, " ").trim();
      if (!s || s === question) continue;
      if (s === last) {
        stable += 1;
        if (stable >= 2 && s.length > 20) return s.slice(0, 1500);
      } else {
        stable = 0;
        last = s;
      }
    }
    return last && last !== question ? last.slice(0, 1500) : "";
  }`;

  function destOf(source) {
    return source === "gemini" ? GEMINI : DUCK;
  }

  function control() {
    var el = document.getElementById("agent-view");
    if (!el || typeof el.executeScript !== "function") return null;
    return el;
  }

  function pageCode(source, question) {
    var run = source === "gemini" ? GEMINI_RUN : DUCK_RUN;
    return "(async function () {\n" + run + "\nreturn await run(" + JSON.stringify(question) + ");\n})()";
  }

  function firstText(value) {
    if (typeof value === "string") return value;
    if (Array.isArray(value)) return firstText(value[0]);
    if (value && typeof value.result === "string") return value.result;
    return "";
  }

  function runControlled(source, question) {
    var el = control();
    var dest = destOf(source);
    return new Promise(function (resolve) {
      var done = false;
      function finish(text) {
        if (done) return;
        done = true;
        resolve(typeof text === "string" ? text : "");
      }
      function read() {
        var code = pageCode(source, question);
        try {
          var pending = el.executeScript({ code: code });
          if (pending && typeof pending.then === "function") {
            pending.then(function (r) { finish(firstText(r)); }).catch(function () { finish(""); });
            return;
          }
          finish(firstText(pending));
        } catch (e) {
          try {
            el.executeScript({ code: code }, function (r) { finish(firstText(r)); });
          } catch (e2) { finish(""); }
        }
      }
      el.addEventListener("loadstop", read, { once: true });
      el.addEventListener("loadabort", function () { finish(""); }, { once: true });
      try { el.src = dest; }
      catch (e) { finish(""); return; }
      setTimeout(function () { finish(""); }, 50000);
    });
  }

  self.__RBI_IWA_ASK__ = function (source, q) {
    var kind = String(source || "") === "gemini" ? "gemini" : "duck";
    var question = String(q || "").replace(/\s+/g, " ").trim().slice(0, 180);
    if (!question) return Promise.resolve("");
    if (control()) return runControlled(kind, question);
    return Promise.resolve("");
  };
})();