@tomflow/chatloop-tools 0.9.63 → 0.9.64
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/package.json +2 -12
- package/providers/extension.mjs +59 -16
- package/node_modules/@tomflow/chatloop-context/README.md +0 -240
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
- package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
- package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
- package/node_modules/@tomflow/chatloop-context/package.json +0 -40
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
- package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
- package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
- package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
- package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
- package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
- package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -89
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
- package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
- package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
- package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
- package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
- package/node_modules/ps-list/index.d.ts +0 -76
- package/node_modules/ps-list/index.js +0 -366
- package/node_modules/ps-list/license +0 -9
- package/node_modules/ps-list/package.json +0 -44
- package/node_modules/ps-list/readme.md +0 -56
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
// Chat Loop Worker — adopt-result. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
-
async function sessionStartResult(message,sender){
|
|
3
|
-
const run=await readRun();
|
|
4
|
-
if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
|
|
5
|
-
||run.machineActionTabId!==sender.tab.id||run.token!==message.token
|
|
6
|
-
||run.phase!=='PENDING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
|
|
7
|
-
const adopted=run.mode==='adopt';
|
|
8
|
-
let confirmed=(adopted?message.result==='ADOPTED_CONFIRMED'
|
|
9
|
-
:message.result==='SENT_CONFIRMED')
|
|
10
|
-
&&Number.isInteger(message.newTabId)
|
|
11
|
-
&&typeof message.newPage==='string'&&pathOf('https://chatgpt.com'+message.newPage)===message.newPage
|
|
12
|
-
&&typeof message.newUserKey==='string'&&/^user:[^\s]{8,}$/.test(message.newUserKey);
|
|
13
|
-
if(confirmed){
|
|
14
|
-
const tab=await chrome.tabs.get(message.newTabId).catch(()=>null);
|
|
15
|
-
confirmed=!!tab&&pathOf(tab.url)===message.newPage;
|
|
16
|
-
}
|
|
17
|
-
if(confirmed && adopted){
|
|
18
|
-
confirmed=message.newTabId===run.adoptTabId
|
|
19
|
-
&&message.newPage===run.adoptPage
|
|
20
|
-
&&message.newUserKey===run.adoptUserKey;
|
|
21
|
-
if(confirmed){
|
|
22
|
-
const repair=run.purpose==='REPAIR_SAME_SCOPE';
|
|
23
|
-
const proof=await chrome.tabs.sendMessage(run.adoptTabId,
|
|
24
|
-
{type:repair?'CHAT_LOOP_REPAIR_EVIDENCE_V1':'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
|
|
25
|
-
...(run.adoptExplicitChatId
|
|
26
|
-
?{explicitChatId:run.adoptExplicitChatId}:{}),
|
|
27
|
-
...(run.adoptExpectedTaskId
|
|
28
|
-
?{expectedTaskId:run.adoptExpectedTaskId}:{})}).catch(()=>null);
|
|
29
|
-
const original={page:run.adoptPage,userKey:run.adoptUserKey,
|
|
30
|
-
priorAssistantKey:run.adoptPriorAssistantKey||null,
|
|
31
|
-
postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
|
|
32
|
-
rVersion:run.adoptRVersion,pVersion:run.adoptPVersion};
|
|
33
|
-
confirmed=repair
|
|
34
|
-
?proof?.contract==='chat-loop.turn-observer.v1'
|
|
35
|
-
&&proof.status==='VERIFIED'&&proof.page===run.adoptPage
|
|
36
|
-
&&proof.userKey===run.adoptUserKey
|
|
37
|
-
&&proof.userText===run.repairUserText
|
|
38
|
-
&&proof.priorDoneAssistantKey===run.repairDoneAssistantKey
|
|
39
|
-
:policy.sameAdoptionEvidence(original,
|
|
40
|
-
policy.normalizeAdoptionEvidence(proof,{page:run.adoptPage}));
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
// Four-hour execution clock begins at confirmed enrollment, not at
|
|
44
|
-
// the UI approval or potentially long Start readiness/preparation.
|
|
45
|
-
const adoptedIdle=confirmed&&adopted&&!!run.adoptPostApprovalAssistantKey;
|
|
46
|
-
const next={...run,
|
|
47
|
-
// Protect the crash window between a confirmed browser send and Native
|
|
48
|
-
// run.bind.initial. This marks the session as Context-governed, NOT as
|
|
49
|
-
// successfully bound; subsequent DONE/Continue must verify the real Store.
|
|
50
|
-
...(confirmed&&run.contextLeaseRef
|
|
51
|
-
?{contextManaged:{storeEpoch:run.contextStoreEpoch}}:{}),
|
|
52
|
-
phase:confirmed?'WAITING_REPLY':'BLOCKED',
|
|
53
|
-
startedAt:confirmed?Date.now():run.startedAt,
|
|
54
|
-
lastStartActionTabId:sender.tab.id,
|
|
55
|
-
...(adoptedIdle?{assistantKey:run.adoptPostApprovalAssistantKey,
|
|
56
|
-
userKey:run.adoptUserKey}:{}),
|
|
57
|
-
reason:confirmed?(adoptedIdle?'ADOPTED_IDLE_BASELINE':'')
|
|
58
|
-
:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED',
|
|
59
|
-
...(!confirmed&&['START_HOME_URL_UNVERIFIED','NEW_CHAT_NOT_READY',
|
|
60
|
-
'START_COMPOSER_NOT_EMPTY','START_ACCOUNT_SWITCH_VISIBLE',
|
|
61
|
-
'FIRST_TURN_OBSERVER_UNAVAILABLE','START_SEND_BUTTON_UNAVAILABLE','START_INPUT_CHANGED',
|
|
62
|
-
'START_INPUT_UNVERIFIED','START_INPUT_REJECTED',
|
|
63
|
-
'START_CLICK_UNVERIFIED','FIRST_SEND_RECEIPT_UNKNOWN']
|
|
64
|
-
.includes(message.failureCode)
|
|
65
|
-
?{lastStartFailureCode:message.failureCode}:{}),
|
|
66
|
-
...(confirmed?{tabId:message.newTabId,page:message.newPage,
|
|
67
|
-
newUserKey:message.newUserKey}:{attemptedNewTabId:Number.isInteger(message.newTabId)?message.newTabId:null})};
|
|
68
|
-
if(confirmed){
|
|
69
|
-
delete next.handoffPending;
|
|
70
|
-
delete next.handoffPendingAt;
|
|
71
|
-
}
|
|
72
|
-
delete next.startPrompt;
|
|
73
|
-
delete next.adoptTabId;
|
|
74
|
-
delete next.adoptPage;
|
|
75
|
-
delete next.adoptUserKey;
|
|
76
|
-
delete next.adoptExplicitChatId;
|
|
77
|
-
delete next.adoptExpectedTaskId;
|
|
78
|
-
delete next.adoptPriorAssistantKey;
|
|
79
|
-
delete next.adoptPostApprovalAssistantKey;
|
|
80
|
-
delete next.adoptRVersion;
|
|
81
|
-
delete next.adoptPVersion;
|
|
82
|
-
delete next.repairUserText;
|
|
83
|
-
delete next.repairDoneAssistantKey;
|
|
84
|
-
delete next.purpose;
|
|
85
|
-
delete next.mode;
|
|
86
|
-
delete next.machineRequestId;
|
|
87
|
-
delete next.machineActionTabId;
|
|
88
|
-
delete next.replacedBlockedSessionId;
|
|
89
|
-
await saveRun(next);
|
|
90
|
-
let privateContext=null;
|
|
91
|
-
if(confirmed&&run.contextLeaseRef){
|
|
92
|
-
const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
93
|
-
op:'context-control',command:'run.bind.initial',
|
|
94
|
-
args:{expectedStoreEpoch:run.contextStoreEpoch,
|
|
95
|
-
writeRequestId:run.token+':initial-bind',
|
|
96
|
-
expectedTaskRevision:run.contextTaskRevision,expectedBindingRevision:0,
|
|
97
|
-
actionToken:run.token,leaseRef:run.contextLeaseRef,
|
|
98
|
-
runCredential:run.contextInitialCredential}
|
|
99
|
-
}).catch(()=>null);
|
|
100
|
-
if(bound?.status!=='OK'||bound.result?.status!=='BOUND'){
|
|
101
|
-
// First Chat may already exist. Never re-send merely to fix Context.
|
|
102
|
-
const stopped={...next,phase:'BLOCKED',reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
|
|
103
|
-
delete stopped.contextInitialCredential;
|
|
104
|
-
await saveRun(stopped);
|
|
105
|
-
return {status:'BLOCKED',code:bound?.code||'CONTEXT_INITIAL_BIND_UNVERIFIED'};
|
|
106
|
-
}
|
|
107
|
-
privateContext={runRef:bound.result.runRef,
|
|
108
|
-
runCredential:run.contextInitialCredential,
|
|
109
|
-
storeEpoch:run.contextStoreEpoch,
|
|
110
|
-
bindingRevision:bound.result.bindingRevision,
|
|
111
|
-
taskRevision:run.contextTaskRevision};
|
|
112
|
-
// Capability is delivered once in the private Start result, not Status.
|
|
113
|
-
const clean={...next,contextManaged:{storeEpoch:run.contextStoreEpoch}};
|
|
114
|
-
for(const key of ['contextInitialCredential','contextLeaseRef','contextStoreEpoch',
|
|
115
|
-
'contextTaskRevision','contextApprovalRevision'])delete clean[key];
|
|
116
|
-
await saveRun(clean);
|
|
117
|
-
}
|
|
118
|
-
if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
|
|
119
|
-
'https://chatgpt.com'+message.newPage).catch(()=>{});
|
|
120
|
-
return confirmed?{status:'OK',sessionId:next.sessionId,
|
|
121
|
-
activeChatId:sessionProjection(next).activeChatId,
|
|
122
|
-
activeChatUrl:sessionProjection(next).activeChatUrl,
|
|
123
|
-
...(next.taskId?{taskId:next.taskId}:{}),
|
|
124
|
-
...(privateContext?{context:privateContext}:{})}
|
|
125
|
-
:{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
|
|
126
|
-
}
|
|
@@ -1,230 +0,0 @@
|
|
|
1
|
-
// Chat Loop Worker — bootstrap. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
-
const workerApi=globalThis.ChatLoopWorkerApiV1;
|
|
3
|
-
const RUN_KEY = "chat-loop.action.run.v1";
|
|
4
|
-
const SESSION_HOST = "com.tomflow.chatloop.extension";
|
|
5
|
-
const ALARM_NAME = "chat-loop.turn-watch.v1";
|
|
6
|
-
const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
|
|
7
|
-
const CONTINUE_TEXT = "继续当前已授权任务,先核实真实进度、权限和已发生副作用;UNKNOWN 只查原回执,不盲目重试,也不把续接视为新增授权。完成本轮后末行只写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
|
|
8
|
-
const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
|
|
9
|
-
let queue = Promise.resolve();
|
|
10
|
-
// Business callbacks expose typed, bounded error codes only; raw messages can
|
|
11
|
-
// contain native paths, browser state or extension internals.
|
|
12
|
-
const safeWorkerErrorCode=(failure,fallback)=>{
|
|
13
|
-
const code=failure?.code||failure?.message;
|
|
14
|
-
return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
|
|
15
|
-
?code:fallback;
|
|
16
|
-
};
|
|
17
|
-
const serial = fn => {
|
|
18
|
-
const work = queue.then(fn);
|
|
19
|
-
queue = work.catch(() => {});
|
|
20
|
-
return work;
|
|
21
|
-
};
|
|
22
|
-
// Admission and recovery run in this same Worker, never another browser executor.
|
|
23
|
-
const resources = workerApi.resources;
|
|
24
|
-
async function createBoundedAction(options) {
|
|
25
|
-
// Validate BEFORE creating a tab. No caller may open an arbitrary URL
|
|
26
|
-
// through the privileged Worker Action quota.
|
|
27
|
-
if(typeof options?.url!=='string'
|
|
28
|
-
||!options.url.startsWith(chrome.runtime.getURL('')))
|
|
29
|
-
throw Error('ACTION_URL_UNVERIFIED');
|
|
30
|
-
const quota=await resources.admit(await readRun(),{kind:'action'});
|
|
31
|
-
if (!quota.ok) throw Error(quota.code);
|
|
32
|
-
const tab=await chrome.tabs.create(options);
|
|
33
|
-
if (!Number.isSafeInteger(tab?.id)||tab.id<=0)
|
|
34
|
-
throw Error('ACTION_CREATED_ID_UNVERIFIED');
|
|
35
|
-
// MV3 tabs.create may return about:blank + pendingUrl. Register the exact
|
|
36
|
-
// Extension URL requested rather than the transitional snapshot.
|
|
37
|
-
let registered=false;
|
|
38
|
-
try{registered=await resources.registerAction({id:tab.id,url:options.url});}
|
|
39
|
-
catch{ /* The newly created page is not trusted without its registration. */ }
|
|
40
|
-
if(!registered){
|
|
41
|
-
// Failed registration must not strand another Action tab. Remove only
|
|
42
|
-
// this tab if its fresh, read-back URL still proves Extension identity;
|
|
43
|
-
// never close a changed, active or pinned tab and never retry a send.
|
|
44
|
-
const current=await chrome.tabs.get(tab.id).catch(()=>null);
|
|
45
|
-
if(current&&!current.active&&!current.pinned
|
|
46
|
-
&&(current.url===options.url
|
|
47
|
-
||current.url==='about:blank'&¤t.pendingUrl===options.url))
|
|
48
|
-
await chrome.tabs.remove(tab.id).catch(()=>{});
|
|
49
|
-
throw Error('ACTION_RESOURCE_UNVERIFIED');
|
|
50
|
-
}
|
|
51
|
-
return tab;
|
|
52
|
-
}
|
|
53
|
-
// Identity and receipt policy are shared deterministic helpers. This Worker
|
|
54
|
-
// remains the only Chrome action/state owner.
|
|
55
|
-
const policy=workerApi.policy;
|
|
56
|
-
const {pathOf,chatIdOf}=policy;
|
|
57
|
-
const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
|
|
58
|
-
// Keep only a fixed-size fingerprint after Start's one-shot prompt is erased.
|
|
59
|
-
// A missing historical fingerprint means NOT_COMPARABLE, not "zero matches".
|
|
60
|
-
async function startPromptFingerprint(prompt) {
|
|
61
|
-
if(typeof prompt!=='string'||!globalThis.crypto?.subtle||
|
|
62
|
-
typeof TextEncoder!=='function')return null;
|
|
63
|
-
const normalized=prompt.replace(/\s+/g,'');
|
|
64
|
-
if(!normalized)return null;
|
|
65
|
-
const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(normalized));
|
|
66
|
-
return Array.from(new Uint8Array(digest),v=>v.toString(16).padStart(2,'0')).join('');
|
|
67
|
-
}
|
|
68
|
-
// Keep the windowMsOf alias as the fingerprint test's pure-read boundary.
|
|
69
|
-
const windowMsOf=policy.windowMsOf;
|
|
70
|
-
const {deadlineOf,clockActive,terminalFenceVerified,MODEL_RECEIPT_TTL_MS,
|
|
71
|
-
receiptHistory,updateModelReceipt,settleModelIntent}=policy;
|
|
72
|
-
async function saveRun(run) {
|
|
73
|
-
if (run && ["DONE","BLOCKED"].includes(run.phase))
|
|
74
|
-
run = settleModelIntent(run, run.phase==="DONE"?"CANCELLED_DONE":"BLOCKED", run.reason);
|
|
75
|
-
const now = Date.now(), deadlineAt = deadlineOf(run);
|
|
76
|
-
// Persist the intent even when a delayed alarm arrives after an Action
|
|
77
|
-
// receipt. This never revokes a Continue already reserved before deadline.
|
|
78
|
-
const sending = ["STARTING","RESERVED","PENDING"].includes(run.phase);
|
|
79
|
-
const marker = sending && typeof run.token==="string" ? run.token : null;
|
|
80
|
-
const next = {...run, ...(deadlineAt ? {deadlineAt} : {}),
|
|
81
|
-
...(marker ? {actionPendingAt: run.resourceToken===marker
|
|
82
|
-
&& Number.isSafeInteger(run.actionPendingAt) ? run.actionPendingAt : now,
|
|
83
|
-
resourceToken:marker} : {})};
|
|
84
|
-
if (clockActive(next) && deadlineAt !== null && now >= deadlineAt
|
|
85
|
-
&& !next.handoffPending) {
|
|
86
|
-
next.handoffPending = true;
|
|
87
|
-
next.handoffPendingAt = now;
|
|
88
|
-
}
|
|
89
|
-
const stored=await readRun();
|
|
90
|
-
const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
|
|
91
|
-
&&["TOOL_PREFLIGHT_REPAIRED","HANDOFF_NOT_SENT","ADOPT_IDLE_BASELINE"].includes(next.recoveryMode)
|
|
92
|
-
&&next.recoveryAttempts>=1&&stored?.phase==="BLOCKED";
|
|
93
|
-
if(recoveryCommit&&(!Number.isSafeInteger(next.recoveryExpectedNativeAt)
|
|
94
|
-
||next.recoveryExpectedNativeAt<=0))
|
|
95
|
-
throw Error('SESSION_RECOVERY_CAS_MISSING');
|
|
96
|
-
// Native must commit first for the exact terminal CAS transitions.
|
|
97
|
-
const replacementCommit=Boolean(next.replacedBlockedSessionId
|
|
98
|
-
&&next.phase==='STARTING'&&stored?.sessionId!==next.sessionId);
|
|
99
|
-
// Cancel must commit Native terminal CAS before exposing Worker CANCELLED.
|
|
100
|
-
// A missing Native reply leaves Worker BLOCKED, never falsely IDLE.
|
|
101
|
-
const cancelFreeze=next.reason==='SESSION_CANCEL_PENDING'
|
|
102
|
-
&&next.phase==='BLOCKED'&&stored?.phase==='WAITING_REPLY'
|
|
103
|
-
&&Number.isSafeInteger(next.cancelFreezeExpectedAt);
|
|
104
|
-
const nativeFirst=recoveryCommit||replacementCommit
|
|
105
|
-
||next.phase==='CANCELLED'||cancelFreeze;
|
|
106
|
-
const syncNative=async()=>{
|
|
107
|
-
if(!next.sessionId)return;
|
|
108
|
-
const record=sessionProjection(next);
|
|
109
|
-
const saved=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
110
|
-
{op:"session-sync",session:record,
|
|
111
|
-
...(next.replacedBlockedSessionId&&!recoveryCommit&&next.phase==='STARTING'
|
|
112
|
-
?{replaceBlockedSessionId:next.replacedBlockedSessionId,
|
|
113
|
-
...(Number.isSafeInteger(next.sameTaskPrePermitUpdatedAt)
|
|
114
|
-
?{sameTaskPrePermitUpdatedAt:next.sameTaskPrePermitUpdatedAt}:{})}:{}),
|
|
115
|
-
...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
|
|
116
|
-
resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{}),
|
|
117
|
-
...(next.phase==='CANCELLED'
|
|
118
|
-
?{cancelBlockedUpdatedAt:next.cancelBlockedUpdatedAt,
|
|
119
|
-
cancelRequestId:next.cancelRequestId}:{}),
|
|
120
|
-
...(cancelFreeze
|
|
121
|
-
?{cancelFreezeExpectedAt:next.cancelFreezeExpectedAt,
|
|
122
|
-
cancelRequestId:next.cancelRequestId}:{})}).catch(()=>null);
|
|
123
|
-
// A fresh replacement Session ID identifies this exact CAS. If its
|
|
124
|
-
// transport reply was lost, confirm the durable projection once, without
|
|
125
|
-
// replaying the write. Same-ID recovery has no such unique commit proof.
|
|
126
|
-
if(!saved&&replacementCommit){
|
|
127
|
-
const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
128
|
-
{op:'session-read'}).catch(()=>null);
|
|
129
|
-
if(observed?.status==='OK'&&matchesNativeProjection(record,observed.session))return;
|
|
130
|
-
}
|
|
131
|
-
// Native acknowledgment must match the whole immutable Owner pointer,
|
|
132
|
-
// not merely its sessionId and phase. updatedAt is CAS metadata, not
|
|
133
|
-
// part of this identity projection.
|
|
134
|
-
if(saved?.status!=="OK"||!matchesNativeProjection(record,saved.session))
|
|
135
|
-
throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
|
|
136
|
-
};
|
|
137
|
-
// BLOCKED recovery and replacement both require a Native CAS first.
|
|
138
|
-
// Do not publish a new Worker reservation when Native rejects the CAS.
|
|
139
|
-
// An unknown acknowledgement stays fail-closed; never replay a Start.
|
|
140
|
-
if(nativeFirst)await syncNative();
|
|
141
|
-
await chrome.storage.local.set({[RUN_KEY]:next});
|
|
142
|
-
if(!nativeFirst)await syncNative();
|
|
143
|
-
// The resource inventory is derived evidence; it never grants browser Owner.
|
|
144
|
-
if (["DONE","BLOCKED","CANCELLED"].includes(next.phase)
|
|
145
|
-
&& next.contextTerminalFence !== "PENDING"
|
|
146
|
-
&& next.contextTerminalFence !== "UNVERIFIED")
|
|
147
|
-
await resources.terminal(next).catch(()=>{});
|
|
148
|
-
|
|
149
|
-
try {
|
|
150
|
-
if (clockActive(next) && !next.handoffPending && deadlineAt > Date.now()) {
|
|
151
|
-
await chrome.alarms?.create?.(DEADLINE_ALARM_NAME, {when: deadlineAt});
|
|
152
|
-
} else {
|
|
153
|
-
await chrome.alarms?.clear?.(DEADLINE_ALARM_NAME);
|
|
154
|
-
}
|
|
155
|
-
} catch { /* The existing periodic alarm is a conservative backup. */ }
|
|
156
|
-
}
|
|
157
|
-
// Browser Owner remains the only send authority. Native Host mirrors a minimal
|
|
158
|
-
// session pointer so later Chats can find the current Web Chat without a task engine.
|
|
159
|
-
function sessionProjection(run) {
|
|
160
|
-
const page=typeof run.page==='string'?run.page:'';
|
|
161
|
-
const match=page.match(/\/c\/([0-9a-f-]{12,})$/i);
|
|
162
|
-
const activeChatId=match?.[1]||null;
|
|
163
|
-
return {sessionId:run.sessionId,projectId:run.projectId,
|
|
164
|
-
...(run.taskId?{taskId:run.taskId}:{}),phase:run.phase,generation:run.generation||0,activeChatId,
|
|
165
|
-
activeChatUrl:activeChatId?"https://chatgpt.com"+page:null,
|
|
166
|
-
updatedAt:Date.now()};
|
|
167
|
-
}
|
|
168
|
-
const SESSION_POINTER_KEYS=Object.freeze(['sessionId','projectId','taskId','phase',
|
|
169
|
-
'generation','activeChatId','activeChatUrl']);
|
|
170
|
-
const matchesNativeProjection=(projected,native)=>Boolean(native
|
|
171
|
-
&&SESSION_POINTER_KEYS.every(key=>projected[key]===native[key]));
|
|
172
|
-
// Read-only status diagnosis: reveal field NAMES only, never Owner identities.
|
|
173
|
-
const sessionProjectionDrift=(projected,native)=>SESSION_POINTER_KEYS.filter(
|
|
174
|
-
key=>projected[key]!==native?.[key]);
|
|
175
|
-
// Two distinct durable IDs may exist after an interrupted Adopt reservation.
|
|
176
|
-
// This narrow read-only shape proves NEITHER a previous send nor authority to
|
|
177
|
-
// replace it. Adopt admission separately verifies independent Task replacement
|
|
178
|
-
// or the exact same-Task pre-permit recovery contract before Native CAS.
|
|
179
|
-
const independentBlockedAdoptDrift=(run,native)=>Boolean(
|
|
180
|
-
run?.phase==='BLOCKED'&&run.reason==='ACTION_RESULT_TIMEOUT_UNVERIFIED'
|
|
181
|
-
&&run.action==='START'&&run.mode==='adopt'
|
|
182
|
-
&&run.contextLeaseRef&&!run.contextManaged
|
|
183
|
-
&&run.generation===0&&run.tabId===null&&run.page==='/'
|
|
184
|
-
&&!run.userKey&&!run.newUserKey&&!run.assistantKey
|
|
185
|
-
&&!run.attemptedNewTabId&&!run.lastStartActionTabId
|
|
186
|
-
&&typeof run.adoptPage==='string'&&run.adoptPage.startsWith('/c/')
|
|
187
|
-
&&Number.isInteger(run.adoptTabId)&&typeof run.adoptUserKey==='string'
|
|
188
|
-
&&native?.phase==='BLOCKED'&&native.generation===0
|
|
189
|
-
&&native.activeChatId===null&&native.activeChatUrl===null
|
|
190
|
-
&&native.projectId===run.projectId&&native.taskId===run.taskId
|
|
191
|
-
&&typeof native.sessionId==='string'&&native.sessionId!==run.sessionId
|
|
192
|
-
&&Number.isSafeInteger(native.updatedAt)&&native.updatedAt>0);
|
|
193
|
-
const sessionPage=(sender,name,id)=> Number.isInteger(sender.tab?.id)
|
|
194
|
-
&& typeof id==='string'&&/^[a-f0-9]{32}$/.test(id)
|
|
195
|
-
&& sender.url===chrome.runtime.getURL(name+'.html')+'?requestId='+id;
|
|
196
|
-
async function resourceChatGate(message,sender) {
|
|
197
|
-
const run=await readRun();
|
|
198
|
-
if(run?.phase!=='PENDING'
|
|
199
|
-
|| !['start','handoff'].includes(message.action))
|
|
200
|
-
return {status:'DENIED',code:'RESOURCE_OWNER_NOT_PENDING'};
|
|
201
|
-
const authorized=message.action==='start'
|
|
202
|
-
? run.action==='START' && run.machineActionTabId===sender.tab?.id
|
|
203
|
-
&& sessionPage(sender,'start',run.machineRequestId)
|
|
204
|
-
: run.action==='HANDOFF' && isAction(sender,
|
|
205
|
-
{tabId:run.tabId,token:run.token},run);
|
|
206
|
-
if(!authorized)return {status:'DENIED',code:'RESOURCE_ACTION_SOURCE_INVALID'};
|
|
207
|
-
if(message.stage==='preflight') {
|
|
208
|
-
const quota=await resources.admit(run,{kind:'chat'});
|
|
209
|
-
return quota.ok?{status:'OK',code:'RESOURCE_CHAT_PERMITTED'}
|
|
210
|
-
:{status:'DENIED',code:quota.code};
|
|
211
|
-
}
|
|
212
|
-
if(message.stage==='adopt' && run.mode==='adopt'
|
|
213
|
-
&&Number.isInteger(message.tabId)&&message.tabId===run.adoptTabId){
|
|
214
|
-
const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
|
|
215
|
-
if(!tab||pathOf(tab.url)!==run.adoptPage
|
|
216
|
-
||!await resources.adoptChat(tab,run))
|
|
217
|
-
return {status:'DENIED',code:'RESOURCE_ADOPTION_UNVERIFIED'};
|
|
218
|
-
return {status:'OK',code:'RESOURCE_CHAT_ADOPTED'};
|
|
219
|
-
}
|
|
220
|
-
if(message.stage!=='register' || !Number.isInteger(message.tabId))
|
|
221
|
-
return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
|
|
222
|
-
const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
|
|
223
|
-
if (!tab || tab.id===run.tabId || tab.id===sender.tab.id
|
|
224
|
-
|| !await resources.registerChat(tab,run))
|
|
225
|
-
return {status:'DENIED',code:'RESOURCE_CHAT_NOT_VERIFIED'};
|
|
226
|
-
const inventory=await resources.reconcile(run);
|
|
227
|
-
if(inventory.activeChatCount>resources.CHAT_LIMIT)
|
|
228
|
-
return {status:'DENIED',code:'RESOURCE_CHAT_LIMIT'};
|
|
229
|
-
return {status:'OK',code:'RESOURCE_CHAT_REGISTERED'};
|
|
230
|
-
}
|
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
// Chat Loop Worker — manual. Imported in order by background.js; no independent Browser Owner.
|
|
2
|
-
async function onManualPrepare(message, sender) {
|
|
3
|
-
const requested = message.action;
|
|
4
|
-
if (!["CONTINUE", "HANDOFF"].includes(requested)
|
|
5
|
-
|| !Number.isInteger(sender.tab?.id)) return {status: "DENIED", code: "INVALID_MANUAL_ACTION"};
|
|
6
|
-
const filename = requested === "HANDOFF" ? "handoff.html" : "continue.html";
|
|
7
|
-
let url;
|
|
8
|
-
try { url = new URL(sender.url); } catch {return {status: "DENIED", code: "INVALID_ACTION_URL"};}
|
|
9
|
-
const rawTabId = url.searchParams.get("tabId");
|
|
10
|
-
// Explicit operator-only migration of 0.3.52's unsent recovery reservation.
|
|
11
|
-
// The old Native Host could NEVER commit BLOCKED -> PENDING. Operator must
|
|
12
|
-
// verify that installed-version provenance before supplying this disk CAS.
|
|
13
|
-
// Modern unknown sends are never eligible, even with the query parameter.
|
|
14
|
-
// Explicit repair acknowledgement binds the operator to the exact disk
|
|
15
|
-
// blocker. It does not claim that the browser can verify business repair.
|
|
16
|
-
const contextRaw=url.searchParams.get("recoverContextNotSentAt");
|
|
17
|
-
const contextAt=contextRaw!==null?Number(contextRaw):null;
|
|
18
|
-
if(contextRaw!==null&&(requested!=="CONTINUE"||!rawTabId
|
|
19
|
-
||!Number.isSafeInteger(contextAt)||contextAt<=0))
|
|
20
|
-
return {status:"DENIED",code:"INVALID_CONTEXT_NOT_SENT_RECOVERY"};
|
|
21
|
-
const resumeRaw=url.searchParams.get("resumeBlockedAt");
|
|
22
|
-
const resumeAt=resumeRaw!==null?Number(resumeRaw):null;
|
|
23
|
-
if(resumeRaw!==null&&(requested!=="CONTINUE"||!rawTabId
|
|
24
|
-
||!Number.isSafeInteger(resumeAt)||resumeAt<=0
|
|
25
|
-
||url.searchParams.has("repairLegacyReservation")))
|
|
26
|
-
return {status:"DENIED",code:"INVALID_BLOCKED_REPAIR"};
|
|
27
|
-
const legacyRaw=url.searchParams.get("repairLegacyReservation");
|
|
28
|
-
const legacyAt=legacyRaw!==null?Number(legacyRaw):null;
|
|
29
|
-
if(legacyRaw!==null&&(requested!=="CONTINUE"||!rawTabId
|
|
30
|
-
||!Number.isSafeInteger(legacyAt)||legacyAt<=0
|
|
31
|
-
||!String(legacyAt).match(/^[1-9][0-9]{12}$/)))
|
|
32
|
-
return {status:"DENIED",code:"INVALID_LEGACY_REPAIR"};
|
|
33
|
-
if (url.origin !== new URL(chrome.runtime.getURL(filename)).origin
|
|
34
|
-
|| url.pathname !== "/" + filename || url.searchParams.has("token")
|
|
35
|
-
|| Array.from(url.searchParams.keys()).some(key => key !== "tabId"&&key!=="repairLegacyReservation"&&key!=="resumeBlockedAt"
|
|
36
|
-
&&key!=="recoverContextNotSentAt")
|
|
37
|
-
|| url.searchParams.size!==new Set(url.searchParams.keys()).size
|
|
38
|
-
|| (rawTabId !== null && (!/^[1-9][0-9]*$/.test(rawTabId)
|
|
39
|
-
|| message.tabId !== Number(rawTabId))))
|
|
40
|
-
return {status: "DENIED", code: "INVALID_ACTION_URL"};
|
|
41
|
-
const previous = await repairUncommittedBlockedRecovery();
|
|
42
|
-
// Existing Owner may recover a *verified resolved* model-level tool blocker
|
|
43
|
-
// via the SAME built-in Continue Action. Never grant a new Owner or create
|
|
44
|
-
// a new conversation. This cannot recover unknown sends/page errors.
|
|
45
|
-
const legacyUnsent=Boolean(legacyAt&&previous?.sessionId
|
|
46
|
-
&&previous.phase==="BLOCKED"&&previous.action==="CONTINUE"
|
|
47
|
-
&&previous.reason==="ACTION_RESULT_TIMEOUT_UNVERIFIED"
|
|
48
|
-
&&previous.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
|
|
49
|
-
&&previous.recoveryAttempts===1&&!previous.recoveryProtocol
|
|
50
|
-
&&previous.newUserKey===previous.userKey
|
|
51
|
-
&&previous.recoverySourceAssistantKey===previous.assistantKey);
|
|
52
|
-
const contextNotSent=Boolean(contextAt&&requested==="CONTINUE"
|
|
53
|
-
&&previous?.sessionId&&previous.taskId&&previous.phase==="BLOCKED"
|
|
54
|
-
&&previous.action==="HANDOFF"
|
|
55
|
-
&&previous.reason==="CONTEXT_HANDOFF_NOT_SENT"
|
|
56
|
-
&&previous.contextHandoff?.sendOutcome==="NOT_SENT"
|
|
57
|
-
&&!previous.contextHandoff.sendBeginAt
|
|
58
|
-
&&Number.isSafeInteger(previous.contextHandoff.terminalActionResultAt)
|
|
59
|
-
&&previous.contextHandoff.attemptId===previous.token
|
|
60
|
-
&&!previous.contextRecoveryAttempted
|
|
61
|
-
&&previous.contextManaged
|
|
62
|
-
&&previous.contextHandoff.targetGeneration===(previous.generation||0)+1);
|
|
63
|
-
const recoveryCandidate=requested==="CONTINUE"
|
|
64
|
-
&&previous?.sessionId&&previous.phase==="BLOCKED"
|
|
65
|
-
&&Number.isInteger(previous.tabId)
|
|
66
|
-
&&(contextNotSent||legacyUnsent||previous.reason==="BLOCKED"
|
|
67
|
-
&&((previous.recoveryAttempts||0)===0||resumeAt
|
|
68
|
-
&&previous.recoverySourceAssistantKey!==previous.assistantKey));
|
|
69
|
-
if (previous && (previous.sessionId&&previous.phase!=="DONE"&&!recoveryCandidate
|
|
70
|
-
|| !["DONE", "BLOCKED"].includes(previous.phase)))
|
|
71
|
-
return {status: "DENIED", code: "LOOP_ALREADY_ACTIVE"};
|
|
72
|
-
const candidates = await chrome.tabs.query({url: "https://chatgpt.com/*"});
|
|
73
|
-
const all = candidates.filter(tab => Number.isInteger(tab.id) && pathOf(tab.url));
|
|
74
|
-
let tab;
|
|
75
|
-
if (Number.isInteger(message.tabId)) tab = all.find(item => item.id === message.tabId);
|
|
76
|
-
else if (all.length === 1) tab = all[0];
|
|
77
|
-
else return {status: "DENIED", code: all.length ? "AMBIGUOUS_CHATGPT_TABS" : "NO_CHATGPT_TAB"};
|
|
78
|
-
if (!tab) return {status: "DENIED", code: "TARGET_CHAT_NOT_FOUND"};
|
|
79
|
-
const query = () => chrome.tabs.sendMessage(tab.id, {type: "CHAT_LOOP_TURN_VERIFY_V1"});
|
|
80
|
-
let first;
|
|
81
|
-
try {first = await query();}
|
|
82
|
-
catch {return {status: "DENIED", code: "OBSERVER_NOT_READY"};}
|
|
83
|
-
if (first?.contract !== "chat-loop.turn-observer.v1" || first.status !== "READY"
|
|
84
|
-
|| first.page !== pathOf(tab.url)) return {status: "DENIED", code: "TURN_NOT_FINISHED"};
|
|
85
|
-
// A manually opened page is still forbidden from interrupting late updates.
|
|
86
|
-
await new Promise(resolve => setTimeout(resolve, 2300));
|
|
87
|
-
const second = await query().catch(() => null);
|
|
88
|
-
if (second?.status !== "READY" || second.page !== first.page
|
|
89
|
-
|| second.userKey !== first.userKey || second.assistantKey !== first.assistantKey
|
|
90
|
-
|| second.replyText !== first.replyText) return {status: "DENIED", code: "TURN_NOT_STABLE"};
|
|
91
|
-
const modelStatus = workerApi.parseStatus(first.replyText);
|
|
92
|
-
const ownedRecovery=Boolean(recoveryCandidate
|
|
93
|
-
&&(modelStatus==="BLOCKED"
|
|
94
|
-
||contextNotSent&&["HANDOFF","CONTINUE"].includes(modelStatus))
|
|
95
|
-
&&Number.isInteger(message.tabId) && message.tabId===previous.tabId
|
|
96
|
-
&&previous.tabId===tab.id&&previous.page===first.page
|
|
97
|
-
&&previous.userKey===first.userKey
|
|
98
|
-
&&previous.assistantKey===first.assistantKey
|
|
99
|
-
// Specific repaired tool capability, not generic BLOCKED, human
|
|
100
|
-
// approval failure, unknown browser send or context exhaustion.
|
|
101
|
-
&&(contextNotSent||resumeAt||/\b(?:adopt|Start)\b/i.test(first.replyText))
|
|
102
|
-
&&!first.pendingConfirmation
|
|
103
|
-
&&!second.pendingConfirmation);
|
|
104
|
-
if (recoveryCandidate && !ownedRecovery)
|
|
105
|
-
return {status:"DENIED",code:"BLOCKED_RECOVERY_UNVERIFIED"};
|
|
106
|
-
if (requested === "CONTINUE" && modelStatus !== "CONTINUE"&&!ownedRecovery
|
|
107
|
-
|| requested === "HANDOFF" && !["HANDOFF", "CONTINUE"].includes(modelStatus))
|
|
108
|
-
return {status: "DENIED", code: "ACTION_MARKER_MISMATCH"};
|
|
109
|
-
if (previous && previous.tabId === tab.id && previous.page === first.page
|
|
110
|
-
&& (previous.userKey === first.userKey || previous.assistantKey === first.assistantKey)
|
|
111
|
-
&&!ownedRecovery)
|
|
112
|
-
return {status: "DENIED", code: "ALREADY_HANDLED"};
|
|
113
|
-
const summary = modelStatus === "HANDOFF"
|
|
114
|
-
? first.replyText.replace(/\r?\n\[CHAT_LOOP_STATUS:HANDOFF\]\s*$/, "").trim() : null;
|
|
115
|
-
if (summary && (summary.length < 120 || summary.length > 16000
|
|
116
|
-
|| !/目标/.test(summary) || !/已完成|进度/.test(summary)
|
|
117
|
-
|| !/下一步|待办/.test(summary)))
|
|
118
|
-
return {status: "DENIED", code: "HANDOFF_PACKET_MISSING"};
|
|
119
|
-
let recoveryExpectedNativeAt=null;
|
|
120
|
-
if(ownedRecovery){
|
|
121
|
-
const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
122
|
-
{op:"session-read"}).catch(()=>null);
|
|
123
|
-
if(disk?.status!=="OK"
|
|
124
|
-
||!matchesNativeProjection(sessionProjection(previous),disk.session)
|
|
125
|
-
||resumeAt&&disk.session.updatedAt!==resumeAt
|
|
126
|
-
||contextAt&&disk.session.updatedAt!==contextAt
|
|
127
|
-
||legacyAt&&(!legacyUnsent||disk.session.updatedAt!==legacyAt))
|
|
128
|
-
return {status:"DENIED",code:"BLOCKED_OWNER_PERSISTENCE_UNVERIFIED"};
|
|
129
|
-
recoveryExpectedNativeAt=disk.session.updatedAt;
|
|
130
|
-
}
|
|
131
|
-
const token = crypto.randomUUID();
|
|
132
|
-
await saveRun({...(ownedRecovery?previous:{}),
|
|
133
|
-
tabId: tab.id, page: first.page, userKey: first.userKey,
|
|
134
|
-
assistantKey: first.assistantKey, phase: "RESERVED", token,
|
|
135
|
-
action: requested, startedAt:ownedRecovery?previous.startedAt:Date.now(),
|
|
136
|
-
manualActionTabId: sender.tab.id,
|
|
137
|
-
...(ownedRecovery?{recoveryMode:contextNotSent?"HANDOFF_NOT_SENT":"TOOL_PREFLIGHT_REPAIRED",
|
|
138
|
-
recoveryAttempts:(previous.recoveryAttempts||0)+1,recoveryProtocol:1,
|
|
139
|
-
recoveryExpectedNativeAt,
|
|
140
|
-
...(contextNotSent?{contextSourceMarker:"[CHAT_LOOP_STATUS:"+modelStatus+"]",
|
|
141
|
-
contextRecoveryCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
|
|
142
|
-
x=>x.toString(16).padStart(2,"0")).join(""),
|
|
143
|
-
contextRecoveryAttempted:true}:{}),
|
|
144
|
-
recoverySourceAssistantKey:first.assistantKey}:{}),
|
|
145
|
-
handoffMode: requested === "HANDOFF"
|
|
146
|
-
? (modelStatus === "HANDOFF" ? "EXPLICIT" : "TIMED") : null,
|
|
147
|
-
...(summary ? {handoffText: summary} : {})});
|
|
148
|
-
return {status: "PREPARED", token, tabId: tab.id};
|
|
149
|
-
}
|
|
150
|
-
const isAction = (sender, message, run) => {
|
|
151
|
-
if (!Number.isInteger(sender.tab?.id) || typeof sender.url !== "string") return false;
|
|
152
|
-
try {
|
|
153
|
-
const file = run?.action === "HANDOFF" ? "handoff.html" : "continue.html";
|
|
154
|
-
const u = new URL(sender.url);
|
|
155
|
-
const manual = Number.isInteger(run?.manualActionTabId)
|
|
156
|
-
&& run.manualActionTabId === sender.tab.id && !u.searchParams.has("token")
|
|
157
|
-
&& (!u.searchParams.has("tabId") || u.searchParams.get("tabId") === String(message.tabId));
|
|
158
|
-
return u.origin === new URL(chrome.runtime.getURL(file)).origin
|
|
159
|
-
&& u.pathname === "/" + file
|
|
160
|
-
&& (manual || u.searchParams.get("token") === message.token
|
|
161
|
-
&& u.searchParams.get("tabId") === String(message.tabId));
|
|
162
|
-
} catch { return false; }
|
|
163
|
-
};
|