@tomflow/chatloop-tools 0.9.15 → 0.9.17

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.
Files changed (148) hide show
  1. package/README.md +2 -1
  2. package/index.mjs +12 -1
  3. package/lib/gateway.mjs +15 -3
  4. package/lib/mcp-tool-router.mjs +50 -3
  5. package/lib/trace-observation.mjs +19 -0
  6. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  7. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  13. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  14. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  15. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  16. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  17. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  18. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  19. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  20. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  45. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  46. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  47. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  48. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  49. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  50. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  51. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  52. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  53. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  114. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  118. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  119. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  120. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  121. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  122. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  123. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  124. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  125. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  126. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  127. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  128. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  129. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  130. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  131. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  132. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  133. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  134. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  135. package/node_modules/ps-list/index.d.ts +76 -0
  136. package/node_modules/ps-list/index.js +366 -0
  137. package/node_modules/ps-list/license +9 -0
  138. package/node_modules/ps-list/package.json +44 -0
  139. package/node_modules/ps-list/readme.md +56 -0
  140. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  141. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  142. package/package.json +23 -8
  143. package/providers/form.mjs +286 -0
  144. package/providers.generated.mjs +3 -2
  145. package/scripts/build-form-app.mjs +27 -0
  146. package/ui/form/review-app.js +128 -0
  147. package/ui/form/review.html +859 -0
  148. package/ui/form/review.template.html +45 -0
