Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions core/src/background/agent-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ import { summarizeExtraction } from '@/lib/extraction';
import { ERROR_PAGE_DOM_HASH_PREFIX, assessPageHealth, describePageTransition, type RecoveryPage } from '@/lib/page-state';
import { parsePlanSteps, advancePlan, completePlan, planContext, markPlanStepFailed, shouldAdvancePlanAfterTool, isValidPlanStepCount, PLAN_MIN_STEPS, PLAN_MAX_STEPS } from '@/lib/planner';
import { decideRetry } from '@/lib/retry';
import { learnFromSuccess, getCookieHint, getSearchHint, getRecoveryHint } from '@/lib/semantic-memory';
import { learnFromSuccess, getCookieHint, getSearchHint } from '@/lib/semantic-memory';
import { learnFromTask, memoryContext } from '@/lib/memory';
import { loadConversation, renderConversationContext } from '@/lib/conversation';
import { classifyTaskNeural, skillPrompts } from '@/lib/skills';
Expand Down Expand Up @@ -1742,12 +1742,6 @@ export async function runTask(task: AgentTask, deps: AgentDeps): Promise<AgentTa
content: `[REVIEW] ✗ retry #${stepRetryCount}: ${retry.strategy} — ${step.result?.error ?? 'action failed'}`,
});

// ── Learn recovery if retry succeeds later ──
const recoveryHint = await getRecoveryHint(snapshot, toolCall.name);
if (recoveryHint) {
history.push({ role: 'user', content: `[REVIEW] Hint: ${recoveryHint}` });
}

step.finishedAt = Date.now();
step.timings = finalizeTimings(stepStart, { snapshotMs, screenshotMs, llmMs, actionMs });
await saveStep(task.id, step);
Expand Down
36 changes: 0 additions & 36 deletions core/src/background/cdp-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -810,39 +810,3 @@ export async function applyStealthPatches(target: Debuggee): Promise<void> {
await send(target, 'Runtime.evaluate', { expression: stealthScript });
} catch {}
}

