@tomflow/chatloop-extension 0.3.84 → 0.4.0
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/README.md +74 -73
- package/actions.generated.mjs +11 -0
- package/bin/cli.mjs +22 -24
- package/bin/native-host.mjs +14 -5
- package/capabilities/chat_dom.mjs +1 -0
- package/capabilities/chat_screenshot.mjs +1 -0
- package/capabilities/chat_text.mjs +1 -0
- package/capabilities/clean.mjs +1 -0
- package/capabilities/continue.mjs +1 -0
- package/capabilities/handoff.mjs +1 -0
- package/capabilities/reload.mjs +1 -0
- package/capabilities/start.mjs +1 -0
- package/capabilities/status.mjs +1 -0
- package/extension/actions/common.js +14 -3
- package/extension/actions/continue.js +1 -1
- package/extension/actions/handoff.js +5 -3
- package/extension/actions/index.js +2 -0
- package/extension/actions/read-mode.js +9 -0
- package/extension/actions/start.js +1 -1
- package/extension/background.js +16 -2202
- package/extension/loop/action-catalog.generated.js +2 -0
- package/extension/loop/api-aspect.generated.js +192 -0
- package/extension/loop/core.js +81 -3
- package/extension/loop/index.js +34 -0
- package/extension/loop/observer-approval.js +227 -0
- package/extension/loop/observer-inspect.js +144 -0
- package/extension/loop/observer-poll.js +171 -0
- package/extension/loop/observer-recovery.js +109 -0
- package/extension/loop/observer.js +27 -630
- package/extension/loop/resources.js +8 -1
- package/extension/manifest.json +6 -2
- package/extension/worker/action-result.js +136 -0
- package/extension/worker/action-take.js +220 -0
- package/extension/worker/admission.js +122 -0
- package/extension/worker/adopt-prepare.js +155 -0
- package/extension/worker/adopt-recovery.js +185 -0
- package/extension/worker/adopt-result.js +120 -0
- package/extension/worker/bootstrap.js +172 -0
- package/extension/worker/manual.js +165 -0
- package/extension/worker/readiness.js +242 -0
- package/extension/worker/router.js +150 -0
- package/extension/worker/scheduler.js +147 -0
- package/extension/worker/turn-failure.js +197 -0
- package/extension/worker/turn-finished.js +200 -0
- package/index.mjs +62 -0
- package/lib/action-routing.mjs +18 -0
- package/lib/api-aspect.mjs +190 -0
- package/lib/bridge.mjs +26 -7
- package/lib/context-binding.mjs +6 -1
- package/lib/context-ipc.mjs +44 -2
- package/lib/owner-evidence.mjs +67 -0
- package/lib/session-file.mjs +20 -8
- package/package.json +13 -3
- package/scripts/build-actions.mjs +133 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// Chat Loop Worker — manual. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
+
async function onManualPrepare(message, sender) {
|
|
3
|
+
const requested = message.action;
|
|
4
|
+
if (!["CONTINUE", "HANDOFF"].includes(requested)
|
|
5
|
+
|| !Number.isInteger(sender.tab?.id)) return {status: "DENIED", code: "INVALID_MANUAL_ACTION"};
|
|
6
|
+
const filename = requested === "HANDOFF" ? "handoff.html" : "continue.html";
|
|
7
|
+
let url;
|
|
8
|
+
try { url = new URL(sender.url); } catch {return {status: "DENIED", code: "INVALID_ACTION_URL"};}
|
|
9
|
+
const rawTabId = url.searchParams.get("tabId");
|
|
10
|
+
// Explicit operator-only migration of 0.3.52's unsent recovery reservation.
|
|
11
|
+
// The old Native Host could NEVER commit BLOCKED -> PENDING. Operator must
|
|
12
|
+
// verify that installed-version provenance before supplying this disk CAS.
|
|
13
|
+
// Modern unknown sends are never eligible, even with the query parameter.
|
|
14
|
+
// Explicit repair acknowledgement binds the operator to the exact disk
|
|
15
|
+
// blocker. It does not claim that the browser can verify business repair.
|
|
16
|
+
const contextRaw=url.searchParams.get("recoverContextNotSentAt");
|
|
17
|
+
const contextAt=contextRaw!==null?Number(contextRaw):null;
|
|
18
|
+
if(contextRaw!==null&&(requested!=="CONTINUE"||!rawTabId
|
|
19
|
+
||!Number.isSafeInteger(contextAt)||contextAt<=0))
|
|
20
|
+
return {status:"DENIED",code:"INVALID_CONTEXT_NOT_SENT_RECOVERY"};
|
|
21
|
+
const resumeRaw=url.searchParams.get("resumeBlockedAt");
|
|
22
|
+
const resumeAt=resumeRaw!==null?Number(resumeRaw):null;
|
|
23
|
+
if(resumeRaw!==null&&(requested!=="CONTINUE"||!rawTabId
|
|
24
|
+
||!Number.isSafeInteger(resumeAt)||resumeAt<=0
|
|
25
|
+
||url.searchParams.has("repairLegacyReservation")))
|
|
26
|
+
return {status:"DENIED",code:"INVALID_BLOCKED_REPAIR"};
|
|
27
|
+
const legacyRaw=url.searchParams.get("repairLegacyReservation");
|
|
28
|
+
const legacyAt=legacyRaw!==null?Number(legacyRaw):null;
|
|
29
|
+
if(legacyRaw!==null&&(requested!=="CONTINUE"||!rawTabId
|
|
30
|
+
||!Number.isSafeInteger(legacyAt)||legacyAt<=0
|
|
31
|
+
||!String(legacyAt).match(/^[1-9][0-9]{12}$/)))
|
|
32
|
+
return {status:"DENIED",code:"INVALID_LEGACY_REPAIR"};
|
|
33
|
+
if (url.origin !== new URL(chrome.runtime.getURL(filename)).origin
|
|
34
|
+
|| url.pathname !== "/" + filename || url.searchParams.has("token")
|
|
35
|
+
|| Array.from(url.searchParams.keys()).some(key => key !== "tabId"&&key!=="repairLegacyReservation"&&key!=="resumeBlockedAt"
|
|
36
|
+
&&key!=="recoverContextNotSentAt")
|
|
37
|
+
|| url.searchParams.size!==new Set(url.searchParams.keys()).size
|
|
38
|
+
|| (rawTabId !== null && (!/^[1-9][0-9]*$/.test(rawTabId)
|
|
39
|
+
|| message.tabId !== Number(rawTabId))))
|
|
40
|
+
return {status: "DENIED", code: "INVALID_ACTION_URL"};
|
|
41
|
+
const previous = await repairUncommittedBlockedRecovery();
|
|
42
|
+
// Existing Owner may recover a *verified resolved* model-level tool blocker
|
|
43
|
+
// via the SAME built-in Continue Action. Never grant a new Owner or create
|
|
44
|
+
// a new conversation. This cannot recover unknown sends/page errors.
|
|
45
|
+
const legacyUnsent=Boolean(legacyAt&&previous?.sessionId
|
|
46
|
+
&&previous.phase==="BLOCKED"&&previous.action==="CONTINUE"
|
|
47
|
+
&&previous.reason==="ACTION_RESULT_TIMEOUT_UNVERIFIED"
|
|
48
|
+
&&previous.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
|
|
49
|
+
&&previous.recoveryAttempts===1&&!previous.recoveryProtocol
|
|
50
|
+
&&previous.newUserKey===previous.userKey
|
|
51
|
+
&&previous.recoverySourceAssistantKey===previous.assistantKey);
|
|
52
|
+
const contextNotSent=Boolean(contextAt&&requested==="CONTINUE"
|
|
53
|
+
&&previous?.sessionId&&previous.taskId&&previous.phase==="BLOCKED"
|
|
54
|
+
&&previous.action==="HANDOFF"
|
|
55
|
+
&&previous.reason==="CONTEXT_HANDOFF_NOT_SENT"
|
|
56
|
+
&&previous.contextHandoff?.sendOutcome==="NOT_SENT"
|
|
57
|
+
&&!previous.contextHandoff.sendBeginAt
|
|
58
|
+
&&Number.isSafeInteger(previous.contextHandoff.terminalActionResultAt)
|
|
59
|
+
&&previous.contextHandoff.attemptId===previous.token
|
|
60
|
+
&&!previous.contextRecoveryAttempted
|
|
61
|
+
&&previous.contextManaged
|
|
62
|
+
&&previous.contextHandoff.targetGeneration===(previous.generation||0)+1);
|
|
63
|
+
const recoveryCandidate=requested==="CONTINUE"
|
|
64
|
+
&&previous?.sessionId&&previous.phase==="BLOCKED"
|
|
65
|
+
&&Number.isInteger(previous.tabId)
|
|
66
|
+
&&(contextNotSent||legacyUnsent||previous.reason==="BLOCKED"
|
|
67
|
+
&&((previous.recoveryAttempts||0)===0||resumeAt
|
|
68
|
+
&&previous.recoverySourceAssistantKey!==previous.assistantKey));
|
|
69
|
+
if (previous && (previous.sessionId&&previous.phase!=="DONE"&&!recoveryCandidate
|
|
70
|
+
|| !["DONE", "BLOCKED"].includes(previous.phase)))
|
|
71
|
+
return {status: "DENIED", code: "LOOP_ALREADY_ACTIVE"};
|
|
72
|
+
const candidates = await chrome.tabs.query({url: "https://chatgpt.com/*"});
|
|
73
|
+
const all = candidates.filter(tab => Number.isInteger(tab.id) && pathOf(tab.url));
|
|
74
|
+
let tab;
|
|
75
|
+
if (Number.isInteger(message.tabId)) tab = all.find(item => item.id === message.tabId);
|
|
76
|
+
else if (all.length === 1) tab = all[0];
|
|
77
|
+
else return {status: "DENIED", code: all.length ? "AMBIGUOUS_CHATGPT_TABS" : "NO_CHATGPT_TAB"};
|
|
78
|
+
if (!tab) return {status: "DENIED", code: "TARGET_CHAT_NOT_FOUND"};
|
|
79
|
+
const query = () => chrome.tabs.sendMessage(tab.id, {type: "CHAT_LOOP_TURN_VERIFY_V1"});
|
|
80
|
+
let first;
|
|
81
|
+
try {first = await query();}
|
|
82
|
+
catch {return {status: "DENIED", code: "OBSERVER_NOT_READY"};}
|
|
83
|
+
if (first?.contract !== "chat-loop.turn-observer.v1" || first.status !== "READY"
|
|
84
|
+
|| first.page !== pathOf(tab.url)) return {status: "DENIED", code: "TURN_NOT_FINISHED"};
|
|
85
|
+
// A manually opened page is still forbidden from interrupting late updates.
|
|
86
|
+
await new Promise(resolve => setTimeout(resolve, 2300));
|
|
87
|
+
const second = await query().catch(() => null);
|
|
88
|
+
if (second?.status !== "READY" || second.page !== first.page
|
|
89
|
+
|| second.userKey !== first.userKey || second.assistantKey !== first.assistantKey
|
|
90
|
+
|| second.replyText !== first.replyText) return {status: "DENIED", code: "TURN_NOT_STABLE"};
|
|
91
|
+
const modelStatus = workerApi.parseStatus(first.replyText);
|
|
92
|
+
const ownedRecovery=Boolean(recoveryCandidate
|
|
93
|
+
&&(modelStatus==="BLOCKED"
|
|
94
|
+
||contextNotSent&&["HANDOFF","CONTINUE"].includes(modelStatus))
|
|
95
|
+
&&Number.isInteger(message.tabId) && message.tabId===previous.tabId
|
|
96
|
+
&&previous.tabId===tab.id&&previous.page===first.page
|
|
97
|
+
&&previous.userKey===first.userKey
|
|
98
|
+
&&previous.assistantKey===first.assistantKey
|
|
99
|
+
// Specific repaired tool capability, not generic BLOCKED, human
|
|
100
|
+
// approval failure, unknown browser send or context exhaustion.
|
|
101
|
+
&&(contextNotSent||resumeAt||/\b(?:adopt|Start)\b/i.test(first.replyText))
|
|
102
|
+
&&!first.pendingConfirmation
|
|
103
|
+
&&!second.pendingConfirmation);
|
|
104
|
+
if (recoveryCandidate && !ownedRecovery)
|
|
105
|
+
return {status:"DENIED",code:"BLOCKED_RECOVERY_UNVERIFIED"};
|
|
106
|
+
if (requested === "CONTINUE" && modelStatus !== "CONTINUE"&&!ownedRecovery
|
|
107
|
+
|| requested === "HANDOFF" && !["HANDOFF", "CONTINUE"].includes(modelStatus))
|
|
108
|
+
return {status: "DENIED", code: "ACTION_MARKER_MISMATCH"};
|
|
109
|
+
if (previous && previous.tabId === tab.id && previous.page === first.page
|
|
110
|
+
&& (previous.userKey === first.userKey || previous.assistantKey === first.assistantKey)
|
|
111
|
+
&&!ownedRecovery)
|
|
112
|
+
return {status: "DENIED", code: "ALREADY_HANDLED"};
|
|
113
|
+
const summary = modelStatus === "HANDOFF"
|
|
114
|
+
? first.replyText.replace(/\r?\n\[CHAT_LOOP_STATUS:HANDOFF\]\s*$/, "").trim() : null;
|
|
115
|
+
if (summary && (summary.length < 120 || summary.length > 16000
|
|
116
|
+
|| !/目标/.test(summary) || !/已完成|进度/.test(summary)
|
|
117
|
+
|| !/下一步|待办/.test(summary)))
|
|
118
|
+
return {status: "DENIED", code: "HANDOFF_PACKET_MISSING"};
|
|
119
|
+
if(ownedRecovery){
|
|
120
|
+
const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
121
|
+
{op:"session-read"}).catch(()=>null);
|
|
122
|
+
if(disk?.status!=="OK"||disk.session?.sessionId!==previous.sessionId
|
|
123
|
+
||disk.session.phase!=="BLOCKED"
|
|
124
|
+
||disk.session.projectId!==previous.projectId
|
|
125
|
+
||disk.session.generation!==(previous.generation||0)
|
|
126
|
+
||disk.session.activeChatId!==chatIdOf(tab.url)
|
|
127
|
+
||resumeAt&&disk.session.updatedAt!==resumeAt
|
|
128
|
+
||contextAt&&disk.session.updatedAt!==contextAt
|
|
129
|
+
||legacyAt&&(!legacyUnsent||disk.session.updatedAt!==legacyAt))
|
|
130
|
+
return {status:"DENIED",code:"BLOCKED_OWNER_PERSISTENCE_UNVERIFIED"};
|
|
131
|
+
}
|
|
132
|
+
const token = crypto.randomUUID();
|
|
133
|
+
await saveRun({...(ownedRecovery?previous:{}),
|
|
134
|
+
tabId: tab.id, page: first.page, userKey: first.userKey,
|
|
135
|
+
assistantKey: first.assistantKey, phase: "RESERVED", token,
|
|
136
|
+
action: requested, startedAt:ownedRecovery?previous.startedAt:Date.now(),
|
|
137
|
+
manualActionTabId: sender.tab.id,
|
|
138
|
+
...(ownedRecovery?{recoveryMode:contextNotSent?"HANDOFF_NOT_SENT":"TOOL_PREFLIGHT_REPAIRED",
|
|
139
|
+
recoveryAttempts:(previous.recoveryAttempts||0)+1,recoveryProtocol:1,
|
|
140
|
+
...(resumeAt||legacyUnsent||contextNotSent
|
|
141
|
+
?{recoveryExpectedNativeAt:contextAt||resumeAt||legacyAt}:{}),
|
|
142
|
+
...(contextNotSent?{contextSourceMarker:"[CHAT_LOOP_STATUS:"+modelStatus+"]",
|
|
143
|
+
contextRecoveryCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
|
|
144
|
+
x=>x.toString(16).padStart(2,"0")).join(""),
|
|
145
|
+
contextRecoveryAttempted:true}:{}),
|
|
146
|
+
recoverySourceAssistantKey:first.assistantKey}:{}),
|
|
147
|
+
handoffMode: requested === "HANDOFF"
|
|
148
|
+
? (modelStatus === "HANDOFF" ? "EXPLICIT" : "TIMED") : null,
|
|
149
|
+
...(summary ? {handoffText: summary} : {})});
|
|
150
|
+
return {status: "PREPARED", token, tabId: tab.id};
|
|
151
|
+
}
|
|
152
|
+
const isAction = (sender, message, run) => {
|
|
153
|
+
if (!Number.isInteger(sender.tab?.id) || typeof sender.url !== "string") return false;
|
|
154
|
+
try {
|
|
155
|
+
const file = run?.action === "HANDOFF" ? "handoff.html" : "continue.html";
|
|
156
|
+
const u = new URL(sender.url);
|
|
157
|
+
const manual = Number.isInteger(run?.manualActionTabId)
|
|
158
|
+
&& run.manualActionTabId === sender.tab.id && !u.searchParams.has("token")
|
|
159
|
+
&& (!u.searchParams.has("tabId") || u.searchParams.get("tabId") === String(message.tabId));
|
|
160
|
+
return u.origin === new URL(chrome.runtime.getURL(file)).origin
|
|
161
|
+
&& u.pathname === "/" + file
|
|
162
|
+
&& (manual || u.searchParams.get("token") === message.token
|
|
163
|
+
&& u.searchParams.get("tabId") === String(message.tabId));
|
|
164
|
+
} catch { return false; }
|
|
165
|
+
};
|
|
@@ -0,0 +1,242 @@
|
|
|
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'}).catch(()=>null);
|
|
110
|
+
if(disk?.status!=='OK')return {status:'UNVERIFIED',code:'SESSION_STATE_UNVERIFIED'};
|
|
111
|
+
const projection=run?.sessionId?sessionProjection(run):null;
|
|
112
|
+
if(projection&&!matchesNativeProjection(projection,disk.session))
|
|
113
|
+
return {status:'UNVERIFIED',code:'SESSION_FILE_MISMATCH'};
|
|
114
|
+
if(!run?.sessionId&&disk.session&&disk.session.phase!=='DONE')
|
|
115
|
+
return {status:'UNVERIFIED',code:'SESSION_OWNER_MISMATCH'};
|
|
116
|
+
if(run&&run.phase!=='DONE'&&!run.sessionId)
|
|
117
|
+
return {status:'OK',state:'LEGACY_OWNER',phase:run.phase};
|
|
118
|
+
if(run?.phase==='DONE'&&!terminalFenceVerified(run))
|
|
119
|
+
return {status:'UNVERIFIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
|
|
120
|
+
if(!run||run.phase==='DONE')return {status:'OK',state:'IDLE',
|
|
121
|
+
...(disk.session?{lastSession:disk.session}:{} )};
|
|
122
|
+
const record=sessionProjection(run);
|
|
123
|
+
// Native validates the private project binding; Status only forwards its
|
|
124
|
+
// read-only verified reference for the SAME active owner.
|
|
125
|
+
const projectContext=disk.contextStatus==='VERIFIED'
|
|
126
|
+
&&disk.projectContext?.projectId===run.projectId
|
|
127
|
+
?disk.projectContext:null;
|
|
128
|
+
if(record.activeChatId&&['WAITING_REPLY','BLOCKED'].includes(run.phase)){
|
|
129
|
+
const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
|
|
130
|
+
if(!tab||pathOf(tab.url)!==run.page)
|
|
131
|
+
return {status:'UNVERIFIED',code:'OWNER_TAB_MISSING',session:record};
|
|
132
|
+
}
|
|
133
|
+
// Identity comes from the verified Worker projection, but updatedAt is
|
|
134
|
+
// Native's durable CAS revision. Never report a synthetic timestamp as a
|
|
135
|
+
// usable recovery credential.
|
|
136
|
+
const tabEvidence=await handoffTabEvidence(run);
|
|
137
|
+
const startEvidence=await startReadinessEvidence(run);
|
|
138
|
+
return {status:'OK',state:run.phase==='BLOCKED'?'BLOCKED':'ACTIVE',session:disk.session,
|
|
139
|
+
diagnostics:{extensionVersion:chrome.runtime.getManifest?.().version||null,
|
|
140
|
+
...(tabEvidence?{handoffTabEvidence:tabEvidence}:{}),
|
|
141
|
+
...(startEvidence?{startReadinessEvidence:startEvidence}:{}),
|
|
142
|
+
...(run.lastStartFailureCode?{lastStartFailureCode:run.lastStartFailureCode}:{}),
|
|
143
|
+
// The numeric tab ID is a locator, never a send capability. Expose only
|
|
144
|
+
// for an exactly verified terminal/awaiting Owner, not a guessed tab.
|
|
145
|
+
ownerTabId:['WAITING_REPLY','BLOCKED'].includes(run.phase)?run.tabId:null,
|
|
146
|
+
reason:run.reason||null,action:run.action||null,
|
|
147
|
+
userKey:run.userKey||null,assistantKey:run.assistantKey||null,
|
|
148
|
+
newUserKey:run.newUserKey||null,recoveryAttempts:run.recoveryAttempts||0,
|
|
149
|
+
...(projectContext?{projectContext}:{}),
|
|
150
|
+
recoveryMode:run.recoveryMode||null,recoveryProtocol:run.recoveryProtocol||null,
|
|
151
|
+
recoverySourceAssistantKey:run.recoverySourceAssistantKey||null,
|
|
152
|
+
startedAt:run.startedAt||null,
|
|
153
|
+
deadlineAt:deadlineOf(run),lastManualFeedback:run.lastManualFeedback||null}};
|
|
154
|
+
}
|
|
155
|
+
async function expireStaleAction() {
|
|
156
|
+
const run=await readRun();
|
|
157
|
+
if(!['STARTING','RESERVED','PENDING'].includes(run?.phase)
|
|
158
|
+
|| !Number.isSafeInteger(run.actionPendingAt)
|
|
159
|
+
|| Date.now()-run.actionPendingAt<((run.action==='START'||run.action==='HANDOFF')
|
|
160
|
+
?330000:180000)) return;
|
|
161
|
+
// No action may be recreated or re-sent on a missing receipt. Keep the Chat.
|
|
162
|
+
await saveRun({...run,phase:'BLOCKED',reason:'ACTION_RESULT_TIMEOUT_UNVERIFIED'});
|
|
163
|
+
}
|
|
164
|
+
async function prepareHandoffIfDue() {
|
|
165
|
+
const run = await readRun();
|
|
166
|
+
const deadlineAt = deadlineOf(run);
|
|
167
|
+
if (!clockActive(run) || run.handoffPending || deadlineAt === null
|
|
168
|
+
|| Date.now() < deadlineAt) return;
|
|
169
|
+
await saveRun({...run, handoffPending: true,
|
|
170
|
+
handoffPendingAt: Date.now()});
|
|
171
|
+
}
|
|
172
|
+
// Chrome preserves a content script's original document sender.url across SPA
|
|
173
|
+
// / → /c/... navigation. Authenticate its origin, then read the CURRENT tab URL.
|
|
174
|
+
const eligible = async (sender, page) => {
|
|
175
|
+
if (!Number.isInteger(sender.tab?.id) || typeof page !== "string"
|
|
176
|
+
|| pathOf("https://chatgpt.com" + page) !== page) return false;
|
|
177
|
+
try {
|
|
178
|
+
if (new URL(sender.url).origin !== "https://chatgpt.com") return false;
|
|
179
|
+
const tab = await chrome.tabs.get(sender.tab.id);
|
|
180
|
+
return pathOf(tab.url) === page;
|
|
181
|
+
} catch { return false; }
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// Reuse the existing Observer read channel. This checks ONLY the latest
|
|
185
|
+
// assistant Turn in the current owned Chat, not historical forms or composer
|
|
186
|
+
// fields. An unknown read is never evidence of approval.
|
|
187
|
+
async function currentConfirmation(tabId,page,userKey,assistantKey) {
|
|
188
|
+
const tab=await chrome.tabs.get(tabId).catch(()=>null);
|
|
189
|
+
if(pathOf(tab?.url)!==page)return null;
|
|
190
|
+
const proof=await chrome.tabs.sendMessage(tabId,
|
|
191
|
+
{type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
|
|
192
|
+
if(proof?.contract!=="chat-loop.turn-observer.v1"
|
|
193
|
+
||proof.page!==page||proof.userKey!==userKey
|
|
194
|
+
||proof.assistantKey!==assistantKey
|
|
195
|
+
||proof.reason==="WAITING_CHAT_HYDRATION"
|
|
196
|
+
||typeof proof.pendingConfirmation!=="boolean")return null;
|
|
197
|
+
return proof.pendingConfirmation;
|
|
198
|
+
}
|
|
199
|
+
// A transient partial UI snapshot may end with UNKNOWN even when the same
|
|
200
|
+
// already-confirmed reply later settles on a valid final status. Only resample
|
|
201
|
+
// the exact in-flight user/assistant turn, read-only, before failing closed.
|
|
202
|
+
async function recheckUnknownTurn(message, previous, tabId) {
|
|
203
|
+
if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== tabId
|
|
204
|
+
|| previous.page !== message.page || previous.newUserKey !== message.userKey
|
|
205
|
+
|| previous.assistantKey === message.assistantKey) return null;
|
|
206
|
+
const read = async () => {
|
|
207
|
+
const tab = await chrome.tabs.get(tabId).catch(() => null);
|
|
208
|
+
if (pathOf(tab?.url) !== message.page) return null;
|
|
209
|
+
const proof = await chrome.tabs.sendMessage(tabId,
|
|
210
|
+
{type: "CHAT_LOOP_TURN_VERIFY_V1"}).catch(() => null);
|
|
211
|
+
if (proof?.contract !== "chat-loop.turn-observer.v1" || proof.status !== "READY"
|
|
212
|
+
|| proof.page !== message.page || proof.userKey !== message.userKey
|
|
213
|
+
|| proof.assistantKey !== message.assistantKey
|
|
214
|
+
|| typeof proof.replyText !== "string") return null;
|
|
215
|
+
return proof.replyText;
|
|
216
|
+
};
|
|
217
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
218
|
+
const first = await read();
|
|
219
|
+
if (first === null) return null;
|
|
220
|
+
const parsed = workerApi.parseStatus(first);
|
|
221
|
+
if (parsed !== "UNKNOWN") {
|
|
222
|
+
await new Promise(resolve => setTimeout(resolve, 2300));
|
|
223
|
+
const second = await read();
|
|
224
|
+
if (second === first) return {status: parsed, replyText: second};
|
|
225
|
+
} else {
|
|
226
|
+
await new Promise(resolve => setTimeout(resolve, 1500));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
// A suspended MV3 Worker may lose the Action receipt. Never retry a send
|
|
232
|
+
// from a stale RESERVED/PENDING phase; scrub the queued task text and block.
|
|
233
|
+
async function expireStaleModelIntent() {
|
|
234
|
+
const run=await readRun();
|
|
235
|
+
if(!run?.modelIntent || !Number.isSafeInteger(run.modelIntent.queuedAt)
|
|
236
|
+
||Date.now()-run.modelIntent.queuedAt<=MODEL_RECEIPT_TTL_MS)return;
|
|
237
|
+
const pendingSend=["RESERVED","PENDING"].includes(run.phase);
|
|
238
|
+
const next=settleModelIntent(run,"STALE_UNVERIFIED","INTENT_TTL_EXPIRED");
|
|
239
|
+
await saveRun(pendingSend
|
|
240
|
+
?{...next,phase:"BLOCKED",reason:"STALE_INTENT_UNKNOWN_SEND"}
|
|
241
|
+
:next);
|
|
242
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
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) => {
|
|
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(message,sender);}
|
|
81
|
+
catch(error){result={status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'};}
|
|
82
|
+
// A bounded diagnostic receipt, never permission or a second state store.
|
|
83
|
+
// In particular a rejected manual recovery must be observable remotely.
|
|
84
|
+
if(type==='CHAT_LOOP_ACTION_MANUAL_PREPARE_V1'){
|
|
85
|
+
const current=await readRun();
|
|
86
|
+
if(current)await chrome.storage.local.set({[RUN_KEY]:{...current,
|
|
87
|
+
lastManualFeedback:{status:result.status,
|
|
88
|
+
code:/^[A-Z0-9_]{1,100}$/.test(result.code||'')?result.code:null,at:Date.now()}}});
|
|
89
|
+
}
|
|
90
|
+
return result;
|
|
91
|
+
}).then(reply,error=>reply({status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'}));
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
if (type === 'CHAT_LOOP_POPUP_CLEAN_OPEN_V1') {
|
|
95
|
+
void serial(()=>openPopupClean(message,sender)).then(reply,
|
|
96
|
+
()=>reply({status:'BLOCKED',code:'CLEAN_ACTION_UNVERIFIED'}));
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
if (type === "CHAT_LOOP_EXTENSION_TARGET_V1") {
|
|
100
|
+
void onExtensionCliTarget(message,sender).then(reply,
|
|
101
|
+
()=>reply({status:"DENIED",code:"OWNER_UNVERIFIED"}));
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
if (type !== "CHAT_LOOP_EYE_RELOAD_V1") return false;
|
|
105
|
+
const id = sender.tab?.id;
|
|
106
|
+
void (async () => {
|
|
107
|
+
try {
|
|
108
|
+
if (!Number.isInteger(id)) throw Error("NO_ACTION_TAB");
|
|
109
|
+
const tab = await chrome.tabs.get(id);
|
|
110
|
+
const reloadBase=chrome.runtime.getURL("reload.html");
|
|
111
|
+
if (!tab.url.startsWith(reloadBase) ||
|
|
112
|
+
(tab.url!==reloadBase &&
|
|
113
|
+
!/^\?requestId=[a-f0-9]{32}$/.test(tab.url.slice(reloadBase.length))))
|
|
114
|
+
throw Error("INVALID_RELOAD_SOURCE");
|
|
115
|
+
reply({status: "ACCEPTED"});
|
|
116
|
+
await chrome.tabs.remove(id);
|
|
117
|
+
chrome.runtime.reload();
|
|
118
|
+
} catch (error) {reply({status: "FAILED", code: error.message});}
|
|
119
|
+
})();
|
|
120
|
+
return true;
|
|
121
|
+
};
|
|
122
|
+
chrome.runtime.onMessage.addListener((message,sender,reply)=>{
|
|
123
|
+
const type=typeof message?.type==='string'&&
|
|
124
|
+
/^CHAT_LOOP_[A-Z0-9_]{2,90}$/.test(message.type)
|
|
125
|
+
?message.type:'unknown';
|
|
126
|
+
// Dispatch is a synchronous acceptance marker, not an Action result.
|
|
127
|
+
// Capture its safe span ID before invoking the original handler so that
|
|
128
|
+
// a later async reply can be independently audited as its child.
|
|
129
|
+
let dispatchSpan=null;
|
|
130
|
+
const respond=result=>{
|
|
131
|
+
try{return reply(result);}
|
|
132
|
+
finally{
|
|
133
|
+
try{
|
|
134
|
+
const rejected=['DENIED','BLOCKED','FAILED','UNVERIFIED']
|
|
135
|
+
.includes(result?.status);
|
|
136
|
+
const code=typeof result?.code==='string'&&
|
|
137
|
+
/^[A-Z][A-Z0-9_]{1,95}$/.test(result.code)
|
|
138
|
+
?result.code:'BROWSER_REPLY_REJECTED';
|
|
139
|
+
workerApi.audit.observe('browser.reply.'+type,()=>{
|
|
140
|
+
if(rejected)throw Object.assign(Error('Reply rejected'),{code});
|
|
141
|
+
return true;
|
|
142
|
+
},'browser',{parent:dispatchSpan})();
|
|
143
|
+
}catch{/* Reply telemetry cannot change the browser callback. */}
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
return workerApi.audit.observe('browser.dispatch.'+type,
|
|
147
|
+
onBrowserMessage,'browser',{
|
|
148
|
+
onBegin:ids=>{dispatchSpan=ids;}
|
|
149
|
+
})(message,sender,respond);
|
|
150
|
+
});
|