@tomflow/chatloop-extension 0.3.84 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +74 -73
  2. package/actions.generated.mjs +11 -0
  3. package/bin/cli.mjs +22 -24
  4. package/bin/native-host.mjs +14 -5
  5. package/capabilities/chat_dom.mjs +1 -0
  6. package/capabilities/chat_screenshot.mjs +1 -0
  7. package/capabilities/chat_text.mjs +1 -0
  8. package/capabilities/clean.mjs +1 -0
  9. package/capabilities/continue.mjs +1 -0
  10. package/capabilities/handoff.mjs +1 -0
  11. package/capabilities/reload.mjs +1 -0
  12. package/capabilities/start.mjs +1 -0
  13. package/capabilities/status.mjs +1 -0
  14. package/extension/actions/common.js +14 -3
  15. package/extension/actions/continue.js +1 -1
  16. package/extension/actions/handoff.js +5 -3
  17. package/extension/actions/index.js +2 -0
  18. package/extension/actions/read-mode.js +9 -0
  19. package/extension/actions/start.js +1 -1
  20. package/extension/background.js +16 -2202
  21. package/extension/loop/action-catalog.generated.js +2 -0
  22. package/extension/loop/api-aspect.generated.js +192 -0
  23. package/extension/loop/core.js +81 -3
  24. package/extension/loop/index.js +34 -0
  25. package/extension/loop/observer-approval.js +227 -0
  26. package/extension/loop/observer-inspect.js +144 -0
  27. package/extension/loop/observer-poll.js +171 -0
  28. package/extension/loop/observer-recovery.js +109 -0
  29. package/extension/loop/observer.js +27 -630
  30. package/extension/loop/resources.js +8 -1
  31. package/extension/manifest.json +6 -2
  32. package/extension/worker/action-result.js +136 -0
  33. package/extension/worker/action-take.js +220 -0
  34. package/extension/worker/admission.js +122 -0
  35. package/extension/worker/adopt-prepare.js +155 -0
  36. package/extension/worker/adopt-recovery.js +185 -0
  37. package/extension/worker/adopt-result.js +120 -0
  38. package/extension/worker/bootstrap.js +172 -0
  39. package/extension/worker/manual.js +165 -0
  40. package/extension/worker/readiness.js +242 -0
  41. package/extension/worker/router.js +150 -0
  42. package/extension/worker/scheduler.js +147 -0
  43. package/extension/worker/turn-failure.js +197 -0
  44. package/extension/worker/turn-finished.js +200 -0
  45. package/index.mjs +62 -0
  46. package/lib/action-routing.mjs +18 -0
  47. package/lib/api-aspect.mjs +190 -0
  48. package/lib/bridge.mjs +26 -7
  49. package/lib/context-binding.mjs +6 -1
  50. package/lib/context-ipc.mjs +44 -2
  51. package/lib/owner-evidence.mjs +67 -0
  52. package/lib/session-file.mjs +20 -8
  53. package/package.json +13 -3
  54. package/scripts/build-actions.mjs +133 -0
