@steipete/oracle 0.7.5 → 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.
@@ -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 { delay } from './utils.js';
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));
@@ -54,11 +37,37 @@ export async function resumeBrowserSession(runtime, config, logger, deps = {}) {
54
37
  if (DOM && typeof DOM.enable === 'function') {
55
38
  await DOM.enable();
56
39
  }
40
+ const ensureConversationOpen = async () => {
41
+ const { result } = await Runtime.evaluate({ expression: 'location.href', returnByValue: true });
42
+ const href = typeof result?.value === 'string' ? result.value : '';
43
+ if (href.includes('/c/')) {
44
+ const currentId = extractConversationIdFromUrl(href);
45
+ if (!runtime.conversationId || (currentId && currentId === runtime.conversationId)) {
46
+ return;
47
+ }
48
+ }
49
+ const opened = await openConversationFromSidebarWithRetry(Runtime, {
50
+ conversationId: runtime.conversationId ?? extractConversationIdFromUrl(runtime.tabUrl ?? ''),
51
+ preferProjects: true,
52
+ promptPreview: deps.promptPreview,
53
+ }, 15_000);
54
+ if (!opened) {
55
+ throw new Error('Unable to locate prior ChatGPT conversation in sidebar.');
56
+ }
57
+ await waitForLocationChange(Runtime, 15_000);
58
+ };
57
59
  const waitForResponse = deps.waitForAssistantResponse ?? waitForAssistantResponse;
58
60
  const captureMarkdown = deps.captureAssistantMarkdown ?? captureAssistantMarkdown;
59
61
  const timeoutMs = config?.timeoutMs ?? 120_000;
60
- const answer = await waitForResponse(Runtime, timeoutMs, logger);
61
- const markdown = (await captureMarkdown(Runtime, answer.meta, logger)) ?? answer.text;
62
+ const pingTimeoutMs = Math.min(5_000, Math.max(1_500, Math.floor(timeoutMs * 0.05)));
63
+ await withTimeout(Runtime.evaluate({ expression: '1+1', returnByValue: true }), pingTimeoutMs, 'Reattach target did not respond');
64
+ await ensureConversationOpen();
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);
62
71
  if (client && typeof client.close === 'function') {
63
72
  try {
64
73
  await client.close();
@@ -67,7 +76,7 @@ export async function resumeBrowserSession(runtime, config, logger, deps = {}) {
67
76
  // ignore
68
77
  }
69
78
  }
70
- return { answerText: answer.text, answerMarkdown: markdown };
79
+ return { answerText: aligned.answerText, answerMarkdown: aligned.answerMarkdown };
71
80
  }
