Open-source AI browser agent for Chrome and Firefox (monorepo) π§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Fix Compact WordPress API guidance and REST route loop detection
Emre Sokulluc65729786f96
diff --git a/src/chrome/src/agent/loop-bucket.js b/src/chrome/src/agent/loop-bucket.jsindex 65023ebca..ba382c928 100644--- a/src/chrome/src/agent/loop-bucket.js+++ b/src/chrome/src/agent/loop-bucket.js@@ -79,6 +79,8 @@ export const URL_FAMILY_TOOLS = new Set([* git/trees/, /repos/o/r/git/refs/, /o/r/blob/<ref>/, /o/r/raw/<ref>/,* /o/r/edit/<ref>/, /o/r/tree/<ref>/, /o/r/commits/<ref>/,* /o/r/commit/<ref>/.+ * - WordPress query-form REST URLs keep the installation path and decoded+ * rest_route. Other query parameters do not change resource identity.* - For everything else we keep the lowercased hostname and the last* three path segments. That's a backstop, not authoritative β it* trades some over-bucketing (different files in the same /a/b/foo/@@ -106,6 +108,15 @@ export function resourceBucket(rawUrl) {const ghBucket = _ghResourceBucket(rawHost, rawPath);if (ghBucket !== null) return `github.com::${ghBucket}`;+ // Without pretty permalinks, every WordPress REST endpoint shares a path;+ // dropping rest_route makes normal discovery look like repeated fetches.+ // URLSearchParams decodes equivalent route encodings. Ignore trailing+ // slashes and unrelated query variations so real repeats still collide.+ const restRoute = u.searchParams.get('rest_route');+ if (restRoute?.startsWith('/')) {+ return `${rawHost}::${rawPath}|rest_route:${restRoute.replace(/\/+$/, '') || '/'}`;+ }+// Non-GitHub: keep the lowercased hostname and the last 3 path segments.// Loose by design β trades some over-bucketing (siblings in the same// /a/b/foo/ directory may collide) for catching cross-host thrashing.diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.jsindex 4a4232c8d..27ed60b39 100644--- a/src/chrome/src/agent/tools.js+++ b/src/chrome/src/agent/tools.js@@ -2328,7 +2328,7 @@ RULES:5. Click by ref_id: click_ax({ref_id:"ref_N"}). For native checkboxes, use set_checked({ref_id:"ref_N", checked:true|false}) instead of toggling. Fallback: click({text:"Submit"}).6. When done, call done({summary:"...", outcome:"success"}). Verify success first.7. If stuck after 2 attempts, try a different approach. Never repeat the same failing action 3 times.-8. Interact through the visible UI. Do not call APIs directly.+8. Use the visible UI by default. For WordPress posts, pages, REST-enabled custom types and their taxonomy, prefer the API when mutations are authorized, required fields and session are verified, and Strict secret handling is off; follow the WordPress adapter. Without API authorization, do not send POST/PUT/PATCH/DELETE. If this route is unavailable, use an existing editor.9. For long tasks, use scratchpad_write to remember facts between steps. For repeated item/action tasks, use progress_update/progress_read and close all pending/acted rows before done.10. For loop tasks, keep using tools in this run; never say "I'll continue" unless you are actually making more tool calls.11. You cannot schedule, sleep, set timers, or check back later in compact mode. If something must wait for an external event, call done({summary:"...", outcome:"partial"}) with the current state and ask the user to re-invoke you.diff --git a/src/firefox/src/agent/loop-bucket.js b/src/firefox/src/agent/loop-bucket.jsindex 65023ebca..ba382c928 100644--- a/src/firefox/src/agent/loop-bucket.js+++ b/src/firefox/src/agent/loop-bucket.js@@ -79,6 +79,8 @@ export const URL_FAMILY_TOOLS = new Set([* git/trees/, /repos/o/r/git/refs/, /o/r/blob/<ref>/, /o/r/raw/<ref>/,* /o/r/edit/<ref>/, /o/r/tree/<ref>/, /o/r/commits/<ref>/,* /o/r/commit/<ref>/.+ * - WordPress query-form REST URLs keep the installation path and decoded+ * rest_route. Other query parameters do not change resource identity.* - For everything else we keep the lowercased hostname and the last* three path segments. That's a backstop, not authoritative β it* trades some over-bucketing (different files in the same /a/b/foo/@@ -106,6 +108,15 @@ export function resourceBucket(rawUrl) {const ghBucket = _ghResourceBucket(rawHost, rawPath);if (ghBucket !== null) return `github.com::${ghBucket}`;+ // Without pretty permalinks, every WordPress REST endpoint shares a path;+ // dropping rest_route makes normal discovery look like repeated fetches.+ // URLSearchParams decodes equivalent route encodings. Ignore trailing+ // slashes and unrelated query variations so real repeats still collide.+ const restRoute = u.searchParams.get('rest_route');+ if (restRoute?.startsWith('/')) {+ return `${rawHost}::${rawPath}|rest_route:${restRoute.replace(/\/+$/, '') || '/'}`;+ }+// Non-GitHub: keep the lowercased hostname and the last 3 path segments.// Loose by design β trades some over-bucketing (siblings in the same// /a/b/foo/ directory may collide) for catching cross-host thrashing.diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.jsindex ae97f4430..896fa1ba0 100644--- a/src/firefox/src/agent/tools.js+++ b/src/firefox/src/agent/tools.js@@ -1802,7 +1802,7 @@ RULES:5. Fill forms one field at a time. Prefer set_field({ref_id, text}) for text fields; it focuses, clears, types, and can submit.6. Click by ref_id with click_ax({ref_id:"ref_N"}). For native checkboxes, use set_checked({ref_id:"ref_N", checked:true|false}) instead of toggling. Fallback to click({text:"Submit"}) when no ref_id works.7. For long tasks, use scratchpad_write to remember facts between steps. For repeated item/action tasks, use progress_update/progress_read and close all pending/acted rows before done.-8. Interact through the visible UI. Do not call APIs directly for actions that create, modify, delete, send, submit, buy, transfer, post, or publish.+8. Use the visible UI by default. For WordPress posts, pages, REST-enabled custom types and their taxonomy, prefer the API when mutations are authorized, required fields and session are verified, and Strict secret handling is off; follow the WordPress adapter. Without API authorization, do not send POST/PUT/PATCH/DELETE. If this route is unavailable, use an existing editor.9. If stuck after 2 attempts, try a different tool or route. Never repeat the same failing action 3 times.10. For loop tasks, keep using tools in this run; never say "I'll continue" unless you are actually making more tool calls.11. You cannot schedule, sleep, set timers, or check back later in compact mode. If something must wait for an external event, call done({summary:"...", outcome:"partial"}) with the current state and ask the user to re-invoke you.diff --git a/test/run.js b/test/run.jsindex a8cce1e0a..51257a131 100644--- a/test/run.js+++ b/test/run.js@@ -9461,6 +9461,20 @@ test('WordPress API and editor guidance reaches every tier on root and subdirectassert.match(messages[0].content, /If API is unsuitable or declined/);assert.match(messages[0].content, /post_type=page&classic-editor/);assert.equal(agent._skillLoaderDefinition('act', tier), null, 'hint must work without installed skills');+ if (tier === 'compact') {+ for (const allowed of [false, true]) {+ agent.setApiMutationsAllowed(4974, allowed);+ const prompt = agent._buildSystemPrompt('act', 4974);+ const apiRule = prompt.split('\n').find(line => line.startsWith('8.'));+ assert.match(apiRule, /WordPress.*prefer the API/);+ assert.match(apiRule, /mutations are authorized/);+ assert.match(apiRule, /fields.*session.*verified/);+ assert.match(apiRule, /Strict secret handling is off/);+ assert.match(apiRule, /Without API authorization.*POST\/PUT\/PATCH\/DELETE/);+ assert.doesNotMatch(prompt, /Do not call APIs directly/);+ assert.equal(agent.isApiMutationsAllowed(4974), allowed, 'prompt construction changed API permission');+ }+ }}const plan = buildMessages({ role: 'user', content: 'Publish this WordPress page' }, url, 'WordPress', '', { allowApi: true });assert.match(plan[0].content, /prefer the API first/);@@ -22896,6 +22910,75 @@ test('non-GitHub hosts use last-3-segments backstop', () => {);});+test('WordPress rest_route buckets preserve route and installation identity without cache-query bypasses', () => {+ for (const bucket of [resourceBucket, resourceBucketFx]) {+ const item = 'https://example.com/blog/?rest_route=/wp/v2/posts/42';+ for (const equivalent of [+ 'https://example.com/blog/?rest_route=%2Fwp%2Fv2%2Fposts%2F42',+ 'https://example.com/blog/?rest_route=/wp/v2/posts/42/&context=edit',+ 'https://example.com/blog/?cache=2&rest_route=/wp/v2/posts/42',+ ]) assert.equal(bucket(item), bucket(equivalent), 'same REST item must keep one loop identity');+ for (const distinct of [+ 'https://example.com/blog/?rest_route=/wp/v2/posts/43',+ 'https://example.com/blog/?rest_route=/wp/v2/users/me',+ 'https://example.com/blog/?rest_route=/custom/v2/posts/42',+ 'https://example.com/other/?rest_route=/wp/v2/posts/42',+ 'https://example.com/blog/',+ ]) assert.notEqual(bucket(item), bucket(distinct), 'different REST resources must not collide');+ assert.notEqual(bucket('https://example.com/a/shared/path/site/?rest_route=/wp/v2/types'), bucket('https://example.com/b/shared/path/site/?rest_route=/wp/v2/types'), 'installation prefixes must survive');+ assert.equal(bucket('https://example.com/?rest_route=/'), bucket('https://example.com/?cache=1&rest_route=%2F'));+ for (const invalid of ['', 'not-a-route']) {+ assert.equal(bucket(`https://example.com/file.txt?rest_route=${invalid}`), bucket('https://example.com/file.txt'));+ }+ }+});++test('WordPress query-form discovery passes the Agent loop guard while repeated resources still warn', async () => {+ const savedFetch = globalThis.fetch;+ const savedChrome = globalThis.chrome, savedBrowser = globalThis.browser;+ try {+ globalThis.chrome = globalThis.browser = { tabs: { get: async () => ({ url: 'https://example.com/blog/wp-admin/' }) } };+ for (const [label, AgentClass, fetchUrl] of [['chrome', AgentCh, fetchUrlCh], ['firefox', AgentFx, fetchUrlFx]]) {+ let dispatched = 0;+ globalThis.fetch = async (url, init) => {+ dispatched++;+ assert.equal(init.credentials, 'include');+ if (new URL(url).searchParams.get('action') === 'rest-nonce') return new Response('test-nonce', { headers: { 'Content-Type': 'text/html' } });+ return new Response(JSON.stringify({ route: new URL(url).searchParams.get('rest_route') }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ };+ const discovery = [+ 'https://example.com/blog/?rest_route=/',+ 'https://example.com/blog/wp-admin/admin-ajax.php?action=rest-nonce',+ ...['users/me', 'types/post', 'taxonomies', 'categories', 'tags', 'posts/42'].map(route => `https://example.com/blog/?rest_route=/wp/v2/${route}&context=edit`),+ ];+ const repeats = [+ 'https://example.com/blog/?rest_route=/wp/v2/posts/42',+ 'https://example.com/blog/?rest_route=%2Fwp%2Fv2%2Fposts%2F42',+ 'https://example.com/blog/?cache=3&rest_route=/wp/v2/posts/42/&context=edit',+ ];+ for (const [urls, expectLoop] of [[discovery, false], [repeats, true]]) {+ const agent = new AgentClass({ getVisionProvider: async () => null });+ const tabId = 4981;+ agent.conversationModes.set(tabId, 'act');+ agent._ensureGateSetting = async () => {};+ agent._skipPermissionGate = true;+ agent.executeTool = async (_tabId, name, args) => {+ assert.equal(name, 'fetch_url');+ return fetchUrl(args.url, args, { tabId });+ };+ const messages = [];+ for (const [step, url] of urls.entries()) {+ await agent._executeToolBatch(tabId, [{+ id: `wp_read_${step}`, function: { name: 'fetch_url', arguments: JSON.stringify({ url, method: 'GET' }) },+ }], messages, () => {}, { supportsVision: false }, '', new Set(['fetch_url']), step + 1);+ }+ assert.equal(messages.some(message => /LOOP DETECTED/.test(message.content)), expectLoop, `${label}: model-facing loop guidance`);+ }+ assert.equal(dispatched, discovery.length + repeats.length, `${label}: expected reads were skipped`);+ }+ } finally { globalThis.fetch = savedFetch; globalThis.chrome = savedChrome; globalThis.browser = savedBrowser; }+});+test('GitHub gist + codeload also normalize to github.com', () => {const a = resourceBucket('https://gist.github.com/user/abc123/raw/file.txt');const b = resourceBucket('https://codeload.github.com/owner/repo/zip/refs/heads/main');