@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,278 @@
1
+ // Task-first Continue via the SAME formal Continue Action / Chrome Worker.
2
+ // The Worker checks the original Action, Native, Context and durable attempt;
3
+ // only actions/continue.js owns the ONE DOM send. No alternative sender.
4
+ const taskActionFail=code=>Object.assign(Error(code),{code});
5
+ const taskActionAssert=(ok,code)=>{if(!ok)throw taskActionFail(code)};
6
+ async function taskActionOwner(message,sender){
7
+ const tabId=message?.tabId,token=message?.token;
8
+ taskActionAssert(message&&typeof message==='object'
9
+ &&Number.isSafeInteger(tabId)&&tabId>0
10
+ &&typeof token==='string'
11
+ &&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(token)
12
+ &&sender?.id===chrome.runtime.id&&sender.frameId===0
13
+ &&Number.isSafeInteger(sender?.tab?.id)&&sender.tab.id>0
14
+ &&sender.url===chrome.runtime.getURL('continue.html')
15
+ +'?tabId='+tabId+'&token='+token+'&taskFirst=1',
16
+ 'SCOPED_ACTION_SOURCE_INVALID');
17
+ const state=await scopedTaskRuns.read();
18
+ const hits=Object.values(state.items).filter(({run})=>
19
+ run.turnToken===token&&run.tabId===tabId
20
+ &&['WAITING_REPLY','PENDING'].includes(run.phase)
21
+ &&run.modelIntent?.action==='CONTINUE'
22
+ &&run.modelIntent.actionTabId===sender.tab.id);
23
+ if(hits.length===0){
24
+ const pending=Object.values(state.items).filter(({run})=>
25
+ run.turnToken===token&&run.tabId===tabId
26
+ &&run.phase==='WAITING_REPLY'
27
+ &&run.modelIntent?.action==='CONTINUE'
28
+ &&run.modelIntent.actionTabId===null);
29
+ if(pending.length===1)throw taskActionFail(
30
+ 'SCOPED_ACTION_REGISTRATION_PENDING');
31
+ }
32
+ taskActionAssert(hits.length===1,'SCOPED_ACTION_OWNER_UNVERIFIED');
33
+ const run=hits[0].run;
34
+ taskActionAssert(run.startedAt===undefined||run.startedAt<=Date.now(),
35
+ 'SCOPED_ACTION_CLOCK_UNTRUSTED');
36
+ return {run,tabId,actionTabId:sender.tab.id};
37
+ }
38
+ const taskActionNative=(run,op)=>({
39
+ op,sourceRequestId:run.modelIntent.id,
40
+ projectId:run.projectId,taskId:run.taskId,
41
+ sessionId:run.sessionId,generation:run.generation,
42
+ expectedSessionRevision:run.nativeOwnerRevision,
43
+ expectedStoreEpoch:run.contextStoreEpoch,
44
+ expectedBindingRevision:run.contextBindingRevision,
45
+ turnToken:run.turnToken
46
+ });
47
+ async function taskActionVerifyBrowserReceipt(run,newUserKey,
48
+ tabId=run.tabId,page=run.page){
49
+ const tab=await chrome.tabs.get(tabId).catch(()=>null);
50
+ if(!tab||pathOf(tab.url)!==page)return false;
51
+ const rows=await chrome.scripting.executeScript({
52
+ target:{tabId},
53
+ func:()=>{
54
+ if(location.origin!=='https://chatgpt.com')return null;
55
+ const mains=[...document.querySelectorAll('main')]
56
+ .filter(el=>el.getClientRects().length>0);
57
+ if(mains.length!==1)return null;
58
+ // Match the existing Observer's source preference. On hydrated
59
+ // ChatGPT pages both representations may coexist; mixing their
60
+ // message identities can manufacture a false unique/new Turn.
61
+ const legacy=[...mains[0].querySelectorAll(
62
+ '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
63
+ const nodes=legacy.length?legacy:[...mains[0]
64
+ .querySelectorAll(
65
+ '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
66
+ const role=n=>n.getAttribute('data-message-author-role')
67
+ ||n.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
68
+ const id=n=>n?.getAttribute('data-message-id')
69
+ ||n?.getAttribute('data-chatgpt-search-message-ids')
70
+ ?.trim().split(/\s+/)[0]
71
+ ||n?.closest('[data-testid^="conversation-turn-"]')
72
+ ?.getAttribute('data-testid');
73
+ const users=nodes.filter(n=>role(n)==='user');
74
+ const latest=users.at(-1);
75
+ return {page:location.pathname,
76
+ userKey:id(latest)?'user:'+id(latest):null,
77
+ unique:new Set(users.map(id).filter(Boolean)).size===users.length};
78
+ }
79
+ }).catch(()=>null);
80
+ return rows?.[0]?.result?.page===page
81
+ &&rows[0].result.userKey===newUserKey
82
+ &&rows[0].result.unique===true;
83
+ }
84
+ async function scopedTaskContinueAction(message,sender){
85
+ const owner=await taskActionOwner(message,sender);
86
+ return scopedTaskScheduler.perTask(owner.run.projectId,owner.run.taskId,
87
+ async()=>{
88
+ const state=await scopedTaskRuns.get(owner.run.projectId,owner.run.taskId);
89
+ const run=state.run;
90
+ taskActionAssert(run?.turnToken===message.token
91
+ &&run.modelIntent?.actionTabId===owner.actionTabId
92
+ &&run.modelIntent.action==='CONTINUE'
93
+ &&run.contextBindingRevision>0
94
+ &&typeof run.contextStoreEpoch==='string',
95
+ 'SCOPED_ACTION_OWNER_CHANGED');
96
+ const event=message.type;
97
+ if(event==='CHAT_LOOP_TASK_ACTION_TAKE_V2'){
98
+ if(run.phase==='PENDING'&&run.modelIntent.state==='TAKEN'
99
+ &&run.nextAttempt?.id===run.modelIntent.id
100
+ &&run.nextAttempt.sendBeginAt===null){
101
+ // Original Action restarted after a lost TAKEN response. The
102
+ // Worker already reserved this exact next Turn, but NO SEND_BEGIN
103
+ // was recorded. Re-read the same Native permit; do not mint a
104
+ // second token or consume a second Context Permit.
105
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
106
+ taskActionAssert(tab&&pathOf(tab.url)===run.page,
107
+ 'SCOPED_ACTION_RESUME_TAB_CHANGED');
108
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,
109
+ taskActionNative(run,'continue-send-check-v2')).catch(()=>null);
110
+ taskActionAssert(proof?.status==='SEND_ALLOWED'
111
+ &&proof.scope==='TASK_SCOPED_CONTINUE_ONCE'
112
+ &&proof.nativeOwnerRevision===run.nativeOwnerRevision,
113
+ 'SCOPED_ACTION_RESUME_PERMIT_UNKNOWN');
114
+ const source=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
115
+ op:'acquire',id:run.modelIntent.id,
116
+ action:'continue'}).catch(()=>null);
117
+ taskActionAssert(source?.status==='OK'
118
+ &&source.intent?.taskFirst===true
119
+ &&source.intent.turnToken===run.turnToken
120
+ &&typeof source.intent.nextPrompt==='string',
121
+ 'SCOPED_ACTION_RESUME_SOURCE_UNVERIFIED');
122
+ return {status:'OK',scope:'TASK_SCOPED_ACTION_TAKEN',
123
+ target:{tabId:run.tabId,page:run.page,
124
+ userKey:run.nextAttempt.sourceUserKey,
125
+ assistantKey:run.nextAttempt.sourceAssistantKey},
126
+ text:source.intent.nextPrompt
127
+ +scopedTurnToolNote(run.nextAttempt.nextTurnToken)
128
+ +'\n本 Task 的后续工具请求须填写 taskFirst:true;'
129
+ +'本次消息只允许原 Chat 的一次性 Continue。'};
130
+ }
131
+ taskActionAssert(Object.keys(message).length===3
132
+ &&run.phase==='WAITING_REPLY'
133
+ &&run.modelIntent.state==='QUEUED'
134
+ &&run.lastObservedTurn?.outcome==='CONTINUE'
135
+ &&run.lastObservedTurn.pendingConfirmation===false,
136
+ 'SCOPED_ACTION_NOT_READY');
137
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
138
+ taskActionAssert(tab&&pathOf(tab.url)===run.page,
139
+ 'SCOPED_ACTION_CHAT_CHANGED');
140
+ const native=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
141
+ op:'session-snapshot-v2',projectId:run.projectId,
142
+ taskId:run.taskId,sessionId:run.sessionId,
143
+ generation:run.generation}).catch(()=>null);
144
+ const pending=native?.status==='OK'
145
+ &&native.session?.phase==='PENDING'
146
+ &&native.session.revision===run.nativeOwnerRevision+1
147
+ &&native.session.activeChatId===run.ownerChatId
148
+ &&native.session.activeChatUrl==='https://chatgpt.com'+run.page;
149
+ if(!pending){
150
+ const route=await scopedTaskOwnerResolver.resolve({
151
+ id:chrome.runtime.id,frameId:0,
152
+ tab:{id:tab.id},url:tab.url});
153
+ taskActionAssert(route.runRevision===state.runRevision
154
+ &&route.nativeOwnerRevision===run.nativeOwnerRevision
155
+ &&route.contextBindingRevision===run.contextBindingRevision
156
+ &&route.contextStoreEpoch===run.contextStoreEpoch
157
+ &&route.projectId===run.projectId&&route.taskId===run.taskId,
158
+ 'SCOPED_ACTION_WRITER_CHANGED');
159
+ }
160
+ // If Native already moved to PENDING but the Worker lost the ACK,
161
+ // reconcile this SAME Context Permit by its original actionToken.
162
+ // An uncommitted SEND_BEGIN cannot be recreated from wall time.
163
+ // The private source contains the ONLY prompt. No text is stored
164
+ // in Worker Task state or passed in Action URL/query parameters.
165
+ const source=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
166
+ op:'acquire',id:run.modelIntent.id,action:'continue'});
167
+ taskActionAssert(source?.status==='OK'&&source.intent?.taskFirst===true
168
+ &&source.intent.turnToken===run.turnToken
169
+ &&typeof source.intent.nextPrompt==='string'
170
+ &&source.intent.nextPrompt.trim(),
171
+ 'SCOPED_ACTION_PROMPT_SOURCE_INVALID');
172
+ const permission=await chrome.runtime.sendNativeMessage(SESSION_HOST,
173
+ taskActionNative(run,pending
174
+ ?'continue-reconcile-v2':'continue-permit-v2')).catch(()=>null);
175
+ taskActionAssert(permission?.status==='PERMITTED'
176
+ &&permission.scope==='TASK_SCOPED_CONTINUE_PENDING'
177
+ &&permission.nativeOwnerRevision===run.nativeOwnerRevision+1
178
+ &&(pending?permission.readOnlyReconciled===true
179
+ :permission.readOnlyReconciled!==true)
180
+ &&permission.contextStoreEpoch===run.contextStoreEpoch
181
+ &&permission.contextBindingRevision===run.contextBindingRevision,
182
+ 'SCOPED_CONTINUE_PERMIT_UNKNOWN');
183
+ const nextTurnToken=crypto.randomUUID();
184
+ const attempt={id:run.modelIntent.id,turnToken:run.turnToken,
185
+ sourceUserKey:run.lastObservedTurn.userKey,
186
+ sourceAssistantKey:run.lastObservedTurn.assistantKey,
187
+ nextTurnToken,sendBeginAt:null};
188
+ await scopedTaskRuns.put({...run,phase:'PENDING',
189
+ reason:'CONTINUE_IN_FLIGHT',
190
+ nativeOwnerRevision:permission.nativeOwnerRevision,
191
+ modelIntent:{...run.modelIntent,state:'TAKEN'},
192
+ nextAttempt:attempt},{
193
+ expectedStoreRevision:state.storeRevision,
194
+ expectedRunRevision:state.runRevision,
195
+ transitionKind:'CONTEXT_CONTINUE_PERMITTED'});
196
+ return {status:'OK',scope:'TASK_SCOPED_ACTION_TAKEN',
197
+ target:{tabId:run.tabId,page:run.page,
198
+ userKey:attempt.sourceUserKey,
199
+ assistantKey:attempt.sourceAssistantKey},
200
+ text:source.intent.nextPrompt+scopedTurnToolNote(nextTurnToken)
201
+ +'\n当前为 Task-first 独立执行;使用工具时须填写 taskFirst:true;'
202
+ +'本次消息只允许原 Chat 的一次性 Continue。'};
203
+ }
204
+ taskActionAssert(run.phase==='PENDING'
205
+ &&run.nextAttempt?.id===run.modelIntent.id
206
+ &&run.nextAttempt.turnToken===run.turnToken,
207
+ 'SCOPED_ACTION_NOT_PENDING');
208
+ if(event==='CHAT_LOOP_TASK_SEND_BEGIN_V2'){
209
+ taskActionAssert(Object.keys(message).length===3
210
+ &&run.modelIntent.state==='TAKEN'
211
+ &&run.nextAttempt.sendBeginAt===null,
212
+ 'SCOPED_SEND_ALREADY_BEGUN');
213
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,
214
+ taskActionNative(run,'continue-send-check-v2')).catch(()=>null);
215
+ taskActionAssert(proof?.status==='SEND_ALLOWED'
216
+ &&proof.scope==='TASK_SCOPED_CONTINUE_ONCE'
217
+ &&proof.nativeOwnerRevision===run.nativeOwnerRevision,
218
+ 'SCOPED_SEND_FENCE_UNVERIFIED');
219
+ // Durable SEND_BEGIN before any Action is told to click. No retry
220
+ // on uncertain reply or Worker suspension.
221
+ await scopedTaskRuns.put({...run,
222
+ nextAttempt:{...run.nextAttempt,sendBeginAt:Date.now()},
223
+ modelIntent:{...run.modelIntent,state:'SEND_BEGIN'}},{
224
+ expectedStoreRevision:state.storeRevision,
225
+ expectedRunRevision:state.runRevision});
226
+ return {status:'RECORDED',scope:'TASK_SCOPED_SEND_BEGIN'};
227
+ }
228
+ if(event==='CHAT_LOOP_TASK_ACTION_RESULT_V2'){
229
+ taskActionAssert(Object.keys(message).length===6
230
+ &&run.modelIntent.state==='SEND_BEGIN'
231
+ &&Number.isSafeInteger(run.nextAttempt.sendBeginAt)
232
+ &&run.nextAttempt.sendBeginAt>0,
233
+ 'SCOPED_ACTION_RESULT_SOURCE_INVALID');
234
+ const confirmed=message.result==='SENT_CONFIRMED'
235
+ &&typeof message.newUserKey==='string'
236
+ &&/^user:[^\s]{8,}$/.test(message.newUserKey)
237
+ &&message.newUserKey!==run.nextAttempt.sourceUserKey
238
+ &&message.newPage===run.page
239
+ &&await taskActionVerifyBrowserReceipt(run,message.newUserKey);
240
+ if(!confirmed){
241
+ await scopedTaskRuns.put({...run,phase:'BLOCKED',
242
+ lastIntentReceipt:{turnToken:run.turnToken,id:run.modelIntent.id,
243
+ action:'CONTINUE',status:'UNKNOWN',updatedAt:Date.now()},
244
+ modelIntent:{...run.modelIntent,state:'ACTION_UNVERIFIED'}},{
245
+ expectedStoreRevision:state.storeRevision,
246
+ expectedRunRevision:state.runRevision});
247
+ return {status:'BLOCKED',code:'SCOPED_SEND_RESULT_UNKNOWN'};
248
+ }
249
+ taskActionAssert(!run.continueReceipt,
250
+ 'SCOPED_CONTINUE_RECEIPT_ALREADY_RECORDED');
251
+ // Preserve only the verified new Chat Turn identity before Native
252
+ // changes its Owner revision. If the one-shot ACK disappears, an
253
+ // existing Alarm can query the original receipt without re-sending.
254
+ const persisted=await scopedTaskRuns.put({...run,
255
+ continueReceipt:{id:run.modelIntent.id,
256
+ newUserKey:message.newUserKey,newPage:message.newPage,
257
+ observedAt:Date.now()}},{
258
+ expectedStoreRevision:state.storeRevision,
259
+ expectedRunRevision:state.runRevision});
260
+ const verified=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
261
+ ...taskActionNative(run,'continue-result-v2'),
262
+ sourceUserKey:run.nextAttempt.sourceUserKey,
263
+ newUserKey:message.newUserKey,newPage:message.newPage
264
+ }).catch(()=>null);
265
+ taskActionAssert(verified?.status==='CONFIRMED'
266
+ &&verified.scope==='TASK_SCOPED_CONTINUE_RECEIPT'
267
+ &&verified.nativeOwnerRevision===run.nativeOwnerRevision+1,
268
+ 'SCOPED_SEND_RECEIPT_UNKNOWN');
269
+ const next=scopedContinueSuccessorRun(run,
270
+ verified.nativeOwnerRevision,message.newUserKey);
271
+ await scopedTaskRuns.put(next,{
272
+ expectedStoreRevision:persisted.storeRevision,
273
+ expectedRunRevision:persisted.runRevision});
274
+ return {status:'OK',scope:'TASK_SCOPED_CONTINUE_CONFIRMED'};
275
+ }
276
+ throw taskActionFail('SCOPED_ACTION_MESSAGE_UNKNOWN');
277
+ });
278
+ }
@@ -0,0 +1,52 @@
1
+ // Context+Native cancel may commit while its one-shot Worker ACK is lost.
2
+ // The SAME minute Alarm checks the original cancel request and immutable
3
+ // Task/Session facts. It does not rerun Context or Native mutations.
4
+ async function reconcileScopedCancelled(){
5
+ if(!scopedTaskRuns||!scopedTaskScheduler)return;
6
+ const state=await scopedTaskRuns.read();
7
+ const candidates=Object.values(state.items).filter(({run})=>
8
+ run.phase==='BLOCKED'&&run.reason==='SESSION_CANCEL_PENDING'
9
+ &&/^[a-f0-9]{32}$/.test(run.cancelRequestId||''));
10
+ const jobs=candidates.map(({run,revision})=>scopedTaskScheduler.perTask(
11
+ run.projectId,run.taskId,async()=>{
12
+ const current=await scopedTaskRuns.get(run.projectId,run.taskId);
13
+ const s=current.run;
14
+ if(current.runRevision!==revision
15
+ ||s?.phase!=='BLOCKED'
16
+ ||s.reason!=='SESSION_CANCEL_PENDING'
17
+ ||s.cancelRequestId!==run.cancelRequestId
18
+ ||s.sessionId!==run.sessionId
19
+ ||s.generation!==run.generation)return;
20
+ const verified=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
21
+ op:'task-cancel-read-v2',
22
+ sourceRequestId:s.cancelRequestId,
23
+ projectId:s.projectId,taskId:s.taskId,
24
+ sessionId:s.sessionId,generation:s.generation,
25
+ expectedPriorSessionRevision:s.nativeOwnerRevision,
26
+ expectedBindingRevision:s.contextBindingRevision,
27
+ expectedActiveChatUrl:'https://chatgpt.com'+s.page
28
+ }).catch(()=>null);
29
+ if(verified?.status!=='CONFIRMED'
30
+ ||verified.scope!=='TASK_SCOPED_CANCELLED_NOT_DELIVERED'
31
+ ||verified.readOnly!==true
32
+ ||verified.nativeOwnerRevision!==s.nativeOwnerRevision+2
33
+ ||verified.contextBindingRevision!==s.contextBindingRevision+1)
34
+ return;
35
+ const fresh=await scopedTaskRuns.get(s.projectId,s.taskId);
36
+ if(fresh.runRevision!==current.runRevision)return;
37
+ const next={...s,phase:'CANCELLED',
38
+ reason:'SESSION_CANCELLED',
39
+ terminalAt:Date.now(),
40
+ nativeOwnerRevision:verified.nativeOwnerRevision,
41
+ contextBindingRevision:verified.contextBindingRevision};
42
+ await scopedTaskRuns.put(next,{
43
+ expectedStoreRevision:fresh.storeRevision,
44
+ expectedRunRevision:fresh.runRevision,
45
+ transitionKind:'CONTEXT_IDLE_CANCELLED'});
46
+ await resources.terminal(next).catch(()=>{});
47
+ }));
48
+ const outcomes=await Promise.allSettled(jobs);
49
+ for(const item of outcomes)if(item.status==='rejected')
50
+ console.warn('TASK_CANCEL_ACK_UNVERIFIED',
51
+ safeWorkerErrorCode(item.reason,'SCOPED_CANCEL_RECOVERY_UNVERIFIED'));
52
+ }
@@ -0,0 +1,93 @@
1
+ // Task-first idle Adopt Cancel, from the existing formal session.html Action.
2
+ // The Worker does NOT derive Task from URL. It fences its own Task first,
3
+ // then Native+Context transact the original confirmed cancellation.
4
+ async function scopedTaskCancel(message,sender){
5
+ if(sender?.id!==chrome.runtime.id||sender.frameId!==0
6
+ ||!Number.isSafeInteger(sender.tab?.id)||sender.tab.id<=0
7
+ ||!/^[a-f0-9]{32}$/.test(message?.requestId||'')
8
+ ||sender.url!==chrome.runtime.getURL('session.html')
9
+ +'?requestId='+message.requestId+'&operation=cancel'
10
+ ||message.operation!=='cancel'
11
+ ||Object.keys(message||{}).length!==3)
12
+ throw Object.assign(Error('Invalid Task cancel Action'),
13
+ {code:'SCOPED_CANCEL_ACTION_SOURCE_INVALID'});
14
+ const source=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
15
+ op:'acquire',id:message.requestId,action:'session'});
16
+ const intent=source?.intent;
17
+ if(source?.status!=='OK'||source.action!=='session'
18
+ ||source.id!==message.requestId||intent?.taskFirst!==true
19
+ ||intent.operation!=='cancel'||intent.confirmed!==true
20
+ ||typeof intent.projectId!=='string'
21
+ ||typeof intent.taskId!=='string')
22
+ throw Object.assign(Error('Missing Task cancel authority'),
23
+ {code:'SCOPED_CANCEL_REQUEST_UNVERIFIED'});
24
+ return scopedTaskScheduler.perTask(intent.projectId,intent.taskId,
25
+ async()=>{
26
+ const current=await scopedTaskRuns.get(intent.projectId,intent.taskId);
27
+ const run=current.run;
28
+ if(!run||run.phase!=='WAITING_REPLY'
29
+ ||run.reason!=='ADOPTED_IDLE_BASELINE'
30
+ ||!run.startRequestId||run.modelIntent||run.nextAttempt
31
+ ||run.lastIntentReceipt||run.handoffFence
32
+ ||run.sessionId!==intent.sessionId
33
+ ||run.generation!==intent.generation
34
+ ||run.nativeOwnerRevision!==intent.expectedNativeRevision
35
+ ||run.contextBindingRevision!==intent.expectedBindingRevision
36
+ ||run.contextStoreEpoch!==intent.contextStoreEpoch)
37
+ throw Object.assign(Error('Task cancel not idle'),
38
+ {code:'SCOPED_CANCEL_TASK_NOT_IDLE'});
39
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
40
+ if(!tab||pathOf(tab.url)!==run.page)
41
+ throw Object.assign(Error('Task Cancel Chat missing'),
42
+ {code:'SCOPED_CANCEL_TAB_CHANGED'});
43
+ const route=await scopedTaskOwnerResolver.resolve({
44
+ id:chrome.runtime.id,frameId:0,
45
+ tab:{id:tab.id},url:tab.url});
46
+ if(route.runRevision!==current.runRevision
47
+ ||route.projectId!==run.projectId
48
+ ||route.taskId!==run.taskId
49
+ ||route.sessionId!==run.sessionId
50
+ ||route.nativeOwnerRevision!==run.nativeOwnerRevision
51
+ ||route.taskRevision!==intent.expectedTaskRevision)
52
+ throw Object.assign(Error('Task Cancel writer drift'),
53
+ {code:'SCOPED_CANCEL_WRITER_CHANGED'});
54
+ // Freeze this Task's Worker queue BEFORE the Native Context write.
55
+ // If the IPC ACK disappears, no other Task is changed or resumed.
56
+ const stopped=await scopedTaskRuns.put({...run,phase:'BLOCKED',
57
+ reason:'SESSION_CANCEL_PENDING',cancelRequestId:message.requestId},{
58
+ expectedStoreRevision:current.storeRevision,
59
+ expectedRunRevision:current.runRevision});
60
+ const committed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
61
+ op:'task-cancel-v2',sourceRequestId:message.requestId,
62
+ projectId:run.projectId,taskId:run.taskId,
63
+ sessionId:run.sessionId,generation:run.generation,
64
+ expectedSessionRevision:run.nativeOwnerRevision,
65
+ expectedStoreEpoch:run.contextStoreEpoch,
66
+ expectedTaskRevision:intent.expectedTaskRevision,
67
+ expectedBindingRevision:run.contextBindingRevision,
68
+ startRequestId:run.startRequestId
69
+ }).catch(()=>null);
70
+ if(committed?.status!=='CONFIRMED'
71
+ ||committed.scope!=='TASK_SCOPED_CANCELLED_NOT_DELIVERED'
72
+ ||committed.nativeOwnerRevision!==run.nativeOwnerRevision+2
73
+ ||committed.contextBindingRevision!==run.contextBindingRevision+1)
74
+ throw Object.assign(Error('Cancel receipt unknown'),
75
+ {code:'SCOPED_CANCEL_RESULT_UNKNOWN'});
76
+ const latest=await scopedTaskRuns.get(run.projectId,run.taskId);
77
+ if(latest.runRevision!==stopped.runRevision)
78
+ throw Object.assign(Error('Cancel Worker drift'),
79
+ {code:'SCOPED_CANCEL_WORKER_UNKNOWN'});
80
+ const final={...latest.run,phase:'CANCELLED',
81
+ terminalAt:Date.now(),reason:'SESSION_CANCELLED',
82
+ nativeOwnerRevision:committed.nativeOwnerRevision,
83
+ contextBindingRevision:committed.contextBindingRevision};
84
+ await scopedTaskRuns.put(final,{
85
+ expectedStoreRevision:latest.storeRevision,
86
+ expectedRunRevision:latest.runRevision,
87
+ transitionKind:'CONTEXT_IDLE_CANCELLED'});
88
+ await resources.terminal(final).catch(()=>{});
89
+ return {status:'OK',scope:'TASK_SCOPED_CANCELLED_NOT_DELIVERED',
90
+ state:'CANCELLED_NOT_DELIVERED',taskId:run.taskId,
91
+ sessionId:run.sessionId};
92
+ });
93
+ }
@@ -0,0 +1,78 @@
1
+ // Complete a known single Continue from its original DOM/Native/Context
2
+ // facts when the one-shot Native RESULT ACK was lost. Never send/retry.
3
+ // Called only after each path independently proves the exact Owner and Turn.
4
+ // Pure Task projection; it cannot mint a permit, click, or create a Chat.
5
+ function scopedContinueSuccessorRun(prior,nativeOwnerRevision,newUserKey){
6
+ const next={...prior,phase:'WAITING_REPLY',reason:'CONTINUE_SENT',
7
+ nativeOwnerRevision,
8
+ turnToken:prior.nextAttempt.nextTurnToken,
9
+ awaitingUserKey:newUserKey,
10
+ lastIntentReceipt:{turnToken:prior.turnToken,id:prior.modelIntent.id,
11
+ action:'CONTINUE',status:'SENT_CONFIRMED',updatedAt:Date.now()},
12
+ nextPollAt:Date.now()+60000};
13
+ delete next.nextAttempt;delete next.modelIntent;
14
+ delete next.continueReceipt;delete next.lastObservedTurn;
15
+ delete next.lastFault;
16
+ return next;
17
+ }
18
+ async function scopedTaskReconcileContinuePending(run){
19
+ const current=await scopedTaskRuns.get(run.projectId,run.taskId);
20
+ const s=current.run,receipt=s?.continueReceipt;
21
+ if(!s||s.phase!=='PENDING'||!receipt
22
+ ||s.sessionId!==run.sessionId||s.generation!==run.generation
23
+ ||s.nativeOwnerRevision!==run.nativeOwnerRevision
24
+ ||s.modelIntent?.state!=='SEND_BEGIN'
25
+ ||s.nextAttempt?.id!==receipt.id
26
+ ||s.nextAttempt.id!==s.modelIntent.id
27
+ ||!Number.isSafeInteger(s.nextAttempt.sendBeginAt)
28
+ ||s.nextAttempt.sendBeginAt<=0
29
+ ||receipt.newPage!==s.page)return;
30
+ const tab=await chrome.tabs.get(s.tabId).catch(()=>null);
31
+ if(!tab||pathOf(tab.url)!==s.page
32
+ ||!await taskActionVerifyBrowserReceipt(s,
33
+ receipt.newUserKey,s.tabId,s.page))return;
34
+ const native=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
35
+ op:'session-snapshot-v2',projectId:s.projectId,
36
+ taskId:s.taskId,sessionId:s.sessionId,
37
+ generation:s.generation}).catch(()=>null);
38
+ const owner=native?.session;
39
+ if(native?.status!=='OK'
40
+ ||owner?.phase!=='WAITING_REPLY'
41
+ ||owner.revision!==s.nativeOwnerRevision+1
42
+ ||owner.sessionId!==s.sessionId
43
+ ||owner.generation!==s.generation
44
+ ||owner.activeChatId!==s.ownerChatId
45
+ ||owner.activeChatUrl!=='https://chatgpt.com'+s.page)return;
46
+ const writer=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
47
+ op:'context-writer-check-v2',projectId:s.projectId,
48
+ taskId:s.taskId,sessionId:s.sessionId,
49
+ generation:s.generation,
50
+ expectedSessionRevision:owner.revision}).catch(()=>null);
51
+ if(writer?.status!=='OK'
52
+ ||writer.scope!=='TASK_SCOPED_WRITER_VERIFIED'
53
+ ||writer.nativeOwnerRevision!==owner.revision
54
+ ||writer.contextBindingRevision!==s.contextBindingRevision
55
+ ||writer.contextStoreEpoch!==s.contextStoreEpoch)return;
56
+ const confirmed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
57
+ ...taskActionNative(s,'continue-result-read-v2'),
58
+ sourceUserKey:s.nextAttempt.sourceUserKey,
59
+ newUserKey:receipt.newUserKey,newPage:receipt.newPage
60
+ }).catch(()=>null);
61
+ if(confirmed?.status!=='CONFIRMED'
62
+ ||confirmed.scope!=='TASK_SCOPED_CONTINUE_RECEIPT'
63
+ ||confirmed.nativeOwnerRevision!==owner.revision
64
+ ||confirmed.readOnly!==true)return;
65
+ const latest=await scopedTaskRuns.get(s.projectId,s.taskId);
66
+ if(latest.runRevision!==current.runRevision)return;
67
+ const next=scopedContinueSuccessorRun(s,owner.revision,
68
+ receipt.newUserKey);
69
+ await scopedTaskRuns.put(next,{
70
+ expectedStoreRevision:latest.storeRevision,
71
+ expectedRunRevision:latest.runRevision});
72
+ // Existing Observer, same verified User Turn; no browser send.
73
+ await chrome.tabs.sendMessage(s.tabId,{
74
+ type:'CHAT_LOOP_TURN_RESUME_V1',page:s.page,
75
+ userKey:receipt.newUserKey,assistantKey:null,
76
+ startedAt:Date.now()}).catch(()=>null);
77
+ return {status:'RECOVERED',scope:'TASK_SCOPED_CONTINUE_ACK_ONLY'};
78
+ }
@@ -0,0 +1,148 @@
1
+ // Reconcile a proven Handoff send whose Native/Context ACK was lost.
2
+ // Same MV3 Worker / same Task queue. Reads exact browser, Native and
3
+ // Context receipts, then repairs ONLY the Worker projection; never sends.
4
+ function scopedHandoffResourceReceipt(prior){
5
+ // Successor identity and generation remain in the Task run. Retain
6
+ // only predecessor provenance and the original attempt for later turns.
7
+ return {sourceTabId:prior.tabId,sourcePage:prior.page,
8
+ attemptId:prior.modelIntent.id};
9
+ }
10
+ // Both independently proven Handoff paths produce the same Worker projection.
11
+ // Proof/authorization remain in their respective Native + DOM consumers.
12
+ function scopedHandoffSuccessorRun(prior,{generation,nativeOwnerRevision,
13
+ contextBindingRevision,ownerChatId,tabId,page,userKey}){
14
+ // Both normal success and lost-ACK recovery must consume the SAME
15
+ // persisted successor Turn receipt; never fall back to the old Chat's
16
+ // window or mint a fresh four-hour budget on a delayed ACK.
17
+ const now=Date.now(),receipt=prior.handoffReceipt;
18
+ const startedAt=receipt?.observedAt;
19
+ if(!Number.isSafeInteger(startedAt)||startedAt<=0||startedAt>now
20
+ ||receipt.newTabId!==tabId||receipt.newPage!==page
21
+ ||receipt.newUserKey!==userKey)
22
+ throw Error('SCOPED_HANDOFF_SUCCESSOR_CLOCK_UNVERIFIED');
23
+ const next={...prior,phase:'WAITING_REPLY',reason:'HANDOFF_SENT',
24
+ generation,nativeOwnerRevision,contextBindingRevision,
25
+ ownerChatId,tabId,page,startedAt,
26
+ deadlineAt:startedAt+policy.windowMsOf(prior),
27
+ turnToken:prior.nextAttempt.nextTurnToken,
28
+ awaitingUserKey:userKey,
29
+ lastIntentReceipt:{turnToken:prior.turnToken,id:prior.modelIntent.id,
30
+ action:'HANDOFF',status:'SENT_CONFIRMED',updatedAt:now},
31
+ nextPollAt:now+60000,
32
+ resourceTransfer:scopedHandoffResourceReceipt(prior)};
33
+ delete next.modelIntent;delete next.nextAttempt;
34
+ delete next.handoffFence;delete next.handoffReceipt;
35
+ delete next.lastObservedTurn;delete next.lastFault;
36
+ return next;
37
+ }
38
+ // Caller holds this Task's queue. A lost resource write/ACK is retried
39
+ // only against the persisted, already committed handoff projection.
40
+ async function scopedSettleHandoffResources(projectId,taskId){
41
+ const snapshot=await scopedTaskRuns.get(projectId,taskId);
42
+ const run=snapshot.run;
43
+ if(!run?.resourceTransfer)return true;
44
+ // Independently verify the current Native successor. A persisted
45
+ // projection by itself never releases quota if its Owner has drifted.
46
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
47
+ op:'session-snapshot-v2',projectId,taskId,sessionId:run.sessionId,
48
+ generation:run.generation}).catch(()=>null);
49
+ const owner=proof?.session;
50
+ if(proof?.status!=='OK'||proof.scope!=='TASK_SCOPED_SNAPSHOT'
51
+ ||owner?.projectId!==projectId||owner.taskId!==taskId
52
+ ||owner.sessionId!==run.sessionId||owner.generation!==run.generation
53
+ ||owner.revision!==run.nativeOwnerRevision
54
+ ||owner.activeChatId!==run.ownerChatId
55
+ ||owner.activeChatUrl!=='https://chatgpt.com'+run.page)return false;
56
+ if(['DONE','CANCELLED'].includes(run.phase)){
57
+ if(owner.phase!==run.phase)return false;
58
+ await resources.terminal(run);
59
+ }else{
60
+ const confirmed=await resources.confirmChat(run.tabId,run.sessionId,
61
+ 'https://chatgpt.com'+run.page,run);
62
+ if(confirmed!==true)return false;
63
+ }
64
+ const next={...run};delete next.resourceTransfer;
65
+ await scopedTaskRuns.put(next,{
66
+ expectedStoreRevision:snapshot.storeRevision,
67
+ expectedRunRevision:snapshot.runRevision});
68
+ return true;
69
+ }
70
+ async function reconcileScopedHandoffResources(){
71
+ if(!scopedTaskRuns||!scopedTaskScheduler)return;
72
+ const state=await scopedTaskRuns.read();
73
+ const jobs=Object.values(state.items).filter(({run})=>run.resourceTransfer)
74
+ .map(({run})=>scopedTaskScheduler.perTask(run.projectId,run.taskId,
75
+ ()=>scopedSettleHandoffResources(run.projectId,run.taskId)));
76
+ const outcomes=await Promise.allSettled(jobs);
77
+ for(const item of outcomes)if(item.status==='rejected'||item.value===false)
78
+ console.warn('TASK_HANDOFF_RESOURCE_RECONCILE_UNVERIFIED',
79
+ item.status==='rejected'?safeWorkerErrorCode(item.reason,'RESOURCE_TRANSFER_UNVERIFIED'):'RESOURCE_TRANSFER_UNVERIFIED');
80
+ }
81
+ async function scopedTaskReconcileHandoffPending(run){
82
+ const current=await scopedTaskRuns.get(run.projectId,run.taskId);
83
+ const s=current.run,receipt=s?.handoffReceipt;
84
+ if(!s||s.phase!=='PENDING'||!receipt
85
+ ||s.sessionId!==run.sessionId||s.generation!==run.generation
86
+ ||s.nativeOwnerRevision!==run.nativeOwnerRevision
87
+ ||s.modelIntent?.state!=='SEND_BEGIN'
88
+ ||s.handoffFence?.attemptId!==s.modelIntent.id
89
+ ||s.handoffFence?.contextStoreEpoch!==s.contextStoreEpoch
90
+ ||s.nextAttempt?.id!==s.modelIntent.id
91
+ ||!Number.isSafeInteger(s.nextAttempt.sendBeginAt)
92
+ ||s.nextAttempt.sendBeginAt<=0)return;
93
+ const tab=await chrome.tabs.get(receipt.newTabId).catch(()=>null);
94
+ const newId=tab&&chatIdOf(tab.url),page=tab&&pathOf(tab.url);
95
+ if(!tab||page!==receipt.newPage
96
+ ||tab.openerTabId!==s.modelIntent.actionTabId
97
+ ||!newId||newId===s.ownerChatId
98
+ ||!/^\/c\/[0-9a-f-]{12,}$/i.test(page)
99
+ ||!await taskActionVerifyBrowserReceipt(s,
100
+ receipt.newUserKey,receipt.newTabId,page))return;
101
+ // Native independently joins the original signed Handoff request,
102
+ // consumed Context Permit, new-generation Owner and bound Writer.
103
+ // A partially committed Native switch must NOT be treated as a bound
104
+ // successor, and no Context bind or browser send is replayed here.
105
+ const verified=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
106
+ ...scopedHandoffNative(s,'handoff-result-read-v2'),
107
+ checkpointId:s.handoffFence.checkpointId,
108
+ fencedBindingRevision:s.handoffFence.fencedBindingRevision,
109
+ newChatUrl:'https://chatgpt.com'+page,
110
+ newUserKey:receipt.newUserKey,
111
+ sourceUserKey:s.nextAttempt.sourceUserKey
112
+ }).catch(()=>null);
113
+ if(verified?.status!=='CONFIRMED'
114
+ ||verified.scope!=='TASK_SCOPED_HANDOFF_RESULT_READ_ONLY'
115
+ ||verified.readOnly!==true
116
+ ||verified.projectId!==s.projectId
117
+ ||verified.taskId!==s.taskId
118
+ ||verified.sessionId!==s.sessionId
119
+ ||verified.generation!==s.generation+1
120
+ ||verified.nativeOwnerRevision!==s.nativeOwnerRevision+1
121
+ ||verified.contextStoreEpoch!==s.contextStoreEpoch
122
+ ||verified.contextBindingRevision!==s.handoffFence.fencedBindingRevision+1)
123
+ return;
124
+ const freshTab=await chrome.tabs.get(receipt.newTabId).catch(()=>null);
125
+ if(!freshTab||pathOf(freshTab.url)!==page
126
+ ||freshTab.openerTabId!==s.modelIntent.actionTabId
127
+ ||!await taskActionVerifyBrowserReceipt(s,
128
+ receipt.newUserKey,receipt.newTabId,page))return;
129
+ const latest=await scopedTaskRuns.get(s.projectId,s.taskId);
130
+ if(latest.runRevision!==current.runRevision)return;
131
+ const next=scopedHandoffSuccessorRun(s,{
132
+ generation:verified.generation,
133
+ nativeOwnerRevision:verified.nativeOwnerRevision,
134
+ contextBindingRevision:verified.contextBindingRevision,
135
+ ownerChatId:newId,tabId:receipt.newTabId,page,
136
+ userKey:receipt.newUserKey});
137
+ await scopedTaskRuns.put(next,{
138
+ expectedStoreRevision:latest.storeRevision,
139
+ expectedRunRevision:latest.runRevision});
140
+ // Derived Resource and Observer actions never revoke a confirmed
141
+ // Native/Context transfer, and never click the composer.
142
+ await scopedSettleHandoffResources(s.projectId,s.taskId).catch(()=>false);
143
+ await chrome.tabs.sendMessage(receipt.newTabId,{
144
+ type:'CHAT_LOOP_TURN_RESUME_V1',page,
145
+ userKey:receipt.newUserKey,assistantKey:null,
146
+ startedAt:next.startedAt}).catch(()=>null);
147
+ return {status:'RECOVERED',scope:'TASK_SCOPED_HANDOFF_ACK_ONLY'};
148
+ }