@@ -0,0 +1,155 @@
1
+ // Chat Loop Worker — adopt-prepare. Imported in order by background.js; no independent Browser Owner.
2
+ async function sessionStartPrepare(message,sender){
3
+ if(!sessionPage(sender,'start',message.requestId))
4
+ return {status:'DENIED',code:'INVALID_START_SOURCE'};
5
+ const prior=await readRun();
6
+ // Read the single authenticated intent BEFORE deciding whether a previously
7
+ // BLOCKED session can be explicitly superseded. Never infer consent from
8
+ // a failed page or an old session pointer alone.
9
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,
10
+ {op:'acquire',id:message.requestId,action:'start'}).catch(()=>null);
11
+ const intent=proof?.intent;
12
+ if(proof?.status!=='OK'||intent?.confirmed!==true
13
+ ||typeof intent.projectId!=='string'
14
+ ||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.projectId)
15
+ ||(intent.taskId!==undefined
16
+ && !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.taskId))
17
+ ||(intent.purpose!==undefined
18
+ &&(intent.purpose!=='REPAIR_SAME_SCOPE'||intent.mode!=='adopt'
19
+ ||!intent.taskId||!intent.contextLeaseRef))
20
+ ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
21
+ .some(k=>Object.hasOwn(intent,k))
22
+ &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
23
+ ||intent.contextLeaseRef.length<8||typeof intent.contextStoreEpoch!=='string'
24
+ ||intent.contextStoreEpoch.length<10
25
+ ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
26
+ ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
27
+ ||(intent.chatUrl!==undefined
28
+ && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'
29
+ ||!pathOf(intent.chatUrl)
30
+ ||intent.chatUrl!=='https://chatgpt.com'+pathOf(intent.chatUrl)))
31
+ ||(intent.mode==='adopt' ? Object.hasOwn(intent,'prompt')
32
+ : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000)
33
+ ||(intent.mode!==undefined && intent.mode!=='adopt')
34
+ ||(intent.replaceBlockedSessionId!==undefined
35
+ && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId)))
36
+ return {status:'DENIED',code:'START_INTENT_UNVERIFIED'};
37
+ // Native DONE is required before the private terminal fence IPC, but
38
+ // DONE without CONFIRMED fencing must never release Start admission.
39
+ if(prior?.contextManaged && prior.taskId
40
+ && (prior.contextTerminalFence==='UNVERIFIED'
41
+ || prior.phase==='DONE'&&!terminalFenceVerified(prior)))
42
+ return {status:'DENIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
43
+ const replace=intent.replaceBlockedSessionId||null;
44
+ const matchingBlocked=prior?.phase==='BLOCKED' && prior.sessionId===replace
45
+ && prior.projectId!==intent.projectId;
46
+ if(replace&&!matchingBlocked)return {status:'DENIED',code:'BLOCKED_REPLACEMENT_MISMATCH'};
47
+ if(prior&&prior.phase!=='DONE'&&!matchingBlocked)
48
+ return {status:'DENIED',code:'LOOP_ALREADY_ACTIVE'};
49
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
50
+ if(disk?.status!=='OK')return {status:'DENIED',code:'SESSION_STATE_UNVERIFIED'};
51
+ if(matchingBlocked&&(!disk.session||disk.session.phase!=='BLOCKED'
52
+ ||disk.session.sessionId!==replace||disk.session.projectId!==prior.projectId))
53
+ return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
54
+ // An abandoned Managed Context writer can outlive its Browser Owner.
55
+ // Replacing the Native session without first verifying its terminal fence
56
+ // would strand a live runRef (and an old write credential) in the Store.
57
+ // Never make that replacement based solely on BLOCKED or absent Owner.
58
+ if(matchingBlocked&&prior.contextManaged){
59
+ const terminal=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
60
+ op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
61
+ const state=terminal?.result;
62
+ if(terminal?.status!=='OK'||!state
63
+ ||state.projectId!==prior.projectId||state.taskId!==prior.taskId
64
+ ||state.runRef!==null||state.executionOutcome!=='DONE'
65
+ ||typeof state.deliveryRef!=='string'||!state.deliveryRef)
66
+ return {status:'DENIED',code:'CONTEXT_BLOCKED_RUN_UNFENCED'};
67
+ }
68
+ if(disk.session&&disk.session.phase!=='DONE'&&!matchingBlocked)
69
+ return {status:'DENIED',code:'SESSION_ALREADY_ACTIVE'};
70
+ const capacity=await resources.admit(prior,{kind:intent.mode==='adopt'?'action':'chat'});
71
+ if(!capacity.ok)return {status:'DENIED',code:capacity.code};
72
+ const adoption=intent.mode==='adopt'
73
+ ?intent.purpose==='REPAIR_SAME_SCOPE'
74
+ ?await approvedRepairTarget(prior,intent)
75
+ :await approvedAdoptionTarget(intent.chatUrl||null,
76
+ intent.contextLeaseRef?intent.taskId:null):null;
77
+ if(adoption?.error)return {status:'DENIED',code:adoption.error};
78
+ // A Project-scoped Chat cannot safely hand off to the ordinary home route:
79
+ // reject BEFORE claiming Owner instead of failing after four hours.
80
+ // Explicit /g/ intent remains Project-scoped even if Chrome aliases the
81
+ // same conversation under /c/<id>.
82
+ if(intent.mode==='adopt'&&(
83
+ pathOf(intent.chatUrl||'').startsWith('/g/')
84
+ ||adoption?.target?.page?.startsWith('/g/')))
85
+ return {status:'DENIED',code:'AUTO_HANDOFF_ROUTE_UNSUPPORTED'};
86
+ // The same blocked task may never be replayed implicitly: a replacement
87
+ // requires a new project ID and leaves the old Chat intact for audit.
88
+ const promptDigest=adoption?null:await startPromptFingerprint(intent.prompt);
89
+ const next={sessionId:crypto.randomUUID(),projectId:intent.projectId,
90
+ ...(intent.taskId?{taskId:intent.taskId}:{}),
91
+ ...(intent.purpose?{purpose:intent.purpose}:{}),
92
+ ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
93
+ contextStoreEpoch:intent.contextStoreEpoch,
94
+ contextTaskRevision:intent.contextTaskRevision,
95
+ contextApprovalRevision:intent.contextApprovalRevision,
96
+ contextInitialCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
97
+ x=>x.toString(16).padStart(2,'0')).join('')}:{}),
98
+ generation:0,phase:'STARTING',action:'START',token:crypto.randomUUID(),
99
+ page:'/',tabId:null,startedAt:Date.now(),
100
+ machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
101
+ ...(matchingBlocked?{replacedBlockedSessionId:replace}:{}),
102
+ ...(adoption?{mode:'adopt',adoptTabId:adoption.target.tabId,
103
+ adoptPage:adoption.target.page,adoptUserKey:adoption.target.userKey,
104
+ ...((intent.chatUrl||adoption.target.explicitChatId)
105
+ ?{adoptExplicitChatId:chatIdOf(intent.chatUrl)||adoption.target.explicitChatId}:{}),
106
+ ...(adoption.target.expectedTaskId
107
+ ?{adoptExpectedTaskId:adoption.target.expectedTaskId}:{}),
108
+ adoptPriorAssistantKey:adoption.target.priorAssistantKey,
109
+ adoptPostApprovalAssistantKey:adoption.target.postApprovalAssistantKey||null,
110
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'?{}:{
111
+ adoptRVersion:adoption.target.rVersion,
112
+ adoptPVersion:adoption.target.pVersion}),
113
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'
114
+ ?{repairUserText:adoption.target.repairUserText,
115
+ repairDoneAssistantKey:adoption.target.repairDoneAssistantKey}:{})}
116
+ :{startPrompt:intent.prompt,...(promptDigest?{startPromptDigest:promptDigest}:{})})};
117
+ await saveRun(next); // Reserve BEFORE any new Chrome tab or send.
118
+ return {status:'PREPARED',token:next.token,sessionId:next.sessionId,
119
+ ...(next.taskId?{taskId:next.taskId}:{})};
120
+ }
121
+ async function sessionStartTake(message,sender){
122
+ const run=await readRun();
123
+ if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
124
+ ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
125
+ ||run.phase!=='STARTING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
126
+ await saveRun({...run,phase:'PENDING'});
127
+ // Native validates current durable Session and signs the narrow Context IPC.
128
+ // No Context adapter? Legacy Start behavior remains unchanged.
129
+ if(run.contextLeaseRef){
130
+ const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
131
+ op:'context-control',command:'permit.consume',
132
+ args:{expectedStoreEpoch:run.contextStoreEpoch,writeRequestId:run.token,
133
+ expectedTaskRevision:run.contextTaskRevision,
134
+ expectedApprovalRevision:run.contextApprovalRevision,
135
+ actionToken:run.token,kind:'START',leaseRef:run.contextLeaseRef}
136
+ }).catch(()=>null);
137
+ if(allowed?.status!=='OK'||allowed.result?.status!=='PERMITTED'){
138
+ await saveRun({...run,phase:'BLOCKED',reason:'CONTEXT_START_PERMIT_UNVERIFIED'});
139
+ return {status:'DENIED',code:allowed?.code||'CONTEXT_START_PERMIT_UNVERIFIED'};
140
+ }
141
+ }
142
+ return {status:'OK',sessionId:run.sessionId,
143
+ ...(run.taskId?{taskId:run.taskId}:{}),
144
+ ...(run.mode==='adopt'?{mode:'adopt',tabId:run.adoptTabId,
145
+ page:run.adoptPage,userKey:run.adoptUserKey,
146
+ ...(run.adoptExplicitChatId?{explicitChatId:run.adoptExplicitChatId}:{}),
147
+ ...(run.adoptExpectedTaskId?{expectedTaskId:run.adoptExpectedTaskId}:{}),
148
+ priorAssistantKey:run.adoptPriorAssistantKey,
149
+ postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
150
+ ...(run.purpose==='REPAIR_SAME_SCOPE'
151
+ ?{purpose:'REPAIR_SAME_SCOPE',repairUserText:run.repairUserText,
152
+ priorDoneAssistantKey:run.repairDoneAssistantKey}
153
+ :{rVersion:run.adoptRVersion,pVersion:run.adoptPVersion})}
154
+ :{prompt:run.startPrompt})};
155
+ }
@@ -0,0 +1,185 @@
1
+ // Chat Loop Worker — adopt-recovery. Imported in order by background.js; no independent Browser Owner.
2
+ // An adopted, already-approved original Chat has an idle historical Pn answer.
3
+ // This one-shot kickoff is the missing bridge into the FIRST controlled execution
4
+ // Turn. Only the formal Continue Action may request it, with exact Native CAS.
5
+ // There is no direct Worker send, second Owner, or replay of prior approval.
6
+ async function onAdoptKickoffPrepare(message,sender){
7
+ const run=await readRun();
8
+ if(run?.phase!=='WAITING_REPLY'||run.reason!=='ADOPTED_IDLE_BASELINE'
9
+ ||run.action!=='START'||!run.contextManaged||!run.taskId
10
+ ||!run.sessionId||run.generation!==0||run.kickoffAttempted
11
+ ||!Number.isInteger(run.tabId)||run.tabId!==message.tabId
12
+ ||!run.page||run.newUserKey!==run.userKey
13
+ ||!/^assistant:[^\s]{8,}$/.test(run.assistantKey||'')
14
+ ||!Number.isSafeInteger(message.nativeUpdatedAt)
15
+ ||!Number.isInteger(sender.tab?.id)||Date.now()>=deadlineOf(run))
16
+ return {status:'DENIED',code:'ADOPT_KICKOFF_NOT_ELIGIBLE'};
17
+ if(sender.url!==chrome.runtime.getURL('continue.html')
18
+ +'?tabId='+run.tabId+'&adoptKickoffAt='+message.nativeUpdatedAt)
19
+ return {status:'DENIED',code:'ADOPT_KICKOFF_ACTION_INVALID'};
20
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
21
+ if(pathOf(tab?.url)!==run.page)
22
+ return {status:'DENIED',code:'ADOPT_KICKOFF_CHAT_CHANGED'};
23
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
24
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
25
+ ||disk.session.phase!=='WAITING_REPLY'
26
+ ||disk.session.updatedAt!==message.nativeUpdatedAt)
27
+ return {status:'DENIED',code:'ADOPT_KICKOFF_NATIVE_CHANGED'};
28
+ // run.snapshot requires a business checkpoint. A freshly adopted Task has
29
+ // no checkpoint yet, so use the existing read-only live terminalStatus
30
+ // which verifies the current bound holder without inventing one.
31
+ const status=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
32
+ op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
33
+ if(status?.status!=='OK'
34
+ ||status.result?.runRef!==run.sessionId+':'+run.taskId+':0'
35
+ ||!Number.isSafeInteger(status.result?.approvalRevision)
36
+ ||status.result.approvalRevision<1
37
+ ||status.result?.unknownEffectCount!==0
38
+ ||status.result?.executionOutcome==='DONE'
39
+ ||status.result?.deliveryRef)
40
+ return {status:'DENIED',code:'ADOPT_KICKOFF_CONTEXT_UNVERIFIED'};
41
+ const exactId=chatIdOf(tab.url);
42
+ const read=async()=>{
43
+ const approval=await chrome.tabs.sendMessage(tab.id,{
44
+ type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
45
+ explicitChatId:exactId,expectedTaskId:run.taskId}).catch(()=>null);
46
+ const turn=await chrome.tabs.sendMessage(tab.id,{
47
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
48
+ const evidence=policy.normalizeAdoptionEvidence(approval,{
49
+ page:run.page,userKey:run.userKey,
50
+ postApprovalAssistantKey:run.assistantKey,
51
+ ...(run.adoptRVersion?{rVersion:run.adoptRVersion}:{}),
52
+ ...(run.adoptPVersion?{pVersion:run.adoptPVersion}:{})
53
+ });
54
+ if(!evidence||turn?.contract!=='chat-loop.turn-observer.v1'
55
+ ||turn.status!=='READY'||turn.page!==run.page
56
+ ||turn.userKey!==run.userKey||turn.assistantKey!==run.assistantKey
57
+ ||turn.pendingConfirmation
58
+ ||workerApi.parseStatus(turn.replyText)!=='UNKNOWN')
59
+ return null;
60
+ return {userKey:turn.userKey,assistantKey:turn.assistantKey,
61
+ replyText:turn.replyText,rVersion:evidence.rVersion,pVersion:evidence.pVersion};
62
+ };
63
+ const first=await read();
64
+ if(!first)return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_UNVERIFIED'};
65
+ await new Promise(resolve=>setTimeout(resolve,2300));
66
+ const second=await read();
67
+ if(!second||JSON.stringify(first)!==JSON.stringify(second))
68
+ return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_CHANGED'};
69
+ const token=crypto.randomUUID();
70
+ await saveRun({...run,phase:'RESERVED',action:'CONTINUE',token,
71
+ manualActionTabId:sender.tab.id,
72
+ recoveryMode:'ADOPT_KICKOFF',kickoffAttempted:true});
73
+ return {status:'PREPARED',token,tabId:run.tabId};
74
+ }
75
+ // One-shot recovery of an ALREADY committed same-Chat Adopt whose historical
76
+ // post-approval reply was wrongly classified UNKNOWN. Never writes a composer,
77
+ // retries an action or replaces Context/Owner. Requires exact Native BLOCKED CAS.
78
+ async function onAdoptBaselineRepair(message,sender){
79
+ const prior=await readRun();
80
+ if(prior?.phase!=='BLOCKED'||prior.reason!=='UNKNOWN'
81
+ ||prior.action!=='START'||!prior.contextManaged||!prior.taskId
82
+ ||(prior.recoveryAttempts||0)!==0
83
+ ||!prior.sessionId||!Number.isInteger(prior.tabId)
84
+ ||prior.tabId!==message.tabId||!prior.page
85
+ ||!/^user:[^\s]{8,}$/.test(prior.newUserKey||'')
86
+ ||!/^assistant:[^\s]{8,}$/.test(prior.assistantKey||'')
87
+ ||prior.userKey!==prior.newUserKey)
88
+ return {status:'DENIED',code:'ADOPT_BASELINE_NOT_ELIGIBLE'};
89
+ if(!Number.isSafeInteger(message.nativeUpdatedAt)||message.nativeUpdatedAt<=0
90
+ ||!Number.isInteger(sender.tab?.id))
91
+ return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_SOURCE'};
92
+ const expected=chrome.runtime.getURL('continue.html')
93
+ +'?tabId='+prior.tabId+'&adoptBaselineAt='+message.nativeUpdatedAt;
94
+ if(sender.url!==expected)
95
+ return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_ACTION'};
96
+ const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
97
+ if(pathOf(tab?.url)!==prior.page)
98
+ return {status:'DENIED',code:'ADOPT_BASELINE_CHAT_CHANGED'};
99
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
100
+ {op:'session-read'}).catch(()=>null);
101
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(prior),disk.session)
102
+ ||disk.session?.phase!=='BLOCKED'
103
+ ||disk.session.updatedAt!==message.nativeUpdatedAt)
104
+ return {status:'DENIED',code:'ADOPT_BASELINE_NATIVE_CHANGED'};
105
+ const exactChatId=chatIdOf(tab.url);
106
+ const read=async()=>{
107
+ const approval=await chrome.tabs.sendMessage(tab.id,
108
+ {type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
109
+ explicitChatId:exactChatId,expectedTaskId:prior.taskId}).catch(()=>null);
110
+ const turn=await chrome.tabs.sendMessage(tab.id,
111
+ {type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
112
+ const evidence=policy.normalizeAdoptionEvidence(approval,{
113
+ page:prior.page,userKey:prior.newUserKey,
114
+ postApprovalAssistantKey:prior.assistantKey,
115
+ ...(prior.adoptRVersion?{rVersion:prior.adoptRVersion}:{}),
116
+ ...(prior.adoptPVersion?{pVersion:prior.adoptPVersion}:{})
117
+ });
118
+ if(!evidence||turn?.contract!=='chat-loop.turn-observer.v1'
119
+ ||turn.status!=='READY'||turn.page!==prior.page
120
+ ||turn.userKey!==prior.newUserKey||turn.assistantKey!==prior.assistantKey
121
+ ||turn.pendingConfirmation
122
+ ||workerApi.parseStatus(turn.replyText)!=='UNKNOWN')
123
+ return null;
124
+ return {userKey:turn.userKey,assistantKey:turn.assistantKey,
125
+ replyText:turn.replyText,rVersion:evidence.rVersion,pVersion:evidence.pVersion};
126
+ };
127
+ const a=await read();
128
+ if(!a)return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_MISSING'};
129
+ await new Promise(resolve=>setTimeout(resolve,2300));
130
+ const b=await read();
131
+ if(!b||JSON.stringify(a)!==JSON.stringify(b))
132
+ return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_CHANGED'};
133
+ // Re-arm the observer as a historical baseline BEFORE Native CAS. Failure
134
+ // cannot leave Native in a half-resumed state. This sends no Chat message.
135
+ const armed=await chrome.tabs.sendMessage(tab.id,{
136
+ type:'CHAT_LOOP_TURN_RESUME_V1',
137
+ page:prior.page,userKey:prior.newUserKey,
138
+ assistantKey:prior.assistantKey,baselineOnly:true,
139
+ startedAt:prior.startedAt
140
+ }).catch(()=>null);
141
+ if(armed?.status!=='RESUMED'||armed.baselineOnly!==true)
142
+ return {status:'DENIED',code:'ADOPT_BASELINE_OBSERVER_UNVERIFIED'};
143
+ await saveRun({...prior,phase:'RESERVED',
144
+ reason:'ADOPT_BASELINE_RECOVERY',
145
+ recoveryMode:'ADOPT_IDLE_BASELINE',recoveryAttempts:1});
146
+ const clean={...prior,phase:'WAITING_REPLY',reason:'ADOPTED_IDLE_BASELINE',
147
+ recoveryAttempts:1,userKey:prior.newUserKey,assistantKey:prior.assistantKey};
148
+ delete clean.recoveryMode;
149
+ await saveRun(clean);
150
+ return {status:'REPAIRED',sessionId:prior.sessionId,taskId:prior.taskId,
151
+ activeChatId:exactChatId,baselineAssistantKey:prior.assistantKey,
152
+ generation:prior.generation||0};
153
+ }
154
+ // Only an explicitly opened, existing Continue Action may reveal a
155
+ // scroll-virtualized *terminal Owner* before the normal double Turn check.
156
+ // This grants no send permit and changes neither Worker nor Native state.
157
+ // The Action alone may scroll the verified Chat UI; the Worker never does.
158
+ async function onManualReveal(message,sender) {
159
+ const run=await readRun();
160
+ if(!run?.sessionId||run.phase!=='BLOCKED'||run.reason!=='BLOCKED'
161
+ ||run.action!=='CONTINUE'||run.recoveryProtocol!==1
162
+ ||!(run.recoveryAttempts>0)
163
+ ||run.recoverySourceAssistantKey===run.assistantKey
164
+ ||run.newUserKey!==run.userKey
165
+ ||!Number.isInteger(run.tabId)||message.tabId!==run.tabId
166
+ ||!Number.isSafeInteger(message.resumeBlockedAt)
167
+ ||message.resumeBlockedAt<=0 ||!Number.isInteger(sender.tab?.id))
168
+ return {status:'DENIED',code:'REVEAL_OWNER_UNVERIFIED'};
169
+ let url;
170
+ try{url=new URL(sender.url);}catch{return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};}
171
+ if(url.origin!==new URL(chrome.runtime.getURL('continue.html')).origin
172
+ ||url.pathname!=='/continue.html'
173
+ ||url.searchParams.size!==2
174
+ ||url.searchParams.get('tabId')!==String(run.tabId)
175
+ ||url.searchParams.get('resumeBlockedAt')!==String(message.resumeBlockedAt))
176
+ return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};
177
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
178
+ if(!tab||pathOf(tab.url)!==run.page)
179
+ return {status:'DENIED',code:'REVEAL_CHAT_CHANGED'};
180
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
181
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
182
+ ||disk.session.updatedAt!==message.resumeBlockedAt)
183
+ return {status:'DENIED',code:'REVEAL_NATIVE_CAS_UNVERIFIED'};
184
+ return {status:'OK',page:run.page};
185
+ }
@@ -0,0 +1,120 @@
1
+ // Chat Loop Worker — adopt-result. Imported in order by background.js; no independent Browser Owner.
2
+ async function sessionStartResult(message,sender){
3
+ const run=await readRun();
4
+ if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
5
+ ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
6
+ ||run.phase!=='PENDING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
7
+ const adopted=run.mode==='adopt';
8
+ let confirmed=(adopted?message.result==='ADOPTED_CONFIRMED'
9
+ :message.result==='SENT_CONFIRMED')
10
+ &&Number.isInteger(message.newTabId)
11
+ &&typeof message.newPage==='string'&&pathOf('https://chatgpt.com'+message.newPage)===message.newPage
12
+ &&typeof message.newUserKey==='string'&&/^user:[^\s]{8,}$/.test(message.newUserKey);
13
+ if(confirmed){
14
+ const tab=await chrome.tabs.get(message.newTabId).catch(()=>null);
15
+ confirmed=!!tab&&pathOf(tab.url)===message.newPage;
16
+ }
17
+ if(confirmed && adopted){
18
+ confirmed=message.newTabId===run.adoptTabId
19
+ &&message.newPage===run.adoptPage
20
+ &&message.newUserKey===run.adoptUserKey;
21
+ if(confirmed){
22
+ const repair=run.purpose==='REPAIR_SAME_SCOPE';
23
+ const proof=await chrome.tabs.sendMessage(run.adoptTabId,
24
+ {type:repair?'CHAT_LOOP_REPAIR_EVIDENCE_V1':'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
25
+ ...(run.adoptExplicitChatId
26
+ ?{explicitChatId:run.adoptExplicitChatId}:{}),
27
+ ...(run.adoptExpectedTaskId
28
+ ?{expectedTaskId:run.adoptExpectedTaskId}:{})}).catch(()=>null);
29
+ const original={page:run.adoptPage,userKey:run.adoptUserKey,
30
+ priorAssistantKey:run.adoptPriorAssistantKey||null,
31
+ postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
32
+ rVersion:run.adoptRVersion,pVersion:run.adoptPVersion};
33
+ confirmed=repair
34
+ ?proof?.contract==='chat-loop.turn-observer.v1'
35
+ &&proof.status==='VERIFIED'&&proof.page===run.adoptPage
36
+ &&proof.userKey===run.adoptUserKey
37
+ &&proof.userText===run.repairUserText
38
+ &&proof.priorDoneAssistantKey===run.repairDoneAssistantKey
39
+ :policy.sameAdoptionEvidence(original,
40
+ policy.normalizeAdoptionEvidence(proof,{page:run.adoptPage}));
41
+ }
42
+ }
43
+ // Four-hour execution clock begins at confirmed enrollment, not at
44
+ // the UI approval or potentially long Start readiness/preparation.
45
+ const adoptedIdle=confirmed&&adopted&&!!run.adoptPostApprovalAssistantKey;
46
+ const next={...run,phase:confirmed?'WAITING_REPLY':'BLOCKED',
47
+ startedAt:confirmed?Date.now():run.startedAt,
48
+ lastStartActionTabId:sender.tab.id,
49
+ ...(adoptedIdle?{assistantKey:run.adoptPostApprovalAssistantKey,
50
+ userKey:run.adoptUserKey}:{}),
51
+ reason:confirmed?(adoptedIdle?'ADOPTED_IDLE_BASELINE':'')
52
+ :adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED',
53
+ ...(!confirmed&&['START_HOME_URL_UNVERIFIED','NEW_CHAT_NOT_READY',
54
+ 'START_COMPOSER_NOT_EMPTY','START_ACCOUNT_SWITCH_VISIBLE',
55
+ 'FIRST_TURN_OBSERVER_UNAVAILABLE','START_SEND_BUTTON_UNAVAILABLE','START_INPUT_CHANGED',
56
+ 'START_INPUT_UNVERIFIED','START_INPUT_REJECTED',
57
+ 'START_CLICK_UNVERIFIED','FIRST_SEND_RECEIPT_UNKNOWN']
58
+ .includes(message.failureCode)
59
+ ?{lastStartFailureCode:message.failureCode}:{}),
60
+ ...(confirmed?{tabId:message.newTabId,page:message.newPage,
61
+ newUserKey:message.newUserKey}:{attemptedNewTabId:Number.isInteger(message.newTabId)?message.newTabId:null})};
62
+ if(confirmed){
63
+ delete next.handoffPending;
64
+ delete next.handoffPendingAt;
65
+ }
66
+ delete next.startPrompt;
67
+ delete next.adoptTabId;
68
+ delete next.adoptPage;
69
+ delete next.adoptUserKey;
70
+ delete next.adoptExplicitChatId;
71
+ delete next.adoptExpectedTaskId;
72
+ delete next.adoptPriorAssistantKey;
73
+ delete next.adoptPostApprovalAssistantKey;
74
+ delete next.adoptRVersion;
75
+ delete next.adoptPVersion;
76
+ delete next.repairUserText;
77
+ delete next.repairDoneAssistantKey;
78
+ delete next.purpose;
79
+ delete next.mode;
80
+ delete next.machineRequestId;
81
+ delete next.machineActionTabId;
82
+ delete next.replacedBlockedSessionId;
83
+ await saveRun(next);
84
+ let privateContext=null;
85
+ if(confirmed&&run.contextLeaseRef){
86
+ const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
87
+ op:'context-control',command:'run.bind.initial',
88
+ args:{expectedStoreEpoch:run.contextStoreEpoch,
89
+ writeRequestId:run.token+':initial-bind',
90
+ expectedTaskRevision:run.contextTaskRevision,expectedBindingRevision:0,
91
+ actionToken:run.token,leaseRef:run.contextLeaseRef,
92
+ runCredential:run.contextInitialCredential}
93
+ }).catch(()=>null);
94
+ if(bound?.status!=='OK'||bound.result?.status!=='BOUND'){
95
+ // First Chat may already exist. Never re-send merely to fix Context.
96
+ const stopped={...next,phase:'BLOCKED',reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
97
+ delete stopped.contextInitialCredential;
98
+ await saveRun(stopped);
99
+ return {status:'BLOCKED',code:bound?.code||'CONTEXT_INITIAL_BIND_UNVERIFIED'};
100
+ }
101
+ privateContext={runRef:bound.result.runRef,
102
+ runCredential:run.contextInitialCredential,
103
+ storeEpoch:run.contextStoreEpoch,
104
+ bindingRevision:bound.result.bindingRevision,
105
+ taskRevision:run.contextTaskRevision};
106
+ // Capability is delivered once in the private Start result, not Status.
107
+ const clean={...next,contextManaged:{storeEpoch:run.contextStoreEpoch}};
108
+ for(const key of ['contextInitialCredential','contextLeaseRef','contextStoreEpoch',
109
+ 'contextTaskRevision','contextApprovalRevision'])delete clean[key];
110
+ await saveRun(clean);
111
+ }
112
+ if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
113
+ 'https://chatgpt.com'+message.newPage).catch(()=>{});
114
+ return confirmed?{status:'OK',sessionId:next.sessionId,
115
+ activeChatId:sessionProjection(next).activeChatId,
116
+ activeChatUrl:sessionProjection(next).activeChatUrl,
117
+ ...(next.taskId?{taskId:next.taskId}:{}),
118
+ ...(privateContext?{context:privateContext}:{})}
119
+ :{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
120
+ }
@@ -0,0 +1,172 @@
1
+ // Chat Loop Worker — bootstrap. Imported in order by background.js; no independent Browser Owner.
2
+ const workerApi=globalThis.ChatLoopWorkerApiV1;
3
+ const RUN_KEY = "chat-loop.action.run.v1";
4
+ const SESSION_HOST = "com.tomflow.chatloop.extension";
5
+ const ALARM_NAME = "chat-loop.turn-watch.v1";
6
+ const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
7
+ const ENGINEERING_FAILURE_NOTE = "【故障边界】编译或测试失败应诊断修复,不是网页运行错误。MCP 初始化或连接临时失败时,先核查已启动进程与未知副作用;只有确认后续是安全只读操作,才可针对本次独立故障再安排一次跨轮复核并输出 CONTINUE。若同一故障复核仍无进展,或消息发送结果、Owner、审批、权限不可信,则 BLOCKED,绝不重复执行未知副作用。不同故障分别判断,不能沿用旧故障的重试次数。";
8
+ const CONTINUE_TEXT = "继续当前任务,完成本轮后只在末行写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
9
+ const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
10
+ let queue = Promise.resolve();
11
+ const serial = fn => {
12
+ const work = queue.then(fn);
13
+ queue = work.catch(() => {});
14
+ return work;
15
+ };
16
+ // Admission and recovery run in this same Worker, never another browser executor.
17
+ const resources = workerApi.resources;
18
+ async function createBoundedAction(options) {
19
+ // Validate BEFORE creating a tab. No caller may open an arbitrary URL
20
+ // through the privileged Worker Action quota.
21
+ if(typeof options?.url!=='string'
22
+ ||!options.url.startsWith(chrome.runtime.getURL('')))
23
+ throw Error('ACTION_URL_UNVERIFIED');
24
+ const quota=await resources.admit(await readRun(),{kind:'action'});
25
+ if (!quota.ok) throw Error(quota.code);
26
+ const tab=await chrome.tabs.create(options);
27
+ if (!Number.isSafeInteger(tab?.id)||tab.id<=0)
28
+ throw Error('ACTION_CREATED_ID_UNVERIFIED');
29
+ // MV3 tabs.create may return about:blank + pendingUrl. Register the exact
30
+ // Extension URL requested rather than the transitional snapshot.
31
+ let registered=false;
32
+ try{registered=await resources.registerAction({id:tab.id,url:options.url});}
33
+ catch{ /* The newly created page is not trusted without its registration. */ }
34
+ if(!registered){
35
+ // Failed registration must not strand another Action tab. Remove only
36
+ // this tab if its fresh, read-back URL still proves Extension identity;
37
+ // never close a changed, active or pinned tab and never retry a send.
38
+ const current=await chrome.tabs.get(tab.id).catch(()=>null);
39
+ if(current&&!current.active&&!current.pinned
40
+ &&(current.url===options.url
41
+ ||current.url==='about:blank'&&current.pendingUrl===options.url))
42
+ await chrome.tabs.remove(tab.id).catch(()=>{});
43
+ throw Error('ACTION_RESOURCE_UNVERIFIED');
44
+ }
45
+ return tab;
46
+ }
47
+ // Identity and receipt policy are shared deterministic helpers. This Worker
48
+ // remains the only Chrome action/state owner.
49
+ const policy=workerApi.policy;
50
+ const {pathOf,chatIdOf}=policy;
51
+ const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
52
+ // Keep only a fixed-size fingerprint after Start's one-shot prompt is erased.
53
+ // A missing historical fingerprint means NOT_COMPARABLE, not "zero matches".
54
+ async function startPromptFingerprint(prompt) {
55
+ if(typeof prompt!=='string'||!globalThis.crypto?.subtle||
56
+ typeof TextEncoder!=='function')return null;
57
+ const normalized=prompt.replace(/\s+/g,'');
58
+ if(!normalized)return null;
59
+ const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(normalized));
60
+ return Array.from(new Uint8Array(digest),v=>v.toString(16).padStart(2,'0')).join('');
61
+ }
62
+ // Keep the windowMsOf alias as the fingerprint test's pure-read boundary.
63
+ const windowMsOf=policy.windowMsOf;
64
+ const {deadlineOf,clockActive,terminalFenceVerified,MODEL_RECEIPT_TTL_MS,
65
+ receiptHistory,updateModelReceipt,settleModelIntent}=policy;
66
+ async function saveRun(run) {
67
+ if (run && ["DONE","BLOCKED"].includes(run.phase))
68
+ run = settleModelIntent(run, run.phase==="DONE"?"CANCELLED_DONE":"BLOCKED", run.reason);
69
+ const now = Date.now(), deadlineAt = deadlineOf(run);
70
+ // Persist the intent even when a delayed alarm arrives after an Action
71
+ // receipt. This never revokes a Continue already reserved before deadline.
72
+ const sending = ["STARTING","RESERVED","PENDING"].includes(run.phase);
73
+ const marker = sending && typeof run.token==="string" ? run.token : null;
74
+ const next = {...run, ...(deadlineAt ? {deadlineAt} : {}),
75
+ ...(marker ? {actionPendingAt: run.resourceToken===marker
76
+ && Number.isSafeInteger(run.actionPendingAt) ? run.actionPendingAt : now,
77
+ resourceToken:marker} : {})};
78
+ if (clockActive(next) && deadlineAt !== null && now >= deadlineAt
79
+ && !next.handoffPending) {
80
+ next.handoffPending = true;
81
+ next.handoffPendingAt = now;
82
+ }
83
+ const stored=await readRun();
84
+ const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
85
+ &&["TOOL_PREFLIGHT_REPAIRED","HANDOFF_NOT_SENT","ADOPT_IDLE_BASELINE"].includes(next.recoveryMode)
86
+ &&next.recoveryAttempts>=1&&stored?.phase==="BLOCKED";
87
+ const syncNative=async()=>{
88
+ if(!next.sessionId)return;
89
+ const record=sessionProjection(next);
90
+ const saved=await chrome.runtime.sendNativeMessage(SESSION_HOST,
91
+ {op:"session-sync",session:record,
92
+ ...(next.replacedBlockedSessionId&&!recoveryCommit&&next.phase==='STARTING'
93
+ ?{replaceBlockedSessionId:next.replacedBlockedSessionId}:{}),
94
+ ...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
95
+ ...(next.recoveryExpectedNativeAt?{resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{})}:{})}).catch(()=>null);
96
+ if(saved?.status!=="OK"||saved.session?.sessionId!==next.sessionId
97
+ ||saved.session?.phase!==next.phase)
98
+ throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
99
+ };
100
+ // A terminal BLOCKED session may resume only after native CAS first.
101
+ // Do not leave a Chrome RESERVED owner behind if native rejects the
102
+ // transition: that mismatch previously made all status calls unreadable.
103
+ if(recoveryCommit)await syncNative();
104
+ await chrome.storage.local.set({[RUN_KEY]:next});
105
+ if(!recoveryCommit)await syncNative();
106
+ // The resource inventory is derived evidence; it never grants browser Owner.
107
+ if (["DONE","BLOCKED"].includes(next.phase)
108
+ && next.contextTerminalFence !== "PENDING"
109
+ && next.contextTerminalFence !== "UNVERIFIED")
110
+ await resources.terminal(next).catch(()=>{});
111
+
112
+ try {
113
+ if (clockActive(next) && !next.handoffPending && deadlineAt > Date.now()) {
114
+ await chrome.alarms?.create?.(DEADLINE_ALARM_NAME, {when: deadlineAt});
115
+ } else {
116
+ await chrome.alarms?.clear?.(DEADLINE_ALARM_NAME);
117
+ }
118
+ } catch { /* The existing periodic alarm is a conservative backup. */ }
119
+ }
120
+ // Browser Owner remains the only send authority. Native Host mirrors a minimal
121
+ // session pointer so later Chats can find the current Web Chat without a task engine.
122
+ function sessionProjection(run) {
123
+ const page=typeof run.page==='string'?run.page:'';
124
+ const match=page.match(/\/c\/([0-9a-f-]{12,})$/i);
125
+ const activeChatId=match?.[1]||null;
126
+ return {sessionId:run.sessionId,projectId:run.projectId,
127
+ ...(run.taskId?{taskId:run.taskId}:{}),phase:run.phase,generation:run.generation||0,activeChatId,
128
+ activeChatUrl:activeChatId?"https://chatgpt.com"+page:null,
129
+ updatedAt:Date.now()};
130
+ }
131
+ const SESSION_POINTER_KEYS=Object.freeze(['sessionId','projectId','taskId','phase',
132
+ 'generation','activeChatId','activeChatUrl']);
133
+ const matchesNativeProjection=(projected,native)=>Boolean(native
134
+ &&SESSION_POINTER_KEYS.every(key=>projected[key]===native[key]));
135
+ const sessionPage=(sender,name,id)=> Number.isInteger(sender.tab?.id)
136
+ && typeof id==='string'&&/^[a-f0-9]{32}$/.test(id)
137
+ && sender.url===chrome.runtime.getURL(name+'.html')+'?requestId='+id;
138
+ async function resourceChatGate(message,sender) {
139
+ const run=await readRun();
140
+ if(run?.phase!=='PENDING'
141
+ || !['start','handoff'].includes(message.action))
142
+ return {status:'DENIED',code:'RESOURCE_OWNER_NOT_PENDING'};
143
+ const authorized=message.action==='start'
144
+ ? run.action==='START' && run.machineActionTabId===sender.tab?.id
145
+ && sessionPage(sender,'start',run.machineRequestId)
146
+ : run.action==='HANDOFF' && isAction(sender,
147
+ {tabId:run.tabId,token:run.token},run);
148
+ if(!authorized)return {status:'DENIED',code:'RESOURCE_ACTION_SOURCE_INVALID'};
149
+ if(message.stage==='preflight') {
150
+ const quota=await resources.admit(run,{kind:'chat'});
151
+ return quota.ok?{status:'OK',code:'RESOURCE_CHAT_PERMITTED'}
152
+ :{status:'DENIED',code:quota.code};
153
+ }
154
+ if(message.stage==='adopt' && run.mode==='adopt'
155
+ &&Number.isInteger(message.tabId)&&message.tabId===run.adoptTabId){
156
+ const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
157
+ if(!tab||pathOf(tab.url)!==run.adoptPage
158
+ ||!await resources.adoptChat(tab,run))
159
+ return {status:'DENIED',code:'RESOURCE_ADOPTION_UNVERIFIED'};
160
+ return {status:'OK',code:'RESOURCE_CHAT_ADOPTED'};
161
+ }
162
+ if(message.stage!=='register' || !Number.isInteger(message.tabId))
163
+ return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
164
+ const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
165
+ if (!tab || tab.id===run.tabId || tab.id===sender.tab.id
166
+ || !await resources.registerChat(tab,run))
167
+ return {status:'DENIED',code:'RESOURCE_CHAT_NOT_VERIFIED'};
168
+ const inventory=await resources.reconcile(run);
169
+ if(inventory.activeChatCount>resources.CHAT_LIMIT)
170
+ return {status:'DENIED',code:'RESOURCE_CHAT_LIMIT'};
171
+ return {status:'OK',code:'RESOURCE_CHAT_REGISTERED'};
172
+ }