@steipete/oracle 0.7.6 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/bin/oracle-cli.js +4 -0
- package/dist/src/browser/actions/assistantResponse.js +437 -84
- package/dist/src/browser/actions/attachmentDataTransfer.js +138 -0
- package/dist/src/browser/actions/attachments.js +1300 -132
- package/dist/src/browser/actions/modelSelection.js +9 -4
- package/dist/src/browser/actions/navigation.js +160 -5
- package/dist/src/browser/actions/promptComposer.js +54 -11
- package/dist/src/browser/actions/remoteFileTransfer.js +5 -156
- package/dist/src/browser/config.js +9 -3
- package/dist/src/browser/constants.js +4 -1
- package/dist/src/browser/cookies.js +55 -21
- package/dist/src/browser/index.js +321 -65
- package/dist/src/browser/modelStrategy.js +13 -0
- package/dist/src/browser/pageActions.js +2 -2
- package/dist/src/browser/reattach.js +21 -179
- package/dist/src/browser/reattachHelpers.js +382 -0
- package/dist/src/browserMode.js +1 -1
- package/dist/src/cli/browserConfig.js +10 -4
- package/dist/src/cli/browserDefaults.js +3 -0
- package/dist/src/cli/sessionDisplay.js +7 -0
- package/dist/src/gemini-web/executor.js +107 -46
- package/dist/src/oracle/run.js +23 -32
- package/dist/src/remote/server.js +30 -15
- package/package.json +8 -17
|
@@ -7,24 +7,7 @@ import { launchChrome, connectToChrome, hideChromeWindow } from './chromeLifecyc
|
|
|
7
7
|
import { resolveBrowserConfig } from './config.js';
|
|
8
8
|
import { syncCookies } from './cookies.js';
|
|
9
9
|
import { CHATGPT_URL } from './constants.js';
|
|
10
|
-
import {
|
|
11
|
-
function pickTarget(targets, runtime) {
|
|
12
|
-
if (!Array.isArray(targets) || targets.length === 0) {
|
|
13
|
-
return undefined;
|
|
14
|
-
}
|
|
15
|
-
if (runtime.chromeTargetId) {
|
|
16
|
-
const byId = targets.find((t) => t.targetId === runtime.chromeTargetId);
|
|
17
|
-
if (byId)
|
|
18
|
-
return byId;
|
|
19
|
-
}
|
|
20
|
-
if (runtime.tabUrl) {
|
|
21
|
-
const byUrl = targets.find((t) => t.url?.startsWith(runtime.tabUrl)) ||
|
|
22
|
-
targets.find((t) => runtime.tabUrl.startsWith(t.url || ''));
|
|
23
|
-
if (byUrl)
|
|
24
|
-
return byUrl;
|
|
25
|
-
}
|
|
26
|
-
return targets.find((t) => t.type === 'page') ?? targets[0];
|
|
27
|
-
}
|
|
10
|
+
import { pickTarget, extractConversationIdFromUrl, buildConversationUrl, withTimeout, openConversationFromSidebar, openConversationFromSidebarWithRetry, waitForLocationChange, readConversationTurnIndex, buildPromptEchoMatcher, recoverPromptEcho, alignPromptEchoMarkdown, } from './reattachHelpers.js';
|
|
28
11
|
export async function resumeBrowserSession(runtime, config, logger, deps = {}) {
|
|
29
12
|
const recoverSession = deps.recoverSession ??
|
|
30
13
|
(async (runtimeMeta, configMeta) => resumeBrowserSessionViaNewChrome(runtimeMeta, configMeta, logger, deps));
|
|
@@ -58,7 +41,10 @@ export async function resumeBrowserSession(runtime, config, logger, deps = {}) {
|
|
|
58
41
|
const { result } = await Runtime.evaluate({ expression: 'location.href', returnByValue: true });
|
|
59
42
|
const href = typeof result?.value === 'string' ? result.value : '';
|
|
60
43
|
if (href.includes('/c/')) {
|
|
61
|
-
|
|
44
|
+
const currentId = extractConversationIdFromUrl(href);
|
|
45
|
+
if (!runtime.conversationId || (currentId && currentId === runtime.conversationId)) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
62
48
|
}
|
|
63
49
|
const opened = await openConversationFromSidebarWithRetry(Runtime, {
|
|
64
50
|
conversationId: runtime.conversationId ?? extractConversationIdFromUrl(runtime.tabUrl ?? ''),
|
|
@@ -76,8 +62,12 @@ export async function resumeBrowserSession(runtime, config, logger, deps = {}) {
|
|
|
76
62
|
const pingTimeoutMs = Math.min(5_000, Math.max(1_500, Math.floor(timeoutMs * 0.05)));
|
|
77
63
|
await withTimeout(Runtime.evaluate({ expression: '1+1', returnByValue: true }), pingTimeoutMs, 'Reattach target did not respond');
|
|
78
64
|
await ensureConversationOpen();
|
|
79
|
-
const
|
|
80
|
-
const
|
|
65
|
+
const minTurnIndex = await readConversationTurnIndex(Runtime, logger);
|
|
66
|
+
const promptEcho = buildPromptEchoMatcher(deps.promptPreview);
|
|
67
|
+
const answer = await withTimeout(waitForResponse(Runtime, timeoutMs, logger, minTurnIndex ?? undefined), timeoutMs + 5_000, 'Reattach response timed out');
|
|
68
|
+
const recovered = await recoverPromptEcho(Runtime, answer, promptEcho, logger, minTurnIndex, timeoutMs);
|
|
69
|
+
const markdown = (await withTimeout(captureMarkdown(Runtime, recovered.meta, logger), 15_000, 'Reattach markdown capture timed out')) ?? recovered.text;
|
|
70
|
+
const aligned = alignPromptEchoMarkdown(recovered.text, markdown, promptEcho, logger);
|
|
81
71
|
if (client && typeof client.close === 'function') {
|
|
82
72
|
try {
|
|
83
73
|
await client.close();
|
|
@@ -86,7 +76,7 @@ export async function resumeBrowserSession(runtime, config, logger, deps = {}) {
|
|
|
86
76
|
// ignore
|
|
87
77
|
}
|
|
88
78
|
}
|
|
89
|
-
return { answerText:
|
|
79
|
+
return { answerText: aligned.answerText, answerMarkdown: aligned.answerMarkdown };
|
|
90
80
|
}
|
|
91
81
|
catch (error) {
|
|
92
82
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -143,7 +133,8 @@ async function resumeBrowserSessionViaNewChrome(runtime, config, logger, deps) {
|
|
|
143
133
|
else {
|
|
144
134
|
const opened = await openConversationFromSidebarWithRetry(Runtime, {
|
|
145
135
|
conversationId: runtime.conversationId ?? extractConversationIdFromUrl(runtime.tabUrl ?? ''),
|
|
146
|
-
preferProjects: resolved.url !== CHATGPT_URL
|
|
136
|
+
preferProjects: resolved.url !== CHATGPT_URL ||
|
|
137
|
+
Boolean(runtime.tabUrl && (/\/g\//.test(runtime.tabUrl) || runtime.tabUrl.includes('/project'))),
|
|
147
138
|
promptPreview: deps.promptPreview,
|
|
148
139
|
}, 15_000);
|
|
149
140
|
if (!opened) {
|
|
@@ -154,8 +145,12 @@ async function resumeBrowserSessionViaNewChrome(runtime, config, logger, deps) {
|
|
|
154
145
|
const waitForResponse = deps.waitForAssistantResponse ?? waitForAssistantResponse;
|
|
155
146
|
const captureMarkdown = deps.captureAssistantMarkdown ?? captureAssistantMarkdown;
|
|
156
147
|
const timeoutMs = resolved.timeoutMs ?? 120_000;
|
|
157
|
-
const
|
|
158
|
-
const
|
|
148
|
+
const minTurnIndex = await readConversationTurnIndex(Runtime, logger);
|
|
149
|
+
const promptEcho = buildPromptEchoMatcher(deps.promptPreview);
|
|
150
|
+
const answer = await waitForResponse(Runtime, timeoutMs, logger, minTurnIndex ?? undefined);
|
|
151
|
+
const recovered = await recoverPromptEcho(Runtime, answer, promptEcho, logger, minTurnIndex, timeoutMs);
|
|
152
|
+
const markdown = (await captureMarkdown(Runtime, recovered.meta, logger)) ?? recovered.text;
|
|
153
|
+
const aligned = alignPromptEchoMarkdown(recovered.text, markdown, promptEcho, logger);
|
|
159
154
|
if (client && typeof client.close === 'function') {
|
|
160
155
|
try {
|
|
161
156
|
await client.close();
|
|
@@ -173,160 +168,7 @@ async function resumeBrowserSessionViaNewChrome(runtime, config, logger, deps) {
|
|
|
173
168
|
}
|
|
174
169
|
await rm(userDataDir, { recursive: true, force: true }).catch(() => undefined);
|
|
175
170
|
}
|
|
176
|
-
return { answerText:
|
|
177
|
-
}
|
|
178
|
-
function extractConversationIdFromUrl(url) {
|
|
179
|
-
if (!url)
|
|
180
|
-
return undefined;
|
|
181
|
-
const match = url.match(/\/c\/([a-zA-Z0-9-]+)/);
|
|
182
|
-
return match?.[1];
|
|
183
|
-
}
|
|
184
|
-
function buildConversationUrl(runtime, baseUrl) {
|
|
185
|
-
if (runtime.tabUrl) {
|
|
186
|
-
if (runtime.tabUrl.includes('/c/')) {
|
|
187
|
-
return runtime.tabUrl;
|
|
188
|
-
}
|
|
189
|
-
return null;
|
|
190
|
-
}
|
|
191
|
-
const conversationId = runtime.conversationId;
|
|
192
|
-
if (!conversationId) {
|
|
193
|
-
return null;
|
|
194
|
-
}
|
|
195
|
-
try {
|
|
196
|
-
const base = new URL(baseUrl);
|
|
197
|
-
return `${base.origin}/c/${conversationId}`;
|
|
198
|
-
}
|
|
199
|
-
catch {
|
|
200
|
-
return null;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
async function withTimeout(task, ms, label) {
|
|
204
|
-
let timeoutId;
|
|
205
|
-
const timeout = new Promise((_, reject) => {
|
|
206
|
-
timeoutId = setTimeout(() => reject(new Error(label)), ms);
|
|
207
|
-
});
|
|
208
|
-
return Promise.race([task, timeout]).finally(() => {
|
|
209
|
-
if (timeoutId) {
|
|
210
|
-
clearTimeout(timeoutId);
|
|
211
|
-
}
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
async function openConversationFromSidebar(Runtime, options) {
|
|
215
|
-
const response = await Runtime.evaluate({
|
|
216
|
-
expression: `(() => {
|
|
217
|
-
const conversationId = ${JSON.stringify(options.conversationId ?? null)};
|
|
218
|
-
const preferProjects = ${JSON.stringify(Boolean(options.preferProjects))};
|
|
219
|
-
const promptPreview = ${JSON.stringify(options.promptPreview ?? null)};
|
|
220
|
-
const promptNeedle = promptPreview ? promptPreview.trim().toLowerCase().slice(0, 100) : '';
|
|
221
|
-
const nav = document.querySelector('nav') || document.querySelector('aside') || document.body;
|
|
222
|
-
if (preferProjects) {
|
|
223
|
-
const projectLink = Array.from(nav.querySelectorAll('a,button'))
|
|
224
|
-
.find((el) => (el.textContent || '').trim().toLowerCase() === 'projects');
|
|
225
|
-
if (projectLink) {
|
|
226
|
-
projectLink.click();
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
const allElements = Array.from(
|
|
230
|
-
document.querySelectorAll(
|
|
231
|
-
'a,button,[role="link"],[role="button"],[data-href],[data-url],[data-conversation-id],[data-testid*="conversation"],[data-testid*="history"]',
|
|
232
|
-
),
|
|
233
|
-
);
|
|
234
|
-
const getHref = (el) =>
|
|
235
|
-
el.getAttribute('href') ||
|
|
236
|
-
el.getAttribute('data-href') ||
|
|
237
|
-
el.getAttribute('data-url') ||
|
|
238
|
-
el.dataset?.href ||
|
|
239
|
-
el.dataset?.url ||
|
|
240
|
-
'';
|
|
241
|
-
const toCandidate = (el) => {
|
|
242
|
-
const clickable = el.closest('a,button,[role="link"],[role="button"]') || el;
|
|
243
|
-
const rawText = (el.textContent || clickable.textContent || '').trim();
|
|
244
|
-
return {
|
|
245
|
-
el,
|
|
246
|
-
clickable,
|
|
247
|
-
href: getHref(clickable) || getHref(el),
|
|
248
|
-
conversationId:
|
|
249
|
-
clickable.getAttribute('data-conversation-id') ||
|
|
250
|
-
el.getAttribute('data-conversation-id') ||
|
|
251
|
-
clickable.dataset?.conversationId ||
|
|
252
|
-
el.dataset?.conversationId ||
|
|
253
|
-
'',
|
|
254
|
-
testId: clickable.getAttribute('data-testid') || el.getAttribute('data-testid') || '',
|
|
255
|
-
text: rawText.replace(/\\s+/g, ' ').slice(0, 400),
|
|
256
|
-
inNav: Boolean(clickable.closest('nav,aside')),
|
|
257
|
-
};
|
|
258
|
-
};
|
|
259
|
-
const candidates = allElements.map(toCandidate);
|
|
260
|
-
const mainCandidates = candidates.filter((item) => !item.inNav);
|
|
261
|
-
const navCandidates = candidates.filter((item) => item.inNav);
|
|
262
|
-
const visible = (item) => {
|
|
263
|
-
const rect = item.clickable.getBoundingClientRect();
|
|
264
|
-
return rect.width > 0 && rect.height > 0;
|
|
265
|
-
};
|
|
266
|
-
const pick = (items) => (items.find(visible) || items[0] || null);
|
|
267
|
-
let target = null;
|
|
268
|
-
if (conversationId) {
|
|
269
|
-
const byId = (item) =>
|
|
270
|
-
(item.href && item.href.includes('/c/' + conversationId)) ||
|
|
271
|
-
(item.conversationId && item.conversationId === conversationId);
|
|
272
|
-
target = pick(mainCandidates.filter(byId)) || pick(navCandidates.filter(byId));
|
|
273
|
-
}
|
|
274
|
-
if (!target && promptNeedle) {
|
|
275
|
-
const byPrompt = (item) => item.text && item.text.toLowerCase().includes(promptNeedle);
|
|
276
|
-
target = pick(mainCandidates.filter(byPrompt)) || pick(navCandidates.filter(byPrompt));
|
|
277
|
-
}
|
|
278
|
-
if (!target) {
|
|
279
|
-
const byHref = (item) => item.href && item.href.includes('/c/');
|
|
280
|
-
target = pick(mainCandidates.filter(byHref)) || pick(navCandidates.filter(byHref));
|
|
281
|
-
}
|
|
282
|
-
if (!target) {
|
|
283
|
-
const byTestId = (item) => /conversation|history/i.test(item.testId || '');
|
|
284
|
-
target = pick(mainCandidates.filter(byTestId)) || pick(navCandidates.filter(byTestId));
|
|
285
|
-
}
|
|
286
|
-
if (target) {
|
|
287
|
-
target.clickable.scrollIntoView({ block: 'center' });
|
|
288
|
-
target.clickable.dispatchEvent(
|
|
289
|
-
new MouseEvent('click', { bubbles: true, cancelable: true, view: window }),
|
|
290
|
-
);
|
|
291
|
-
return {
|
|
292
|
-
ok: true,
|
|
293
|
-
href: target.href || '',
|
|
294
|
-
count: candidates.length,
|
|
295
|
-
scope: target.inNav ? 'nav' : 'main',
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
return { ok: false, count: candidates.length };
|
|
299
|
-
})()`,
|
|
300
|
-
returnByValue: true,
|
|
301
|
-
});
|
|
302
|
-
return Boolean(response.result?.value?.ok);
|
|
303
|
-
}
|
|
304
|
-
async function openConversationFromSidebarWithRetry(Runtime, options, timeoutMs) {
|
|
305
|
-
const start = Date.now();
|
|
306
|
-
let attempt = 0;
|
|
307
|
-
while (Date.now() - start < timeoutMs) {
|
|
308
|
-
// Retry because project list can hydrate after initial navigation.
|
|
309
|
-
const opened = await openConversationFromSidebar(Runtime, options);
|
|
310
|
-
if (opened) {
|
|
311
|
-
return true;
|
|
312
|
-
}
|
|
313
|
-
attempt += 1;
|
|
314
|
-
await delay(attempt < 5 ? 250 : 500);
|
|
315
|
-
}
|
|
316
|
-
return false;
|
|
317
|
-
}
|
|
318
|
-
async function waitForLocationChange(Runtime, timeoutMs) {
|
|
319
|
-
const start = Date.now();
|
|
320
|
-
let lastHref = '';
|
|
321
|
-
while (Date.now() - start < timeoutMs) {
|
|
322
|
-
const { result } = await Runtime.evaluate({ expression: 'location.href', returnByValue: true });
|
|
323
|
-
const href = typeof result?.value === 'string' ? result.value : '';
|
|
324
|
-
if (lastHref && href !== lastHref) {
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
lastHref = href;
|
|
328
|
-
await delay(200);
|
|
329
|
-
}
|
|
171
|
+
return { answerText: aligned.answerText, answerMarkdown: aligned.answerMarkdown };
|
|
330
172
|
}
|
|
331
173
|
// biome-ignore lint/style/useNamingConvention: test-only export used in vitest suite
|
|
332
174
|
export const __test__ = {
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { CONVERSATION_TURN_SELECTOR } from './constants.js';
|
|
2
|
+
import { delay } from './utils.js';
|
|
3
|
+
import { readAssistantSnapshot } from './pageActions.js';
|
|
4
|
+
export function pickTarget(targets, runtime) {
|
|
5
|
+
if (!Array.isArray(targets) || targets.length === 0) {
|
|
6
|
+
return undefined;
|
|
7
|
+
}
|
|
8
|
+
if (runtime.chromeTargetId) {
|
|
9
|
+
const byId = targets.find((t) => t.targetId === runtime.chromeTargetId);
|
|
10
|
+
if (byId)
|
|
11
|
+
return byId;
|
|
12
|
+
}
|
|
13
|
+
if (runtime.tabUrl) {
|
|
14
|
+
const byUrl = targets.find((t) => t.url?.startsWith(runtime.tabUrl)) ||
|
|
15
|
+
targets.find((t) => runtime.tabUrl.startsWith(t.url || ''));
|
|
16
|
+
if (byUrl)
|
|
17
|
+
return byUrl;
|
|
18
|
+
}
|
|
19
|
+
return targets.find((t) => t.type === 'page') ?? targets[0];
|
|
20
|
+
}
|
|
21
|
+
export function extractConversationIdFromUrl(url) {
|
|
22
|
+
if (!url)
|
|
23
|
+
return undefined;
|
|
24
|
+
const match = url.match(/\/c\/([a-zA-Z0-9-]+)/);
|
|
25
|
+
return match?.[1];
|
|
26
|
+
}
|
|
27
|
+
export function buildConversationUrl(runtime, baseUrl) {
|
|
28
|
+
if (runtime.tabUrl) {
|
|
29
|
+
if (runtime.tabUrl.includes('/c/')) {
|
|
30
|
+
return runtime.tabUrl;
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
const conversationId = runtime.conversationId;
|
|
35
|
+
if (!conversationId) {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const base = new URL(baseUrl);
|
|
40
|
+
const pathRoot = base.pathname.replace(/\/$/, '');
|
|
41
|
+
const prefix = pathRoot === '/' ? '' : pathRoot;
|
|
42
|
+
return `${base.origin}${prefix}/c/${conversationId}`;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export async function withTimeout(task, ms, label) {
|
|
49
|
+
let timeoutId;
|
|
50
|
+
const timeout = new Promise((_, reject) => {
|
|
51
|
+
timeoutId = setTimeout(() => reject(new Error(label)), ms);
|
|
52
|
+
});
|
|
53
|
+
return Promise.race([task, timeout]).finally(() => {
|
|
54
|
+
if (timeoutId) {
|
|
55
|
+
clearTimeout(timeoutId);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
export async function openConversationFromSidebar(Runtime, options, attempt = 0) {
|
|
60
|
+
const response = await Runtime.evaluate({
|
|
61
|
+
expression: `(() => {
|
|
62
|
+
const conversationId = ${JSON.stringify(options.conversationId ?? null)};
|
|
63
|
+
const preferProjects = ${JSON.stringify(Boolean(options.preferProjects))};
|
|
64
|
+
const promptPreview = ${JSON.stringify(options.promptPreview ?? null)};
|
|
65
|
+
const attemptIndex = ${Math.max(0, attempt)};
|
|
66
|
+
const promptNeedleFull = promptPreview ? promptPreview.trim().toLowerCase().slice(0, 100) : '';
|
|
67
|
+
const promptNeedleShort = promptNeedleFull.replace(/\\s*\\d{4,}\\s*$/, '').trim();
|
|
68
|
+
const promptNeedles = Array.from(new Set([promptNeedleFull, promptNeedleShort].filter(Boolean)));
|
|
69
|
+
const nav = document.querySelector('nav') || document.querySelector('aside') || document.body;
|
|
70
|
+
if (preferProjects) {
|
|
71
|
+
const projectLink = Array.from(nav.querySelectorAll('a,button'))
|
|
72
|
+
.find((el) => (el.textContent || '').trim().toLowerCase() === 'projects');
|
|
73
|
+
if (projectLink) {
|
|
74
|
+
projectLink.click();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const allElements = Array.from(
|
|
78
|
+
document.querySelectorAll(
|
|
79
|
+
'a,button,[role="link"],[role="button"],[data-href],[data-url],[data-conversation-id],[data-testid*="conversation"],[data-testid*="history"]',
|
|
80
|
+
),
|
|
81
|
+
);
|
|
82
|
+
const getHref = (el) =>
|
|
83
|
+
el.getAttribute('href') ||
|
|
84
|
+
el.getAttribute('data-href') ||
|
|
85
|
+
el.getAttribute('data-url') ||
|
|
86
|
+
el.dataset?.href ||
|
|
87
|
+
el.dataset?.url ||
|
|
88
|
+
'';
|
|
89
|
+
const toCandidate = (el) => {
|
|
90
|
+
const clickable = el.closest('a,button,[role="link"],[role="button"]') || el;
|
|
91
|
+
const rawText = (el.textContent || clickable.textContent || '').trim();
|
|
92
|
+
return {
|
|
93
|
+
el,
|
|
94
|
+
clickable,
|
|
95
|
+
href: getHref(clickable) || getHref(el),
|
|
96
|
+
conversationId:
|
|
97
|
+
clickable.getAttribute('data-conversation-id') ||
|
|
98
|
+
el.getAttribute('data-conversation-id') ||
|
|
99
|
+
clickable.dataset?.conversationId ||
|
|
100
|
+
el.dataset?.conversationId ||
|
|
101
|
+
'',
|
|
102
|
+
testId: clickable.getAttribute('data-testid') || el.getAttribute('data-testid') || '',
|
|
103
|
+
text: rawText.replace(/\\s+/g, ' ').slice(0, 400),
|
|
104
|
+
inNav: Boolean(clickable.closest('nav,aside')),
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
const candidates = allElements.map(toCandidate);
|
|
108
|
+
const mainCandidates = candidates.filter((item) => !item.inNav);
|
|
109
|
+
const navCandidates = candidates.filter((item) => item.inNav);
|
|
110
|
+
const visible = (item) => {
|
|
111
|
+
const rect = item.clickable.getBoundingClientRect();
|
|
112
|
+
return rect.width > 0 && rect.height > 0;
|
|
113
|
+
};
|
|
114
|
+
const pick = (items) => (items.find(visible) || items[0] || null);
|
|
115
|
+
const pickWithAttempt = (items) => {
|
|
116
|
+
if (!items.length) return null;
|
|
117
|
+
const visibleItems = items.filter(visible);
|
|
118
|
+
const pool = visibleItems.length > 0 ? visibleItems : items;
|
|
119
|
+
const index = Math.min(attemptIndex, pool.length - 1);
|
|
120
|
+
return pool[index] ?? null;
|
|
121
|
+
};
|
|
122
|
+
let target = null;
|
|
123
|
+
if (conversationId) {
|
|
124
|
+
const byId = (item) =>
|
|
125
|
+
(item.href && item.href.includes('/c/' + conversationId)) ||
|
|
126
|
+
(item.conversationId && item.conversationId === conversationId);
|
|
127
|
+
target = pick(mainCandidates.filter(byId)) || pick(navCandidates.filter(byId));
|
|
128
|
+
}
|
|
129
|
+
if (!target && promptNeedles.length > 0) {
|
|
130
|
+
const byPrompt = (item) => promptNeedles.some((needle) => item.text && item.text.toLowerCase().includes(needle));
|
|
131
|
+
const sortBySpecificity = (items) =>
|
|
132
|
+
items
|
|
133
|
+
.filter(byPrompt)
|
|
134
|
+
.sort((a, b) => (a.text?.length ?? 0) - (b.text?.length ?? 0));
|
|
135
|
+
target = pickWithAttempt(sortBySpecificity(mainCandidates)) || pickWithAttempt(sortBySpecificity(navCandidates));
|
|
136
|
+
}
|
|
137
|
+
if (!target) {
|
|
138
|
+
const byHref = (item) => item.href && item.href.includes('/c/');
|
|
139
|
+
target = pickWithAttempt(mainCandidates.filter(byHref)) || pickWithAttempt(navCandidates.filter(byHref));
|
|
140
|
+
}
|
|
141
|
+
if (!target) {
|
|
142
|
+
const byTestId = (item) => /conversation|history/i.test(item.testId || '');
|
|
143
|
+
target = pickWithAttempt(mainCandidates.filter(byTestId)) || pickWithAttempt(navCandidates.filter(byTestId));
|
|
144
|
+
}
|
|
145
|
+
if (target) {
|
|
146
|
+
target.clickable.scrollIntoView({ block: 'center' });
|
|
147
|
+
target.clickable.dispatchEvent(
|
|
148
|
+
new MouseEvent('click', { bubbles: true, cancelable: true, view: window }),
|
|
149
|
+
);
|
|
150
|
+
// Fallback: some project-sidebar items don't navigate on click, force the URL.
|
|
151
|
+
if (target.href && target.href.includes('/c/')) {
|
|
152
|
+
const targetUrl = target.href.startsWith('http')
|
|
153
|
+
? target.href
|
|
154
|
+
: new URL(target.href, location.origin).toString();
|
|
155
|
+
if (targetUrl && targetUrl !== location.href) {
|
|
156
|
+
location.href = targetUrl;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
ok: true,
|
|
161
|
+
href: target.href || '',
|
|
162
|
+
count: candidates.length,
|
|
163
|
+
scope: target.inNav ? 'nav' : 'main',
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
return { ok: false, count: candidates.length };
|
|
167
|
+
})()`,
|
|
168
|
+
returnByValue: true,
|
|
169
|
+
});
|
|
170
|
+
return Boolean(response.result?.value?.ok);
|
|
171
|
+
}
|
|
172
|
+
export async function openConversationFromSidebarWithRetry(Runtime, options, timeoutMs) {
|
|
173
|
+
const start = Date.now();
|
|
174
|
+
let attempt = 0;
|
|
175
|
+
while (Date.now() - start < timeoutMs) {
|
|
176
|
+
// Retry because project list can hydrate after initial navigation.
|
|
177
|
+
const opened = await openConversationFromSidebar(Runtime, options, attempt);
|
|
178
|
+
if (opened) {
|
|
179
|
+
if (options.promptPreview) {
|
|
180
|
+
const matched = await waitForPromptPreview(Runtime, options.promptPreview, 10_000);
|
|
181
|
+
if (matched) {
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
attempt += 1;
|
|
190
|
+
await delay(attempt < 5 ? 250 : 500);
|
|
191
|
+
}
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
export async function waitForPromptPreview(Runtime, promptPreview, timeoutMs) {
|
|
195
|
+
const needleFull = promptPreview.trim().toLowerCase().slice(0, 120);
|
|
196
|
+
const needleShort = needleFull.replace(/\\s*\\d{4,}\\s*$/, '').trim();
|
|
197
|
+
const needles = Array.from(new Set([needleFull, needleShort].filter(Boolean)));
|
|
198
|
+
if (needles.length === 0)
|
|
199
|
+
return false;
|
|
200
|
+
const selectorLiteral = JSON.stringify(CONVERSATION_TURN_SELECTOR);
|
|
201
|
+
const expression = `(() => {
|
|
202
|
+
const needles = ${JSON.stringify(needles)};
|
|
203
|
+
const root =
|
|
204
|
+
document.querySelector('section[data-testid="screen-threadFlyOut"]') ||
|
|
205
|
+
document.querySelector('[data-testid="chat-thread"]') ||
|
|
206
|
+
document.querySelector('main') ||
|
|
207
|
+
document.querySelector('[role="main"]');
|
|
208
|
+
if (!root) return false;
|
|
209
|
+
const userTurns = Array.from(root.querySelectorAll('[data-message-author-role="user"], [data-turn="user"]'));
|
|
210
|
+
const collectText = (nodes) =>
|
|
211
|
+
nodes
|
|
212
|
+
.map((node) => (node.innerText || node.textContent || ''))
|
|
213
|
+
.join(' ')
|
|
214
|
+
.toLowerCase();
|
|
215
|
+
let text = collectText(userTurns);
|
|
216
|
+
let hasTurns = userTurns.length > 0;
|
|
217
|
+
if (!text) {
|
|
218
|
+
const turns = Array.from(root.querySelectorAll(${selectorLiteral}));
|
|
219
|
+
hasTurns = hasTurns || turns.length > 0;
|
|
220
|
+
text = collectText(turns);
|
|
221
|
+
}
|
|
222
|
+
if (!text) {
|
|
223
|
+
text = (root.innerText || root.textContent || '').toLowerCase();
|
|
224
|
+
}
|
|
225
|
+
return needles.some((needle) => text.includes(needle));
|
|
226
|
+
})()`;
|
|
227
|
+
const start = Date.now();
|
|
228
|
+
while (Date.now() - start < timeoutMs) {
|
|
229
|
+
try {
|
|
230
|
+
const { result } = await Runtime.evaluate({ expression, returnByValue: true });
|
|
231
|
+
if (result?.value === true) {
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
// ignore
|
|
237
|
+
}
|
|
238
|
+
await delay(300);
|
|
239
|
+
}
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
export async function waitForLocationChange(Runtime, timeoutMs) {
|
|
243
|
+
const start = Date.now();
|
|
244
|
+
let lastHref = '';
|
|
245
|
+
while (Date.now() - start < timeoutMs) {
|
|
246
|
+
const { result } = await Runtime.evaluate({ expression: 'location.href', returnByValue: true });
|
|
247
|
+
const href = typeof result?.value === 'string' ? result.value : '';
|
|
248
|
+
if (lastHref && href !== lastHref) {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
lastHref = href;
|
|
252
|
+
await delay(200);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
export async function readConversationTurnIndex(Runtime, logger) {
|
|
256
|
+
const selectorLiteral = JSON.stringify(CONVERSATION_TURN_SELECTOR);
|
|
257
|
+
try {
|
|
258
|
+
const { result } = await Runtime.evaluate({
|
|
259
|
+
expression: `document.querySelectorAll(${selectorLiteral}).length`,
|
|
260
|
+
returnByValue: true,
|
|
261
|
+
});
|
|
262
|
+
const raw = typeof result?.value === 'number' ? result.value : Number(result?.value);
|
|
263
|
+
if (!Number.isFinite(raw)) {
|
|
264
|
+
throw new Error('Turn count not numeric');
|
|
265
|
+
}
|
|
266
|
+
return Math.max(0, Math.floor(raw) - 1);
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
if (logger?.verbose) {
|
|
270
|
+
logger(`Failed to read conversation turn index: ${error instanceof Error ? error.message : String(error)}`);
|
|
271
|
+
}
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
function normalizeForComparison(text) {
|
|
276
|
+
return String(text || '').toLowerCase().replace(/\\s+/g, ' ').trim();
|
|
277
|
+
}
|
|
278
|
+
export function buildPromptEchoMatcher(promptPreview) {
|
|
279
|
+
const normalizedPrompt = normalizeForComparison(promptPreview ?? '');
|
|
280
|
+
if (!normalizedPrompt) {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
const promptPrefix = normalizedPrompt.length >= 80 ? normalizedPrompt.slice(0, Math.min(200, normalizedPrompt.length)) : '';
|
|
284
|
+
const minFragment = Math.min(40, normalizedPrompt.length);
|
|
285
|
+
return {
|
|
286
|
+
isEcho: (text) => {
|
|
287
|
+
const normalized = normalizeForComparison(text);
|
|
288
|
+
if (!normalized)
|
|
289
|
+
return false;
|
|
290
|
+
if (normalized === normalizedPrompt)
|
|
291
|
+
return true;
|
|
292
|
+
if (promptPrefix.length > 0 && normalized.startsWith(promptPrefix))
|
|
293
|
+
return true;
|
|
294
|
+
if (normalized.length >= minFragment && normalizedPrompt.startsWith(normalized)) {
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
if (normalized.includes('…') || normalized.includes('...')) {
|
|
298
|
+
const marker = normalized.includes('…') ? '…' : '...';
|
|
299
|
+
const [prefixRaw, suffixRaw] = normalized.split(marker);
|
|
300
|
+
const prefix = prefixRaw?.trim() ?? '';
|
|
301
|
+
const suffix = suffixRaw?.trim() ?? '';
|
|
302
|
+
if (!prefix && !suffix)
|
|
303
|
+
return false;
|
|
304
|
+
if (prefix && !normalizedPrompt.includes(prefix))
|
|
305
|
+
return false;
|
|
306
|
+
if (suffix && !normalizedPrompt.includes(suffix))
|
|
307
|
+
return false;
|
|
308
|
+
const fragmentLength = prefix.length + suffix.length;
|
|
309
|
+
return fragmentLength >= minFragment;
|
|
310
|
+
}
|
|
311
|
+
return false;
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
export async function recoverPromptEcho(Runtime, answer, matcher, logger, minTurnIndex, timeoutMs) {
|
|
316
|
+
if (!matcher || !matcher.isEcho(answer.text)) {
|
|
317
|
+
return answer;
|
|
318
|
+
}
|
|
319
|
+
logger('Detected prompt echo while reattaching; waiting for assistant response...');
|
|
320
|
+
const deadline = Date.now() + Math.min(timeoutMs, 15_000);
|
|
321
|
+
let bestText = null;
|
|
322
|
+
let stableCount = 0;
|
|
323
|
+
while (Date.now() < deadline) {
|
|
324
|
+
const snapshot = await readAssistantSnapshot(Runtime, minTurnIndex ?? undefined).catch(() => null);
|
|
325
|
+
const text = typeof snapshot?.text === 'string' ? snapshot.text.trim() : '';
|
|
326
|
+
if (!text || matcher.isEcho(text)) {
|
|
327
|
+
await delay(300);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (!bestText || text.length > bestText.length) {
|
|
331
|
+
bestText = text;
|
|
332
|
+
stableCount = 0;
|
|
333
|
+
}
|
|
334
|
+
else if (text === bestText) {
|
|
335
|
+
stableCount += 1;
|
|
336
|
+
}
|
|
337
|
+
if (stableCount >= 2) {
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
await delay(300);
|
|
341
|
+
}
|
|
342
|
+
if (bestText) {
|
|
343
|
+
logger('Recovered assistant response after prompt echo during reattach');
|
|
344
|
+
return { ...answer, text: bestText };
|
|
345
|
+
}
|
|
346
|
+
return answer;
|
|
347
|
+
}
|
|
348
|
+
export function alignPromptEchoPair(answerText, answerMarkdown, matcher, logger, messages) {
|
|
349
|
+
if (!matcher) {
|
|
350
|
+
return { answerText, answerMarkdown, textEcho: false, markdownEcho: false, isEcho: false };
|
|
351
|
+
}
|
|
352
|
+
let textEcho = matcher.isEcho(answerText);
|
|
353
|
+
let markdownEcho = matcher.isEcho(answerMarkdown);
|
|
354
|
+
if (textEcho && !markdownEcho && answerMarkdown) {
|
|
355
|
+
if (logger && messages?.text) {
|
|
356
|
+
logger(messages.text);
|
|
357
|
+
}
|
|
358
|
+
answerText = answerMarkdown;
|
|
359
|
+
textEcho = false;
|
|
360
|
+
}
|
|
361
|
+
if (markdownEcho && !textEcho && answerText) {
|
|
362
|
+
if (logger && messages?.markdown) {
|
|
363
|
+
logger(messages.markdown);
|
|
364
|
+
}
|
|
365
|
+
answerMarkdown = answerText;
|
|
366
|
+
markdownEcho = false;
|
|
367
|
+
}
|
|
368
|
+
return {
|
|
369
|
+
answerText,
|
|
370
|
+
answerMarkdown,
|
|
371
|
+
textEcho,
|
|
372
|
+
markdownEcho,
|
|
373
|
+
isEcho: textEcho || markdownEcho,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
export function alignPromptEchoMarkdown(answerText, answerMarkdown, matcher, logger) {
|
|
377
|
+
const aligned = alignPromptEchoPair(answerText, answerMarkdown, matcher, logger, {
|
|
378
|
+
text: 'Aligned prompt-echo text to copied markdown during reattach',
|
|
379
|
+
markdown: 'Aligned prompt-echo markdown to response text during reattach',
|
|
380
|
+
});
|
|
381
|
+
return { answerText: aligned.answerText, answerMarkdown: aligned.answerMarkdown };
|
|
382
|
+
}
|
package/dist/src/browserMode.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { runBrowserMode, CHATGPT_URL, DEFAULT_MODEL_TARGET, parseDuration, normalizeChatgptUrl, isTemporaryChatUrl, } from './browser/index.js';
|
|
1
|
+
export { runBrowserMode, CHATGPT_URL, DEFAULT_MODEL_STRATEGY, DEFAULT_MODEL_TARGET, parseDuration, normalizeChatgptUrl, isTemporaryChatUrl, } from './browser/index.js';
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { CHATGPT_URL, DEFAULT_MODEL_TARGET, isTemporaryChatUrl, normalizeChatgptUrl, parseDuration } from '../browserMode.js';
|
|
3
|
+
import { CHATGPT_URL, DEFAULT_MODEL_STRATEGY, DEFAULT_MODEL_TARGET, isTemporaryChatUrl, normalizeChatgptUrl, parseDuration } from '../browserMode.js';
|
|
4
|
+
import { normalizeBrowserModelStrategy } from '../browser/modelStrategy.js';
|
|
4
5
|
import { getOracleHomeDir } from '../oracleHome.js';
|
|
5
6
|
const DEFAULT_BROWSER_TIMEOUT_MS = 1_200_000;
|
|
6
|
-
const DEFAULT_BROWSER_INPUT_TIMEOUT_MS =
|
|
7
|
+
const DEFAULT_BROWSER_INPUT_TIMEOUT_MS = 60_000;
|
|
7
8
|
const DEFAULT_CHROME_PROFILE = 'Default';
|
|
8
9
|
// Ordered array: most specific models first to ensure correct selection.
|
|
9
10
|
// The browser label is passed to the model picker which fuzzy-matches against ChatGPT's UI.
|
|
@@ -44,14 +45,18 @@ export async function buildBrowserConfig(options) {
|
|
|
44
45
|
const baseModel = options.model.toLowerCase();
|
|
45
46
|
const isChatGptModel = baseModel.startsWith('gpt-') && !baseModel.includes('codex');
|
|
46
47
|
const shouldUseOverride = !isChatGptModel && normalizedOverride.length > 0 && normalizedOverride !== baseModel;
|
|
48
|
+
const modelStrategy = normalizeBrowserModelStrategy(options.browserModelStrategy) ?? DEFAULT_MODEL_STRATEGY;
|
|
47
49
|
const cookieNames = parseCookieNames(options.browserCookieNames ?? process.env.ORACLE_BROWSER_COOKIE_NAMES);
|
|
48
|
-
|
|
50
|
+
let inline = await resolveInlineCookies({
|
|
49
51
|
inlineArg: options.browserInlineCookies,
|
|
50
52
|
inlineFileArg: options.browserInlineCookiesFile,
|
|
51
53
|
envPayload: process.env.ORACLE_BROWSER_COOKIES_JSON,
|
|
52
54
|
envFile: process.env.ORACLE_BROWSER_COOKIES_FILE,
|
|
53
55
|
cwd: process.cwd(),
|
|
54
56
|
});
|
|
57
|
+
if (inline?.source?.startsWith('home:') && options.browserNoCookieSync !== true) {
|
|
58
|
+
inline = undefined;
|
|
59
|
+
}
|
|
55
60
|
let remoteChrome;
|
|
56
61
|
if (options.remoteChrome) {
|
|
57
62
|
remoteChrome = parseRemoteChromeTarget(options.remoteChrome);
|
|
@@ -63,7 +68,7 @@ export async function buildBrowserConfig(options) {
|
|
|
63
68
|
: shouldUseOverride
|
|
64
69
|
? desiredModelOverride
|
|
65
70
|
: mapModelToBrowserLabel(options.model);
|
|
66
|
-
if (url && isTemporaryChatUrl(url) && /\bpro\b/i.test(desiredModel ?? '')) {
|
|
71
|
+
if (modelStrategy === 'select' && url && isTemporaryChatUrl(url) && /\bpro\b/i.test(desiredModel ?? '')) {
|
|
67
72
|
throw new Error('Temporary Chat mode does not expose Pro models in the ChatGPT model picker. ' +
|
|
68
73
|
'Remove "temporary-chat=true" from --chatgpt-url (or omit --chatgpt-url), or use a non-Pro model (e.g. --model gpt-5.2).');
|
|
69
74
|
}
|
|
@@ -86,6 +91,7 @@ export async function buildBrowserConfig(options) {
|
|
|
86
91
|
manualLogin: options.browserManualLogin ? true : undefined,
|
|
87
92
|
hideWindow: options.browserHideWindow ? true : undefined,
|
|
88
93
|
desiredModel,
|
|
94
|
+
modelStrategy,
|
|
89
95
|
debug: options.verbose ? true : undefined,
|
|
90
96
|
// Allow cookie failures by default so runs can continue without Chrome/Keychain secrets.
|
|
91
97
|
allowCookieErrors: options.browserAllowCookieErrors ?? true,
|