@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.
Files changed (54) hide show
  1. package/README.md +74 -73
  2. package/actions.generated.mjs +11 -0
  3. package/bin/cli.mjs +22 -24
  4. package/bin/native-host.mjs +14 -5
  5. package/capabilities/chat_dom.mjs +1 -0
  6. package/capabilities/chat_screenshot.mjs +1 -0
  7. package/capabilities/chat_text.mjs +1 -0
  8. package/capabilities/clean.mjs +1 -0
  9. package/capabilities/continue.mjs +1 -0
  10. package/capabilities/handoff.mjs +1 -0
  11. package/capabilities/reload.mjs +1 -0
  12. package/capabilities/start.mjs +1 -0
  13. package/capabilities/status.mjs +1 -0
  14. package/extension/actions/common.js +14 -3
  15. package/extension/actions/continue.js +1 -1
  16. package/extension/actions/handoff.js +5 -3
  17. package/extension/actions/index.js +2 -0
  18. package/extension/actions/read-mode.js +9 -0
  19. package/extension/actions/start.js +1 -1
  20. package/extension/background.js +16 -2202
  21. package/extension/loop/action-catalog.generated.js +2 -0
  22. package/extension/loop/api-aspect.generated.js +192 -0
  23. package/extension/loop/core.js +81 -3
  24. package/extension/loop/index.js +34 -0
  25. package/extension/loop/observer-approval.js +227 -0
  26. package/extension/loop/observer-inspect.js +144 -0
  27. package/extension/loop/observer-poll.js +171 -0
  28. package/extension/loop/observer-recovery.js +109 -0
  29. package/extension/loop/observer.js +27 -630
  30. package/extension/loop/resources.js +8 -1
  31. package/extension/manifest.json +6 -2
  32. package/extension/worker/action-result.js +136 -0
  33. package/extension/worker/action-take.js +220 -0
  34. package/extension/worker/admission.js +122 -0
  35. package/extension/worker/adopt-prepare.js +155 -0
  36. package/extension/worker/adopt-recovery.js +185 -0
  37. package/extension/worker/adopt-result.js +120 -0
  38. package/extension/worker/bootstrap.js +172 -0
  39. package/extension/worker/manual.js +165 -0
  40. package/extension/worker/readiness.js +242 -0
  41. package/extension/worker/router.js +150 -0
  42. package/extension/worker/scheduler.js +147 -0
  43. package/extension/worker/turn-failure.js +197 -0
  44. package/extension/worker/turn-finished.js +200 -0
  45. package/index.mjs +62 -0
  46. package/lib/action-routing.mjs +18 -0
  47. package/lib/api-aspect.mjs +190 -0
  48. package/lib/bridge.mjs +26 -7
  49. package/lib/context-binding.mjs +6 -1
  50. package/lib/context-ipc.mjs +44 -2
  51. package/lib/owner-evidence.mjs +67 -0
  52. package/lib/session-file.mjs +20 -8
  53. package/package.json +13 -3
  54. package/scripts/build-actions.mjs +133 -0