/**
* Dispatches a trusted CDP Press and Hold sequence with humanized micro-tremor.
*/
export async function cdpPressAndHold(target: Debuggee, x: number, y: number, durationMs = 6500): Promise<void> {
await send(target, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
await send(target, 'Input.dispatchMouseEvent', {
type: 'mousePressed',
x,
y,
button: 'left',
clickCount: 1,
});

const startTime = Date.now();
while (Date.now() - startTime < durationMs) {
await sleep(75);
const jitterX = x + (Math.random() - 0.5) * 2;
const jitterY = y + (Math.random() - 0.5) * 2;
await send(target, 'Input.dispatchMouseEvent', {
type: 'mouseMoved',
x: jitterX,
y: jitterY,
button: 'left',
}).catch(() => {});
}

await send(target, 'Input.dispatchMouseEvent', {
type: 'mouseReleased',
x,
y,
button: 'left',
clickCount: 1,
});
await sleep(100);
}
18 changes: 1 addition & 17 deletions core/src/lib/action-cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { db } from './storage';
import { fastHash } from './hash';
import type { A11ySnapshot, ToolCall } from './types';
import type { ToolCall } from './types';

export interface CachedAction {
key: string;
Expand Down Expand Up @@ -66,19 +66,3 @@ export async function clearCache(): Promise<number> {
export async function invalidate(key: string): Promise<void> {
await db.actionCache.delete(key);
}

export function summarizeCall(call: ToolCall): string {
const parts: string[] = [call.name];
const a = call.arguments;
if (a.ref) parts.push(`ref=${a.ref}`);
if (a.text) parts.push(`text="${String(a.text).slice(0, 24)}"`);
if (a.url) parts.push(`url=${a.url}`);
if (a.value) parts.push(`value=${a.value}`);
if (a.key) parts.push(`key=${a.key}`);
if (a.modifiers) parts.push(`modifiers=${a.modifiers}`);
return parts.join(' ');
}

export function snapshotSignature(s: A11ySnapshot): string {
return s.domHash;
}
68 changes: 0 additions & 68 deletions core/src/lib/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,6 @@ export function buildTrace(task: AgentTask): TraceFile {
return { version: 1, exportedAt: Date.now(), task: maskTaskForLog(task) };
}

export function downloadJson(name: string, data: unknown): void {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}

// ── PDF Export ──

function escapeHtml(text: string): string {
Expand Down Expand Up @@ -275,62 +263,6 @@ export function buildPdfHtml(task: AgentTask): string {
</html>`;
}

export function downloadPdfViaPrint(task: AgentTask): void {
const html = buildPdfHtml(task);

const iframe = document.createElement('iframe');
iframe.style.cssText = 'position:fixed;top:-9999px;left:-9999px;width:794px;height:1123px;border:none;';
document.body.appendChild(iframe);

const doc = iframe.contentDocument ?? iframe.contentWindow?.document;
if (!doc) {
iframe.remove();
// Fallback: download as HTML
const blob = new Blob([html], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `report-${task.id.slice(0, 8)}.html`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
return;
}

doc.open();
doc.write(html);
doc.close();

// Keep print synchronous with the button click. Chrome only permits print dialogs
// initiated during a user gesture; scheduling this even one tick later causes the
// dialog to be silently blocked from the extension side panel.
const cleanup = () => iframe.remove();
iframe.contentWindow?.addEventListener('afterprint', cleanup, { once: true });

try {
iframe.contentWindow?.focus();
iframe.contentWindow?.print();
} catch {
// If printing is unavailable, provide the rendered report as a usable fallback.
cleanup();
const blob = new Blob([html], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `report-${task.id.slice(0, 8)}.html`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
return;
}

// Some browsers do not dispatch afterprint for an iframe. Keep it alive long
// enough for the print preview, then remove it without leaving hidden frames.
setTimeout(cleanup, 30_000);
}

function printableValue(value: unknown): string {
if (typeof value === 'string') return value;
try {
Expand Down
9 changes: 0 additions & 9 deletions core/src/lib/hash.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
export async function sha256Hex(input: string): Promise<string> {
const buf = new TextEncoder().encode(input);
const digest = await crypto.subtle.digest('SHA-256', buf);
const bytes = new Uint8Array(digest);
let out = '';
for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, '0');
return out;
}

export function fastHash(input: string): string {
let h1 = 0xdeadbeef ^ 0;
let h2 = 0x41c6ce57 ^ 0;
Expand Down
10 changes: 0 additions & 10 deletions core/src/lib/messaging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,6 @@ function withReplyTimeout(pending: Promise<CSResponse>, msg: CSMessage): Promise
});
}

export function onSWEvent(cb: (evt: SWEvent) => void): () => void {
const handler = (msg: unknown) => {
if (msg && typeof msg === 'object' && 'kind' in (msg as Record<string, unknown>)) {
cb(msg as SWEvent);
}
};
chrome.runtime.onMessage.addListener(handler);
return () => chrome.runtime.onMessage.removeListener(handler);
}

export function broadcastEvent(evt: SWEvent): void {
for (const listener of localEventListeners) {
try { listener(evt); } catch {}
Expand Down
32 changes: 1 addition & 31 deletions core/src/lib/orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type {
TabContext,
} from './orchestrator-types';
import type { AgentPlan, SkillId } from './types';
import { classifyTask, getSkill } from './skills';
import { classifyTask } from './skills';

// ── Tab Manager ───────────────────────────────────────────────────────

Expand Down Expand Up @@ -303,10 +303,6 @@ export function allSubtasksComplete(plan: OrchestrationPlan): boolean {
);
}

export function anySubtasksPending(plan: OrchestrationPlan): boolean {
return plan.subtasks.some((s) => s.status === 'pending');
}

export function nextPendingSubtask(plan: OrchestrationPlan): Subtask | undefined {
return plan.subtasks.find((s) => s.status === 'pending');
}
Expand Down Expand Up @@ -365,10 +361,6 @@ export function advanceOrchPlan(plan: OrchestrationPlan, toolName: string): void
plan.updatedAt = Date.now();
}

export function getCurrentSubtask(plan: OrchestrationPlan): Subtask | undefined {
return plan.subtasks.find((s) => s.status === 'running');
}

export function markSubtaskDone(plan: OrchestrationPlan, subtaskId: string): void {
const st = findSubtask(plan, subtaskId);
if (st) {
Expand All @@ -388,30 +380,8 @@ export function markSubtaskFailed(plan: OrchestrationPlan, subtaskId: string, er
}
}

export function getSubtaskResult(plan: OrchestrationPlan, index: number): string | undefined {
const st = plan.subtasks.find((s) => s.index === index);
return st?.result;
}

// ── Sub-task skill injection ──────────────────────────────────────────

export function skillPromptForSubtask(subtask: Subtask): string {
const prompts: string[] = [];

// Get the skill's own prompt
if (subtask.skillId) {
const skill = getSkill(subtask.skillId);
if (skill) {
prompts.push(skill.prompt);
}
}

// Inject context from completed dependent subtasks
prompts.push(`SUBTASK: ${subtask.description}`);

return prompts.join('\n\n');
}

// ── Utils ─────────────────────────────────────────────────────────────

function sleep(ms: number): Promise<void> {
Expand Down
5 changes: 0 additions & 5 deletions core/src/lib/partial-work.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,6 @@ export function buildTraceQuestionPrompt(goal: string, work: CollectedWork, ques
].join('\n');
}

/** Steps whose results were summarized, for marking the synthetic step. */
export function isInterrupted(status: AgentTask['status']): boolean {
return status === 'stopped';
}

export type { AgentStep };

/** Evidence below this is too thin for the question to be worth asking. */
Expand Down
28 changes: 0 additions & 28 deletions core/src/lib/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,31 +93,3 @@ export function decideRetry(
};
}
}

export function retryPromptForStep(
retryCount: number,
maxRetries: number,
strategy: RetryStrategy,
originalError: string,
): string {
const header = `[RETRY ${retryCount}/${maxRetries}] Previous action failed: ${originalError}`;

switch (strategy) {
case 'close_popup':
return `${header}\nA popup/dialog was detected on the page. Find the close button and click it.`;
case 'different_selector':
return `${header}\nElement changed or not found. Find a similar element by name/text.`;
case 'wait_and_retry':
return `${header}\nPage is loading. Wait longer and take a new snapshot.`;
case 'scroll_to_element':
return `${header}\nScroll the page — the element may be outside the visible area.`;
case 'coordinates_click':
return `${header}\nSystem will perform a coordinate click via CDP.`;
case 'refresh_page':
return `${header}\nRefresh the page and retry the step.`;
case 'try_alternative':
return `${header}\nFind an alternative way to complete the task.`;
default:
return `${header}\nWait for the page to settle, then retry. If it fails again, try a different element.`;
}
}
43 changes: 1 addition & 42 deletions core/src/lib/semantic-memory.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { db } from './storage';
import { urlPattern } from './action-cache';
import type { A11ySnapshot, RecoveryMemory, SitePattern, ToolCall } from './types';
import type { A11ySnapshot, SitePattern, ToolCall } from './types';
import { parseBatchActions } from './batch-actions';

export async function getSitePattern(snapshot: A11ySnapshot): Promise<SitePattern | undefined> {
Expand Down Expand Up @@ -58,39 +58,6 @@ export async function learnFromSuccess(
await db.sitePatterns.put(sitePattern);
}

export async function learnRecovery(
snapshot: A11ySnapshot,
failedAction: string,
successAction: string,
recoveryHint: string,
): Promise<void> {
const pat = urlPattern(snapshot.url);
const existing = await db.recoveryMemory.where({ urlPattern: pat, failedAction }).first();

const record: RecoveryMemory = {
urlPattern: pat,
failedAction,
successAction,
recoveryHint,
hitCount: (existing?.hitCount ?? 0) + 1,
};

await db.recoveryMemory.put(record);
}

export async function getRecoveryHint(
snapshot: A11ySnapshot,
failedAction: string,
): Promise<string | undefined> {
const pat = urlPattern(snapshot.url);
const record = await db.recoveryMemory.where({ urlPattern: pat, failedAction }).first();
if (!record) return undefined;

record.hitCount += 1;
await db.recoveryMemory.put(record);
return record.recoveryHint;
}

export async function getCookieHint(snapshot: A11ySnapshot): Promise<string | undefined> {
const pattern = await getSitePattern(snapshot);
if (pattern?.cookieAcceptSelector) {
Expand All @@ -107,14 +74,6 @@ export async function getSearchHint(snapshot: A11ySnapshot): Promise<string | un
return undefined;
}

export async function clearMemory(): Promise<number> {
const s = await db.sitePatterns.count();
const r = await db.recoveryMemory.count();
await db.sitePatterns.clear();
await db.recoveryMemory.clear();
return s + r;
}

function isSearchInput(name: string, role: string): boolean {
const s = name;
return (role === 'textbox' || role === 'searchbox' || role === 'combobox') && (
Expand Down
1 change: 1 addition & 0 deletions core/src/lib/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export class AgentDB extends Dexie {
steps!: Table<AgentStep & { taskId: string }, string>;
actionCache!: Table<CachedAction, string>;
sitePatterns!: Table<SitePattern, string>;
/** Never written; kept so existing databases keep a valid schema without a migration. */
recoveryMemory!: Table<RecoveryMemory, string>;

constructor() {
Expand Down
Loading