72
81
  catch (error) {
73
82
  const message = error instanceof Error ? error.message : String(error);
@@ -122,10 +131,12 @@ async function resumeBrowserSessionViaNewChrome(runtime, config, logger, deps) {
122
131
  await ensurePromptReady(Runtime, resolved.inputTimeoutMs, logger);
123
132
  }
124
133
  else {
125
- const opened = await openConversationFromSidebar(Runtime, {
134
+ const opened = await openConversationFromSidebarWithRetry(Runtime, {
126
135
  conversationId: runtime.conversationId ?? extractConversationIdFromUrl(runtime.tabUrl ?? ''),
127
- preferProjects: resolved.url !== CHATGPT_URL,
128
- });
136
+ preferProjects: resolved.url !== CHATGPT_URL ||
137
+ Boolean(runtime.tabUrl && (/\/g\//.test(runtime.tabUrl) || runtime.tabUrl.includes('/project'))),
138
+ promptPreview: deps.promptPreview,
139
+ }, 15_000);
129
140
  if (!opened) {
130
141
  throw new Error('Unable to locate prior ChatGPT conversation in sidebar.');
131
142
  }
@@ -134,8 +145,12 @@ async function resumeBrowserSessionViaNewChrome(runtime, config, logger, deps) {
134
145
  const waitForResponse = deps.waitForAssistantResponse ?? waitForAssistantResponse;
135
146
  const captureMarkdown = deps.captureAssistantMarkdown ?? captureAssistantMarkdown;
136
147
  const timeoutMs = resolved.timeoutMs ?? 120_000;
137
- const answer = await waitForResponse(Runtime, timeoutMs, logger);
138
- const markdown = (await captureMarkdown(Runtime, answer.meta, logger)) ?? answer.text;
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);
139
154
  if (client && typeof client.close === 'function') {
140
155
  try {
141
156
  await client.close();
@@ -153,77 +168,7 @@ async function resumeBrowserSessionViaNewChrome(runtime, config, logger, deps) {
153
168
  }
154
169
  await rm(userDataDir, { recursive: true, force: true }).catch(() => undefined);
155
170
  }
156
- return { answerText: answer.text, answerMarkdown: markdown };
157
- }
158
- function extractConversationIdFromUrl(url) {
159
- if (!url)
160
- return undefined;
161
- const match = url.match(/\/c\/([a-zA-Z0-9-]+)/);
162
- return match?.[1];
163
- }
164
- function buildConversationUrl(runtime, baseUrl) {
165
- if (runtime.tabUrl) {
166
- return runtime.tabUrl;
167
- }
168
- const conversationId = runtime.conversationId;
169
- if (!conversationId) {
170
- return null;
171
- }
172
- try {
173
- const base = new URL(baseUrl);
174
- return `${base.origin}/c/${conversationId}`;
175
- }
176
- catch {
177
- return null;
178
- }
179
- }
180
- async function openConversationFromSidebar(Runtime, options) {
181
- const response = await Runtime.evaluate({
182
- expression: `(() => {
183
- const conversationId = ${JSON.stringify(options.conversationId ?? null)};
184
- const preferProjects = ${JSON.stringify(Boolean(options.preferProjects))};
185
- const nav = document.querySelector('nav') || document.querySelector('aside') || document.body;
186
- if (preferProjects) {
187
- const projectLink = Array.from(nav.querySelectorAll('a,button'))
188
- .find((el) => (el.textContent || '').trim().toLowerCase() === 'projects');
189
- if (projectLink) {
190
- projectLink.click();
191
- }
192
- }
193
- const links = Array.from(nav.querySelectorAll('a[href]'))
194
- .filter((el) => el instanceof HTMLAnchorElement)
195
- .map((el) => el);
196
- const convoLinks = links.filter((el) => el.href.includes('/c/'));
197
- let target = null;
198
- if (conversationId) {
199
- target = convoLinks.find((el) => el.href.includes('/c/' + conversationId));
200
- }
201
- if (!target && convoLinks.length > 0) {
202
- target = convoLinks[0];
203
- }
204
- if (target) {
205
- target.scrollIntoView({ block: 'center' });
206
- target.click();
207
- return { ok: true, href: target.href, count: convoLinks.length };
208
- }
209
- return { ok: false, count: convoLinks.length };
210
- })()`,
211
- returnByValue: true,
212
- });
213
- return Boolean(response.result?.value?.ok);
214
- }
215
- async function waitForLocationChange(Runtime, timeoutMs) {
216
- const start = Date.now();
217
- let lastHref = '';
218
- while (Date.now() - start < timeoutMs) {
219
- const { result } = await Runtime.evaluate({ expression: 'location.href', returnByValue: true });
220
- const href = typeof result?.value === 'string' ? result.value : '';
221
- if (lastHref && href !== lastHref) {
222
- return;
223
- }
224
- lastHref = href;
225
- await delay(200);
226
- }
171
+ return { answerText: aligned.answerText, answerMarkdown: aligned.answerMarkdown };
227
172
  }
228
173
  // biome-ignore lint/style/useNamingConvention: test-only export used in vitest suite
229
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
+ }
@@ -1,6 +1,6 @@
1
1
  import chalk from 'chalk';
2
- import { formatElapsed } from '../oracle.js';
3
2
  import { formatTokenCount } from '../oracle/runUtils.js';
3
+ import { formatFinishLine } from '../oracle/finishLine.js';
4
4
  import { runBrowserMode } from '../browserMode.js';
5
5
  import { assembleBrowserPrompt } from './prompt.js';
6
6
  import { BrowserAutomationError } from '../oracle/errors.js';
@@ -88,12 +88,22 @@ export async function runBrowserSessionExecution({ runOptions, browserConfig, cw
88
88
  ]
89
89
  .map((value) => formatTokenCount(value))
90
90
  .join('/');
91
- const tokensLabel = runOptions.verbose ? 'tokens (input/output/reasoning/total)' : 'tok(i/o/r/t)';
92
- const statsParts = [`${runOptions.model}[browser]`, `${tokensLabel}=${tokensDisplay}`];
93
- if (runOptions.file && runOptions.file.length > 0) {
94
- statsParts.push(`files=${runOptions.file.length}`);
91
+ const tokensPart = (() => {
92
+ const parts = tokensDisplay.split('/');
93
+ if (parts.length !== 4)
94
+ return tokensDisplay;
95
+ return `↑${parts[0]} ↓${parts[1]} ↻${parts[2]} Δ${parts[3]}`;
96
+ })();
97
+ const { line1, line2 } = formatFinishLine({
98
+ elapsedMs: browserResult.tookMs,
99
+ model: `${runOptions.model}[browser]`,
100
+ tokensPart,
101
+ detailParts: [runOptions.file && runOptions.file.length > 0 ? `files=${runOptions.file.length}` : null],
102
+ });
103
+ log(chalk.blue(line1));
104
+ if (line2) {
105
+ log(chalk.dim(line2));
95
106
  }
96
- log(chalk.blue(`Finished in ${formatElapsed(browserResult.tookMs)} (${statsParts.join(' | ')})`));
97
107
  return {
98
108
  usage,
99
109
  elapsedMs: browserResult.tookMs,
@@ -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 = 30_000;
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
- const inline = await resolveInlineCookies({
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,
@@ -42,4 +42,7 @@ export function applyBrowserDefaultsFromConfig(options, config, getSource) {
42
42
  if (isUnset('browserKeepBrowser') && browser.keepBrowser !== undefined) {
43
43
  options.browserKeepBrowser = browser.keepBrowser;
44
44
  }
45
+ if (isUnset('browserModelStrategy') && browser.modelStrategy !== undefined) {
46
+ options.browserModelStrategy = browser.modelStrategy;
47
+ }
45
48
  }