@@ -1,2202 +1,16 @@
1
- // Chat Loop browser scheduler. It never types or clicks in ChatGPT.
2
- // Only extension-owned Action pages execute Continue or cross-Chat Handoff.
3
- importScripts("loop/core.js", "loop/resources.js");
4
- const RUN_KEY = "chat-loop.action.run.v1";
5
- const SESSION_HOST = "com.tomflow.chatloop.extension";
6
- // Product window: 4h of elapsed execution time per owned Chat, never per R/P review.
7
- const RUN_BUDGET_MS = 4 * 60 * 60 * 1000;
8
- const ALARM_NAME = "chat-loop.turn-watch.v1";
9
- const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
10
- const ENGINEERING_FAILURE_NOTE = "【故障边界】编译或测试失败应诊断修复,不是网页运行错误。MCP 初始化或连接临时失败时,先核查已启动进程与未知副作用;只有确认后续是安全只读操作,才可针对本次独立故障再安排一次跨轮复核并输出 CONTINUE。若同一故障复核仍无进展,或消息发送结果、Owner、审批、权限不可信,则 BLOCKED,绝不重复执行未知副作用。不同故障分别判断,不能沿用旧故障的重试次数。";
11
- const CONTINUE_TEXT = "继续当前任务,完成本轮后只在末行写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
12
- const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
13
- let queue = Promise.resolve();
14
- const serial = fn => {
15
- const work = queue.then(fn);
16
- queue = work.catch(() => {});
17
- return work;
18
- };
19
- // Admission and recovery run in this same Worker, never another browser executor.
20
- const resources = globalThis.ChatLoopResourcesV1;
21
- async function createBoundedAction(options) {
22
- const quota=await resources.admit(await readRun(),{kind:'action'});
23
- if (!quota.ok) throw Error(quota.code);
24
- const tab=await chrome.tabs.create(options);
25
- // MV3 tabs.create may return a tab with pendingUrl but no committed url.
26
- // Register the exact Extension URL WE requested, not an about:blank
27
- // transitional snapshot. The Action still checks its own actual source,
28
- // token and Owner before any browser write.
29
- if (!Number.isSafeInteger(tab?.id)||tab.id<=0
30
- ||typeof options?.url!=='string'
31
- ||!options.url.startsWith(chrome.runtime.getURL('')))
32
- throw Error('ACTION_CREATED_ID_UNVERIFIED');
33
- if (!await resources.registerAction({id:tab.id,url:options.url}))
34
- throw Error('ACTION_RESOURCE_UNVERIFIED');
35
- return tab;
36
- }
37
- const pathOf = url => {
38
- try {
39
- const u = new URL(url);
40
- const path = u.pathname.replace(/\/$/, "");
41
- return u.origin === "https://chatgpt.com"
42
- && /^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(path)
43
- ? path : "";
44
- } catch { return ""; }
45
- };
46
- // ChatGPT may render the very same conversation as /c/<id> or under a
47
- // project /g/<project>/c/<id>. Match the immutable conversation ID, never
48
- // create a second Chat because the visible path prefix differs.
49
- const chatIdOf = url => pathOf(url)?.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase() || null;
50
- const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
51
- // Keep only a fixed-size fingerprint after Start's one-shot prompt is erased.
52
- // A missing historical fingerprint means NOT_COMPARABLE, not "zero matches".
53
- async function startPromptFingerprint(prompt) {
54
- if(typeof prompt!=='string'||!globalThis.crypto?.subtle||
55
- typeof TextEncoder!=='function')return null;
56
- const normalized=prompt.replace(/\s+/g,'');
57
- if(!normalized)return null;
58
- const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(normalized));
59
- return Array.from(new Uint8Array(digest),v=>v.toString(16).padStart(2,'0')).join('');
60
- }
61
- const windowMsOf = run => Number.isSafeInteger(run?.windowMs) && run.windowMs > 0
62
- ? run.windowMs : RUN_BUDGET_MS;
63
- const deadlineOf = run => Number.isSafeInteger(run?.startedAt) && run.startedAt > 0
64
- ? run.startedAt + windowMsOf(run) : null;
65
- const clockActive = run => run && ["RESERVED", "PENDING", "WAITING_REPLY"].includes(run.phase);
66
- const terminalFenceVerified = run => !run?.contextManaged || !run?.taskId
67
- || run.contextTerminalFence === "CONFIRMED";
68
- // Durable, bounded metadata for model intent receipts. The prompt text remains only
69
- // in the active run while its Action is pending; history never stores the prompt.
70
- const MODEL_RECEIPT_TTL_MS = 24 * 60 * 60 * 1000;
71
- const receiptHistory = run => Array.isArray(run?.modelReceipts)
72
- ? run.modelReceipts.filter(x => x && typeof x.id === "string"
73
- && Number.isSafeInteger(x.updatedAt)
74
- && Date.now() - x.updatedAt < MODEL_RECEIPT_TTL_MS).slice(-16) : [];
75
- const updateModelReceipt = (run, id, change) => {
76
- if (!id) return run;
77
- const records = receiptHistory(run);
78
- const index = records.findIndex(x => x.id === id);
79
- const existing = index >= 0 ? records.splice(index, 1)[0] : {id};
80
- return {...run, modelReceipts: [...records,
81
- {...existing, ...change, id, updatedAt:Date.now()}].slice(-16)};
82
- };
83
- const settleModelIntent = (run, status, reason) => {
84
- const pending = run?.modelIntent;
85
- const finished = pending
86
- ? updateModelReceipt(run, pending.id, {status,
87
- reason:reason||run.reason||null,
88
- actualAction:run.action||pending.action,
89
- checkpointForwarded:false})
90
- : run;
91
- const next = {...finished};
92
- delete next.modelIntent;
93
- delete next.modelTurnToken;
94
- return next;
95
- };
96
- async function saveRun(run) {
97
- if (run && ["DONE","BLOCKED"].includes(run.phase))
98
- run = settleModelIntent(run, run.phase==="DONE"?"CANCELLED_DONE":"BLOCKED", run.reason);
99
- const now = Date.now(), deadlineAt = deadlineOf(run);
100
- // Persist the intent even when a delayed alarm arrives after an Action
101
- // receipt. This never revokes a Continue already reserved before deadline.
102
- const sending = ["STARTING","RESERVED","PENDING"].includes(run.phase);
103
- const marker = sending && typeof run.token==="string" ? run.token : null;
104
- const next = {...run, ...(deadlineAt ? {deadlineAt} : {}),
105
- ...(marker ? {actionPendingAt: run.resourceToken===marker
106
- && Number.isSafeInteger(run.actionPendingAt) ? run.actionPendingAt : now,
107
- resourceToken:marker} : {})};
108
- if (clockActive(next) && deadlineAt !== null && now >= deadlineAt
109
- && !next.handoffPending) {
110
- next.handoffPending = true;
111
- next.handoffPendingAt = now;
112
- }
113
- const stored=await readRun();
114
- const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
115
- &&["TOOL_PREFLIGHT_REPAIRED","HANDOFF_NOT_SENT","ADOPT_IDLE_BASELINE"].includes(next.recoveryMode)
116
- &&next.recoveryAttempts>=1&&stored?.phase==="BLOCKED";
117
- const syncNative=async()=>{
118
- if(!next.sessionId)return;
119
- const record=sessionProjection(next);
120
- const saved=await chrome.runtime.sendNativeMessage(SESSION_HOST,
121
- {op:"session-sync",session:record,
122
- ...(next.replacedBlockedSessionId&&!recoveryCommit&&next.phase==='STARTING'
123
- ?{replaceBlockedSessionId:next.replacedBlockedSessionId}:{}),
124
- ...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
125
- ...(next.recoveryExpectedNativeAt?{resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{})}:{})}).catch(()=>null);
126
- if(saved?.status!=="OK"||saved.session?.sessionId!==next.sessionId
127
- ||saved.session?.phase!==next.phase)
128
- throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
129
- };
130
- // A terminal BLOCKED session may resume only after native CAS first.
131
- // Do not leave a Chrome RESERVED owner behind if native rejects the
132
- // transition: that mismatch previously made all status calls unreadable.
133
- if(recoveryCommit)await syncNative();
134
- await chrome.storage.local.set({[RUN_KEY]:next});
135
- if(!recoveryCommit)await syncNative();
136
- // The resource inventory is derived evidence; it never grants browser Owner.
137
- if (["DONE","BLOCKED"].includes(next.phase)
138
- && next.contextTerminalFence !== "PENDING"
139
- && next.contextTerminalFence !== "UNVERIFIED")
140
- await resources.terminal(next).catch(()=>{});
141
-
142
- try {
143
- if (clockActive(next) && !next.handoffPending && deadlineAt > Date.now()) {
144
- await chrome.alarms?.create?.(DEADLINE_ALARM_NAME, {when: deadlineAt});
145
- } else {
146
- await chrome.alarms?.clear?.(DEADLINE_ALARM_NAME);
147
- }
148
- } catch { /* The existing periodic alarm is a conservative backup. */ }
149
- }
150
- // Browser Owner remains the only send authority. Native Host mirrors a minimal
151
- // session pointer so later Chats can find the current Web Chat without a task engine.
152
- function sessionProjection(run) {
153
- const page=typeof run.page==='string'?run.page:'';
154
- const match=page.match(/\/c\/([0-9a-f-]{12,})$/i);
155
- const activeChatId=match?.[1]||null;
156
- return {sessionId:run.sessionId,projectId:run.projectId,
157
- ...(run.taskId?{taskId:run.taskId}:{}),phase:run.phase,generation:run.generation||0,activeChatId,
158
- activeChatUrl:activeChatId?"https://chatgpt.com"+page:null,
159
- updatedAt:Date.now()};
160
- }
161
- const SESSION_POINTER_KEYS=Object.freeze(['sessionId','projectId','taskId','phase',
162
- 'generation','activeChatId','activeChatUrl']);
163
- const matchesNativeProjection=(projected,native)=>Boolean(native
164
- &&SESSION_POINTER_KEYS.every(key=>projected[key]===native[key]));
165
- const sessionPage=(sender,name,id)=> Number.isInteger(sender.tab?.id)
166
- && typeof id==='string'&&/^[a-f0-9]{32}$/.test(id)
167
- && sender.url===chrome.runtime.getURL(name+'.html')+'?requestId='+id;
168
- async function resourceChatGate(message,sender) {
169
- const run=await readRun();
170
- if(run?.phase!=='PENDING'
171
- || !['start','handoff'].includes(message.action))
172
- return {status:'DENIED',code:'RESOURCE_OWNER_NOT_PENDING'};
173
- const authorized=message.action==='start'
174
- ? run.action==='START' && run.machineActionTabId===sender.tab?.id
175
- && sessionPage(sender,'start',run.machineRequestId)
176
- : run.action==='HANDOFF' && isAction(sender,
177
- {tabId:run.tabId,token:run.token},run);
178
- if(!authorized)return {status:'DENIED',code:'RESOURCE_ACTION_SOURCE_INVALID'};
179
- if(message.stage==='preflight') {
180
- const quota=await resources.admit(run,{kind:'chat'});
181
- return quota.ok?{status:'OK',code:'RESOURCE_CHAT_PERMITTED'}
182
- :{status:'DENIED',code:quota.code};
183
- }
184
- if(message.stage==='adopt' && run.mode==='adopt'
185
- &&Number.isInteger(message.tabId)&&message.tabId===run.adoptTabId){
186
- const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
187
- if(!tab||pathOf(tab.url)!==run.adoptPage
188
- ||!await resources.adoptChat(tab,run))
189
- return {status:'DENIED',code:'RESOURCE_ADOPTION_UNVERIFIED'};
190
- return {status:'OK',code:'RESOURCE_CHAT_ADOPTED'};
191
- }
192
- if(message.stage!=='register' || !Number.isInteger(message.tabId))
193
- return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
194
- const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
195
- if (!tab || tab.id===run.tabId || tab.id===sender.tab.id
196
- || !await resources.registerChat(tab,run))
197
- return {status:'DENIED',code:'RESOURCE_CHAT_NOT_VERIFIED'};
198
- const inventory=await resources.reconcile(run);
199
- if(inventory.activeChatCount>resources.CHAT_LIMIT)
200
- return {status:'DENIED',code:'RESOURCE_CHAT_LIMIT'};
201
- return {status:'OK',code:'RESOURCE_CHAT_REGISTERED'};
202
- }
203
- async function approvedAdoptionTarget(chatUrl=null,taskId=null){
204
- const requestedId=chatUrl?chatIdOf(chatUrl):null;
205
- let tabs=await chrome.tabs.query({url:"https://chatgpt.com/*"});
206
- // App and desktop users keep their exact conversation ID. When Chrome
207
- // has not opened that conversation yet, open only the supplied existing
208
- // URL. No / new-chat page, prompt, composer write or first-send occurs.
209
- if(requestedId){
210
- const existing=tabs.filter(t=>chatIdOf(t.url)===requestedId);
211
- if(existing.length>1)return {error:"ADOPTION_CHAT_DUPLICATE_TABS"};
212
- if(existing.length===0){
213
- let opened;
214
- try{opened=await chrome.tabs.create({url:chatUrl,active:true});}
215
- catch{return {error:"ADOPTION_CHAT_OPEN_FAILED"};}
216
- if(!Number.isSafeInteger(opened?.id))
217
- return {error:"ADOPTION_CHAT_OPEN_UNVERIFIED"};
218
- // Content scripts have document_idle timing. A bounded wait allows
219
- // authentication/hydration; an error or CAPTCHA is NOT approval.
220
- let ready=false;
221
- for(let attempt=0;attempt<60;attempt++){
222
- const current=await chrome.tabs.get(opened.id).catch(()=>null);
223
- if(!current)return {error:"ADOPTION_CHAT_CLOSED"};
224
- if(current.url && chatIdOf(current.url)!==requestedId){
225
- if(current.url!=="about:blank"&&current.url!=="chrome://newtab/")
226
- return {error:"ADOPTION_CHAT_REDIRECTED"};
227
- }
228
- const proof=await chrome.tabs.sendMessage(opened.id,
229
- {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
230
- explicitChatId:requestedId,
231
- ...(taskId?{expectedTaskId:taskId}:{})}).catch(()=>null);
232
- if(proof?.contract==="chat-loop.turn-observer.v1"
233
- &&proof.status==="VERIFIED"
234
- &&chatIdOf('https://chatgpt.com'+proof.page)===requestedId){
235
- ready=true;break;
236
- }
237
- await new Promise(resolve=>setTimeout(resolve,500));
238
- }
239
- if(!ready)return {error:"ADOPTION_APPROVAL_NOT_FOUND"};
240
- tabs=await chrome.tabs.query({url:"https://chatgpt.com/*"});
241
- }
242
- }
243
- const matched=[];
244
- for(const tab of tabs) {
245
- const page=pathOf(tab.url);
246
- if(!page||!Number.isSafeInteger(tab.id)
247
- ||(requestedId && chatIdOf(tab.url)!==requestedId))continue;
248
- // No chatUrl means the caller does not authorize opening any Chat.
249
- // For the approved Task only, inspect each ALREADY OPEN tab by its own
250
- // immutable Chat ID and require exact native R/P issue-scoped user Turns.
251
- const scopedId=requestedId||taskId&&chatIdOf(tab.url);
252
- const proof=await chrome.tabs.sendMessage(tab.id,
253
- {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
254
- ...(scopedId?{explicitChatId:scopedId}:{}),
255
- ...(!requestedId&&taskId?{expectedTaskId:taskId}:{})}).catch(()=>null);
256
- if(proof?.contract!=="chat-loop.turn-observer.v1"
257
- ||proof.status!=="VERIFIED"||proof.page!==page
258
- ||typeof proof.userKey!=="string"||!/^user:[^\s]{8,}$/.test(proof.userKey)
259
- ||!/^R[1-9][0-9]*$/.test(proof.rVersion||"")
260
- ||!/^P[1-9][0-9]*$/.test(proof.pVersion||""))
261
- continue;
262
- matched.push({tabId:tab.id,page,userKey:proof.userKey,
263
- priorAssistantKey:proof.priorAssistantKey||null,
264
- rVersion:proof.rVersion,pVersion:proof.pVersion,
265
- postApprovalAssistantKey:proof.postApprovalAssistantKey||null,
266
- ...(!requestedId&&taskId?{explicitChatId:scopedId,expectedTaskId:taskId}:{})});
267
- }
268
- if(matched.length!==1)return {error:matched.length
269
- ?"ADOPTION_APPROVAL_AMBIGUOUS":"ADOPTION_APPROVAL_NOT_FOUND"};
270
- const target=matched[0];
271
- await new Promise(resolve=>setTimeout(resolve,400));
272
- const second=await chrome.tabs.sendMessage(target.tabId,
273
- {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
274
- ...((requestedId||target.explicitChatId)
275
- ?{explicitChatId:requestedId||target.explicitChatId}:{}),
276
- ...(target.expectedTaskId?{expectedTaskId:target.expectedTaskId}:{})}).catch(()=>null);
277
- if(second?.status!=="VERIFIED"
278
- ||second.page!==target.page||second.userKey!==target.userKey
279
- ||second.rVersion!==target.rVersion||second.pVersion!==target.pVersion
280
- ||(second.priorAssistantKey||null)!==(target.priorAssistantKey||null)
281
- ||(second.postApprovalAssistantKey||null)!==target.postApprovalAssistantKey)
282
- return {error:"ADOPTION_APPROVAL_CHANGED"};
283
- return {target};
284
- }
285
- async function approvedRepairTarget(prior,intent){
286
- // Repair is a new explicit USER request in the SAME exact Chat after the
287
- // original Task's machine DONE, never a synthetic P approval or replacement.
288
- if(!prior||prior.phase!=='DONE'||prior.projectId!==intent.projectId
289
- ||prior.taskId!==intent.taskId||!prior.sessionId
290
- ||!Number.isSafeInteger(prior.tabId)||!prior.page)
291
- return {error:'REPAIR_PREVIOUS_DONE_MISSING'};
292
- const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
293
- if(!tab||pathOf(tab.url)!==prior.page
294
- ||intent.chatUrl&&intent.chatUrl!=='https://chatgpt.com'+prior.page)
295
- return {error:'REPAIR_OLD_CHAT_CHANGED'};
296
- const durable=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
297
- op:'session-read'}).catch(()=>null);
298
- if(durable?.status!=='OK'||!durable.session
299
- ||durable.session.phase!=='DONE'
300
- ||durable.session.sessionId!==prior.sessionId
301
- ||durable.session.projectId!==intent.projectId
302
- ||durable.session.taskId!==intent.taskId
303
- ||durable.session.activeChatId!==chatIdOf(tab.url)
304
- ||durable.session.generation!==(prior.generation||0))
305
- return {error:'REPAIR_DONE_OWNER_UNVERIFIED'};
306
- const context=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
307
- op:'context-control',command:'run.reopenStatus',args:{}}).catch(()=>null);
308
- const reopen=context?.result;
309
- if(context?.status!=='OK'||reopen?.stage!=='REOPENED'
310
- ||reopen.taskRevision!==intent.contextTaskRevision
311
- ||reopen.approvalRevision!==intent.contextApprovalRevision
312
- ||typeof reopen.reopenUserTurn!=='string')
313
- return {error:'REPAIR_CONTEXT_UNVERIFIED'};
314
- const explicitChatId=chatIdOf(tab.url);
315
- const observe=()=>chrome.tabs.sendMessage(prior.tabId,{
316
- type:'CHAT_LOOP_REPAIR_EVIDENCE_V1',explicitChatId}).catch(()=>null);
317
- const first=await observe();
318
- await new Promise(resolve=>setTimeout(resolve,400));
319
- const second=await observe();
320
- const matching=proof=>proof?.contract==='chat-loop.turn-observer.v1'
321
- &&proof.status==='VERIFIED'&&proof.page===prior.page
322
- &&proof.priorDoneAssistantKey===prior.assistantKey
323
- &&typeof proof.userKey==='string'
324
- &&(reopen.reopenUserTurn===proof.userKey
325
- ||reopen.reopenUserTurn===proof.userText);
326
- if(!matching(first)||!matching(second)
327
- ||first.userKey!==second.userKey
328
- ||first.userText!==second.userText)
329
- return {error:'REPAIR_USER_INTENT_UNVERIFIED'};
330
- return {target:{tabId:prior.tabId,page:prior.page,
331
- userKey:first.userKey,priorAssistantKey:prior.assistantKey,
332
- repairUserText:first.userText,repairDoneAssistantKey:prior.assistantKey}};
333
- }
334
- async function sessionStartPrepare(message,sender){
335
- if(!sessionPage(sender,'start',message.requestId))
336
- return {status:'DENIED',code:'INVALID_START_SOURCE'};
337
- const prior=await readRun();
338
- // Read the single authenticated intent BEFORE deciding whether a previously
339
- // BLOCKED session can be explicitly superseded. Never infer consent from
340
- // a failed page or an old session pointer alone.
341
- const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,
342
- {op:'acquire',id:message.requestId,action:'start'}).catch(()=>null);
343
- const intent=proof?.intent;
344
- if(proof?.status!=='OK'||intent?.confirmed!==true
345
- ||typeof intent.projectId!=='string'
346
- ||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.projectId)
347
- ||(intent.taskId!==undefined
348
- && !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.taskId))
349
- ||(intent.purpose!==undefined
350
- &&(intent.purpose!=='REPAIR_SAME_SCOPE'||intent.mode!=='adopt'
351
- ||!intent.taskId||!intent.contextLeaseRef))
352
- ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
353
- .some(k=>Object.hasOwn(intent,k))
354
- &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
355
- ||intent.contextLeaseRef.length<8||typeof intent.contextStoreEpoch!=='string'
356
- ||intent.contextStoreEpoch.length<10
357
- ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
358
- ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
359
- ||(intent.chatUrl!==undefined
360
- && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'
361
- ||!pathOf(intent.chatUrl)
362
- ||intent.chatUrl!=='https://chatgpt.com'+pathOf(intent.chatUrl)))
363
- ||(intent.mode==='adopt' ? Object.hasOwn(intent,'prompt')
364
- : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000)
365
- ||(intent.mode!==undefined && intent.mode!=='adopt')
366
- ||(intent.replaceBlockedSessionId!==undefined
367
- && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId)))
368
- return {status:'DENIED',code:'START_INTENT_UNVERIFIED'};
369
- // Native DONE is required before the private terminal fence IPC, but
370
- // DONE without CONFIRMED fencing must never release Start admission.
371
- if(prior?.contextManaged && prior.taskId
372
- && (prior.contextTerminalFence==='UNVERIFIED'
373
- || prior.phase==='DONE'&&!terminalFenceVerified(prior)))
374
- return {status:'DENIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
375
- const replace=intent.replaceBlockedSessionId||null;
376
- const matchingBlocked=prior?.phase==='BLOCKED' && prior.sessionId===replace
377
- && prior.projectId!==intent.projectId;
378
- if(replace&&!matchingBlocked)return {status:'DENIED',code:'BLOCKED_REPLACEMENT_MISMATCH'};
379
- if(prior&&prior.phase!=='DONE'&&!matchingBlocked)
380
- return {status:'DENIED',code:'LOOP_ALREADY_ACTIVE'};
381
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
382
- if(disk?.status!=='OK')return {status:'DENIED',code:'SESSION_STATE_UNVERIFIED'};
383
- if(matchingBlocked&&(!disk.session||disk.session.phase!=='BLOCKED'
384
- ||disk.session.sessionId!==replace||disk.session.projectId!==prior.projectId))
385
- return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
386
- // An abandoned Managed Context writer can outlive its Browser Owner.
387
- // Replacing the Native session without first verifying its terminal fence
388
- // would strand a live runRef (and an old write credential) in the Store.
389
- // Never make that replacement based solely on BLOCKED or absent Owner.
390
- if(matchingBlocked&&prior.contextManaged){
391
- const terminal=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
392
- op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
393
- const state=terminal?.result;
394
- if(terminal?.status!=='OK'||!state
395
- ||state.projectId!==prior.projectId||state.taskId!==prior.taskId
396
- ||state.runRef!==null||state.executionOutcome!=='DONE'
397
- ||typeof state.deliveryRef!=='string'||!state.deliveryRef)
398
- return {status:'DENIED',code:'CONTEXT_BLOCKED_RUN_UNFENCED'};
399
- }
400
- if(disk.session&&disk.session.phase!=='DONE'&&!matchingBlocked)
401
- return {status:'DENIED',code:'SESSION_ALREADY_ACTIVE'};
402
- const capacity=await resources.admit(prior,{kind:intent.mode==='adopt'?'action':'chat'});
403
- if(!capacity.ok)return {status:'DENIED',code:capacity.code};
404
- const adoption=intent.mode==='adopt'
405
- ?intent.purpose==='REPAIR_SAME_SCOPE'
406
- ?await approvedRepairTarget(prior,intent)
407
- :await approvedAdoptionTarget(intent.chatUrl||null,
408
- intent.contextLeaseRef?intent.taskId:null):null;
409
- if(adoption?.error)return {status:'DENIED',code:adoption.error};
410
- // A Project-scoped Chat cannot safely hand off to the ordinary home route:
411
- // reject BEFORE claiming Owner instead of failing after four hours.
412
- // Explicit /g/ intent remains Project-scoped even if Chrome aliases the
413
- // same conversation under /c/<id>.
414
- if(intent.mode==='adopt'&&(
415
- pathOf(intent.chatUrl||'').startsWith('/g/')
416
- ||adoption?.target?.page?.startsWith('/g/')))
417
- return {status:'DENIED',code:'AUTO_HANDOFF_ROUTE_UNSUPPORTED'};
418
- // The same blocked task may never be replayed implicitly: a replacement
419
- // requires a new project ID and leaves the old Chat intact for audit.
420
- const promptDigest=adoption?null:await startPromptFingerprint(intent.prompt);
421
- const next={sessionId:crypto.randomUUID(),projectId:intent.projectId,
422
- ...(intent.taskId?{taskId:intent.taskId}:{}),
423
- ...(intent.purpose?{purpose:intent.purpose}:{}),
424
- ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
425
- contextStoreEpoch:intent.contextStoreEpoch,
426
- contextTaskRevision:intent.contextTaskRevision,
427
- contextApprovalRevision:intent.contextApprovalRevision,
428
- contextInitialCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
429
- x=>x.toString(16).padStart(2,'0')).join('')}:{}),
430
- generation:0,phase:'STARTING',action:'START',token:crypto.randomUUID(),
431
- page:'/',tabId:null,startedAt:Date.now(),
432
- machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
433
- ...(matchingBlocked?{replacedBlockedSessionId:replace}:{}),
434
- ...(adoption?{mode:'adopt',adoptTabId:adoption.target.tabId,
435
- adoptPage:adoption.target.page,adoptUserKey:adoption.target.userKey,
436
- ...((intent.chatUrl||adoption.target.explicitChatId)
437
- ?{adoptExplicitChatId:chatIdOf(intent.chatUrl)||adoption.target.explicitChatId}:{}),
438
- ...(adoption.target.expectedTaskId
439
- ?{adoptExpectedTaskId:adoption.target.expectedTaskId}:{}),
440
- adoptPriorAssistantKey:adoption.target.priorAssistantKey,
441
- adoptPostApprovalAssistantKey:adoption.target.postApprovalAssistantKey||null,
442
- ...(intent.purpose==='REPAIR_SAME_SCOPE'?{}:{
443
- adoptRVersion:adoption.target.rVersion,
444
- adoptPVersion:adoption.target.pVersion}),
445
- ...(intent.purpose==='REPAIR_SAME_SCOPE'
446
- ?{repairUserText:adoption.target.repairUserText,
447
- repairDoneAssistantKey:adoption.target.repairDoneAssistantKey}:{})}
448
- :{startPrompt:intent.prompt,...(promptDigest?{startPromptDigest:promptDigest}:{})})};
449
- await saveRun(next); // Reserve BEFORE any new Chrome tab or send.
450
- return {status:'PREPARED',token:next.token,sessionId:next.sessionId,
451
- ...(next.taskId?{taskId:next.taskId}:{})};
452
- }
453
- async function sessionStartTake(message,sender){
454
- const run=await readRun();
455
- if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
456
- ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
457
- ||run.phase!=='STARTING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
458
- await saveRun({...run,phase:'PENDING'});
459
- // Native validates current durable Session and signs the narrow Context IPC.
460
- // No Context adapter? Legacy Start behavior remains unchanged.
461
- if(run.contextLeaseRef){
462
- const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
463
- op:'context-control',command:'permit.consume',
464
- args:{expectedStoreEpoch:run.contextStoreEpoch,writeRequestId:run.token,
465
- expectedTaskRevision:run.contextTaskRevision,
466
- expectedApprovalRevision:run.contextApprovalRevision,
467
- actionToken:run.token,kind:'START',leaseRef:run.contextLeaseRef}
468
- }).catch(()=>null);
469
- if(allowed?.status!=='OK'||allowed.result?.status!=='PERMITTED'){
470
- await saveRun({...run,phase:'BLOCKED',reason:'CONTEXT_START_PERMIT_UNVERIFIED'});
471
- return {status:'DENIED',code:allowed?.code||'CONTEXT_START_PERMIT_UNVERIFIED'};
472
- }
473
- }
474
- return {status:'OK',sessionId:run.sessionId,
475
- ...(run.taskId?{taskId:run.taskId}:{}),
476
- ...(run.mode==='adopt'?{mode:'adopt',tabId:run.adoptTabId,
477
- page:run.adoptPage,userKey:run.adoptUserKey,
478
- ...(run.adoptExplicitChatId?{explicitChatId:run.adoptExplicitChatId}:{}),
479
- ...(run.adoptExpectedTaskId?{expectedTaskId:run.adoptExpectedTaskId}:{}),
480
- priorAssistantKey:run.adoptPriorAssistantKey,
481
- postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
482
- ...(run.purpose==='REPAIR_SAME_SCOPE'
483
- ?{purpose:'REPAIR_SAME_SCOPE',repairUserText:run.repairUserText,
484
- priorDoneAssistantKey:run.repairDoneAssistantKey}
485
- :{rVersion:run.adoptRVersion,pVersion:run.adoptPVersion})}
486
- :{prompt:run.startPrompt})};
487
- }
488
- async function sessionStartResult(message,sender){
489
- const run=await readRun();
490
- if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
491
- ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
492
- ||run.phase!=='PENDING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
493
- const adopted=run.mode==='adopt';
494
- let confirmed=(adopted?message.result==='ADOPTED_CONFIRMED'
495
- :message.result==='SENT_CONFIRMED')
496
- &&Number.isInteger(message.newTabId)
497
- &&typeof message.newPage==='string'&&pathOf('https://chatgpt.com'+message.newPage)===message.newPage
498
- &&typeof message.newUserKey==='string'&&/^user:[^\s]{8,}$/.test(message.newUserKey);
499
- if(confirmed){
500
- const tab=await chrome.tabs.get(message.newTabId).catch(()=>null);
501
- confirmed=!!tab&&pathOf(tab.url)===message.newPage;
502
- }
503
- if(confirmed && adopted){
504
- confirmed=message.newTabId===run.adoptTabId
505
- &&message.newPage===run.adoptPage
506
- &&message.newUserKey===run.adoptUserKey;
507
- if(confirmed){
508
- const repair=run.purpose==='REPAIR_SAME_SCOPE';
509
- const proof=await chrome.tabs.sendMessage(run.adoptTabId,
510
- {type:repair?'CHAT_LOOP_REPAIR_EVIDENCE_V1':'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
511
- ...(run.adoptExplicitChatId
512
- ?{explicitChatId:run.adoptExplicitChatId}:{}),
513
- ...(run.adoptExpectedTaskId
514
- ?{expectedTaskId:run.adoptExpectedTaskId}:{})}).catch(()=>null);
515
- confirmed=proof?.contract==='chat-loop.turn-observer.v1'
516
- &&proof.status==='VERIFIED'&&proof.page===run.adoptPage
517
- &&proof.userKey===run.adoptUserKey
518
- &&(repair
519
- ? proof.userText===run.repairUserText
520
- &&proof.priorDoneAssistantKey===run.repairDoneAssistantKey
521
- :proof.rVersion===run.adoptRVersion
522
- &&proof.pVersion===run.adoptPVersion
523
- &&(proof.priorAssistantKey||null)===(run.adoptPriorAssistantKey||null)
524
- &&(proof.postApprovalAssistantKey||null)===(run.adoptPostApprovalAssistantKey||null));
525
- }
526
- }
527
- // Four-hour execution clock begins at confirmed enrollment, not at
528
- // the UI approval or potentially long Start readiness/preparation.
529
- const adoptedIdle=confirmed&&adopted&&!!run.adoptPostApprovalAssistantKey;
530
- const next={...run,phase:confirmed?'WAITING_REPLY':'BLOCKED',
531
- startedAt:confirmed?Date.now():run.startedAt,
532
- lastStartActionTabId:sender.tab.id,
533
- ...(adoptedIdle?{assistantKey:run.adoptPostApprovalAssistantKey,
534
- userKey:run.adoptUserKey}:{}),
535
- reason:confirmed?(adoptedIdle?'ADOPTED_IDLE_BASELINE':'')
536
- :adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED',
537
- ...(!confirmed&&['START_HOME_URL_UNVERIFIED','NEW_CHAT_NOT_READY',
538
- 'START_COMPOSER_NOT_EMPTY','START_ACCOUNT_SWITCH_VISIBLE',
539
- 'FIRST_TURN_OBSERVER_UNAVAILABLE','START_SEND_BUTTON_UNAVAILABLE','START_INPUT_CHANGED',
540
- 'START_INPUT_UNVERIFIED','START_INPUT_REJECTED',
541
- 'START_CLICK_UNVERIFIED','FIRST_SEND_RECEIPT_UNKNOWN']
542
- .includes(message.failureCode)
543
- ?{lastStartFailureCode:message.failureCode}:{}),
544
- ...(confirmed?{tabId:message.newTabId,page:message.newPage,
545
- newUserKey:message.newUserKey}:{attemptedNewTabId:Number.isInteger(message.newTabId)?message.newTabId:null})};
546
- if(confirmed){
547
- delete next.handoffPending;
548
- delete next.handoffPendingAt;
549
- }
550
- delete next.startPrompt;
551
- delete next.adoptTabId;
552
- delete next.adoptPage;
553
- delete next.adoptUserKey;
554
- delete next.adoptExplicitChatId;
555
- delete next.adoptExpectedTaskId;
556
- delete next.adoptPriorAssistantKey;
557
- delete next.adoptPostApprovalAssistantKey;
558
- delete next.adoptRVersion;
559
- delete next.adoptPVersion;
560
- delete next.repairUserText;
561
- delete next.repairDoneAssistantKey;
562
- delete next.purpose;
563
- delete next.mode;
564
- delete next.machineRequestId;
565
- delete next.machineActionTabId;
566
- delete next.replacedBlockedSessionId;
567
- await saveRun(next);
568
- let privateContext=null;
569
- if(confirmed&&run.contextLeaseRef){
570
- const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
571
- op:'context-control',command:'run.bind.initial',
572
- args:{expectedStoreEpoch:run.contextStoreEpoch,
573
- writeRequestId:run.token+':initial-bind',
574
- expectedTaskRevision:run.contextTaskRevision,expectedBindingRevision:0,
575
- actionToken:run.token,leaseRef:run.contextLeaseRef,
576
- runCredential:run.contextInitialCredential}
577
- }).catch(()=>null);
578
- if(bound?.status!=='OK'||bound.result?.status!=='BOUND'){
579
- // First Chat may already exist. Never re-send merely to fix Context.
580
- const stopped={...next,phase:'BLOCKED',reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
581
- delete stopped.contextInitialCredential;
582
- await saveRun(stopped);
583
- return {status:'BLOCKED',code:bound?.code||'CONTEXT_INITIAL_BIND_UNVERIFIED'};
584
- }
585
- privateContext={runRef:bound.result.runRef,
586
- runCredential:run.contextInitialCredential,
587
- storeEpoch:run.contextStoreEpoch,
588
- bindingRevision:bound.result.bindingRevision,
589
- taskRevision:run.contextTaskRevision};
590
- // Capability is delivered once in the private Start result, not Status.
591
- const clean={...next,contextManaged:{storeEpoch:run.contextStoreEpoch}};
592
- for(const key of ['contextInitialCredential','contextLeaseRef','contextStoreEpoch',
593
- 'contextTaskRevision','contextApprovalRevision'])delete clean[key];
594
- await saveRun(clean);
595
- }
596
- if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
597
- 'https://chatgpt.com'+message.newPage).catch(()=>{});
598
- return confirmed?{status:'OK',sessionId:next.sessionId,
599
- activeChatId:sessionProjection(next).activeChatId,
600
- activeChatUrl:sessionProjection(next).activeChatUrl,
601
- ...(next.taskId?{taskId:next.taskId}:{}),
602
- ...(privateContext?{context:privateContext}:{})}
603
- :{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
604
- }
605
- // Read the existing resource index without reconciliation, tab mutation or
606
- // Owner changes. A registered blank successor proves only tab creation,
607
- // NEVER a click, user message or successful Handoff.
608
- async function handoffTabEvidence(run){
609
- if(run?.phase!=="BLOCKED"||run.action!=="HANDOFF"||!run.sessionId)
610
- return null;
611
- const saved=(await chrome.storage.local.get(resources.KEY).catch(()=>null))
612
- ?.[resources.KEY];
613
- const candidates=Array.isArray(saved?.entries)?saved.entries.filter(entry=>
614
- entry?.kind==="chat"&&entry.confirmed===false
615
- &&entry.sessionId===run.sessionId&&Number.isInteger(entry.id)
616
- &&entry.id!==run.tabId):[];
617
- if(candidates.length!==1)return null;
618
- const entry=candidates[0];
619
- const tab=await chrome.tabs.get(entry.id).catch(()=>null);
620
- if(!tab||typeof tab.url!=="string"||!tab.url.startsWith("https://chatgpt.com/"))
621
- return null;
622
- return {tabId:entry.id,recorded:true,confirmed:false,
623
- pageState:tab.url==="https://chatgpt.com/"?"BLANK_HOME":"CHANGED_UNVERIFIED",
624
- sendReceipt:"UNVERIFIED"};
625
- }
626
- // Read-only diagnosis for a START that created an unconfirmed Chat home.
627
- // Never infers a send receipt, creates a tab, reads message text, or changes Owner.
628
- async function startReadinessEvidence(run){
629
- if(run?.phase!=='BLOCKED'||run.action!=='START'||!run.sessionId
630
- ||!Number.isSafeInteger(run.attemptedNewTabId))return null;
631
- const saved=(await chrome.storage.local.get(resources.KEY).catch(()=>null))
632
- ?.[resources.KEY];
633
- const candidates=Array.isArray(saved?.entries)?saved.entries.filter(entry=>
634
- entry?.kind==='chat'&&entry.confirmed===false
635
- &&entry.sessionId===run.sessionId&&entry.id===run.attemptedNewTabId):[];
636
- if(candidates.length!==1)return null;
637
- const tab=await Promise.race([
638
- chrome.tabs.get(run.attemptedNewTabId).catch(()=>null),
639
- new Promise(resolve=>setTimeout(()=>resolve(null),1500))
640
- ]);
641
- if(!tab||typeof tab.url!=='string'||!tab.url.startsWith('https://chatgpt.com/'))
642
- return null;
643
- const result=await Promise.race([
644
- chrome.scripting.executeScript({target:{tabId:tab.id},func:async expectedDigest=>{
645
- const visible=e=>Boolean(e?.getClientRects?.().length);
646
- const mains=[...document.querySelectorAll('main')].filter(visible);
647
- const editors=[...document.querySelectorAll(
648
- '[contenteditable="true"][data-composer-markdown],#prompt-textarea[contenteditable="true"]')];
649
- const editor=editors.find(visible);
650
- const messages=mains.flatMap(m=>[...m.querySelectorAll(
651
- '[data-chatgpt-search-message-ids],[data-message-author-role]')]);
652
- const modern=mains.flatMap(m=>[...m.querySelectorAll(
653
- '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]);
654
- const units=modern.length?modern:messages;
655
- const role=n=>n.getAttribute('data-message-author-role')
656
- ||n.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
657
- const messageId=n=>{
658
- const id=n.getAttribute('data-message-id')
659
- ||n.getAttribute('data-chatgpt-search-message-ids')?.trim().split(/\s+/)[0];
660
- return typeof id==='string'&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,115}$/.test(id)
661
- ?id:null;
662
- };
663
- const canonical=v=>String(v||'').replace(/\s+/g,'');
664
- const users=units.filter(n=>role(n)==='user');
665
- const assistants=units.filter(n=>role(n)==='assistant');
666
- const comparable=typeof expectedDigest==='string'&&/^[a-f0-9]{64}$/.test(expectedDigest)
667
- &&Boolean(globalThis.crypto?.subtle)&&typeof TextEncoder==='function';
668
- const matched=[];
669
- if(comparable)for(const user of users){
670
- if(!messageId(user))continue;
671
- const bubble=user.querySelector('[data-search-result-target]')
672
- ||user.querySelector('[data-user-message-bubble="true"]')||user;
673
- const normalized=canonical(bubble.innerText||bubble.textContent);
674
- const bytes=new TextEncoder().encode(normalized);
675
- const hash=await crypto.subtle.digest('SHA-256',bytes);
676
- const digest=Array.from(new Uint8Array(hash),v=>v.toString(16).padStart(2,'0')).join('');
677
- if(digest===expectedDigest)matched.push(user);
678
- }
679
- const key=(prefix,node)=>node&&messageId(node)?prefix+messageId(node):null;
680
- // Diagnostic only: an account-switch error can leave a local-chatgpt
681
- // user bubble visible without any server-confirmed first send.
682
- // Never infer NOT_SENT or a retry permit from this UI text.
683
- const switched=/你的账户已切换[。.!!\s]*请重新发送消息|your account (?:has been |was )?switched[.!\s]*please (?:re-?send|send again) (?:your )?message/i;
684
- const inUserMessage=users.some(n=>switched.test(n.innerText||n.textContent||''));
685
- const accountSwitchVisible=!inUserMessage&&mains.some(m=>
686
- switched.test(m.innerText||m.textContent||''));
687
- return {path:location.pathname,readyState:document.readyState,
688
- uiErrorCode:accountSwitchVisible?'ACCOUNT_SWITCHED_RETRY_REQUIRED':null,
689
- mainCount:mains.length,editorCount:editors.length,
690
- editorVisible:Boolean(editor),editorEditable:Boolean(editor?.isContentEditable),
691
- editorEmpty:editor?!(editor.innerText||editor.textContent||'').trim():null,
692
- messageNodeCount:messages.length,
693
- // Read-only identity and equality evidence. No message text or send permit.
694
- userMessageCount:users.length,assistantMessageCount:assistants.length,
695
- startPromptComparison:comparable?'AVAILABLE':'UNAVAILABLE',
696
- matchedStartPromptCount:comparable?new Set(matched.map(messageId)).size:null,
697
- lastUserKey:key('user:',users.at(-1)),
698
- lastMatchedUserKey:key('user:',matched.at(-1)),
699
- lastAssistantKey:key('assistant:',assistants.at(-1))};
700
- },args:[typeof run.startPromptDigest==='string'?run.startPromptDigest:null]
701
- }).then(rows=>rows?.[0]?.result||null).catch(()=>null),
702
- new Promise(resolve=>setTimeout(()=>resolve(null),1500))
703
- ]);
704
- return {tabId:tab.id,confirmed:false,sendReceipt:'UNVERIFIED',
705
- pageState:tab.url==='https://chatgpt.com/'?'BLANK_HOME':'CHANGED_UNVERIFIED',
706
- ...(result&&typeof result.mainCount==='number'?{readiness:result}:{})};
707
- }
708
- async function sessionStatus(message,sender){
709
- if(!sessionPage(sender,'status',message.requestId))
710
- return {status:'DENIED',code:'INVALID_STATUS_SOURCE'};
711
- const run=await readRun();
712
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
713
- if(disk?.status!=='OK')return {status:'UNVERIFIED',code:'SESSION_STATE_UNVERIFIED'};
714
- const projection=run?.sessionId?sessionProjection(run):null;
715
- if(projection&&!matchesNativeProjection(projection,disk.session))
716
- return {status:'UNVERIFIED',code:'SESSION_FILE_MISMATCH'};
717
- if(!run?.sessionId&&disk.session&&disk.session.phase!=='DONE')
718
- return {status:'UNVERIFIED',code:'SESSION_OWNER_MISMATCH'};
719
- if(run&&run.phase!=='DONE'&&!run.sessionId)
720
- return {status:'OK',state:'LEGACY_OWNER',phase:run.phase};
721
- if(run?.phase==='DONE'&&!terminalFenceVerified(run))
722
- return {status:'UNVERIFIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
723
- if(!run||run.phase==='DONE')return {status:'OK',state:'IDLE',
724
- ...(disk.session?{lastSession:disk.session}:{} )};
725
- const record=sessionProjection(run);
726
- // Native validates the private project binding; Status only forwards its
727
- // read-only verified reference for the SAME active owner.
728
- const projectContext=disk.contextStatus==='VERIFIED'
729
- &&disk.projectContext?.projectId===run.projectId
730
- ?disk.projectContext:null;
731
- if(record.activeChatId&&['WAITING_REPLY','BLOCKED'].includes(run.phase)){
732
- const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
733
- if(!tab||pathOf(tab.url)!==run.page)
734
- return {status:'UNVERIFIED',code:'OWNER_TAB_MISSING',session:record};
735
- }
736
- // Identity comes from the verified Worker projection, but updatedAt is
737
- // Native's durable CAS revision. Never report a synthetic timestamp as a
738
- // usable recovery credential.
739
- const tabEvidence=await handoffTabEvidence(run);
740
- const startEvidence=await startReadinessEvidence(run);
741
- return {status:'OK',state:run.phase==='BLOCKED'?'BLOCKED':'ACTIVE',session:disk.session,
742
- diagnostics:{extensionVersion:chrome.runtime.getManifest?.().version||null,
743
- ...(tabEvidence?{handoffTabEvidence:tabEvidence}:{}),
744
- ...(startEvidence?{startReadinessEvidence:startEvidence}:{}),
745
- ...(run.lastStartFailureCode?{lastStartFailureCode:run.lastStartFailureCode}:{}),
746
- // The numeric tab ID is a locator, never a send capability. Expose only
747
- // for an exactly verified terminal/awaiting Owner, not a guessed tab.
748
- ownerTabId:['WAITING_REPLY','BLOCKED'].includes(run.phase)?run.tabId:null,
749
- reason:run.reason||null,action:run.action||null,
750
- userKey:run.userKey||null,assistantKey:run.assistantKey||null,
751
- newUserKey:run.newUserKey||null,recoveryAttempts:run.recoveryAttempts||0,
752
- ...(projectContext?{projectContext}:{}),
753
- recoveryMode:run.recoveryMode||null,recoveryProtocol:run.recoveryProtocol||null,
754
- recoverySourceAssistantKey:run.recoverySourceAssistantKey||null,
755
- startedAt:run.startedAt||null,
756
- deadlineAt:deadlineOf(run),lastManualFeedback:run.lastManualFeedback||null}};
757
- }
758
- async function expireStaleAction() {
759
- const run=await readRun();
760
- if(!['STARTING','RESERVED','PENDING'].includes(run?.phase)
761
- || !Number.isSafeInteger(run.actionPendingAt)
762
- || Date.now()-run.actionPendingAt<((run.action==='START'||run.action==='HANDOFF')
763
- ?330000:180000)) return;
764
- // No action may be recreated or re-sent on a missing receipt. Keep the Chat.
765
- await saveRun({...run,phase:'BLOCKED',reason:'ACTION_RESULT_TIMEOUT_UNVERIFIED'});
766
- }
767
- async function prepareHandoffIfDue() {
768
- const run = await readRun();
769
- const deadlineAt = deadlineOf(run);
770
- if (!clockActive(run) || run.handoffPending || deadlineAt === null
771
- || Date.now() < deadlineAt) return;
772
- await saveRun({...run, handoffPending: true,
773
- handoffPendingAt: Date.now()});
774
- }
775
- // Chrome preserves a content script's original document sender.url across SPA
776
- // / → /c/... navigation. Authenticate its origin, then read the CURRENT tab URL.
777
- const eligible = async (sender, page) => {
778
- if (!Number.isInteger(sender.tab?.id) || typeof page !== "string"
779
- || pathOf("https://chatgpt.com" + page) !== page) return false;
780
- try {
781
- if (new URL(sender.url).origin !== "https://chatgpt.com") return false;
782
- const tab = await chrome.tabs.get(sender.tab.id);
783
- return pathOf(tab.url) === page;
784
- } catch { return false; }
785
- };
786
-
787
- // Reuse the existing Observer read channel. This checks ONLY the latest
788
- // assistant Turn in the current owned Chat, not historical forms or composer
789
- // fields. An unknown read is never evidence of approval.
790
- async function currentConfirmation(tabId,page,userKey,assistantKey) {
791
- const tab=await chrome.tabs.get(tabId).catch(()=>null);
792
- if(pathOf(tab?.url)!==page)return null;
793
- const proof=await chrome.tabs.sendMessage(tabId,
794
- {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
795
- if(proof?.contract!=="chat-loop.turn-observer.v1"
796
- ||proof.page!==page||proof.userKey!==userKey
797
- ||proof.assistantKey!==assistantKey
798
- ||proof.reason==="WAITING_CHAT_HYDRATION"
799
- ||typeof proof.pendingConfirmation!=="boolean")return null;
800
- return proof.pendingConfirmation;
801
- }
802
- // A transient partial UI snapshot may end with UNKNOWN even when the same
803
- // already-confirmed reply later settles on a valid final status. Only resample
804
- // the exact in-flight user/assistant turn, read-only, before failing closed.
805
- async function recheckUnknownTurn(message, previous, tabId) {
806
- if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== tabId
807
- || previous.page !== message.page || previous.newUserKey !== message.userKey
808
- || previous.assistantKey === message.assistantKey) return null;
809
- const read = async () => {
810
- const tab = await chrome.tabs.get(tabId).catch(() => null);
811
- if (pathOf(tab?.url) !== message.page) return null;
812
- const proof = await chrome.tabs.sendMessage(tabId,
813
- {type: "CHAT_LOOP_TURN_VERIFY_V1"}).catch(() => null);
814
- if (proof?.contract !== "chat-loop.turn-observer.v1" || proof.status !== "READY"
815
- || proof.page !== message.page || proof.userKey !== message.userKey
816
- || proof.assistantKey !== message.assistantKey
817
- || typeof proof.replyText !== "string") return null;
818
- return proof.replyText;
819
- };
820
- for (let attempt = 0; attempt < 8; attempt++) {
821
- const first = await read();
822
- if (first === null) return null;
823
- const parsed = globalThis.ChatLoopCoreV1.parseStatus(first);
824
- if (parsed !== "UNKNOWN") {
825
- await new Promise(resolve => setTimeout(resolve, 2300));
826
- const second = await read();
827
- if (second === first) return {status: parsed, replyText: second};
828
- } else {
829
- await new Promise(resolve => setTimeout(resolve, 1500));
830
- }
831
- }
832
- return null;
833
- }
834
- // A suspended MV3 Worker may lose the Action receipt. Never retry a send
835
- // from a stale RESERVED/PENDING phase; scrub the queued task text and block.
836
- async function expireStaleModelIntent() {
837
- const run=await readRun();
838
- if(!run?.modelIntent || !Number.isSafeInteger(run.modelIntent.queuedAt)
839
- ||Date.now()-run.modelIntent.queuedAt<=MODEL_RECEIPT_TTL_MS)return;
840
- const pendingSend=["RESERVED","PENDING"].includes(run.phase);
841
- const next=settleModelIntent(run,"STALE_UNVERIFIED","INTENT_TTL_EXPIRED");
842
- await saveRun(pendingSend
843
- ?{...next,phase:"BLOCKED",reason:"STALE_INTENT_UNKNOWN_SEND"}
844
- :next);
845
- }
846
- async function onTurnBlocked(message, sender) {
847
- const reason = message.reason;
848
- if (!["PAGE_ERROR", "CONTEXT_LIMIT", "SECURITY_CHALLENGE"].includes(reason)
849
- || !await eligible(sender, message.page)
850
- || typeof message.userKey !== "string" || !/^user:[^\s]{8,}$/.test(message.userKey))
851
- return {status: "DENIED", code: "ERROR_SOURCE_UNVERIFIED"};
852
- const previous = await readRun();
853
- if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== sender.tab.id
854
- || previous.page !== message.page)
855
- return {status: "IGNORED", code: "NOT_OWNED_RUNNING_TURN"};
856
- // An unanswered confirmation can be followed by a new human user Turn.
857
- // If THAT Turn fails, stop the same Owner; never silently ignore its error
858
- // or treat it as an automatically sent Turn eligible for Retry/Handoff.
859
- if(message.userKey!==previous.newUserKey){
860
- const proof=await chrome.tabs.sendMessage(previous.tabId,
861
- {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
862
- const humanFault=proof?.contract==="chat-loop.turn-observer.v1"
863
- &&proof.page===previous.page&&proof.status==="BLOCKED"
864
- &&proof.userKey===message.userKey
865
- &&proof.priorAssistantKey===previous.assistantKey
866
- &&proof.priorAssistantUserKey===previous.userKey
867
- &&proof.directReplyAfterPriorAssistant===true;
868
- if(!humanFault)return {status:"IGNORED",code:"NOT_OWNED_RUNNING_TURN"};
869
- await saveRun({...previous,phase:"BLOCKED",reason:"HUMAN_RESPONSE_PAGE_ERROR"});
870
- return {status:"BLOCKED",code:"HUMAN_RESPONSE_PAGE_ERROR"};
871
- }
872
- const verify = async () => {
873
- const proof = await chrome.tabs.sendMessage(previous.tabId,
874
- {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
875
- return proof?.contract === "chat-loop.turn-observer.v1"
876
- && proof.status === "BLOCKED" && proof.reason === reason
877
- && proof.page === previous.page && proof.userKey === previous.newUserKey
878
- ? proof : null;
879
- };
880
- const first = await verify();
881
- if (!first) return {status: "IGNORED", code: "ERROR_NOT_CONFIRMED"};
882
- await new Promise(resolve => setTimeout(resolve, 400));
883
- const second = await verify();
884
- if (!second || first.retryAvailable !== second.retryAvailable)
885
- return {status: "IGNORED", code: "ERROR_NOT_STABLE"};
886
- // A bounded non-content receipt lets the existing Audit prove which
887
- // decision the ONLY Worker actually took. Never log raw Chat text.
888
- const faultProof = code => ({code, reason, userKey: message.userKey, at: Date.now()});
889
- const recordFault = async code => {
890
- await saveRun({...previous, lastFaultProof: faultProof(code)});
891
- return {status: "IGNORED", code};
892
- };
893
- await saveRun({...previous, lastFaultProof: faultProof("ERROR_CONFIRMED")});
894
- // A network interruption may show a transient page error without a native
895
- // Retry button. Only *observe* for a bounded grace period: never resend an
896
- // uncertain user Turn. Resume normal observation only if the EXACT submitted
897
- // user identity stays present and two consecutive polls show no page fault.
898
- // If the optimistic user message disappears, this is NOT proof of no send.
899
- if (reason === "PAGE_ERROR" && second.retryAvailable !== true) {
900
- let recovered = 0;
901
- for (let attempt = 0; attempt < 4; attempt++) {
902
- await new Promise(resolve => setTimeout(resolve, 1000));
903
- const proof = await chrome.tabs.sendMessage(previous.tabId,
904
- {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
905
- const sameTurn = proof?.contract === "chat-loop.turn-observer.v1"
906
- && proof.page === previous.page
907
- && proof.userKey === previous.newUserKey;
908
- // The Observer may emit its verified completion while this error handler
909
- // owns the serialized Worker queue. That completion message is waiting
910
- // behind us: fail-closing here would discard a real, finished Turn.
911
- // TURN_FINISHED or the exact already-emitted state is sufficient proof
912
- // that the SAME user Turn recovered; do not invent/send another message.
913
- if (sameTurn && (proof.status === "TURN_FINISHED"
914
- || proof.status === "IDLE" && proof.reason === "TURN_ALREADY_EMITTED"))
915
- return recordFault("PAGE_ERROR_COMPLETION_QUEUED");
916
- if (sameTurn && ["RUNNING", "UNKNOWN"].includes(proof.status)) {
917
- recovered++;
918
- if (recovered === 2) return recordFault("PAGE_ERROR_CLEARED_SAME_TURN");
919
- } else recovered = 0;
920
- }
921
- }
922
- // A security challenge is an explicit stop condition, not a prompt to retry
923
- // or evade site access controls. Keep the original Chat and user Turn intact.
924
- if (reason === "SECURITY_CHALLENGE") {
925
- await saveRun({...previous, phase:"BLOCKED", reason,
926
- lastFaultProof:faultProof("SECURITY_CHALLENGE")});
927
- return {status:"BLOCKED", code:reason};
928
- }
929
- // The second capacity failure immediately after an ERROR Handoff must not
930
- // start an infinite series of new ChatGPT conversations.
931
- const errorHandoffCount = previous.errorHandoffCount || 0;
932
- if (reason === "CONTEXT_LIMIT" && errorHandoffCount < 1
933
- || reason === "PAGE_ERROR" && previous.retryCount !== 1 && second.retryAvailable === true) {
934
- const retry = reason === "PAGE_ERROR";
935
- const token = crypto.randomUUID();
936
- let next = {...previous, phase: "RESERVED", action: retry ? "CONTINUE" : "HANDOFF",
937
- token, reason: "", lastFaultProof:faultProof(retry ? "NATIVE_RETRY_ONCE" : "CONTEXT_HANDOFF"),
938
- ...(retry ? {retryMode: "NATIVE", retryCount: 1}
939
- : {handoffMode: "ERROR", errorReason: reason})};
940
- if (previous.modelIntent) {
941
- next=updateModelReceipt(next,previous.modelIntent.id,{
942
- status:"OVERRIDDEN_BY_ERROR",reason,actualAction:next.action});
943
- delete next.modelIntent;
944
- }
945
- await saveRun(next); // Durable before opening the only authorized Action.
946
- try {
947
- const url = chrome.runtime.getURL(retry ? "continue.html" : "handoff.html")
948
- + "?tabId=" + previous.tabId + "&token=" + encodeURIComponent(token);
949
- const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
950
- return {status: "QUEUED", actionTabId: actionTab.id, code: retry ? "NATIVE_RETRY_ONCE" : "CONTEXT_HANDOFF"};
951
- } catch {
952
- await saveRun({...next, phase: "BLOCKED", reason: "ERROR_ACTION_CREATE_FAILED"});
953
- return {status: "BLOCKED", code: "ERROR_ACTION_CREATE_FAILED"};
954
- }
955
- }
956
- const finalReason = reason === "PAGE_ERROR"
957
- ? previous.retryCount === 1 ? "PAGE_ERROR_AFTER_RETRY" : "PAGE_ERROR_NO_RETRY_BUTTON"
958
- : "CONTEXT_HANDOFF_REPEATED";
959
- await saveRun({...previous, phase:"BLOCKED", reason:finalReason,
960
- lastFaultProof:faultProof(finalReason)});
961
- return {status: "BLOCKED", code: reason === "PAGE_ERROR" ? "PAGE_ERROR" : "CONTEXT_HANDOFF_REPEATED"};
962
- }
963
- // A model-driven request can only be queued against a currently RUNNING,
964
- // already-owned user Turn. The MCP call returns immediately: waiting for this
965
- // assistant to finish inside the tool call would deadlock the Turn.
966
- async function onModelIntent(message,sender) {
967
- const action=message?.action;
968
- const file=action==='HANDOFF'?'handoff.html':action==='CONTINUE'?'continue.html':null;
969
- const id=message?.id;
970
- if(!file||!Number.isInteger(sender.tab?.id)||!/^[a-f0-9]{32}$/.test(id||'')
971
- ||sender.url!==chrome.runtime.getURL(file)+'?requestId='+id)
972
- return {status:'DENIED',code:'INVALID_MODEL_INTENT_SOURCE'};
973
- const intent=message.intent;
974
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
975
- ||Object.keys(intent).some(k=>k!=='turnToken' && (action==='CONTINUE'?k!=='nextPrompt':k!=='reason'))
976
- ||typeof intent.turnToken!=='string'
977
- ||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(intent.turnToken))
978
- return {status:'DENIED',code:'INVALID_MODEL_INTENT'};
979
- if(action==='CONTINUE' && (typeof intent.nextPrompt!=='string'
980
- ||!intent.nextPrompt.trim()||intent.nextPrompt.length>4000
981
- ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.nextPrompt))
982
- ||action==='HANDOFF' && intent.reason!==undefined
983
- &&(typeof intent.reason!=='string'||intent.reason.length>400
984
- ||/[\x00-\x1f]/.test(intent.reason)))
985
- return {status:'DENIED',code:'INVALID_MODEL_INTENT'};
986
- const run=await readRun();
987
- if(!run||run.phase!=='WAITING_REPLY'||run.modelTurnToken!==intent.turnToken)
988
- return {status:'DENIED',code:'MODEL_INTENT_OWNER_NOT_RUNNING'};
989
- if(run.modelIntent)
990
- return {status:'DENIED',code:'MODEL_INTENT_ALREADY_QUEUED'};
991
- const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
992
- if(!tab||pathOf(tab.url)!==run.page)
993
- return {status:'DENIED',code:'MODEL_INTENT_OWNER_CHANGED'};
994
- const proof=await chrome.tabs.sendMessage(run.tabId,{
995
- type:'CHAT_LOOP_TURN_OBSERVE_V1',poll:true}).catch(()=>null);
996
- if(proof?.contract!=='chat-loop.turn-observer.v1'||proof.status!=='RUNNING'
997
- ||proof.page!==run.page||proof.userKey!==run.newUserKey)
998
- return {status:'DENIED',code:'MODEL_INTENT_TURN_NOT_RUNNING'};
999
- const next = {...run,modelIntent:{
1000
- id, action, page:run.page, userKey:run.newUserKey,
1001
- ...(action==='CONTINUE'?{nextPrompt:intent.nextPrompt}
1002
- :{reason:intent.reason||''}), queuedAt:Date.now()
1003
- }};
1004
- const correlation=run.sessionId&&run.projectId?{
1005
- sessionId:run.sessionId,projectId:run.projectId,
1006
- ...(run.taskId?{taskId:run.taskId}:{}),generation:run.generation||0}:{};
1007
- await saveRun(updateModelReceipt(next,id,{action,turnToken:intent.turnToken,
1008
- ...correlation,status:'QUEUED',reason:null,actualAction:null,
1009
- checkpointForwarded:false}));
1010
- // Scoped correlation metadata only. This is an intent queue receipt,
1011
- // never proof that a browser send happened.
1012
- return {status:'QUEUED',action,intentId:id,...correlation};
1013
- }
1014
- async function onModelIntentStatus(message,sender) {
1015
- const action=message?.action;
1016
- const file=action==='HANDOFF'?'handoff.html':action==='CONTINUE'?'continue.html':null;
1017
- const id=message?.id, intent=message?.intent;
1018
- if(!file||!Number.isInteger(sender.tab?.id)||!/^[a-f0-9]{32}$/.test(id||'')
1019
- ||sender.url!==chrome.runtime.getURL(file)+'?requestId='+id
1020
- ||!intent||typeof intent!=='object'||Array.isArray(intent)
1021
- ||typeof intent.turnToken!=='string'
1022
- ||!(intent.lookup===true||typeof intent.intentId==='string')
1023
- ||Object.keys(intent).some(k=>k!=='turnToken'&&
1024
- k!==(intent.lookup===true?'lookup':'intentId'))
1025
- ||intent.lookup!==true&& !/^[a-f0-9]{32}$/.test(intent.intentId||''))
1026
- return {status:'DENIED',code:'INTENT_QUERY_UNAUTHORIZED'};
1027
- const run=await readRun();
1028
- const receipts=receiptHistory(run).filter(x=>x.turnToken===intent.turnToken
1029
- &&x.action===action);
1030
- const receipt=intent.lookup===true?receipts.at(-1)
1031
- :receipts.find(x=>x.id===intent.intentId);
1032
- if(!receipt)return {status:'DENIED',code:'INTENT_RECEIPT_NOT_FOUND'};
1033
- return {status:'STATUS',action,intentId:receipt.id,phase:receipt.status,
1034
- ...(receipt.sessionId&&receipt.projectId?{
1035
- sessionId:receipt.sessionId,projectId:receipt.projectId,
1036
- ...(receipt.taskId?{taskId:receipt.taskId}:{}),
1037
- generation:receipt.generation}:{}),
1038
- actualAction:receipt.actualAction||null,reason:receipt.reason||null,
1039
- checkpointForwarded:receipt.checkpointForwarded===true,
1040
- updatedAt:receipt.updatedAt};
1041
- }
1042
- async function onTurnFinished(message, sender) {
1043
- if (!await eligible(sender, message.page)
1044
- || typeof message.userKey !== "string" || !/^user:[^\s]{8,}$/.test(message.userKey)
1045
- || typeof message.assistantKey !== "string"
1046
- || !/^assistant:[^\s]{8,}$/.test(message.assistantKey)
1047
- || typeof message.replyText !== "string" || message.replyText.length > 100000) {
1048
- return {status: "DENIED", code: "UNVERIFIED_TURN_SOURCE"};
1049
- }
1050
- const tabId = sender.tab.id;
1051
- const previous = await readRun();
1052
- // A Chat is owned only after an extension Action has explicitly reserved
1053
- // and confirmed its user Turn. A status marker on an arbitrary Chat never
1054
- // starts or reactivates a loop, including after DONE/BLOCKED.
1055
- if (!previous || ["DONE", "BLOCKED"].includes(previous.phase))
1056
- return {status: "IGNORED", code: "NO_ACTIVE_OWNER"};
1057
- if (previous.tabId !== tabId || previous.page !== message.page)
1058
- return {status: "IGNORED", code: "ANOTHER_CHAT_OWNS_LOOP"};
1059
- if (["PENDING", "RESERVED"].includes(previous.phase))
1060
- return {status: "IGNORED", code: previous.phase};
1061
- if (previous.assistantKey === message.assistantKey
1062
- || previous.userKey === message.userKey)
1063
- return {status: "IGNORED", code: "ALREADY_HANDLED"};
1064
- if (previous.phase !== "WAITING_REPLY")
1065
- return {status: "IGNORED", code: "INVALID_PHASE"};
1066
- // A clicked ChatGPT choice creates a regular NEW user Turn. Its preceding
1067
- // assistant must be the exact already-handled question from this Owner, with
1068
- // no intervening user messages. This keeps the old identity boundary
1069
- // without adding a WAITING_USER phase or a second communication channel.
1070
- const humanReply=["PENDING_CONFIRMATION_DOM","ADOPTED_IDLE_BASELINE"].includes(previous.reason)
1071
- && message.userKey!==previous.newUserKey
1072
- && previous.userKey && previous.assistantKey
1073
- && message.userKey!==previous.userKey
1074
- && message.priorAssistantKey===previous.assistantKey
1075
- && message.priorAssistantUserKey===previous.userKey
1076
- && message.directReplyAfterPriorAssistant===true;
1077
- if (message.userKey !== previous.newUserKey && !humanReply) {
1078
- await saveRun({...previous, phase: "BLOCKED", reason: "REPLY_USER_MISMATCH"});
1079
- return {status: "BLOCKED", code: "REPLY_USER_MISMATCH"};
1080
- }
1081
- const confirmation=await currentConfirmation(tabId,message.page,
1082
- message.userKey,message.assistantKey);
1083
- if (message.pendingConfirmation===true || confirmation===true) {
1084
- // The current assistant still has an unanswered confirmation widget.
1085
- // Do not open a Continue/Handoff Action, even after its old deadline.
1086
- const held=settleModelIntent({...previous,phase:"WAITING_REPLY",
1087
- userKey:message.userKey,assistantKey:message.assistantKey,
1088
- reason:"PENDING_CONFIRMATION_DOM"},
1089
- "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
1090
- await saveRun(held);
1091
- return {status:"IGNORED",code:"PENDING_CONFIRMATION_DOM"};
1092
- }
1093
- if (confirmation===null) {
1094
- await saveRun({...previous,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
1095
- return {status:"BLOCKED",code:"CONFIRMATION_DOM_UNVERIFIED"};
1096
- }
1097
- let replyText = message.replyText;
1098
- let status = globalThis.ChatLoopCoreV1.parseStatus(replyText);
1099
- if (status === "UNKNOWN") {
1100
- const recovery = await recheckUnknownTurn(message, previous, tabId);
1101
- if (recovery) {status = recovery.status; replyText = recovery.replyText;}
1102
- }
1103
- const now = Date.now();
1104
- // Keep the same clock throughout one Chat. A successful Handoff resets it.
1105
- const initial = Number.isSafeInteger(message.startedAt) && message.startedAt > 0
1106
- && message.startedAt <= now ? message.startedAt : now;
1107
- const startedAt = previous?.phase === "WAITING_REPLY"
1108
- ? previous.startedAt || now : initial;
1109
- const timeExpired = now >= startedAt + windowMsOf(previous);
1110
- // Deadline intent can be persisted by the timer even while a Turn RUNS.
1111
- // The decision below still waits for the observer's complete Turn proof.
1112
- const queued = !humanReply && previous?.modelIntent?.page===message.page
1113
- && previous.modelIntent.userKey===message.userKey ? previous.modelIntent : null;
1114
- // Existing DONE/BLOCKED, deadline and page-error policies still win.
1115
- // A queued model request only changes a still-eligible CONTINUE Turn.
1116
- let nextAction = status === "HANDOFF" ? "UNSUPPORTED_MODEL_HANDOFF"
1117
- : (previous?.handoffPending || timeExpired) && status === "CONTINUE"
1118
- ? "HANDOFF" : status === "CONTINUE" && queued
1119
- ? queued.action : status;
1120
- if (nextAction !== "CONTINUE" && nextAction !== "HANDOFF") {
1121
- if (previous?.phase === "WAITING_REPLY" && previous.tabId === tabId) {
1122
- const terminal={...previous, phase:status==="DONE"?"DONE":"BLOCKED",
1123
- reason:status,userKey:message.userKey,assistantKey:message.assistantKey};
1124
- if(status==="DONE"&&previous.contextManaged&&previous.taskId){
1125
- // Check the actual Context delivery BEFORE publishing a durable DONE.
1126
- // A model's machine marker alone is never a committed Task outcome.
1127
- const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1128
- op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
1129
- const fact=observed?.result;
1130
- if(observed?.status!=="OK"||fact?.executionOutcome!=="DONE"
1131
- ||!fact.deliveryRef
1132
- ||fact.runRef!==previous.sessionId+":"+previous.taskId+":"+(previous.generation||0)){
1133
- await saveRun({...terminal,phase:"BLOCKED",
1134
- reason:"CONTEXT_TERMINAL_NOT_COMMITTED",contextTerminalFence:"UNVERIFIED"});
1135
- return {status:"BLOCKED",code:"CONTEXT_TERMINAL_NOT_COMMITTED"};
1136
- }
1137
- // The signed Native fence requires phase DONE; keep a durable
1138
- // PENDING marker that denies IDLE/Start until the fence is verified.
1139
- await saveRun({...terminal,contextTerminalFence:"PENDING"});
1140
- const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1141
- op:"context-control",command:"run.fence.terminal",
1142
- args:{expectedStoreEpoch:previous.contextManaged.storeEpoch,
1143
- writeRequestId:"terminal:"+previous.sessionId+":"+(previous.generation||0),
1144
- expectedTaskRevision:fact.taskRevision,
1145
- expectedBindingRevision:fact.bindingRevision}
1146
- }).catch(()=>null);
1147
- if(fenced?.status!=="OK"||fenced.result?.status!=="TERMINAL_FENCED"){
1148
- // Native DONE cannot regress to BLOCKED. Leave that truthful
1149
- // projection in place, but never treat it as released write rights.
1150
- await saveRun({...terminal,reason:"CONTEXT_TERMINAL_FENCE_UNVERIFIED",
1151
- contextTerminalFence:"UNVERIFIED"});
1152
- return {status:"BLOCKED",code:"CONTEXT_TERMINAL_FENCE_UNVERIFIED"};
1153
- }
1154
- await saveRun({...terminal,contextTerminalFence:"CONFIRMED"});
1155
- }else await saveRun(terminal);
1156
- }
1157
- return {status: "IGNORED", code: nextAction === "UNSUPPORTED_MODEL_HANDOFF"
1158
- ? "MODEL_HANDOFF_DISABLED" : status};
1159
- }
1160
- // Recheck at the last new-authorization boundary, even if a periodic or
1161
- // one-shot alarm was delayed while the Worker handled completion evidence.
1162
- const newlyDue = Date.now() >= startedAt + windowMsOf(previous);
1163
- if (nextAction === "CONTINUE" && newlyDue) nextAction = "HANDOFF";
1164
- const token = crypto.randomUUID();
1165
- const run = {...(previous?.sessionId ? {sessionId: previous.sessionId,
1166
- projectId: previous.projectId,...(previous.taskId?{taskId:previous.taskId}:{}),
1167
- ...(previous.contextManaged?{contextManaged:previous.contextManaged}:{}),
1168
- generation: previous.generation || 0} : {}),
1169
- tabId, page: message.page, userKey: message.userKey,
1170
- assistantKey: message.assistantKey, phase: "RESERVED", token,
1171
- action: nextAction, startedAt, modelReceipts:receiptHistory(previous),
1172
- // Preserve the last recovered message across normal progress: a repair
1173
- // acknowledgement cannot replay that same failed Turn.
1174
- ...(previous?.recoveryAttempts ? {recoveryAttempts:previous.recoveryAttempts,
1175
- ...(previous.recoveryProtocol?{recoveryProtocol:previous.recoveryProtocol}:{}),
1176
- ...(previous.recoverySourceAssistantKey?{recoverySourceAssistantKey:previous.recoverySourceAssistantKey}:{})} : {}),
1177
- // Preserve an explicitly configured window through every Continue and
1178
- // Handoff. Otherwise the clock silently falls back to the default
1179
- // after the first completed Turn, breaking the persisted deadline.
1180
- ...(Number.isSafeInteger(previous?.windowMs) && previous.windowMs > 0
1181
- ? {windowMs:previous.windowMs} : {}),
1182
- ...(previous?.lastFaultProof ? {lastFaultProof:previous.lastFaultProof} : {}),
1183
- ...((previous?.handoffPending || newlyDue) ? {
1184
- handoffPending: true,
1185
- handoffPendingAt: previous?.handoffPendingAt || Date.now()} : {}),
1186
- // A completed Turn is a successful recovery and clears the consecutive error-Handoff guard.
1187
- errorHandoffCount: 0,
1188
- // A timed Handoff uses an Action-local read-only snapshot. Do not keep
1189
- // the entire conversation in storage or embed it in the Action URL.
1190
- handoffMode: nextAction === "HANDOFF" ? "TIMED" : null,
1191
- ...(status==="CONTINUE" && queued
1192
- && (queued.action===nextAction
1193
- ||queued.action==="CONTINUE"&&nextAction==="HANDOFF")
1194
- ? {modelIntent:queued} : {})};
1195
- // Deadline wins, but the queued continuation is retained as a *proposal*
1196
- // in the bounded Handoff packet instead of silently losing task progress.
1197
- const overridden=queued?.action==="CONTINUE"&&nextAction==="HANDOFF";
1198
- const recorded=queued?updateModelReceipt(run,queued.id,{
1199
- status:overridden?"OVERRIDDEN_BY_DEADLINE":"RESERVED",
1200
- actualAction:nextAction,
1201
- reason:overridden?"OVERRIDDEN_BY_DEADLINE":null,
1202
- checkpointForwarded:false}):run;
1203
- // Durable before opening an Action; an uncertain outcome must never be retried.
1204
- await saveRun(recorded);
1205
- try {
1206
- const url = chrome.runtime.getURL(nextAction === "HANDOFF" ? "handoff.html" : "continue.html")
1207
- + "?tabId=" + tabId + "&token=" + encodeURIComponent(token);
1208
- const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
1209
- return {status: "QUEUED", actionTabId: actionTab.id};
1210
- } catch (error) {
1211
- await saveRun({...recorded, phase: "BLOCKED", reason: "ACTION_PAGE_CREATE_FAILED"});
1212
- return {status: "BLOCKED", code: error.message || "ACTION_PAGE_CREATE_FAILED"};
1213
- }
1214
- }
1215
- // Recover ONLY an interrupted pre-send reservation from the old Worker
1216
- // implementation: Chrome said RESERVED, native still said BLOCKED, so no
1217
- // ACTION_TAKE/PENDING/DOM click could have occurred. Invalidate that token
1218
- // through the same authorized scheduler, never by editing the disk file.
1219
- async function repairUncommittedBlockedRecovery(){
1220
- const run=await readRun();
1221
- if(run?.phase!=="RESERVED"
1222
- ||run.recoveryMode!=="TOOL_PREFLIGHT_REPAIRED"
1223
- ||run.recoveryAttempts!==1 || run.recoveryProtocol || !run.sessionId
1224
- ||!Number.isInteger(run.manualActionTabId))
1225
- return run;
1226
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
1227
- {op:"session-read"}).catch(()=>null);
1228
- if(disk?.status!=="OK"||disk.session?.phase!=="BLOCKED"
1229
- ||disk.session.sessionId!==run.sessionId
1230
- ||disk.session.projectId!==run.projectId
1231
- ||disk.session.generation!==(run.generation||0)
1232
- ||disk.session.activeChatId!==chatIdOf("https://chatgpt.com"+run.page))
1233
- return run;
1234
- const restored={...run,phase:"BLOCKED",reason:"BLOCKED",recoveryAttempts:0};
1235
- for(const field of ["recoveryMode","recoverySourceAssistantKey","token",
1236
- "manualActionTabId","actionPendingAt","resourceToken"])
1237
- delete restored[field];
1238
- await saveRun(restored);
1239
- return restored;
1240
- }
1241
- // An adopted, already-approved original Chat has an idle historical Pn answer.
1242
- // This one-shot kickoff is the missing bridge into the FIRST controlled execution
1243
- // Turn. Only the formal Continue Action may request it, with exact Native CAS.
1244
- // There is no direct Worker send, second Owner, or replay of prior approval.
1245
- async function onAdoptKickoffPrepare(message,sender){
1246
- const run=await readRun();
1247
- if(run?.phase!=='WAITING_REPLY'||run.reason!=='ADOPTED_IDLE_BASELINE'
1248
- ||run.action!=='START'||!run.contextManaged||!run.taskId
1249
- ||!run.sessionId||run.generation!==0||run.kickoffAttempted
1250
- ||!Number.isInteger(run.tabId)||run.tabId!==message.tabId
1251
- ||!run.page||run.newUserKey!==run.userKey
1252
- ||!/^assistant:[^\s]{8,}$/.test(run.assistantKey||'')
1253
- ||!Number.isSafeInteger(message.nativeUpdatedAt)
1254
- ||!Number.isInteger(sender.tab?.id)||Date.now()>=deadlineOf(run))
1255
- return {status:'DENIED',code:'ADOPT_KICKOFF_NOT_ELIGIBLE'};
1256
- if(sender.url!==chrome.runtime.getURL('continue.html')
1257
- +'?tabId='+run.tabId+'&adoptKickoffAt='+message.nativeUpdatedAt)
1258
- return {status:'DENIED',code:'ADOPT_KICKOFF_ACTION_INVALID'};
1259
- const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
1260
- if(pathOf(tab?.url)!==run.page)
1261
- return {status:'DENIED',code:'ADOPT_KICKOFF_CHAT_CHANGED'};
1262
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
1263
- if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
1264
- ||disk.session.phase!=='WAITING_REPLY'
1265
- ||disk.session.updatedAt!==message.nativeUpdatedAt)
1266
- return {status:'DENIED',code:'ADOPT_KICKOFF_NATIVE_CHANGED'};
1267
- // run.snapshot requires a business checkpoint. A freshly adopted Task has
1268
- // no checkpoint yet, so use the existing read-only live terminalStatus
1269
- // which verifies the current bound holder without inventing one.
1270
- const status=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1271
- op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
1272
- if(status?.status!=='OK'
1273
- ||status.result?.runRef!==run.sessionId+':'+run.taskId+':0'
1274
- ||!Number.isSafeInteger(status.result?.approvalRevision)
1275
- ||status.result.approvalRevision<1
1276
- ||status.result?.unknownEffectCount!==0
1277
- ||status.result?.executionOutcome==='DONE'
1278
- ||status.result?.deliveryRef)
1279
- return {status:'DENIED',code:'ADOPT_KICKOFF_CONTEXT_UNVERIFIED'};
1280
- const exactId=chatIdOf(tab.url);
1281
- const read=async()=>{
1282
- const approval=await chrome.tabs.sendMessage(tab.id,{
1283
- type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
1284
- explicitChatId:exactId,expectedTaskId:run.taskId}).catch(()=>null);
1285
- const turn=await chrome.tabs.sendMessage(tab.id,{
1286
- type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
1287
- if(approval?.contract!=='chat-loop.turn-observer.v1'
1288
- ||approval.status!=='VERIFIED'||approval.page!==run.page
1289
- ||approval.userKey!==run.userKey
1290
- ||approval.postApprovalAssistantKey!==run.assistantKey
1291
- ||turn?.contract!=='chat-loop.turn-observer.v1'
1292
- ||turn.status!=='READY'||turn.page!==run.page
1293
- ||turn.userKey!==run.userKey||turn.assistantKey!==run.assistantKey
1294
- ||turn.pendingConfirmation
1295
- ||globalThis.ChatLoopCoreV1.parseStatus(turn.replyText)!=='UNKNOWN')
1296
- return null;
1297
- return {userKey:turn.userKey,assistantKey:turn.assistantKey,
1298
- replyText:turn.replyText,rVersion:approval.rVersion,pVersion:approval.pVersion};
1299
- };
1300
- const first=await read();
1301
- if(!first)return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_UNVERIFIED'};
1302
- await new Promise(resolve=>setTimeout(resolve,2300));
1303
- const second=await read();
1304
- if(!second||JSON.stringify(first)!==JSON.stringify(second))
1305
- return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_CHANGED'};
1306
- const token=crypto.randomUUID();
1307
- await saveRun({...run,phase:'RESERVED',action:'CONTINUE',token,
1308
- manualActionTabId:sender.tab.id,
1309
- recoveryMode:'ADOPT_KICKOFF',kickoffAttempted:true});
1310
- return {status:'PREPARED',token,tabId:run.tabId};
1311
- }
1312
- // One-shot recovery of an ALREADY committed same-Chat Adopt whose historical
1313
- // post-approval reply was wrongly classified UNKNOWN. Never writes a composer,
1314
- // retries an action or replaces Context/Owner. Requires exact Native BLOCKED CAS.
1315
- async function onAdoptBaselineRepair(message,sender){
1316
- const prior=await readRun();
1317
- if(prior?.phase!=='BLOCKED'||prior.reason!=='UNKNOWN'
1318
- ||prior.action!=='START'||!prior.contextManaged||!prior.taskId
1319
- ||(prior.recoveryAttempts||0)!==0
1320
- ||!prior.sessionId||!Number.isInteger(prior.tabId)
1321
- ||prior.tabId!==message.tabId||!prior.page
1322
- ||!/^user:[^\s]{8,}$/.test(prior.newUserKey||'')
1323
- ||!/^assistant:[^\s]{8,}$/.test(prior.assistantKey||'')
1324
- ||prior.userKey!==prior.newUserKey)
1325
- return {status:'DENIED',code:'ADOPT_BASELINE_NOT_ELIGIBLE'};
1326
- if(!Number.isSafeInteger(message.nativeUpdatedAt)||message.nativeUpdatedAt<=0
1327
- ||!Number.isInteger(sender.tab?.id))
1328
- return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_SOURCE'};
1329
- const expected=chrome.runtime.getURL('continue.html')
1330
- +'?tabId='+prior.tabId+'&adoptBaselineAt='+message.nativeUpdatedAt;
1331
- if(sender.url!==expected)
1332
- return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_ACTION'};
1333
- const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
1334
- if(pathOf(tab?.url)!==prior.page)
1335
- return {status:'DENIED',code:'ADOPT_BASELINE_CHAT_CHANGED'};
1336
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
1337
- {op:'session-read'}).catch(()=>null);
1338
- if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(prior),disk.session)
1339
- ||disk.session?.phase!=='BLOCKED'
1340
- ||disk.session.updatedAt!==message.nativeUpdatedAt)
1341
- return {status:'DENIED',code:'ADOPT_BASELINE_NATIVE_CHANGED'};
1342
- const exactChatId=chatIdOf(tab.url);
1343
- const read=async()=>{
1344
- const approval=await chrome.tabs.sendMessage(tab.id,
1345
- {type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
1346
- explicitChatId:exactChatId,expectedTaskId:prior.taskId}).catch(()=>null);
1347
- const turn=await chrome.tabs.sendMessage(tab.id,
1348
- {type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
1349
- if(approval?.contract!=='chat-loop.turn-observer.v1'
1350
- ||approval.status!=='VERIFIED'
1351
- ||approval.page!==prior.page
1352
- ||approval.userKey!==prior.newUserKey
1353
- ||approval.postApprovalAssistantKey!==prior.assistantKey
1354
- ||turn?.contract!=='chat-loop.turn-observer.v1'
1355
- ||turn.status!=='READY'||turn.page!==prior.page
1356
- ||turn.userKey!==prior.newUserKey||turn.assistantKey!==prior.assistantKey
1357
- ||turn.pendingConfirmation
1358
- ||globalThis.ChatLoopCoreV1.parseStatus(turn.replyText)!=='UNKNOWN')
1359
- return null;
1360
- return {userKey:turn.userKey,assistantKey:turn.assistantKey,
1361
- replyText:turn.replyText,rVersion:approval.rVersion,pVersion:approval.pVersion};
1362
- };
1363
- const a=await read();
1364
- if(!a)return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_MISSING'};
1365
- await new Promise(resolve=>setTimeout(resolve,2300));
1366
- const b=await read();
1367
- if(!b||JSON.stringify(a)!==JSON.stringify(b))
1368
- return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_CHANGED'};
1369
- // Re-arm the observer as a historical baseline BEFORE Native CAS. Failure
1370
- // cannot leave Native in a half-resumed state. This sends no Chat message.
1371
- const armed=await chrome.tabs.sendMessage(tab.id,{
1372
- type:'CHAT_LOOP_TURN_RESUME_V1',
1373
- page:prior.page,userKey:prior.newUserKey,
1374
- assistantKey:prior.assistantKey,baselineOnly:true,
1375
- startedAt:prior.startedAt
1376
- }).catch(()=>null);
1377
- if(armed?.status!=='RESUMED'||armed.baselineOnly!==true)
1378
- return {status:'DENIED',code:'ADOPT_BASELINE_OBSERVER_UNVERIFIED'};
1379
- await saveRun({...prior,phase:'RESERVED',
1380
- reason:'ADOPT_BASELINE_RECOVERY',
1381
- recoveryMode:'ADOPT_IDLE_BASELINE',recoveryAttempts:1});
1382
- const clean={...prior,phase:'WAITING_REPLY',reason:'ADOPTED_IDLE_BASELINE',
1383
- recoveryAttempts:1,userKey:prior.newUserKey,assistantKey:prior.assistantKey};
1384
- delete clean.recoveryMode;
1385
- await saveRun(clean);
1386
- return {status:'REPAIRED',sessionId:prior.sessionId,taskId:prior.taskId,
1387
- activeChatId:exactChatId,baselineAssistantKey:prior.assistantKey,
1388
- generation:prior.generation||0};
1389
- }
1390
- // Only an explicitly opened, existing Continue Action may reveal a
1391
- // scroll-virtualized *terminal Owner* before the normal double Turn check.
1392
- // This grants no send permit and changes neither Worker nor Native state.
1393
- // The Action alone may scroll the verified Chat UI; the Worker never does.
1394
- async function onManualReveal(message,sender) {
1395
- const run=await readRun();
1396
- if(!run?.sessionId||run.phase!=='BLOCKED'||run.reason!=='BLOCKED'
1397
- ||run.action!=='CONTINUE'||run.recoveryProtocol!==1
1398
- ||!(run.recoveryAttempts>0)
1399
- ||run.recoverySourceAssistantKey===run.assistantKey
1400
- ||run.newUserKey!==run.userKey
1401
- ||!Number.isInteger(run.tabId)||message.tabId!==run.tabId
1402
- ||!Number.isSafeInteger(message.resumeBlockedAt)
1403
- ||message.resumeBlockedAt<=0 ||!Number.isInteger(sender.tab?.id))
1404
- return {status:'DENIED',code:'REVEAL_OWNER_UNVERIFIED'};
1405
- let url;
1406
- try{url=new URL(sender.url);}catch{return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};}
1407
- if(url.origin!==new URL(chrome.runtime.getURL('continue.html')).origin
1408
- ||url.pathname!=='/continue.html'
1409
- ||url.searchParams.size!==2
1410
- ||url.searchParams.get('tabId')!==String(run.tabId)
1411
- ||url.searchParams.get('resumeBlockedAt')!==String(message.resumeBlockedAt))
1412
- return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};
1413
- const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
1414
- if(!tab||pathOf(tab.url)!==run.page)
1415
- return {status:'DENIED',code:'REVEAL_CHAT_CHANGED'};
1416
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
1417
- if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
1418
- ||disk.session.updatedAt!==message.resumeBlockedAt)
1419
- return {status:'DENIED',code:'REVEAL_NATIVE_CAS_UNVERIFIED'};
1420
- return {status:'OK',page:run.page};
1421
- }
1422
- async function onManualPrepare(message, sender) {
1423
- const requested = message.action;
1424
- if (!["CONTINUE", "HANDOFF"].includes(requested)
1425
- || !Number.isInteger(sender.tab?.id)) return {status: "DENIED", code: "INVALID_MANUAL_ACTION"};
1426
- const filename = requested === "HANDOFF" ? "handoff.html" : "continue.html";
1427
- let url;
1428
- try { url = new URL(sender.url); } catch {return {status: "DENIED", code: "INVALID_ACTION_URL"};}
1429
- const rawTabId = url.searchParams.get("tabId");
1430
- // Explicit operator-only migration of 0.3.52's unsent recovery reservation.
1431
- // The old Native Host could NEVER commit BLOCKED -> PENDING. Operator must
1432
- // verify that installed-version provenance before supplying this disk CAS.
1433
- // Modern unknown sends are never eligible, even with the query parameter.
1434
- // Explicit repair acknowledgement binds the operator to the exact disk
1435
- // blocker. It does not claim that the browser can verify business repair.
1436
- const contextRaw=url.searchParams.get("recoverContextNotSentAt");
1437
- const contextAt=contextRaw!==null?Number(contextRaw):null;
1438
- if(contextRaw!==null&&(requested!=="CONTINUE"||!rawTabId
1439
- ||!Number.isSafeInteger(contextAt)||contextAt<=0))
1440
- return {status:"DENIED",code:"INVALID_CONTEXT_NOT_SENT_RECOVERY"};
1441
- const resumeRaw=url.searchParams.get("resumeBlockedAt");
1442
- const resumeAt=resumeRaw!==null?Number(resumeRaw):null;
1443
- if(resumeRaw!==null&&(requested!=="CONTINUE"||!rawTabId
1444
- ||!Number.isSafeInteger(resumeAt)||resumeAt<=0
1445
- ||url.searchParams.has("repairLegacyReservation")))
1446
- return {status:"DENIED",code:"INVALID_BLOCKED_REPAIR"};
1447
- const legacyRaw=url.searchParams.get("repairLegacyReservation");
1448
- const legacyAt=legacyRaw!==null?Number(legacyRaw):null;
1449
- if(legacyRaw!==null&&(requested!=="CONTINUE"||!rawTabId
1450
- ||!Number.isSafeInteger(legacyAt)||legacyAt<=0
1451
- ||!String(legacyAt).match(/^[1-9][0-9]{12}$/)))
1452
- return {status:"DENIED",code:"INVALID_LEGACY_REPAIR"};
1453
- if (url.origin !== new URL(chrome.runtime.getURL(filename)).origin
1454
- || url.pathname !== "/" + filename || url.searchParams.has("token")
1455
- || Array.from(url.searchParams.keys()).some(key => key !== "tabId"&&key!=="repairLegacyReservation"&&key!=="resumeBlockedAt"
1456
- &&key!=="recoverContextNotSentAt")
1457
- || url.searchParams.size!==new Set(url.searchParams.keys()).size
1458
- || (rawTabId !== null && (!/^[1-9][0-9]*$/.test(rawTabId)
1459
- || message.tabId !== Number(rawTabId))))
1460
- return {status: "DENIED", code: "INVALID_ACTION_URL"};
1461
- const previous = await repairUncommittedBlockedRecovery();
1462
- // Existing Owner may recover a *verified resolved* model-level tool blocker
1463
- // via the SAME built-in Continue Action. Never grant a new Owner or create
1464
- // a new conversation. This cannot recover unknown sends/page errors.
1465
- const legacyUnsent=Boolean(legacyAt&&previous?.sessionId
1466
- &&previous.phase==="BLOCKED"&&previous.action==="CONTINUE"
1467
- &&previous.reason==="ACTION_RESULT_TIMEOUT_UNVERIFIED"
1468
- &&previous.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
1469
- &&previous.recoveryAttempts===1&&!previous.recoveryProtocol
1470
- &&previous.newUserKey===previous.userKey
1471
- &&previous.recoverySourceAssistantKey===previous.assistantKey);
1472
- const contextNotSent=Boolean(contextAt&&requested==="CONTINUE"
1473
- &&previous?.sessionId&&previous.taskId&&previous.phase==="BLOCKED"
1474
- &&previous.action==="HANDOFF"
1475
- &&previous.reason==="CONTEXT_HANDOFF_NOT_SENT"
1476
- &&previous.contextHandoff?.sendOutcome==="NOT_SENT"
1477
- &&!previous.contextHandoff.sendBeginAt
1478
- &&Number.isSafeInteger(previous.contextHandoff.terminalActionResultAt)
1479
- &&previous.contextHandoff.attemptId===previous.token
1480
- &&!previous.contextRecoveryAttempted
1481
- &&previous.contextManaged
1482
- &&previous.contextHandoff.targetGeneration===(previous.generation||0)+1);
1483
- const recoveryCandidate=requested==="CONTINUE"
1484
- &&previous?.sessionId&&previous.phase==="BLOCKED"
1485
- &&Number.isInteger(previous.tabId)
1486
- &&(contextNotSent||legacyUnsent||previous.reason==="BLOCKED"
1487
- &&((previous.recoveryAttempts||0)===0||resumeAt
1488
- &&previous.recoverySourceAssistantKey!==previous.assistantKey));
1489
- if (previous && (previous.sessionId&&previous.phase!=="DONE"&&!recoveryCandidate
1490
- || !["DONE", "BLOCKED"].includes(previous.phase)))
1491
- return {status: "DENIED", code: "LOOP_ALREADY_ACTIVE"};
1492
- const candidates = await chrome.tabs.query({url: "https://chatgpt.com/*"});
1493
- const all = candidates.filter(tab => Number.isInteger(tab.id) && pathOf(tab.url));
1494
- let tab;
1495
- if (Number.isInteger(message.tabId)) tab = all.find(item => item.id === message.tabId);
1496
- else if (all.length === 1) tab = all[0];
1497
- else return {status: "DENIED", code: all.length ? "AMBIGUOUS_CHATGPT_TABS" : "NO_CHATGPT_TAB"};
1498
- if (!tab) return {status: "DENIED", code: "TARGET_CHAT_NOT_FOUND"};
1499
- const query = () => chrome.tabs.sendMessage(tab.id, {type: "CHAT_LOOP_TURN_VERIFY_V1"});
1500
- let first;
1501
- try {first = await query();}
1502
- catch {return {status: "DENIED", code: "OBSERVER_NOT_READY"};}
1503
- if (first?.contract !== "chat-loop.turn-observer.v1" || first.status !== "READY"
1504
- || first.page !== pathOf(tab.url)) return {status: "DENIED", code: "TURN_NOT_FINISHED"};
1505
- // A manually opened page is still forbidden from interrupting late updates.
1506
- await new Promise(resolve => setTimeout(resolve, 2300));
1507
- const second = await query().catch(() => null);
1508
- if (second?.status !== "READY" || second.page !== first.page
1509
- || second.userKey !== first.userKey || second.assistantKey !== first.assistantKey
1510
- || second.replyText !== first.replyText) return {status: "DENIED", code: "TURN_NOT_STABLE"};
1511
- const modelStatus = globalThis.ChatLoopCoreV1.parseStatus(first.replyText);
1512
- const ownedRecovery=Boolean(recoveryCandidate
1513
- &&(modelStatus==="BLOCKED"
1514
- ||contextNotSent&&["HANDOFF","CONTINUE"].includes(modelStatus))
1515
- &&Number.isInteger(message.tabId) && message.tabId===previous.tabId
1516
- &&previous.tabId===tab.id&&previous.page===first.page
1517
- &&previous.userKey===first.userKey
1518
- &&previous.assistantKey===first.assistantKey
1519
- // Specific repaired tool capability, not generic BLOCKED, human
1520
- // approval failure, unknown browser send or context exhaustion.
1521
- &&(contextNotSent||resumeAt||/\b(?:adopt|Start)\b/i.test(first.replyText))
1522
- &&!first.pendingConfirmation
1523
- &&!second.pendingConfirmation);
1524
- if (recoveryCandidate && !ownedRecovery)
1525
- return {status:"DENIED",code:"BLOCKED_RECOVERY_UNVERIFIED"};
1526
- if (requested === "CONTINUE" && modelStatus !== "CONTINUE"&&!ownedRecovery
1527
- || requested === "HANDOFF" && !["HANDOFF", "CONTINUE"].includes(modelStatus))
1528
- return {status: "DENIED", code: "ACTION_MARKER_MISMATCH"};
1529
- if (previous && previous.tabId === tab.id && previous.page === first.page
1530
- && (previous.userKey === first.userKey || previous.assistantKey === first.assistantKey)
1531
- &&!ownedRecovery)
1532
- return {status: "DENIED", code: "ALREADY_HANDLED"};
1533
- const summary = modelStatus === "HANDOFF"
1534
- ? first.replyText.replace(/\r?\n\[CHAT_LOOP_STATUS:HANDOFF\]\s*$/, "").trim() : null;
1535
- if (summary && (summary.length < 120 || summary.length > 16000
1536
- || !/目标/.test(summary) || !/已完成|进度/.test(summary)
1537
- || !/下一步|待办/.test(summary)))
1538
- return {status: "DENIED", code: "HANDOFF_PACKET_MISSING"};
1539
- if(ownedRecovery){
1540
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
1541
- {op:"session-read"}).catch(()=>null);
1542
- if(disk?.status!=="OK"||disk.session?.sessionId!==previous.sessionId
1543
- ||disk.session.phase!=="BLOCKED"
1544
- ||disk.session.projectId!==previous.projectId
1545
- ||disk.session.generation!==(previous.generation||0)
1546
- ||disk.session.activeChatId!==chatIdOf(tab.url)
1547
- ||resumeAt&&disk.session.updatedAt!==resumeAt
1548
- ||contextAt&&disk.session.updatedAt!==contextAt
1549
- ||legacyAt&&(!legacyUnsent||disk.session.updatedAt!==legacyAt))
1550
- return {status:"DENIED",code:"BLOCKED_OWNER_PERSISTENCE_UNVERIFIED"};
1551
- }
1552
- const token = crypto.randomUUID();
1553
- await saveRun({...(ownedRecovery?previous:{}),
1554
- tabId: tab.id, page: first.page, userKey: first.userKey,
1555
- assistantKey: first.assistantKey, phase: "RESERVED", token,
1556
- action: requested, startedAt:ownedRecovery?previous.startedAt:Date.now(),
1557
- manualActionTabId: sender.tab.id,
1558
- ...(ownedRecovery?{recoveryMode:contextNotSent?"HANDOFF_NOT_SENT":"TOOL_PREFLIGHT_REPAIRED",
1559
- recoveryAttempts:(previous.recoveryAttempts||0)+1,recoveryProtocol:1,
1560
- ...(resumeAt||legacyUnsent||contextNotSent
1561
- ?{recoveryExpectedNativeAt:contextAt||resumeAt||legacyAt}:{}),
1562
- ...(contextNotSent?{contextSourceMarker:"[CHAT_LOOP_STATUS:"+modelStatus+"]",
1563
- contextRecoveryCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
1564
- x=>x.toString(16).padStart(2,"0")).join(""),
1565
- contextRecoveryAttempted:true}:{}),
1566
- recoverySourceAssistantKey:first.assistantKey}:{}),
1567
- handoffMode: requested === "HANDOFF"
1568
- ? (modelStatus === "HANDOFF" ? "EXPLICIT" : "TIMED") : null,
1569
- ...(summary ? {handoffText: summary} : {})});
1570
- return {status: "PREPARED", token, tabId: tab.id};
1571
- }
1572
- const isAction = (sender, message, run) => {
1573
- if (!Number.isInteger(sender.tab?.id) || typeof sender.url !== "string") return false;
1574
- try {
1575
- const file = run?.action === "HANDOFF" ? "handoff.html" : "continue.html";
1576
- const u = new URL(sender.url);
1577
- const manual = Number.isInteger(run?.manualActionTabId)
1578
- && run.manualActionTabId === sender.tab.id && !u.searchParams.has("token")
1579
- && (!u.searchParams.has("tabId") || u.searchParams.get("tabId") === String(message.tabId));
1580
- return u.origin === new URL(chrome.runtime.getURL(file)).origin
1581
- && u.pathname === "/" + file
1582
- && (manual || u.searchParams.get("token") === message.token
1583
- && u.searchParams.get("tabId") === String(message.tabId));
1584
- } catch { return false; }
1585
- };
1586
- async function onTake(message, sender) {
1587
- const run = await readRun();
1588
- if (!isAction(sender, message, run)) return {status: "DENIED", code: "ACTION_SOURCE_INVALID"};
1589
- if (run?.phase !== "RESERVED" || run.token !== message.token
1590
- || run.tabId !== message.tabId) return {status: "DENIED", code: "ACTION_NOT_RESERVED"};
1591
- const tab = await chrome.tabs.get(run.tabId).catch(() => null);
1592
- if (!tab || pathOf(tab.url) !== run.page) {
1593
- await saveRun({...run, phase: "BLOCKED", reason: "CHAT_TARGET_CHANGED"});
1594
- return {status: "DENIED", code: "CHAT_TARGET_CHANGED"};
1595
- }
1596
- if (run.retryMode!=="NATIVE" && run.handoffMode!=="ERROR") {
1597
- const pending=await currentConfirmation(run.tabId,run.page,
1598
- run.userKey,run.assistantKey);
1599
- if(pending===true) {
1600
- // A widget appeared after the scheduler decided to Continue.
1601
- // Cancel this Action without a send; the same owner observes a fresh
1602
- // user reply through the existing Turn observer.
1603
- const held=settleModelIntent({...run,phase:"WAITING_REPLY",
1604
- newUserKey:run.userKey,reason:"PENDING_CONFIRMATION_DOM"},
1605
- "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
1606
- await saveRun(held);
1607
- return {status:"DENIED",code:"PENDING_CONFIRMATION_DOM"};
1608
- }
1609
- if(pending===null) {
1610
- await saveRun({...run,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
1611
- return {status:"DENIED",code:"CONFIRMATION_DOM_UNVERIFIED"};
1612
- }
1613
- }
1614
- let projectContext=null;
1615
- if(run.action==='HANDOFF'&&run.sessionId){
1616
- const durable=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
1617
- const projection=sessionProjection(run);
1618
- if(durable?.status!=='OK'
1619
- ||!matchesNativeProjection(projection,durable.session)
1620
- ||durable.contextStatus==='UNVERIFIED'
1621
- ||durable.projectContext&&durable.projectContext.projectId!==run.projectId){
1622
- await saveRun({...run,phase:'BLOCKED',reason:'HANDOFF_CONTEXT_UNVERIFIED'});
1623
- return {status:'DENIED',code:'HANDOFF_CONTEXT_UNVERIFIED'};
1624
- }
1625
- projectContext=durable.projectContext||null;
1626
- }
1627
- // Bind a model-control capability to the next *user* Turn, not to a tab or to another Chat.
1628
- // Acceptance fixtures retain their existing prompts; native Retry keeps its original Turn token.
1629
- const modelTurnToken = run.retryMode === "NATIVE"
1630
- ? run.modelTurnToken || null : crypto.randomUUID();
1631
- let recoveredContext=null;
1632
- if(run.action==="CONTINUE" && run.recoveryMode==="HANDOFF_NOT_SENT"){
1633
- const h=run.contextHandoff;
1634
- if(!run.contextRecoveryCredential || !h || h.sendOutcome!=="NOT_SENT"
1635
- ||h.sendBeginAt ||h.attemptId===run.token){
1636
- await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_NOT_SENT_PROOF_INVALID"});
1637
- return {status:"DENIED",code:"CONTEXT_NOT_SENT_PROOF_INVALID"};
1638
- }
1639
- const snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1640
- op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
1641
- const cp=snapshot?.result;
1642
- if(snapshot?.status!=="OK" || cp.taskRevision!==h.taskRevision
1643
- ||cp.bindingRevision!==h.bindingRevision ||cp.runRef!==null
1644
- ||cp.checkpointId!==h.checkpointId ||cp.unknownEffectCount!==0){
1645
- await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_SNAPSHOT_UNVERIFIED"});
1646
- return {status:"DENIED",code:"CONTEXT_RESTORE_SNAPSHOT_UNVERIFIED"};
1647
- }
1648
- const approval=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1649
- op:"context-control",command:"permit.consume",
1650
- args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:run.token+":permit",
1651
- actionToken:run.token,kind:"CONTINUE",expectedTaskRevision:h.taskRevision,
1652
- expectedApprovalRevision:cp.approvalRevision}
1653
- }).catch(()=>null);
1654
- if(approval?.status!=="OK"||approval.result?.status!=="PERMITTED"){
1655
- await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_PERMIT_UNVERIFIED"});
1656
- return {status:"DENIED",code:"CONTEXT_RESTORE_PERMIT_UNVERIFIED"};
1657
- }
1658
- const restored=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1659
- op:"context-control",command:"run.restore-same-owner",
1660
- args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:run.token+":restore",
1661
- expectedTaskRevision:h.taskRevision,expectedBindingRevision:h.bindingRevision,
1662
- attemptId:h.attemptId,checkpointId:h.checkpointId,
1663
- recoveryCredential:run.contextRecoveryCredential,
1664
- recoveryActionToken:run.token,sendState:"NOT_SENT"}
1665
- }).catch(()=>null);
1666
- if(restored?.status!=="OK"||restored.result?.status!=="RESTORED_SAME_OWNER"){
1667
- await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_BIND_UNVERIFIED"});
1668
- return {status:"DENIED",code:"CONTEXT_RESTORE_BIND_UNVERIFIED"};
1669
- }
1670
- recoveredContext={runRef:restored.result.runRef,
1671
- runCredential:run.contextRecoveryCredential,storeEpoch:h.storeEpoch,
1672
- bindingRevision:restored.result.bindingRevision,taskRevision:h.taskRevision};
1673
- }
1674
- const pending={...run, phase: "PENDING", modelTurnToken,
1675
- ...(recoveredContext?{contextRecoveryBound:recoveredContext}:{})};
1676
- await saveRun(run.modelIntent ? updateModelReceipt(pending,run.modelIntent.id,{
1677
- status:run.action==="HANDOFF"&&run.modelIntent.action==="CONTINUE"
1678
- ?"OVERRIDDEN_BY_DEADLINE":"PENDING"}) : pending);
1679
- if(run.action==="CONTINUE" &&run.contextManaged &&!recoveredContext &&run.retryMode!=="NATIVE"){
1680
- let snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1681
- op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
1682
- // First controlled Continue may precede the FIRST business checkpoint.
1683
- // Only a proven CHECKPOINT_NOT_FOUND may use the current live task/run
1684
- // projection. Network errors and all other snapshot failures stay BLOCKED.
1685
- if(snapshot?.status!=="OK"&&snapshot?.code==="CHECKPOINT_NOT_FOUND")
1686
- snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1687
- op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
1688
- const cp=snapshot?.result;
1689
- if(snapshot?.status!=="OK"||!cp ||cp.runRef!==
1690
- run.sessionId+":"+run.taskId+":"+(run.generation||0)
1691
- ||!Number.isSafeInteger(cp.taskRevision)||cp.taskRevision<1
1692
- ||!Number.isSafeInteger(cp.approvalRevision)||cp.approvalRevision<1
1693
- ||cp.unknownEffectCount!==0||cp.executionOutcome==="DONE"){
1694
- await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CONTINUE_SNAPSHOT_UNVERIFIED"});
1695
- return {status:"DENIED",code:"CONTEXT_CONTINUE_SNAPSHOT_UNVERIFIED"};
1696
- }
1697
- const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1698
- op:"context-control",command:"permit.consume",
1699
- args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
1700
- writeRequestId:run.token+":permit",expectedTaskRevision:cp.taskRevision,
1701
- expectedApprovalRevision:cp.approvalRevision,
1702
- actionToken:run.token,kind:"CONTINUE"}
1703
- }).catch(()=>null);
1704
- if(allowed?.status!=="OK"||allowed.result?.status!=="PERMITTED"){
1705
- await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CONTINUE_PERMIT_UNVERIFIED"});
1706
- return {status:"DENIED",code:"CONTEXT_CONTINUE_PERMIT_UNVERIFIED"};
1707
- }
1708
- }
1709
- let managedHandoff=null;
1710
- if(run.action==="HANDOFF"&&run.contextManaged){
1711
- if(!run.taskId||!run.sessionId){
1712
- await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_TASK_IDENTITY_MISSING"});
1713
- return {status:"DENIED",code:"CONTEXT_TASK_IDENTITY_MISSING"};
1714
- }
1715
- const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1716
- op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
1717
- const cp=proof?.result;
1718
- if(proof?.status!=="OK"||!cp?.checkpointCurrent||cp.unknownEffectCount!==0
1719
- ||cp.runRef!==run.sessionId+":"+run.taskId+":"+(run.generation||0)){
1720
- await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CHECKPOINT_UNVERIFIED"});
1721
- return {status:"DENIED",code:"CONTEXT_CHECKPOINT_UNVERIFIED"};
1722
- }
1723
- const permitProof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1724
- op:"context-control",command:"permit.consume",
1725
- args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
1726
- writeRequestId:run.token+":permit",actionToken:run.token,kind:"HANDOFF",
1727
- expectedTaskRevision:cp.taskRevision,
1728
- expectedApprovalRevision:cp.approvalRevision}
1729
- }).catch(()=>null);
1730
- if(permitProof?.status!=="OK"||permitProof.result?.status!=="PERMITTED"){
1731
- await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_HANDOFF_PERMIT_UNVERIFIED"});
1732
- return {status:"DENIED",code:"CONTEXT_HANDOFF_PERMIT_UNVERIFIED"};
1733
- }
1734
- const nextRunCredential=Array.from(crypto.getRandomValues(new Uint8Array(32)),
1735
- x=>x.toString(16).padStart(2,"0")).join("");
1736
- const targetGeneration=(run.generation||0)+1;
1737
- const nextRunRef=run.sessionId+":"+run.taskId+":"+targetGeneration;
1738
- const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1739
- op:"context-control",command:"run.fence",
1740
- args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
1741
- writeRequestId:run.token+":fence",expectedTaskRevision:cp.taskRevision,
1742
- expectedBindingRevision:cp.bindingRevision,checkpointId:cp.checkpointId,
1743
- attemptId:run.token,actionToken:run.token,targetGeneration,
1744
- nextRunRef,nextRunCredential}
1745
- }).catch(()=>null);
1746
- if(fenced?.status!=="OK"||fenced.result?.status!=="FENCED"){
1747
- await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_HANDOFF_FENCE_UNVERIFIED"});
1748
- return {status:"DENIED",code:"CONTEXT_HANDOFF_FENCE_UNVERIFIED"};
1749
- }
1750
- managedHandoff={attemptId:run.token,checkpointId:cp.checkpointId,
1751
- taskRevision:cp.taskRevision,bindingRevision:fenced.result.bindingRevision,
1752
- targetGeneration,nextRunRef,nextRunCredential,
1753
- storeEpoch:run.contextManaged.storeEpoch};
1754
- await saveRun({...pending,contextHandoff:managedHandoff});
1755
- }
1756
- const permit = {status: "OK", action: run.action || "CONTINUE",
1757
- modelTurnToken,
1758
- modelTurnNote: modelTurnToken ? turnToolNote(modelTurnToken) : "",
1759
- handoffMode: run.handoffMode || null, retryMode: run.retryMode || null,
1760
- ...(projectContext?{projectContext}:{}),
1761
- ...(managedHandoff?{contextHandoff:{...managedHandoff,
1762
- projectId:run.projectId,taskId:run.taskId,sessionId:run.sessionId}}:{}),
1763
- target: {tabId: run.tabId, page: run.page,
1764
- ...(run.sessionId?{sessionId:run.sessionId,projectId:run.projectId,
1765
- ...(run.taskId?{taskId:run.taskId}:{}),generation:run.generation||0}:{}),
1766
- recoveryMode:run.recoveryMode||null,
1767
- ...(run.contextSourceMarker?{contextSourceMarker:run.contextSourceMarker}:{}),
1768
- assistantKey: run.assistantKey,
1769
- userKey: run.retryMode === "NATIVE" || run.handoffMode === "ERROR"
1770
- ? run.newUserKey : run.userKey,
1771
- },
1772
- modelIntent: run.action==="HANDOFF" && run.modelIntent?.action==="HANDOFF"
1773
- ? {id:run.modelIntent.id,reason:run.modelIntent.reason||""} : null,
1774
- pendingPlan: run.action==="HANDOFF" && run.modelIntent?.action==="CONTINUE"
1775
- ? {id:run.modelIntent.id,nextPrompt:run.modelIntent.nextPrompt} : null,
1776
- text: run.action === "HANDOFF" ? run.handoffText || null
1777
- : run.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
1778
- ? "【Chat Loop 同 Chat 受控恢复】上一轮以 BLOCKED 结束;当前恢复已通过唯一 Owner、原 Chat 和 Native 身份核验,但不代表工程问题已自动解决。不要再次调用 Start、不要新建 Chat、不要重复 R/P 审批。首先核实原工作区真实状态、已执行副作用和当前 Tools 可调用能力,再依据原任务唯一检查点继续尚未完成的工作、测试与迭代;若仍有真实风险如实 BLOCKED,不要再次反复自恢复。本轮结束末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
1779
- : run.recoveryMode==="ADOPT_KICKOFF"
1780
- ? "【Chat Loop 原 Chat 已正式 Start/adopt】这是当前已批准 R2/P3 Task 的第一条受控执行消息,不是新的需求或审批。请从真实 Context 读取 Task、已批准的计划及 Stage03 QA 报告,完成剩余可安全的验收工作项;不得重做旧 H UNKNOWN 首发,不得新建执行 Chat,也不得重复 R/P。若所有批准的工作项确实满足 DONE,先按 SDK 正式提交 Task delivery(没有权限则不要伪造),再输出唯一 DONE 状态;存在安全的待做工作则输出 CONTINUE,关键身份/副作用不可信则输出 BLOCKED。末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
1781
- : run.modelIntent?.action==="CONTINUE" ? (
1782
- "【Chat Loop 续接来源】上一轮由模型登记的 Continue 请求 " + run.modelIntent.id
1783
- + " 已被扩展唯一 Action 领取。\n"
1784
- + "【待核实的模型下一步计划(并非用户新增授权)】\n"
1785
- + run.modelIntent.nextPrompt + "\n\n"
1786
- + "执行前核对当前项目状态、既有用户授权和已完成副作用,不重做不明操作。"
1787
- + "本轮完成后,末行只输出一个状态标记:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。")
1788
- : CONTINUE_TEXT};
1789
- // A single error contract applies to default, model-specified and repaired
1790
- // Continue prompts; the Worker still obeys the model's terminal marker.
1791
- if(run.action==="CONTINUE" && typeof permit.text==="string"){
1792
- permit.text=ENGINEERING_FAILURE_NOTE+"\n\n"+permit.text;
1793
- if(recoveredContext){
1794
- permit.text += "\n\n【Chat Loop Context|HANDOFF_NOT_SENT 单次恢复写凭据】\n"
1795
- +JSON.stringify({projectId:run.projectId,taskId:run.taskId,
1796
- sessionId:run.sessionId,generation:run.generation||0,
1797
- ...recoveredContext})+"\n请先按原 Session 核实 Context 与未知副作用,"
1798
- +"此凭据仅用于当前任务 Context 写入;旧 Handoff 不得重新发送。";
1799
- }
1800
- }
1801
- if (modelTurnToken && typeof permit.text === "string")
1802
- permit.text += permit.modelTurnNote;
1803
- return permit;
1804
- }
1805
- // Durable pre-send evidence; once recorded a browser send may have happened.
1806
- // A later timeout is UNKNOWN, never equivalent to NOT_SENT.
1807
- async function onHandoffSendBegin(message,sender){
1808
- const run=await readRun();
1809
- if(!isAction(sender,message,run)||run?.action!=="HANDOFF"
1810
- ||run.phase!=="PENDING"||!run.contextHandoff
1811
- ||run.token!==message.token||run.tabId!==message.tabId)
1812
- return {status:"DENIED",code:"HANDOFF_SEND_SOURCE_INVALID"};
1813
- if(run.contextHandoff.sendBeginAt)
1814
- return {status:"DENIED",code:"HANDOFF_SEND_ALREADY_BEGUN"};
1815
- await saveRun({...run,contextHandoff:{...run.contextHandoff,sendBeginAt:Date.now()}});
1816
- return {status:"RECORDED"};
1817
- }
1818
- async function onResult(message, sender) {
1819
- const run = await readRun();
1820
- if (!isAction(sender, message, run)) return {status: "DENIED", code: "ACTION_SOURCE_INVALID"};
1821
- if (run?.phase !== "PENDING" || run.token !== message.token)
1822
- return {status: "DENIED", code: "ACTION_NOT_PENDING"};
1823
- // Native Retry does not submit another user message. One-time click is
1824
- // confirmed separately and re-arms the already-owned pending user Turn.
1825
- if (run.retryMode === "NATIVE") {
1826
- const tab = await chrome.tabs.get(run.tabId).catch(() => null);
1827
- const confirmedRetry = message.result === "RETRY_CLICKED" && tab
1828
- && pathOf(tab.url) === run.page && run.retryCount === 1;
1829
- const nextRetry = {...run, phase: confirmedRetry ? "WAITING_REPLY" : "BLOCKED",
1830
- reason: confirmedRetry ? "" : "RETRY_UNVERIFIED"};
1831
- delete nextRetry.retryMode;
1832
- await saveRun(nextRetry);
1833
- if (confirmedRetry) {
1834
- const reset = await chrome.tabs.sendMessage(run.tabId,
1835
- {type: "CHAT_LOOP_TURN_RETRY_MONITOR_V1", page: run.page,
1836
- userKey: run.newUserKey}).catch(() => null);
1837
- if (reset?.status !== "REARMED") {
1838
- await saveRun({...nextRetry, phase: "BLOCKED", reason: "RETRY_OBSERVER_UNVERIFIED"});
1839
- return {status: "BLOCKED", code: "RETRY_OBSERVER_UNVERIFIED"};
1840
- }
1841
- }
1842
- return {status: confirmedRetry ? "OK" : "BLOCKED"};
1843
- }
1844
- let confirmed = message.result === "SENT_CONFIRMED"
1845
- && typeof message.newUserKey === "string"
1846
- && /^user:[^\s]{8,}$/.test(message.newUserKey)
1847
- && message.newUserKey !== run.userKey;
1848
- const failure = typeof message.reason === "string" && /^[A-Z0-9_]{4,100}$/.test(message.reason)
1849
- ? message.reason : "SEND_UNVERIFIED";
1850
- let next = {...run, phase: "BLOCKED", reason: failure};
1851
- // Diagnostic only: retain the possibly-created target without granting ownership.
1852
- if (run.action === "HANDOFF" && Number.isInteger(message.newTabId))
1853
- next.attemptedNewTabId = message.newTabId;
1854
- if (confirmed && run.action === "HANDOFF") {
1855
- const newTab = Number.isInteger(message.newTabId)
1856
- ? await chrome.tabs.get(message.newTabId).catch(() => null) : null;
1857
- confirmed = Boolean(newTab && message.newTabId !== run.tabId
1858
- && pathOf(newTab.url) && pathOf(newTab.url) === message.newPage);
1859
- if (confirmed) {
1860
- // Transfer the single loop owner. The old Chat remains open for audit.
1861
- next = {...run, action: "HANDOFF", sourceTabId: run.tabId,
1862
- sourcePage: run.page, tabId: newTab.id, page: message.newPage,
1863
- // Keep source identities as the already-processed baseline; the new
1864
- // user's first reply must not be suppressed by duplicate detection.
1865
- newUserKey: message.newUserKey, phase: "WAITING_REPLY", reason: "",
1866
- ...(run.sessionId?{generation:(run.generation||0)+1}:{}),
1867
- // The new Chat has no previous assistant message. Never authenticate
1868
- // its first Retry/Error Handoff using the OLD Chat's assistant ID.
1869
- userKey: null, assistantKey: null, startedAt: Date.now(),
1870
- errorHandoffCount: run.handoffMode === "ERROR" ? (run.errorHandoffCount || 0) + 1 : 0,
1871
- };
1872
- delete next.handoffText;
1873
- delete next.errorReason;
1874
- delete next.handoffPending;
1875
- delete next.handoffPendingAt;
1876
- delete next.deadlineAt;
1877
- }
1878
- } else if (confirmed) {
1879
- next = {...run, phase: "WAITING_REPLY", reason: "",
1880
- newUserKey: message.newUserKey};
1881
- }
1882
- // A model prompt is one-shot. Keep only a short receipt, not the prompt
1883
- // body, after the Action has reached a confirmed or blocked terminal state.
1884
- // The kickoff exception applies to ONE historical P3 reply only.
1885
- // Remove it after this send attempt; subsequent Continue Turns must carry
1886
- // ordinary independent terminal markers and never inherit the exception.
1887
- if(run.recoveryMode==="ADOPT_KICKOFF")delete next.recoveryMode;
1888
- if(run.modelIntent){
1889
- const override=run.action==="HANDOFF"&&run.modelIntent.action==="CONTINUE";
1890
- const finalStatus=confirmed?"SENT_CONFIRMED":"BLOCKED";
1891
- next=updateModelReceipt(next,run.modelIntent.id,{
1892
- status:finalStatus,actualAction:run.action,
1893
- reason:override?"OVERRIDDEN_BY_DEADLINE":confirmed?null:failure,
1894
- checkpointForwarded:confirmed&&override});
1895
- // The bounded modelReceipts entry above is the unique final intent record.
1896
- delete next.modelIntent;
1897
- }
1898
- if (!confirmed) delete next.modelTurnToken;
1899
- if(confirmed&&run.recoveryMode==="HANDOFF_NOT_SENT"){
1900
- for(const key of ["contextRecoveryCredential","contextRecoveryBound",
1901
- "contextHandoff","recoveryMode","contextSourceMarker",
1902
- "recoveryExpectedNativeAt","recoverySourceAssistantKey",
1903
- "recoveryProtocol","recoveryAttempts","contextRecoveryAttempted"])
1904
- delete next[key];
1905
- }
1906
- if(!confirmed && run.action==="HANDOFF" && run.contextHandoff){
1907
- const notSent=!run.contextHandoff.sendBeginAt;
1908
- next={...next,reason:notSent?"CONTEXT_HANDOFF_NOT_SENT":"CONTEXT_HANDOFF_SEND_UNKNOWN",
1909
- contextHandoff:{...run.contextHandoff,
1910
- sendOutcome:notSent?"NOT_SENT":"SEND_UNKNOWN",
1911
- // This is derived ONLY after original Action Result is received.
1912
- terminalActionResultAt:Date.now()}};
1913
- }
1914
- await saveRun(next);
1915
- if(confirmed && run.action==="HANDOFF" && run.contextHandoff){
1916
- const h=run.contextHandoff;
1917
- const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1918
- op:"context-control",command:"run.bind.handoff",
1919
- args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:h.attemptId+":bind",
1920
- expectedTaskRevision:h.taskRevision,expectedBindingRevision:h.bindingRevision,
1921
- attemptId:h.attemptId,checkpointId:h.checkpointId,
1922
- targetGeneration:h.targetGeneration,runCredential:h.nextRunCredential}
1923
- }).catch(()=>null);
1924
- if(bound?.status!=="OK"||bound.result?.status!=="BOUND"){
1925
- const failed={...next,phase:"BLOCKED",reason:"CONTEXT_NEW_OWNER_BIND_UNVERIFIED"};
1926
- // Retain the exact original attempt and pending credential in private
1927
- // Worker storage for receipt-only diagnosis. Never re-send the message.
1928
- await saveRun(failed);
1929
- return {status:"BLOCKED",code:bound?.code||"CONTEXT_NEW_OWNER_BIND_UNVERIFIED"};
1930
- }
1931
- const clean={...next,contextManaged:{storeEpoch:h.storeEpoch}};
1932
- delete clean.contextHandoff;
1933
- await saveRun(clean); // secret has already been delivered in the unique first message
1934
- }
1935
- if(confirmed && run.action==="HANDOFF" && Number.isInteger(message.newTabId))
1936
- await resources.confirmChat(message.newTabId,next.sessionId||next.token,
1937
- "https://chatgpt.com"+message.newPage).catch(()=>{});
1938
- return {status: confirmed ? "OK" : "BLOCKED"};
1939
- }
1940
- // Extension updates invalidate previous injected listeners. Reconnect only its own observers.
1941
- async function reconnectOpenChats() {
1942
- const tabs = await chrome.tabs.query({url: "https://chatgpt.com/*"});
1943
- for (const tab of tabs) {
1944
- if (!Number.isInteger(tab.id) || !pathOf(tab.url) && !/^https:\/\/chatgpt\.com\/$/.test(tab.url)) continue;
1945
- try {
1946
- await chrome.scripting.executeScript({target: {tabId: tab.id},
1947
- files: ["content.js", "loop/observer.js"]});
1948
- const owner = await readRun();
1949
- if (owner?.phase === "WAITING_REPLY" && owner.tabId === tab.id
1950
- && owner.page === pathOf(tab.url) && owner.newUserKey) {
1951
- // Normal WAITING_REPLY uses its original zero-extra-read resume.
1952
- // Only a previously seen pending confirmation needs an extra DOM
1953
- // identity check for a human response that arrived during reload.
1954
- const proof=owner.reason==="PENDING_CONFIRMATION_DOM"
1955
- ? await chrome.tabs.sendMessage(tab.id,
1956
- {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null)
1957
- :null;
1958
- const freshUser=proof?.page===owner.page
1959
- && proof.userKey!==owner.newUserKey
1960
- && proof.priorAssistantKey===owner.assistantKey
1961
- && proof.priorAssistantUserKey===owner.userKey
1962
- && proof.directReplyAfterPriorAssistant===true;
1963
- const res = await chrome.tabs.sendMessage(tab.id, {
1964
- type: "CHAT_LOOP_TURN_RESUME_V1", page: owner.page,
1965
- userKey:freshUser?proof.userKey:owner.newUserKey,
1966
- assistantKey: owner.assistantKey || null,
1967
- ...(owner.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
1968
- startedAt: owner.startedAt
1969
- }).catch(() => null);
1970
- if (res?.status !== "RESUMED" && res?.status !== "ALREADY_MONITORING")
1971
- console.warn("Chat Loop pending Turn resume not yet verified:", res?.reason || res?.status);
1972
- }
1973
- } catch (error) {console.warn("Chat Loop observer reconnect unavailable:", error?.message);}
1974
- }
1975
- }
1976
- // MV3 background service workers can suspend, and hidden-page setInterval
1977
- // may be throttled. An alarm asks the Observer to sample, never acts directly.
1978
- async function ensureAlarm() {
1979
- if (!chrome.alarms?.create) return;
1980
- const existing = await chrome.alarms.get?.(ALARM_NAME).catch(() => null);
1981
- if (!existing) await chrome.alarms.create(ALARM_NAME, {periodInMinutes: 1});
1982
- }
1983
- async function watchActiveTurn() {
1984
- // One bounded reconciliation on the existing 1-minute Worker alarm.
1985
- await serial(async()=>{await expireStaleAction();
1986
- await resources.reconcile(await readRun()).catch(()=>{});});
1987
- // Normal periodic wakeups also reconcile a delayed one-shot deadline.
1988
- // All state changes share the same serial queue as Turn/Action receipts.
1989
- await serial(async()=>{await expireStaleModelIntent();await prepareHandoffIfDue();});
1990
- const run = await readRun();
1991
- // While an Action is pending, never dispatch competing operations.
1992
- if (run && ["RESERVED", "PENDING"].includes(run.phase)) return;
1993
- const tabs = run?.phase === "WAITING_REPLY"
1994
- ? [await chrome.tabs.get(run.tabId).catch(() => null)]
1995
- : await chrome.tabs.query({url: "https://chatgpt.com/*"});
1996
- for (const tab of tabs) {
1997
- if (!tab?.id || !pathOf(tab.url)) continue;
1998
- try {
1999
- const proof = await chrome.tabs.sendMessage(tab.id,
2000
- {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true});
2001
- // A reloaded Observer may have mistaken the in-flight user Turn for
2002
- // historical baseline. Its IDLE state is not proof of completion.
2003
- // Rebind the exact persisted owner using read-only verification.
2004
- const freshHuman=run?.phase==="WAITING_REPLY" && run.tabId===tab.id
2005
- && proof?.page===run.page && proof.userKey!==run.newUserKey
2006
- && proof.priorAssistantKey===run.assistantKey
2007
- && proof.priorAssistantUserKey===run.userKey
2008
- && proof.directReplyAfterPriorAssistant===true;
2009
- if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
2010
- && proof?.page === run.page
2011
- && (proof.userKey === run.newUserKey || freshHuman)
2012
- && (proof.status === "IDLE"
2013
- || proof.status === "UNKNOWN"
2014
- && ["ATTACHING_CHAT", "WAITING_CHAT_HYDRATION"].includes(proof.reason))) {
2015
- await chrome.tabs.sendMessage(tab.id, {
2016
- type: "CHAT_LOOP_TURN_RESUME_V1", page: run.page,
2017
- userKey: freshHuman?proof.userKey:run.newUserKey,
2018
- assistantKey: run.assistantKey || null,
2019
- ...(run.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
2020
- startedAt: run.startedAt
2021
- }).catch(() => null);
2022
- }
2023
- // A human response can fail after the previous question was kept in
2024
- // WAITING_REPLY. Do not let this become an indefinite silent wait.
2025
- if(freshHuman && proof.status==="BLOCKED") {
2026
- void serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
2027
- reason:proof.reason||"PAGE_ERROR"},
2028
- {tab,url:tab.url}));
2029
- }
2030
- // Alarm is still read-only. It may reconcile a verified page failure if
2031
- // the observer's original notification was lost while Worker slept.
2032
- if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
2033
- && proof?.status === "BLOCKED" && ["PAGE_ERROR","CONTEXT_LIMIT","SECURITY_CHALLENGE"].includes(proof.reason)
2034
- && proof.page === run.page && proof.userKey === run.newUserKey) {
2035
- void serial(() => onTurnBlocked({page: run.page,
2036
- userKey: run.newUserKey, reason: proof.reason},
2037
- {tab, url: tab.url}));
2038
- }
2039
- } catch { /* Observer unavailable; never infer Turn completion. */ }
2040
- }
2041
- }
2042
- chrome.alarms?.onAlarm?.addListener(alarm => {
2043
- if (alarm?.name === ALARM_NAME) void watchActiveTurn();
2044
- if (alarm?.name === DEADLINE_ALARM_NAME)
2045
- void serial(prepareHandoffIfDue);
2046
- });
2047
- chrome.runtime.onInstalled?.addListener(() => {
2048
- void ensureAlarm();
2049
- void serial(async()=>{await expireStaleAction();
2050
- await resources.reconcile(await readRun()).catch(()=>{});});
2051
- void reconnectOpenChats();
2052
- });
2053
- chrome.runtime.onStartup?.addListener(() => {
2054
- void ensureAlarm();
2055
- void serial(async()=>{await expireStaleAction();
2056
- await resources.reconcile(await readRun()).catch(()=>{});});
2057
- void reconnectOpenChats();
2058
- });
2059
- void ensureAlarm();
2060
- // Reconcile an elapsed deadline after MV3 Worker suspension/reload.
2061
- void serial(async()=>{await expireStaleAction();
2062
- await resources.reconcile(await readRun()).catch(()=>{});
2063
- await prepareHandoffIfDue();});
2064
- // A manual extension Reload does not necessarily fire onInstalled/onStartup.
2065
- // Reattach the two idempotent read-only scripts to existing ChatGPT tabs.
2066
- void reconnectOpenChats();
2067
- // User-clicked popup Clean must share the same Action quota as Worker actions.
2068
- // The popup cannot create extra Chrome tabs directly.
2069
- async function openPopupClean(message,sender) {
2070
- if(sender?.url!==chrome.runtime.getURL('popup.html')
2071
- ||!Number.isSafeInteger(message?.tabId)||message.tabId<=0)
2072
- return {status:'DENIED',code:'POPUP_SOURCE_INVALID'};
2073
- const target=await chrome.tabs.get(message.tabId).catch(()=>null);
2074
- let valid=false;
2075
- try {valid=target?.active===true && Number.isSafeInteger(target.windowId)
2076
- && new URL(target.url).origin==='https://chatgpt.com';} catch {}
2077
- if(!valid)return {status:'DENIED',code:'CLEAN_TARGET_UNVERIFIED'};
2078
- try {
2079
- const action=await createBoundedAction({url:chrome.runtime.getURL('clean.html')
2080
- +'?tabId='+target.id,windowId:target.windowId,active:true});
2081
- return {status:'OK',actionTabId:action.id};
2082
- } catch(error) {
2083
- return {status:'BLOCKED',code:error?.message||'CLEAN_ACTION_UNVERIFIED'};
2084
- }
2085
- }
2086
- // Read-only target resolver for a CLI-created formal Eye Action.
2087
- // This never starts a Loop, changes Owner, or sends a chat message.
2088
- async function onExtensionCliTarget(message,sender) {
2089
- const pages={chat_text:"text.html",chat_dom:"dom.html",
2090
- chat_screenshot:"screenshot.html",reload:"reload.html"};
2091
- const page=pages[message?.action];
2092
- if(!page || !/^[a-f0-9]{32}$/.test(message?.id||"")
2093
- || sender.url !== chrome.runtime.getURL(page)+"?requestId="+message.id)
2094
- return {status:"DENIED",code:"INVALID_EXTENSION_ACTION_SOURCE"};
2095
- if(message.action==="reload")return {status:"OK"};
2096
- const run=await readRun();
2097
- // A failed first send has no Chat Owner. Eye may inspect only the exact
2098
- // unconfirmed tab created by this START, and only after verifying its
2099
- // original prompt fingerprint. No ownership, recovery or send is granted.
2100
- if(run?.phase==='BLOCKED'&&run.action==='START'
2101
- &&run.lastStartFailureCode==='FIRST_SEND_RECEIPT_UNKNOWN'){
2102
- const evidence=await startReadinessEvidence(run);
2103
- const observed=evidence?.readiness;
2104
- if(evidence?.sendReceipt==='UNVERIFIED'
2105
- &&observed?.startPromptComparison==='AVAILABLE'
2106
- &&observed.matchedStartPromptCount===1
2107
- &&observed.userMessageCount>=1
2108
- &&typeof observed.path==='string'&&observed.path.startsWith('/c/')){
2109
- const candidate=await chrome.tabs.get(evidence.tabId).catch(()=>null);
2110
- // pathOf deliberately rejects provisional local-chatgpt paths for
2111
- // Ownership. Eye instead checks the exact observed HTTPS path only.
2112
- try {
2113
- const url=new URL(candidate?.url);
2114
- if(url.origin==='https://chatgpt.com'&&url.pathname===observed.path)
2115
- return {status:'OK',tabId:candidate.id,page:observed.path};
2116
- } catch { /* A changed or malformed tab is not a read target. */ }
2117
- }
2118
- return {status:'DENIED',code:'START_EYE_EVIDENCE_UNVERIFIED'};
2119
- }
2120
- // Read-only Eye may inspect the last confirmed terminal Owner while the same
2121
- // Chat URL and exact tab still match. This does not reactivate the Loop,
2122
- // grant Continue/Handoff permission or select another Chat tab.
2123
- const finishedOwned = ["DONE","BLOCKED"].includes(run?.phase)
2124
- && /^user:[^\s]{8,}$/.test(run.userKey || "")
2125
- && /^assistant:[^\s]{8,}$/.test(run.assistantKey || "");
2126
- if(!(run?.phase === "WAITING_REPLY" || finishedOwned) || !Number.isInteger(run.tabId)
2127
- || typeof run.page!=="string")
2128
- return {status:"DENIED",code:"NO_ACTIVE_CHAT_OWNER"};
2129
- const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
2130
- if(!tab || pathOf(tab.url)!==run.page)
2131
- return {status:"DENIED",code:"OWNER_CHANGED"};
2132
- return {status:"OK",tabId:run.tabId,page:run.page};
2133
- }
2134
- // One explicit router for authenticated, serialized state changes.
2135
- // The registered handler still verifies source, token, Owner and Turn identity.
2136
- const SERIAL_ROUTES=new Map([
2137
- ['CHAT_LOOP_TURN_FINISHED_V1',onTurnFinished],
2138
- ['CHAT_LOOP_TURN_BLOCKED_V1',onTurnBlocked],
2139
- ['CHAT_LOOP_ACTION_TAKE_V1',onTake],
2140
- ['CHAT_LOOP_ACTION_RESULT_V1',onResult],
2141
- ['CHAT_LOOP_HANDOFF_SEND_BEGIN_V1',onHandoffSendBegin],
2142
- ['CHAT_LOOP_ADOPT_KICKOFF_PREPARE_V1',onAdoptKickoffPrepare],
2143
- ['CHAT_LOOP_ADOPT_BASELINE_REPAIR_V1',onAdoptBaselineRepair],
2144
- ['CHAT_LOOP_ACTION_MANUAL_REVEAL_V1',onManualReveal],
2145
- ['CHAT_LOOP_ACTION_MANUAL_PREPARE_V1',onManualPrepare],
2146
- ['CHAT_LOOP_MODEL_INTENT_V1',onModelIntent],
2147
- ['CHAT_LOOP_MODEL_INTENT_STATUS_V1',onModelIntentStatus],
2148
- ['CHAT_LOOP_SESSION_START_PREPARE_V1',sessionStartPrepare],
2149
- ['CHAT_LOOP_SESSION_START_TAKE_V1',sessionStartTake],
2150
- ['CHAT_LOOP_SESSION_START_RESULT_V1',sessionStartResult],
2151
- ['CHAT_LOOP_SESSION_STATUS_V1',sessionStatus],
2152
- ['CHAT_LOOP_RESOURCE_CHAT_V1',resourceChatGate]
2153
-
2154
- ]);
2155
- chrome.runtime.onMessage.addListener((message, sender, reply) => {
2156
- const type=message?.type;
2157
- const handle=SERIAL_ROUTES.get(type);
2158
- if(handle){
2159
- void serial(async()=>{
2160
- let result;
2161
- try{result=await handle(message,sender);}
2162
- catch(error){result={status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'};}
2163
- // A bounded diagnostic receipt, never permission or a second state store.
2164
- // In particular a rejected manual recovery must be observable remotely.
2165
- if(type==='CHAT_LOOP_ACTION_MANUAL_PREPARE_V1'){
2166
- const current=await readRun();
2167
- if(current)await chrome.storage.local.set({[RUN_KEY]:{...current,
2168
- lastManualFeedback:{status:result.status,
2169
- code:/^[A-Z0-9_]{1,100}$/.test(result.code||'')?result.code:null,at:Date.now()}}});
2170
- }
2171
- return result;
2172
- }).then(reply,error=>reply({status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'}));
2173
- return true;
2174
- }
2175
- if (type === 'CHAT_LOOP_POPUP_CLEAN_OPEN_V1') {
2176
- void serial(()=>openPopupClean(message,sender)).then(reply,
2177
- ()=>reply({status:'BLOCKED',code:'CLEAN_ACTION_UNVERIFIED'}));
2178
- return true;
2179
- }
2180
- if (type === "CHAT_LOOP_EXTENSION_TARGET_V1") {
2181
- void onExtensionCliTarget(message,sender).then(reply,
2182
- ()=>reply({status:"DENIED",code:"OWNER_UNVERIFIED"}));
2183
- return true;
2184
- }
2185
- if (type !== "CHAT_LOOP_EYE_RELOAD_V1") return false;
2186
- const id = sender.tab?.id;
2187
- void (async () => {
2188
- try {
2189
- if (!Number.isInteger(id)) throw Error("NO_ACTION_TAB");
2190
- const tab = await chrome.tabs.get(id);
2191
- const reloadBase=chrome.runtime.getURL("reload.html");
2192
- if (!tab.url.startsWith(reloadBase) ||
2193
- (tab.url!==reloadBase &&
2194
- !/^\?requestId=[a-f0-9]{32}$/.test(tab.url.slice(reloadBase.length))))
2195
- throw Error("INVALID_RELOAD_SOURCE");
2196
- reply({status: "ACCEPTED"});
2197
- await chrome.tabs.remove(id);
2198
- chrome.runtime.reload();
2199
- } catch (error) {reply({status: "FAILED", code: error.message});}
2200
- })();
2201
- return true;
2202
- });
1
+ // Chrome MV3 classic service Worker. Shared lexical context; exact order
2
+ // preserves the original single-Worker Owner and serialized Action lifecycle.
3
+ importScripts("loop/index.js");
4
+ importScripts("worker/bootstrap.js");
5
+ importScripts("worker/admission.js");
6
+ importScripts("worker/adopt-prepare.js");
7
+ importScripts("worker/adopt-result.js");
8
+ importScripts("worker/readiness.js");
9
+ importScripts("worker/turn-failure.js");
10
+ importScripts("worker/turn-finished.js");
11
+ importScripts("worker/adopt-recovery.js");
12
+ importScripts("worker/manual.js");
13
+ importScripts("worker/action-take.js");
14
+ importScripts("worker/action-result.js");
15
+ importScripts("worker/scheduler.js");
16
+ importScripts("worker/router.js");