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(guard): require messaging authorization for recipient consent and preserve role negation
Emre Sokullu5f32449f02bb
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 9002944d5..bf5cd18f8 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -17848,14 +17848,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}// Retain what the page actually showed only when the plan already permits- // messaging. The block below tells the model to ask the user who the- // message is for, and that answer has to be matched against real observed- // identities. A read-only plan (requiresSubmission=false or- // requiresStateChange=false) must never stage recipient consent: an answer- // to a recipient clarify must not elevate a read-only plan into a sendable one.+ // messaging and has pre-existing messaging authorization. The block below+ // tells the model to ask the user who the message is for, and that answer+ // has to be matched against real observed identities. A read-only plan+ // (requiresSubmission=false or requiresStateChange=false) or an unrelated+ // consequential submission plan (guard.messaging=null) must never stage+ // recipient consent: an answer to a recipient clarify must not elevate an+ // unauthorized plan into a sendable one.if (guard) {+ const messagingAuthorized = !!normalizeMessageTarget(guard.messaging);const messagingPermitted = guard.requiresSubmission === true- && guard.requiresStateChange === true;+ && guard.requiresStateChange === true+ && messagingAuthorized;const observedRecipientCandidates = messagingPermitted? this._messageRecipientCandidates(probe): [];@@ -17864,11 +17868,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d: null;// Offered to the next clarify only. The model chooses what it asks, so a// pending authorization must not survive into an unrelated question.- // Staged only when the plan already permits messaging.- // Associate with an explicit recipient-change clarification when a target- // was already authorized, or a recipient clarification when missing.+ // Staged only when the plan already permits messaging and has pre-existing+ // messaging authorization.+ // Associate with an explicit recipient-change clarification when a named target+ // was already authorized, or a recipient clarification for active conversations.guard.pendingRecipientAuthorization = messagingPermitted && observedRecipientCandidates.length > 0- ? (target ? 'recipient_change' : true)+ ? (target?.target_kind === 'named' ? 'recipient_change' : true): false;}@@ -17885,7 +17890,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d? 'Message action blocked: WebBrain could not conclusively resolve the target control and active composer. Re-read the page and retry with an exact visible control or fresh ref_id.': target? 'Message send blocked: the active conversation does not exactly match the recipient authorized by the user. Select the intended conversation, re-read its visible header, then retry the send action.'- : (guard?.requiresSubmission === false || guard?.requiresStateChange === false+ : (guard?.requiresSubmission === false || guard?.requiresStateChange === false || !target? 'Message send blocked: the current plan does not authorize sending or submitting messages. Return the draft in chat or ask the user to authorize sending before attempting delivery.': 'Message send blocked: the current task has no structured recipient authorization. Ask the user to name the recipient or explicitly authorize the currently open conversation before retrying.'),};@@ -17966,8 +17971,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// question is a different question and must not inherit it. Clearing on// all paths (including timeout, auto, mismatch, cancellation) keeps staged// consent from remaining parked for an unrelated later clarify to pick up.+ const messagingAuthorized = !!normalizeMessageTarget(guard.messaging);const messagingPermitted = guard.requiresSubmission === true- && guard.requiresStateChange === true;+ && guard.requiresStateChange === true+ && messagingAuthorized;const pending = !!guard.pendingRecipientAuthorization && messagingPermitted;const pendingType = typeof guard.pendingRecipientAuthorization === 'string'? guard.pendingRecipientAuthorizationdiff --git a/src/chrome/src/agent/message-recipient-guard.js b/src/chrome/src/agent/message-recipient-guard.jsindex d9b68958a..975c495f5 100644--- a/src/chrome/src/agent/message-recipient-guard.js+++ b/src/chrome/src/agent/message-recipient-guard.js@@ -299,7 +299,7 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canreturn negationRe.test(str);}- function prefixHasNegation(fullPrefix, prefix) {+ function prefixHasNegation(fullPrefix, prefix, roleToCheck = null) {if (hasNegation(prefix)) return true;if (!fullPrefix) return false;const boundaryRe = /[;\n\r|]|(?:\b(?:but|however|yet|instead\s+of|rather\s+than|whereas|while|whilst)\b)|(?:而不是|而非)/gi;@@ -311,9 +311,30 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst segment = fullPrefix.slice(lastBoundary);const parts = segment.split(/[,,]/);let relevantStart = 0;+ const generalRecipientRe = /\b(?:anyone|anybody|any\s+one|no\s*one|nobody|someone|somebody|people|persons?|users?|recipients?|contacts?|others?|everyone|everybody|either|neither|all|any|team|group|members?)\b|谁|任何人|大家|所有人|团队|群组|成员/i;+ const continuationRe = /^\s*(?:\b(?:especially|particularly|including|specifically|mainly|even|let\s+alone|much\s+less|not\s+to\s+mention)\b|尤其是|特别[是地]?|包括|更不用说|更别提)/i;+for (let i = 0; i < parts.length - 1; i++) {- if (roleWordsRe.test(parts[i])) {- relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ const part = parts[i];+ const partHasNeg = hasNegation(part);+ const partHasRole = roleWordsRe.test(part);++ if (partHasRole) {+ if (!partHasNeg) {+ relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ } else {+ if (roleToCheck && !snippetHasExplicitRole(part, roleToCheck)) {+ relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ } else {+ const remainingPrefix = parts.slice(i + 1).join(',');+ const namesOtherRecipient = candidateAliases.length > 0+ && !candidateAliases.some(alias => answerNamesIdentity(part, alias))+ && !generalRecipientRe.test(part);+ if (namesOtherRecipient && !continuationRe.test(remainingPrefix)) {+ relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ }+ }+ }}}const relevantPrefix = segment.slice(relevantStart);@@ -379,14 +400,14 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst fullPrefix = answerText.slice(0, span.start);if (prefixPatterns[roleToCheck].test(prefix)) {- if (!prefixHasNegation(fullPrefix, prefix)) {+ if (!prefixHasNegation(fullPrefix, prefix, roleToCheck)) {return true;}}const suffixMatch = suffix.match(suffixPatterns[roleToCheck]);if (suffixMatch) {- if (!prefixHasNegation(fullPrefix, prefix) && !hasNegation(suffixMatch[0]) && !isPrecededByNegatedCoordGroup(fullPrefix)) {+ if (!prefixHasNegation(fullPrefix, prefix, roleToCheck) && !hasNegation(suffixMatch[0]) && !isPrecededByNegatedCoordGroup(fullPrefix)) {return true;}}@@ -398,7 +419,7 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst intervening = fullSuffix.slice(0, coordMatch.index + coordMatch[0].length - coordMatch[1].length);const rolePart = coordMatch[1];if (!roleWordsRe.test(intervening) && suffixPatterns[roleToCheck].test(rolePart)) {- if (!prefixHasNegation(fullPrefix, prefix) && !hasNegation(intervening) && !hasNegation(rolePart) && !isPrecededByNegatedCoordGroup(fullPrefix)) {+ if (!prefixHasNegation(fullPrefix, prefix, roleToCheck) && !hasNegation(intervening) && !hasNegation(rolePart) && !isPrecededByNegatedCoordGroup(fullPrefix)) {return true;}}@@ -411,7 +432,7 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst intervening = prefixCoordMatch[0].slice(roleLeader.length);if (!roleWordsRe.test(intervening) && prefixPatterns[roleToCheck].test(roleLeader)) {const beforeLeader = fullPrefix.slice(0, fullPrefix.length - prefixCoordMatch[0].length);- if (!prefixHasNegation(beforeLeader, beforeLeader) && !hasNegation(roleLeader) && !hasNegation(intervening)) {+ if (!prefixHasNegation(beforeLeader, beforeLeader, roleToCheck) && !hasNegation(roleLeader) && !hasNegation(intervening)) {return true;}}diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 01e4344ea..5a480f418 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -15601,14 +15601,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}// Retain what the page actually showed only when the plan already permits- // messaging. The block below tells the model to ask the user who the- // message is for, and that answer has to be matched against real observed- // identities. A read-only plan (requiresSubmission=false or- // requiresStateChange=false) must never stage recipient consent: an answer- // to a recipient clarify must not elevate a read-only plan into a sendable one.+ // messaging and has pre-existing messaging authorization. The block below+ // tells the model to ask the user who the message is for, and that answer+ // has to be matched against real observed identities. A read-only plan+ // (requiresSubmission=false or requiresStateChange=false) or an unrelated+ // consequential submission plan (guard.messaging=null) must never stage+ // recipient consent: an answer to a recipient clarify must not elevate an+ // unauthorized plan into a sendable one.if (guard) {+ const messagingAuthorized = !!normalizeMessageTarget(guard.messaging);const messagingPermitted = guard.requiresSubmission === true- && guard.requiresStateChange === true;+ && guard.requiresStateChange === true+ && messagingAuthorized;const observedRecipientCandidates = messagingPermitted? this._messageRecipientCandidates(probe): [];@@ -15617,11 +15621,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d: null;// Offered to the next clarify only. The model chooses what it asks, so a// pending authorization must not survive into an unrelated question.- // Staged only when the plan already permits messaging.- // Associate with an explicit recipient-change clarification when a target- // was already authorized, or a recipient clarification when missing.+ // Staged only when the plan already permits messaging and has pre-existing+ // messaging authorization.+ // Associate with an explicit recipient-change clarification when a named target+ // was already authorized, or a recipient clarification for active conversations.guard.pendingRecipientAuthorization = messagingPermitted && observedRecipientCandidates.length > 0- ? (target ? 'recipient_change' : true)+ ? (target?.target_kind === 'named' ? 'recipient_change' : true): false;}@@ -15638,7 +15643,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d? 'Message action blocked: WebBrain could not conclusively resolve the target control and active composer. Re-read the page and retry with an exact visible control or fresh ref_id.': target? 'Message send blocked: the active conversation does not exactly match the recipient authorized by the user. Select the intended conversation, re-read its visible header, then retry the send action.'- : (guard?.requiresSubmission === false || guard?.requiresStateChange === false+ : (guard?.requiresSubmission === false || guard?.requiresStateChange === false || !target? 'Message send blocked: the current plan does not authorize sending or submitting messages. Return the draft in chat or ask the user to authorize sending before attempting delivery.': 'Message send blocked: the current task has no structured recipient authorization. Ask the user to name the recipient or explicitly authorize the currently open conversation before retrying.'),};@@ -15719,8 +15724,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// question is a different question and must not inherit it. Clearing on// all paths (including timeout, auto, mismatch, cancellation) keeps staged// consent from remaining parked for an unrelated later clarify to pick up.+ const messagingAuthorized = !!normalizeMessageTarget(guard.messaging);const messagingPermitted = guard.requiresSubmission === true- && guard.requiresStateChange === true;+ && guard.requiresStateChange === true+ && messagingAuthorized;const pending = !!guard.pendingRecipientAuthorization && messagingPermitted;const pendingType = typeof guard.pendingRecipientAuthorization === 'string'? guard.pendingRecipientAuthorizationdiff --git a/src/firefox/src/agent/message-recipient-guard.js b/src/firefox/src/agent/message-recipient-guard.jsindex d9b68958a..975c495f5 100644--- a/src/firefox/src/agent/message-recipient-guard.js+++ b/src/firefox/src/agent/message-recipient-guard.js@@ -299,7 +299,7 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canreturn negationRe.test(str);}- function prefixHasNegation(fullPrefix, prefix) {+ function prefixHasNegation(fullPrefix, prefix, roleToCheck = null) {if (hasNegation(prefix)) return true;if (!fullPrefix) return false;const boundaryRe = /[;\n\r|]|(?:\b(?:but|however|yet|instead\s+of|rather\s+than|whereas|while|whilst)\b)|(?:而不是|而非)/gi;@@ -311,9 +311,30 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst segment = fullPrefix.slice(lastBoundary);const parts = segment.split(/[,,]/);let relevantStart = 0;+ const generalRecipientRe = /\b(?:anyone|anybody|any\s+one|no\s*one|nobody|someone|somebody|people|persons?|users?|recipients?|contacts?|others?|everyone|everybody|either|neither|all|any|team|group|members?)\b|谁|任何人|大家|所有人|团队|群组|成员/i;+ const continuationRe = /^\s*(?:\b(?:especially|particularly|including|specifically|mainly|even|let\s+alone|much\s+less|not\s+to\s+mention)\b|尤其是|特别[是地]?|包括|更不用说|更别提)/i;+for (let i = 0; i < parts.length - 1; i++) {- if (roleWordsRe.test(parts[i])) {- relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ const part = parts[i];+ const partHasNeg = hasNegation(part);+ const partHasRole = roleWordsRe.test(part);++ if (partHasRole) {+ if (!partHasNeg) {+ relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ } else {+ if (roleToCheck && !snippetHasExplicitRole(part, roleToCheck)) {+ relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ } else {+ const remainingPrefix = parts.slice(i + 1).join(',');+ const namesOtherRecipient = candidateAliases.length > 0+ && !candidateAliases.some(alias => answerNamesIdentity(part, alias))+ && !generalRecipientRe.test(part);+ if (namesOtherRecipient && !continuationRe.test(remainingPrefix)) {+ relevantStart = parts.slice(0, i + 1).join(',').length + 1;+ }+ }+ }}}const relevantPrefix = segment.slice(relevantStart);@@ -379,14 +400,14 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst fullPrefix = answerText.slice(0, span.start);if (prefixPatterns[roleToCheck].test(prefix)) {- if (!prefixHasNegation(fullPrefix, prefix)) {+ if (!prefixHasNegation(fullPrefix, prefix, roleToCheck)) {return true;}}const suffixMatch = suffix.match(suffixPatterns[roleToCheck]);if (suffixMatch) {- if (!prefixHasNegation(fullPrefix, prefix) && !hasNegation(suffixMatch[0]) && !isPrecededByNegatedCoordGroup(fullPrefix)) {+ if (!prefixHasNegation(fullPrefix, prefix, roleToCheck) && !hasNegation(suffixMatch[0]) && !isPrecededByNegatedCoordGroup(fullPrefix)) {return true;}}@@ -398,7 +419,7 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst intervening = fullSuffix.slice(0, coordMatch.index + coordMatch[0].length - coordMatch[1].length);const rolePart = coordMatch[1];if (!roleWordsRe.test(intervening) && suffixPatterns[roleToCheck].test(rolePart)) {- if (!prefixHasNegation(fullPrefix, prefix) && !hasNegation(intervening) && !hasNegation(rolePart) && !isPrecededByNegatedCoordGroup(fullPrefix)) {+ if (!prefixHasNegation(fullPrefix, prefix, roleToCheck) && !hasNegation(intervening) && !hasNegation(rolePart) && !isPrecededByNegatedCoordGroup(fullPrefix)) {return true;}}@@ -411,7 +432,7 @@ export function clarificationAuthorizesRecipientRole(clarifyContext, answer, canconst intervening = prefixCoordMatch[0].slice(roleLeader.length);if (!roleWordsRe.test(intervening) && prefixPatterns[roleToCheck].test(roleLeader)) {const beforeLeader = fullPrefix.slice(0, fullPrefix.length - prefixCoordMatch[0].length);- if (!prefixHasNegation(beforeLeader, beforeLeader) && !hasNegation(roleLeader) && !hasNegation(intervening)) {+ if (!prefixHasNegation(beforeLeader, beforeLeader, roleToCheck) && !hasNegation(roleLeader) && !hasNegation(intervening)) {return true;}}diff --git a/test/run.js b/test/run.jsindex ed0602d25..c0a70e75f 100644--- a/test/run.js+++ b/test/run.js@@ -4996,6 +4996,31 @@ test('direct-message recipient guard uses structured intent and exact active idefalse,'emphasized denial across commas "Do not, under any circumstances, put Alice in To" must not authorize To for Alice',);+ assert.equal(+ helper.clarificationAuthorizesRecipientRole(null, 'Do not put anyone in To, especially Alice in To', 'Alice', 'to'),+ false,+ 'comma following negated role phrase "Do not put anyone in To, especially Alice in To" must retain negation',+ );+ assert.equal(+ helper.clarificationAuthorizesRecipientRole(null, 'Do not put anyone in To, including Alice in To', 'Alice', 'to'),+ false,+ 'comma following negated role phrase "Do not put anyone in To, including Alice in To" must retain negation',+ );+ assert.equal(+ helper.clarificationAuthorizesRecipientRole(null, 'Do not put anyone in CC, especially Alice in To', 'Alice', 'to'),+ true,+ 'denial of CC must not negate affirmative role in To',+ );+ assert.equal(+ helper.clarificationAuthorizesRecipientRole(null, 'Do not put Bob in To, Alice in To', 'Alice', 'to'),+ true,+ 'denial naming a different recipient must not negate Alice in To',+ );+ assert.equal(+ helper.clarificationAuthorizesRecipientRole(null, 'Do not put Bob in To, put Alice in To', 'Alice', 'to'),+ true,+ 'denial naming Bob followed by affirmative verb must authorize Alice in To',+ );assert.deepEqual(helper.resolveClarifiedRecipients([@@ -5426,10 +5451,45 @@ test('direct-message recipient guard uses structured intent and exact active ide);assert.equal(agent._planExecutionGuards.get(tabId)?.messaging, null);+ // A plan without messaging authorization (e.g. submitting a LinkedIn application)+ // must never stage recipient consent even when requiresSubmission and requiresStateChange+ // are true: a recipient clarify must not authorize sending when the plan never requested it.+ agent._planExecutionGuards.set(tabId, {+ messaging: null,+ requiresSubmission: true,+ requiresStateChange: true,+ });+ const unrelatedSubmissionSendBlock = await agent._messageRecipientGuardBlock(+ tabId,+ 'click_ax',+ { ref_id: 'ref_send' },+ 'https://mail.google.com/mail/u/0/#inbox/thread-1',+ {},+ );+ assert.equal(unrelatedSubmissionSendBlock?.blocked, true);+ assert.equal(unrelatedSubmissionSendBlock?.reasonCode, 'authorized_recipient_missing');+ assert.equal(+ agent._planExecutionGuards.get(tabId)?.observedRecipientCandidates,+ null,+ `${label}: plan without messaging authorization staged recipient candidates`,+ );+ assert.equal(+ agent._planExecutionGuards.get(tabId)?.pendingRecipientAuthorization,+ false,+ `${label}: plan without messaging authorization staged pendingRecipientAuthorization`,+ );+ assert.equal(+ agent._bindClarifiedMessageRecipient(tabId, 'Reply to Alice ([email protected])'),+ false,+ `${label}: clarify answer elevated an unrelated plan into an authorized sender`,+ );+ assert.equal(agent._planExecutionGuards.get(tabId)?.messaging, null);+// A messaging-authorized plan does stage consent for the clarify it asks for,// and binds to the page-observed candidate rather than model-authored option text.agent._planExecutionGuards.set(tabId, {- messaging: null,+ messaging: { target_kind: 'active_conversation', recipients: [] },+ messagingConversationScope: 'thread-authorized',requiresSubmission: true,requiresStateChange: true,});@@ -5458,7 +5518,7 @@ test('direct-message recipient guard uses structured intent and exact active ide}, `${label}: clarify authorization did not reach the recipient guard`);const clarifyGuardState = candidates => ({- messaging: null,+ messaging: { target_kind: 'active_conversation', recipients: [] },requiresSubmission: true,requiresStateChange: true,pendingRecipientAuthorization: true,@@ -5472,7 +5532,9 @@ test('direct-message recipient guard uses structured intent and exact active idefalse,`${label}: a recipient absent from the page was authorized by answer text alone`,);- assert.equal(agent._planExecutionGuards.get(tabId)?.messaging, null);+ assert.deepEqual(agent._planExecutionGuards.get(tabId)?.messaging, {+ target_kind: 'active_conversation', recipients: [],+ });// A failed match must consume the staged consent, not park it for whatever// unrelated answer arrives next.assert.equal(agent._planExecutionGuards.get(tabId)?.observedRecipientCandidates, null,@@ -5545,13 +5607,15 @@ test('direct-message recipient guard uses structured intent and exact active idefalse,`${label}: an incomplete recipient subset authorized a send target`,);- assert.equal(agent._planExecutionGuards.get(tabId)?.messaging, null);+ assert.deepEqual(agent._planExecutionGuards.get(tabId)?.messaging, {+ target_kind: 'active_conversation', recipients: [],+ });// Consent is staged for exactly one clarify. Without that scope, an answer// to an unrelated question that merely mentions someone on the page would// authorize sending to them.agent._planExecutionGuards.set(tabId, {- messaging: null,+ messaging: { target_kind: 'active_conversation', recipients: [] },requiresSubmission: true,requiresStateChange: true,observedRecipientCandidates: [{ identity: '[email protected]', role: 'to' }],