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
fixes
Emre Sokullua8a8eec9de53
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 6c0d55cf2..d4f4ea25d 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -2194,6 +2194,64 @@ export class Agent extends LoopDetector {};}+ async _conditionalGithubCommitTransition(tabId, name, args = {}, detectedSubmit = null) {+ const guard = this._planExecutionGuards.get(tabId);+ if (!guard?.enabled || !guard.scheduledResume || guard.siteWorkflow+ || guard.requiresStateChange !== false || guard.requiresSubmission !== false) return null;+ const capabilities = capabilitiesFor(name, args);+ const mayMutate = capabilities.some(capability => [+ Capability.TYPE, Capability.CLICK, Capability.EXECUTE_JS, Capability.DEV_PATCH, Capability.UPLOAD,+ ].includes(capability)) || isNetworkMutation(name, args);+ const navigationOrFocus = ['click', 'click_ax', 'iframe_click'].includes(name)+ && (detectedSubmit?.resolvedNavigationTarget === true || detectedSubmit?.resolvedEditableTarget === true);+ if (!mayMutate || navigationOrFocus) return null;+ const pageUrl = await this._currentUrl(tabId);+ const repository = this._workflowGithubRepositoryPath(pageUrl);+ const opaqueMutation = name === 'execute_js' || isNetworkMutation(name, args);+ const fileEditorRoute = repository && /^\/[^/]+\/[^/]+\/(?:edit|new)(?:\/|$)/i.test(new URL(pageUrl).pathname);+ if (!repository || (!fileEditorRoute && !opaqueMutation)) return null;+ const editor = this._workflowGithubEditFileScope(pageUrl);+ const deferred = guard.conditionalSiteWorkflow;+ const live = this._resolvePlannerSiteWorkflow(pageUrl, { request_kind: 'execute', site_job: 'edit-file-and-commit' });+ const sameTask = !guard.taskDrifted && guard.taskKey === this._progressTaskKeyHash(tabId);+ const sameRepository = editor?.repository === this._workflowGithubRepositoryPath(guard.siteWorkflowUrl);+ if (opaqueMutation || !editor || !sameTask || !sameRepository || !this._sameAdapterWorkflowBinding(deferred, live)) {+ guard.conditionalMutationBlocked = true;+ return {+ success: false, noDispatch: true, dispatched: false, conditionalMutationBlocked: true,+ error: 'This resumed verification cannot bind this action to its conditional file-commit contract. Use the supported file editor in the authorized repository. No editor change was dispatched. Finish with outcome partial or failed and explain that the failure branch needs a fresh plan; do not claim the repair is complete.',+ };+ }+ // Activate before even the first write, so its replacement proof and every+ // later commit use the same contract. Earlier CI reads cannot satisfy it.+ guard.siteWorkflow = live;+ guard.siteWorkflowUrl = pageUrl;+ guard.conditionalSiteWorkflow = null;+ guard.requiresStateChange = true;+ guard.requiresSubmission = true;+ guard.successfulTaskToolCalls = 0;+ guard.successfulConsequentialToolCalls = 0;+ guard.evidenceTaskKey = '';+ guard.verifiedSubmissionEvidence = false;+ guard.workflowTerminalEvidence = null;+ guard.workflowMetadataRequirementsResolved = false;+ guard.workflowMetadataRequirementsIncomplete = true;+ guard.conditionalMutationBlocked = false;+ this._completionSubmitStates.delete(tabId);+ this._armWorkflowJobRequiredEvidence(tabId, guard);+ const messages = this.conversations.get(tabId);+ if (messages?.[0]?.role === 'system') messages[0].content = this._buildSystemPrompt(this._effectiveRunMode(tabId), tabId);+ this._recordAdapterWorkflowTrace(this.currentRunId.get(tabId), live);+ await this._ensureWorkflowMetadataRequirements(tabId, {+ provider: this._activeProvider(tabId), costState: this.currentCostState.get(tabId) || null,+ }, guard.taskText, pageUrl);+ return {+ success: false, noDispatch: true, dispatched: false, retryable: true,+ workflowRearmed: true, workflowJob: 'edit-file-and-commit',+ error: 'The conditional repair branch now requires a verified file edit and commit. The editor action was not dispatched. Reread the editor, make and verify the intended change, then commit and verify the exact committed blob before done(success).',+ };+ }+async _workflowPreSubmitDispatchBlock(tabId, name, args = {}, detectedSubmit = null, provider = this._activeProvider(tabId)) {const socialBlock = await this._socialPublicationPreSubmitBlock(tabId, name, args, detectedSubmit, provider);if (socialBlock) return socialBlock;@@ -11735,7 +11793,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreason: 'submit the configured Chrome Web Store release for review',};}- const workflowPreSubmitBlock = await this._workflowPreSubmitDispatchBlock(+ const workflowPreSubmitBlock = await this._conditionalGithubCommitTransition(tabId, fnName, fnArgs, detectedSubmitAction)+ || await this._workflowPreSubmitDispatchBlock(tabId, fnName, fnArgs, detectedSubmitAction, provider,);if (workflowPreSubmitBlock) {@@ -11751,6 +11810,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dname: fnName, args: fnArgs, result: workflowPreSubmitBlock, latencyMs: 0,});onUpdate('warning', { message: workflowPreSubmitBlock.error });+ if (workflowPreSubmitBlock.workflowRearmed || workflowPreSubmitBlock.conditionalMutationBlocked) {+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,+ () => ({ success: false, skipped: true, error: 'skipped: conditional workflow transition requires a fresh tool batch' }));+ this._injectNavNotices(messages, navNotices, onUpdate);+ this._persist(tabId);+ return { action: 'continue' };+ }if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }continue;}@@ -12499,6 +12565,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}} catch {}};+ const settleConsequentialTool = async () => {+ const knownToolOutcome = toolResult?.dispatched === false || toolResult?.noDispatch === true+ || (toolResult?.outcomeUnknown !== true && toolResult?.inconclusive !== true+ && toolResult?.mutationMayHaveOccurred !== true+ && (toolResult?.success === true || toolResult?.verified === true));+ if (missingResponseOutcomeUnknown && knownToolOutcome && typeof runOptions?.afterConsequentialTool === 'function') {+ const conversationDurable = await this._persistNow(tabId);+ if (conversationDurable === true || conversationDurable?.ok === true) {+ try {+ await runOptions.afterConsequentialTool({ name: fnName, result: toolResult, outcomeUnknown: false });+ } catch {}+ }+ }+ };if (!toolResult?.done) {// Always await: this used to float on the common path, so a trace// entry could land after the next tool call's.@@ -12638,6 +12718,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtabId, toolCalls, toolIndex + 1, messages, onUpdate, step,() => ({ success: false, skipped: true, error: 'skipped: run ended via done' }));+ // schedule_resume is consequential AND terminal. Persist its result and+ // settle the parent run's checkpoint before taking this early return.+ // Without this, the child alarm exists but the parent needs reconciliation.+ await settleConsequentialTool();this._persist(tabId);return { action: 'return', value: finalResponse };}@@ -12820,18 +12904,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtool_call_id: tc.id,content: resultContent,});- const knownToolOutcome = toolResult?.dispatched === false || toolResult?.noDispatch === true- || (toolResult?.outcomeUnknown !== true && toolResult?.inconclusive !== true- && toolResult?.mutationMayHaveOccurred !== true- && (toolResult?.success === true || toolResult?.verified === true));- if (missingResponseOutcomeUnknown && knownToolOutcome && typeof runOptions?.afterConsequentialTool === 'function') {- const conversationDurable = await this._persistNow(tabId);- if (conversationDurable === true || conversationDurable?.ok === true) {- try {- await runOptions.afterConsequentialTool({ name: fnName, result: toolResult, outcomeUnknown: false });- } catch {}- }- }+ await settleConsequentialTool();this._throwIfAborted(this._runAbortSignal(tabId));if (captchaGateDecision?.status === 'manual_required' || captchaSolveOutcome?.status === 'manual_required') {@@ -19394,6 +19467,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dallowsAppStateToolEvidence: gate.allowsAppStateToolEvidence === true,requiredSchedulingTool: gate.requiredSchedulingTool || null,siteWorkflow,+ conditionalSiteWorkflow: gate.conditionalSiteWorkflow || null,progressLedgerPolicy: workflowRequiresLedger ? 'enabled' : (gate.progressLedgerPolicy || 'auto'),progressAction: workflowRequiresLedger? (normalizeProgressAction(gate.progressAction) || 'process_item')@@ -20066,11 +20140,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d),};const locale = runOptions?.locale || 'en';- const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched) };+ const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched), scheduledResume: runOptions?.scheduledResume === true };const recheckOnly = runOptions?.plannerIntentRecheckOnly === true;const provider = this._activeProvider(tabId);const plannerMessages = buildPlannerIntentMessages(enriched, tabUrl, tabTitle, historyDigest, {noThink: this._plannerPrefersNoThinkPrompt(provider),+ scheduledResume: runOptions?.scheduledResume === true,locale,priorUserTask: followUpContext.priorUserTask,scratchpadFacts: followUpContext.scratchpadFacts,@@ -20247,8 +20322,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddraftRecipients: plan.draft_recipients,allowsPlannerShapedResult: plan.allows_planner_shaped_result === true,allowsAppStateToolEvidence: plan.allows_app_state_tool_evidence === true,- requiredSchedulingTool: plan.scheduling?.tool || null,+ requiredSchedulingTool: plan.scheduling?.tool === 'schedule_task' ? 'schedule_task' : null,siteWorkflow,+ conditionalSiteWorkflow: await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, { ...plan, site_job: plan.conditional_site_job }),...this._plannerCompletionGateFields(plan),...this._plannerProgressLedgerGateFields(plan),};@@ -20289,7 +20365,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d),};const locale = runOptions?.locale || 'en';- const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched) };+ const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched), scheduledResume: runOptions?.scheduledResume === true };onUpdate('thinking', { step: 0, note: 'Planning…' });@@ -20298,6 +20374,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst skillCatalog = this._skillCatalog(conversationMode, tier);const plannerMessages = buildPlannerMessages(enriched, tabUrl, tabTitle, historyDigest, {noThink: this._plannerPrefersNoThinkPrompt(provider),+ scheduledResume: runOptions?.scheduledResume === true,allowApi: this.isApiMutationsAllowed(tabId),skillCatalog,locale,@@ -20533,8 +20610,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddraftRecipients: plan.draft_recipients,allowsPlannerShapedResult: plan.allows_planner_shaped_result === true,allowsAppStateToolEvidence: plan.allows_app_state_tool_evidence === true,- requiredSchedulingTool: plan.scheduling?.tool || null,+ requiredSchedulingTool: plan.scheduling?.tool === 'schedule_task' ? 'schedule_task' : null,siteWorkflow: await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, plan),+ conditionalSiteWorkflow: await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, { ...plan, site_job: plan.conditional_site_job }),...this._plannerCompletionGateFields(plan),...this._plannerProgressLedgerGateFields(plan),};@@ -20637,8 +20715,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddraftRecipients: approvedPlanEdited ? null : plan.draft_recipients,allowsPlannerShapedResult: plan.allows_planner_shaped_result === true,allowsAppStateToolEvidence: plan.allows_app_state_tool_evidence === true,- requiredSchedulingTool: approvedSchedulingTool,+ requiredSchedulingTool: approvedSchedulingTool === 'schedule_task' ? 'schedule_task' : null,siteWorkflow: approvedSiteWorkflow,+ conditionalSiteWorkflow: approvedPlanEdited ? null+ : await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, { ...plan, site_job: plan.conditional_site_job }),requiresDownload: approvedRequiresDownload,expectedItems: approvedExpectedItems,...approvedProgressLedger,@@ -28190,8 +28270,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d? this._workflowJobScopeIdentity(gateOutcome?.siteWorkflowUrl): '';const allowsAppStateToolEvidence = gateOutcome?.allowsAppStateToolEvidence === true;+ // schedule_resume is an optional external wait. Requiring it at completion+ // makes every resumed verification enqueue another run, even after success.const requiredSchedulingTool = gateOutcome?.requiredSchedulingTool === 'schedule_task'- || gateOutcome?.requiredSchedulingTool === 'schedule_resume'? gateOutcome.requiredSchedulingTool: null;const taskText = this._progressTaskTextKey(@@ -28214,6 +28295,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& carried.allowsAppStateToolEvidence === allowsAppStateToolEvidence&& carried.requiredSchedulingTool === requiredSchedulingTool&& JSON.stringify(carried.siteWorkflow || null) === JSON.stringify(siteWorkflow || null)+ && JSON.stringify(carried.conditionalSiteWorkflow || null) === JSON.stringify(gateOutcome.conditionalSiteWorkflow || null)&& carried.taskKey === taskKey&& carried.evidenceTaskKey === taskKey&& carried.conversationId === (this.conversationIds.get(tabId) || null);@@ -28235,6 +28317,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dallowsAppStateToolEvidence,requiredSchedulingTool,siteWorkflow,+ scheduledResume: runOptions?.scheduledResume === true || (carried?.scheduledResume === true+ && carried.taskKey === taskKey && carried.conversationId === (this.conversationIds.get(tabId) || null)),+ conditionalSiteWorkflow: gateOutcome.conditionalSiteWorkflow || null,+ conditionalMutationBlocked: carryMatches && carried.conditionalMutationBlocked === true,taskKey,taskText,approvedPlanAnchor,@@ -28540,7 +28626,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_executionEvidenceSatisfied(state) {if (!state) return false;- if (state.taskDrifted === true) return false;+ if (state.taskDrifted === true || state.conditionalMutationBlocked === true) return false;if (state.workflowForbiddenSubmission === true) return false;if (state.taskKey && state.evidenceTaskKey !== state.taskKey) return false;// Unknown mutation intent is conservative: observational evidence may be@@ -28605,6 +28691,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dallowsAppStateToolEvidence: guard.allowsAppStateToolEvidence,requiredSchedulingTool: guard.requiredSchedulingTool,siteWorkflow: guard.siteWorkflow,+ scheduledResume: guard.scheduledResume === true,+ conditionalSiteWorkflow: guard.conditionalSiteWorkflow,+ conditionalMutationBlocked: guard.conditionalMutationBlocked === true,approvedPlanAnchor: guard.approvedPlanAnchor,approvedPlanText: guard.approvedPlanText,taskKey: guard.taskKey,@@ -28959,6 +29048,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d: null,nudge: (state.taskDrifted? '[PLAN EXECUTION BLOCK: The genuine user task changed after this run was authorized. Do not execute either the old or new task under stale authorization. Call done with outcome failed and report that a fresh run is required.]'+ : state.conditionalMutationBlocked+ ? '[PLAN EXECUTION BLOCK: The conditional editor mutation was not authorized by a matching workflow contract. No repair was dispatched. Use done with outcome partial or failed and explain that the failure branch needs a fresh plan.]': staleCancellation? '[PLAN EXECUTION BLOCK: No current user stop was received. The previous response echoed a stale local cancellation status from conversation history. That status is UI metadata, not an instruction or task result. Continue the active task with permitted tools. If complete or blocked, call done with an explicit outcome; do not repeat the cancellation status or return plain text.]': missingRequiredSchedulingTooldiff --git a/src/chrome/src/agent/planner.js b/src/chrome/src/agent/planner.jsindex cd5a00a07..c988c3ef4 100644--- a/src/chrome/src/agent/planner.js+++ b/src/chrome/src/agent/planner.js@@ -137,6 +137,7 @@ export const PLANNER_RESPONSE_JSON_SCHEMA = {deliverables: { type: 'array', items: { type: 'string' } },expected_items: PLANNER_EXPECTED_ITEMS_SCHEMA,site_job: PLANNER_SITE_JOB_SCHEMA,+ conditional_site_job: { anyOf: [{ type: 'null' }, { type: 'string', enum: ['edit-file-and-commit'] }] },requires_state_change: { type: 'boolean' },requires_submission: { type: 'boolean' },messaging: PLANNER_MESSAGING_SCHEMA,@@ -180,6 +181,7 @@ export const PLANNER_RESPONSE_JSON_SCHEMA = {required: ['request_kind','site_job',+ 'conditional_site_job','requires_state_change','requires_submission','messaging',@@ -209,6 +211,7 @@ export const PLANNER_INTENT_RESPONSE_JSON_SCHEMA = {deliverables: { type: 'array', items: { type: 'string' } },expected_items: PLANNER_EXPECTED_ITEMS_SCHEMA,site_job: PLANNER_SITE_JOB_SCHEMA,+ conditional_site_job: { anyOf: [{ type: 'null' }, { type: 'string', enum: ['edit-file-and-commit'] }] },requires_state_change: { type: 'boolean' },requires_submission: { type: 'boolean' },messaging: PLANNER_MESSAGING_SCHEMA,@@ -243,6 +246,7 @@ export const PLANNER_INTENT_RESPONSE_JSON_SCHEMA = {required: ['request_kind','site_job',+ 'conditional_site_job','requires_state_change','requires_submission','messaging',@@ -293,6 +297,7 @@ Schema:"deliverables": ["explicit result the latest user request asks for"],"expected_items": null | { "count": 15, "item_type": "hotel", "ordered": true, "required_fields": ["hotel_name", "carousel_position", "evidence_source"] },"site_job": null | "exact app-provided site workflow job id",+ "conditional_site_job": null | "edit-file-and-commit","requires_state_change": boolean,"requires_submission": boolean,"messaging": null | { "target_kind": "named" | "active_conversation", "recipients": [{ "identity": "exact user-authorized recipient", "role": "to" | "cc" | "bcc" }] },@@ -386,6 +391,7 @@ export const PLANNER_INTENT_SYSTEM_PROMPT = `You are the intent and compact plan{"request_kind": "execute" | "respond" | "plan_only" | "clarify","site_job": null | "exact app-provided site workflow job id",+ "conditional_site_job": null | "edit-file-and-commit","scope_relation": "new" | "continue" | "narrow" | "extend","deliverables": ["explicit result required by the latest request"],"expected_items": null | { "count": 15, "item_type": "hotel", "ordered": true, "required_fields": ["hotel_name", "carousel_position", "evidence_source"] },@@ -612,8 +618,11 @@ export function formatResponseLanguagePolicyInstruction(value, fallbackLocale =].join('\n');}+const PLANNER_RESUME_RULE = '\n- This run is an app-owned scheduled continuation. Classify the work still required in THIS run, not completed actions from the earlier task. First inspect the external event. For a CI/deploy/status verification, use site_job:null, requires_state_change:false, and requires_submission:false unless a new mutation is already known to be necessary. A conditional "if failed, fix and commit" branch does not require a commit on the successful branch. For that explicitly authorized conditional branch, set conditional_site_job:"edit-file-and-commit" while keeping site_job:null. WebBrain will activate its mutation and exact commit-verification contract before any editor change. Use conditional_site_job:null when no such branch is authorized. Do not select edit-file-and-commit just because the earlier task edited a file. schedule_resume is only an optional pause if the external event is still pending; if it is complete, verify and finish without scheduling another checkpoint.';+export function buildPlannerSystemPrompt(opts = {}) {let prompt = opts.allowApi ? `${PLANNER_SYSTEM_PROMPT}\n${PLANNER_API_REPLAY_RULE}` : PLANNER_SYSTEM_PROMPT;+ if (opts.scheduledResume === true) prompt += PLANNER_RESUME_RULE;prompt += `\n- Requested wbLocale for localized display fields: ${normalizePlannerLocale(opts.locale)}.`;if (opts.researchEscalationEnabled === true) {prompt += '\n- Research escalation is available for materially complex read-only research subtasks. If it would substantially improve speed or quality, plan an explicit clarify consent step followed by delegate_research; only the exact user-approved prompt may be shared. Do not use it for ordinary browsing, private/account data, mutations, purchases, bookings, or high-stakes decisions.';@@ -643,7 +652,7 @@ export function buildPlannerIntentSystemPrompt(opts = {}) {? '\n- A complex read-only research subtask may use explicit clarify consent followed by delegate_research; never delegate private data or consequential actions.': '';const workflowRouting = formatSiteWorkflowRouting(opts.siteWorkflow);- return `${PLANNER_INTENT_SYSTEM_PROMPT}\n- Requested wbLocale for localized display fields: ${normalizePlannerLocale(opts.locale)}.${researchRule}${workflowRouting ? `\n\n${workflowRouting}` : ''}`;+ return `${PLANNER_INTENT_SYSTEM_PROMPT}${opts.scheduledResume === true ? PLANNER_RESUME_RULE : ''}\n- Requested wbLocale for localized display fields: ${normalizePlannerLocale(opts.locale)}.${researchRule}${workflowRouting ? `\n\n${workflowRouting}` : ''}`;}export function formatSiteWorkflowRouting(value) {@@ -926,7 +935,9 @@ export function normalizePlan(obj, opts = {}) {? (!!obj.requires_state_change|| requiresSubmission === true- || !!normalizedScheduling+ // A resume is a possible pause while waiting, not a required mutation+ // when the external event has already completed by the time we read it.+ || normalizedScheduling?.tool === 'schedule_task'|| requiresDownload): false;@@ -936,6 +947,10 @@ export function normalizePlan(obj, opts = {}) {deliverables,expected_items: expectedItems,site_job: siteJob,+ conditional_site_job: opts.scheduledResume === true && executablePlan+ && !siteJob && !requiresStateChange && requiresSubmission === false+ && obj.conditional_site_job === 'edit-file-and-commit'+ ? 'edit-file-and-commit' : null,requires_state_change: requiresStateChange,requires_submission: requiresSubmission,messaging,@@ -981,6 +996,7 @@ export function normalizePlan(obj, opts = {}) {tools: ['carousel_navigate', 'progress_update'],};normalizedPlan.scope_relation = 'narrow';+ normalizedPlan.conditional_site_job = null;normalizedPlan.deliverables = [deliverable];normalizedPlan.expected_items = {count: hotelCount,@@ -1060,6 +1076,7 @@ function appendPlanExecutionMetadata(lines, plan) {lines.push(`- Expected items: ${plan.expected_items.count} ordered=${plan.expected_items.ordered ? 'yes' : 'no'} type=${plan.expected_items.item_type}; required fields=${plan.expected_items.required_fields.join(', ') || 'none'}`);}if (plan.site_job) lines.push(`- Site workflow job: ${plan.site_job}`);+ if (plan.conditional_site_job) lines.push(`- Conditional site workflow job: ${plan.conditional_site_job}`);lines.push(`- Submission required: ${plan.requires_submission === true ? 'yes' : (plan.requires_submission === false ? 'no' : 'auto')}`);if (plan.messaging?.target_kind === 'named') {lines.push(`- Message targets: ${plan.messaging.recipients.map(recipient => `${recipient.role}:${recipient.identity}`).join(', ')}`);diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.jsindex 54acc0970..c176eab01 100644--- a/src/chrome/src/agent/tools.js+++ b/src/chrome/src/agent/tools.js@@ -555,7 +555,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'schedule_resume',- description: 'Durably pause this current task and resume it later in the same tab/conversation. Use only when the task is blocked on external time or an external event (CI/deploy/email/upload/etc.) and continuing immediately would be wasteful or impossible. This is a terminal tool: after it succeeds, the current run ends; only then may you tell the user the scheduled resume time. Do NOT use for standalone reminders or recurring monitors — use schedule_task only when the user explicitly asks for future/recurring work.',+ description: 'Durably pause this current task and resume it later in the same tab/conversation. Use only when the task is blocked on external time or an external event (CI/deploy/email/upload/etc.) and continuing immediately would be wasteful or impossible. Recheck the event first: if it has completed, verify the result and call done. Never schedule a redundant final checkpoint or use scheduling to escape a rejected done; if completion evidence cannot be verified, use done with outcome partial or failed. This is a terminal tool: after it succeeds, the current run ends; only then may you tell the user the scheduled resume time. Do NOT use for standalone reminders or recurring monitors — use schedule_task only when the user explicitly asks for future/recurring work.',parameters: {type: 'object',properties: {diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 8def44b8a..6ae8bfc8e 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -1909,6 +1909,64 @@ export class Agent extends LoopDetector {};}+ async _conditionalGithubCommitTransition(tabId, name, args = {}, detectedSubmit = null) {+ const guard = this._planExecutionGuards.get(tabId);+ if (!guard?.enabled || !guard.scheduledResume || guard.siteWorkflow+ || guard.requiresStateChange !== false || guard.requiresSubmission !== false) return null;+ const capabilities = capabilitiesFor(name, args);+ const mayMutate = capabilities.some(capability => [+ Capability.TYPE, Capability.CLICK, Capability.EXECUTE_JS, Capability.DEV_PATCH, Capability.UPLOAD,+ ].includes(capability)) || isNetworkMutation(name, args);+ const navigationOrFocus = ['click', 'click_ax', 'iframe_click'].includes(name)+ && (detectedSubmit?.resolvedNavigationTarget === true || detectedSubmit?.resolvedEditableTarget === true);+ if (!mayMutate || navigationOrFocus) return null;+ const pageUrl = await this._currentUrl(tabId);+ const repository = this._workflowGithubRepositoryPath(pageUrl);+ const opaqueMutation = name === 'execute_js' || isNetworkMutation(name, args);+ const fileEditorRoute = repository && /^\/[^/]+\/[^/]+\/(?:edit|new)(?:\/|$)/i.test(new URL(pageUrl).pathname);+ if (!repository || (!fileEditorRoute && !opaqueMutation)) return null;+ const editor = this._workflowGithubEditFileScope(pageUrl);+ const deferred = guard.conditionalSiteWorkflow;+ const live = this._resolvePlannerSiteWorkflow(pageUrl, { request_kind: 'execute', site_job: 'edit-file-and-commit' });+ const sameTask = !guard.taskDrifted && guard.taskKey === this._progressTaskKeyHash(tabId);+ const sameRepository = editor?.repository === this._workflowGithubRepositoryPath(guard.siteWorkflowUrl);+ if (opaqueMutation || !editor || !sameTask || !sameRepository || !this._sameAdapterWorkflowBinding(deferred, live)) {+ guard.conditionalMutationBlocked = true;+ return {+ success: false, noDispatch: true, dispatched: false, conditionalMutationBlocked: true,+ error: 'This resumed verification cannot bind this action to its conditional file-commit contract. Use the supported file editor in the authorized repository. No editor change was dispatched. Finish with outcome partial or failed and explain that the failure branch needs a fresh plan; do not claim the repair is complete.',+ };+ }+ // Activate before even the first write, so its replacement proof and every+ // later commit use the same contract. Earlier CI reads cannot satisfy it.+ guard.siteWorkflow = live;+ guard.siteWorkflowUrl = pageUrl;+ guard.conditionalSiteWorkflow = null;+ guard.requiresStateChange = true;+ guard.requiresSubmission = true;+ guard.successfulTaskToolCalls = 0;+ guard.successfulConsequentialToolCalls = 0;+ guard.evidenceTaskKey = '';+ guard.verifiedSubmissionEvidence = false;+ guard.workflowTerminalEvidence = null;+ guard.workflowMetadataRequirementsResolved = false;+ guard.workflowMetadataRequirementsIncomplete = true;+ guard.conditionalMutationBlocked = false;+ this._completionSubmitStates.delete(tabId);+ this._armWorkflowJobRequiredEvidence(tabId, guard);+ const messages = this.conversations.get(tabId);+ if (messages?.[0]?.role === 'system') messages[0].content = this._buildSystemPrompt(this._effectiveRunMode(tabId), tabId);+ this._recordAdapterWorkflowTrace(this.currentRunId.get(tabId), live);+ await this._ensureWorkflowMetadataRequirements(tabId, {+ provider: this._activeProvider(tabId), costState: this.currentCostState.get(tabId) || null,+ }, guard.taskText, pageUrl);+ return {+ success: false, noDispatch: true, dispatched: false, retryable: true,+ workflowRearmed: true, workflowJob: 'edit-file-and-commit',+ error: 'The conditional repair branch now requires a verified file edit and commit. The editor action was not dispatched. Reread the editor, make and verify the intended change, then commit and verify the exact committed blob before done(success).',+ };+ }+async _workflowPreSubmitDispatchBlock(tabId, name, args = {}, detectedSubmit = null, provider = this._activeProvider(tabId)) {const socialBlock = await this._socialPublicationPreSubmitBlock(tabId, name, args, detectedSubmit, provider);if (socialBlock) return socialBlock;@@ -10280,7 +10338,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreason: 'submit the configured Chrome Web Store release for review',};}- const workflowPreSubmitBlock = await this._workflowPreSubmitDispatchBlock(+ const workflowPreSubmitBlock = await this._conditionalGithubCommitTransition(tabId, fnName, fnArgs, detectedSubmitAction)+ || await this._workflowPreSubmitDispatchBlock(tabId, fnName, fnArgs, detectedSubmitAction, provider,);if (workflowPreSubmitBlock) {@@ -10296,6 +10355,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dname: fnName, args: fnArgs, result: workflowPreSubmitBlock, latencyMs: 0,});onUpdate('warning', { message: workflowPreSubmitBlock.error });+ if (workflowPreSubmitBlock.workflowRearmed || workflowPreSubmitBlock.conditionalMutationBlocked) {+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex + 1, messages, onUpdate, step,+ () => ({ success: false, skipped: true, error: 'skipped: conditional workflow transition requires a fresh tool batch' }));+ this._injectNavNotices(messages, navNotices, onUpdate);+ this._persist(tabId);+ return { action: 'continue' };+ }if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }continue;}@@ -11015,6 +11081,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}} catch {}};+ const settleConsequentialTool = async () => {+ const knownToolOutcome = toolResult?.dispatched === false || toolResult?.noDispatch === true+ || (toolResult?.outcomeUnknown !== true && toolResult?.inconclusive !== true+ && toolResult?.mutationMayHaveOccurred !== true+ && (toolResult?.success === true || toolResult?.verified === true));+ if (missingResponseOutcomeUnknown && knownToolOutcome && typeof runOptions?.afterConsequentialTool === 'function') {+ const conversationDurable = await this._persistNow(tabId);+ if (conversationDurable === true || conversationDurable?.ok === true) {+ try {+ await runOptions.afterConsequentialTool({ name: fnName, result: toolResult, outcomeUnknown: false });+ } catch {}+ }+ }+ };if (!toolResult?.done) {await recordFinalToolTrace(toolResult);if (runIdForTool && toolbarPreflight.traceCapture?.dataUrl) {@@ -11151,6 +11231,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtabId, toolCalls, toolIndex + 1, messages, onUpdate, step,() => ({ success: false, skipped: true, error: 'skipped: run ended via done' }));+ // schedule_resume is consequential AND terminal. Persist its result and+ // settle the parent run's checkpoint before taking this early return.+ // Without this, the child alarm exists but the parent needs reconciliation.+ await settleConsequentialTool();this._persist(tabId);return { action: 'return', value: finalResponse };}@@ -11312,18 +11396,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtool_call_id: tc.id,content: resultContent,});- const knownToolOutcome = toolResult?.dispatched === false || toolResult?.noDispatch === true- || (toolResult?.outcomeUnknown !== true && toolResult?.inconclusive !== true- && toolResult?.mutationMayHaveOccurred !== true- && (toolResult?.success === true || toolResult?.verified === true));- if (missingResponseOutcomeUnknown && knownToolOutcome && typeof runOptions?.afterConsequentialTool === 'function') {- const conversationDurable = await this._persistNow(tabId);- if (conversationDurable === true || conversationDurable?.ok === true) {- try {- await runOptions.afterConsequentialTool({ name: fnName, result: toolResult, outcomeUnknown: false });- } catch {}- }- }+ await settleConsequentialTool();this._throwIfAborted(this._runAbortSignal(tabId));if (captchaGateDecision?.status === 'manual_required' || captchaSolveOutcome?.status === 'manual_required') {this._appendSyntheticToolResults(@@ -17178,6 +17251,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dallowsAppStateToolEvidence: gate.allowsAppStateToolEvidence === true,requiredSchedulingTool: gate.requiredSchedulingTool || null,siteWorkflow,+ conditionalSiteWorkflow: gate.conditionalSiteWorkflow || null,progressLedgerPolicy: workflowRequiresLedger ? 'enabled' : (gate.progressLedgerPolicy || 'auto'),progressAction: workflowRequiresLedger? (normalizeProgressAction(gate.progressAction) || 'process_item')@@ -17850,11 +17924,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d),};const locale = runOptions?.locale || 'en';- const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched) };+ const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched), scheduledResume: runOptions?.scheduledResume === true };const recheckOnly = runOptions?.plannerIntentRecheckOnly === true;const provider = this.providerManager.getActive();const plannerMessages = buildPlannerIntentMessages(enriched, tabUrl, tabTitle, historyDigest, {noThink: this._plannerPrefersNoThinkPrompt(provider),+ scheduledResume: runOptions?.scheduledResume === true,locale,priorUserTask: followUpContext.priorUserTask,scratchpadFacts: followUpContext.scratchpadFacts,@@ -18031,8 +18106,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddraftRecipients: plan.draft_recipients,allowsPlannerShapedResult: plan.allows_planner_shaped_result === true,allowsAppStateToolEvidence: plan.allows_app_state_tool_evidence === true,- requiredSchedulingTool: plan.scheduling?.tool || null,+ requiredSchedulingTool: plan.scheduling?.tool === 'schedule_task' ? 'schedule_task' : null,siteWorkflow,+ conditionalSiteWorkflow: await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, { ...plan, site_job: plan.conditional_site_job }),...this._plannerCompletionGateFields(plan),...this._plannerProgressLedgerGateFields(plan),};@@ -18069,7 +18145,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d),};const locale = runOptions?.locale || 'en';- const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched) };+ const plannerParseOptions = { requireIntent: true, locale, latestUserTask: userMessageToText(enriched), scheduledResume: runOptions?.scheduledResume === true };onUpdate('thinking', { step: 0, note: 'Planning…' });@@ -18078,6 +18154,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst skillCatalog = this._skillCatalog(conversationMode, tier);const plannerMessages = buildPlannerMessages(enriched, tabUrl, tabTitle, historyDigest, {noThink: this._plannerPrefersNoThinkPrompt(provider),+ scheduledResume: runOptions?.scheduledResume === true,allowApi: this.isApiMutationsAllowed(tabId),skillCatalog,locale,@@ -18313,8 +18390,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddraftRecipients: plan.draft_recipients,allowsPlannerShapedResult: plan.allows_planner_shaped_result === true,allowsAppStateToolEvidence: plan.allows_app_state_tool_evidence === true,- requiredSchedulingTool: plan.scheduling?.tool || null,+ requiredSchedulingTool: plan.scheduling?.tool === 'schedule_task' ? 'schedule_task' : null,siteWorkflow: await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, plan),+ conditionalSiteWorkflow: await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, { ...plan, site_job: plan.conditional_site_job }),...this._plannerCompletionGateFields(plan),...this._plannerProgressLedgerGateFields(plan),};@@ -18417,8 +18495,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout ddraftRecipients: approvedPlanEdited ? null : plan.draft_recipients,allowsPlannerShapedResult: plan.allows_planner_shaped_result === true,allowsAppStateToolEvidence: plan.allows_app_state_tool_evidence === true,- requiredSchedulingTool: approvedSchedulingTool,+ requiredSchedulingTool: approvedSchedulingTool === 'schedule_task' ? 'schedule_task' : null,siteWorkflow: approvedSiteWorkflow,+ conditionalSiteWorkflow: approvedPlanEdited ? null+ : await this._resolvePlannerSiteWorkflowForLiveTab(tabId, tabUrl, { ...plan, site_job: plan.conditional_site_job }),requiresDownload: approvedRequiresDownload,expectedItems: approvedExpectedItems,...approvedProgressLedger,@@ -25797,8 +25877,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d? this._workflowJobScopeIdentity(gateOutcome?.siteWorkflowUrl): '';const allowsAppStateToolEvidence = gateOutcome?.allowsAppStateToolEvidence === true;+ // schedule_resume is an optional external wait. Requiring it at completion+ // makes every resumed verification enqueue another run, even after success.const requiredSchedulingTool = gateOutcome?.requiredSchedulingTool === 'schedule_task'- || gateOutcome?.requiredSchedulingTool === 'schedule_resume'? gateOutcome.requiredSchedulingTool: null;const taskText = this._progressTaskTextKey(@@ -25821,6 +25902,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& carried.allowsAppStateToolEvidence === allowsAppStateToolEvidence&& carried.requiredSchedulingTool === requiredSchedulingTool&& JSON.stringify(carried.siteWorkflow || null) === JSON.stringify(siteWorkflow || null)+ && JSON.stringify(carried.conditionalSiteWorkflow || null) === JSON.stringify(gateOutcome.conditionalSiteWorkflow || null)&& carried.taskKey === taskKey&& carried.evidenceTaskKey === taskKey&& carried.conversationId === (this.conversationIds.get(tabId) || null);@@ -25842,6 +25924,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dallowsAppStateToolEvidence,requiredSchedulingTool,siteWorkflow,+ scheduledResume: runOptions?.scheduledResume === true || (carried?.scheduledResume === true+ && carried.taskKey === taskKey && carried.conversationId === (this.conversationIds.get(tabId) || null)),+ conditionalSiteWorkflow: gateOutcome.conditionalSiteWorkflow || null,+ conditionalMutationBlocked: carryMatches && carried.conditionalMutationBlocked === true,taskKey,taskText,approvedPlanAnchor,@@ -26147,7 +26233,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_executionEvidenceSatisfied(state) {if (!state) return false;- if (state.taskDrifted === true) return false;+ if (state.taskDrifted === true || state.conditionalMutationBlocked === true) return false;if (state.workflowForbiddenSubmission === true) return false;if (state.taskKey && state.evidenceTaskKey !== state.taskKey) return false;// Unknown mutation intent is conservative: observational evidence may be@@ -26212,6 +26298,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dallowsAppStateToolEvidence: guard.allowsAppStateToolEvidence,requiredSchedulingTool: guard.requiredSchedulingTool,siteWorkflow: guard.siteWorkflow,+ scheduledResume: guard.scheduledResume === true,+ conditionalSiteWorkflow: guard.conditionalSiteWorkflow,+ conditionalMutationBlocked: guard.conditionalMutationBlocked === true,approvedPlanAnchor: guard.approvedPlanAnchor,approvedPlanText: guard.approvedPlanText,taskKey: guard.taskKey,@@ -26566,6 +26655,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d: null,nudge: (state.taskDrifted? '[PLAN EXECUTION BLOCK: The genuine user task changed after this run was authorized. Do not execute either the old or new task under stale authorization. Call done with outcome failed and report that a fresh run is required.]'+ : state.conditionalMutationBlocked+ ? '[PLAN EXECUTION BLOCK: The conditional editor mutation was not authorized by a matching workflow contract. No repair was dispatched. Use done with outcome partial or failed and explain that the failure branch needs a fresh plan.]': staleCancellation? '[PLAN EXECUTION BLOCK: No current user stop was received. The previous response echoed a stale local cancellation status from conversation history. That status is UI metadata, not an instruction or task result. Continue the active task with permitted tools. If complete or blocked, call done with an explicit outcome; do not repeat the cancellation status or return plain text.]': missingRequiredSchedulingTooldiff --git a/src/firefox/src/agent/planner.js b/src/firefox/src/agent/planner.jsindex cd5a00a07..c988c3ef4 100644--- a/src/firefox/src/agent/planner.js+++ b/src/firefox/src/agent/planner.js@@ -137,6 +137,7 @@ export const PLANNER_RESPONSE_JSON_SCHEMA = {deliverables: { type: 'array', items: { type: 'string' } },expected_items: PLANNER_EXPECTED_ITEMS_SCHEMA,site_job: PLANNER_SITE_JOB_SCHEMA,+ conditional_site_job: { anyOf: [{ type: 'null' }, { type: 'string', enum: ['edit-file-and-commit'] }] },requires_state_change: { type: 'boolean' },requires_submission: { type: 'boolean' },messaging: PLANNER_MESSAGING_SCHEMA,@@ -180,6 +181,7 @@ export const PLANNER_RESPONSE_JSON_SCHEMA = {required: ['request_kind','site_job',+ 'conditional_site_job','requires_state_change','requires_submission','messaging',@@ -209,6 +211,7 @@ export const PLANNER_INTENT_RESPONSE_JSON_SCHEMA = {deliverables: { type: 'array', items: { type: 'string' } },expected_items: PLANNER_EXPECTED_ITEMS_SCHEMA,site_job: PLANNER_SITE_JOB_SCHEMA,+ conditional_site_job: { anyOf: [{ type: 'null' }, { type: 'string', enum: ['edit-file-and-commit'] }] },requires_state_change: { type: 'boolean' },requires_submission: { type: 'boolean' },messaging: PLANNER_MESSAGING_SCHEMA,@@ -243,6 +246,7 @@ export const PLANNER_INTENT_RESPONSE_JSON_SCHEMA = {required: ['request_kind','site_job',+ 'conditional_site_job','requires_state_change','requires_submission','messaging',@@ -293,6 +297,7 @@ Schema:"deliverables": ["explicit result the latest user request asks for"],"expected_items": null | { "count": 15, "item_type": "hotel", "ordered": true, "required_fields": ["hotel_name", "carousel_position", "evidence_source"] },"site_job": null | "exact app-provided site workflow job id",+ "conditional_site_job": null | "edit-file-and-commit","requires_state_change": boolean,"requires_submission": boolean,"messaging": null | { "target_kind": "named" | "active_conversation", "recipients": [{ "identity": "exact user-authorized recipient", "role": "to" | "cc" | "bcc" }] },@@ -386,6 +391,7 @@ export const PLANNER_INTENT_SYSTEM_PROMPT = `You are the intent and compact plan{"request_kind": "execute" | "respond" | "plan_only" | "clarify","site_job": null | "exact app-provided site workflow job id",+ "conditional_site_job": null | "edit-file-and-commit","scope_relation": "new" | "continue" | "narrow" | "extend","deliverables": ["explicit result required by the latest request"],"expected_items": null | { "count": 15, "item_type": "hotel", "ordered": true, "required_fields": ["hotel_name", "carousel_position", "evidence_source"] },@@ -612,8 +618,11 @@ export function formatResponseLanguagePolicyInstruction(value, fallbackLocale =].join('\n');}+const PLANNER_RESUME_RULE = '\n- This run is an app-owned scheduled continuation. Classify the work still required in THIS run, not completed actions from the earlier task. First inspect the external event. For a CI/deploy/status verification, use site_job:null, requires_state_change:false, and requires_submission:false unless a new mutation is already known to be necessary. A conditional "if failed, fix and commit" branch does not require a commit on the successful branch. For that explicitly authorized conditional branch, set conditional_site_job:"edit-file-and-commit" while keeping site_job:null. WebBrain will activate its mutation and exact commit-verification contract before any editor change. Use conditional_site_job:null when no such branch is authorized. Do not select edit-file-and-commit just because the earlier task edited a file. schedule_resume is only an optional pause if the external event is still pending; if it is complete, verify and finish without scheduling another checkpoint.';+export function buildPlannerSystemPrompt(opts = {}) {let prompt = opts.allowApi ? `${PLANNER_SYSTEM_PROMPT}\n${PLANNER_API_REPLAY_RULE}` : PLANNER_SYSTEM_PROMPT;+ if (opts.scheduledResume === true) prompt += PLANNER_RESUME_RULE;prompt += `\n- Requested wbLocale for localized display fields: ${normalizePlannerLocale(opts.locale)}.`;if (opts.researchEscalationEnabled === true) {prompt += '\n- Research escalation is available for materially complex read-only research subtasks. If it would substantially improve speed or quality, plan an explicit clarify consent step followed by delegate_research; only the exact user-approved prompt may be shared. Do not use it for ordinary browsing, private/account data, mutations, purchases, bookings, or high-stakes decisions.';@@ -643,7 +652,7 @@ export function buildPlannerIntentSystemPrompt(opts = {}) {? '\n- A complex read-only research subtask may use explicit clarify consent followed by delegate_research; never delegate private data or consequential actions.': '';const workflowRouting = formatSiteWorkflowRouting(opts.siteWorkflow);- return `${PLANNER_INTENT_SYSTEM_PROMPT}\n- Requested wbLocale for localized display fields: ${normalizePlannerLocale(opts.locale)}.${researchRule}${workflowRouting ? `\n\n${workflowRouting}` : ''}`;+ return `${PLANNER_INTENT_SYSTEM_PROMPT}${opts.scheduledResume === true ? PLANNER_RESUME_RULE : ''}\n- Requested wbLocale for localized display fields: ${normalizePlannerLocale(opts.locale)}.${researchRule}${workflowRouting ? `\n\n${workflowRouting}` : ''}`;}export function formatSiteWorkflowRouting(value) {@@ -926,7 +935,9 @@ export function normalizePlan(obj, opts = {}) {? (!!obj.requires_state_change|| requiresSubmission === true- || !!normalizedScheduling+ // A resume is a possible pause while waiting, not a required mutation+ // when the external event has already completed by the time we read it.+ || normalizedScheduling?.tool === 'schedule_task'|| requiresDownload): false;@@ -936,6 +947,10 @@ export function normalizePlan(obj, opts = {}) {deliverables,expected_items: expectedItems,site_job: siteJob,+ conditional_site_job: opts.scheduledResume === true && executablePlan+ && !siteJob && !requiresStateChange && requiresSubmission === false+ && obj.conditional_site_job === 'edit-file-and-commit'+ ? 'edit-file-and-commit' : null,requires_state_change: requiresStateChange,requires_submission: requiresSubmission,messaging,@@ -981,6 +996,7 @@ export function normalizePlan(obj, opts = {}) {tools: ['carousel_navigate', 'progress_update'],};normalizedPlan.scope_relation = 'narrow';+ normalizedPlan.conditional_site_job = null;normalizedPlan.deliverables = [deliverable];normalizedPlan.expected_items = {count: hotelCount,@@ -1060,6 +1076,7 @@ function appendPlanExecutionMetadata(lines, plan) {lines.push(`- Expected items: ${plan.expected_items.count} ordered=${plan.expected_items.ordered ? 'yes' : 'no'} type=${plan.expected_items.item_type}; required fields=${plan.expected_items.required_fields.join(', ') || 'none'}`);}if (plan.site_job) lines.push(`- Site workflow job: ${plan.site_job}`);+ if (plan.conditional_site_job) lines.push(`- Conditional site workflow job: ${plan.conditional_site_job}`);lines.push(`- Submission required: ${plan.requires_submission === true ? 'yes' : (plan.requires_submission === false ? 'no' : 'auto')}`);if (plan.messaging?.target_kind === 'named') {lines.push(`- Message targets: ${plan.messaging.recipients.map(recipient => `${recipient.role}:${recipient.identity}`).join(', ')}`);diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.jsindex 2ff278ff9..e4db67484 100644--- a/src/firefox/src/agent/tools.js+++ b/src/firefox/src/agent/tools.js@@ -555,7 +555,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'schedule_resume',- description: 'Durably pause this current task and resume it later in the same tab/conversation. Use only when the task is blocked on external time or an external event (CI/deploy/email/upload/etc.) and continuing immediately would be wasteful or impossible. This is a terminal tool: after it succeeds, the current run ends; only then may you tell the user the scheduled resume time. Do NOT use for standalone reminders or recurring monitors — use schedule_task only when the user explicitly asks for future/recurring work.',+ description: 'Durably pause this current task and resume it later in the same tab/conversation. Use only when the task is blocked on external time or an external event (CI/deploy/email/upload/etc.) and continuing immediately would be wasteful or impossible. Recheck the event first: if it has completed, verify the result and call done. Never schedule a redundant final checkpoint or use scheduling to escape a rejected done; if completion evidence cannot be verified, use done with outcome partial or failed. This is a terminal tool: after it succeeds, the current run ends; only then may you tell the user the scheduled resume time. Do NOT use for standalone reminders or recurring monitors — use schedule_task only when the user explicitly asks for future/recurring work.',parameters: {type: 'object',properties: {diff --git a/test/run.js b/test/run.jsindex e042e2b8c..693b73948 100644--- a/test/run.js+++ b/test/run.js@@ -52738,6 +52738,7 @@ function makeResumeBatchHarness(AgentClass, SchedulerMod) {agent._skipPermissionGate = true;agent._currentUrl = async () => 'https://example.com/';agent._persist = () => {};+ agent._persistNow = async () => true;const executeTool = agent.executeTool.bind(agent);const executed = [];agent.executeTool = async (tabId, name, args, ...rest) => {@@ -52770,6 +52771,50 @@ function makeResumeBatchHarness(AgentClass, SchedulerMod) {return { ...h, agent, executed, updates, messages, batch, schedule };}+test('terminal schedule_resume settles its parent checkpoint only after durable result persistence', async () => {+ for (const [label, AgentClass, SchedulerMod] of [['chrome', AgentCh, SchedulerCh], ['firefox', AgentFx, SchedulerFx]]) {+ for (const durable of [true, false]) {+ const h = makeResumeBatchHarness(AgentClass, SchedulerMod);+ const parent = await h.schedule();+ const events = [];+ h.agent._persistNow = async () => {+ const results = h.messages.filter(message => message.role === 'tool');+ assert.equal(results.length, 2, `${label}: persistence must include the terminal result and skipped stale call`);+ assert.match(results[0].content, /"scheduled":true/);+ assert.match(results[1].content, /skipped: run ended via done/);+ events.push('persist');+ return durable;+ };+ h.manager.agent.processMessage = async (_tabId, _message, onUpdate, _mode, _attachments, runOptions) => {+ const after = runOptions.afterConsequentialTool;+ const result = await h.batch([+ ['schedule_resume', { after_seconds: 60, reason: 'Build still running', resume_instruction: 'Recheck the build; finish if complete.' }],+ ['done', { summary: 'Stale completion must not run.', outcome: 'success' }],+ ], {+ ...runOptions,+ afterConsequentialTool: async (args) => {+ assert.deepEqual(events, ['persist'], `${label}: checkpoint settled before result durability`);+ events.push('settle');+ return after(args);+ },+ });+ for (const update of h.updates) onUpdate(update.type, update.data);+ return result.value;+ };+ await h.manager.handleAlarm(h.alarmName(parent.jobId));+ const finished = h.jobs().find(job => job.id === parent.jobId);+ assert.equal(finished.status, durable ? 'completed' : 'needs_user_input', `${label}: wrong parent state after terminal schedule`);+ assert.equal(!!finished.pendingToolCall, !durable, `${label}: checkpoint must match durable result availability`);+ assert.deepEqual(events, durable ? ['persist', 'settle'] : ['persist']);+ assert.deepEqual(h.executed, ['schedule_resume'], `${label}: scheduling must not replay stale work`);+ const children = h.jobs().filter(job => job.id !== parent.jobId);+ assert.equal(children.length, 1);+ assert.equal(children[0].status, 'pending');+ assert.equal(h.alarms.has(h.alarmName(children[0].id)), true);+ }+ }+});+test('schedule_resume pauses unfinished chat work without running success completion guards', async () => {for (const [label, AgentClass, SchedulerMod] of [['chrome', AgentCh, SchedulerCh], ['firefox', AgentFx, SchedulerFx]]) {const h = makeResumeBatchHarness(AgentClass, SchedulerMod);@@ -77844,9 +77889,11 @@ test('GitHub edit-file workflow verifies the exact committed raw blob', async ()const editUrl = 'https://github.com/Example/Repo/edit/main/docs/plan.md';const commitUrl = `https://github.com/Example/Repo/commit/${commitSha}`;try {- for (const [label, AgentClass, resolveJob] of [- ['chrome', AgentCh, resolveAdapterWorkflowJob],- ['firefox', AgentFx, resolveAdapterWorkflowJobFx],+ for (const [label, AgentClass, resolveJob, conditional] of [+ ['chrome', AgentCh, resolveAdapterWorkflowJob, false],+ ['firefox', AgentFx, resolveAdapterWorkflowJobFx, false],+ ['chrome', AgentCh, resolveAdapterWorkflowJob, true],+ ['firefox', AgentFx, resolveAdapterWorkflowJobFx, true],]) {const agent = new AgentClass({});const tabId = label === 'chrome' ? 9445 : 9446;@@ -77862,16 +77909,25 @@ test('GitHub edit-file workflow verifies the exact committed raw blob', async ()branch: 'feature/fix-copy',path: 'docs/plan.md',}, `${label}: an explicit slash-containing branch was split into the file path`);- const workflowGuard = {- enabled: true,- siteWorkflow,+ const workflowGuard = conditional ? agent._startPlanExecutionGuard(tabId, 'act', {+ requestKind: 'execute', requiresStateChange: false, requiresSubmission: false,+ siteWorkflowUrl: 'https://github.com/Example/Repo/actions/runs/123', conditionalSiteWorkflow: siteWorkflow,+ }, { scheduledResume: true }) : { enabled: true, siteWorkflow };+ if (conditional) {+ agent._currentUrl = async () => editUrl;+ agent._ensureWorkflowMetadataRequirements = async () => {};+ assert.equal((await agent._conditionalGithubCommitTransition(tabId, 'set_field', { ref_id: 'ref_editor', text: body }))?.workflowRearmed, true);+ assert.equal(workflowGuard.requiresSubmission, true);+ }+ Object.assign(workflowGuard, {workflowMetadataRequirements: [{ field: 'path', value: 'docs/plan.md' },{ field: 'branch', value: 'main' },{ field: 'commit_message', value: 'Translate plan' },],workflowMetadataRequirementsResolved: true,- };+ workflowMetadataRequirementsIncomplete: false,+ });agent._planExecutionGuards.set(tabId, workflowGuard);agent._lastAxScopes.set(tabId, { documentToken: 'doc', pageUrl: editUrl });let liveEditorValue = body;@@ -88205,6 +88261,119 @@ test('execution evidence ignores failed, denied, skipped, blocked, and unknown o}});+test('completed CI verification can finish without taking its conditional scheduled-resume branch', async () => {+ await withPlannerBrowserGlobals(async () => {+ for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) {+ for (const fullPlanner of [false, true]) {+ const tabId = 8560;+ const agent = new AgentClass({ getActive: () => ({ name: 'planner-test', model: 'planner-test' }) });+ agent._chatWithCostAllowance = async (_provider, messages) => {+ assert.match(messages[0].content, /app-owned scheduled continuation/);+ assert.match(messages[0].content, /site_job:null, requires_state_change:false, and requires_submission:false/);+ assert.match(messages[0].content, /conditional "if failed, fix and commit" branch does not require a commit/);+ return { content: plannerFixtureJson({+ scope_relation: 'continue',+ conditional_site_job: 'edit-file-and-commit',+ summary: 'Verify Build and Package #169 and its Playwright installation and tests.',+ steps: [+ { id: '1', action: 'Read the current build result.', tools: ['get_accessibility_tree'] },+ { id: '2', action: 'If still running, resume later; otherwise verify the result and finish.', tools: ['schedule_resume', 'done'] },+ ],+ scheduling: { tool: 'schedule_resume', hint: 'Use only if CI is still queued or in progress.' },+ }) };+ };+ const tabInfo = { tabUrl: 'https://github.com/webbrain-one/webbrain/actions/runs/34418357023/job/102688157939', tabTitle: 'Build and Package' };+ agent._currentUrl = async () => tabInfo.tabUrl;+ const options = { scheduledRun: true, scheduledResume: true };+ const user = { role: 'user', content: 'Recheck the build. If successful, verify the result and finish; if failed, fix the workflow file and commit; if still running, resume later.' };+ const gate = fullPlanner+ ? await agent._runPlannerGate(tabId, user, () => {}, null, null, '', tabInfo, 'try', 'act', options)+ : await agent._runPlannerIntentGate(tabId, user, () => {}, null, null, '', tabInfo, 'act', options);+ assert.equal(gate.proceed, true, `${label}: planner did not authorize verification`);+ assert.equal(gate.requiredSchedulingTool, null, `${label}: optional wait became mandatory`);+ assert.equal(gate.requiresStateChange, false, `${label}: optional wait required a mutation`);+ assert.equal(gate.requiresSubmission, false, `${label}: verification inherited a commit requirement`);+ assert.equal(gate.siteWorkflow, null);+ assert.equal(gate.conditionalSiteWorkflow?.job?.id, 'edit-file-and-commit');+ const state = agent._startPlanExecutionGuard(tabId, 'act', gate, options);+ const summary = 'Build #169 succeeded in 3m14s. Install Playwright Chromium and Test passed.';+ agent._markPlanExecutionToolCall(tabId, 'get_accessibility_tree', { success: true, pageContent: summary });+ assert.equal(agent._completionPageWarning(tabId, summary, 'success', {+ url: tabInfo.tabUrl, visibleFormCount: 1, relevantFormCount: 1, successMessages: [],+ }, tabInfo.tabUrl), null, `${label}: log-page form blocked read-only verification`);+ assert.equal(agent._planOnlyTerminalDecision(tabId, summary, { viaDone: true, outcome: 'success' }), null);+ assert.equal(state.successfulConsequentialToolCalls, 0, `${label}: verification should need no mutation`);++ // Older planner handoffs must not re-arm the erroneous resume requirement.+ const legacy = agent._startPlanExecutionGuard(tabId, 'act', { ...gate, requiredSchedulingTool: 'schedule_resume' });+ assert.equal(legacy.requiredSchedulingTool, null);+ }+ }+ });+});++test('conditional resumed GitHub repair re-arms commit guards before dispatch and rejects missing contracts', async () => {+ for (const [label, AgentClass, resolveJob] of [['chrome', AgentCh, resolveAdapterWorkflowJob], ['firefox', AgentFx, resolveAdapterWorkflowJobFx]]) {+ for (const variant of ['authorized', 'missing', 'other_repository', 'changed_task', 'new_file', 'network', 'script']) {+ const tabId = 8562;+ const runUrl = 'https://github.com/Example/Repo/actions/runs/123';+ const editUrl = `https://github.com/${variant === 'other_repository' ? 'Other/Repo' : 'Example/Repo'}/${variant === 'new_file' ? 'new' : 'edit'}/main/.github/workflows/main.yml`;+ const agent = new AgentClass({ getActive: () => ({ supportsVision: false }), getVisionProvider: async () => null });+ configurePlanOnlyGuardAgent(agent, tabId);+ agent.conversations.get(tabId).push({ role: 'user', content: 'Check CI; if it failed, fix the workflow and commit.' });+ agent._currentUrl = async () => editUrl;+ agent._ensureGateSetting = async () => {};+ agent._detectLikelySubmitAction = async () => ({ resolvedEditableTarget: true });+ agent.isApiMutationsAllowed = () => true;+ let metadataCalls = 0;+ agent._ensureWorkflowMetadataRequirements = async () => {+ metadataCalls++;+ assert.equal(agent._planExecutionGuards.get(tabId).siteWorkflow.job.id, 'edit-file-and-commit');+ };+ const state = agent._startPlanExecutionGuard(tabId, 'act', {+ requestKind: 'execute', requiresStateChange: false, requiresSubmission: false,+ siteWorkflowUrl: runUrl,+ conditionalSiteWorkflow: variant === 'missing' ? null : resolveJob(runUrl, 'edit-file-and-commit'),+ }, { scheduledResume: true });+ agent._markPlanExecutionToolCall(tabId, 'get_accessibility_tree', { success: true, pageContent: 'Build failed: missing Chromium executable.' });+ if (variant === 'changed_task') agent._progressTaskKeyHash = () => 'new-task';+ const dispatched = [];+ agent.executeTool = async (_tab, name) => { dispatched.push(name); return { success: true }; };+ const messages = [];+ const calls = [+ variant === 'network' ? ['fetch_url', { url: 'https://api.github.com/repos/Example/Repo/contents/main.yml', method: 'PUT' }]+ : variant === 'script' ? ['execute_js', { code: 'void 0' }]+ : ['set_field', { ref_id: 'ref_editor', text: 'corrected workflow', submit: false }],+ ['click_ax', { ref_id: 'ref_commit' }],+ ['done', { summary: 'Workflow fixed.', outcome: 'success' }],+ ].map(([name, args], index) => ({ id: `conditional_${index}`, function: { name, arguments: JSON.stringify(args) } }));+ const batch = await agent._executeToolBatch(tabId, calls, messages, () => {}, { supportsVision: false }, null,+ new Set(['set_field', 'click_ax', 'done', 'fetch_url', 'execute_js']), 1, { scheduledRun: true, scheduledResume: true });+ assert.equal(batch.action, 'continue', `${label}/${variant}: transition did not require a fresh batch`);+ assert.deepEqual(dispatched, [], `${label}/${variant}: stale read-only batch dispatched a mutation`);+ assert.equal(messages.filter(message => message.role === 'tool').length, 3, `${label}: stale calls were not closed`);+ if (variant === 'authorized') {+ assert.equal(state.siteWorkflow.job.id, 'edit-file-and-commit');+ assert.equal(state.requiresStateChange, true);+ assert.equal(state.requiresSubmission, true);+ assert.equal(metadataCalls, 1);+ assert.equal(state.successfulTaskToolCalls, 0, `${label}: initial CI read survived as repair evidence`);+ assert.equal((await agent._workflowPreSubmitDispatchBlock(tabId, 'click_ax', {}, { isSubmit: true }))?.noDispatch, true,+ `${label}: re-armed workflow allowed a commit without exact editor proof`);+ assert.equal((await agent._githubCommittedFileVerification(tabId, {}, runUrl, {}))?.verified, false,+ `${label}: committed-file verification was still disabled`);+ } else {+ assert.equal(state.siteWorkflow, null);+ assert.equal(metadataCalls, 0);+ assert.equal(state.conditionalMutationBlocked, true);+ }+ assert.equal(agent._executionEvidenceSatisfied(state), false, `${label}: a CI read proved the repair completed`);+ assert.ok(agent._planOnlyTerminalDecision(tabId, 'Workflow fixed.', { viaDone: true, outcome: 'success' }));+ assert.equal(agent._planOnlyTerminalDecision(tabId, 'The build failed and the repair could not be verified.', { viaDone: true, outcome: 'partial' }), null);+ }+ }+});+test('planned scheduling requires successful evidence from the matching scheduling tool', () => {for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {const agent = new AgentClass({});@@ -88284,9 +88453,10 @@ test('planned scheduling requires successful evidence from the matching scheduli);assert.equal(agent._executionEvidenceSatisfied(resumeState),- true,- `${AgentClass.name}: terminal schedule_resume result was not counted`,+ false,+ `${AgentClass.name}: an optional pause must not prove the state-changing task is complete`,);+ assert.equal(resumeState.requiredSchedulingTool, null, `${AgentClass.name}: pause became a completion prerequisite`);const blockedTabId = 8576 + index;agent._startPlanExecutionGuard(blockedTabId, 'act', {@@ -105057,6 +105227,7 @@ function plannerFixtureJson(overrides = {}) {return JSON.stringify({request_kind: 'execute',site_job: null,+ conditional_site_job: null,requires_state_change: false,requires_submission: false,completion_requirements: { download: false },@@ -106000,7 +106171,8 @@ test('reviewed plan edits preserve only explicitly approved scheduling metadata''verbose',text => text.replace(/-\s*schedule_task:/, '- schedule_resume:'),);- assert.equal(changed.requiredSchedulingTool, 'schedule_resume', `${label}: edited schedule tool was not honored`);+ assert.equal(changed.requiredSchedulingTool, null, `${label}: edited resume became a mandatory completion action`);+ assert.match(changed.approvedScratchpadText, /-\s*schedule_resume:/, `${label}: edited pause metadata was lost`);}});});