@tomflow/chatloop-tools 0.9.63 → 0.9.70
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 +13 -1
- package/index.mjs +7 -7
- package/lib/context-control-run.mjs +23 -5
- package/lib/extension-proxy.mjs +16 -7
- package/lib/native-owner-v2.mjs +128 -0
- package/lib/release-health-checks.mjs +29 -5
- package/lib/trace-gateway.mjs +3 -1
- package/node_modules/@tomflow/chatloop-context/README.md +56 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +24 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +1 -1
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +2 -2
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +69 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +3 -1
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +50 -3
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +54 -1
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +2 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +61 -2
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +33 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +14 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +31 -39
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +6 -5
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +84 -3
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +52 -7
- package/node_modules/@tomflow/chatloop-context/package.json +2 -4
- package/node_modules/@tomflow/chatloop-extension/README.md +66 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +19 -4
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +40 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -1
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +54 -4
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +9 -3
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +9 -5
- package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +53 -10
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +34 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +16 -2
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +1 -1
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +7 -6
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +64 -7
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +235 -95
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/session.html +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +3 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +73 -16
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +23 -6
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +237 -13
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +7 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +94 -19
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +3 -3
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +9 -2
- package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +50 -7
- package/node_modules/@tomflow/chatloop-extension/package.json +1 -3
- package/node_modules/@tomflow/chatloop-trace/package.json +1 -3
- package/package.json +9 -11
- package/providers/extension.mjs +59 -16
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// Pure support functions for the existing single Resource Ledger Owner.
|
|
2
|
+
// No storage or independent background Worker/Alarm is introduced.
|
|
3
|
+
(() => {
|
|
4
|
+
const safeRemove = async (tab,entry,state,reason) => {
|
|
5
|
+
const live=await chrome.tabs.get(tab.id).catch(()=>null);
|
|
6
|
+
if (!live || live.url !== entry.url || live.active || live.pinned) return false;
|
|
7
|
+
try {await chrome.tabs.remove(tab.id);}
|
|
8
|
+
catch (error) {
|
|
9
|
+
// A user can close this tab after the final ownership check. Treat an
|
|
10
|
+
// absent tab as unconfirmed cleanup and reconcile it on the next scan;
|
|
11
|
+
// a still-live tab with a remove error must remain an explicit failure.
|
|
12
|
+
if (await chrome.tabs.get(tab.id).catch(()=>null)) throw error;
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
state.closed++;
|
|
16
|
+
state.lastReaped={id:tab.id, reason, at:Date.now()};
|
|
17
|
+
state.entries=state.entries.filter(e=>e.id!==tab.id);
|
|
18
|
+
return true;
|
|
19
|
+
};
|
|
20
|
+
const noDraft = async tabId => {
|
|
21
|
+
try {
|
|
22
|
+
const [p]=await chrome.scripting.executeScript({target:{tabId},func:()=>{
|
|
23
|
+
if (location.origin !== 'https://chatgpt.com' || !/^\/c\/[0-9a-f-]{12,}$/i.test(location.pathname)) return false;
|
|
24
|
+
const editor=document.querySelector('[contenteditable="true"][data-composer-markdown]')
|
|
25
|
+
||document.querySelector('#prompt-textarea[contenteditable="true"]');
|
|
26
|
+
return !!editor && !(editor.innerText || editor.textContent || '').trim()
|
|
27
|
+
&& !document.querySelector('[data-testid*="attachment-preview"], [data-testid*="image-preview"], [data-testid="composer-attachment"]');
|
|
28
|
+
}});
|
|
29
|
+
return p?.result===true;
|
|
30
|
+
} catch {return false;}
|
|
31
|
+
};
|
|
32
|
+
const actionTabMatches=async tab=>{
|
|
33
|
+
const live=await chrome.tabs.get(tab.id).catch(()=>null);
|
|
34
|
+
return !!live&&(live.url===tab.url
|
|
35
|
+
||live.url==='about:blank'&&live.pendingUrl===tab.url);
|
|
36
|
+
};
|
|
37
|
+
// Opener absence is meaningful only while the exact original Action
|
|
38
|
+
// remains alive: closing it can erase a successor's opener attribution.
|
|
39
|
+
// Read the original before and after querying all tabs; any uncertainty
|
|
40
|
+
// retains the original Resource Ledger hold.
|
|
41
|
+
const noSuccessorForAbortedHandoff=async(run,actionTabId)=>{
|
|
42
|
+
const action={id:actionTabId,url:chrome.runtime.getURL('handoff.html')
|
|
43
|
+
+'?tabId='+run.tabId+'&token='+run.turnToken+'&taskFirst=1'};
|
|
44
|
+
if(!await actionTabMatches(action))return false;
|
|
45
|
+
const tabs=await chrome.tabs.query({});
|
|
46
|
+
if(tabs.some(tab=>tab.openerTabId===actionTabId))return false;
|
|
47
|
+
return actionTabMatches(action);
|
|
48
|
+
};
|
|
49
|
+
// Only a completed Native + Context transfer, already committed to
|
|
50
|
+
// the Worker Task Store, can retire the old physical Owner seat.
|
|
51
|
+
// Retain the old Chat entry and tab; it is historical provenance.
|
|
52
|
+
const confirmTransfer=async(state,entry,run,sameSession,url)=>{
|
|
53
|
+
// resourceTransfer is committed with the proven generation switch
|
|
54
|
+
// by the Task Store CAS, not supplied by an Action or a Chat page.
|
|
55
|
+
const r=run?.resourceTransfer;
|
|
56
|
+
if(!r||!run.taskId||run.generation<1
|
|
57
|
+
||r.sourceTabId===run.tabId||r.sourcePage===run.page
|
|
58
|
+
||entry.id!==run.tabId||!sameSession(entry,run)
|
|
59
|
+
||entry.supersededBy!==undefined
|
|
60
|
+
||(entry.url!=='https://chatgpt.com/'&&entry.url!==url)
|
|
61
|
+
||!Number.isSafeInteger(r.sourceTabId)||r.sourceTabId<=0
|
|
62
|
+
||!/^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(r.sourcePage)
|
|
63
|
+
||!/^\/c\/[0-9a-f-]{12,}$/i.test(run.page)
|
|
64
|
+
||!/^[a-f0-9]{32}$/.test(r.attemptId)
|
|
65
|
+
||url!=='https://chatgpt.com'+run.page)return false;
|
|
66
|
+
const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
|
|
67
|
+
try{
|
|
68
|
+
const live=new URL(tab?.url);
|
|
69
|
+
if(live.origin+live.pathname!==url)return false;
|
|
70
|
+
}catch{return false;}
|
|
71
|
+
const old=state.entries.find(e=>e.id===r.sourceTabId);
|
|
72
|
+
if(old&&(!old.confirmed||old.kind!=='chat'||!sameSession(old,run)
|
|
73
|
+
||old.url!=='https://chatgpt.com'+r.sourcePage
|
|
74
|
+
||old.supersededBy!==undefined&&old.supersededBy!==entry.id))
|
|
75
|
+
return false;
|
|
76
|
+
if(old)old.supersededBy=entry.id;
|
|
77
|
+
return true;
|
|
78
|
+
};
|
|
79
|
+
const activeChat=(entry,runs,sameSession)=>{
|
|
80
|
+
// Never use a historical seat as an active Owner, except when a
|
|
81
|
+
// conflicting current projection still points to its exact tab.
|
|
82
|
+
if(Number.isSafeInteger(entry.supersededBy)&&entry.supersededBy>0
|
|
83
|
+
&&entry.supersededBy!==entry.id&&entry.confirmed&&entry.taskId)
|
|
84
|
+
return runs.some(r=>sameSession(entry,r)&&r.tabId===entry.id
|
|
85
|
+
&&!['DONE','BLOCKED','CANCELLED'].includes(r.phase));
|
|
86
|
+
return !['DONE','BLOCKED','CANCELLED'].includes(entry.terminal)
|
|
87
|
+
||runs.some(r=>sameSession(entry,r)
|
|
88
|
+
&&!['DONE','BLOCKED','CANCELLED'].includes(r.phase));
|
|
89
|
+
};
|
|
90
|
+
// Only binds to the caller's existing Resource Ledger. This helper
|
|
91
|
+
// owns no storage, queue, browser sender, clock or independent authority.
|
|
92
|
+
const createHandoffReservation=({load,reserveChat,actionTabMatches,validScope})=>{
|
|
93
|
+
const same=(h,run,actionTabId)=>typeof run.turnToken==='string'
|
|
94
|
+
&&typeof run.sessionId==='string'
|
|
95
|
+
&&h.token.toLowerCase()===run.turnToken.toLowerCase()
|
|
96
|
+
&&h.sessionId.toLowerCase()===run.sessionId.toLowerCase()
|
|
97
|
+
&&h.projectId===run.projectId&&h.taskId===run.taskId
|
|
98
|
+
&&h.actionTabId===actionTabId;
|
|
99
|
+
const reserve=async(run,actionTabId)=>{
|
|
100
|
+
if(run?.phase!=='WAITING_REPLY'
|
|
101
|
+
||!validScope(run.projectId)||!validScope(run.taskId)
|
|
102
|
+
||run.modelIntent?.action!=='HANDOFF'
|
|
103
|
+
||run.modelIntent.state!=='QUEUED'
|
|
104
|
+
||run.modelIntent.actionTabId!==actionTabId
|
|
105
|
+
||run.modelIntent.turnToken!==run.turnToken
|
|
106
|
+
||run.lastObservedTurn?.outcome!=='HANDOFF'
|
|
107
|
+
||run.lastObservedTurn.pendingConfirmation!==false
|
|
108
|
+
||run.lastObservedTurn.userKey!==run.modelIntent.targetUserKey
|
|
109
|
+
||!Number.isSafeInteger(actionTabId)||actionTabId<=0
|
|
110
|
+
||!/^[0-9a-f-]{36}$/i.test(run.turnToken||''))
|
|
111
|
+
throw Error('RESOURCE_HANDOFF_SOURCE_INVALID');
|
|
112
|
+
const url=chrome.runtime.getURL('handoff.html')+
|
|
113
|
+
'?tabId='+run.tabId+'&token='+run.turnToken+'&taskFirst=1';
|
|
114
|
+
if(!await actionTabMatches({id:actionTabId,url}))
|
|
115
|
+
throw Error('RESOURCE_HANDOFF_ACTION_CHANGED');
|
|
116
|
+
const state=await load(),owned=state.pendingChats.filter(h=>
|
|
117
|
+
same(h,run,actionTabId));
|
|
118
|
+
if(owned.length===1)return {ok:true,code:'RESOURCE_CHAT_RESERVED_SAME_ATTEMPT'};
|
|
119
|
+
if(state.pendingChats.some(h=>
|
|
120
|
+
h.token.toLowerCase()===run.turnToken.toLowerCase()
|
|
121
|
+
||h.sessionId.toLowerCase()===run.sessionId.toLowerCase()
|
|
122
|
+
||h.actionTabId===actionTabId))
|
|
123
|
+
return {ok:false,code:'RESOURCE_HANDOFF_HOLD_CONFLICT'};
|
|
124
|
+
return reserveChat({...run,phase:'PENDING',token:run.turnToken},actionTabId);
|
|
125
|
+
};
|
|
126
|
+
const verify=async(run,actionTabId)=>{
|
|
127
|
+
if(run?.phase!=='PENDING'||run.modelIntent?.action!=='HANDOFF'
|
|
128
|
+
||run.modelIntent.state!=='TAKEN'
|
|
129
|
+
||run.modelIntent.actionTabId!==actionTabId
|
|
130
|
+
||run.nextAttempt?.id!==run.modelIntent.id
|
|
131
|
+
||!validScope(run.projectId)||!validScope(run.taskId))
|
|
132
|
+
return false;
|
|
133
|
+
const url=chrome.runtime.getURL('handoff.html')+
|
|
134
|
+
'?tabId='+run.tabId+'&token='+run.turnToken+'&taskFirst=1';
|
|
135
|
+
if(!await actionTabMatches({id:actionTabId,url}))return false;
|
|
136
|
+
const state=await load();
|
|
137
|
+
// load() already rejects duplicate token/session/action-tab holds.
|
|
138
|
+
return state.pendingChats.some(h=>same(h,run,actionTabId));
|
|
139
|
+
};
|
|
140
|
+
return {reserve,verify};
|
|
141
|
+
};
|
|
142
|
+
const finishedSendAction=(info,entry,runs)=>runs.some(run=>{
|
|
143
|
+
const legacy=['DONE','BLOCKED'].includes(run.phase)
|
|
144
|
+
&&run.token===info.token
|
|
145
|
+
&&[run.tabId,run.sourceTabId].includes(info.targetId);
|
|
146
|
+
const receipt=run.lastIntentReceipt;
|
|
147
|
+
const scoped=entry.owned===true
|
|
148
|
+
&&['continue','handoff'].includes(info.name)
|
|
149
|
+
&&receipt?.turnToken===info.token
|
|
150
|
+
&&receipt.action===info.name.toUpperCase()
|
|
151
|
+
&&receipt.status==='SENT_CONFIRMED'
|
|
152
|
+
&&(info.name==='continue'
|
|
153
|
+
?run.tabId===info.targetId:run.generation>=1);
|
|
154
|
+
return legacy||scoped;
|
|
155
|
+
});
|
|
156
|
+
globalThis.ChatLoopResourceMaintenanceV1=Object.freeze({
|
|
157
|
+
safeRemove,noDraft,actionTabMatches,noSuccessorForAbortedHandoff,
|
|
158
|
+
confirmTransfer,activeChat,createHandoffReservation,finishedSendAction});
|
|
159
|
+
})();
|
|
@@ -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
|
})();
|
|
@@ -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>
|