@tomflow/chatloop-tools 0.9.62 → 0.9.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +29 -10
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/package.json +3 -13
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -83
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,241 +0,0 @@
1
- // Reviewed TEST_ONLY native @ App entry. Never owns a Loop Session or uses Continue.
2
- const HOST='com.tomflow.chatloop.extension';
3
- const statusNode=document.getElementById('status');
4
- const detailNode=document.getElementById('details');
5
- const show=(status,detail)=>{statusNode.textContent=status;detailNode.textContent=detail;document.body.dataset.result=status==='SUCCESS'?'success':'error';};
6
- const pause=ms=>new Promise(r=>setTimeout(r,ms));
7
- const safeCode=code=>/^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'ENTRY_TEST_UNVERIFIED';
8
- async function readNewChat(id,recoverTestAt=false,recoverExactDraft=''){
9
- const end=Date.now()+90000;
10
- let cleaned=false;
11
- while(Date.now()<end){
12
- const tab=await chrome.tabs.get(id).catch(()=>null);
13
- if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
14
- if(tab.url==='https://chatgpt.com/'){
15
- const proof=await chrome.scripting.executeScript({target:{tabId:id},
16
- func:(recover,exactDraft)=>{
17
- if(location.origin!=='https://chatgpt.com'||location.pathname!=='/')return false;
18
- const mains=[...document.querySelectorAll('main')].filter(e=>e.getClientRects().length);
19
- const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
20
- ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
21
- if(mains.length!==1||!editor?.getClientRects().length||!editor.isContentEditable
22
- ||mains[0].querySelector('[data-chatgpt-search-message-ids],[data-message-author-role]'))
23
- return false;
24
- const current=(editor.innerText||editor.textContent||'').trim();
25
- if(!current)return 'READY';
26
- const canonical=value=>String(value||'').replace(/\s+/g,'');
27
- const exactRecovery=typeof exactDraft==='string'&&!!exactDraft
28
- &&canonical(current)===canonical(exactDraft);
29
- if(!recover&& !exactRecovery)return 'HAS_DRAFT';
30
- if(recover&&current!=='@'&&!exactRecovery)return 'HAS_DRAFT';
31
- // Only a verified leftover "@" or byte-equivalent earlier TEST_ONLY
32
- // draft may be cleared, on the newly created empty Chat home. Never
33
- // touch other drafts, user turns or existing Chat tabs.
34
- editor.focus();
35
- const selection=window.getSelection(),range=document.createRange();
36
- range.selectNodeContents(editor);selection.removeAllRanges();selection.addRange(range);
37
- if(!document.execCommand('delete',false))return 'RECOVERY_FAILED';
38
- return !(editor.innerText||editor.textContent||'').trim()
39
- ?'RECOVERED_DRAFT':'RECOVERY_FAILED';
40
- },args:[recoverTestAt&&!cleaned,cleaned?'':recoverExactDraft]}).catch(()=>null);
41
- const state=proof?.[0]?.result;
42
- if(state==='READY')return;
43
- if(state==='RECOVERED_DRAFT'){cleaned=true;continue;}
44
- if(state==='HAS_DRAFT')throw Error('ENTRY_COMPOSER_HAS_DRAFT');
45
- if(state==='RECOVERY_FAILED')throw Error('ENTRY_AT_RECOVERY_FAILED');
46
- }
47
- await pause(320);
48
- }
49
- throw Error('ENTRY_COMPOSER_NOT_READY');
50
- }
51
- async function nativeMentionAndSend(id,appId,prompt){
52
- const response=await chrome.scripting.executeScript({target:{tabId:id},
53
- func:async(appId,prompt)=>{
54
- const wait=ms=>new Promise(r=>setTimeout(r,ms));
55
- const visible=e=>Boolean(e?.getClientRects?.().length);
56
- const canonical=v=>String(v||'').replace(/\s+/g,'');
57
- const fail=(code,diagnostic='')=>({status:'FAILED',code,diagnostic:diagnostic.slice(0,180)});
58
- const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
59
- ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
60
- if(location.origin!=='https://chatgpt.com'||location.pathname!=='/'
61
- ||!editor||!visible(editor)||!editor.isContentEditable
62
- ||(editor.innerText||editor.textContent||'').trim())
63
- return fail('ENTRY_EDITOR_UNVERIFIED');
64
- // Commit the natural-language task to the host editor first. Selecting
65
- // a native App mention can rehydrate the composer and otherwise discard
66
- // text entered immediately after the selection transaction.
67
- editor.focus();
68
- if(!document.execCommand('insertText',false,prompt))return fail('ENTRY_PROMPT_INPUT_FAILED');
69
- await wait(700);
70
- if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
71
- return fail('ENTRY_PROMPT_NOT_VISIBLE');
72
- const selection=window.getSelection(),range=document.createRange();
73
- range.selectNodeContents(editor);range.collapse(true);
74
- selection.removeAllRanges();selection.addRange(range);
75
- if(!document.execCommand('insertText',false,'@'))return fail('ENTRY_AT_INPUT_FAILED');
76
- let choice=null,diagnostic='';
77
- const selectors=['button[data-plugin-impression-id]','[role="option"]','[role="menuitem"]','[cmdk-item]',
78
- '[data-testid*="app-item"]','[data-testid*="mention-item"]'];
79
- for(let i=0;i<55;i++){
80
- if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
81
- const nodes=[...document.querySelectorAll(selectors.join(','))]
82
- .filter(visible).filter(e=>(e.innerText||'').includes('Chat Loop'));
83
- const matching=nodes.filter(e=>e.getAttribute('data-plugin-impression-id')===appId);
84
- if(matching.length===1){choice=matching[0];break;}
85
- const exact=nodes.filter(e=>{
86
- const t=(e.innerText||'').trim();
87
- return t==='Chat Loop'||t.startsWith('Chat Loop\n');
88
- });
89
- if(exact.length===1){choice=exact[0];break;}
90
- if(!exact.length && nodes.length===1){choice=nodes[0];break;}
91
- diagnostic=nodes.slice(0,4).map(e=>e.getAttribute('data-plugin-impression-id')+':'+(e.innerText||'').slice(0,55)).join('|');
92
- await wait(220);
93
- }
94
- if(!choice)return fail('ENTRY_NATIVE_APP_OPTION_MISSING',diagnostic);
95
- choice.click();
96
- // A native mention is a structured composer node, not a literal "@Chat Loop" string.
97
- let native=false;
98
- for(let i=0;i<38;i++){
99
- const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
100
- native=tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
101
- ||(e.getAttribute('data-app-mention-path')||'').includes(appId)
102
- ||(e.getAttribute('href')||'').includes(appId));
103
- if(native)break;
104
- await wait(120);
105
- }
106
- if(!native)return fail('ENTRY_NATIVE_MENTION_UNVERIFIED',editor.innerHTML);
107
- // Wait for the host selection transaction to settle; never rely on
108
- // a transient DOM text match before clicking its native send button.
109
- for(let i=0;i<5;i++){
110
- await wait(240);
111
- if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED_BEFORE_SEND');
112
- if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
113
- return fail('ENTRY_PROMPT_LOST_ON_MENTION');
114
- }
115
- const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
116
- if(!tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
117
- ||(e.getAttribute('data-app-mention-path')||'').includes(appId)
118
- ||(e.getAttribute('href')||'').includes(appId)))
119
- return fail('ENTRY_NATIVE_MENTION_LOST');
120
- const send=document.querySelector('button[data-testid="send-button"]')
121
- ||document.querySelector('button[data-testid="composer-send-button"]')
122
- ||document.querySelector('button[aria-label="发送"]')
123
- ||document.querySelector('button[aria-label="Send message"]');
124
- if(!send||send.disabled||!visible(send))return fail('ENTRY_SEND_UNAVAILABLE');
125
- if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
126
- send.click(); // Exactly once. No caller retries on an uncertain receipt.
127
- return {status:'CLICKED_ONCE'};
128
- },args:[appId,prompt]}).catch(()=>null);
129
- const r=response?.[0]?.result;
130
- if(!r)throw Error('ENTRY_SEND_RESULT_UNKNOWN');
131
- if(r.status!=='CLICKED_ONCE')throw Error(safeCode(r.code));
132
- }
133
- async function verifyNativeUserTurn(id,appId,prompt){
134
- const end=Date.now()+120000;let last=null,stable=0,mismatch=0;
135
- while(Date.now()<end){
136
- const tab=await chrome.tabs.get(id).catch(()=>null);
137
- if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
138
- const path=tab.url&&new URL(tab.url).pathname;
139
- if(/^\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(path||'')){
140
- const r=await chrome.scripting.executeScript({target:{tabId:id},
141
- func:(appId,prompt)=>{
142
- if(location.origin!=='https://chatgpt.com')return null;
143
- // ChatGPT can render conversation turns outside its composer <main>.
144
- // A main-scoped read silently misses real user turns in that layout.
145
- const users=[...document.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]
146
- .filter(x=>x.getAttribute('data-chatgpt-search-unit-key')?.endsWith(':user'));
147
- if(!users.length){
148
- users.push(...document.querySelectorAll('[data-message-author-role="user"]'));
149
- }
150
- const u=users.at(-1);
151
- const key=u?.getAttribute('data-message-id')
152
- ||u?.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0];
153
- const bubble=u?.querySelector('[data-user-message-bubble="true"]')||u;
154
- const m=bubble?.querySelector('[data-prompt-link-href="app://'+appId+'"]');
155
- const canonical=v=>String(v||'').replace(/\s+/g,'');
156
- return {path:location.pathname,userCount:users.length,
157
- ids:users.map(x=>x.getAttribute('data-message-id')
158
- ||x.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0]),
159
- userKey:typeof key==='string'&&m
160
- &&canonical(bubble.innerText||bubble.textContent).includes(canonical(prompt))
161
- ?'user:'+key:null,hasNativeApp:Boolean(m)};
162
- },args:[appId,prompt]}).catch(()=>null);
163
- const v=r?.[0]?.result;
164
- if(v?.userCount>1||v?.ids?.some(x=>x!==v.ids[0]))
165
- throw Error('ENTRY_DUPLICATE_USER_TURN');
166
- if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&!v.userKey){
167
- if(++mismatch>=4)throw Error('ENTRY_USER_TURN_CONTENT_MISMATCH');
168
- }else mismatch=0;
169
- if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&v.userKey){
170
- const k=path+'|'+v.userKey;
171
- stable=last===k?stable+1:1;last=k;
172
- if(stable>=4){
173
- const chatId=path.slice(3);
174
- return {status:'OK',testOnly:true,appId,
175
- activeChatId:chatId,activeChatUrl:'https://chatgpt.com'+path,
176
- userKey:v.userKey};
177
- }
178
- }else{stable=0;last=null;}
179
- }
180
- await pause(350);
181
- }
182
- throw Error('ENTRY_NATIVE_TURN_RECEIPT_UNKNOWN');
183
- }
184
- async function run(){
185
- const own=await chrome.tabs.getCurrent();
186
- const params=new URLSearchParams(location.search),id=params.get('requestId');
187
- if(!own?.id||own.url!==location.href||[...params.keys()].length!==1
188
- ||!/^[a-f0-9]{32}$/.test(id||'')
189
- ||location.href!==chrome.runtime.getURL('entry_test.html')+'?requestId='+id)
190
- throw Error('ENTRY_TEST_ACTION_SOURCE_INVALID');
191
- const proof=await chrome.runtime.sendNativeMessage(HOST,{op:'acquire',id,action:'entry_test'});
192
- if(proof?.status!=='OK'||proof.action!=='entry_test'||proof.id!==id
193
- ||!proof.nonce||proof.intent?.confirmed!==true||proof.intent?.testOnly!==true)
194
- throw Error('ENTRY_TEST_NATIVE_UNAUTHORIZED');
195
- const intent=proof.intent;
196
- let tab,clicked=false;
197
- try{
198
- // This read-only Worker/Native gate may admit a provably frozen orphan
199
- // for an independent TEST_ONLY Chat; it never releases the old Session.
200
- const admitted=async()=>{
201
- const decision=await chrome.runtime.sendMessage({
202
- type:'CHAT_LOOP_ENTRY_TEST_ADMISSION_V1',requestId:id}).catch(()=>null);
203
- if(decision?.status!=='OK'||decision.scope!=='TEST_ONLY')
204
- throw Error(safeCode(decision?.code||'ENTRY_TEST_OWNER_UNVERIFIED'));
205
- };
206
- await admitted();
207
- let result;
208
- if(intent.verifyChatUrl){
209
- // Pure receipt recovery. Never click, resend, adopt or modify an existing Chat.
210
- show('RUNNING','只读核对已存在 Chat 的唯一原生 @ App 用户消息。');
211
- const candidates=await chrome.tabs.query({url:intent.verifyChatUrl});
212
- const matches=candidates.filter(t=>t.url===intent.verifyChatUrl
213
- &&Number.isSafeInteger(t.id));
214
- if(matches.length!==1)throw Error('ENTRY_VERIFY_TAB_UNVERIFIED');
215
- result=await verifyNativeUserTurn(matches[0].id,intent.appId,intent.prompt);
216
- }else{
217
- show('RUNNING','新普通 Chat 正在加载;仅验证原生 App 入口,不进行批准或 Start。');
218
- tab=await chrome.tabs.create({url:'https://chatgpt.com/',active:true,
219
- windowId:own.windowId,openerTabId:own.id});
220
- if(!Number.isSafeInteger(tab?.id))throw Error('ENTRY_NEW_TAB_UNVERIFIED');
221
- await readNewChat(tab.id,intent.recoverTestAt===true,intent.recoverExactDraft||'');
222
- await admitted(); // Recheck before the only possible first send.
223
- await nativeMentionAndSend(tab.id,intent.appId,intent.prompt);
224
- clicked=true;
225
- result=await verifyNativeUserTurn(tab.id,intent.appId,intent.prompt);
226
- }
227
- const stored=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
228
- nonce:proof.nonce,action:'entry_test',status:'OK',payload:JSON.stringify(result)});
229
- if(stored?.status!=='SAVED'||stored.id!==id)throw Error('ENTRY_TEST_NATIVE_RECEIPT_UNVERIFIED');
230
- show('SUCCESS','已确认唯一原生 @ App 用户消息,未创建 Browser Owner。');
231
- await chrome.tabs.remove(own.id);
232
- }catch(error){
233
- const code=safeCode(error?.message);
234
- // After an uncertain click, never send again. Preserve created chat for audit.
235
- const saved=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
236
- nonce:proof.nonce,action:'entry_test',status:'FAILED',code}).catch(()=>null);
237
- show('BLOCKED',code+(clicked?';已发送或副作用未知,禁止重试。':';尚未验证发送。'));
238
- if(saved?.status==='SAVED')await chrome.tabs.remove(own.id).catch(()=>{});
239
- }
240
- }
241
- void run().catch(error=>show('BLOCKED',safeCode(error?.message)));
@@ -1,393 +0,0 @@
1
- // Sole executor for a cross-Chat handoff. Worker only schedules/authorizes.
2
- // Never auto-retry a write or a tab creation after the result is uncertain.
3
- const statusNode = document.getElementById("status");
4
- const detailsNode = document.getElementById("details");
5
- const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
6
- const actionErrorCode=(error,fallback='HANDOFF_ERROR')=>{
7
- const code=error?.code||error?.message;
8
- return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
9
- ?code:fallback;
10
- };
11
- function show(status, details) {
12
- statusNode.textContent = status;
13
- detailsNode.textContent = details;
14
- document.body.dataset.result = status === "SUCCESS" ? "success" : "error";
15
- }
16
- async function verifyOldChat(target, summary, mode = "EXPLICIT") {
17
- const [execution] = await chrome.scripting.executeScript({
18
- target: {tabId: target.tabId},
19
- func: (expected, handoffText, handoffMode) => {
20
- if (location.origin !== "https://chatgpt.com" || location.pathname !== expected.page)
21
- throw Error("SOURCE_CHAT_CHANGED");
22
- const visible = node => Boolean(node?.getClientRects?.().length)
23
- && !node.closest?.('[hidden],[aria-hidden="true"]')
24
- && getComputedStyle(node).display !== "none";
25
- const mains = [...document.querySelectorAll("main")].filter(visible);
26
- if (mains.length !== 1) throw Error("SOURCE_MAIN_UNVERIFIED");
27
- const main = mains[0];
28
- const modern = [...main.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
29
- const legacy = [...main.querySelectorAll('[data-message-author-role]')];
30
- const role = n => n.getAttribute("data-message-author-role")
31
- || n.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
32
- const id = n => n?.getAttribute("data-message-id")
33
- || n?.getAttribute("data-chatgpt-search-message-ids")?.trim().split(/\s+/)[0]
34
- || n?.closest('[data-testid^="conversation-turn-"]')?.getAttribute("data-testid");
35
- const rows = modern.length ? modern : legacy;
36
- const user = rows.filter(n => role(n) === "user").at(-1);
37
- const assistant = rows.filter(n => role(n) === "assistant").at(-1);
38
- if ("user:" + id(user) !== expected.userKey
39
- || (assistant ? "assistant:" + id(assistant) : null) !== expected.assistantKey)
40
- throw Error("SOURCE_TURN_CHANGED");
41
- const content = (assistant?.querySelector('.markdown')?.innerText || assistant?.innerText || '').trim();
42
- if (handoffMode === "ERROR") {
43
- // No completed assistant response after the pending user Turn.
44
- // Require an explicit context limit on the *same* visible chat.
45
- const lastUserIndex = rows.findLastIndex(n => role(n) === "user");
46
- if (rows.slice(lastUserIndex + 1).some(n => role(n) === "assistant"))
47
- throw Error("ERROR_HANDOFF_NEW_ASSISTANT_EXISTS");
48
- const contextPattern = /(?:conversation (?:has (?:reached|exceeded) (?:its |the )?(?:maximum|context)|is too long)|context (?:window|length|limit) (?:has been |was )?(?:exceeded|reached)|maximum conversation (?:length|limit) (?:reached|exceeded)|对话(?:上下文|长度)(?:已)?(?:达到|超过)(?:上限|限制)|上下文(?:窗口|长度)(?:已)?(?:达到|超过)(?:上限|限制))/i;
49
- if (![...main.querySelectorAll('[role="alert"],[role="status"],[data-testid="conversation-error"]')]
50
- .some(el => visible(el) && contextPattern.test(el.innerText || el.textContent || '')))
51
- throw Error("CONTEXT_ERROR_NOT_CONFIRMED");
52
- } else if (handoffMode === "EXPLICIT") {
53
- if (!content.endsWith('\n[CHAT_LOOP_STATUS:HANDOFF]')
54
- || content.slice(0, -'[CHAT_LOOP_STATUS:HANDOFF]'.length).trim() !== handoffText)
55
- throw Error("SOURCE_HANDOFF_TEXT_CHANGED");
56
- } else if (handoffMode !== "TIMED" || !content
57
- || /\[CHAT_LOOP_STATUS:(?:DONE|BLOCKED)\]$/.test(content)) {
58
- throw Error("TIMED_HANDOFF_NOT_ELIGIBLE");
59
- }
60
- const scope = assistant?.closest('[data-testid^="conversation-turn-"]')
61
- || assistant?.closest('[data-talvt-turn-state]') || assistant;
62
- const state = scope?.getAttribute?.('data-talvt-turn-state');
63
- if (handoffMode !== "ERROR" && state && state !== "complete") throw Error("SOURCE_TURN_STILL_RUNNING");
64
- if ([...document.querySelectorAll('button[data-testid="stop-button"],button[aria-label="Stop generating"],button[aria-label="停止响应"]')].some(visible)
65
- || [...scope?.querySelectorAll?.('[aria-busy="true"],[data-tool-status="running"]') || []].some(visible))
66
- throw Error("SOURCE_GENERATION_STILL_RUNNING");
67
- if (handoffMode !== "ERROR" && ![...scope.querySelectorAll('button[aria-label="复制"],button[aria-label="Copy"],button[data-testid="copy-turn-action-button"]')].some(visible))
68
- throw Error("SOURCE_NOT_FINAL");
69
- // Last read-only guard before the Action creates any successor Chat:
70
- // an unanswered confirmation in the current assistant Turn wins.
71
- if (handoffMode !== "ERROR") {
72
- const gate = globalThis.ChatLoopTurnObserverV1?.poll?.();
73
- if (gate?.contract !== "chat-loop.turn-observer.v1"
74
- || gate.page !== expected.page
75
- || gate.userKey !== expected.userKey
76
- || gate.assistantKey !== expected.assistantKey
77
- || gate.reason === "WAITING_CHAT_HYDRATION"
78
- || typeof gate.pendingConfirmation !== "boolean")
79
- throw Error("CONFIRMATION_OBSERVER_UNVERIFIED");
80
- if (gate.pendingConfirmation) throw Error("CONFIRMATION_PENDING_DOM");
81
- }
82
- // Timed handoff must not modify the original Chat. Capture a bounded
83
- // read-only evidence snapshot here, not through URL or Worker storage.
84
- if (handoffMode === "TIMED" || handoffMode === "ERROR") {
85
- const entries = rows.map(node => ({role: role(node),
86
- text: (node.querySelector?.('.markdown')?.innerText
87
- || node.innerText || node.textContent || '').trim()}))
88
- .filter(item => (item.role === "user" || item.role === "assistant") && item.text);
89
- const head = entries.find(item => item.role === "user");
90
- if (!head) throw Error("SOURCE_CONTEXT_TOO_SHORT");
91
- const headText = head.text.slice(0, 6000);
92
- const tailText = entries.slice(-24).filter(item => item !== head).map(item =>
93
- (item.role === "user" ? "用户:" : "助手:") + item.text.slice(-3000))
94
- .join("\n\n").slice(-21000);
95
- const excerpt = "【当前可见片段首条用户消息|可能不是原始任务】\n" + headText
96
- + "\n\n【最近轮次证据】\n" + tailText;
97
- if (excerpt.length < 120) throw Error("SOURCE_CONTEXT_TOO_SHORT");
98
- const identity="【来源 Chat】https://chatgpt.com"+expected.page
99
- +(expected.sessionId?"\n【来源 Session】"+expected.sessionId:"")
100
- +(expected.projectId?"\n【项目标识】"+expected.projectId:"")
101
- +(Number.isSafeInteger(expected.generation)?"\n【来源 generation】"+expected.generation:"");
102
- return {ok: true, snapshot: "【交接参考:只读网页片段,可能截断】\n"+identity+"\n"+excerpt
103
- + (handoffMode === "ERROR" ? "\n【中断说明】当前 Chat 明确出现上下文容量错误,最后一条用户消息未收到完整助手回复;任何上轮工具副作用均需先核实,不得盲目重复。" : "")
104
- + "\n【证据边界】DOM可能虚拟化,首条可见消息不保证是原始任务,也不能作为新增批准。此片段不等于完整记录;必须通过实际工具、唯一Context和来源核对任务进展。"};
105
- }
106
- return {ok: true};
107
- }, args: [target, summary, mode]
108
- });
109
- if (execution?.result?.ok !== true) throw Error("SOURCE_HANDOFF_UNVERIFIED");
110
- if (["TIMED", "ERROR"].includes(mode) && (typeof execution.result.snapshot !== "string"
111
- || execution.result.snapshot.length < 120)) throw Error("SOURCE_SNAPSHOT_UNVERIFIED");
112
- return execution.result.snapshot || summary;
113
- }
114
- // Read-only readiness of the new, strictly blank Chat home. Never clear a
115
- // restored human draft, even if its text resembles a historical test prompt.
116
- async function waitForNewChat(tabId) {
117
- // An API promise can stall even if the bounded loop itself is short. The
118
- // timeout races READ-ONLY probes only; it never schedules a second send.
119
- const started = Date.now(), maxWaitMs = 45_000;
120
- const boundedRead = (promise, ms) => Promise.race([
121
- promise.catch(() => null), delay(ms).then(() => null)
122
- ]);
123
- for (let attempt = 0; attempt < 100 && Date.now()-started<maxWaitMs; attempt++) {
124
- const remaining = maxWaitMs-(Date.now()-started);
125
- const tab = await boundedRead(chrome.tabs.get(tabId),Math.min(1500,remaining));
126
- if (tab?.url?.startsWith("https://chatgpt.com/")) {
127
- const [check] = await boundedRead(chrome.scripting.executeScript({target: {tabId}, func: () => {
128
- if (location.origin !== "https://chatgpt.com" || location.pathname !== "/") return false;
129
- const input = document.querySelector('[contenteditable="true"][data-composer-markdown]')
130
- || document.querySelector('#prompt-textarea[contenteditable="true"]');
131
- return !!input?.getClientRects?.().length
132
- && !(input.innerText || input.textContent || "").trim();
133
- }}),Math.min(1500,maxWaitMs-(Date.now()-started))) || [];
134
- if (check?.result === true) return;
135
- }
136
- await delay(Math.min(450,Math.max(0,maxWaitMs-(Date.now()-started))));
137
- }
138
- throw Error("NEW_CHAT_NOT_READY");
139
- }
140
- async function sendHandoffOnce(tabId, text) {
141
- const [dispatch] = await chrome.scripting.executeScript({target: {tabId},
142
- func: async instruction => {
143
- try {
144
- if (location.origin !== "https://chatgpt.com" || location.pathname !== "/")
145
- throw Error("NEW_CHAT_NOT_BLANK");
146
- const input = document.querySelector('[contenteditable="true"][data-composer-markdown]')
147
- || document.querySelector('#prompt-textarea[contenteditable="true"]');
148
- if (!input?.getClientRects?.().length || (input.innerText || '').trim())
149
- throw Error("NEW_CHAT_COMPOSER_NOT_EMPTY");
150
- input.focus();
151
- // The ProseMirror editor may normalize paragraph boundaries after
152
- // execCommand returns. Check its actual rendered state without editing
153
- // or sending again, rather than treating a transient mismatch as proof
154
- // that the whole insertion failed.
155
- const canonical = value => String(value || '').replace(/\s+/g, '');
156
- if (!document.execCommand("insertText", false, instruction))
157
- throw Error("HANDOFF_INPUT_REJECTED");
158
- await new Promise(resolve => setTimeout(resolve, 400));
159
- const expected = canonical(instruction);
160
- let verified = false;
161
- for (let i = 0; i < 30; i++) {
162
- if (location.pathname !== "/") throw Error("NEW_CHAT_CHANGED_DURING_INPUT");
163
- if (canonical(input.innerText) === expected
164
- || canonical(input.textContent) === expected) {
165
- verified = true;
166
- break;
167
- }
168
- await new Promise(resolve => setTimeout(resolve, 120));
169
- }
170
- if (!verified) throw Error("HANDOFF_INPUT_UNVERIFIED");
171
- let button;
172
- for (let i = 0; i < 18; i++) {
173
- button = document.querySelector('button[type="submit"][aria-label="发送"]')
174
- || document.querySelector('button[data-testid="send-button"]')
175
- || document.querySelector('button[data-testid="composer-send-button"]');
176
- if (button && !button.disabled && button.getClientRects().length) break;
177
- await new Promise(resolve => setTimeout(resolve, 120));
178
- }
179
- if (!button || button.disabled || !button.getClientRects().length)
180
- throw Error("HANDOFF_SEND_NOT_READY");
181
- if (location.pathname !== "/") throw Error("NEW_CHAT_CHANGED_BEFORE_SEND");
182
- if (canonical(input.innerText) !== expected && canonical(input.textContent) !== expected)
183
- throw Error("HANDOFF_INPUT_CHANGED_BEFORE_SEND");
184
- button.click();
185
- return {clickedOnce: true};
186
- } catch (error) {
187
- const code=error?.code||error?.message;
188
- return {clickedOnce:false,reason:
189
- /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'HANDOFF_SEND_ERROR'};
190
- }
191
- }, args: [text]
192
- });
193
- if (dispatch?.result?.clickedOnce !== true) throw Error(dispatch?.result?.reason || "HANDOFF_SEND_UNVERIFIED");
194
- // Once clicked, only observe. A missing or ambiguous receipt must BLOCK;
195
- // no second Chat and no retry can be authorized from this Action.
196
- let candidateKey = null, candidateSince = 0;
197
- for (let attempt = 0; attempt < 75; attempt++) {
198
- const tab = await chrome.tabs.get(tabId);
199
- const path = new URL(tab.url || "https://chatgpt.com/").pathname;
200
- if (/^\/c\/[0-9a-f-]{12,}$/i.test(path)) {
201
- const [read] = await chrome.scripting.executeScript({target: {tabId},func: expected => {
202
- const visible = n => Boolean(n?.getClientRects?.().length);
203
- const mains = [...document.querySelectorAll("main")].filter(visible);
204
- if (mains.length !== 1) return null;
205
- const modern = [...mains[0].querySelectorAll(
206
- '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
207
- const rows = modern.length ? modern : [...mains[0].querySelectorAll('[data-message-author-role]')];
208
- const role = n => n.getAttribute('data-message-author-role')
209
- || n.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
210
- const idOf = n => n.getAttribute('data-message-id')
211
- || n.getAttribute('data-chatgpt-search-message-ids')?.trim().split(/\s+/)[0];
212
- const users = rows.filter(n => role(n) === 'user');
213
- const keys = [...new Set(users.map(idOf).filter(Boolean))];
214
- // The successor was verified to be a blank Chat home. More than one
215
- // user identity after our single click is an ambiguous send, NOT a
216
- // successful Handoff (even if the last bubble matches).
217
- if (keys.length > 1) return {reason:'HANDOFF_DUPLICATE_USER_TURNS'};
218
- if (keys.length !== 1) return null;
219
- const user = users.at(-1), id = idOf(user);
220
- const bubble = user.querySelector?.('[data-search-result-target]')
221
- || user.querySelector?.('[data-user-message-bubble="true"]') || user;
222
- const canonical = v => String(v || '').replace(/\s+/g, '');
223
- return id && id === keys[0]
224
- // A substring match may accept an extra or corrupted user message.
225
- // The sole successor Turn must contain exactly the sent handoff text.
226
- && canonical(bubble.innerText || bubble.textContent)===canonical(expected)
227
- ? {userKey: 'user:' + id} : null;
228
- },args: [text]});
229
- if (read?.result?.reason) throw Error(read.result.reason);
230
- if (read?.result?.userKey) {
231
- if (candidateKey !== read.result.userKey) {
232
- candidateKey = read.result.userKey;
233
- candidateSince = Date.now();
234
- }
235
- // Re-read over a bounded stability window before transferring the
236
- // original Owner, so immediately visible duplicate messages fail.
237
- if (Date.now() - candidateSince >= 900)
238
- return {status: "SENT_CONFIRMED", newTabId: tabId,
239
- newPage: path, newUserKey: read.result.userKey};
240
- }
241
- }
242
- await delay(450);
243
- }
244
- throw Error("NEW_CHAT_SEND_RECEIPT_UNKNOWN");
245
- }
246
- async function run() {
247
- const own = await chrome.tabs.getCurrent();
248
- const params = new URLSearchParams(location.search);
249
- const raw = params.get("tabId") || "";
250
- let token = params.get("token") || "";
251
- let tabId = Number(raw);
252
- if (!own?.id || own.url !== location.href || raw && !/^[1-9][0-9]*$/.test(raw)
253
- || token && !/^[0-9a-f-]{36}$/.test(token)
254
- || token && !raw) throw Error("HANDOFF_ACTION_PARAMETERS_INVALID");
255
- if (!token) {
256
- show("VERIFYING", "手动打开 Handoff:核对已完成的旧 Chat,申请单次新 Chat 交接许可。");
257
- const prepared = await chrome.runtime.sendMessage({
258
- type: "CHAT_LOOP_ACTION_MANUAL_PREPARE_V1", action: "HANDOFF",
259
- ...(raw ? {tabId} : {})
260
- });
261
- if (prepared?.status !== "PREPARED")
262
- throw Error(prepared?.code || "MANUAL_PREPARE_DENIED");
263
- tabId = prepared.tabId;
264
- token = prepared.token;
265
- }
266
- const request = {tabId, token};
267
- const permit = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_TAKE_V1", ...request});
268
- if (permit?.status === "DENIED" && permit.code === "PENDING_CONFIRMATION_DOM") {
269
- // A choice appeared after timed Handoff was reserved. Worker retains
270
- // the same Owner and no new Chat was created; close this stale Action.
271
- await chrome.tabs.remove(own.id);
272
- return;
273
- }
274
- if (permit?.status !== "OK" || permit.action !== "HANDOFF"
275
- || permit.target?.tabId !== request.tabId
276
- || (permit.handoffMode === "EXPLICIT" && typeof permit.text !== "string")
277
- || !["TIMED", "EXPLICIT", "ERROR"].includes(permit.handoffMode))
278
- throw Error("HANDOFF_NOT_AUTHORIZED");
279
- const quota=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
280
- action:'handoff',stage:'preflight'});
281
- if(quota?.status!=='OK') {
282
- await chrome.runtime.sendMessage({type:'CHAT_LOOP_ACTION_RESULT_V1',...request,
283
- result:'UNVERIFIED',reason:quota?.code||'RESOURCE_QUOTA_UNVERIFIED'}).catch(()=>{});
284
- throw Error(quota?.code||'RESOURCE_QUOTA_UNVERIFIED');
285
- }
286
- show("RUNNING", "已领取不可重试的一次性授权,验证旧会话交接信息。");
287
- let result;
288
- let newTab;
289
- try {
290
- const contextPacket = await verifyOldChat(permit.target, permit.text, permit.handoffMode);
291
- const source = await chrome.tabs.get(request.tabId);
292
- if (permit.target.page.startsWith('/g/')) throw Error('PROJECT_HANDOFF_ROUTE_UNVERIFIED');
293
- // Opening a new Chat is itself a side effect; never create another on failure.
294
- newTab = await chrome.tabs.create({url: "https://chatgpt.com/", active: true,
295
- windowId: source.windowId, openerTabId: own.id});
296
- // Chrome may initially report about:blank while the requested home URL loads.
297
- let homeUrlReady=false;
298
- for(let i=0;i<40;i++){
299
- const candidate=await chrome.tabs.get(newTab.id).catch(()=>null);
300
- if(candidate?.url==='https://chatgpt.com/'){homeUrlReady=true;break;}
301
- await new Promise(resolve=>setTimeout(resolve,250));
302
- }
303
- if(!homeUrlReady)throw Error('HANDOFF_HOME_URL_UNVERIFIED');
304
- const registered=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
305
- action:'handoff',stage:'register',tabId:newTab.id});
306
- if(registered?.status!=='OK')throw Error(registered?.code||'RESOURCE_REGISTER_UNVERIFIED');
307
- await waitForNewChat(newTab.id);
308
- // The observer must exist before the first user click on the new home page.
309
- // A successful send without an observer cannot be automatically continued.
310
- let observed;
311
- try { observed = await chrome.tabs.sendMessage(newTab.id,
312
- {type: "CHAT_LOOP_TURN_OBSERVE_V1"}); } catch { /* Reconnect below. */ }
313
- if (observed?.contract !== "chat-loop.turn-observer.v1") {
314
- await chrome.scripting.executeScript({target: {tabId: newTab.id},
315
- files: ["content.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
316
- observed = await chrome.tabs.sendMessage(newTab.id,
317
- {type: "CHAT_LOOP_TURN_OBSERVE_V1"});
318
- }
319
- if (observed?.contract !== "chat-loop.turn-observer.v1")
320
- throw Error("NEW_CHAT_OBSERVER_UNAVAILABLE");
321
- const contextReferences=permit.projectContext
322
- ?"\n\n【已核实的恢复入口|仅引用,不代表新增批准】\n"
323
- +JSON.stringify(permit.projectContext)
324
- +"\n先读取contextPath与taskDocPath,核实当前R/P有效版本、允许工作区和未知副作用;approvalDocPath如有仅是历史批准原文附件,不可替代当前任务有效性判断。"
325
- :"";
326
- const message = "你正在接手上一 Chat 未完成的任务。旧 Chat 的网页历史仍可核实,但当前 Chat 没有其隐式上下文。若为项目任务,先按已授权的项目 Skill 或目标仓库真实入口核实规则、进度和上一轮副作用;不要假定每个项目都有 AGENTS.md 或固定 context 目录,也不要重复未知副作用。\n\n交接资料:\n" + contextPacket + contextReferences
327
- + "\n\n本轮最终回复末行只能输出一个状态标记:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。是否跨 Chat 由扩展决定,不要主动要求 Handoff。";
328
- // The new run capability belongs ONLY in the successor Chat's first
329
- // formal user message. It is not a proof that Worker/Native already
330
- // committed ownership: the recipient must verify CommitProof first.
331
- const managed=permit.contextHandoff;
332
- const resumeCapability=managed
333
- ? "\n\n【Chat Loop Context 恢复凭证|目标 Chat 首消息专用】\n"
334
- + JSON.stringify({projectId:managed.projectId,taskId:managed.taskId,
335
- sessionId:managed.sessionId,attemptId:managed.attemptId,
336
- checkpointId:managed.checkpointId,storeEpoch:managed.storeEpoch,
337
- targetGeneration:managed.targetGeneration,
338
- taskRevision:managed.taskRevision,
339
- bindingRevision:managed.bindingRevision+1,
340
- runRef:managed.nextRunRef,runCredential:managed.nextRunCredential})
341
- + "\n【重要边界】凭证仅用于 Context 写入校验,不能凭它抢占网页 Owner。收到消息后先只读核对"
342
- + " Worker/Native 当前 Chat、Session、generation、原 attempt 和 Context 绑定已提交,"
343
- + "再根据唯一 Checkpoint 与未知副作用决定下一工作项。未确认只能只读,不得重复旧工具或 Handoff。"
344
- : "";
345
- const notice=permit.modelIntent?.id
346
- ? "\n\n【扩展控制回执】本次交接由上一 Chat 的工具意图 "
347
- + permit.modelIntent.id + " 触发;已通过唯一 Action 发送。"
348
- + (permit.modelIntent.reason ? "\n【交接原因(待核实)】"
349
- + permit.modelIntent.reason : "") : "";
350
- const checkpoint=permit.pendingPlan?.id&&typeof permit.pendingPlan.nextPrompt==="string"
351
- ? "\n\n【上一 Chat 暂存的下一步检查点|到期交接覆盖了 Continue】请求 "
352
- + permit.pendingPlan.id + " 原计划:\n"
353
- + permit.pendingPlan.nextPrompt
354
- + "\n【边界】这只是上一轮模型提出的计划,不代表用户新增批准。新 Chat 必须先核实任务状态、项目规则及已发生的副作用,不能盲目重复。"
355
- : "";
356
- // Durable SEND_BEGIN must precede the only possible send call. A lost
357
- // receipt after this point is SEND_UNKNOWN, NEVER NOT_SENT.
358
- if(managed){
359
- const begun=await chrome.runtime.sendMessage({
360
- type:'CHAT_LOOP_HANDOFF_SEND_BEGIN_V1',...request});
361
- if(begun?.status!=='RECORDED')
362
- throw Error(begun?.code||'HANDOFF_SEND_BEGIN_UNVERIFIED');
363
- }
364
- result = await sendHandoffOnce(newTab.id,
365
- message + notice + checkpoint + resumeCapability + (permit.modelTurnNote || ""));
366
- } catch (error) {
367
- result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
368
- }
369
- if(result.status!=="SENT_CONFIRMED")
370
- result.reason=actionErrorCode({code:result.reason});
371
- const committed = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
372
- result: result.status, reason: result.reason,
373
- newUserKey: result.newUserKey, newTabId: result.newTabId ?? newTab?.id,
374
- newPage: result.newPage});
375
- if (result.status !== "SENT_CONFIRMED" || committed?.status !== "OK")
376
- throw Error(result.reason || committed?.code || "HANDOFF_TRANSFER_UNVERIFIED");
377
- // The old Chat is closed only after the Worker confirms ownership transfer.
378
- // Its canonical conversation URL remains in ChatGPT history.
379
- const old = await chrome.tabs.get(request.tabId).catch(() => null);
380
- if (old && old.id !== newTab?.id && old.id !== own.id
381
- && old.url === "https://chatgpt.com" + permit.target.page) {
382
- await chrome.tabs.remove(old.id).catch(error => {
383
- console.warn("OLD_CHAT_TAB_CLEANUP_UNVERIFIED",
384
- actionErrorCode(error,"TAB_CLEANUP_UNVERIFIED"));
385
- });
386
- }
387
- show("SUCCESS", "新 Chat 已收到交接包;旧 Chat 标签已尝试安全清理。");
388
- await chrome.tabs.remove(own.id);
389
- }
390
- (new URLSearchParams(location.search).has("requestId")
391
- ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("handoff")) : run())
392
- .catch(error => show("BLOCKED",
393
- actionErrorCode(error,"HANDOFF_ACTION_FAILED")));
@@ -1,2 +0,0 @@
1
- // Browser Action API root. Actions only import this, not private helpers.
2
- export {queueModelIntent} from './model-intent.js';