@tomflow/chatloop-tools 0.9.21 → 0.9.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
- package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
- package/node_modules/ps-list/index.d.ts +76 -0
- package/node_modules/ps-list/index.js +366 -0
- package/node_modules/ps-list/license +9 -0
- package/node_modules/ps-list/package.json +44 -0
- package/node_modules/ps-list/readme.md +56 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
- package/package.json +7 -3
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// Chat Loop Worker — readiness. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
+
// Read the existing resource index without reconciliation, tab mutation or
|
|
3
|
+
// Owner changes. A registered blank successor proves only tab creation,
|
|
4
|
+
// NEVER a click, user message or successful Handoff.
|
|
5
|
+
async function handoffTabEvidence(run){
|
|
6
|
+
if(run?.phase!=="BLOCKED"||run.action!=="HANDOFF"||!run.sessionId)
|
|
7
|
+
return null;
|
|
8
|
+
const saved=(await chrome.storage.local.get(resources.KEY).catch(()=>null))
|
|
9
|
+
?.[resources.KEY];
|
|
10
|
+
const candidates=Array.isArray(saved?.entries)?saved.entries.filter(entry=>
|
|
11
|
+
entry?.kind==="chat"&&entry.confirmed===false
|
|
12
|
+
&&entry.sessionId===run.sessionId&&Number.isInteger(entry.id)
|
|
13
|
+
&&entry.id!==run.tabId):[];
|
|
14
|
+
if(candidates.length!==1)return null;
|
|
15
|
+
const entry=candidates[0];
|
|
16
|
+
const tab=await chrome.tabs.get(entry.id).catch(()=>null);
|
|
17
|
+
if(!tab||typeof tab.url!=="string"||!tab.url.startsWith("https://chatgpt.com/"))
|
|
18
|
+
return null;
|
|
19
|
+
return {tabId:entry.id,recorded:true,confirmed:false,
|
|
20
|
+
pageState:tab.url==="https://chatgpt.com/"?"BLANK_HOME":"CHANGED_UNVERIFIED",
|
|
21
|
+
sendReceipt:"UNVERIFIED"};
|
|
22
|
+
}
|
|
23
|
+
// Read-only diagnosis for a START that created an unconfirmed Chat home.
|
|
24
|
+
// Never infers a send receipt, creates a tab, reads message text, or changes Owner.
|
|
25
|
+
async function startReadinessEvidence(run){
|
|
26
|
+
if(run?.phase!=='BLOCKED'||run.action!=='START'||!run.sessionId
|
|
27
|
+
||!Number.isSafeInteger(run.attemptedNewTabId))return null;
|
|
28
|
+
const saved=(await chrome.storage.local.get(resources.KEY).catch(()=>null))
|
|
29
|
+
?.[resources.KEY];
|
|
30
|
+
const candidates=Array.isArray(saved?.entries)?saved.entries.filter(entry=>
|
|
31
|
+
entry?.kind==='chat'&&entry.confirmed===false
|
|
32
|
+
&&entry.sessionId===run.sessionId&&entry.id===run.attemptedNewTabId):[];
|
|
33
|
+
if(candidates.length!==1)return null;
|
|
34
|
+
const tab=await Promise.race([
|
|
35
|
+
chrome.tabs.get(run.attemptedNewTabId).catch(()=>null),
|
|
36
|
+
new Promise(resolve=>setTimeout(()=>resolve(null),1500))
|
|
37
|
+
]);
|
|
38
|
+
if(!tab||typeof tab.url!=='string'||!tab.url.startsWith('https://chatgpt.com/'))
|
|
39
|
+
return null;
|
|
40
|
+
const result=await Promise.race([
|
|
41
|
+
chrome.scripting.executeScript({target:{tabId:tab.id},func:async expectedDigest=>{
|
|
42
|
+
const visible=e=>Boolean(e?.getClientRects?.().length);
|
|
43
|
+
const mains=[...document.querySelectorAll('main')].filter(visible);
|
|
44
|
+
const editors=[...document.querySelectorAll(
|
|
45
|
+
'[contenteditable="true"][data-composer-markdown],#prompt-textarea[contenteditable="true"]')];
|
|
46
|
+
const editor=editors.find(visible);
|
|
47
|
+
const messages=mains.flatMap(m=>[...m.querySelectorAll(
|
|
48
|
+
'[data-chatgpt-search-message-ids],[data-message-author-role]')]);
|
|
49
|
+
const modern=mains.flatMap(m=>[...m.querySelectorAll(
|
|
50
|
+
'[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]);
|
|
51
|
+
const units=modern.length?modern:messages;
|
|
52
|
+
const role=n=>n.getAttribute('data-message-author-role')
|
|
53
|
+
||n.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
|
|
54
|
+
const messageId=n=>{
|
|
55
|
+
const id=n.getAttribute('data-message-id')
|
|
56
|
+
||n.getAttribute('data-chatgpt-search-message-ids')?.trim().split(/\s+/)[0];
|
|
57
|
+
return typeof id==='string'&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,115}$/.test(id)
|
|
58
|
+
?id:null;
|
|
59
|
+
};
|
|
60
|
+
const canonical=v=>String(v||'').replace(/\s+/g,'');
|
|
61
|
+
const users=units.filter(n=>role(n)==='user');
|
|
62
|
+
const assistants=units.filter(n=>role(n)==='assistant');
|
|
63
|
+
const comparable=typeof expectedDigest==='string'&&/^[a-f0-9]{64}$/.test(expectedDigest)
|
|
64
|
+
&&Boolean(globalThis.crypto?.subtle)&&typeof TextEncoder==='function';
|
|
65
|
+
const matched=[];
|
|
66
|
+
if(comparable)for(const user of users){
|
|
67
|
+
if(!messageId(user))continue;
|
|
68
|
+
const bubble=user.querySelector('[data-search-result-target]')
|
|
69
|
+
||user.querySelector('[data-user-message-bubble="true"]')||user;
|
|
70
|
+
const normalized=canonical(bubble.innerText||bubble.textContent);
|
|
71
|
+
const bytes=new TextEncoder().encode(normalized);
|
|
72
|
+
const hash=await crypto.subtle.digest('SHA-256',bytes);
|
|
73
|
+
const digest=Array.from(new Uint8Array(hash),v=>v.toString(16).padStart(2,'0')).join('');
|
|
74
|
+
if(digest===expectedDigest)matched.push(user);
|
|
75
|
+
}
|
|
76
|
+
const key=(prefix,node)=>node&&messageId(node)?prefix+messageId(node):null;
|
|
77
|
+
// Diagnostic only: an account-switch error can leave a local-chatgpt
|
|
78
|
+
// user bubble visible without any server-confirmed first send.
|
|
79
|
+
// Never infer NOT_SENT or a retry permit from this UI text.
|
|
80
|
+
const switched=/你的账户已切换[。.!!\s]*请重新发送消息|your account (?:has been |was )?switched[.!\s]*please (?:re-?send|send again) (?:your )?message/i;
|
|
81
|
+
const inUserMessage=users.some(n=>switched.test(n.innerText||n.textContent||''));
|
|
82
|
+
const accountSwitchVisible=!inUserMessage&&mains.some(m=>
|
|
83
|
+
switched.test(m.innerText||m.textContent||''));
|
|
84
|
+
return {path:location.pathname,readyState:document.readyState,
|
|
85
|
+
uiErrorCode:accountSwitchVisible?'ACCOUNT_SWITCHED_RETRY_REQUIRED':null,
|
|
86
|
+
mainCount:mains.length,editorCount:editors.length,
|
|
87
|
+
editorVisible:Boolean(editor),editorEditable:Boolean(editor?.isContentEditable),
|
|
88
|
+
editorEmpty:editor?!(editor.innerText||editor.textContent||'').trim():null,
|
|
89
|
+
messageNodeCount:messages.length,
|
|
90
|
+
// Read-only identity and equality evidence. No message text or send permit.
|
|
91
|
+
userMessageCount:users.length,assistantMessageCount:assistants.length,
|
|
92
|
+
startPromptComparison:comparable?'AVAILABLE':'UNAVAILABLE',
|
|
93
|
+
matchedStartPromptCount:comparable?new Set(matched.map(messageId)).size:null,
|
|
94
|
+
lastUserKey:key('user:',users.at(-1)),
|
|
95
|
+
lastMatchedUserKey:key('user:',matched.at(-1)),
|
|
96
|
+
lastAssistantKey:key('assistant:',assistants.at(-1))};
|
|
97
|
+
},args:[typeof run.startPromptDigest==='string'?run.startPromptDigest:null]
|
|
98
|
+
}).then(rows=>rows?.[0]?.result||null).catch(()=>null),
|
|
99
|
+
new Promise(resolve=>setTimeout(()=>resolve(null),1500))
|
|
100
|
+
]);
|
|
101
|
+
return {tabId:tab.id,confirmed:false,sendReceipt:'UNVERIFIED',
|
|
102
|
+
pageState:tab.url==='https://chatgpt.com/'?'BLANK_HOME':'CHANGED_UNVERIFIED',
|
|
103
|
+
...(result&&typeof result.mainCount==='number'?{readiness:result}:{})};
|
|
104
|
+
}
|
|
105
|
+
async function sessionStatus(message,sender){
|
|
106
|
+
if(!sessionPage(sender,'status',message.requestId))
|
|
107
|
+
return {status:'DENIED',code:'INVALID_STATUS_SOURCE'};
|
|
108
|
+
const run=await readRun();
|
|
109
|
+
const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read',
|
|
110
|
+
...(message.auditDispatchParent?{sourceRequestId:message.requestId,
|
|
111
|
+
traceParent:message.auditDispatchParent}:{})}).catch(()=>null);
|
|
112
|
+
if(disk?.status!=='OK')return {status:'UNVERIFIED',code:'SESSION_STATE_UNVERIFIED'};
|
|
113
|
+
const projection=run?.sessionId?sessionProjection(run):null;
|
|
114
|
+
if(projection&&!matchesNativeProjection(projection,disk.session))
|
|
115
|
+
return {status:'UNVERIFIED',code:'SESSION_FILE_MISMATCH'};
|
|
116
|
+
if(!run?.sessionId&&disk.session&&disk.session.phase!=='DONE')
|
|
117
|
+
return {status:'UNVERIFIED',code:'SESSION_OWNER_MISMATCH'};
|
|
118
|
+
if(run&&run.phase!=='DONE'&&!run.sessionId)
|
|
119
|
+
return {status:'OK',state:'LEGACY_OWNER',phase:run.phase};
|
|
120
|
+
if(run?.phase==='DONE'&&!terminalFenceVerified(run))
|
|
121
|
+
return {status:'UNVERIFIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
|
|
122
|
+
if(!run||run.phase==='DONE')return {status:'OK',state:'IDLE',
|
|
123
|
+
...(disk.session?{lastSession:disk.session}:{} )};
|
|
124
|
+
const record=sessionProjection(run);
|
|
125
|
+
// Native validates the private project binding; Status only forwards its
|
|
126
|
+
// read-only verified reference for the SAME active owner.
|
|
127
|
+
const projectContext=disk.contextStatus==='VERIFIED'
|
|
128
|
+
&&disk.projectContext?.projectId===run.projectId
|
|
129
|
+
?disk.projectContext:null;
|
|
130
|
+
if(record.activeChatId&&['WAITING_REPLY','BLOCKED'].includes(run.phase)){
|
|
131
|
+
const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
|
|
132
|
+
if(!tab||pathOf(tab.url)!==run.page)
|
|
133
|
+
return {status:'UNVERIFIED',code:'OWNER_TAB_MISSING',session:record};
|
|
134
|
+
}
|
|
135
|
+
// Identity comes from the verified Worker projection, but updatedAt is
|
|
136
|
+
// Native's durable CAS revision. Never report a synthetic timestamp as a
|
|
137
|
+
// usable recovery credential.
|
|
138
|
+
const tabEvidence=await handoffTabEvidence(run);
|
|
139
|
+
const startEvidence=await startReadinessEvidence(run);
|
|
140
|
+
return {status:'OK',state:run.phase==='BLOCKED'?'BLOCKED':'ACTIVE',session:disk.session,
|
|
141
|
+
diagnostics:{extensionVersion:chrome.runtime.getManifest?.().version||null,
|
|
142
|
+
...(tabEvidence?{handoffTabEvidence:tabEvidence}:{}),
|
|
143
|
+
...(startEvidence?{startReadinessEvidence:startEvidence}:{}),
|
|
144
|
+
...(run.lastStartFailureCode?{lastStartFailureCode:run.lastStartFailureCode}:{}),
|
|
145
|
+
// The numeric tab ID is a locator, never a send capability. Expose only
|
|
146
|
+
// for an exactly verified terminal/awaiting Owner, not a guessed tab.
|
|
147
|
+
ownerTabId:['WAITING_REPLY','BLOCKED'].includes(run.phase)?run.tabId:null,
|
|
148
|
+
reason:run.reason||null,action:run.action||null,
|
|
149
|
+
userKey:run.userKey||null,assistantKey:run.assistantKey||null,
|
|
150
|
+
newUserKey:run.newUserKey||null,recoveryAttempts:run.recoveryAttempts||0,
|
|
151
|
+
...(projectContext?{projectContext}:{}),
|
|
152
|
+
recoveryMode:run.recoveryMode||null,recoveryProtocol:run.recoveryProtocol||null,
|
|
153
|
+
recoverySourceAssistantKey:run.recoverySourceAssistantKey||null,
|
|
154
|
+
startedAt:run.startedAt||null,
|
|
155
|
+
deadlineAt:deadlineOf(run),lastManualFeedback:run.lastManualFeedback||null}};
|
|
156
|
+
}
|
|
157
|
+
async function expireStaleAction() {
|
|
158
|
+
const run=await readRun();
|
|
159
|
+
if(!['STARTING','RESERVED','PENDING'].includes(run?.phase)
|
|
160
|
+
|| !Number.isSafeInteger(run.actionPendingAt)
|
|
161
|
+
|| Date.now()-run.actionPendingAt<((run.action==='START'||run.action==='HANDOFF')
|
|
162
|
+
?330000:180000)) return;
|
|
163
|
+
// No action may be recreated or re-sent on a missing receipt. Keep the Chat.
|
|
164
|
+
await saveRun({...run,phase:'BLOCKED',reason:'ACTION_RESULT_TIMEOUT_UNVERIFIED'});
|
|
165
|
+
}
|
|
166
|
+
async function prepareHandoffIfDue() {
|
|
167
|
+
const run = await readRun();
|
|
168
|
+
const deadlineAt = deadlineOf(run);
|
|
169
|
+
if (!clockActive(run) || run.handoffPending || deadlineAt === null
|
|
170
|
+
|| Date.now() < deadlineAt) return;
|
|
171
|
+
await saveRun({...run, handoffPending: true,
|
|
172
|
+
handoffPendingAt: Date.now()});
|
|
173
|
+
}
|
|
174
|
+
// Chrome preserves a content script's original document sender.url across SPA
|
|
175
|
+
// / → /c/... navigation. Authenticate its origin, then read the CURRENT tab URL.
|
|
176
|
+
const eligible = async (sender, page) => {
|
|
177
|
+
if (!Number.isInteger(sender.tab?.id) || typeof page !== "string"
|
|
178
|
+
|| pathOf("https://chatgpt.com" + page) !== page) return false;
|
|
179
|
+
try {
|
|
180
|
+
if (new URL(sender.url).origin !== "https://chatgpt.com") return false;
|
|
181
|
+
const tab = await chrome.tabs.get(sender.tab.id);
|
|
182
|
+
return pathOf(tab.url) === page;
|
|
183
|
+
} catch { return false; }
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
// Reuse the existing Observer read channel. This checks ONLY the latest
|
|
187
|
+
// assistant Turn in the current owned Chat, not historical forms or composer
|
|
188
|
+
// fields. An unknown read is never evidence of approval.
|
|
189
|
+
async function currentConfirmation(tabId,page,userKey,assistantKey) {
|
|
190
|
+
const tab=await chrome.tabs.get(tabId).catch(()=>null);
|
|
191
|
+
if(pathOf(tab?.url)!==page)return null;
|
|
192
|
+
const proof=await chrome.tabs.sendMessage(tabId,
|
|
193
|
+
{type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
|
|
194
|
+
if(proof?.contract!=="chat-loop.turn-observer.v1"
|
|
195
|
+
||proof.page!==page||proof.userKey!==userKey
|
|
196
|
+
||proof.assistantKey!==assistantKey
|
|
197
|
+
||proof.reason==="WAITING_CHAT_HYDRATION"
|
|
198
|
+
||typeof proof.pendingConfirmation!=="boolean")return null;
|
|
199
|
+
return proof.pendingConfirmation;
|
|
200
|
+
}
|
|
201
|
+
// A transient partial UI snapshot may end with UNKNOWN even when the same
|
|
202
|
+
// already-confirmed reply later settles on a valid final status. Only resample
|
|
203
|
+
// the exact in-flight user/assistant turn, read-only, before failing closed.
|
|
204
|
+
async function recheckUnknownTurn(message, previous, tabId) {
|
|
205
|
+
if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== tabId
|
|
206
|
+
|| previous.page !== message.page || previous.newUserKey !== message.userKey
|
|
207
|
+
|| previous.assistantKey === message.assistantKey) return null;
|
|
208
|
+
const read = async () => {
|
|
209
|
+
const tab = await chrome.tabs.get(tabId).catch(() => null);
|
|
210
|
+
if (pathOf(tab?.url) !== message.page) return null;
|
|
211
|
+
const proof = await chrome.tabs.sendMessage(tabId,
|
|
212
|
+
{type: "CHAT_LOOP_TURN_VERIFY_V1"}).catch(() => null);
|
|
213
|
+
if (proof?.contract !== "chat-loop.turn-observer.v1" || proof.status !== "READY"
|
|
214
|
+
|| proof.page !== message.page || proof.userKey !== message.userKey
|
|
215
|
+
|| proof.assistantKey !== message.assistantKey
|
|
216
|
+
|| typeof proof.replyText !== "string") return null;
|
|
217
|
+
return proof.replyText;
|
|
218
|
+
};
|
|
219
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
220
|
+
const first = await read();
|
|
221
|
+
if (first === null) return null;
|
|
222
|
+
const parsed = workerApi.parseStatus(first);
|
|
223
|
+
if (parsed !== "UNKNOWN") {
|
|
224
|
+
await new Promise(resolve => setTimeout(resolve, 2300));
|
|
225
|
+
const second = await read();
|
|
226
|
+
if (second === first) return {status: parsed, replyText: second};
|
|
227
|
+
} else {
|
|
228
|
+
await new Promise(resolve => setTimeout(resolve, 1500));
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
// A suspended MV3 Worker may lose the Action receipt. Never retry a send
|
|
234
|
+
// from a stale RESERVED/PENDING phase; scrub the queued task text and block.
|
|
235
|
+
async function expireStaleModelIntent() {
|
|
236
|
+
const run=await readRun();
|
|
237
|
+
if(!run?.modelIntent || !Number.isSafeInteger(run.modelIntent.queuedAt)
|
|
238
|
+
||Date.now()-run.modelIntent.queuedAt<=MODEL_RECEIPT_TTL_MS)return;
|
|
239
|
+
const pendingSend=["RESERVED","PENDING"].includes(run.phase);
|
|
240
|
+
const next=settleModelIntent(run,"STALE_UNVERIFIED","INTENT_TTL_EXPIRED");
|
|
241
|
+
await saveRun(pendingSend
|
|
242
|
+
?{...next,phase:"BLOCKED",reason:"STALE_INTENT_UNKNOWN_SEND"}
|
|
243
|
+
:next);
|
|
244
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Chat Loop Worker — router. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
+
// Read-only target resolver for a CLI-created formal Eye Action.
|
|
3
|
+
// This never starts a Loop, changes Owner, or sends a chat message.
|
|
4
|
+
async function onExtensionCliTarget(message,sender) {
|
|
5
|
+
const entry=workerApi.eyeCatalog?.[message?.action];
|
|
6
|
+
const page=entry?.page;
|
|
7
|
+
// Catalog only grants the existing read-only Eye permission category. It
|
|
8
|
+
// does not register new send/Owner/Native control message handlers.
|
|
9
|
+
if(!['eye-read','eye-screenshot','eye-reload'].includes(entry?.kind))
|
|
10
|
+
return {status:'DENIED',code:'INVALID_EXTENSION_ACTION_SOURCE'};
|
|
11
|
+
if(!page || !/^[a-f0-9]{32}$/.test(message?.id||"")
|
|
12
|
+
|| sender.url !== chrome.runtime.getURL(page)+"?requestId="+message.id)
|
|
13
|
+
return {status:"DENIED",code:"INVALID_EXTENSION_ACTION_SOURCE"};
|
|
14
|
+
if(message.action==="reload")return {status:"OK"};
|
|
15
|
+
const run=await readRun();
|
|
16
|
+
// A failed first send has no Chat Owner. Eye may inspect only the exact
|
|
17
|
+
// unconfirmed tab created by this START, and only after verifying its
|
|
18
|
+
// original prompt fingerprint. No ownership, recovery or send is granted.
|
|
19
|
+
if(run?.phase==='BLOCKED'&&run.action==='START'
|
|
20
|
+
&&run.lastStartFailureCode==='FIRST_SEND_RECEIPT_UNKNOWN'){
|
|
21
|
+
const evidence=await startReadinessEvidence(run);
|
|
22
|
+
const observed=evidence?.readiness;
|
|
23
|
+
if(evidence?.sendReceipt==='UNVERIFIED'
|
|
24
|
+
&&observed?.startPromptComparison==='AVAILABLE'
|
|
25
|
+
&&observed.matchedStartPromptCount===1
|
|
26
|
+
&&observed.userMessageCount>=1
|
|
27
|
+
&&typeof observed.path==='string'&&observed.path.startsWith('/c/')){
|
|
28
|
+
const candidate=await chrome.tabs.get(evidence.tabId).catch(()=>null);
|
|
29
|
+
// pathOf deliberately rejects provisional local-chatgpt paths for
|
|
30
|
+
// Ownership. Eye instead checks the exact observed HTTPS path only.
|
|
31
|
+
try {
|
|
32
|
+
const url=new URL(candidate?.url);
|
|
33
|
+
if(url.origin==='https://chatgpt.com'&&url.pathname===observed.path)
|
|
34
|
+
return {status:'OK',tabId:candidate.id,page:observed.path};
|
|
35
|
+
} catch { /* A changed or malformed tab is not a read target. */ }
|
|
36
|
+
}
|
|
37
|
+
return {status:'DENIED',code:'START_EYE_EVIDENCE_UNVERIFIED'};
|
|
38
|
+
}
|
|
39
|
+
// Read-only Eye may inspect the last confirmed terminal Owner while the same
|
|
40
|
+
// Chat URL and exact tab still match. This does not reactivate the Loop,
|
|
41
|
+
// grant Continue/Handoff permission or select another Chat tab.
|
|
42
|
+
const finishedOwned = ["DONE","BLOCKED"].includes(run?.phase)
|
|
43
|
+
&& /^user:[^\s]{8,}$/.test(run.userKey || "")
|
|
44
|
+
&& /^assistant:[^\s]{8,}$/.test(run.assistantKey || "");
|
|
45
|
+
if(!(run?.phase === "WAITING_REPLY" || finishedOwned) || !Number.isInteger(run.tabId)
|
|
46
|
+
|| typeof run.page!=="string")
|
|
47
|
+
return {status:"DENIED",code:"NO_ACTIVE_CHAT_OWNER"};
|
|
48
|
+
const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
|
|
49
|
+
if(!tab || pathOf(tab.url)!==run.page)
|
|
50
|
+
return {status:"DENIED",code:"OWNER_CHANGED"};
|
|
51
|
+
return {status:"OK",tabId:run.tabId,page:run.page};
|
|
52
|
+
}
|
|
53
|
+
// One explicit router for authenticated, serialized state changes.
|
|
54
|
+
// The registered handler still verifies source, token, Owner and Turn identity.
|
|
55
|
+
const SERIAL_ROUTES=new Map([
|
|
56
|
+
['CHAT_LOOP_TURN_FINISHED_V1',onTurnFinished],
|
|
57
|
+
['CHAT_LOOP_TURN_BLOCKED_V1',onTurnBlocked],
|
|
58
|
+
['CHAT_LOOP_ACTION_TAKE_V1',onTake],
|
|
59
|
+
['CHAT_LOOP_ACTION_RESULT_V1',onResult],
|
|
60
|
+
['CHAT_LOOP_HANDOFF_SEND_BEGIN_V1',onHandoffSendBegin],
|
|
61
|
+
['CHAT_LOOP_ADOPT_KICKOFF_PREPARE_V1',onAdoptKickoffPrepare],
|
|
62
|
+
['CHAT_LOOP_ADOPT_BASELINE_REPAIR_V1',onAdoptBaselineRepair],
|
|
63
|
+
['CHAT_LOOP_ACTION_MANUAL_REVEAL_V1',onManualReveal],
|
|
64
|
+
['CHAT_LOOP_ACTION_MANUAL_PREPARE_V1',onManualPrepare],
|
|
65
|
+
['CHAT_LOOP_MODEL_INTENT_V1',onModelIntent],
|
|
66
|
+
['CHAT_LOOP_MODEL_INTENT_STATUS_V1',onModelIntentStatus],
|
|
67
|
+
['CHAT_LOOP_SESSION_START_PREPARE_V1',sessionStartPrepare],
|
|
68
|
+
['CHAT_LOOP_SESSION_START_TAKE_V1',sessionStartTake],
|
|
69
|
+
['CHAT_LOOP_SESSION_START_RESULT_V1',sessionStartResult],
|
|
70
|
+
['CHAT_LOOP_SESSION_STATUS_V1',sessionStatus],
|
|
71
|
+
['CHAT_LOOP_RESOURCE_CHAT_V1',resourceChatGate]
|
|
72
|
+
|
|
73
|
+
]);
|
|
74
|
+
const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
|
|
75
|
+
const type=message?.type;
|
|
76
|
+
const handle=SERIAL_ROUTES.get(type);
|
|
77
|
+
if(handle){
|
|
78
|
+
void serial(async()=>{
|
|
79
|
+
let result;
|
|
80
|
+
try{result=await handle(type==='CHAT_LOOP_SESSION_STATUS_V1'
|
|
81
|
+
?{...message,auditDispatchParent:dispatchParent}:message,sender);}
|
|
82
|
+
catch(error){result={status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'};}
|
|
83
|
+
// A bounded diagnostic receipt, never permission or a second state store.
|
|
84
|
+
// In particular a rejected manual recovery must be observable remotely.
|
|
85
|
+
if(type==='CHAT_LOOP_ACTION_MANUAL_PREPARE_V1'){
|
|
86
|
+
const current=await readRun();
|
|
87
|
+
if(current)await chrome.storage.local.set({[RUN_KEY]:{...current,
|
|
88
|
+
lastManualFeedback:{status:result.status,
|
|
89
|
+
code:/^[A-Z0-9_]{1,100}$/.test(result.code||'')?result.code:null,at:Date.now()}}});
|
|
90
|
+
}
|
|
91
|
+
return result;
|
|
92
|
+
}).then(reply,error=>reply({status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'}));
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
if (type === 'CHAT_LOOP_POPUP_CLEAN_OPEN_V1') {
|
|
96
|
+
void serial(()=>openPopupClean(message,sender)).then(reply,
|
|
97
|
+
()=>reply({status:'BLOCKED',code:'CLEAN_ACTION_UNVERIFIED'}));
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
if (type === "CHAT_LOOP_EXTENSION_TARGET_V1") {
|
|
101
|
+
void onExtensionCliTarget(message,sender).then(reply,
|
|
102
|
+
()=>reply({status:"DENIED",code:"OWNER_UNVERIFIED"}));
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
if (type !== "CHAT_LOOP_EYE_RELOAD_V1") return false;
|
|
106
|
+
const id = sender.tab?.id;
|
|
107
|
+
void (async () => {
|
|
108
|
+
try {
|
|
109
|
+
if (!Number.isInteger(id)) throw Error("NO_ACTION_TAB");
|
|
110
|
+
const tab = await chrome.tabs.get(id);
|
|
111
|
+
const reloadBase=chrome.runtime.getURL("reload.html");
|
|
112
|
+
if (!tab.url.startsWith(reloadBase) ||
|
|
113
|
+
(tab.url!==reloadBase &&
|
|
114
|
+
!/^\?requestId=[a-f0-9]{32}$/.test(tab.url.slice(reloadBase.length))))
|
|
115
|
+
throw Error("INVALID_RELOAD_SOURCE");
|
|
116
|
+
reply({status: "ACCEPTED"});
|
|
117
|
+
await chrome.tabs.remove(id);
|
|
118
|
+
// Reload terminates pending MV3 Native Messaging Promises immediately.
|
|
119
|
+
// Each span's terminal record follows its BEGIN across a one-shot
|
|
120
|
+
// Native process, which can take longer than a single 300-ms drain.
|
|
121
|
+
// The business receipt is already sent; only soft audit transport
|
|
122
|
+
// may run until this bounded teardown deadline (never retry Action).
|
|
123
|
+
try{
|
|
124
|
+
const deadline=Date.now()+2300;
|
|
125
|
+
while(Date.now()<deadline){
|
|
126
|
+
if(await workerApi.audit.drain(Math.min(700,deadline-Date.now())))break;
|
|
127
|
+
const health=workerApi.audit.health();
|
|
128
|
+
if(health.pending===0&&health.inFlight===0)break;
|
|
129
|
+
}
|
|
130
|
+
}catch{/* Audit cannot change the accepted business result. */}
|
|
131
|
+
chrome.runtime.reload();
|
|
132
|
+
} catch (error) {reply({status: "FAILED", code: error.message});}
|
|
133
|
+
})();
|
|
134
|
+
return true;
|
|
135
|
+
};
|
|
136
|
+
chrome.runtime.onMessage.addListener((message,sender,reply)=>{
|
|
137
|
+
const type=typeof message?.type==='string'&&
|
|
138
|
+
/^CHAT_LOOP_[A-Z0-9_]{2,90}$/.test(message.type)
|
|
139
|
+
?message.type:'unknown';
|
|
140
|
+
// Dispatch is a synchronous acceptance marker, not an Action result.
|
|
141
|
+
// Capture its safe span ID before invoking the original handler so that
|
|
142
|
+
// a later async reply can be independently audited as its child.
|
|
143
|
+
let dispatchSpan=null;
|
|
144
|
+
const respond=result=>{
|
|
145
|
+
try{return reply(result);}
|
|
146
|
+
finally{
|
|
147
|
+
try{
|
|
148
|
+
const rejected=['DENIED','BLOCKED','FAILED','UNVERIFIED']
|
|
149
|
+
.includes(result?.status);
|
|
150
|
+
const code=typeof result?.code==='string'&&
|
|
151
|
+
/^[A-Z][A-Z0-9_]{1,95}$/.test(result.code)
|
|
152
|
+
?result.code:'BROWSER_REPLY_REJECTED';
|
|
153
|
+
workerApi.audit.observe('browser.reply.'+type,()=>{
|
|
154
|
+
if(rejected)throw Object.assign(Error('Reply rejected'),{code});
|
|
155
|
+
return true;
|
|
156
|
+
},'browser',{parent:dispatchSpan})();
|
|
157
|
+
}catch{/* Reply telemetry cannot change the browser callback. */}
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
// Only the known, exact status Action may offer an AOP parent. The
|
|
161
|
+
// existing sessionPage/Owner gate still independently checks the request.
|
|
162
|
+
const sourceId=message?.requestId||message?.id;
|
|
163
|
+
const actionSource=/^[a-f0-9]{32}$/.test(sourceId||'')&&(
|
|
164
|
+
type==='CHAT_LOOP_SESSION_STATUS_V1'&&
|
|
165
|
+
sender?.url===chrome.runtime.getURL('status.html')+'?requestId='+sourceId||
|
|
166
|
+
['CHAT_LOOP_MODEL_INTENT_V1','CHAT_LOOP_MODEL_INTENT_STATUS_V1']
|
|
167
|
+
.includes(type)&&['CONTINUE','HANDOFF'].includes(message?.action)&&
|
|
168
|
+
sender?.url===chrome.runtime.getURL(message.action.toLowerCase()+'.html')+
|
|
169
|
+
'?requestId='+sourceId||
|
|
170
|
+
['CHAT_LOOP_SESSION_START_PREPARE_V1','CHAT_LOOP_SESSION_START_TAKE_V1',
|
|
171
|
+
'CHAT_LOOP_SESSION_START_RESULT_V1'].includes(type)&&
|
|
172
|
+
sender?.url===chrome.runtime.getURL('start.html')+'?requestId='+sourceId);
|
|
173
|
+
return workerApi.audit.observe('browser.dispatch.'+type,
|
|
174
|
+
// Read dispatchSpan only when the AOP invokes its target: onBegin has
|
|
175
|
+
// already allocated the child Span. Passing it as an eager argument
|
|
176
|
+
// captures undefined before onBegin and breaks Native parent linkage.
|
|
177
|
+
(msg,src,cb)=>onBrowserMessage(msg,src,cb,dispatchSpan),'browser',{
|
|
178
|
+
...(actionSource&&message.traceParent?{parent:message.traceParent}:{}),
|
|
179
|
+
onBegin:ids=>{dispatchSpan=ids;}
|
|
180
|
+
})(message,sender,respond);
|
|
181
|
+
});
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Chat Loop Worker — scheduler. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
+
// Extension updates invalidate previous injected listeners. Reconnect only its own observers.
|
|
3
|
+
async function reconnectOpenChats() {
|
|
4
|
+
const tabs = await chrome.tabs.query({url: "https://chatgpt.com/*"});
|
|
5
|
+
for (const tab of tabs) {
|
|
6
|
+
if (!Number.isInteger(tab.id) || !pathOf(tab.url) && !/^https:\/\/chatgpt\.com\/$/.test(tab.url)) continue;
|
|
7
|
+
try {
|
|
8
|
+
await chrome.scripting.executeScript({target: {tabId: tab.id},
|
|
9
|
+
files: ["content.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
|
|
10
|
+
const owner = await readRun();
|
|
11
|
+
if (owner?.phase === "WAITING_REPLY" && owner.tabId === tab.id
|
|
12
|
+
&& owner.page === pathOf(tab.url) && owner.newUserKey) {
|
|
13
|
+
// Normal WAITING_REPLY uses its original zero-extra-read resume.
|
|
14
|
+
// Only a previously seen pending confirmation needs an extra DOM
|
|
15
|
+
// identity check for a human response that arrived during reload.
|
|
16
|
+
const proof=owner.reason==="PENDING_CONFIRMATION_DOM"
|
|
17
|
+
? await chrome.tabs.sendMessage(tab.id,
|
|
18
|
+
{type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null)
|
|
19
|
+
:null;
|
|
20
|
+
const freshUser=proof?.page===owner.page
|
|
21
|
+
&& proof.userKey!==owner.newUserKey
|
|
22
|
+
&& proof.priorAssistantKey===owner.assistantKey
|
|
23
|
+
&& proof.priorAssistantUserKey===owner.userKey
|
|
24
|
+
&& proof.directReplyAfterPriorAssistant===true;
|
|
25
|
+
const res = await chrome.tabs.sendMessage(tab.id, {
|
|
26
|
+
type: "CHAT_LOOP_TURN_RESUME_V1", page: owner.page,
|
|
27
|
+
userKey:freshUser?proof.userKey:owner.newUserKey,
|
|
28
|
+
assistantKey: owner.assistantKey || null,
|
|
29
|
+
...(owner.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
|
|
30
|
+
startedAt: owner.startedAt
|
|
31
|
+
}).catch(() => null);
|
|
32
|
+
if (res?.status !== "RESUMED" && res?.status !== "ALREADY_MONITORING")
|
|
33
|
+
console.warn("Chat Loop pending Turn resume not yet verified:", res?.reason || res?.status);
|
|
34
|
+
}
|
|
35
|
+
} catch (error) {console.warn("Chat Loop observer reconnect unavailable:", error?.message);}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// MV3 background service workers can suspend, and hidden-page setInterval
|
|
39
|
+
// may be throttled. An alarm asks the Observer to sample, never acts directly.
|
|
40
|
+
async function ensureAlarm() {
|
|
41
|
+
if (!chrome.alarms?.create) return;
|
|
42
|
+
const existing = await chrome.alarms.get?.(ALARM_NAME).catch(() => null);
|
|
43
|
+
if (!existing) await chrome.alarms.create(ALARM_NAME, {periodInMinutes: 1});
|
|
44
|
+
}
|
|
45
|
+
async function watchActiveTurn() {
|
|
46
|
+
// One bounded reconciliation on the existing 1-minute Worker alarm.
|
|
47
|
+
await serial(async()=>{await expireStaleAction();
|
|
48
|
+
await resources.reconcile(await readRun()).catch(()=>{});});
|
|
49
|
+
// Normal periodic wakeups also reconcile a delayed one-shot deadline.
|
|
50
|
+
// All state changes share the same serial queue as Turn/Action receipts.
|
|
51
|
+
await serial(async()=>{await expireStaleModelIntent();await prepareHandoffIfDue();});
|
|
52
|
+
const run = await readRun();
|
|
53
|
+
// While an Action is pending, never dispatch competing operations.
|
|
54
|
+
if (run && ["RESERVED", "PENDING"].includes(run.phase)) return;
|
|
55
|
+
const tabs = run?.phase === "WAITING_REPLY"
|
|
56
|
+
? [await chrome.tabs.get(run.tabId).catch(() => null)]
|
|
57
|
+
: await chrome.tabs.query({url: "https://chatgpt.com/*"});
|
|
58
|
+
for (const tab of tabs) {
|
|
59
|
+
if (!tab?.id || !pathOf(tab.url)) continue;
|
|
60
|
+
try {
|
|
61
|
+
const proof = await chrome.tabs.sendMessage(tab.id,
|
|
62
|
+
{type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true});
|
|
63
|
+
// A reloaded Observer may have mistaken the in-flight user Turn for
|
|
64
|
+
// historical baseline. Its IDLE state is not proof of completion.
|
|
65
|
+
// Rebind the exact persisted owner using read-only verification.
|
|
66
|
+
const freshHuman=run?.phase==="WAITING_REPLY" && run.tabId===tab.id
|
|
67
|
+
&& proof?.page===run.page && proof.userKey!==run.newUserKey
|
|
68
|
+
&& proof.priorAssistantKey===run.assistantKey
|
|
69
|
+
&& proof.priorAssistantUserKey===run.userKey
|
|
70
|
+
&& proof.directReplyAfterPriorAssistant===true;
|
|
71
|
+
if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
|
|
72
|
+
&& proof?.page === run.page
|
|
73
|
+
&& (proof.userKey === run.newUserKey || freshHuman)
|
|
74
|
+
&& (proof.status === "IDLE"
|
|
75
|
+
|| proof.status === "UNKNOWN"
|
|
76
|
+
&& ["ATTACHING_CHAT", "WAITING_CHAT_HYDRATION"].includes(proof.reason))) {
|
|
77
|
+
await chrome.tabs.sendMessage(tab.id, {
|
|
78
|
+
type: "CHAT_LOOP_TURN_RESUME_V1", page: run.page,
|
|
79
|
+
userKey: freshHuman?proof.userKey:run.newUserKey,
|
|
80
|
+
assistantKey: run.assistantKey || null,
|
|
81
|
+
...(run.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
|
|
82
|
+
startedAt: run.startedAt
|
|
83
|
+
}).catch(() => null);
|
|
84
|
+
}
|
|
85
|
+
// A human response can fail after the previous question was kept in
|
|
86
|
+
// WAITING_REPLY. Do not let this become an indefinite silent wait.
|
|
87
|
+
if(freshHuman && proof.status==="BLOCKED") {
|
|
88
|
+
void serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
|
|
89
|
+
reason:proof.reason||"PAGE_ERROR"},
|
|
90
|
+
{tab,url:tab.url}));
|
|
91
|
+
}
|
|
92
|
+
// Alarm is still read-only. It may reconcile a verified page failure if
|
|
93
|
+
// the observer's original notification was lost while Worker slept.
|
|
94
|
+
if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
|
|
95
|
+
&& proof?.status === "BLOCKED" && ["PAGE_ERROR","CONTEXT_LIMIT","SECURITY_CHALLENGE"].includes(proof.reason)
|
|
96
|
+
&& proof.page === run.page && proof.userKey === run.newUserKey) {
|
|
97
|
+
void serial(() => onTurnBlocked({page: run.page,
|
|
98
|
+
userKey: run.newUserKey, reason: proof.reason},
|
|
99
|
+
{tab, url: tab.url}));
|
|
100
|
+
}
|
|
101
|
+
} catch { /* Observer unavailable; never infer Turn completion. */ }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
chrome.alarms?.onAlarm?.addListener(alarm => {
|
|
105
|
+
if (alarm?.name === ALARM_NAME) void watchActiveTurn();
|
|
106
|
+
if (alarm?.name === DEADLINE_ALARM_NAME)
|
|
107
|
+
void serial(prepareHandoffIfDue);
|
|
108
|
+
});
|
|
109
|
+
chrome.runtime.onInstalled?.addListener(() => {
|
|
110
|
+
void ensureAlarm();
|
|
111
|
+
void serial(async()=>{await expireStaleAction();
|
|
112
|
+
await resources.reconcile(await readRun()).catch(()=>{});});
|
|
113
|
+
void reconnectOpenChats();
|
|
114
|
+
});
|
|
115
|
+
chrome.runtime.onStartup?.addListener(() => {
|
|
116
|
+
void ensureAlarm();
|
|
117
|
+
void serial(async()=>{await expireStaleAction();
|
|
118
|
+
await resources.reconcile(await readRun()).catch(()=>{});});
|
|
119
|
+
void reconnectOpenChats();
|
|
120
|
+
});
|
|
121
|
+
void ensureAlarm();
|
|
122
|
+
// Reconcile an elapsed deadline after MV3 Worker suspension/reload.
|
|
123
|
+
void serial(async()=>{await expireStaleAction();
|
|
124
|
+
await resources.reconcile(await readRun()).catch(()=>{});
|
|
125
|
+
await prepareHandoffIfDue();});
|
|
126
|
+
// A manual extension Reload does not necessarily fire onInstalled/onStartup.
|
|
127
|
+
// Reattach the two idempotent read-only scripts to existing ChatGPT tabs.
|
|
128
|
+
void reconnectOpenChats();
|
|
129
|
+
// User-clicked popup Clean must share the same Action quota as Worker actions.
|
|
130
|
+
// The popup cannot create extra Chrome tabs directly.
|
|
131
|
+
async function openPopupClean(message,sender) {
|
|
132
|
+
if(sender?.url!==chrome.runtime.getURL('popup.html')
|
|
133
|
+
||!Number.isSafeInteger(message?.tabId)||message.tabId<=0)
|
|
134
|
+
return {status:'DENIED',code:'POPUP_SOURCE_INVALID'};
|
|
135
|
+
const target=await chrome.tabs.get(message.tabId).catch(()=>null);
|
|
136
|
+
let valid=false;
|
|
137
|
+
try {valid=target?.active===true && Number.isSafeInteger(target.windowId)
|
|
138
|
+
&& new URL(target.url).origin==='https://chatgpt.com';} catch {}
|
|
139
|
+
if(!valid)return {status:'DENIED',code:'CLEAN_TARGET_UNVERIFIED'};
|
|
140
|
+
try {
|
|
141
|
+
const action=await createBoundedAction({url:chrome.runtime.getURL('clean.html')
|
|
142
|
+
+'?tabId='+target.id,windowId:target.windowId,active:true});
|
|
143
|
+
return {status:'OK',actionTabId:action.id};
|
|
144
|
+
} catch(error) {
|
|
145
|
+
return {status:'BLOCKED',code:error?.message||'CLEAN_ACTION_UNVERIFIED'};
|
|
146
|
+
}
|
|
147
|
+
}
|