@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,325 @@
1
+ // Task-scoped Handoff: original approval + Context checkpoint/fence + one Action.
2
+ // The only Chrome sender is the EXISTING actions/handoff.js.
3
+ const scopedHandoffFail=code=>Object.assign(Error(code),{code});
4
+ const scopedHandoffAssert=(value,code)=>{if(!value)throw scopedHandoffFail(code)};
5
+ async function scopedHandoffOwner(message,sender){
6
+ const tabId=message?.tabId,token=message?.token;
7
+ scopedHandoffAssert(Number.isSafeInteger(tabId)&&tabId>0
8
+ &&typeof token==='string'
9
+ &&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f-]{12}$/i.test(token)
10
+ &&sender?.id===chrome.runtime.id&&sender.frameId===0
11
+ &&Number.isSafeInteger(sender.tab?.id)&&sender.tab.id>0
12
+ &&sender.url===chrome.runtime.getURL('handoff.html')
13
+ +'?tabId='+tabId+'&token='+token+'&taskFirst=1',
14
+ 'SCOPED_HANDOFF_ACTION_SOURCE_INVALID');
15
+ const tasks=await scopedTaskRuns.read();
16
+ const matching=Object.values(tasks.items).filter(({run})=>
17
+ run.tabId===tabId&&run.turnToken===token
18
+ &&['WAITING_REPLY','PENDING'].includes(run.phase)
19
+ &&run.modelIntent?.action==='HANDOFF'
20
+ &&run.modelIntent.actionTabId===sender.tab.id);
21
+ if(!matching.length&&Object.values(tasks.items).some(({run})=>
22
+ run.tabId===tabId&&run.turnToken===token
23
+ &&run.modelIntent?.action==='HANDOFF'
24
+ &&run.modelIntent.actionTabId===null))
25
+ throw scopedHandoffFail('SCOPED_ACTION_REGISTRATION_PENDING');
26
+ scopedHandoffAssert(matching.length===1,'SCOPED_HANDOFF_OWNER_UNVERIFIED');
27
+ const run=matching[0].run;
28
+ scopedHandoffAssert(run.startedAt===undefined||run.startedAt<=Date.now(),
29
+ 'SCOPED_HANDOFF_CLOCK_UNTRUSTED');
30
+ return {run,actionTabId:sender.tab.id};
31
+ }
32
+ const scopedHandoffNative=(run,op)=>({
33
+ op,sourceRequestId:run.modelIntent.id,
34
+ projectId:run.projectId,taskId:run.taskId,
35
+ sessionId:run.sessionId,generation:run.generation,
36
+ expectedSessionRevision:run.nativeOwnerRevision,
37
+ expectedStoreEpoch:run.contextStoreEpoch,
38
+ expectedBindingRevision:run.contextBindingRevision,
39
+ turnToken:run.turnToken
40
+ });
41
+ async function scopedTaskHandoffAction(message,sender){
42
+ const owned=await scopedHandoffOwner(message,sender);
43
+ return scopedTaskScheduler.perTask(owned.run.projectId,owned.run.taskId,
44
+ async()=>{
45
+ const snapshot=await scopedTaskRuns.get(owned.run.projectId,
46
+ owned.run.taskId),run=snapshot.run;
47
+ scopedHandoffAssert(run?.turnToken===message.token
48
+ &&run.modelIntent?.actionTabId===owned.actionTabId
49
+ &&run.modelIntent.action==='HANDOFF'
50
+ &&run.contextStoreEpoch&&run.contextBindingRevision>0,
51
+ 'SCOPED_HANDOFF_OWNER_CHANGED');
52
+ const type=message.type;
53
+ if(type==='CHAT_LOOP_TASK_HANDOFF_TAKE_V2'){
54
+ scopedHandoffAssert(Object.keys(message).length===3
55
+ &&run.phase==='WAITING_REPLY'
56
+ &&!run.resourceTransfer
57
+ &&run.modelIntent.state==='QUEUED'
58
+ &&run.lastObservedTurn?.outcome==='HANDOFF'
59
+ &&run.lastObservedTurn.pendingConfirmation===false,
60
+ 'SCOPED_HANDOFF_TURN_UNVERIFIED');
61
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
62
+ scopedHandoffAssert(tab&&pathOf(tab.url)===run.page
63
+ &&!run.page.startsWith('/g/'),
64
+ 'SCOPED_HANDOFF_CHAT_UNVERIFIED');
65
+ const route=await scopedTaskOwnerResolver.resolve({
66
+ id:chrome.runtime.id,frameId:0,
67
+ tab:{id:tab.id},url:tab.url});
68
+ scopedHandoffAssert(route.runRevision===snapshot.runRevision
69
+ &&route.nativeOwnerRevision===run.nativeOwnerRevision
70
+ &&route.contextStoreEpoch===run.contextStoreEpoch
71
+ &&route.contextBindingRevision===run.contextBindingRevision
72
+ &&route.projectId===run.projectId&&route.taskId===run.taskId,
73
+ 'SCOPED_HANDOFF_WRITER_CHANGED');
74
+ const read=()=>chrome.tabs.sendMessage(run.tabId,{
75
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
76
+ const one=await read();
77
+ await new Promise(resolve=>setTimeout(resolve,400));
78
+ const two=await read();
79
+ scopedHandoffAssert(one?.status==='READY'&&two?.status==='READY'
80
+ &&one.page===run.page&&two.page===run.page
81
+ &&one.userKey===run.lastObservedTurn.userKey
82
+ &&one.assistantKey===run.lastObservedTurn.assistantKey
83
+ &&two.userKey===one.userKey
84
+ &&two.assistantKey===one.assistantKey
85
+ &&one.replyText===two.replyText
86
+ &&one.pendingConfirmation===false&&two.pendingConfirmation===false
87
+ &&workerApi.parseStatus(one.replyText)==='HANDOFF',
88
+ 'SCOPED_HANDOFF_SOURCE_CHANGED');
89
+ const summary=one.replyText.replace(
90
+ /\r?\n\[CHAT_LOOP_STATUS:HANDOFF\]\s*$/,'').trim();
91
+ scopedHandoffAssert(summary.length>=120&&summary.length<=16000
92
+ &&/目标/.test(summary)&&/已完成|进度/.test(summary)
93
+ &&/下一步|待办/.test(summary),
94
+ 'SCOPED_HANDOFF_PACKET_UNVERIFIED');
95
+ // Physical capacity is a prerequisite to consuming an irreversible
96
+ // Context Permit. A full shared quota leaves the old Writer active.
97
+ // The single Resource Ledger keeps the exact action-scoped hold
98
+ // across any lost reply; this never creates a new Chat.
99
+ const quota=await resources.reserveScopedHandoff(run,owned.actionTabId);
100
+ scopedHandoffAssert(quota?.ok===true
101
+ &&['RESOURCE_CHAT_RESERVED','RESOURCE_CHAT_RESERVED_SAME_ATTEMPT'].includes(quota.code),
102
+ quota?.code||'SCOPED_HANDOFF_QUOTA_UNVERIFIED');
103
+ const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,
104
+ scopedHandoffNative(run,'handoff-permit-v2')).catch(()=>null);
105
+ scopedHandoffAssert(allowed?.status==='PERMITTED'
106
+ &&allowed.scope==='TASK_SCOPED_HANDOFF_PENDING'
107
+ &&allowed.nativeOwnerRevision===run.nativeOwnerRevision+1
108
+ &&allowed.contextStoreEpoch===run.contextStoreEpoch
109
+ &&allowed.targetGeneration===run.generation+1
110
+ &&allowed.fencedBindingRevision===run.contextBindingRevision+1,
111
+ 'SCOPED_HANDOFF_PERMIT_UNKNOWN');
112
+ const handoffFence={attemptId:run.modelIntent.id,
113
+ checkpointId:allowed.checkpointId,
114
+ taskRevision:allowed.taskRevision,
115
+ fencedBindingRevision:allowed.fencedBindingRevision,
116
+ targetGeneration:allowed.targetGeneration,
117
+ nextRunRef:allowed.nextRunRef,
118
+ contextStoreEpoch:allowed.contextStoreEpoch};
119
+ const nextAttempt={id:run.modelIntent.id,
120
+ turnToken:run.turnToken,
121
+ sourceUserKey:run.lastObservedTurn.userKey,
122
+ sourceAssistantKey:run.lastObservedTurn.assistantKey,
123
+ nextTurnToken:crypto.randomUUID(),sendBeginAt:null};
124
+ await scopedTaskRuns.put({...run,phase:'PENDING',
125
+ reason:'HANDOFF_IN_FLIGHT',
126
+ nativeOwnerRevision:allowed.nativeOwnerRevision,
127
+ modelIntent:{...run.modelIntent,state:'TAKEN'},
128
+ handoffFence,nextAttempt},{
129
+ expectedStoreRevision:snapshot.storeRevision,
130
+ expectedRunRevision:snapshot.runRevision,
131
+ transitionKind:'CONTEXT_HANDOFF_PERMITTED'});
132
+ return {status:'OK',scope:'TASK_SCOPED_HANDOFF_TAKEN',
133
+ handoffMode:'EXPLICIT',text:summary,
134
+ target:{tabId:run.tabId,page:run.page,
135
+ userKey:nextAttempt.sourceUserKey,
136
+ assistantKey:nextAttempt.sourceAssistantKey},
137
+ contextHandoff:{projectId:run.projectId,taskId:run.taskId,
138
+ sessionId:run.sessionId,
139
+ ...handoffFence,
140
+ nextRunCredential:allowed.nextRunCredential,
141
+ bindingRevision:run.contextBindingRevision},
142
+ modelTurnNote:scopedTurnToolNote(nextAttempt.nextTurnToken)
143
+ +'\n本 Task 的后续工具请求须填写 taskFirst:true;'};
144
+ }
145
+ scopedHandoffAssert(run.phase==='PENDING'
146
+ &&run.nextAttempt?.id===run.modelIntent.id
147
+ &&run.handoffFence?.attemptId===run.modelIntent.id,
148
+ 'SCOPED_HANDOFF_NOT_PENDING');
149
+ if(type==='CHAT_LOOP_TASK_HANDOFF_ABORT_V2'){
150
+ scopedHandoffAssert(Object.keys(message).length===4
151
+ &&run.modelIntent.state==='TAKEN'
152
+ &&run.nextAttempt.sendBeginAt===null
153
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(message.reason||''),
154
+ 'SCOPED_HANDOFF_ABORT_INVALID');
155
+ // Persist the exact pre-send-abort proof before touching the
156
+ // physical seat. It can be rechecked by the same Alarm later
157
+ // if an unfinished successor tab is still open right now.
158
+ const blocked={...run,phase:'BLOCKED',
159
+ preSendAbort:{id:run.modelIntent.id,
160
+ actionTabId:sender.tab.id,recordedAt:Date.now()},
161
+ lastIntentReceipt:{turnToken:run.turnToken,id:run.modelIntent.id,
162
+ // The original Action had not received SEND_BEGIN. This is
163
+ // confirmed NOT_SENT for the Chat message, NOT a restored Writer.
164
+ action:'HANDOFF',status:'NOT_SENT',updatedAt:Date.now()},
165
+ modelIntent:{...run.modelIntent,state:'ACTION_UNVERIFIED'}};
166
+ const frozen=await scopedTaskRuns.put(blocked,{
167
+ expectedStoreRevision:snapshot.storeRevision,
168
+ expectedRunRevision:snapshot.runRevision});
169
+ // The original Action was proven pre-SEND_BEGIN by this Task's
170
+ // serialized Worker CAS. Revoke the old Native PENDING send gate
171
+ // exactly once; a lost ACK is followed only by the original
172
+ // request's read-only BLOCKED fence proof.
173
+ await chrome.runtime.sendNativeMessage(SESSION_HOST,{
174
+ ...scopedHandoffNative(blocked,'handoff-abort-fence-v2'),
175
+ checkpointId:blocked.handoffFence.checkpointId,
176
+ fencedBindingRevision:blocked.handoffFence.fencedBindingRevision
177
+ }).catch(()=>null);
178
+ const fenced=await scopedVerifyAbortedHandoffFence(blocked);
179
+ const released=fenced
180
+ ?await resources.releaseReservedChat({
181
+ ...blocked,token:blocked.turnToken},sender.tab.id)
182
+ .catch(()=>({released:false}))
183
+ :{released:false};
184
+ if(released.released===true){
185
+ // Loss of this Worker ACK affects quota bookkeeping only. A
186
+ // future Alarm must never delete the pre-send NOT_SENT receipt.
187
+ const current=await scopedTaskRuns.get(run.projectId,run.taskId);
188
+ if(current.runRevision===frozen.runRevision)
189
+ await scopedTaskRuns.put({...blocked,
190
+ resourceHoldSettledAt:Date.now()},{
191
+ expectedStoreRevision:current.storeRevision,
192
+ expectedRunRevision:current.runRevision}).catch(()=>null);
193
+ }
194
+ return {status:'BLOCKED',
195
+ code:fenced?'SCOPED_HANDOFF_PRE_SEND_FENCED':'SCOPED_HANDOFF_ABORT_NATIVE_UNKNOWN',
196
+ resourceHoldReleased:released.released===true};
197
+ }
198
+ if(type==='CHAT_LOOP_TASK_HANDOFF_CHAT_V2'){
199
+ scopedHandoffAssert(['preflight','register'].includes(message.stage)
200
+ &&(message.stage==='preflight'
201
+ ?Object.keys(message).length===4
202
+ :Object.keys(message).length===5
203
+ &&Number.isSafeInteger(message.newTabId)),
204
+ 'SCOPED_HANDOFF_RESOURCE_REQUEST_INVALID');
205
+ const projection={...run,token:run.turnToken};
206
+ if(message.stage==='preflight'){
207
+ // This is now ONLY a read of the hold committed before TAKE.
208
+ // Never create new capacity AFTER the Context Writer is fenced.
209
+ const reserved=await resources.verifyScopedHandoffHold(
210
+ run,sender.tab.id);
211
+ return reserved?{status:'OK',scope:'TASK_SCOPED_CHAT_RESERVED'}
212
+ :{status:'DENIED',code:'SCOPED_HANDOFF_HOLD_UNVERIFIED'};
213
+ }
214
+ const tab=await chrome.tabs.get(message.newTabId).catch(()=>null);
215
+ const registered=tab&&tab.url==='https://chatgpt.com/'
216
+ &&tab.openerTabId===sender.tab.id
217
+ &&await resources.registerReservedChat(tab,projection);
218
+ return registered?{status:'OK',scope:'TASK_SCOPED_CHAT_REGISTERED'}
219
+ :{status:'DENIED',code:'SCOPED_CHAT_REGISTRATION_UNVERIFIED'};
220
+ }
221
+ if(type==='CHAT_LOOP_TASK_HANDOFF_SEND_BEGIN_V2'){
222
+ scopedHandoffAssert(Object.keys(message).length===3
223
+ &&run.modelIntent.state==='TAKEN'
224
+ &&run.nextAttempt.sendBeginAt===null,
225
+ 'SCOPED_HANDOFF_SEND_ALREADY_BEGUN');
226
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
227
+ ...scopedHandoffNative(run,'handoff-send-check-v2'),
228
+ checkpointId:run.handoffFence.checkpointId,
229
+ fencedBindingRevision:run.handoffFence.fencedBindingRevision
230
+ }).catch(()=>null);
231
+ scopedHandoffAssert(proof?.status==='SEND_ALLOWED'
232
+ &&proof.scope==='TASK_SCOPED_HANDOFF_ONCE'
233
+ &&proof.nativeOwnerRevision===run.nativeOwnerRevision,
234
+ 'SCOPED_HANDOFF_SEND_FENCE_UNVERIFIED');
235
+ await scopedTaskRuns.put({...run,modelIntent:{
236
+ ...run.modelIntent,state:'SEND_BEGIN'},
237
+ nextAttempt:{...run.nextAttempt,sendBeginAt:Date.now()}},{
238
+ expectedStoreRevision:snapshot.storeRevision,
239
+ expectedRunRevision:snapshot.runRevision});
240
+ return {status:'RECORDED',scope:'TASK_SCOPED_HANDOFF_SEND_BEGIN'};
241
+ }
242
+ if(type==='CHAT_LOOP_TASK_HANDOFF_RESULT_V2'){
243
+ scopedHandoffAssert(Object.keys(message).length===8
244
+ &&typeof message.nextRunCredential==='string'
245
+ &&/^[0-9a-f]{64}$/.test(message.nextRunCredential)
246
+ &&run.modelIntent.state==='SEND_BEGIN'
247
+ &&Number.isSafeInteger(run.nextAttempt.sendBeginAt)
248
+ &&run.nextAttempt.sendBeginAt>0,
249
+ 'SCOPED_HANDOFF_RESULT_SOURCE_INVALID');
250
+ const target=await chrome.tabs.get(message.newTabId).catch(()=>null);
251
+ const page=target&&pathOf(target.url),newId=target&&chatIdOf(target.url);
252
+ const confirmed=message.result==='SENT_CONFIRMED'
253
+ &&Number.isSafeInteger(message.newTabId)
254
+ &&target?.openerTabId===sender.tab.id
255
+ &&newId&&newId!==run.ownerChatId
256
+ &&page===message.newPage
257
+ &&/^\/c\/[0-9a-f-]{12,}$/i.test(page||'')
258
+ &&await taskActionVerifyBrowserReceipt(run,
259
+ message.newUserKey,message.newTabId,page);
260
+ if(!confirmed){
261
+ await scopedTaskRuns.put({...run,phase:'BLOCKED',
262
+ lastIntentReceipt:{turnToken:run.turnToken,id:run.modelIntent.id,
263
+ action:'HANDOFF',status:'UNKNOWN',updatedAt:Date.now()},
264
+ modelIntent:{...run.modelIntent,state:'ACTION_UNVERIFIED'}},{
265
+ expectedStoreRevision:snapshot.storeRevision,
266
+ expectedRunRevision:snapshot.runRevision});
267
+ return {status:'BLOCKED',code:'SCOPED_HANDOFF_RESULT_UNKNOWN'};
268
+ }
269
+ scopedHandoffAssert(!run.handoffReceipt,
270
+ 'SCOPED_HANDOFF_RECEIPT_ALREADY_RECORDED');
271
+ // The new Chat's DOM send is independently proven. Persist only
272
+ // its exact URL/Tab/User identity BEFORE Native/Context commits the
273
+ // new generation, so a lost IPC ACK is read-only reconcilable.
274
+ // Never persist the successor Writer credential here.
275
+ const recorded={...run,handoffReceipt:{
276
+ newTabId:message.newTabId,newPage:page,
277
+ newUserKey:message.newUserKey,observedAt:Date.now()}};
278
+ const persisted=await scopedTaskRuns.put(recorded,{
279
+ expectedStoreRevision:snapshot.storeRevision,
280
+ expectedRunRevision:snapshot.runRevision});
281
+ const verified=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
282
+ ...scopedHandoffNative(run,'handoff-result-v2'),
283
+ checkpointId:run.handoffFence.checkpointId,
284
+ fencedBindingRevision:run.handoffFence.fencedBindingRevision,
285
+ nextRunCredential:message.nextRunCredential,
286
+ newChatUrl:'https://chatgpt.com'+page,
287
+ newUserKey:message.newUserKey,
288
+ sourceUserKey:run.nextAttempt.sourceUserKey
289
+ }).catch(()=>null);
290
+ scopedHandoffAssert(verified?.status==='CONFIRMED'
291
+ &&verified.scope==='TASK_SCOPED_HANDOFF_RECEIPT'
292
+ &&verified.generation===run.generation+1
293
+ &&verified.nativeOwnerRevision===run.nativeOwnerRevision+1
294
+ &&verified.bindingRevision===run.handoffFence.fencedBindingRevision+1,
295
+ 'SCOPED_HANDOFF_BIND_UNKNOWN');
296
+ const next=scopedHandoffSuccessorRun(recorded,{
297
+ generation:verified.generation,
298
+ nativeOwnerRevision:verified.nativeOwnerRevision,
299
+ contextBindingRevision:verified.bindingRevision,
300
+ ownerChatId:newId,tabId:message.newTabId,page,
301
+ userKey:message.newUserKey});
302
+ await scopedTaskRuns.put(next,{
303
+ expectedStoreRevision:persisted.storeRevision,
304
+ expectedRunRevision:persisted.runRevision});
305
+ // Quota inventory is downstream evidence. An unavailable
306
+ // inventory must not override a confirmed Native+Context transfer
307
+ // or accidentally cause another attempt to send.
308
+ await scopedSettleHandoffResources(run.projectId,run.taskId).catch(()=>false);
309
+ // The new Chat's first user Turn can finish while Native/Context are
310
+ // still transferring ownership. Re-arm that *same* Turn after
311
+ // CommitProof, otherwise its sole Observer event may have been
312
+ // rejected as unowned and the new Task would stay silent forever.
313
+ // This is a read-only Observer poll, never a second Chat send.
314
+ const monitoring=await chrome.tabs.sendMessage(message.newTabId,{
315
+ type:'CHAT_LOOP_TURN_RESUME_V1',page,
316
+ userKey:message.newUserKey,assistantKey:null,
317
+ startedAt:next.startedAt}).catch(()=>null);
318
+ return {status:'OK',scope:'TASK_SCOPED_HANDOFF_CONFIRMED',
319
+ observer:monitoring?.status==='RESUMED'
320
+ ||monitoring?.status==='ALREADY_MONITORING'
321
+ ?'MONITORING':'UNVERIFIED'};
322
+ }
323
+ throw scopedHandoffFail('SCOPED_HANDOFF_MESSAGE_UNKNOWN');
324
+ });
325
+ }
@@ -0,0 +1,109 @@
1
+ // Same existing minute Alarm, no second scheduler or Resource writer.
2
+ // A proven pre-SEND_BEGIN Handoff abort can release its unused Chat seat,
3
+ // but NEVER restores or removes a BLOCKED Native/Context Owner.
4
+ // Native rechecks the original signed Handoff + consumed Permit + exact
5
+ // Context checkpoint before a Worker-local NOT_SENT receipt affects quota.
6
+ async function scopedVerifyAbortedHandoffFence(run){
7
+ if(run?.phase!=='BLOCKED'||!run.preSendAbort
8
+ ||run.lastIntentReceipt?.status!=='NOT_SENT'
9
+ ||run.preSendAbort.id!==run.modelIntent?.id
10
+ ||run.nextAttempt?.sendBeginAt!==null
11
+ ||!run.handoffFence)return false;
12
+ const result=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
13
+ ...scopedHandoffNative(run,'handoff-abort-fence-read-v2'),
14
+ checkpointId:run.handoffFence.checkpointId,
15
+ fencedBindingRevision:run.handoffFence.fencedBindingRevision
16
+ }).catch(()=>null);
17
+ return result?.status==='REVOKED'
18
+ &&result.scope==='TASK_SCOPED_HANDOFF_ABORT_REVOKED'
19
+ &&result.readOnly===true
20
+ &&result.projectId===run.projectId&&result.taskId===run.taskId
21
+ &&result.sessionId===run.sessionId
22
+ &&result.generation===run.generation
23
+ &&result.nativeOwnerRevision===run.nativeOwnerRevision+1
24
+ &&result.contextBindingRevision===run.handoffFence.fencedBindingRevision;
25
+ }
26
+ async function reconcileScopedAbortedHolds(){
27
+ if(!scopedTaskRuns||!scopedTaskScheduler)return;
28
+ const store=await scopedTaskRuns.read();
29
+ const candidates=Object.values(store.items).filter(({run})=>
30
+ run.phase==='BLOCKED'&&Boolean(run.preSendAbort)
31
+ &&run.resourceHoldSettledAt===undefined);
32
+ const outcomes=await Promise.allSettled(candidates.map(({run,revision})=>
33
+ scopedTaskScheduler.perTask(run.projectId,run.taskId,async()=>{
34
+ const current=await scopedTaskRuns.get(run.projectId,run.taskId);
35
+ const s=current.run;
36
+ if(current.runRevision!==revision
37
+ ||s?.phase!=='BLOCKED'
38
+ ||s.preSendAbort?.id!==run.preSendAbort.id
39
+ ||s.preSendAbort.actionTabId!==run.preSendAbort.actionTabId
40
+ ||s.nextAttempt?.sendBeginAt!==null
41
+ ||!await scopedVerifyAbortedHandoffFence(s))return;
42
+ const released=await resources.releaseReservedChat({
43
+ ...s,token:s.turnToken},s.preSendAbort.actionTabId);
44
+ if(released?.released===true){
45
+ // Preserve permanent NOT_SENT evidence for Stage 06; settle only
46
+ // the physical quota, never remove the Task's recovery proof.
47
+ const next={...s,resourceHoldSettledAt:Date.now()};
48
+ await scopedTaskRuns.put(next,{
49
+ expectedStoreRevision:current.storeRevision,
50
+ expectedRunRevision:current.runRevision});
51
+ }
52
+ })));
53
+ for(const item of outcomes)if(item.status==='rejected')
54
+ console.warn('TASK_PRE_SEND_HOLD_RECONCILE_UNVERIFIED',
55
+ safeWorkerErrorCode(item.reason,'RESOURCE_HOLD_UNVERIFIED'));
56
+ }
57
+ // One Resource Ledger and one Native Owner: a Worker terminal snapshot
58
+ // alone cannot authorize releasing the old physical Chat seat.
59
+ async function scopedTerminalOwnerVerified(run){
60
+ if(!['DONE','BLOCKED','CANCELLED'].includes(run?.phase)
61
+ ||!run.ownerChatId||!Number.isSafeInteger(run.tabId))return false;
62
+ const native=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
63
+ op:'session-snapshot-v2',projectId:run.projectId,
64
+ taskId:run.taskId,sessionId:run.sessionId,
65
+ generation:run.generation}).catch(()=>null);
66
+ const owner=native?.session;
67
+ return native?.status==='OK'&&native.scope==='TASK_SCOPED_SNAPSHOT'
68
+ &&owner?.projectId===run.projectId&&owner.taskId===run.taskId
69
+ &&owner.sessionId===run.sessionId
70
+ &&owner.generation===run.generation
71
+ &&owner.revision===run.nativeOwnerRevision
72
+ &&owner.phase===run.phase
73
+ &&owner.activeChatId===run.ownerChatId
74
+ &&owner.activeChatUrl==='https://chatgpt.com'+run.page;
75
+ }
76
+ const scopedUnsettledTerminalEntries=(inventory,run)=>
77
+ inventory.state.entries.some(entry=>entry.kind==='chat'
78
+ &&entry.sessionId===run.sessionId
79
+ &&entry.projectId===run.projectId&&entry.taskId===run.taskId
80
+ &&entry.terminal!==run.phase);
81
+ async function reconcileScopedResourceInventory(){
82
+ if(!scopedTaskRuns)return;
83
+ const store=await scopedTaskRuns.read();
84
+ const runs=Object.values(store.items).map(({run})=>run);
85
+ if(!runs.length)return;
86
+ const inventory=await resources.reconcile(runs);
87
+ let repaired=false;
88
+ for(const run of runs){
89
+ // An earlier resources.terminal ACK may have been lost after the
90
+ // Worker CAS. A pre-send Handoff BLOCKED has Native PENDING and
91
+ // therefore fails the independently scoped terminal proof.
92
+ if(scopedUnsettledTerminalEntries(inventory,run)
93
+ &&await scopedTerminalOwnerVerified(run)){
94
+ await resources.terminal(run);
95
+ repaired=true;
96
+ }
97
+ }
98
+ if(repaired)await resources.reconcile(runs,{reap:false});
99
+ }
100
+ // Before retiring the Native terminal witness, settle the original
101
+ // Resource Ledger. Failure cannot remove a Task or release a Writer.
102
+ async function scopedEnsureTerminalQuota(run){
103
+ if(!await scopedTerminalOwnerVerified(run))return false;
104
+ await resources.terminal(run);
105
+ const store=await scopedTaskRuns.read();
106
+ const runs=Object.values(store.items).map(({run})=>run);
107
+ const inventory=await resources.reconcile(runs,{reap:false});
108
+ return !scopedUnsettledTerminalEntries(inventory,run);
109
+ }
@@ -0,0 +1,220 @@
1
+ // A signed model intent is registered DURING its assistant Turn. Only
2
+ // the completed, stable original Chat Turn may create the existing formal
3
+ // Continue/Handoff Action. No Action, Context Permit or sender is created
4
+ // at model-intent registration time. Caller owns the per-Task queue.
5
+ async function scopedLaunchReadyIntent(projectId,taskId){
6
+ const snapshot=await scopedTaskRuns.get(projectId,taskId);
7
+ const run=snapshot.run,intent=run?.modelIntent,observed=run?.lastObservedTurn;
8
+ // The original resource transfer is a derived receipt, not a second
9
+ // owner. Do not consume another Handoff permit until its seat is settled.
10
+ if(run?.resourceTransfer&&intent?.action==='HANDOFF')
11
+ return {status:'BLOCKED',code:'SCOPED_HANDOFF_RESOURCE_TRANSFER_PENDING'};
12
+ if(!run||run.phase!=='WAITING_REPLY'
13
+ ||!['QUEUED','CAPACITY_BLOCKED'].includes(intent?.state)
14
+ ||intent.actionTabId!==null
15
+ ||!observed||observed.pendingConfirmation!==false
16
+ ||intent.targetUserKey!==observed.userKey
17
+ ||observed.outcome!==intent.action
18
+ ||observed.page!==run.page)return {
19
+ status:'NOT_READY',scope:'TASK_SCOPED_INTENT_OBSERVER_PENDING'};
20
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
21
+ scopedIntentAssert(tab&&pathOf(tab.url)===run.page,
22
+ 'SCOPED_INTENT_DISPATCH_TAB_CHANGED');
23
+ const route=await scopedTaskOwnerResolver.resolve({
24
+ id:chrome.runtime.id,frameId:0,
25
+ tab:{id:run.tabId},url:tab.url});
26
+ scopedIntentAssert(route.projectId===run.projectId
27
+ &&route.taskId===run.taskId
28
+ &&route.sessionId===run.sessionId
29
+ &&route.generation===run.generation
30
+ &&route.runRevision===snapshot.runRevision
31
+ &&route.nativeOwnerRevision===run.nativeOwnerRevision
32
+ &&route.contextStoreEpoch===run.contextStoreEpoch,
33
+ 'SCOPED_INTENT_DISPATCH_OWNER_CHANGED');
34
+ const read=()=>chrome.tabs.sendMessage(run.tabId,{
35
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
36
+ const first=await read();
37
+ await new Promise(resolve=>setTimeout(resolve,350));
38
+ const second=await read();
39
+ scopedIntentAssert(first?.contract==='chat-loop.turn-observer.v1'
40
+ &&first.status==='READY'
41
+ &&second?.status==='READY'
42
+ &&first.page===run.page&&second.page===run.page
43
+ &&first.userKey===intent.targetUserKey
44
+ &&first.assistantKey===observed.assistantKey
45
+ &&second.userKey===first.userKey
46
+ &&second.assistantKey===first.assistantKey
47
+ &&first.replyText===second.replyText
48
+ &&first.pendingConfirmation===false
49
+ &&second.pendingConfirmation===false
50
+ &&workerApi.parseStatus(first.replyText)===intent.action,
51
+ 'SCOPED_INTENT_DISPATCH_TURN_CHANGED');
52
+ const latest=await scopedTaskRuns.get(run.projectId,run.taskId);
53
+ scopedIntentAssert(latest.runRevision===snapshot.runRevision,
54
+ 'SCOPED_INTENT_DISPATCH_RUN_STALE');
55
+ // Durable LAUNCHING BEFORE chrome.tabs.create. If Chrome creates the
56
+ // page but loses its tab/registration ACK, NEVER open a second Action.
57
+ const launching=await scopedTaskRuns.put({...run,modelIntent:{
58
+ ...intent,state:'LAUNCHING'}},{
59
+ expectedStoreRevision:latest.storeRevision,
60
+ expectedRunRevision:latest.runRevision});
61
+ const url=chrome.runtime.getURL(intent.action.toLowerCase()+'.html')
62
+ +'?tabId='+run.tabId+'&token='+run.turnToken+'&taskFirst=1';
63
+ let receipt;
64
+ try{
65
+ receipt=await resources.withRegisteredAction(run,{url,
66
+ create:()=>chrome.tabs.create({url,active:false,
67
+ windowId:tab.windowId})});
68
+ }catch{receipt={ok:false,code:'SCOPED_INTENT_ACTION_CREATE_UNKNOWN'};}
69
+ const after=await scopedTaskRuns.get(run.projectId,run.taskId);
70
+ scopedIntentAssert(after.runRevision===launching.runRevision
71
+ &&after.run.modelIntent?.id===intent.id
72
+ &&after.run.modelIntent.state==='LAUNCHING',
73
+ 'SCOPED_INTENT_ACTION_STATE_CHANGED');
74
+ if(!receipt?.ok||!Number.isSafeInteger(receipt.tab?.id)
75
+ ||receipt.tab.id<=0){
76
+ // Quota denial happens BEFORE chrome.tabs.create, and is therefore
77
+ // safely retriable after capacity changes. A missing tab ACK after a
78
+ // create attempt is UNKNOWN: never create a second Action page.
79
+ const capacityOnly=!receipt?.tab
80
+ &&['RESOURCE_ACTION_LIMIT','RESOURCE_CHAT_LIMIT']
81
+ .includes(receipt?.code);
82
+ await scopedTaskRuns.put({...after.run,modelIntent:{
83
+ ...after.run.modelIntent,state:capacityOnly
84
+ ?'CAPACITY_BLOCKED':'ACTION_UNVERIFIED'}},{
85
+ expectedStoreRevision:after.storeRevision,
86
+ expectedRunRevision:after.runRevision});
87
+ return {status:'BLOCKED',
88
+ code:receipt?.code||'SCOPED_INTENT_ACTION_UNKNOWN'};
89
+ }
90
+ await scopedTaskRuns.put({...after.run,modelIntent:{
91
+ ...after.run.modelIntent,state:'QUEUED',
92
+ actionTabId:receipt.tab.id}},{
93
+ expectedStoreRevision:after.storeRevision,
94
+ expectedRunRevision:after.runRevision});
95
+ return {status:'PREPARED',scope:'TASK_SCOPED_INTENT_ACTION_READY',
96
+ intentId:intent.id,action:intent.action};
97
+ }
98
+
99
+ // Only a signed but UNLAUNCHED model proposal may be settled after the
100
+ // assistant's actual final Turn disagrees with the proposed next action.
101
+ // No Action is created, no Context Permit is consumed, and no send occurs.
102
+ async function scopedSettleMismatchedIntent(projectId,taskId){
103
+ const snapshot=await scopedTaskRuns.get(projectId,taskId);
104
+ const run=snapshot.run,intent=run?.modelIntent,seen=run?.lastObservedTurn;
105
+ if(!run||run.phase!=='WAITING_REPLY'
106
+ ||!['QUEUED','CAPACITY_BLOCKED'].includes(intent?.state)
107
+ ||intent.actionTabId!==null
108
+ ||!seen||seen.pendingConfirmation!==false
109
+ ||seen.userKey!==intent.targetUserKey
110
+ ||seen.outcome===intent.action
111
+ ||!['CONTINUE','HANDOFF','UNKNOWN'].includes(seen.outcome))
112
+ return {status:'NOT_APPLICABLE'};
113
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
114
+ scopedIntentAssert(tab&&pathOf(tab.url)===run.page,
115
+ 'SCOPED_INTENT_MISMATCH_TAB_CHANGED');
116
+ const route=await scopedTaskOwnerResolver.resolve({
117
+ id:chrome.runtime.id,frameId:0,tab:{id:run.tabId},url:tab.url});
118
+ scopedIntentAssert(route.runRevision===snapshot.runRevision
119
+ &&route.projectId===run.projectId&&route.taskId===run.taskId
120
+ &&route.nativeOwnerRevision===run.nativeOwnerRevision,
121
+ 'SCOPED_INTENT_MISMATCH_OWNER_CHANGED');
122
+ const read=()=>chrome.tabs.sendMessage(run.tabId,{
123
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
124
+ const first=await read();
125
+ await new Promise(resolve=>setTimeout(resolve,350));
126
+ const second=await read();
127
+ scopedIntentAssert(first?.status==='READY'&&second?.status==='READY'
128
+ &&first.userKey===intent.targetUserKey
129
+ &&first.assistantKey===seen.assistantKey
130
+ &&second.userKey===first.userKey
131
+ &&second.assistantKey===first.assistantKey
132
+ &&first.replyText===second.replyText
133
+ &&first.pendingConfirmation===false
134
+ &&second.pendingConfirmation===false
135
+ &&workerApi.parseStatus(first.replyText)===seen.outcome,
136
+ 'SCOPED_INTENT_MISMATCH_TURN_UNVERIFIED');
137
+ const fresh=await scopedTaskRuns.get(projectId,taskId);
138
+ scopedIntentAssert(fresh.runRevision===snapshot.runRevision,
139
+ 'SCOPED_INTENT_MISMATCH_RUN_STALE');
140
+ const next={...run,lastIntentReceipt:{
141
+ id:intent.id,action:intent.action,turnToken:intent.turnToken,
142
+ status:'NOT_SENT',updatedAt:Date.now()}};
143
+ delete next.modelIntent;
144
+ await scopedTaskRuns.put(next,{
145
+ expectedStoreRevision:fresh.storeRevision,
146
+ expectedRunRevision:fresh.runRevision});
147
+ return {status:'NOT_SENT',scope:'TASK_SCOPED_INTENT_MISMATCH'};
148
+ }
149
+
150
+ // An Action tab may exist when chrome.tabs.create/register lost its ACK.
151
+ // NEVER create a second one. Find exactly one real tab bearing the
152
+ // original signed, Task-specific URL and bind that existing Action only.
153
+ async function scopedRecoverLaunchedIntent(projectId,taskId){
154
+ const snapshot=await scopedTaskRuns.get(projectId,taskId);
155
+ const run=snapshot.run,intent=run?.modelIntent;
156
+ if(!run||run.phase!=='WAITING_REPLY'
157
+ ||!['LAUNCHING','ACTION_UNVERIFIED'].includes(intent?.state)
158
+ ||intent.actionTabId!==null||run.nextAttempt||run.handoffFence
159
+ ||run.lastObservedTurn?.userKey!==intent.targetUserKey
160
+ ||run.lastObservedTurn?.outcome!==intent.action
161
+ ||run.lastObservedTurn.pendingConfirmation!==false)
162
+ return {status:'NOT_APPLICABLE'};
163
+ const original=await chrome.tabs.get(run.tabId).catch(()=>null);
164
+ scopedIntentAssert(original&&pathOf(original.url)===run.page,
165
+ 'SCOPED_INTENT_RECOVERY_CHAT_CHANGED');
166
+ const route=await scopedTaskOwnerResolver.resolve({
167
+ id:chrome.runtime.id,frameId:0,
168
+ tab:{id:run.tabId},url:original.url});
169
+ scopedIntentAssert(route.runRevision===snapshot.runRevision
170
+ &&route.projectId===run.projectId&&route.taskId===run.taskId
171
+ &&route.nativeOwnerRevision===run.nativeOwnerRevision,
172
+ 'SCOPED_INTENT_RECOVERY_OWNER_CHANGED');
173
+ const source=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
174
+ op:'acquire',id:intent.id,action:intent.action.toLowerCase()
175
+ }).catch(()=>null);
176
+ scopedIntentAssert(source?.status==='OK'
177
+ &&source.intent?.taskFirst===true
178
+ &&source.intent.turnToken===intent.turnToken,
179
+ 'SCOPED_INTENT_RECOVERY_SOURCE_UNKNOWN');
180
+ const read=()=>chrome.tabs.sendMessage(run.tabId,{
181
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
182
+ const a=await read();
183
+ await new Promise(resolve=>setTimeout(resolve,350));
184
+ const b=await read();
185
+ scopedIntentAssert(a?.status==='READY'&&b?.status==='READY'
186
+ &&a.page===run.page&&b.page===run.page
187
+ &&a.userKey===intent.targetUserKey
188
+ &&a.assistantKey===run.lastObservedTurn.assistantKey
189
+ &&b.userKey===a.userKey&&b.assistantKey===a.assistantKey
190
+ &&a.replyText===b.replyText
191
+ &&workerApi.parseStatus(a.replyText)===intent.action,
192
+ 'SCOPED_INTENT_RECOVERY_TURN_UNKNOWN');
193
+ const url=chrome.runtime.getURL(intent.action.toLowerCase()+'.html')
194
+ +'?tabId='+run.tabId+'&token='+run.turnToken+'&taskFirst=1';
195
+ const found=(await chrome.tabs.query({})).filter(t=>
196
+ Number.isSafeInteger(t.id)&&t.url===url
197
+ &&t.windowId===original.windowId);
198
+ // Zero or duplicate pages mean UNKNOWN, not permission to re-create one.
199
+ if(found.length!==1)return {status:'BLOCKED',
200
+ code:found.length?'SCOPED_INTENT_TABS_AMBIGUOUS'
201
+ :'SCOPED_INTENT_CREATED_TAB_UNVERIFIED'};
202
+ const registered=await resources.registerAction({
203
+ id:found[0].id,url});
204
+ scopedIntentAssert(registered===true,
205
+ 'SCOPED_INTENT_RESOURCE_REGISTRATION_UNKNOWN');
206
+ const fresh=await scopedTaskRuns.get(projectId,taskId);
207
+ scopedIntentAssert(fresh.runRevision===snapshot.runRevision,
208
+ 'SCOPED_INTENT_RECOVERY_RUN_CHANGED');
209
+ await scopedTaskRuns.put({...run,modelIntent:{
210
+ ...intent,state:'QUEUED',actionTabId:found[0].id}},{
211
+ expectedStoreRevision:fresh.storeRevision,
212
+ expectedRunRevision:fresh.runRevision});
213
+ // Reuse the existing Action tab, not a new tab/Chat/Token. Its TAKE
214
+ // still must independently obtain the original Context+Native Permit.
215
+ const unchanged=await chrome.tabs.get(found[0].id).catch(()=>null);
216
+ if(unchanged?.url===url&&unchanged.windowId===original.windowId)
217
+ await chrome.tabs.reload(found[0].id).catch(()=>null);
218
+ return {status:'RECOVERED',
219
+ scope:'TASK_SCOPED_EXISTING_ACTION_TAB'};
220
+ }