@tomflow/chatloop-extension 0.4.34 → 0.4.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -0
- package/bin/cli.mjs +19 -4
- package/bin/native-host.mjs +40 -1
- package/capabilities/session.mjs +1 -1
- package/extension/actions/continue.js +54 -4
- package/extension/actions/handoff-scoped.js +143 -0
- package/extension/actions/handoff.js +9 -3
- package/extension/actions/model-intent.js +9 -5
- package/extension/actions/session.js +53 -10
- package/extension/actions/start.js +34 -0
- package/extension/actions/status.js +16 -2
- package/extension/background.js +16 -0
- package/extension/loop/index.js +1 -1
- package/extension/loop/observer-approval.js +19 -10
- package/extension/loop/observer-poll.js +7 -6
- package/extension/loop/observer.js +64 -7
- package/extension/loop/resource-maintenance.js +159 -0
- package/extension/loop/resources.js +235 -95
- package/extension/manifest.json +2 -1
- package/extension/session.html +1 -0
- package/extension/worker/admission.js +3 -0
- package/extension/worker/bootstrap.js +73 -16
- package/extension/worker/router.js +23 -6
- package/extension/worker/scheduler.js +237 -13
- package/extension/worker/task-action-v2.js +278 -0
- package/extension/worker/task-cancel-recovery-v2.js +52 -0
- package/extension/worker/task-cancel-v2.js +93 -0
- package/extension/worker/task-continue-recovery-v2.js +78 -0
- package/extension/worker/task-handoff-recovery-v2.js +148 -0
- package/extension/worker/task-handoff-v2.js +325 -0
- package/extension/worker/task-hold-recovery-v2.js +109 -0
- package/extension/worker/task-intent-dispatch-v2.js +220 -0
- package/extension/worker/task-intent-v2.js +106 -0
- package/extension/worker/task-owner-resolver.js +110 -0
- package/extension/worker/task-recover-v2.js +209 -0
- package/extension/worker/task-routes-v2.js +357 -0
- package/extension/worker/task-run-store.js +400 -0
- package/extension/worker/task-scheduler.js +78 -0
- package/extension/worker/task-start-v2.js +361 -0
- package/extension/worker/task-terminal-v2.js +235 -0
- package/index.mjs +7 -0
- package/lib/bridge.mjs +94 -19
- package/lib/browser-launch.mjs +3 -3
- package/lib/context-ipc.mjs +9 -2
- package/lib/owner-kernel-lock.mjs +106 -0
- package/lib/owner-ledger.mjs +316 -0
- package/lib/owner-locked-write.mjs +30 -0
- package/lib/scoped-cancel-v2.mjs +190 -0
- package/lib/scoped-continue-v2.mjs +214 -0
- package/lib/scoped-handoff-v2.mjs +338 -0
- package/lib/scoped-native-control.mjs +398 -0
- package/lib/scoped-recovery-v2.mjs +234 -0
- package/lib/scoped-retire-v2.mjs +70 -0
- package/lib/scoped-terminal-v2.mjs +143 -0
- package/lib/session-file.mjs +50 -7
- package/package.json +2 -4
|
@@ -1,17 +1,28 @@
|
|
|
1
|
-
// One bounded inventory for the
|
|
2
|
-
// types into, or otherwise drives a ChatGPT page.
|
|
1
|
+
// One bounded inventory for the Worker; no ChatGPT page sends or input.
|
|
3
2
|
(() => {
|
|
4
3
|
const KEY = 'chat-loop.resources.v1';
|
|
5
4
|
const ACTION_LIMIT = 3; // Includes machine Eye, Start, manual and timed Actions.
|
|
6
|
-
const CHAT_LIMIT = 2; //
|
|
5
|
+
const CHAT_LIMIT = 2; // Shared physical capacity, NOT a global Task/Owner count.
|
|
7
6
|
const AUDIT_TTL = 60_000; // Reap obsolete audit pages from installed older Extension versions.
|
|
8
7
|
const READ_TTL = 180_000;
|
|
9
8
|
const TERMINAL_TTL = 30_000;
|
|
10
9
|
const READ_ONLY = new Set(['status','text','dom','screenshot','reload']);
|
|
11
|
-
const ACTIONS = new Set(['start','continue','handoff','status','text','dom',
|
|
12
|
-
'screenshot','reload','clean','session']);
|
|
10
|
+
const ACTIONS = new Set(['start','continue','handoff','status','text','dom','screenshot','reload','clean','session']);
|
|
13
11
|
const validId = s => /^[a-f0-9]{32}$/.test(s || '');
|
|
14
12
|
const validTabId = s => /^[1-9][0-9]*$/.test(s || '');
|
|
13
|
+
const validScope = s => /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(s||'');
|
|
14
|
+
const scopeOf = run => validScope(run?.projectId)&&validScope(run?.taskId)?{projectId:run.projectId,taskId:run.taskId}:{};
|
|
15
|
+
const sameSession = (entry,run)=>{
|
|
16
|
+
if(entry.sessionId!==(run.sessionId||run.token))return false;
|
|
17
|
+
// V2 TaskKey cannot inherit a V1 entry without an exact scope.
|
|
18
|
+
if(run.taskId!==undefined||entry.taskId!==undefined){
|
|
19
|
+
return validScope(run.projectId)&&validScope(run.taskId)
|
|
20
|
+
&&entry.projectId===run.projectId&&entry.taskId===run.taskId;
|
|
21
|
+
}
|
|
22
|
+
// Restrict legacy V1 unscoped entries until its fence retires.
|
|
23
|
+
return entry.projectId===undefined||run.projectId===undefined
|
|
24
|
+
||entry.projectId===run.projectId;
|
|
25
|
+
};
|
|
15
26
|
const extensionBase = () => chrome.runtime.getURL('');
|
|
16
27
|
function classify(tab) {
|
|
17
28
|
if (!Number.isInteger(tab?.id) || !tab.url) return null;
|
|
@@ -25,63 +36,66 @@
|
|
|
25
36
|
if (!ACTIONS.has(name)) return null;
|
|
26
37
|
if (name==='session' && u.searchParams.size===2
|
|
27
38
|
&& validId(u.searchParams.get('requestId'))
|
|
28
|
-
&& u.searchParams.get('operation')
|
|
39
|
+
&& ['cancel','recover-handoff'].includes(u.searchParams.get('operation')))
|
|
29
40
|
return {kind:'machine',name,requestId:u.searchParams.get('requestId')};
|
|
30
41
|
if (u.searchParams.size === 1 && validId(u.searchParams.get('requestId')))
|
|
31
42
|
return {kind:READ_ONLY.has(name) || ['continue','handoff'].includes(name)
|
|
32
43
|
? 'read-only' : 'machine', name, requestId:u.searchParams.get('requestId')};
|
|
33
44
|
if (['continue','handoff'].includes(name)
|
|
34
|
-
&& u.searchParams.size === 2
|
|
45
|
+
&& (u.searchParams.size === 2
|
|
46
|
+
||u.searchParams.size===3&&u.searchParams.get('taskFirst')==='1')
|
|
47
|
+
&& validTabId(u.searchParams.get('tabId'))
|
|
35
48
|
&& /^[0-9a-f-]{36}$/i.test(u.searchParams.get('token') || ''))
|
|
36
49
|
return {kind:'send', name, token:u.searchParams.get('token'),
|
|
37
50
|
targetId:Number(u.searchParams.get('tabId'))};
|
|
38
|
-
// Manual pages count toward the quota but are never automatically closed.
|
|
39
51
|
return {kind:'manual', name};
|
|
40
52
|
}
|
|
41
53
|
const initial = () => ({created:0, observed:0, closed:0, denied:0,
|
|
42
|
-
peakActions:0, peakChats:0, lastDenial:null, entries:[]});
|
|
54
|
+
peakActions:0, peakChats:0, lastDenial:null, entries:[],pendingChats:[]});
|
|
55
|
+
const validHold = h=>h&&typeof h==='object'&&!Array.isArray(h)
|
|
56
|
+
&&typeof h.token==='string'&&/^[0-9a-f-]{36}$/i.test(h.token)
|
|
57
|
+
&&typeof h.sessionId==='string'&&h.sessionId.length>=8
|
|
58
|
+
&&validScope(h.projectId)
|
|
59
|
+
&&(h.taskId===null||validScope(h.taskId))
|
|
60
|
+
&&Number.isSafeInteger(h.actionTabId)&&h.actionTabId>0
|
|
61
|
+
&&Number.isSafeInteger(h.createdAt)&&h.createdAt>0
|
|
62
|
+
&&Object.keys(h).length===6;
|
|
43
63
|
const load = async () => {
|
|
44
64
|
const value=(await chrome.storage.local.get(KEY))[KEY];
|
|
45
|
-
|
|
65
|
+
if(value===undefined)return initial();
|
|
66
|
+
// Only an ABSENT key is fresh; corrupt quota or holds fail closed.
|
|
67
|
+
if(!value||typeof value!=='object'||Array.isArray(value)
|
|
68
|
+
||!Array.isArray(value.entries))throw Error('RESOURCE_LEDGER_INVALID');
|
|
69
|
+
const pendingChats=value.pendingChats===undefined?[]:value.pendingChats;
|
|
70
|
+
if(!Array.isArray(pendingChats)||pendingChats.length>32
|
|
71
|
+
||pendingChats.some(h=>!validHold(h))
|
|
72
|
+
||['token','sessionId','actionTabId'].some(k=>
|
|
73
|
+
new Set(pendingChats.map(h=>String(h[k]).toLowerCase())).size!==pendingChats.length))
|
|
74
|
+
throw Error('RESOURCE_HOLDS_INVALID');
|
|
75
|
+
return {...value,pendingChats};
|
|
46
76
|
};
|
|
47
77
|
const save = state => chrome.storage.local.set({[KEY]:state});
|
|
48
78
|
const cleanEntry = x => x && Number.isInteger(x.id) && typeof x.url === 'string';
|
|
49
|
-
const safeRemove
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
catch (error) {
|
|
54
|
-
// A user can close this tab after the final ownership check. Treat an
|
|
55
|
-
// absent tab as unconfirmed cleanup and reconcile it on the next scan;
|
|
56
|
-
// a still-live tab with a remove error must remain an explicit failure.
|
|
57
|
-
if (await chrome.tabs.get(tab.id).catch(()=>null)) throw error;
|
|
58
|
-
return false;
|
|
59
|
-
}
|
|
60
|
-
state.closed++;
|
|
61
|
-
state.lastReaped={id:tab.id, reason, at:Date.now()};
|
|
62
|
-
state.entries=state.entries.filter(e=>e.id!==tab.id);
|
|
63
|
-
return true;
|
|
64
|
-
};
|
|
65
|
-
const noDraft = async tabId => {
|
|
66
|
-
try {
|
|
67
|
-
const [p]=await chrome.scripting.executeScript({target:{tabId},func:()=>{
|
|
68
|
-
if (location.origin !== 'https://chatgpt.com' || !/^\/c\/[0-9a-f-]{12,}$/i.test(location.pathname)) return false;
|
|
69
|
-
const editor=document.querySelector('[contenteditable="true"][data-composer-markdown]')
|
|
70
|
-
||document.querySelector('#prompt-textarea[contenteditable="true"]');
|
|
71
|
-
return !!editor && !(editor.innerText || editor.textContent || '').trim()
|
|
72
|
-
&& !document.querySelector('[data-testid*="attachment-preview"], [data-testid*="image-preview"], [data-testid="composer-attachment"]');
|
|
73
|
-
}});
|
|
74
|
-
return p?.result===true;
|
|
75
|
-
} catch {return false;}
|
|
76
|
-
};
|
|
79
|
+
const {safeRemove,noDraft,actionTabMatches,confirmTransfer,activeChat,
|
|
80
|
+
finishedSendAction,noSuccessorForAbortedHandoff}=globalThis.ChatLoopResourceMaintenanceV1||{};
|
|
81
|
+
if([safeRemove,noDraft,actionTabMatches,confirmTransfer,activeChat,finishedSendAction,noSuccessorForAbortedHandoff].some(x=>typeof x!=='function'))
|
|
82
|
+
throw Error('RESOURCE_MAINTENANCE_UNAVAILABLE');
|
|
77
83
|
async function reconcile(run, {reap=true}={}) {
|
|
84
|
+
// Explicit Task snapshots only; never infer the latest Task.
|
|
85
|
+
const runs=(Array.isArray(run)?run:[run]).filter(Boolean);
|
|
86
|
+
if(runs.length>32||runs.some(r=>!r||typeof r!=='object'
|
|
87
|
+
||Array.isArray(r)||!(typeof r.sessionId==='string'
|
|
88
|
+
||typeof r.token==='string')))
|
|
89
|
+
throw Error('RESOURCE_TASK_SNAPSHOT_INVALID');
|
|
78
90
|
const state=await load(),now=Date.now();
|
|
79
91
|
const all=await chrome.tabs.query({});
|
|
80
92
|
const live=new Map(all.filter(t=>Number.isInteger(t.id)).map(t=>[t.id,t]));
|
|
81
93
|
const kept=[];
|
|
82
94
|
for (const entry of state.entries.filter(cleanEntry)) {
|
|
83
95
|
const tab=live.get(entry.id);
|
|
84
|
-
|
|
96
|
+
const pendingAction=entry.kind==='action'&&tab?.url==='about:blank'&&tab.pendingUrl===entry.url;
|
|
97
|
+
if (!tab || tab.url!==entry.url && entry.kind!=='chat'
|
|
98
|
+
&&!pendingAction) {
|
|
85
99
|
if (!tab) state.closed++;
|
|
86
100
|
continue;
|
|
87
101
|
}
|
|
@@ -99,23 +113,29 @@
|
|
|
99
113
|
name:info.name||null,firstSeenAt:now,owned:false});
|
|
100
114
|
state.observed++;
|
|
101
115
|
}
|
|
102
|
-
//
|
|
103
|
-
// Chrome's trusted openerTabId lets us recover that exact provenance,
|
|
104
|
-
// including after an MV3 Worker restart. Unknown other Chats are not owned.
|
|
116
|
+
// Recover exact opener provenance after MV3 crash; others stay unowned.
|
|
105
117
|
for (const tab of all) {
|
|
106
118
|
if (!Number.isInteger(tab.id)||!Number.isInteger(tab.openerTabId)
|
|
107
119
|
|| !/^https:\/\/chatgpt\.com\/(?:|c\/[0-9a-f-]{12,})$/i.test(tab.url||'')
|
|
108
120
|
|| state.entries.some(e=>e.id===tab.id)) continue;
|
|
109
121
|
const opener=live.get(tab.openerTabId), proof=classify(opener);
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
122
|
+
const matched=runs.filter(r=>{
|
|
123
|
+
const start=proof?.name==='start'&&proof.kind==='machine'
|
|
124
|
+
&&[r.machineActionTabId,r.lastStartActionTabId].includes(opener?.id);
|
|
125
|
+
const handoff=proof?.name==='handoff'&&proof.kind==='send'
|
|
126
|
+
&&(proof.token===r.token||r.taskId&&r.phase==='PENDING'
|
|
127
|
+
&&r.modelIntent?.action==='HANDOFF'
|
|
128
|
+
&&r.modelIntent.actionTabId===opener?.id&&proof.token===r.turnToken)
|
|
129
|
+
&&[r.tabId,r.sourceTabId].includes(proof.targetId);
|
|
130
|
+
return (start||handoff)&&(r.sessionId||r.token);
|
|
131
|
+
});
|
|
132
|
+
// Ambiguous source stays unowned and consumes capacity.
|
|
133
|
+
if(matched.length!==1)continue;
|
|
134
|
+
const owner=matched[0];
|
|
116
135
|
state.entries.push({id:tab.id,url:tab.url,kind:'chat',
|
|
117
|
-
sessionId:
|
|
118
|
-
|
|
136
|
+
sessionId:owner.sessionId||owner.token,...scopeOf(owner),
|
|
137
|
+
firstSeenAt:now,confirmed:false,
|
|
138
|
+
testOwned:/^cl-intent-e2e-[a-z0-9-]+$/i.test(owner.projectId||'')});
|
|
119
139
|
state.observed++;state.created++;
|
|
120
140
|
}
|
|
121
141
|
if (reap) {
|
|
@@ -130,14 +150,13 @@
|
|
|
130
150
|
await safeRemove(tab,entry,state,'STALE_AUDIT');
|
|
131
151
|
else if (info.kind==='read-only' && age>=READ_TTL)
|
|
132
152
|
await safeRemove(tab,entry,state,'STALE_READ_ONLY_NO_SEND');
|
|
133
|
-
else if
|
|
134
|
-
&&
|
|
135
|
-
&& run?.token===info.token
|
|
136
|
-
&& [run.tabId,run.sourceTabId].includes(info.targetId))
|
|
153
|
+
else if(info.kind==='send'&&age>=TERMINAL_TTL
|
|
154
|
+
&&finishedSendAction(info,entry,runs))
|
|
137
155
|
await safeRemove(tab,entry,state,'CONFIRMED_TERMINAL_ACTION');
|
|
138
|
-
else if (info.kind==='machine'
|
|
139
|
-
&&
|
|
140
|
-
&&
|
|
156
|
+
else if (info.kind==='machine'&&info.name==='start'
|
|
157
|
+
&&age>=TERMINAL_TTL
|
|
158
|
+
&&runs.some(r=>['DONE','BLOCKED'].includes(r.phase)
|
|
159
|
+
&&[r.lastStartActionTabId,r.machineActionTabId].includes(tab.id)))
|
|
141
160
|
await safeRemove(tab,entry,state,'CONFIRMED_TERMINAL_START');
|
|
142
161
|
} else if (entry.kind==='chat' && entry.confirmed
|
|
143
162
|
&& entry.testOwned===true && entry.terminal==='DONE' && age>=TERMINAL_TTL
|
|
@@ -146,42 +165,44 @@
|
|
|
146
165
|
}
|
|
147
166
|
}
|
|
148
167
|
}
|
|
149
|
-
// Count
|
|
150
|
-
// cannot retain every item after an external flood of manual pages.
|
|
168
|
+
// Count physical live tabs even beyond the bounded evidence index.
|
|
151
169
|
const after=await chrome.tabs.query({});
|
|
152
|
-
|
|
170
|
+
// Pending extension Actions still occupy a physical slot.
|
|
171
|
+
const actionCount=after.filter(t=>classify(t)||t.url==='about:blank'
|
|
172
|
+
&&classify({id:t.id,url:t.pendingUrl})).length;
|
|
153
173
|
const afterIds=new Set(after.map(t=>t.id));
|
|
154
174
|
const liveChatEntries=state.entries.filter(e=>e.kind==='chat'
|
|
155
175
|
&& afterIds.has(e.id));
|
|
156
176
|
const chatCount=liveChatEntries.length;
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
// neither is permission to send. A recovered same-Session Owner counts
|
|
160
|
-
// again even when its ledger still records an earlier BLOCKED phase.
|
|
161
|
-
const activeChatCount=liveChatEntries.filter(e=>
|
|
162
|
-
!['DONE','BLOCKED','CANCELLED'].includes(e.terminal)
|
|
163
|
-
||(e.sessionId===(run?.sessionId||run?.token)
|
|
164
|
-
&&!['DONE','BLOCKED','CANCELLED'].includes(run?.phase))).length;
|
|
177
|
+
// Retained historical tabs are provenance, not new send permits.
|
|
178
|
+
const activeChatCount=liveChatEntries.filter(e=>activeChat(e,runs,sameSession)).length;
|
|
165
179
|
const unownedHomes=after.filter(t=>t.url==='https://chatgpt.com/'
|
|
166
180
|
&& !state.entries.some(e=>e.kind==='chat'&&e.id===t.id)).length;
|
|
167
181
|
state.peakActions=Math.max(state.peakActions,actionCount);
|
|
168
182
|
state.peakChats=Math.max(state.peakChats,chatCount);
|
|
169
|
-
// Retain tracked Chats first: evicting their provenance would weaken the
|
|
170
|
-
// quota and could make an unknown send appear safe to replay.
|
|
171
183
|
const chatEntries=state.entries.filter(e=>e.kind==='chat');
|
|
172
184
|
const actionEntries=state.entries.filter(e=>e.kind==='action');
|
|
173
185
|
const slots=Math.max(0,32-chatEntries.length);
|
|
174
186
|
state.entries=[...chatEntries,...(slots?actionEntries.slice(-slots):[])];
|
|
175
|
-
|
|
187
|
+
const coveredHold=h=>after.some(t=>t.openerTabId===h.actionTabId&&
|
|
188
|
+
(t.url==='https://chatgpt.com/'||state.entries.some(e=>
|
|
189
|
+
e.kind==='chat'&&e.id===t.id&&e.sessionId===h.sessionId
|
|
190
|
+
&&e.projectId===h.projectId&&(e.taskId??null)===h.taskId)));
|
|
191
|
+
const pendingChatSlots=state.pendingChats.filter(h=>!coveredHold(h)).length;
|
|
176
192
|
state.current={actions:actionCount,chats:chatCount,
|
|
177
|
-
activeChats:activeChatCount,unownedHomes,
|
|
193
|
+
activeChats:activeChatCount,unownedHomes,
|
|
194
|
+
pendingChats:state.pendingChats.length,pendingChatSlots,
|
|
195
|
+
totalTabs:after.length,at:now};
|
|
178
196
|
await save(state);
|
|
179
|
-
return {state,actionCount,chatCount,activeChatCount,unownedHomes
|
|
197
|
+
return {state,actionCount,chatCount,activeChatCount,unownedHomes,
|
|
198
|
+
pendingChatSlots};
|
|
180
199
|
}
|
|
181
200
|
async function admit(run,{kind='action'}={}) {
|
|
182
|
-
const {state,actionCount,chatCount,activeChatCount,unownedHomes
|
|
201
|
+
const {state,actionCount,chatCount,activeChatCount,unownedHomes,
|
|
202
|
+
pendingChatSlots}=await reconcile(run);
|
|
183
203
|
const blocked=actionCount+(kind==='action'?1:0)>ACTION_LIMIT
|
|
184
|
-
? 'RESOURCE_ACTION_LIMIT' : activeChatCount+unownedHomes+
|
|
204
|
+
? 'RESOURCE_ACTION_LIMIT' : activeChatCount+unownedHomes+
|
|
205
|
+
pendingChatSlots+(kind==='chat'?1:0)>CHAT_LIMIT
|
|
185
206
|
? 'RESOURCE_CHAT_LIMIT' : null;
|
|
186
207
|
if (blocked) {
|
|
187
208
|
state.denied++;state.lastDenial={code:blocked,at:Date.now()};
|
|
@@ -190,20 +211,119 @@
|
|
|
190
211
|
return blocked?{ok:false,code:blocked,actionCount,chatCount}
|
|
191
212
|
:{ok:true,actionCount,chatCount};
|
|
192
213
|
}
|
|
214
|
+
// An unacknowledged Chat retains its reserved seat.
|
|
215
|
+
async function reserveChat(run,actionTabId) {
|
|
216
|
+
if(!Number.isSafeInteger(actionTabId)||actionTabId<=0
|
|
217
|
+
||run?.phase!=='PENDING'||!validScope(run.projectId)
|
|
218
|
+
||run.taskId!==undefined&&!validScope(run.taskId)
|
|
219
|
+
||typeof run.sessionId!=='string'||run.sessionId.length<8
|
|
220
|
+
||typeof run.token!=='string'||!/^[0-9a-f-]{36}$/i.test(run.token))
|
|
221
|
+
throw Error('RESOURCE_RESERVATION_SCOPE_INVALID');
|
|
222
|
+
const {state,activeChatCount,unownedHomes,
|
|
223
|
+
pendingChatSlots}=await reconcile(run,{reap:false});
|
|
224
|
+
if(state.pendingChats.some(h=>h.token.toLowerCase()===run.token.toLowerCase()
|
|
225
|
+
||h.sessionId.toLowerCase()===run.sessionId.toLowerCase()||h.actionTabId===actionTabId)){
|
|
226
|
+
return {ok:false,code:'RESOURCE_CHAT_RESERVATION_EXISTS'};
|
|
227
|
+
}
|
|
228
|
+
if(activeChatCount+unownedHomes+pendingChatSlots>=CHAT_LIMIT){
|
|
229
|
+
state.denied++;state.lastDenial={code:'RESOURCE_CHAT_LIMIT',at:Date.now()};
|
|
230
|
+
await save(state);
|
|
231
|
+
return {ok:false,code:'RESOURCE_CHAT_LIMIT'};
|
|
232
|
+
}
|
|
233
|
+
state.pendingChats.push({token:run.token,sessionId:run.sessionId,
|
|
234
|
+
projectId:run.projectId,taskId:run.taskId??null,
|
|
235
|
+
actionTabId,createdAt:Date.now()});
|
|
236
|
+
await save(state);
|
|
237
|
+
return {ok:true,code:'RESOURCE_CHAT_RESERVED'};
|
|
238
|
+
}
|
|
239
|
+
const {reserve:reserveScopedHandoff,verify:verifyScopedHandoffHold}=
|
|
240
|
+
globalThis.ChatLoopResourceMaintenanceV1.createHandoffReservation({
|
|
241
|
+
load,reserveChat,actionTabMatches,validScope});
|
|
242
|
+
async function releaseReservedChat(run,actionTabId){
|
|
243
|
+
const aborted=run?.phase==='BLOCKED'
|
|
244
|
+
&&run.preSendAbort?.id===run.modelIntent?.id
|
|
245
|
+
&&run.preSendAbort?.actionTabId===actionTabId
|
|
246
|
+
&&run.modelIntent?.state==='ACTION_UNVERIFIED'
|
|
247
|
+
&&run.lastIntentReceipt?.id===run.preSendAbort.id&&run.lastIntentReceipt?.status==='NOT_SENT';
|
|
248
|
+
if(!aborted||run.nextAttempt?.sendBeginAt!==null
|
|
249
|
+
||run.modelIntent?.action!=='HANDOFF'
|
|
250
|
+
||!validScope(run.projectId)||!validScope(run.taskId)
|
|
251
|
+
||!Number.isSafeInteger(actionTabId)||actionTabId<=0
|
|
252
|
+
||!/^[0-9a-f-]{36}$/i.test(run.turnToken||''))
|
|
253
|
+
throw Error('RESOURCE_RELEASE_SEND_NOT_EXCLUDED');
|
|
254
|
+
const state=await load(),matched=state.pendingChats.filter(h=>
|
|
255
|
+
h.token.toLowerCase()===run.turnToken.toLowerCase()
|
|
256
|
+
&&h.sessionId.toLowerCase()===run.sessionId.toLowerCase()&&h.projectId===run.projectId
|
|
257
|
+
&&h.taskId===run.taskId&&h.actionTabId===actionTabId);
|
|
258
|
+
if(state.pendingChats.some(h=>h.token.toLowerCase()===run.turnToken.toLowerCase()&&h!==matched[0]))
|
|
259
|
+
return {released:false,code:'HOLD_SCOPE_CONFLICT'};
|
|
260
|
+
if(!await noSuccessorForAbortedHandoff(run,actionTabId))
|
|
261
|
+
return {released:false,code:'HANDOFF_ACTION_OR_SUCCESSOR_UNVERIFIED'};
|
|
262
|
+
if(!matched.length)return {released:true,scope:'EXACT_UNSENT_CHAT_HOLD',alreadyAbsent:true};
|
|
263
|
+
state.pendingChats=state.pendingChats.filter(h=>h!==matched[0]);await save(state);
|
|
264
|
+
return {released:true,scope:'EXACT_UNSENT_CHAT_HOLD'};
|
|
265
|
+
}
|
|
266
|
+
async function registerReservedChat(tab,run) {
|
|
267
|
+
if(!Number.isSafeInteger(tab?.id)||tab.id<=0||typeof run?.token!=='string'
|
|
268
|
+
||typeof run.sessionId!=='string'||tab.url!=='https://chatgpt.com/'||run.phase!=='PENDING')return false;
|
|
269
|
+
const quota=await reconcile(run,{reap:false});
|
|
270
|
+
if(quota.activeChatCount+quota.unownedHomes+quota.pendingChatSlots>CHAT_LIMIT)
|
|
271
|
+
return false;
|
|
272
|
+
const state=await load(),hold=state.pendingChats.find(h=>h.token.toLowerCase()===run.token.toLowerCase());
|
|
273
|
+
if(!hold||hold.sessionId.toLowerCase()!==run.sessionId.toLowerCase()
|
|
274
|
+
||hold.projectId!==run.projectId
|
|
275
|
+
||hold.taskId!==(run.taskId??null))return false;
|
|
276
|
+
const live=await chrome.tabs.get(tab.id).catch(()=>null);
|
|
277
|
+
if(!live||live.url!==tab.url||live.openerTabId!==hold.actionTabId)
|
|
278
|
+
return false;
|
|
279
|
+
const prior=state.entries.find(e=>e.id===tab.id);
|
|
280
|
+
if(prior&&!(prior.kind==='chat'&&sameSession(prior,run)))return false;
|
|
281
|
+
if(!prior){
|
|
282
|
+
state.entries.push({id:tab.id,url:tab.url,kind:'chat',
|
|
283
|
+
sessionId:run.sessionId,...scopeOf(run),firstSeenAt:Date.now(),
|
|
284
|
+
confirmed:false,testOwned:/^cl-intent-e2e-[a-z0-9-]+$/i.test(run.projectId)});
|
|
285
|
+
state.created++;
|
|
286
|
+
state.peakChats=Math.max(state.peakChats,
|
|
287
|
+
state.entries.filter(e=>e.kind==='chat').length);
|
|
288
|
+
}
|
|
289
|
+
state.pendingChats=state.pendingChats.filter(h=>h.token.toLowerCase()!==hold.token.toLowerCase());
|
|
290
|
+
await save(state);
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
async function withRegisteredAction(run,{url,create}) {
|
|
294
|
+
if(typeof url!=='string'||!classify({id:1,url})
|
|
295
|
+
||typeof create!=='function')throw Error('ACTION_URL_UNVERIFIED');
|
|
296
|
+
const quota=await admit(run,{kind:'action'});
|
|
297
|
+
if(!quota.ok)return {ok:false,code:quota.code};
|
|
298
|
+
const tab=await create(); // Only the Worker caller can create a tab.
|
|
299
|
+
if(!Number.isSafeInteger(tab?.id)||tab.id<=0)
|
|
300
|
+
return {ok:false,code:'ACTION_CREATED_ID_UNVERIFIED',tab};
|
|
301
|
+
const registered=await registerAction({id:tab.id,url});
|
|
302
|
+
return registered?{ok:true,tab}
|
|
303
|
+
:{ok:false,code:'ACTION_RESOURCE_UNVERIFIED',tab};
|
|
304
|
+
}
|
|
193
305
|
async function registerAction(tab) {
|
|
194
306
|
const info=classify(tab);
|
|
195
|
-
if
|
|
196
|
-
|
|
197
|
-
if
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
//
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
307
|
+
if(!info)return false;
|
|
308
|
+
// A stale tab ID must not be registered as the Task's Action.
|
|
309
|
+
if(!await actionTabMatches(tab))return false;
|
|
310
|
+
const state=await load(),prior=state.entries.find(e=>e.id===tab.id);
|
|
311
|
+
if(prior){
|
|
312
|
+
if(prior.kind!=='action'||prior.url!==tab.url)return false;
|
|
313
|
+
// Old owned entries may lack type; unowned upgrades need exact kind.
|
|
314
|
+
if(prior.owned!==true){
|
|
315
|
+
if(prior.type!==info.kind)return false;
|
|
316
|
+
prior.owned=true;
|
|
317
|
+
await save(state);
|
|
318
|
+
}
|
|
319
|
+
return true;
|
|
206
320
|
}
|
|
321
|
+
state.entries.push({id:tab.id,url:tab.url,kind:'action',
|
|
322
|
+
type:info.kind,firstSeenAt:Date.now(),owned:true});
|
|
323
|
+
state.created++;
|
|
324
|
+
state.peakActions=Math.max(state.peakActions,
|
|
325
|
+
state.entries.filter(e=>e.kind==='action').length);
|
|
326
|
+
await save(state);
|
|
207
327
|
return true;
|
|
208
328
|
}
|
|
209
329
|
async function registerChat(tab,run) {
|
|
@@ -211,10 +331,10 @@
|
|
|
211
331
|
|| !(run?.sessionId || run?.token) || run.phase!=='PENDING') return false;
|
|
212
332
|
const state=await load();
|
|
213
333
|
const existing=state.entries.find(e=>e.id===tab.id);
|
|
214
|
-
if(existing)return existing.kind==='chat'
|
|
215
|
-
&&existing.sessionId===(run.sessionId||run.token);
|
|
334
|
+
if(existing)return existing.kind==='chat'&&sameSession(existing,run);
|
|
216
335
|
state.entries.push({id:tab.id,url:tab.url,kind:'chat',
|
|
217
|
-
sessionId:run.sessionId||run.token
|
|
336
|
+
sessionId:run.sessionId||run.token,...scopeOf(run),
|
|
337
|
+
firstSeenAt:Date.now(),confirmed:false,
|
|
218
338
|
testOwned:/^cl-intent-e2e-[a-z0-9-]+$/i.test(run.projectId||'')});
|
|
219
339
|
state.created++;
|
|
220
340
|
state.peakChats=Math.max(state.peakChats,
|
|
@@ -227,10 +347,14 @@
|
|
|
227
347
|
|| !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(tab.url)
|
|
228
348
|
||!run?.sessionId||run.phase!=="PENDING"||run.adoptTabId!==tab.id)
|
|
229
349
|
return false;
|
|
350
|
+
const quota=await reconcile(run,{reap:false});
|
|
351
|
+
if(quota.activeChatCount+quota.unownedHomes+quota.pendingChatSlots>=CHAT_LIMIT)
|
|
352
|
+
return false;
|
|
230
353
|
const state=await load();
|
|
231
354
|
if(state.entries.some(e=>e.id===tab.id))return false; // Existing Owner, even terminal, is not silently replaced.
|
|
232
355
|
state.entries.push({id:tab.id,url:tab.url,kind:"chat",
|
|
233
|
-
sessionId:run.sessionId
|
|
356
|
+
sessionId:run.sessionId,...scopeOf(run),
|
|
357
|
+
firstSeenAt:Date.now(),confirmed:true,
|
|
234
358
|
adopted:true,testOwned:false});
|
|
235
359
|
state.created++;
|
|
236
360
|
state.peakChats=Math.max(state.peakChats,
|
|
@@ -238,22 +362,38 @@
|
|
|
238
362
|
await save(state);
|
|
239
363
|
return true;
|
|
240
364
|
}
|
|
241
|
-
async function confirmChat(id,sessionId,url) {
|
|
365
|
+
async function confirmChat(id,sessionId,url,transfer) {
|
|
242
366
|
const state=await load();
|
|
243
367
|
const entry=state.entries.find(e=>e.id===id&&e.kind==='chat'
|
|
244
368
|
&&e.sessionId===sessionId);
|
|
245
369
|
if (!entry || !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(url)) return;
|
|
370
|
+
if(transfer&&!await confirmTransfer(state,entry,transfer,sameSession,url))return false;
|
|
246
371
|
entry.url=url;entry.confirmed=true;
|
|
247
|
-
await save(state);
|
|
372
|
+
await save(state);return transfer?true:undefined;
|
|
248
373
|
}
|
|
249
374
|
async function terminal(run) {
|
|
250
375
|
if (!(run?.sessionId||run?.token)
|
|
251
376
|
|| !['DONE','BLOCKED','CANCELLED'].includes(run.phase)) return;
|
|
252
377
|
const state=await load();
|
|
253
378
|
for(const entry of state.entries) if(entry.kind==='chat'
|
|
254
|
-
&&entry
|
|
379
|
+
&&sameSession(entry,run))entry.terminal=run.phase;
|
|
255
380
|
await save(state);
|
|
256
381
|
}
|
|
257
|
-
|
|
258
|
-
|
|
382
|
+
let operations=Promise.resolve();
|
|
383
|
+
const guard=operation=>(...args)=>{
|
|
384
|
+
const current=operations.then(()=>operation(...args));
|
|
385
|
+
operations=current.then(()=>undefined,()=>undefined);
|
|
386
|
+
return current;
|
|
387
|
+
};
|
|
388
|
+
globalThis.ChatLoopResourcesV1=Object.freeze({
|
|
389
|
+
reconcile:guard(reconcile),admit:guard(admit),
|
|
390
|
+
registerAction:guard(registerAction),registerChat:guard(registerChat),
|
|
391
|
+
adoptChat:guard(adoptChat),confirmChat:guard(confirmChat),
|
|
392
|
+
terminal:guard(terminal),reserveChat:guard(reserveChat),
|
|
393
|
+
releaseReservedChat:guard(releaseReservedChat),
|
|
394
|
+
reserveScopedHandoff:guard(reserveScopedHandoff),
|
|
395
|
+
verifyScopedHandoffHold:guard(verifyScopedHandoffHold),
|
|
396
|
+
registerReservedChat:guard(registerReservedChat),
|
|
397
|
+
withRegisteredAction:guard(withRegisteredAction),
|
|
398
|
+
KEY,ACTION_LIMIT,CHAT_LIMIT});
|
|
259
399
|
})();
|
package/extension/manifest.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"manifest_version": 3,
|
|
3
3
|
"name": "Chat Loop Extension",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.35",
|
|
5
5
|
"description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
|
|
6
6
|
"permissions": [
|
|
7
7
|
"activeTab",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
],
|
|
31
31
|
"js": [
|
|
32
32
|
"content.js",
|
|
33
|
+
"loop/core.js",
|
|
33
34
|
"loop/observer-inspect.js",
|
|
34
35
|
"loop/observer-poll.js",
|
|
35
36
|
"loop/observer-recovery.js",
|
package/extension/session.html
CHANGED
|
@@ -3,4 +3,5 @@
|
|
|
3
3
|
<style>body{font:15px system-ui,sans-serif;padding:24px;max-width:620px;color:#222}#status{font-weight:bold}#details{white-space:pre-wrap;overflow-wrap:anywhere}body[data-result="error"] #status{color:#b00020}</style>
|
|
4
4
|
</head><body><h1>Chat Loop · Session</h1><p id="status" role="status">STARTING</p>
|
|
5
5
|
<p id="details">验证精确 Session 和 Context 写权,不直接操作 Chat 页面。</p>
|
|
6
|
+
<button id="confirm-recovery" type="button" hidden>确认恢复原 Task 写权(不会发送 Chat 消息)</button>
|
|
6
7
|
<script src="actions/session.js"></script></body></html>
|
|
@@ -9,6 +9,9 @@ async function approvedAdoptionTarget(chatUrl=null,taskId=null){
|
|
|
9
9
|
const existing=tabs.filter(t=>chatIdOf(t.url)===requestedId);
|
|
10
10
|
if(existing.length>1)return {error:"ADOPTION_CHAT_DUPLICATE_TABS"};
|
|
11
11
|
if(existing.length===0){
|
|
12
|
+
// Opening the user-specified existing Chat is a Browser side effect.
|
|
13
|
+
// An active V2 Task must not be bypassed by this legacy V1 helper.
|
|
14
|
+
await assertLegacyWorkerWritable({native:true});
|
|
12
15
|
let opened;
|
|
13
16
|
try{opened=await chrome.tabs.create({url:chatUrl,active:true});}
|
|
14
17
|
catch{return {error:"ADOPTION_CHAT_OPEN_FAILED"};}
|
|
@@ -6,6 +6,22 @@ const ALARM_NAME = "chat-loop.turn-watch.v1";
|
|
|
6
6
|
const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
|
|
7
7
|
const CONTINUE_TEXT = "继续当前已授权任务,先核实真实进度、权限和已发生副作用;UNKNOWN 只查原回执,不盲目重试,也不把续接视为新增授权。完成本轮后末行只写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
|
|
8
8
|
const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
|
|
9
|
+
// V2 differs from V1: EVERY continuing Task Turn registers a future
|
|
10
|
+
// private intent BEFORE its assistant reply ends. A naked CONTINUE marker
|
|
11
|
+
// has no signed nextPrompt and MUST NOT be converted to an implicit send.
|
|
12
|
+
const scopedTurnToolNote = token =>
|
|
13
|
+
"\n\n【Chat Loop Task-first 本轮续接协议】" +
|
|
14
|
+
"本 Task 的 turnToken 为 " + token + "(不要在助手正文复述)。" +
|
|
15
|
+
"如果仍有已授权工作,必须在本轮助手回复尚未结束时调用 " +
|
|
16
|
+
"chat_loop_extension__continue,参数 taskFirst:true、turnToken " +
|
|
17
|
+
"及下一步 nextPrompt(无特殊内容时使用“继续当前已授权任务,核实进度、权限和副作用;UNKNOWN 只查原回执,不重发。”)。" +
|
|
18
|
+
"工具只登记 QUEUED,不会立即发送。随后整轮回答最后独立一行" +
|
|
19
|
+
"输出 [CHAT_LOOP_STATUS:CONTINUE]。" +
|
|
20
|
+
"如需提前交接,先核实可交接 Checkpoint,再在本轮调用 " +
|
|
21
|
+
"chat_loop_extension__handoff(taskFirst:true,turnToken)," +
|
|
22
|
+
"末行输出 [CHAT_LOOP_STATUS:HANDOFF]。" +
|
|
23
|
+
"任务完成或必须停止时不登记新发送,分别输出 DONE/BLOCKED。" +
|
|
24
|
+
"不允许只输出 CONTINUE/HANDOFF 而不登记对应的本 Task 意图。";
|
|
9
25
|
let queue = Promise.resolve();
|
|
10
26
|
// Business callbacks expose typed, bounded error codes only; raw messages can
|
|
11
27
|
// contain native paths, browser state or extension internals.
|
|
@@ -21,23 +37,62 @@ const serial = fn => {
|
|
|
21
37
|
};
|
|
22
38
|
// Admission and recovery run in this same Worker, never another browser executor.
|
|
23
39
|
const resources = workerApi.resources;
|
|
40
|
+
const policy=workerApi.policy;
|
|
41
|
+
const {pathOf,chatIdOf}=policy;
|
|
42
|
+
// The V2 store is Task-addressed, but it is not a replacement Browser Owner.
|
|
43
|
+
// Until scoped Router/Native/Context activation is verified, V1 must not write
|
|
44
|
+
// over an active V2 Task. Never fall back to the latest V2 Task.
|
|
45
|
+
const scopedTaskRuns=globalThis.ChatLoopTaskRunStoreV2?.create(chrome.storage.local);
|
|
46
|
+
const scopedTaskScheduler=scopedTaskRuns
|
|
47
|
+
?globalThis.ChatLoopTaskSchedulerV2?.create(scopedTaskRuns):null;
|
|
48
|
+
const scopedTaskOwnerResolver=scopedTaskRuns
|
|
49
|
+
?globalThis.ChatLoopTaskOwnerResolverV2?.create({
|
|
50
|
+
store:scopedTaskRuns,getTab:id=>chrome.tabs.get(id),
|
|
51
|
+
readNative:scope=>chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
52
|
+
op:'session-snapshot-v2',...scope}),
|
|
53
|
+
checkWriter:scope=>chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
54
|
+
op:'context-writer-check-v2',...scope}),
|
|
55
|
+
pathOf,chatIdOf}):null;
|
|
56
|
+
// These are dormant V2 route/dispatch primitives until every sender
|
|
57
|
+
// boundary uses exact TaskKey + Session generation; never auto-dispatch here.
|
|
58
|
+
async function hasActiveScopedTask(){
|
|
59
|
+
if(!scopedTaskRuns)return false;
|
|
60
|
+
const state=await scopedTaskRuns.read();
|
|
61
|
+
return Object.values(state.items).some(({run})=>
|
|
62
|
+
!['DONE','CANCELLED'].includes(run.phase));
|
|
63
|
+
}
|
|
64
|
+
async function assertLegacyWorkerWritable({native=false}={}){
|
|
65
|
+
if(await hasActiveScopedTask())throw Error('TASK_SCOPED_ROUTER_NOT_READY');
|
|
66
|
+
if(!native)return;
|
|
67
|
+
// The Worker snapshot may be stale after MV3 suspension or after another
|
|
68
|
+
// Profile committed a Native Owner. The existing V1 Native read refuses
|
|
69
|
+
// every live V2 Ledger, including ones not present in this Worker store.
|
|
70
|
+
const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
71
|
+
op:'session-read'}).catch(()=>null);
|
|
72
|
+
if(observed?.status!=='OK')
|
|
73
|
+
throw Error(observed?.code==='OWNER_LEDGER_ACTIVE_USE_SCOPED_QUERY'
|
|
74
|
+
?'TASK_SCOPED_ROUTER_NOT_READY':'LEGACY_NATIVE_OWNER_UNVERIFIED');
|
|
75
|
+
// An in-flight V2 Worker update after Native read must also be rejected.
|
|
76
|
+
if(await hasActiveScopedTask())throw Error('TASK_SCOPED_ROUTER_NOT_READY');
|
|
77
|
+
}
|
|
24
78
|
async function createBoundedAction(options) {
|
|
25
79
|
// Validate BEFORE creating a tab. No caller may open an arbitrary URL
|
|
26
80
|
// through the privileged Worker Action quota.
|
|
27
81
|
if(typeof options?.url!=='string'
|
|
28
82
|
||!options.url.startsWith(chrome.runtime.getURL('')))
|
|
29
83
|
throw Error('ACTION_URL_UNVERIFIED');
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
84
|
+
// One Worker resource critical section encloses quota admission,
|
|
85
|
+
// actual tab creation and exact URL registration. Another Task cannot
|
|
86
|
+
// pass admission against a stale count while this side effect is in flight.
|
|
87
|
+
const receipt=await resources.withRegisteredAction(await readRun(),{
|
|
88
|
+
url:options.url,create:async()=>{
|
|
89
|
+
await assertLegacyWorkerWritable({native:true});
|
|
90
|
+
return chrome.tabs.create(options);
|
|
91
|
+
}});
|
|
92
|
+
const tab=receipt.tab;
|
|
93
|
+
if(!receipt.ok){
|
|
94
|
+
if(!Number.isSafeInteger(tab?.id)||tab.id<=0)
|
|
95
|
+
throw Error(receipt.code||'ACTION_CREATED_ID_UNVERIFIED');
|
|
41
96
|
// Failed registration must not strand another Action tab. Remove only
|
|
42
97
|
// this tab if its fresh, read-back URL still proves Extension identity;
|
|
43
98
|
// never close a changed, active or pinned tab and never retry a send.
|
|
@@ -52,8 +107,6 @@ async function createBoundedAction(options) {
|
|
|
52
107
|
}
|
|
53
108
|
// Identity and receipt policy are shared deterministic helpers. This Worker
|
|
54
109
|
// remains the only Chrome action/state owner.
|
|
55
|
-
const policy=workerApi.policy;
|
|
56
|
-
const {pathOf,chatIdOf}=policy;
|
|
57
110
|
const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
|
|
58
111
|
// Keep only a fixed-size fingerprint after Start's one-shot prompt is erased.
|
|
59
112
|
// A missing historical fingerprint means NOT_COMPARABLE, not "zero matches".
|
|
@@ -70,6 +123,9 @@ const windowMsOf=policy.windowMsOf;
|
|
|
70
123
|
const {deadlineOf,clockActive,terminalFenceVerified,MODEL_RECEIPT_TTL_MS,
|
|
71
124
|
receiptHistory,updateModelReceipt,settleModelIntent}=policy;
|
|
72
125
|
async function saveRun(run) {
|
|
126
|
+
// Last Worker write fence: an independently committed V2 Native Owner
|
|
127
|
+
// must not be overwritten even if the caller skipped an earlier route.
|
|
128
|
+
await assertLegacyWorkerWritable({native:true});
|
|
73
129
|
if (run && ["DONE","BLOCKED"].includes(run.phase))
|
|
74
130
|
run = settleModelIntent(run, run.phase==="DONE"?"CANCELLED_DONE":"BLOCKED", run.reason);
|
|
75
131
|
const now = Date.now(), deadlineAt = deadlineOf(run);
|
|
@@ -205,8 +261,8 @@ async function resourceChatGate(message,sender) {
|
|
|
205
261
|
{tabId:run.tabId,token:run.token},run);
|
|
206
262
|
if(!authorized)return {status:'DENIED',code:'RESOURCE_ACTION_SOURCE_INVALID'};
|
|
207
263
|
if(message.stage==='preflight') {
|
|
208
|
-
const quota=await resources.
|
|
209
|
-
return quota.ok?{status:'OK',code:'
|
|
264
|
+
const quota=await resources.reserveChat(run,sender.tab.id);
|
|
265
|
+
return quota.ok?{status:'OK',code:'RESOURCE_CHAT_RESERVED'}
|
|
210
266
|
:{status:'DENIED',code:quota.code};
|
|
211
267
|
}
|
|
212
268
|
if(message.stage==='adopt' && run.mode==='adopt'
|
|
@@ -221,7 +277,8 @@ async function resourceChatGate(message,sender) {
|
|
|
221
277
|
return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
|
|
222
278
|
const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
|
|
223
279
|
if (!tab || tab.id===run.tabId || tab.id===sender.tab.id
|
|
224
|
-
||
|
|
280
|
+
|| tab.openerTabId!==sender.tab.id
|
|
281
|
+
|| !await resources.registerReservedChat(tab,run))
|
|
225
282
|
return {status:'DENIED',code:'RESOURCE_CHAT_NOT_VERIFIED'};
|
|
226
283
|
const inventory=await resources.reconcile(run);
|
|
227
284
|
if(inventory.activeChatCount>resources.CHAT_LIMIT)
|