@tomflow/chatloop-extension 0.4.34 → 0.4.36
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 +108 -0
- package/lib/owner-ledger.mjs +316 -0
- package/lib/owner-lock-exec.py +49 -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
|
@@ -184,6 +184,40 @@ async function run(){
|
|
|
184
184
|
||typeof proof.nonce!=='string')throw Error(proof?.code||'START_NATIVE_INVALID');
|
|
185
185
|
let prepared,taken,newTab,committed;
|
|
186
186
|
try{
|
|
187
|
+
if(proof.intent?.taskFirst===true){
|
|
188
|
+
// Versioned task-first original Chat Adopt. There is NO composer write,
|
|
189
|
+
// send click, new Chat or V1 global Run in this path.
|
|
190
|
+
prepared=await chrome.runtime.sendMessage({
|
|
191
|
+
type:'CHAT_LOOP_TASK_START_PREPARE_V2',requestId:id});
|
|
192
|
+
if(prepared?.status!=='PREPARED'
|
|
193
|
+
||prepared.scope!=='TASK_SCOPED_ADOPT_NO_SEND'
|
|
194
|
+
||!Number.isSafeInteger(prepared.tabId)
|
|
195
|
+
||typeof prepared.sessionId!=='string')
|
|
196
|
+
throw Error(prepared?.code||'SCOPED_START_PREPARE_UNVERIFIED');
|
|
197
|
+
await observerReady(prepared.tabId);
|
|
198
|
+
committed=await chrome.runtime.sendMessage({
|
|
199
|
+
type:'CHAT_LOOP_TASK_START_COMMIT_V2',requestId:id});
|
|
200
|
+
if(committed?.status!=='OK'
|
|
201
|
+
||committed.scope!=='TASK_SCOPED_ADOPTED_NO_SEND'
|
|
202
|
+
||committed.sessionId!==prepared.sessionId
|
|
203
|
+
||committed.tabId!==prepared.tabId)
|
|
204
|
+
throw Error(committed?.code||'SCOPED_START_COMMIT_UNVERIFIED');
|
|
205
|
+
// Resume only the existing Observer's baseline. It cannot grant a
|
|
206
|
+
// second sender; future new Turn events use the V2 Task route.
|
|
207
|
+
await chrome.tabs.sendMessage(prepared.tabId,{
|
|
208
|
+
type:'CHAT_LOOP_TURN_RESUME_V1',page:committed.page,
|
|
209
|
+
userKey:committed.userKey,assistantKey:committed.assistantKey,
|
|
210
|
+
...(committed.assistantKey?{baselineOnly:true}:{}),
|
|
211
|
+
startedAt:Date.now()}).catch(()=>null);
|
|
212
|
+
const receipt=await chrome.runtime.sendNativeMessage(host,{
|
|
213
|
+
op:'complete',id,nonce:proof.nonce,action:'start',
|
|
214
|
+
status:'OK',payload:JSON.stringify(committed)});
|
|
215
|
+
if(receipt?.status!=='SAVED'||receipt.id!==id)
|
|
216
|
+
throw Error('SCOPED_START_RECEIPT_UNKNOWN');
|
|
217
|
+
show('SUCCESS','当前 Task 已接管获批的原 Chat;未新建或发送消息。');
|
|
218
|
+
await chrome.tabs.remove(own.id).catch(()=>{});
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
187
221
|
prepared=await chrome.runtime.sendMessage({type:'CHAT_LOOP_SESSION_START_PREPARE_V1',
|
|
188
222
|
requestId:id,...(proof.traceParent?{traceParent:proof.traceParent}:{})});
|
|
189
223
|
if(prepared?.status!=='PREPARED')throw Error(prepared?.code||'START_PREPARE_DENIED');
|
|
@@ -8,8 +8,22 @@ async function run(){
|
|
|
8
8
|
const proof=await chrome.runtime.sendNativeMessage(host,{op:'acquire',id,action:'status'});
|
|
9
9
|
if(proof?.status!=='OK'||proof.action!=='status'||proof.id!==id)
|
|
10
10
|
throw Error(proof?.code||'STATUS_NATIVE_INVALID');
|
|
11
|
-
const
|
|
12
|
-
|
|
11
|
+
const scoped=Boolean(proof.intent?.projectId&&proof.intent?.taskId);
|
|
12
|
+
const state=await chrome.runtime.sendMessage(scoped
|
|
13
|
+
?{type:'CHAT_LOOP_TASK_STATUS_V2',requestId:id}
|
|
14
|
+
:{type:'CHAT_LOOP_SESSION_STATUS_V1',requestId:id,
|
|
15
|
+
...(proof.traceParent?{traceParent:proof.traceParent}:{})})
|
|
16
|
+
.catch(()=>null);
|
|
17
|
+
if(scoped&&(state?.status!=='OK'
|
|
18
|
+
||state.scope!=='TASK_SCOPED_STATUS_READ_ONLY')){
|
|
19
|
+
const code=/^[A-Z][A-Z0-9_]{1,95}$/.test(state?.code||'')
|
|
20
|
+
?state.code:'SCOPED_TASK_STATUS_UNVERIFIED';
|
|
21
|
+
// Failure is an actual read-only result, not an absent ACK that makes
|
|
22
|
+
// the caller wait or retry an unrelated Status Action.
|
|
23
|
+
await chrome.runtime.sendNativeMessage(host,{op:'complete',id,
|
|
24
|
+
nonce:proof.nonce,action:'status',status:'FAILED',code}).catch(()=>null);
|
|
25
|
+
throw Error(code);
|
|
26
|
+
}
|
|
13
27
|
const receipt=await chrome.runtime.sendNativeMessage(host,{op:'complete',id,
|
|
14
28
|
nonce:proof.nonce,action:'status',status:'OK',payload:JSON.stringify(state)});
|
|
15
29
|
if(receipt?.status!=='SAVED')throw Error(receipt?.code||'STATUS_NOT_STORED');
|
package/extension/background.js
CHANGED
|
@@ -1,10 +1,25 @@
|
|
|
1
1
|
// Chrome MV3 classic service Worker. Shared lexical context; exact order
|
|
2
2
|
// preserves the original single-Worker Owner and serialized Action lifecycle.
|
|
3
3
|
importScripts("loop/index.js");
|
|
4
|
+
importScripts("worker/task-run-store.js");
|
|
5
|
+
importScripts("worker/task-scheduler.js");
|
|
6
|
+
importScripts("worker/task-owner-resolver.js");
|
|
4
7
|
importScripts("worker/bootstrap.js");
|
|
5
8
|
importScripts("worker/admission.js");
|
|
6
9
|
importScripts("worker/adopt-prepare.js");
|
|
7
10
|
importScripts("worker/adopt-result.js");
|
|
11
|
+
importScripts("worker/task-start-v2.js");
|
|
12
|
+
importScripts("worker/task-intent-v2.js");
|
|
13
|
+
importScripts("worker/task-intent-dispatch-v2.js");
|
|
14
|
+
importScripts("worker/task-action-v2.js");
|
|
15
|
+
importScripts("worker/task-continue-recovery-v2.js");
|
|
16
|
+
importScripts("worker/task-handoff-v2.js");
|
|
17
|
+
importScripts("worker/task-handoff-recovery-v2.js");
|
|
18
|
+
importScripts("worker/task-hold-recovery-v2.js");
|
|
19
|
+
importScripts("worker/task-terminal-v2.js");
|
|
20
|
+
importScripts("worker/task-cancel-v2.js");
|
|
21
|
+
importScripts("worker/task-recover-v2.js");
|
|
22
|
+
importScripts("worker/task-cancel-recovery-v2.js");
|
|
8
23
|
importScripts("worker/session-control.js");
|
|
9
24
|
importScripts("worker/readiness.js");
|
|
10
25
|
importScripts("worker/turn-failure.js");
|
|
@@ -14,4 +29,5 @@ importScripts("worker/manual.js");
|
|
|
14
29
|
importScripts("worker/action-take.js");
|
|
15
30
|
importScripts("worker/action-result.js");
|
|
16
31
|
importScripts("worker/scheduler.js");
|
|
32
|
+
importScripts("worker/task-routes-v2.js");
|
|
17
33
|
importScripts("worker/router.js");
|
package/extension/loop/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Browser Worker API root; npm index.mjs is for Node only.
|
|
2
|
-
importScripts('loop/core.js','loop/resources.js');
|
|
2
|
+
importScripts('loop/core.js','loop/resource-maintenance.js','loop/resources.js');
|
|
3
3
|
importScripts('loop/action-catalog.generated.js');
|
|
4
4
|
importScripts('loop/api-aspect.generated.js');
|
|
5
5
|
importScripts('loop/api-observation-queue.generated.js');
|
|
@@ -16,27 +16,36 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
|
|
|
16
16
|
.filter(x=>["user","assistant"].includes(x.role));
|
|
17
17
|
const textOf=x=>(x.el.querySelector?.(".markdown")?.innerText
|
|
18
18
|
||x.el.innerText||x.el.textContent||"").trim();
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
19
|
+
// The Form App now emits "approve" and a task-specific formId.
|
|
20
|
+
// Require the full six-line Turn, a distinct UUID trace, R/P version
|
|
21
|
+
// encoded in the formId or explicit legacy label, and an A-only label.
|
|
22
|
+
// A summary, B-choice or casual affirmation is not Form evidence.
|
|
23
23
|
// This is SOFT evidence only: a text-shaped copy is not host-signed,
|
|
24
24
|
// so Context's independent Start lease remains mandatory.
|
|
25
25
|
const formApprovalVersion=(value,type)=>{
|
|
26
26
|
const lines=value.split(/\r?\n/).map(x=>x.trim()).filter(Boolean);
|
|
27
27
|
if(lines.length!==6
|
|
28
28
|
||lines[0]!=='Chat Loop Form 提交结果(由用户点击表单提交)'
|
|
29
|
-
||!/^formId:\s*[
|
|
29
|
+
||!/^formId:\s*[a-z0-9][a-z0-9_-]{7,127}$/i.test(lines[1])
|
|
30
30
|
||!/^traceRef:\s*[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(lines[2])
|
|
31
|
-
|
|
31
|
+
||!['选项值: A','选项值: approve'].includes(lines[3])
|
|
32
32
|
||lines[5]!=='请核对当前业务任务、文档与 Issue 版本及原生消息身份后处理本次选择;表单回执本身不构成审批或写权。')
|
|
33
33
|
return null;
|
|
34
|
-
const label=lines[4].match(/^选项标签:\s*A[||]\s*确认当前\s*([RP][1-9][0-9]*)\s*(需求|技术与验证方案|技术方案|方案)$/i);
|
|
35
|
-
if(!label||label[1][0].toUpperCase()!==type
|
|
36
|
-
||(type==='R')!==(label[2]==='需求'))return null;
|
|
37
34
|
const formId=lines[1].slice('formId:'.length).trim().toLowerCase();
|
|
38
35
|
const traceRef=lines[2].slice('traceRef:'.length).trim().toLowerCase();
|
|
39
|
-
|
|
36
|
+
const oldLabel=lines[4].match(/^选项标签:\s*A[||]\s*确认当前\s*([RP][1-9][0-9]*)\s*(需求|技术与验证方案|技术方案|方案)$/i);
|
|
37
|
+
const modernLabel=lines[3]==='选项值: approve'
|
|
38
|
+
&&/^选项标签:\s*A[||]\s*确认(需求|技术与验证方案|技术方案|方案)$/.exec(lines[4]);
|
|
39
|
+
const versions=[...formId.matchAll(/(?:^|[-_])([rp][1-9][0-9]*)(?=[-_]|$)/gi)]
|
|
40
|
+
.map(m=>m[1].toUpperCase());
|
|
41
|
+
const version=oldLabel?.[1].toUpperCase()
|
|
42
|
+
||(modernLabel&&versions.length===1?versions[0]:null);
|
|
43
|
+
const label=oldLabel?.[2]||modernLabel?.[1];
|
|
44
|
+
if(!version||version[0]!==type||!label
|
|
45
|
+
||(type==='R')!==(label==='需求')
|
|
46
|
+
||(oldLabel&&versions.length>0&&versions.some(v=>v!==version))
|
|
47
|
+
||formId===traceRef)return null;
|
|
48
|
+
return {version,formId,traceRef};
|
|
40
49
|
};
|
|
41
50
|
const confirms=(value,type)=>{
|
|
42
51
|
const line=value.replace(/\s+/g," ").trim();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Read-only Observer helper: no composer writes, Chrome Owner or sends.
|
|
2
2
|
(() => {
|
|
3
3
|
globalThis.ChatLoopObserverPollV1=({session,inspect,emit,resetCandidate,
|
|
4
|
-
fingerprint,STABLE_MS,getState})=>{
|
|
4
|
+
fingerprint,STABLE_MS,getState,reportBlocked})=>{
|
|
5
5
|
function poll() {
|
|
6
6
|
try {
|
|
7
7
|
const snap = inspect();
|
|
@@ -109,11 +109,12 @@ function poll() {
|
|
|
109
109
|
|| session.baselineUser && snap.userKey !== session.baselineUser)
|
|
110
110
|
&& session.reportedErrorUser !== snap.userKey) {
|
|
111
111
|
session.reportedErrorUser = snap.userKey;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
112
|
+
const detail={page:snap.path,userKey:snap.userKey,
|
|
113
|
+
reason:snap.errorReason,retryAvailable:snap.retryAvailable===true};
|
|
114
|
+
void Promise.resolve().then(()=>reportBlocked
|
|
115
|
+
?reportBlocked(detail)
|
|
116
|
+
:chrome.runtime.sendMessage({
|
|
117
|
+
type:'CHAT_LOOP_TURN_BLOCKED_V1',...detail})).catch(()=>{});
|
|
117
118
|
}
|
|
118
119
|
return emit(snap.fatal ? "BLOCKED" : "UNKNOWN",
|
|
119
120
|
snap.fatal ? snap.errorReason : "MODAL_PRESENT", snap);
|
|
@@ -66,10 +66,13 @@
|
|
|
66
66
|
detail: {contract: CONTRACT, page: snap.path,
|
|
67
67
|
userKey: snap.userKey, assistantKey: snap.assistantKey}
|
|
68
68
|
}));
|
|
69
|
-
//
|
|
70
|
-
//
|
|
69
|
+
// The V2 route is read-only and selects a Task from the real sender
|
|
70
|
+
// Tab, never from DOM text or a global latest-Task pointer. Only a
|
|
71
|
+
// verified UNSCOPED reply (or an old Worker without the V2 handler)
|
|
72
|
+
// falls back to the original V1 Turn delivery. A V2 BLOCKED/UNKNOWN
|
|
73
|
+
// never authorizes replay on the legacy sender.
|
|
71
74
|
if (typeof chrome.runtime.sendMessage === "function") {
|
|
72
|
-
|
|
75
|
+
const legacy=()=>chrome.runtime.sendMessage({
|
|
73
76
|
type: "CHAT_LOOP_TURN_FINISHED_V1", page: snap.path,
|
|
74
77
|
userKey: snap.userKey, assistantKey: snap.assistantKey,
|
|
75
78
|
replyText: snap.text, startedAt: session.firstTurnAt || Date.now(),
|
|
@@ -77,7 +80,29 @@
|
|
|
77
80
|
priorAssistantKey: snap.priorAssistantKey || null,
|
|
78
81
|
priorAssistantUserKey:snap.priorAssistantUserKey || null,
|
|
79
82
|
directReplyAfterPriorAssistant:snap.directReplyAfterPriorAssistant===true
|
|
80
|
-
})
|
|
83
|
+
});
|
|
84
|
+
void Promise.resolve().then(()=>chrome.runtime.sendMessage({
|
|
85
|
+
type:"CHAT_LOOP_TASK_TURN_OBSERVED_V2",page:snap.path,
|
|
86
|
+
userKey:snap.userKey,assistantKey:snap.assistantKey,
|
|
87
|
+
// Core is the SAME canonical status parser used in the Worker.
|
|
88
|
+
// Only the marker classification crosses this boundary; never
|
|
89
|
+
// forward the full private user reply into Task Store.
|
|
90
|
+
outcome:!snap.pendingConfirmation
|
|
91
|
+
?globalThis.ChatLoopCoreV1?.parseStatus(snap.text)??'UNKNOWN'
|
|
92
|
+
:'UNKNOWN',
|
|
93
|
+
pendingConfirmation:snap.pendingConfirmation===true
|
|
94
|
+
})).then(result=>{
|
|
95
|
+
if(result?.status==='OBSERVED'
|
|
96
|
+
&&['TASK_SCOPED_OBSERVATION_ONLY',
|
|
97
|
+
'TASK_SCOPED_TERMINAL_OBSERVATION'].includes(result.scope))
|
|
98
|
+
return;
|
|
99
|
+
// A genuine scoped rejection, including UNKNOWN/UNVERIFIED,
|
|
100
|
+
// never becomes a legacy V1 sender. Only a proven unowned Tab
|
|
101
|
+
// or an old Worker without this response may use V1 routing.
|
|
102
|
+
if(result?.status==='UNSCOPED'
|
|
103
|
+
&&result.code==='SCOPED_OBSERVER_TASK_NOT_FOUND'||!result)
|
|
104
|
+
return legacy();
|
|
105
|
+
},()=>legacy()).catch(()=>{});
|
|
81
106
|
}
|
|
82
107
|
}
|
|
83
108
|
return state;
|
|
@@ -86,8 +111,21 @@
|
|
|
86
111
|
session.candidate = "";
|
|
87
112
|
session.stableSince = 0;
|
|
88
113
|
}
|
|
89
|
-
|
|
90
|
-
|
|
114
|
+
const reportBlocked=detail=>{
|
|
115
|
+
const legacy=()=>chrome.runtime.sendMessage({
|
|
116
|
+
type:'CHAT_LOOP_TURN_BLOCKED_V1',...detail});
|
|
117
|
+
// A Task fault is only an observation, not a Handoff permit. Do not
|
|
118
|
+
// downgrade an explicit scoped denial into a legacy V1 side effect.
|
|
119
|
+
return Promise.resolve(chrome.runtime.sendMessage({
|
|
120
|
+
type:'CHAT_LOOP_TASK_TURN_BLOCKED_V2',...detail
|
|
121
|
+
})).then(result=>{
|
|
122
|
+
if(result?.status==='UNSCOPED'
|
|
123
|
+
&&result.code==='SCOPED_OBSERVER_TASK_NOT_FOUND'||!result)
|
|
124
|
+
return legacy();
|
|
125
|
+
},()=>legacy()).catch(()=>{});
|
|
126
|
+
};
|
|
127
|
+
const poll=globalThis.ChatLoopObserverPollV1({session,inspect,emit,
|
|
128
|
+
resetCandidate,fingerprint,STABLE_MS,getState:()=>state,reportBlocked});
|
|
91
129
|
function recordFirstChatSubmission(event) {
|
|
92
130
|
if (!event?.target?.closest) return;
|
|
93
131
|
const fromHome = !conversationPath() && !session.path;
|
|
@@ -130,17 +168,36 @@
|
|
|
130
168
|
return onRecovery(message,reply);
|
|
131
169
|
if(message?.type==='CHAT_LOOP_APPROVAL_EVIDENCE_V1')
|
|
132
170
|
return onApproval(message,reply);
|
|
171
|
+
if(message?.type==='CHAT_LOOP_TURN_PROGRESS_V2'){
|
|
172
|
+
// Model Intent is issued BEFORE the assistant Turn finishes. A
|
|
173
|
+
// completed historical user Turn never authorizes a fresh Action.
|
|
174
|
+
// Report only top-level current DOM identity and active generation
|
|
175
|
+
// evidence; neither message text nor a send permit crosses here.
|
|
176
|
+
if(Object.keys(message).length!==1)return false;
|
|
177
|
+
const snap=inspect();
|
|
178
|
+
reply({contract:CONTRACT,page:snap.path||null,
|
|
179
|
+
userKey:snap.userKey||null,
|
|
180
|
+
active:Boolean(snap.path&&snap.userKey
|
|
181
|
+
&&(snap.stop||snap.busy
|
|
182
|
+
||snap.hasAssistant&&snap.turnState
|
|
183
|
+
&&snap.turnState!=='complete')
|
|
184
|
+
&&!snap.pendingConfirmation&&!snap.fatal&&!snap.dialog),
|
|
185
|
+
pendingConfirmation:snap.pendingConfirmation===true});
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
133
188
|
if (message?.type === "CHAT_LOOP_TURN_VERIFY_V1") {
|
|
134
189
|
// Explicit manual Action: only a fresh read-only completed-Turn candidate.
|
|
135
190
|
// This does not emit a completion event or write anything to the page.
|
|
136
191
|
const snap = inspect();
|
|
137
192
|
const ready = Boolean(snap.path && snap.userKey && snap.assistantKey
|
|
138
193
|
&& snap.text && snap.composerReady && snap.copyAction
|
|
139
|
-
&& !snap.stop && !snap.busy && !snap.
|
|
194
|
+
&& !snap.stop && !snap.busy && !snap.pendingConfirmation
|
|
195
|
+
&& !snap.toolUnknown && !snap.fatal
|
|
140
196
|
&& !snap.dialog && (!snap.turnState || snap.turnState === "complete"));
|
|
141
197
|
reply({contract: CONTRACT, status: ready ? "READY" : "UNVERIFIED",
|
|
142
198
|
page: snap.path || null, userKey: snap.userKey || null,
|
|
143
199
|
assistantKey: snap.assistantKey || null,
|
|
200
|
+
pendingConfirmation:snap.pendingConfirmation===true,
|
|
144
201
|
replyText: ready ? snap.text : null});
|
|
145
202
|
return false;
|
|
146
203
|
}
|
|
@@ -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
|
+
})();
|