@tomflow/chatloop-tools 0.9.64 → 0.9.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +296 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  45. package/node_modules/@tomflow/chatloop-context/package.json +38 -0
  46. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  47. package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
  48. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
  49. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  126. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  127. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  128. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  129. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  130. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  131. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  132. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  133. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  134. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  135. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
  136. package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
  137. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
  138. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
  139. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
  140. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
  141. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  142. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
  143. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
  144. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  145. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  146. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  147. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  148. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  149. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  150. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  151. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  152. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  153. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  154. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
  155. package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
  156. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
  157. package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
  158. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  159. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  160. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  161. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  162. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  163. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
  164. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
  165. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
  166. package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
  167. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  168. package/node_modules/ps-list/index.d.ts +76 -0
  169. package/node_modules/ps-list/index.js +366 -0
  170. package/node_modules/ps-list/license +9 -0
  171. package/node_modules/ps-list/package.json +44 -0
  172. package/node_modules/ps-list/readme.md +56 -0
  173. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  174. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  175. package/package.json +12 -4
@@ -0,0 +1,143 @@
1
+ // V2 Task-first Handoff on the pre-existing formal handoff.html sender.
2
+ // Delegates the exact DOM interaction to handoff.js; never creates another
3
+ // browser sender or derives a Task from a user-supplied URL.
4
+ const sameOriginalChat=(tab,tabId,page)=>{
5
+ if(tab?.id!==tabId)return false;
6
+ try{
7
+ const url=new URL(tab.url);
8
+ return url.origin==='https://chatgpt.com'&&url.pathname===page;
9
+ }catch{return false;}
10
+ };
11
+ export async function runScopedHandoff(ports){
12
+ const {verifyOldChat,waitForNewChat,sendHandoffOnce,show,
13
+ actionErrorCode}=ports;
14
+ const own=await chrome.tabs.getCurrent(),q=new URLSearchParams(location.search);
15
+ const raw=q.get('tabId'),token=q.get('token');
16
+ if(!own?.id||own.url!==location.href||q.size!==3
17
+ ||q.get('taskFirst')!=='1'
18
+ ||!/^[1-9][0-9]*$/.test(raw||'')
19
+ ||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f-]{12}$/i.test(token||''))
20
+ throw Error('SCOPED_HANDOFF_PARAMETERS_INVALID');
21
+ const request={tabId:Number(raw),token};
22
+ const ask=(type,fields={})=>chrome.runtime.sendMessage({
23
+ type,...request,...fields});
24
+ let permit=null,registrationAttempts=0;
25
+ const capacityDeadline=Date.now()+60*60*1000;
26
+ for(;;){
27
+ permit=await ask('CHAT_LOOP_TASK_HANDOFF_TAKE_V2').catch(()=>null);
28
+ if(permit?.code==='SCOPED_ACTION_REGISTRATION_PENDING'
29
+ &&registrationAttempts++<12){
30
+ await new Promise(resolve=>setTimeout(resolve,180));
31
+ continue;
32
+ }
33
+ // RESOURCE_CHAT_LIMIT is decided in the Resource Ledger BEFORE
34
+ // Native/Context Permit consumption. Retry only that determinate
35
+ // no-side-effect denial on the SAME Action tab and original request.
36
+ // Never retry UNKNOWN, a partial Permit, or a lost Action ACK.
37
+ if(permit?.status==='DENIED'&&permit.code==='RESOURCE_CHAT_LIMIT'
38
+ &&Date.now()<capacityDeadline){
39
+ show('WAITING','当前 Task 的 Chat 名额不足,保留原 Writer,等待可用名额。');
40
+ await new Promise(resolve=>setTimeout(resolve,60_000));
41
+ // Worker rechecks the exact sender Tab URL and original Task/Turn
42
+ // on every TAKE; no duplicate check or second browser query here.
43
+ continue;
44
+ }
45
+ break;
46
+ }
47
+ if(permit?.status!=='OK'||permit.scope!=='TASK_SCOPED_HANDOFF_TAKEN'
48
+ ||permit.handoffMode!=='EXPLICIT'
49
+ ||permit.target?.tabId!==request.tabId
50
+ ||typeof permit.text!=='string'||!permit.contextHandoff)
51
+ throw Error(permit?.code||'SCOPED_HANDOFF_PERMIT_UNVERIFIED');
52
+ const h=permit.contextHandoff;
53
+ let newTab,started=false,result=null;
54
+ try{
55
+ const summary=await verifyOldChat(permit.target,permit.text,'EXPLICIT');
56
+ const source=await chrome.tabs.get(request.tabId);
57
+ if(!sameOriginalChat(source,request.tabId,permit.target.page))
58
+ throw Error('SCOPED_HANDOFF_OLD_CHAT_CHANGED');
59
+ // TAKE already reserved the original Action's successor seat before
60
+ // consuming the Permit. This check must not allocate another seat.
61
+ const hold=await ask('CHAT_LOOP_TASK_HANDOFF_CHAT_V2',{
62
+ stage:'preflight'}).catch(()=>null);
63
+ if(hold?.status!=='OK'||hold.scope!=='TASK_SCOPED_CHAT_RESERVED')
64
+ throw Error(hold?.code||'SCOPED_HANDOFF_HOLD_UNVERIFIED');
65
+ // A new Chat is an irreversible browser side effect: create once, never
66
+ // regenerate it if the tab ID, URL, page or ACK is missing.
67
+ newTab=await chrome.tabs.create({url:'https://chatgpt.com/',
68
+ active:true,windowId:source.windowId,openerTabId:own.id});
69
+ let ready=false;
70
+ for(let i=0;i<40;i++){
71
+ const current=await chrome.tabs.get(newTab.id).catch(()=>null);
72
+ if(current?.url==='https://chatgpt.com/'){ready=true;break;}
73
+ await new Promise(resolve=>setTimeout(resolve,250));
74
+ }
75
+ if(!ready)throw Error('SCOPED_HANDOFF_HOME_UNKNOWN');
76
+ const registered=await ask('CHAT_LOOP_TASK_HANDOFF_CHAT_V2',{
77
+ stage:'register',newTabId:newTab.id}).catch(()=>null);
78
+ if(registered?.status!=='OK'
79
+ ||registered.scope!=='TASK_SCOPED_CHAT_REGISTERED')
80
+ throw Error(registered?.code||'SCOPED_HANDOFF_CHAT_NOT_REGISTERED');
81
+ await waitForNewChat(newTab.id);
82
+ let observer=await chrome.tabs.sendMessage(newTab.id,{
83
+ type:'CHAT_LOOP_TURN_OBSERVE_V1'}).catch(()=>null);
84
+ if(observer?.contract!=='chat-loop.turn-observer.v1'){
85
+ await chrome.scripting.executeScript({target:{tabId:newTab.id},
86
+ files:['content.js','loop/core.js','loop/observer-inspect.js',
87
+ 'loop/observer-poll.js','loop/observer-recovery.js',
88
+ 'loop/observer-approval.js','loop/observer.js']});
89
+ observer=await chrome.tabs.sendMessage(newTab.id,{
90
+ type:'CHAT_LOOP_TURN_OBSERVE_V1'}).catch(()=>null);
91
+ }
92
+ if(observer?.contract!=='chat-loop.turn-observer.v1')
93
+ throw Error('SCOPED_HANDOFF_OBSERVER_UNVERIFIED');
94
+ const context={projectId:h.projectId,taskId:h.taskId,
95
+ sessionId:h.sessionId,checkpointId:h.checkpointId,
96
+ attemptId:h.attemptId,storeEpoch:h.contextStoreEpoch,
97
+ targetGeneration:h.targetGeneration,
98
+ taskRevision:h.taskRevision,
99
+ bindingRevision:h.fencedBindingRevision+1,
100
+ runRef:h.nextRunRef,runCredential:h.nextRunCredential};
101
+ const handoff='你正在接手同一已授权 Task 的下一个 Chat。'
102
+ +'先核实原 Task 的 R/P、最新 Context Checkpoint、Native Owner、'
103
+ +'已发生的副作用;不要重复未知发送或新建另一任务。'
104
+ +'\n\n【旧 Chat 交接摘要】\n'+summary
105
+ +'\n\n【当前任务 Context 受控恢复凭据|仅本次新 Chat】\n'
106
+ +JSON.stringify(context)
107
+ +'\n验证新 generation、绑定修订与原 Handoff attempt 后,'
108
+ +'只按本 Task 原计划继续;阻断则报告 BLOCKED。'
109
+ +'\n\n最后一行必须是 [CHAT_LOOP_STATUS:CONTINUE]、'
110
+ +'[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。'
111
+ +(permit.modelTurnNote||'');
112
+ const begun=await ask('CHAT_LOOP_TASK_HANDOFF_SEND_BEGIN_V2')
113
+ .catch(()=>null);
114
+ if(begun?.status!=='RECORDED'
115
+ ||begun.scope!=='TASK_SCOPED_HANDOFF_SEND_BEGIN')
116
+ throw Error(begun?.code||'SCOPED_HANDOFF_SEND_BEGIN_UNKNOWN');
117
+ started=true;
118
+ show('RUNNING','当前 Task 已围栏旧 Writer,正在对新 Chat 发送一次交接。');
119
+ result=await sendHandoffOnce(newTab.id,handoff);
120
+ }catch(error){
121
+ result={status:'UNVERIFIED',reason:actionErrorCode(error)};
122
+ if(!started){
123
+ await ask('CHAT_LOOP_TASK_HANDOFF_ABORT_V2',{
124
+ reason:result.reason}).catch(()=>null);
125
+ throw Error(result.reason);
126
+ }
127
+ }
128
+ const done=await ask('CHAT_LOOP_TASK_HANDOFF_RESULT_V2',{
129
+ result:result.status,newTabId:result.newTabId??newTab?.id??null,
130
+ newUserKey:result.newUserKey??null,newPage:result.newPage??null,
131
+ nextRunCredential:h.nextRunCredential
132
+ }).catch(()=>null);
133
+ if(result.status!=='SENT_CONFIRMED'||done?.status!=='OK'
134
+ ||done.scope!=='TASK_SCOPED_HANDOFF_CONFIRMED')
135
+ throw Error(done?.code||result.reason||'SCOPED_HANDOFF_RECEIPT_UNKNOWN');
136
+ // Close the old tab only after Native + Context have promoted the exact
137
+ // new Chat. History remains available for audit; no send is retried.
138
+ const old=await chrome.tabs.get(request.tabId).catch(()=>null);
139
+ if(sameOriginalChat(old,request.tabId,permit.target.page))
140
+ await chrome.tabs.remove(old.id).catch(()=>{});
141
+ show('SUCCESS','同一 Task 已确认新 Chat 的交接和唯一 Owner。');
142
+ await chrome.tabs.remove(own.id).catch(()=>{});
143
+ }
@@ -0,0 +1,399 @@
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 legacy = [...mains[0].querySelectorAll(
208
+ '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
209
+ const rows = legacy.length ? legacy : modern;
210
+ const role = n => n.getAttribute('data-message-author-role')
211
+ || n.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
212
+ const idOf = n => n.getAttribute('data-message-id')
213
+ || n.getAttribute('data-chatgpt-search-message-ids')?.trim().split(/\s+/)[0];
214
+ const users = rows.filter(n => role(n) === 'user');
215
+ const keys = [...new Set(users.map(idOf).filter(Boolean))];
216
+ // The successor was verified to be a blank Chat home. More than one
217
+ // user identity after our single click is an ambiguous send, NOT a
218
+ // successful Handoff (even if the last bubble matches).
219
+ if (keys.length > 1) return {reason:'HANDOFF_DUPLICATE_USER_TURNS'};
220
+ if (keys.length !== 1) return null;
221
+ const user = users.at(-1), id = idOf(user);
222
+ const bubble = user.querySelector?.('[data-search-result-target]')
223
+ || user.querySelector?.('[data-user-message-bubble="true"]') || user;
224
+ const canonical = v => String(v || '').replace(/\s+/g, '');
225
+ return id && id === keys[0]
226
+ // A substring match may accept an extra or corrupted user message.
227
+ // The sole successor Turn must contain exactly the sent handoff text.
228
+ && canonical(bubble.innerText || bubble.textContent)===canonical(expected)
229
+ ? {userKey: 'user:' + id} : null;
230
+ },args: [text]});
231
+ if (read?.result?.reason) throw Error(read.result.reason);
232
+ if (read?.result?.userKey) {
233
+ if (candidateKey !== read.result.userKey) {
234
+ candidateKey = read.result.userKey;
235
+ candidateSince = Date.now();
236
+ }
237
+ // Re-read over a bounded stability window before transferring the
238
+ // original Owner, so immediately visible duplicate messages fail.
239
+ if (Date.now() - candidateSince >= 900)
240
+ return {status: "SENT_CONFIRMED", newTabId: tabId,
241
+ newPage: path, newUserKey: read.result.userKey};
242
+ }
243
+ }
244
+ await delay(450);
245
+ }
246
+ throw Error("NEW_CHAT_SEND_RECEIPT_UNKNOWN");
247
+ }
248
+ async function run() {
249
+ const own = await chrome.tabs.getCurrent();
250
+ const params = new URLSearchParams(location.search);
251
+ const raw = params.get("tabId") || "";
252
+ let token = params.get("token") || "";
253
+ let tabId = Number(raw);
254
+ if (!own?.id || own.url !== location.href || raw && !/^[1-9][0-9]*$/.test(raw)
255
+ || token && !/^[0-9a-f-]{36}$/.test(token)
256
+ || token && !raw) throw Error("HANDOFF_ACTION_PARAMETERS_INVALID");
257
+ if (!token) {
258
+ show("VERIFYING", "手动打开 Handoff:核对已完成的旧 Chat,申请单次新 Chat 交接许可。");
259
+ const prepared = await chrome.runtime.sendMessage({
260
+ type: "CHAT_LOOP_ACTION_MANUAL_PREPARE_V1", action: "HANDOFF",
261
+ ...(raw ? {tabId} : {})
262
+ });
263
+ if (prepared?.status !== "PREPARED")
264
+ throw Error(prepared?.code || "MANUAL_PREPARE_DENIED");
265
+ tabId = prepared.tabId;
266
+ token = prepared.token;
267
+ }
268
+ const request = {tabId, token};
269
+ const permit = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_TAKE_V1", ...request});
270
+ if (permit?.status === "DENIED" && permit.code === "PENDING_CONFIRMATION_DOM") {
271
+ // A choice appeared after timed Handoff was reserved. Worker retains
272
+ // the same Owner and no new Chat was created; close this stale Action.
273
+ await chrome.tabs.remove(own.id);
274
+ return;
275
+ }
276
+ if (permit?.status !== "OK" || permit.action !== "HANDOFF"
277
+ || permit.target?.tabId !== request.tabId
278
+ || (permit.handoffMode === "EXPLICIT" && typeof permit.text !== "string")
279
+ || !["TIMED", "EXPLICIT", "ERROR"].includes(permit.handoffMode))
280
+ throw Error("HANDOFF_NOT_AUTHORIZED");
281
+ const quota=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
282
+ action:'handoff',stage:'preflight'});
283
+ if(quota?.status!=='OK') {
284
+ await chrome.runtime.sendMessage({type:'CHAT_LOOP_ACTION_RESULT_V1',...request,
285
+ result:'UNVERIFIED',reason:quota?.code||'RESOURCE_QUOTA_UNVERIFIED'}).catch(()=>{});
286
+ throw Error(quota?.code||'RESOURCE_QUOTA_UNVERIFIED');
287
+ }
288
+ show("RUNNING", "已领取不可重试的一次性授权,验证旧会话交接信息。");
289
+ let result;
290
+ let newTab;
291
+ try {
292
+ const contextPacket = await verifyOldChat(permit.target, permit.text, permit.handoffMode);
293
+ const source = await chrome.tabs.get(request.tabId);
294
+ if (permit.target.page.startsWith('/g/')) throw Error('PROJECT_HANDOFF_ROUTE_UNVERIFIED');
295
+ // Opening a new Chat is itself a side effect; never create another on failure.
296
+ newTab = await chrome.tabs.create({url: "https://chatgpt.com/", active: true,
297
+ windowId: source.windowId, openerTabId: own.id});
298
+ // Chrome may initially report about:blank while the requested home URL loads.
299
+ let homeUrlReady=false;
300
+ for(let i=0;i<40;i++){
301
+ const candidate=await chrome.tabs.get(newTab.id).catch(()=>null);
302
+ if(candidate?.url==='https://chatgpt.com/'){homeUrlReady=true;break;}
303
+ await new Promise(resolve=>setTimeout(resolve,250));
304
+ }
305
+ if(!homeUrlReady)throw Error('HANDOFF_HOME_URL_UNVERIFIED');
306
+ const registered=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
307
+ action:'handoff',stage:'register',tabId:newTab.id});
308
+ if(registered?.status!=='OK')throw Error(registered?.code||'RESOURCE_REGISTER_UNVERIFIED');
309
+ await waitForNewChat(newTab.id);
310
+ // The observer must exist before the first user click on the new home page.
311
+ // A successful send without an observer cannot be automatically continued.
312
+ let observed;
313
+ try { observed = await chrome.tabs.sendMessage(newTab.id,
314
+ {type: "CHAT_LOOP_TURN_OBSERVE_V1"}); } catch { /* Reconnect below. */ }
315
+ if (observed?.contract !== "chat-loop.turn-observer.v1") {
316
+ await chrome.scripting.executeScript({target: {tabId: newTab.id},
317
+ files: ["content.js", "loop/core.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
318
+ observed = await chrome.tabs.sendMessage(newTab.id,
319
+ {type: "CHAT_LOOP_TURN_OBSERVE_V1"});
320
+ }
321
+ if (observed?.contract !== "chat-loop.turn-observer.v1")
322
+ throw Error("NEW_CHAT_OBSERVER_UNAVAILABLE");
323
+ const contextReferences=permit.projectContext
324
+ ?"\n\n【已核实的恢复入口|仅引用,不代表新增批准】\n"
325
+ +JSON.stringify(permit.projectContext)
326
+ +"\n先读取contextPath与taskDocPath,核实当前R/P有效版本、允许工作区和未知副作用;approvalDocPath如有仅是历史批准原文附件,不可替代当前任务有效性判断。"
327
+ :"";
328
+ const message = "你正在接手上一 Chat 未完成的任务。旧 Chat 的网页历史仍可核实,但当前 Chat 没有其隐式上下文。若为项目任务,先按已授权的项目 Skill 或目标仓库真实入口核实规则、进度和上一轮副作用;不要假定每个项目都有 AGENTS.md 或固定 context 目录,也不要重复未知副作用。\n\n交接资料:\n" + contextPacket + contextReferences
329
+ + "\n\n本轮最终回复末行只能输出一个状态标记:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。是否跨 Chat 由扩展决定,不要主动要求 Handoff。";
330
+ // The new run capability belongs ONLY in the successor Chat's first
331
+ // formal user message. It is not a proof that Worker/Native already
332
+ // committed ownership: the recipient must verify CommitProof first.
333
+ const managed=permit.contextHandoff;
334
+ const resumeCapability=managed
335
+ ? "\n\n【Chat Loop Context 恢复凭证|目标 Chat 首消息专用】\n"
336
+ + JSON.stringify({projectId:managed.projectId,taskId:managed.taskId,
337
+ sessionId:managed.sessionId,attemptId:managed.attemptId,
338
+ checkpointId:managed.checkpointId,storeEpoch:managed.storeEpoch,
339
+ targetGeneration:managed.targetGeneration,
340
+ taskRevision:managed.taskRevision,
341
+ bindingRevision:managed.bindingRevision+1,
342
+ runRef:managed.nextRunRef,runCredential:managed.nextRunCredential})
343
+ + "\n【重要边界】凭证仅用于 Context 写入校验,不能凭它抢占网页 Owner。收到消息后先只读核对"
344
+ + " Worker/Native 当前 Chat、Session、generation、原 attempt 和 Context 绑定已提交,"
345
+ + "再根据唯一 Checkpoint 与未知副作用决定下一工作项。未确认只能只读,不得重复旧工具或 Handoff。"
346
+ : "";
347
+ const notice=permit.modelIntent?.id
348
+ ? "\n\n【扩展控制回执】本次交接由上一 Chat 的工具意图 "
349
+ + permit.modelIntent.id + " 触发;已通过唯一 Action 发送。"
350
+ + (permit.modelIntent.reason ? "\n【交接原因(待核实)】"
351
+ + permit.modelIntent.reason : "") : "";
352
+ const checkpoint=permit.pendingPlan?.id&&typeof permit.pendingPlan.nextPrompt==="string"
353
+ ? "\n\n【上一 Chat 暂存的下一步检查点|到期交接覆盖了 Continue】请求 "
354
+ + permit.pendingPlan.id + " 原计划:\n"
355
+ + permit.pendingPlan.nextPrompt
356
+ + "\n【边界】这只是上一轮模型提出的计划,不代表用户新增批准。新 Chat 必须先核实任务状态、项目规则及已发生的副作用,不能盲目重复。"
357
+ : "";
358
+ // Durable SEND_BEGIN must precede the only possible send call. A lost
359
+ // receipt after this point is SEND_UNKNOWN, NEVER NOT_SENT.
360
+ if(managed){
361
+ const begun=await chrome.runtime.sendMessage({
362
+ type:'CHAT_LOOP_HANDOFF_SEND_BEGIN_V1',...request});
363
+ if(begun?.status!=='RECORDED')
364
+ throw Error(begun?.code||'HANDOFF_SEND_BEGIN_UNVERIFIED');
365
+ }
366
+ result = await sendHandoffOnce(newTab.id,
367
+ message + notice + checkpoint + resumeCapability + (permit.modelTurnNote || ""));
368
+ } catch (error) {
369
+ result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
370
+ }
371
+ if(result.status!=="SENT_CONFIRMED")
372
+ result.reason=actionErrorCode({code:result.reason});
373
+ const committed = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
374
+ result: result.status, reason: result.reason,
375
+ newUserKey: result.newUserKey, newTabId: result.newTabId ?? newTab?.id,
376
+ newPage: result.newPage});
377
+ if (result.status !== "SENT_CONFIRMED" || committed?.status !== "OK")
378
+ throw Error(result.reason || committed?.code || "HANDOFF_TRANSFER_UNVERIFIED");
379
+ // The old Chat is closed only after the Worker confirms ownership transfer.
380
+ // Its canonical conversation URL remains in ChatGPT history.
381
+ const old = await chrome.tabs.get(request.tabId).catch(() => null);
382
+ if (old && old.id !== newTab?.id && old.id !== own.id
383
+ && old.url === "https://chatgpt.com" + permit.target.page) {
384
+ await chrome.tabs.remove(old.id).catch(error => {
385
+ console.warn("OLD_CHAT_TAB_CLEANUP_UNVERIFIED",
386
+ actionErrorCode(error,"TAB_CLEANUP_UNVERIFIED"));
387
+ });
388
+ }
389
+ show("SUCCESS", "新 Chat 已收到交接包;旧 Chat 标签已尝试安全清理。");
390
+ await chrome.tabs.remove(own.id);
391
+ }
392
+ (new URLSearchParams(location.search).has("requestId")
393
+ ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("handoff"))
394
+ : new URLSearchParams(location.search).get('taskFirst')==='1'
395
+ ?import(chrome.runtime.getURL('actions/handoff-scoped.js'))
396
+ .then(m=>m.runScopedHandoff({verifyOldChat,waitForNewChat,
397
+ sendHandoffOnce,show,actionErrorCode})):run())
398
+ .catch(error => show("BLOCKED",
399
+ actionErrorCode(error,"HANDOFF_ACTION_FAILED")));
@@ -0,0 +1,2 @@
1
+ // Browser Action API root. Actions only import this, not private helpers.
2
+ export {queueModelIntent} from './model-intent.js';
@@ -0,0 +1,60 @@
1
+ // The only model-driven entrance reuses the two existing formal Action pages.
2
+ // It registers a decision; it never edits ChatGPT, creates a new Chat, or sends.
3
+ export async function queueModelIntent(action) {
4
+ const params = new URLSearchParams(location.search);
5
+ const id = params.get('requestId');
6
+ if([...params.keys()].length !== 1 || !/^[a-f0-9]{32}$/.test(id||''))
7
+ throw Error('INVALID_MODEL_REQUEST');
8
+ const own = await chrome.tabs.getCurrent();
9
+ if(!own?.id || own.url !== location.href)
10
+ throw Error('MODEL_ACTION_TAB_UNVERIFIED');
11
+ const host='com.tomflow.chatloop.extension';
12
+ const auth = await chrome.runtime.sendNativeMessage(host,{op:'acquire',id,action});
13
+ if(auth?.status!=='OK'||auth.id!==id||auth.action!==action
14
+ ||typeof auth.nonce!=='string'||!auth.intent)
15
+ throw Error(auth?.code||'MODEL_REQUEST_UNVERIFIED');
16
+ let outcome;
17
+ try {
18
+ const query=typeof auth.intent.intentId==='string'||auth.intent.lookup===true;
19
+ outcome = await chrome.runtime.sendMessage(auth.intent.taskFirst===true
20
+ ?{type:'CHAT_LOOP_TASK_MODEL_INTENT_V2',id,
21
+ action:action.toUpperCase()}
22
+ :{type:query?'CHAT_LOOP_MODEL_INTENT_STATUS_V1':'CHAT_LOOP_MODEL_INTENT_V1',
23
+ id,action:action.toUpperCase(),intent:auth.intent,
24
+ ...(auth.traceParent?{traceParent:auth.traceParent}:{})});
25
+ if(outcome?.status!==(query?'STATUS':'QUEUED')
26
+ || (auth.intent.taskFirst===true
27
+ &&!['TASK_SCOPED_INTENT_STATUS','TASK_SCOPED_INTENT_PENDING']
28
+ .includes(outcome.scope))
29
+ || !/^[a-f0-9]{32}$/.test(outcome.intentId||'')
30
+ || (query&&auth.intent.intentId&&outcome.intentId!==auth.intent.intentId)
31
+ || (!query&&outcome.intentId!==id)
32
+ ||outcome.action!==action.toUpperCase())
33
+ throw Error(outcome?.code||'MODEL_INTENT_DENIED');
34
+ const saved = await chrome.runtime.sendNativeMessage(host,{
35
+ op:'complete',id,nonce:auth.nonce,action,status:'OK',
36
+ payload:JSON.stringify(outcome)
37
+ });
38
+ if(saved?.status!=='SAVED'||saved.id!==id)
39
+ throw Error(saved?.code||'INTENT_RECEIPT_UNVERIFIED');
40
+ await chrome.tabs.remove(own.id);
41
+ } catch(e) {
42
+ // An already-queued intent is not retried. Native failure is diagnostic only.
43
+ try {
44
+ const rawCode=e?.code||e?.message;
45
+ const code=typeof rawCode==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
46
+ ?rawCode:'INTENT_UNVERIFIED';
47
+ const saved=await chrome.runtime.sendNativeMessage(host,{
48
+ op:'complete',id,nonce:auth.nonce,action,status:'FAILED',code
49
+ });
50
+ // The CLI already has a durable failure receipt. Keep the page only
51
+ // when that receipt could not be verified; never resubmit the intent.
52
+ if(saved?.status==='SAVED'&&saved.id===id) {
53
+ const live=await chrome.tabs.getCurrent();
54
+ if(live?.id===own.id&&live.url===location.href)
55
+ await chrome.tabs.remove(own.id).catch(()=>{});
56
+ }
57
+ } catch {}
58
+ throw e;
59
+ }
60
+ };
@@ -0,0 +1,9 @@
1
+ // Stateless Eye executor: read only a declared text/DOM mode with the same
2
+ // trusted Owner/Native admission as the two original Eye pages.
3
+ const script=document.currentScript;
4
+ const action=script?.dataset?.action;
5
+ const mode=script?.dataset?.readMode;
6
+ if(!/^chat_[a-z0-9_]+$/.test(action||'')||!['text','dom'].includes(mode))
7
+ throw Error('EYE_CAPABILITY_INVALID');
8
+ void globalThis.ChatLoopActionCommonV1.runReadAction(
9
+ mode,mode==='text'?250:1000,action);
@@ -0,0 +1,20 @@
1
+ // Reload Action: request reloading this extension, not other tabs/extensions.
2
+ (() => {
3
+ const {show, fail, requireOwnTab, machineBinding, machineResult, machineFailure} = globalThis.ChatLoopActionCommonV1;
4
+ async function run() {
5
+ const machine = await machineBinding("reload");
6
+ const own = requireOwnTab(await chrome.tabs.getCurrent());
7
+ show("RELOADING", "正在刷新 Chat Loop 扩展...");
8
+ // Save an ACCEPTED-but-unverified receipt before reload destroys this page.
9
+ if(machine)await machineResult(machine,"ACCEPTED");
10
+ const response = await chrome.runtime.sendMessage({
11
+ type: "CHAT_LOOP_EYE_RELOAD_V1", tabId: own.id
12
+ });
13
+ if (response?.status !== "ACCEPTED") throw Error("RELOAD_UNVERIFIED");
14
+ }
15
+ run().catch(async error => {
16
+ await machineFailure("reload",error);
17
+ fail(error.message || "UNEXPECTED_ERROR",
18
+ "操作未完成;动作页已保留,未对其他 ChatGPT 标签页进行操作。");
19
+ });
20
+ })();