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