@tomflow/chatloop-tools 0.9.64 → 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/node_modules/@tomflow/chatloop-context/README.md +296 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
- package/node_modules/@tomflow/chatloop-context/package.json +38 -0
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
- package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
- 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/extension/worker/turn-failure.js +197 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
- 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 +228 -0
- package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
- package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
- package/node_modules/ps-list/index.d.ts +76 -0
- package/node_modules/ps-list/index.js +366 -0
- package/node_modules/ps-list/license +9 -0
- package/node_modules/ps-list/package.json +44 -0
- package/node_modules/ps-list/readme.md +56 -0
- 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
- package/package.json +12 -4
|
@@ -0,0 +1,287 @@
|
|
|
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
|
+
// V2 differs from V1: EVERY continuing Task Turn registers a future
|
|
10
|
+
// private intent BEFORE its assistant reply ends. A naked CONTINUE marker
|
|
11
|
+
// has no signed nextPrompt and MUST NOT be converted to an implicit send.
|
|
12
|
+
const scopedTurnToolNote = token =>
|
|
13
|
+
"\n\n【Chat Loop Task-first 本轮续接协议】" +
|
|
14
|
+
"本 Task 的 turnToken 为 " + token + "(不要在助手正文复述)。" +
|
|
15
|
+
"如果仍有已授权工作,必须在本轮助手回复尚未结束时调用 " +
|
|
16
|
+
"chat_loop_extension__continue,参数 taskFirst:true、turnToken " +
|
|
17
|
+
"及下一步 nextPrompt(无特殊内容时使用“继续当前已授权任务,核实进度、权限和副作用;UNKNOWN 只查原回执,不重发。”)。" +
|
|
18
|
+
"工具只登记 QUEUED,不会立即发送。随后整轮回答最后独立一行" +
|
|
19
|
+
"输出 [CHAT_LOOP_STATUS:CONTINUE]。" +
|
|
20
|
+
"如需提前交接,先核实可交接 Checkpoint,再在本轮调用 " +
|
|
21
|
+
"chat_loop_extension__handoff(taskFirst:true,turnToken)," +
|
|
22
|
+
"末行输出 [CHAT_LOOP_STATUS:HANDOFF]。" +
|
|
23
|
+
"任务完成或必须停止时不登记新发送,分别输出 DONE/BLOCKED。" +
|
|
24
|
+
"不允许只输出 CONTINUE/HANDOFF 而不登记对应的本 Task 意图。";
|
|
25
|
+
let queue = Promise.resolve();
|
|
26
|
+
// Business callbacks expose typed, bounded error codes only; raw messages can
|
|
27
|
+
// contain native paths, browser state or extension internals.
|
|
28
|
+
const safeWorkerErrorCode=(failure,fallback)=>{
|
|
29
|
+
const code=failure?.code||failure?.message;
|
|
30
|
+
return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
|
|
31
|
+
?code:fallback;
|
|
32
|
+
};
|
|
33
|
+
const serial = fn => {
|
|
34
|
+
const work = queue.then(fn);
|
|
35
|
+
queue = work.catch(() => {});
|
|
36
|
+
return work;
|
|
37
|
+
};
|
|
38
|
+
// Admission and recovery run in this same Worker, never another browser executor.
|
|
39
|
+
const resources = workerApi.resources;
|
|
40
|
+
const policy=workerApi.policy;
|
|
41
|
+
const {pathOf,chatIdOf}=policy;
|
|
42
|
+
// The V2 store is Task-addressed, but it is not a replacement Browser Owner.
|
|
43
|
+
// Until scoped Router/Native/Context activation is verified, V1 must not write
|
|
44
|
+
// over an active V2 Task. Never fall back to the latest V2 Task.
|
|
45
|
+
const scopedTaskRuns=globalThis.ChatLoopTaskRunStoreV2?.create(chrome.storage.local);
|
|
46
|
+
const scopedTaskScheduler=scopedTaskRuns
|
|
47
|
+
?globalThis.ChatLoopTaskSchedulerV2?.create(scopedTaskRuns):null;
|
|
48
|
+
const scopedTaskOwnerResolver=scopedTaskRuns
|
|
49
|
+
?globalThis.ChatLoopTaskOwnerResolverV2?.create({
|
|
50
|
+
store:scopedTaskRuns,getTab:id=>chrome.tabs.get(id),
|
|
51
|
+
readNative:scope=>chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
52
|
+
op:'session-snapshot-v2',...scope}),
|
|
53
|
+
checkWriter:scope=>chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
54
|
+
op:'context-writer-check-v2',...scope}),
|
|
55
|
+
pathOf,chatIdOf}):null;
|
|
56
|
+
// These are dormant V2 route/dispatch primitives until every sender
|
|
57
|
+
// boundary uses exact TaskKey + Session generation; never auto-dispatch here.
|
|
58
|
+
async function hasActiveScopedTask(){
|
|
59
|
+
if(!scopedTaskRuns)return false;
|
|
60
|
+
const state=await scopedTaskRuns.read();
|
|
61
|
+
return Object.values(state.items).some(({run})=>
|
|
62
|
+
!['DONE','CANCELLED'].includes(run.phase));
|
|
63
|
+
}
|
|
64
|
+
async function assertLegacyWorkerWritable({native=false}={}){
|
|
65
|
+
if(await hasActiveScopedTask())throw Error('TASK_SCOPED_ROUTER_NOT_READY');
|
|
66
|
+
if(!native)return;
|
|
67
|
+
// The Worker snapshot may be stale after MV3 suspension or after another
|
|
68
|
+
// Profile committed a Native Owner. The existing V1 Native read refuses
|
|
69
|
+
// every live V2 Ledger, including ones not present in this Worker store.
|
|
70
|
+
const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
|
|
71
|
+
op:'session-read'}).catch(()=>null);
|
|
72
|
+
if(observed?.status!=='OK')
|
|
73
|
+
throw Error(observed?.code==='OWNER_LEDGER_ACTIVE_USE_SCOPED_QUERY'
|
|
74
|
+
?'TASK_SCOPED_ROUTER_NOT_READY':'LEGACY_NATIVE_OWNER_UNVERIFIED');
|
|
75
|
+
// An in-flight V2 Worker update after Native read must also be rejected.
|
|
76
|
+
if(await hasActiveScopedTask())throw Error('TASK_SCOPED_ROUTER_NOT_READY');
|
|
77
|
+
}
|
|
78
|
+
async function createBoundedAction(options) {
|
|
79
|
+
// Validate BEFORE creating a tab. No caller may open an arbitrary URL
|
|
80
|
+
// through the privileged Worker Action quota.
|
|
81
|
+
if(typeof options?.url!=='string'
|
|
82
|
+
||!options.url.startsWith(chrome.runtime.getURL('')))
|
|
83
|
+
throw Error('ACTION_URL_UNVERIFIED');
|
|
84
|
+
// One Worker resource critical section encloses quota admission,
|
|
85
|
+
// actual tab creation and exact URL registration. Another Task cannot
|
|
86
|
+
// pass admission against a stale count while this side effect is in flight.
|
|
87
|
+
const receipt=await resources.withRegisteredAction(await readRun(),{
|
|
88
|
+
url:options.url,create:async()=>{
|
|
89
|
+
await assertLegacyWorkerWritable({native:true});
|
|
90
|
+
return chrome.tabs.create(options);
|
|
91
|
+
}});
|
|
92
|
+
const tab=receipt.tab;
|
|
93
|
+
if(!receipt.ok){
|
|
94
|
+
if(!Number.isSafeInteger(tab?.id)||tab.id<=0)
|
|
95
|
+
throw Error(receipt.code||'ACTION_CREATED_ID_UNVERIFIED');
|
|
96
|
+
// Failed registration must not strand another Action tab. Remove only
|
|
97
|
+
// this tab if its fresh, read-back URL still proves Extension identity;
|
|
98
|
+
// never close a changed, active or pinned tab and never retry a send.
|
|
99
|
+
const current=await chrome.tabs.get(tab.id).catch(()=>null);
|
|
100
|
+
if(current&&!current.active&&!current.pinned
|
|
101
|
+
&&(current.url===options.url
|
|
102
|
+
||current.url==='about:blank'&¤t.pendingUrl===options.url))
|
|
103
|
+
await chrome.tabs.remove(tab.id).catch(()=>{});
|
|
104
|
+
throw Error('ACTION_RESOURCE_UNVERIFIED');
|
|
105
|
+
}
|
|
106
|
+
return tab;
|
|
107
|
+
}
|
|
108
|
+
// Identity and receipt policy are shared deterministic helpers. This Worker
|
|
109
|
+
// remains the only Chrome action/state owner.
|
|
110
|
+
const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
|
|
111
|
+
// Keep only a fixed-size fingerprint after Start's one-shot prompt is erased.
|
|
112
|
+
// A missing historical fingerprint means NOT_COMPARABLE, not "zero matches".
|
|
113
|
+
async function startPromptFingerprint(prompt) {
|
|
114
|
+
if(typeof prompt!=='string'||!globalThis.crypto?.subtle||
|
|
115
|
+
typeof TextEncoder!=='function')return null;
|
|
116
|
+
const normalized=prompt.replace(/\s+/g,'');
|
|
117
|
+
if(!normalized)return null;
|
|
118
|
+
const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(normalized));
|
|
119
|
+
return Array.from(new Uint8Array(digest),v=>v.toString(16).padStart(2,'0')).join('');
|
|
120
|
+
}
|
|
121
|
+
// Keep the windowMsOf alias as the fingerprint test's pure-read boundary.
|
|
122
|
+
const windowMsOf=policy.windowMsOf;
|
|
123
|
+
const {deadlineOf,clockActive,terminalFenceVerified,MODEL_RECEIPT_TTL_MS,
|
|
124
|
+
receiptHistory,updateModelReceipt,settleModelIntent}=policy;
|
|
125
|
+
async function saveRun(run) {
|
|
126
|
+
// Last Worker write fence: an independently committed V2 Native Owner
|
|
127
|
+
// must not be overwritten even if the caller skipped an earlier route.
|
|
128
|
+
await assertLegacyWorkerWritable({native:true});
|
|
129
|
+
if (run && ["DONE","BLOCKED"].includes(run.phase))
|
|
130
|
+
run = settleModelIntent(run, run.phase==="DONE"?"CANCELLED_DONE":"BLOCKED", run.reason);
|
|
131
|
+
const now = Date.now(), deadlineAt = deadlineOf(run);
|
|
132
|
+
// Persist the intent even when a delayed alarm arrives after an Action
|
|
133
|
+
// receipt. This never revokes a Continue already reserved before deadline.
|
|
134
|
+
const sending = ["STARTING","RESERVED","PENDING"].includes(run.phase);
|
|
135
|
+
const marker = sending && typeof run.token==="string" ? run.token : null;
|
|
136
|
+
const next = {...run, ...(deadlineAt ? {deadlineAt} : {}),
|
|
137
|
+
...(marker ? {actionPendingAt: run.resourceToken===marker
|
|
138
|
+
&& Number.isSafeInteger(run.actionPendingAt) ? run.actionPendingAt : now,
|
|
139
|
+
resourceToken:marker} : {})};
|
|
140
|
+
if (clockActive(next) && deadlineAt !== null && now >= deadlineAt
|
|
141
|
+
&& !next.handoffPending) {
|
|
142
|
+
next.handoffPending = true;
|
|
143
|
+
next.handoffPendingAt = now;
|
|
144
|
+
}
|
|
145
|
+
const stored=await readRun();
|
|
146
|
+
const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
|
|
147
|
+
&&["TOOL_PREFLIGHT_REPAIRED","HANDOFF_NOT_SENT","ADOPT_IDLE_BASELINE"].includes(next.recoveryMode)
|
|
148
|
+
&&next.recoveryAttempts>=1&&stored?.phase==="BLOCKED";
|
|
149
|
+
if(recoveryCommit&&(!Number.isSafeInteger(next.recoveryExpectedNativeAt)
|
|
150
|
+
||next.recoveryExpectedNativeAt<=0))
|
|
151
|
+
throw Error('SESSION_RECOVERY_CAS_MISSING');
|
|
152
|
+
// Native must commit first for the exact terminal CAS transitions.
|
|
153
|
+
const replacementCommit=Boolean(next.replacedBlockedSessionId
|
|
154
|
+
&&next.phase==='STARTING'&&stored?.sessionId!==next.sessionId);
|
|
155
|
+
// Cancel must commit Native terminal CAS before exposing Worker CANCELLED.
|
|
156
|
+
// A missing Native reply leaves Worker BLOCKED, never falsely IDLE.
|
|
157
|
+
const cancelFreeze=next.reason==='SESSION_CANCEL_PENDING'
|
|
158
|
+
&&next.phase==='BLOCKED'&&stored?.phase==='WAITING_REPLY'
|
|
159
|
+
&&Number.isSafeInteger(next.cancelFreezeExpectedAt);
|
|
160
|
+
const nativeFirst=recoveryCommit||replacementCommit
|
|
161
|
+
||next.phase==='CANCELLED'||cancelFreeze;
|
|
162
|
+
const syncNative=async()=>{
|
|
163
|
+
if(!next.sessionId)return;
|
|
164
|
+
const record=sessionProjection(next);
|
|
165
|
+
const saved=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
166
|
+
{op:"session-sync",session:record,
|
|
167
|
+
...(next.replacedBlockedSessionId&&!recoveryCommit&&next.phase==='STARTING'
|
|
168
|
+
?{replaceBlockedSessionId:next.replacedBlockedSessionId,
|
|
169
|
+
...(Number.isSafeInteger(next.sameTaskPrePermitUpdatedAt)
|
|
170
|
+
?{sameTaskPrePermitUpdatedAt:next.sameTaskPrePermitUpdatedAt}:{})}:{}),
|
|
171
|
+
...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
|
|
172
|
+
resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{}),
|
|
173
|
+
...(next.phase==='CANCELLED'
|
|
174
|
+
?{cancelBlockedUpdatedAt:next.cancelBlockedUpdatedAt,
|
|
175
|
+
cancelRequestId:next.cancelRequestId}:{}),
|
|
176
|
+
...(cancelFreeze
|
|
177
|
+
?{cancelFreezeExpectedAt:next.cancelFreezeExpectedAt,
|
|
178
|
+
cancelRequestId:next.cancelRequestId}:{})}).catch(()=>null);
|
|
179
|
+
// A fresh replacement Session ID identifies this exact CAS. If its
|
|
180
|
+
// transport reply was lost, confirm the durable projection once, without
|
|
181
|
+
// replaying the write. Same-ID recovery has no such unique commit proof.
|
|
182
|
+
if(!saved&&replacementCommit){
|
|
183
|
+
const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
184
|
+
{op:'session-read'}).catch(()=>null);
|
|
185
|
+
if(observed?.status==='OK'&&matchesNativeProjection(record,observed.session))return;
|
|
186
|
+
}
|
|
187
|
+
// Native acknowledgment must match the whole immutable Owner pointer,
|
|
188
|
+
// not merely its sessionId and phase. updatedAt is CAS metadata, not
|
|
189
|
+
// part of this identity projection.
|
|
190
|
+
if(saved?.status!=="OK"||!matchesNativeProjection(record,saved.session))
|
|
191
|
+
throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
|
|
192
|
+
};
|
|
193
|
+
// BLOCKED recovery and replacement both require a Native CAS first.
|
|
194
|
+
// Do not publish a new Worker reservation when Native rejects the CAS.
|
|
195
|
+
// An unknown acknowledgement stays fail-closed; never replay a Start.
|
|
196
|
+
if(nativeFirst)await syncNative();
|
|
197
|
+
await chrome.storage.local.set({[RUN_KEY]:next});
|
|
198
|
+
if(!nativeFirst)await syncNative();
|
|
199
|
+
// The resource inventory is derived evidence; it never grants browser Owner.
|
|
200
|
+
if (["DONE","BLOCKED","CANCELLED"].includes(next.phase)
|
|
201
|
+
&& next.contextTerminalFence !== "PENDING"
|
|
202
|
+
&& next.contextTerminalFence !== "UNVERIFIED")
|
|
203
|
+
await resources.terminal(next).catch(()=>{});
|
|
204
|
+
|
|
205
|
+
try {
|
|
206
|
+
if (clockActive(next) && !next.handoffPending && deadlineAt > Date.now()) {
|
|
207
|
+
await chrome.alarms?.create?.(DEADLINE_ALARM_NAME, {when: deadlineAt});
|
|
208
|
+
} else {
|
|
209
|
+
await chrome.alarms?.clear?.(DEADLINE_ALARM_NAME);
|
|
210
|
+
}
|
|
211
|
+
} catch { /* The existing periodic alarm is a conservative backup. */ }
|
|
212
|
+
}
|
|
213
|
+
// Browser Owner remains the only send authority. Native Host mirrors a minimal
|
|
214
|
+
// session pointer so later Chats can find the current Web Chat without a task engine.
|
|
215
|
+
function sessionProjection(run) {
|
|
216
|
+
const page=typeof run.page==='string'?run.page:'';
|
|
217
|
+
const match=page.match(/\/c\/([0-9a-f-]{12,})$/i);
|
|
218
|
+
const activeChatId=match?.[1]||null;
|
|
219
|
+
return {sessionId:run.sessionId,projectId:run.projectId,
|
|
220
|
+
...(run.taskId?{taskId:run.taskId}:{}),phase:run.phase,generation:run.generation||0,activeChatId,
|
|
221
|
+
activeChatUrl:activeChatId?"https://chatgpt.com"+page:null,
|
|
222
|
+
updatedAt:Date.now()};
|
|
223
|
+
}
|
|
224
|
+
const SESSION_POINTER_KEYS=Object.freeze(['sessionId','projectId','taskId','phase',
|
|
225
|
+
'generation','activeChatId','activeChatUrl']);
|
|
226
|
+
const matchesNativeProjection=(projected,native)=>Boolean(native
|
|
227
|
+
&&SESSION_POINTER_KEYS.every(key=>projected[key]===native[key]));
|
|
228
|
+
// Read-only status diagnosis: reveal field NAMES only, never Owner identities.
|
|
229
|
+
const sessionProjectionDrift=(projected,native)=>SESSION_POINTER_KEYS.filter(
|
|
230
|
+
key=>projected[key]!==native?.[key]);
|
|
231
|
+
// Two distinct durable IDs may exist after an interrupted Adopt reservation.
|
|
232
|
+
// This narrow read-only shape proves NEITHER a previous send nor authority to
|
|
233
|
+
// replace it. Adopt admission separately verifies independent Task replacement
|
|
234
|
+
// or the exact same-Task pre-permit recovery contract before Native CAS.
|
|
235
|
+
const independentBlockedAdoptDrift=(run,native)=>Boolean(
|
|
236
|
+
run?.phase==='BLOCKED'&&run.reason==='ACTION_RESULT_TIMEOUT_UNVERIFIED'
|
|
237
|
+
&&run.action==='START'&&run.mode==='adopt'
|
|
238
|
+
&&run.contextLeaseRef&&!run.contextManaged
|
|
239
|
+
&&run.generation===0&&run.tabId===null&&run.page==='/'
|
|
240
|
+
&&!run.userKey&&!run.newUserKey&&!run.assistantKey
|
|
241
|
+
&&!run.attemptedNewTabId&&!run.lastStartActionTabId
|
|
242
|
+
&&typeof run.adoptPage==='string'&&run.adoptPage.startsWith('/c/')
|
|
243
|
+
&&Number.isInteger(run.adoptTabId)&&typeof run.adoptUserKey==='string'
|
|
244
|
+
&&native?.phase==='BLOCKED'&&native.generation===0
|
|
245
|
+
&&native.activeChatId===null&&native.activeChatUrl===null
|
|
246
|
+
&&native.projectId===run.projectId&&native.taskId===run.taskId
|
|
247
|
+
&&typeof native.sessionId==='string'&&native.sessionId!==run.sessionId
|
|
248
|
+
&&Number.isSafeInteger(native.updatedAt)&&native.updatedAt>0);
|
|
249
|
+
const sessionPage=(sender,name,id)=> Number.isInteger(sender.tab?.id)
|
|
250
|
+
&& typeof id==='string'&&/^[a-f0-9]{32}$/.test(id)
|
|
251
|
+
&& sender.url===chrome.runtime.getURL(name+'.html')+'?requestId='+id;
|
|
252
|
+
async function resourceChatGate(message,sender) {
|
|
253
|
+
const run=await readRun();
|
|
254
|
+
if(run?.phase!=='PENDING'
|
|
255
|
+
|| !['start','handoff'].includes(message.action))
|
|
256
|
+
return {status:'DENIED',code:'RESOURCE_OWNER_NOT_PENDING'};
|
|
257
|
+
const authorized=message.action==='start'
|
|
258
|
+
? run.action==='START' && run.machineActionTabId===sender.tab?.id
|
|
259
|
+
&& sessionPage(sender,'start',run.machineRequestId)
|
|
260
|
+
: run.action==='HANDOFF' && isAction(sender,
|
|
261
|
+
{tabId:run.tabId,token:run.token},run);
|
|
262
|
+
if(!authorized)return {status:'DENIED',code:'RESOURCE_ACTION_SOURCE_INVALID'};
|
|
263
|
+
if(message.stage==='preflight') {
|
|
264
|
+
const quota=await resources.reserveChat(run,sender.tab.id);
|
|
265
|
+
return quota.ok?{status:'OK',code:'RESOURCE_CHAT_RESERVED'}
|
|
266
|
+
:{status:'DENIED',code:quota.code};
|
|
267
|
+
}
|
|
268
|
+
if(message.stage==='adopt' && run.mode==='adopt'
|
|
269
|
+
&&Number.isInteger(message.tabId)&&message.tabId===run.adoptTabId){
|
|
270
|
+
const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
|
|
271
|
+
if(!tab||pathOf(tab.url)!==run.adoptPage
|
|
272
|
+
||!await resources.adoptChat(tab,run))
|
|
273
|
+
return {status:'DENIED',code:'RESOURCE_ADOPTION_UNVERIFIED'};
|
|
274
|
+
return {status:'OK',code:'RESOURCE_CHAT_ADOPTED'};
|
|
275
|
+
}
|
|
276
|
+
if(message.stage!=='register' || !Number.isInteger(message.tabId))
|
|
277
|
+
return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
|
|
278
|
+
const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
|
|
279
|
+
if (!tab || tab.id===run.tabId || tab.id===sender.tab.id
|
|
280
|
+
|| tab.openerTabId!==sender.tab.id
|
|
281
|
+
|| !await resources.registerReservedChat(tab,run))
|
|
282
|
+
return {status:'DENIED',code:'RESOURCE_CHAT_NOT_VERIFIED'};
|
|
283
|
+
const inventory=await resources.reconcile(run);
|
|
284
|
+
if(inventory.activeChatCount>resources.CHAT_LIMIT)
|
|
285
|
+
return {status:'DENIED',code:'RESOURCE_CHAT_LIMIT'};
|
|
286
|
+
return {status:'OK',code:'RESOURCE_CHAT_REGISTERED'};
|
|
287
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
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
|
+
};
|