@@ -0,0 +1,185 @@
1
+ // Chat Loop Worker — adopt-recovery. Imported in order by background.js; no independent Browser Owner.
2
+ // An adopted, already-approved original Chat has an idle historical Pn answer.
3
+ // This one-shot kickoff is the missing bridge into the FIRST controlled execution
4
+ // Turn. Only the formal Continue Action may request it, with exact Native CAS.
5
+ // There is no direct Worker send, second Owner, or replay of prior approval.
6
+ async function onAdoptKickoffPrepare(message,sender){
7
+ const run=await readRun();
8
+ if(run?.phase!=='WAITING_REPLY'||run.reason!=='ADOPTED_IDLE_BASELINE'
9
+ ||run.action!=='START'||!run.contextManaged||!run.taskId
10
+ ||!run.sessionId||run.generation!==0||run.kickoffAttempted
11
+ ||!Number.isInteger(run.tabId)||run.tabId!==message.tabId
12
+ ||!run.page||run.newUserKey!==run.userKey
13
+ ||!/^assistant:[^\s]{8,}$/.test(run.assistantKey||'')
14
+ ||!Number.isSafeInteger(message.nativeUpdatedAt)
15
+ ||!Number.isInteger(sender.tab?.id)||Date.now()>=deadlineOf(run))
16
+ return {status:'DENIED',code:'ADOPT_KICKOFF_NOT_ELIGIBLE'};
17
+ if(sender.url!==chrome.runtime.getURL('continue.html')
18
+ +'?tabId='+run.tabId+'&adoptKickoffAt='+message.nativeUpdatedAt)
19
+ return {status:'DENIED',code:'ADOPT_KICKOFF_ACTION_INVALID'};
20
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
21
+ if(pathOf(tab?.url)!==run.page)
22
+ return {status:'DENIED',code:'ADOPT_KICKOFF_CHAT_CHANGED'};
23
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
24
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
25
+ ||disk.session.phase!=='WAITING_REPLY'
26
+ ||disk.session.updatedAt!==message.nativeUpdatedAt)
27
+ return {status:'DENIED',code:'ADOPT_KICKOFF_NATIVE_CHANGED'};
28
+ // run.snapshot requires a business checkpoint. A freshly adopted Task has
29
+ // no checkpoint yet, so use the existing read-only live terminalStatus
30
+ // which verifies the current bound holder without inventing one.
31
+ const status=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
32
+ op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
33
+ if(status?.status!=='OK'
34
+ ||status.result?.runRef!==run.sessionId+':'+run.taskId+':0'
35
+ ||!Number.isSafeInteger(status.result?.approvalRevision)
36
+ ||status.result.approvalRevision<1
37
+ ||status.result?.unknownEffectCount!==0
38
+ ||status.result?.executionOutcome==='DONE'
39
+ ||status.result?.deliveryRef)
40
+ return {status:'DENIED',code:'ADOPT_KICKOFF_CONTEXT_UNVERIFIED'};
41
+ const exactId=chatIdOf(tab.url);
42
+ const read=async()=>{
43
+ const approval=await chrome.tabs.sendMessage(tab.id,{
44
+ type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
45
+ explicitChatId:exactId,expectedTaskId:run.taskId}).catch(()=>null);
46
+ const turn=await chrome.tabs.sendMessage(tab.id,{
47
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
48
+ const evidence=policy.normalizeAdoptionEvidence(approval,{
49
+ page:run.page,userKey:run.userKey,
50
+ postApprovalAssistantKey:run.assistantKey,
51
+ ...(run.adoptRVersion?{rVersion:run.adoptRVersion}:{}),
52
+ ...(run.adoptPVersion?{pVersion:run.adoptPVersion}:{})
53
+ });
54
+ if(!evidence||turn?.contract!=='chat-loop.turn-observer.v1'
55
+ ||turn.status!=='READY'||turn.page!==run.page
56
+ ||turn.userKey!==run.userKey||turn.assistantKey!==run.assistantKey
57
+ ||turn.pendingConfirmation
58
+ ||workerApi.parseStatus(turn.replyText)!=='UNKNOWN')
59
+ return null;
60
+ return {userKey:turn.userKey,assistantKey:turn.assistantKey,
61
+ replyText:turn.replyText,rVersion:evidence.rVersion,pVersion:evidence.pVersion};
62
+ };
63
+ const first=await read();
64
+ if(!first)return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_UNVERIFIED'};
65
+ await new Promise(resolve=>setTimeout(resolve,2300));
66
+ const second=await read();
67
+ if(!second||JSON.stringify(first)!==JSON.stringify(second))
68
+ return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_CHANGED'};
69
+ const token=crypto.randomUUID();
70
+ await saveRun({...run,phase:'RESERVED',action:'CONTINUE',token,
71
+ manualActionTabId:sender.tab.id,
72
+ recoveryMode:'ADOPT_KICKOFF',kickoffAttempted:true});
73
+ return {status:'PREPARED',token,tabId:run.tabId};
74
+ }
75
+ // One-shot recovery of an ALREADY committed same-Chat Adopt whose historical
76
+ // post-approval reply was wrongly classified UNKNOWN. Never writes a composer,
77
+ // retries an action or replaces Context/Owner. Requires exact Native BLOCKED CAS.
78
+ async function onAdoptBaselineRepair(message,sender){
79
+ const prior=await readRun();
80
+ if(prior?.phase!=='BLOCKED'||prior.reason!=='UNKNOWN'
81
+ ||prior.action!=='START'||!prior.contextManaged||!prior.taskId
82
+ ||(prior.recoveryAttempts||0)!==0
83
+ ||!prior.sessionId||!Number.isInteger(prior.tabId)
84
+ ||prior.tabId!==message.tabId||!prior.page
85
+ ||!/^user:[^\s]{8,}$/.test(prior.newUserKey||'')
86
+ ||!/^assistant:[^\s]{8,}$/.test(prior.assistantKey||'')
87
+ ||prior.userKey!==prior.newUserKey)
88
+ return {status:'DENIED',code:'ADOPT_BASELINE_NOT_ELIGIBLE'};
89
+ if(!Number.isSafeInteger(message.nativeUpdatedAt)||message.nativeUpdatedAt<=0
90
+ ||!Number.isInteger(sender.tab?.id))
91
+ return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_SOURCE'};
92
+ const expected=chrome.runtime.getURL('continue.html')
93
+ +'?tabId='+prior.tabId+'&adoptBaselineAt='+message.nativeUpdatedAt;
94
+ if(sender.url!==expected)
95
+ return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_ACTION'};
96
+ const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
97
+ if(pathOf(tab?.url)!==prior.page)
98
+ return {status:'DENIED',code:'ADOPT_BASELINE_CHAT_CHANGED'};
99
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
100
+ {op:'session-read'}).catch(()=>null);
101
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(prior),disk.session)
102
+ ||disk.session?.phase!=='BLOCKED'
103
+ ||disk.session.updatedAt!==message.nativeUpdatedAt)
104
+ return {status:'DENIED',code:'ADOPT_BASELINE_NATIVE_CHANGED'};
105
+ const exactChatId=chatIdOf(tab.url);
106
+ const read=async()=>{
107
+ const approval=await chrome.tabs.sendMessage(tab.id,
108
+ {type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
109
+ explicitChatId:exactChatId,expectedTaskId:prior.taskId}).catch(()=>null);
110
+ const turn=await chrome.tabs.sendMessage(tab.id,
111
+ {type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
112
+ const evidence=policy.normalizeAdoptionEvidence(approval,{
113
+ page:prior.page,userKey:prior.newUserKey,
114
+ postApprovalAssistantKey:prior.assistantKey,
115
+ ...(prior.adoptRVersion?{rVersion:prior.adoptRVersion}:{}),
116
+ ...(prior.adoptPVersion?{pVersion:prior.adoptPVersion}:{})
117
+ });
118
+ if(!evidence||turn?.contract!=='chat-loop.turn-observer.v1'
119
+ ||turn.status!=='READY'||turn.page!==prior.page
120
+ ||turn.userKey!==prior.newUserKey||turn.assistantKey!==prior.assistantKey
121
+ ||turn.pendingConfirmation
122
+ ||workerApi.parseStatus(turn.replyText)!=='UNKNOWN')
123
+ return null;
124
+ return {userKey:turn.userKey,assistantKey:turn.assistantKey,
125
+ replyText:turn.replyText,rVersion:evidence.rVersion,pVersion:evidence.pVersion};
126
+ };
127
+ const a=await read();
128
+ if(!a)return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_MISSING'};
129
+ await new Promise(resolve=>setTimeout(resolve,2300));
130
+ const b=await read();
131
+ if(!b||JSON.stringify(a)!==JSON.stringify(b))
132
+ return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_CHANGED'};
133
+ // Re-arm the observer as a historical baseline BEFORE Native CAS. Failure
134
+ // cannot leave Native in a half-resumed state. This sends no Chat message.
135
+ const armed=await chrome.tabs.sendMessage(tab.id,{
136
+ type:'CHAT_LOOP_TURN_RESUME_V1',
137
+ page:prior.page,userKey:prior.newUserKey,
138
+ assistantKey:prior.assistantKey,baselineOnly:true,
139
+ startedAt:prior.startedAt
140
+ }).catch(()=>null);
141
+ if(armed?.status!=='RESUMED'||armed.baselineOnly!==true)
142
+ return {status:'DENIED',code:'ADOPT_BASELINE_OBSERVER_UNVERIFIED'};
143
+ await saveRun({...prior,phase:'RESERVED',
144
+ reason:'ADOPT_BASELINE_RECOVERY',
145
+ recoveryMode:'ADOPT_IDLE_BASELINE',recoveryAttempts:1});
146
+ const clean={...prior,phase:'WAITING_REPLY',reason:'ADOPTED_IDLE_BASELINE',
147
+ recoveryAttempts:1,userKey:prior.newUserKey,assistantKey:prior.assistantKey};
148
+ delete clean.recoveryMode;
149
+ await saveRun(clean);
150
+ return {status:'REPAIRED',sessionId:prior.sessionId,taskId:prior.taskId,
151
+ activeChatId:exactChatId,baselineAssistantKey:prior.assistantKey,
152
+ generation:prior.generation||0};
153
+ }
154
+ // Only an explicitly opened, existing Continue Action may reveal a
155
+ // scroll-virtualized *terminal Owner* before the normal double Turn check.
156
+ // This grants no send permit and changes neither Worker nor Native state.
157
+ // The Action alone may scroll the verified Chat UI; the Worker never does.
158
+ async function onManualReveal(message,sender) {
159
+ const run=await readRun();
160
+ if(!run?.sessionId||run.phase!=='BLOCKED'||run.reason!=='BLOCKED'
161
+ ||run.action!=='CONTINUE'||run.recoveryProtocol!==1
162
+ ||!(run.recoveryAttempts>0)
163
+ ||run.recoverySourceAssistantKey===run.assistantKey
164
+ ||run.newUserKey!==run.userKey
165
+ ||!Number.isInteger(run.tabId)||message.tabId!==run.tabId
166
+ ||!Number.isSafeInteger(message.resumeBlockedAt)
167
+ ||message.resumeBlockedAt<=0 ||!Number.isInteger(sender.tab?.id))
168
+ return {status:'DENIED',code:'REVEAL_OWNER_UNVERIFIED'};
169
+ let url;
170
+ try{url=new URL(sender.url);}catch{return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};}
171
+ if(url.origin!==new URL(chrome.runtime.getURL('continue.html')).origin
172
+ ||url.pathname!=='/continue.html'
173
+ ||url.searchParams.size!==2
174
+ ||url.searchParams.get('tabId')!==String(run.tabId)
175
+ ||url.searchParams.get('resumeBlockedAt')!==String(message.resumeBlockedAt))
176
+ return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};
177
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
178
+ if(!tab||pathOf(tab.url)!==run.page)
179
+ return {status:'DENIED',code:'REVEAL_CHAT_CHANGED'};
180
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
181
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
182
+ ||disk.session.updatedAt!==message.resumeBlockedAt)
183
+ return {status:'DENIED',code:'REVEAL_NATIVE_CAS_UNVERIFIED'};
184
+ return {status:'OK',page:run.page};
185
+ }
@@ -0,0 +1,120 @@
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,phase:confirmed?'WAITING_REPLY':'BLOCKED',
47
+ startedAt:confirmed?Date.now():run.startedAt,
48
+ lastStartActionTabId:sender.tab.id,
49
+ ...(adoptedIdle?{assistantKey:run.adoptPostApprovalAssistantKey,
50
+ userKey:run.adoptUserKey}:{}),
51
+ reason:confirmed?(adoptedIdle?'ADOPTED_IDLE_BASELINE':'')
52
+ :adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED',
53
+ ...(!confirmed&&['START_HOME_URL_UNVERIFIED','NEW_CHAT_NOT_READY',
54
+ 'START_COMPOSER_NOT_EMPTY','START_ACCOUNT_SWITCH_VISIBLE',
55
+ 'FIRST_TURN_OBSERVER_UNAVAILABLE','START_SEND_BUTTON_UNAVAILABLE','START_INPUT_CHANGED',
56
+ 'START_INPUT_UNVERIFIED','START_INPUT_REJECTED',
57
+ 'START_CLICK_UNVERIFIED','FIRST_SEND_RECEIPT_UNKNOWN']
58
+ .includes(message.failureCode)
59
+ ?{lastStartFailureCode:message.failureCode}:{}),
60
+ ...(confirmed?{tabId:message.newTabId,page:message.newPage,
61
+ newUserKey:message.newUserKey}:{attemptedNewTabId:Number.isInteger(message.newTabId)?message.newTabId:null})};
62
+ if(confirmed){
63
+ delete next.handoffPending;
64
+ delete next.handoffPendingAt;
65
+ }
66
+ delete next.startPrompt;
67
+ delete next.adoptTabId;
68
+ delete next.adoptPage;
69
+ delete next.adoptUserKey;
70
+ delete next.adoptExplicitChatId;
71
+ delete next.adoptExpectedTaskId;
72
+ delete next.adoptPriorAssistantKey;
73
+ delete next.adoptPostApprovalAssistantKey;
74
+ delete next.adoptRVersion;
75
+ delete next.adoptPVersion;
76
+ delete next.repairUserText;
77
+ delete next.repairDoneAssistantKey;
78
+ delete next.purpose;
79
+ delete next.mode;
80
+ delete next.machineRequestId;
81
+ delete next.machineActionTabId;
82
+ delete next.replacedBlockedSessionId;
83
+ await saveRun(next);
84
+ let privateContext=null;
85
+ if(confirmed&&run.contextLeaseRef){
86
+ const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
87
+ op:'context-control',command:'run.bind.initial',
88
+ args:{expectedStoreEpoch:run.contextStoreEpoch,
89
+ writeRequestId:run.token+':initial-bind',
90
+ expectedTaskRevision:run.contextTaskRevision,expectedBindingRevision:0,
91
+ actionToken:run.token,leaseRef:run.contextLeaseRef,
92
+ runCredential:run.contextInitialCredential}
93
+ }).catch(()=>null);
94
+ if(bound?.status!=='OK'||bound.result?.status!=='BOUND'){
95
+ // First Chat may already exist. Never re-send merely to fix Context.
96
+ const stopped={...next,phase:'BLOCKED',reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
97
+ delete stopped.contextInitialCredential;
98
+ await saveRun(stopped);
99
+ return {status:'BLOCKED',code:bound?.code||'CONTEXT_INITIAL_BIND_UNVERIFIED'};
100
+ }
101
+ privateContext={runRef:bound.result.runRef,
102
+ runCredential:run.contextInitialCredential,
103
+ storeEpoch:run.contextStoreEpoch,
104
+ bindingRevision:bound.result.bindingRevision,
105
+ taskRevision:run.contextTaskRevision};
106
+ // Capability is delivered once in the private Start result, not Status.
107
+ const clean={...next,contextManaged:{storeEpoch:run.contextStoreEpoch}};
108
+ for(const key of ['contextInitialCredential','contextLeaseRef','contextStoreEpoch',
109
+ 'contextTaskRevision','contextApprovalRevision'])delete clean[key];
110
+ await saveRun(clean);
111
+ }
112
+ if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
113
+ 'https://chatgpt.com'+message.newPage).catch(()=>{});
114
+ return confirmed?{status:'OK',sessionId:next.sessionId,
115
+ activeChatId:sessionProjection(next).activeChatId,
116
+ activeChatUrl:sessionProjection(next).activeChatUrl,
117
+ ...(next.taskId?{taskId:next.taskId}:{}),
118
+ ...(privateContext?{context:privateContext}:{})}
119
+ :{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
120
+ }
@@ -0,0 +1,172 @@
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 ENGINEERING_FAILURE_NOTE = "【故障边界】编译或测试失败应诊断修复,不是网页运行错误。MCP 初始化或连接临时失败时,先核查已启动进程与未知副作用;只有确认后续是安全只读操作,才可针对本次独立故障再安排一次跨轮复核并输出 CONTINUE。若同一故障复核仍无进展,或消息发送结果、Owner、审批、权限不可信,则 BLOCKED,绝不重复执行未知副作用。不同故障分别判断,不能沿用旧故障的重试次数。";
8
+ const CONTINUE_TEXT = "继续当前任务,完成本轮后只在末行写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
9
+ const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
10
+ let queue = Promise.resolve();
11
+ const serial = fn => {
12
+ const work = queue.then(fn);
13
+ queue = work.catch(() => {});
14
+ return work;
15
+ };
16
+ // Admission and recovery run in this same Worker, never another browser executor.
17
+ const resources = workerApi.resources;
18
+ async function createBoundedAction(options) {
19
+ // Validate BEFORE creating a tab. No caller may open an arbitrary URL
20
+ // through the privileged Worker Action quota.
21
+ if(typeof options?.url!=='string'
22
+ ||!options.url.startsWith(chrome.runtime.getURL('')))
23
+ throw Error('ACTION_URL_UNVERIFIED');
24
+ const quota=await resources.admit(await readRun(),{kind:'action'});
25
+ if (!quota.ok) throw Error(quota.code);
26
+ const tab=await chrome.tabs.create(options);
27
+ if (!Number.isSafeInteger(tab?.id)||tab.id<=0)
28
+ throw Error('ACTION_CREATED_ID_UNVERIFIED');
29
+ // MV3 tabs.create may return about:blank + pendingUrl. Register the exact
30
+ // Extension URL requested rather than the transitional snapshot.
31
+ let registered=false;
32
+ try{registered=await resources.registerAction({id:tab.id,url:options.url});}
33
+ catch{ /* The newly created page is not trusted without its registration. */ }
34
+ if(!registered){
35
+ // Failed registration must not strand another Action tab. Remove only
36
+ // this tab if its fresh, read-back URL still proves Extension identity;
37
+ // never close a changed, active or pinned tab and never retry a send.
38
+ const current=await chrome.tabs.get(tab.id).catch(()=>null);
39
+ if(current&&!current.active&&!current.pinned
40
+ &&(current.url===options.url
41
+ ||current.url==='about:blank'&&current.pendingUrl===options.url))
42
+ await chrome.tabs.remove(tab.id).catch(()=>{});
43
+ throw Error('ACTION_RESOURCE_UNVERIFIED');
44
+ }
45
+ return tab;
46
+ }
47
+ // Identity and receipt policy are shared deterministic helpers. This Worker
48
+ // remains the only Chrome action/state owner.
49
+ const policy=workerApi.policy;
50
+ const {pathOf,chatIdOf}=policy;
51
+ const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
52
+ // Keep only a fixed-size fingerprint after Start's one-shot prompt is erased.
53
+ // A missing historical fingerprint means NOT_COMPARABLE, not "zero matches".
54
+ async function startPromptFingerprint(prompt) {
55
+ if(typeof prompt!=='string'||!globalThis.crypto?.subtle||
56
+ typeof TextEncoder!=='function')return null;
57
+ const normalized=prompt.replace(/\s+/g,'');
58
+ if(!normalized)return null;
59
+ const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(normalized));
60
+ return Array.from(new Uint8Array(digest),v=>v.toString(16).padStart(2,'0')).join('');
61
+ }
62
+ // Keep the windowMsOf alias as the fingerprint test's pure-read boundary.
63
+ const windowMsOf=policy.windowMsOf;
64
+ const {deadlineOf,clockActive,terminalFenceVerified,MODEL_RECEIPT_TTL_MS,
65
+ receiptHistory,updateModelReceipt,settleModelIntent}=policy;
66
+ async function saveRun(run) {
67
+ if (run && ["DONE","BLOCKED"].includes(run.phase))
68
+ run = settleModelIntent(run, run.phase==="DONE"?"CANCELLED_DONE":"BLOCKED", run.reason);
69
+ const now = Date.now(), deadlineAt = deadlineOf(run);
70
+ // Persist the intent even when a delayed alarm arrives after an Action
71
+ // receipt. This never revokes a Continue already reserved before deadline.
72
+ const sending = ["STARTING","RESERVED","PENDING"].includes(run.phase);
73
+ const marker = sending && typeof run.token==="string" ? run.token : null;
74
+ const next = {...run, ...(deadlineAt ? {deadlineAt} : {}),
75
+ ...(marker ? {actionPendingAt: run.resourceToken===marker
76
+ && Number.isSafeInteger(run.actionPendingAt) ? run.actionPendingAt : now,
77
+ resourceToken:marker} : {})};
78
+ if (clockActive(next) && deadlineAt !== null && now >= deadlineAt
79
+ && !next.handoffPending) {
80
+ next.handoffPending = true;
81
+ next.handoffPendingAt = now;
82
+ }
83
+ const stored=await readRun();
84
+ const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
85
+ &&["TOOL_PREFLIGHT_REPAIRED","HANDOFF_NOT_SENT","ADOPT_IDLE_BASELINE"].includes(next.recoveryMode)
86
+ &&next.recoveryAttempts>=1&&stored?.phase==="BLOCKED";
87
+ const syncNative=async()=>{
88
+ if(!next.sessionId)return;
89
+ const record=sessionProjection(next);
90
+ const saved=await chrome.runtime.sendNativeMessage(SESSION_HOST,
91
+ {op:"session-sync",session:record,
92
+ ...(next.replacedBlockedSessionId&&!recoveryCommit&&next.phase==='STARTING'
93
+ ?{replaceBlockedSessionId:next.replacedBlockedSessionId}:{}),
94
+ ...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
95
+ ...(next.recoveryExpectedNativeAt?{resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{})}:{})}).catch(()=>null);
96
+ if(saved?.status!=="OK"||saved.session?.sessionId!==next.sessionId
97
+ ||saved.session?.phase!==next.phase)
98
+ throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
99
+ };
100
+ // A terminal BLOCKED session may resume only after native CAS first.
101
+ // Do not leave a Chrome RESERVED owner behind if native rejects the
102
+ // transition: that mismatch previously made all status calls unreadable.
103
+ if(recoveryCommit)await syncNative();
104
+ await chrome.storage.local.set({[RUN_KEY]:next});
105
+ if(!recoveryCommit)await syncNative();
106
+ // The resource inventory is derived evidence; it never grants browser Owner.
107
+ if (["DONE","BLOCKED"].includes(next.phase)
108
+ && next.contextTerminalFence !== "PENDING"
109
+ && next.contextTerminalFence !== "UNVERIFIED")
110
+ await resources.terminal(next).catch(()=>{});
111
+
112
+ try {
113
+ if (clockActive(next) && !next.handoffPending && deadlineAt > Date.now()) {
114
+ await chrome.alarms?.create?.(DEADLINE_ALARM_NAME, {when: deadlineAt});
115
+ } else {
116
+ await chrome.alarms?.clear?.(DEADLINE_ALARM_NAME);
117
+ }
118
+ } catch { /* The existing periodic alarm is a conservative backup. */ }
119
+ }
120
+ // Browser Owner remains the only send authority. Native Host mirrors a minimal
121
+ // session pointer so later Chats can find the current Web Chat without a task engine.
122
+ function sessionProjection(run) {
123
+ const page=typeof run.page==='string'?run.page:'';
124
+ const match=page.match(/\/c\/([0-9a-f-]{12,})$/i);
125
+ const activeChatId=match?.[1]||null;
126
+ return {sessionId:run.sessionId,projectId:run.projectId,
127
+ ...(run.taskId?{taskId:run.taskId}:{}),phase:run.phase,generation:run.generation||0,activeChatId,
128
+ activeChatUrl:activeChatId?"https://chatgpt.com"+page:null,
129
+ updatedAt:Date.now()};
130
+ }
131
+ const SESSION_POINTER_KEYS=Object.freeze(['sessionId','projectId','taskId','phase',
132
+ 'generation','activeChatId','activeChatUrl']);
133
+ const matchesNativeProjection=(projected,native)=>Boolean(native
134
+ &&SESSION_POINTER_KEYS.every(key=>projected[key]===native[key]));
135
+ const sessionPage=(sender,name,id)=> Number.isInteger(sender.tab?.id)
136
+ && typeof id==='string'&&/^[a-f0-9]{32}$/.test(id)
137
+ && sender.url===chrome.runtime.getURL(name+'.html')+'?requestId='+id;
138
+ async function resourceChatGate(message,sender) {
139
+ const run=await readRun();
140
+ if(run?.phase!=='PENDING'
141
+ || !['start','handoff'].includes(message.action))
142
+ return {status:'DENIED',code:'RESOURCE_OWNER_NOT_PENDING'};
143
+ const authorized=message.action==='start'
144
+ ? run.action==='START' && run.machineActionTabId===sender.tab?.id
145
+ && sessionPage(sender,'start',run.machineRequestId)
146
+ : run.action==='HANDOFF' && isAction(sender,
147
+ {tabId:run.tabId,token:run.token},run);
148
+ if(!authorized)return {status:'DENIED',code:'RESOURCE_ACTION_SOURCE_INVALID'};
149
+ if(message.stage==='preflight') {
150
+ const quota=await resources.admit(run,{kind:'chat'});
151
+ return quota.ok?{status:'OK',code:'RESOURCE_CHAT_PERMITTED'}
152
+ :{status:'DENIED',code:quota.code};
153
+ }
154
+ if(message.stage==='adopt' && run.mode==='adopt'
155
+ &&Number.isInteger(message.tabId)&&message.tabId===run.adoptTabId){
156
+ const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
157
+ if(!tab||pathOf(tab.url)!==run.adoptPage
158
+ ||!await resources.adoptChat(tab,run))
159
+ return {status:'DENIED',code:'RESOURCE_ADOPTION_UNVERIFIED'};
160
+ return {status:'OK',code:'RESOURCE_CHAT_ADOPTED'};
161
+ }
162
+ if(message.stage!=='register' || !Number.isInteger(message.tabId))
163
+ return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
164
+ const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
165
+ if (!tab || tab.id===run.tabId || tab.id===sender.tab.id
166
+ || !await resources.registerChat(tab,run))
167
+ return {status:'DENIED',code:'RESOURCE_CHAT_NOT_VERIFIED'};
168
+ const inventory=await resources.reconcile(run);
169
+ if(inventory.activeChatCount>resources.CHAT_LIMIT)
170
+ return {status:'DENIED',code:'RESOURCE_CHAT_LIMIT'};
171
+ return {status:'OK',code:'RESOURCE_CHAT_REGISTERED'};
172
+ }
@@ -0,0 +1,165 @@
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
+ if(ownedRecovery){
120
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
121
+ {op:"session-read"}).catch(()=>null);
122
+ if(disk?.status!=="OK"||disk.session?.sessionId!==previous.sessionId
123
+ ||disk.session.phase!=="BLOCKED"
124
+ ||disk.session.projectId!==previous.projectId
125
+ ||disk.session.generation!==(previous.generation||0)
126
+ ||disk.session.activeChatId!==chatIdOf(tab.url)
127
+ ||resumeAt&&disk.session.updatedAt!==resumeAt
128
+ ||contextAt&&disk.session.updatedAt!==contextAt
129
+ ||legacyAt&&(!legacyUnsent||disk.session.updatedAt!==legacyAt))
130
+ return {status:"DENIED",code:"BLOCKED_OWNER_PERSISTENCE_UNVERIFIED"};
131
+ }
132
+ const token = crypto.randomUUID();
133
+ await saveRun({...(ownedRecovery?previous:{}),
134
+ tabId: tab.id, page: first.page, userKey: first.userKey,
135
+ assistantKey: first.assistantKey, phase: "RESERVED", token,
136
+ action: requested, startedAt:ownedRecovery?previous.startedAt:Date.now(),
137
+ manualActionTabId: sender.tab.id,
138
+ ...(ownedRecovery?{recoveryMode:contextNotSent?"HANDOFF_NOT_SENT":"TOOL_PREFLIGHT_REPAIRED",
139
+ recoveryAttempts:(previous.recoveryAttempts||0)+1,recoveryProtocol:1,
140
+ ...(resumeAt||legacyUnsent||contextNotSent
141
+ ?{recoveryExpectedNativeAt:contextAt||resumeAt||legacyAt}:{}),
142
+ ...(contextNotSent?{contextSourceMarker:"[CHAT_LOOP_STATUS:"+modelStatus+"]",
143
+ contextRecoveryCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
144
+ x=>x.toString(16).padStart(2,"0")).join(""),
145
+ contextRecoveryAttempted:true}:{}),
146
+ recoverySourceAssistantKey:first.assistantKey}:{}),
147
+ handoffMode: requested === "HANDOFF"
148
+ ? (modelStatus === "HANDOFF" ? "EXPLICIT" : "TIMED") : null,
149
+ ...(summary ? {handoffText: summary} : {})});
150
+ return {status: "PREPARED", token, tabId: tab.id};
151
+ }
152
+ const isAction = (sender, message, run) => {
153
+ if (!Number.isInteger(sender.tab?.id) || typeof sender.url !== "string") return false;
154
+ try {
155
+ const file = run?.action === "HANDOFF" ? "handoff.html" : "continue.html";
156
+ const u = new URL(sender.url);
157
+ const manual = Number.isInteger(run?.manualActionTabId)
158
+ && run.manualActionTabId === sender.tab.id && !u.searchParams.has("token")
159
+ && (!u.searchParams.has("tabId") || u.searchParams.get("tabId") === String(message.tabId));
160
+ return u.origin === new URL(chrome.runtime.getURL(file)).origin
161
+ && u.pathname === "/" + file
162
+ && (manual || u.searchParams.get("token") === message.token
163
+ && u.searchParams.get("tabId") === String(message.tabId));
164
+ } catch { return false; }
165
+ };