@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,296 @@
1
+ // Chat Loop Worker — adopt-prepare. Imported in order by background.js; no independent Browser Owner.
2
+ async function sessionStartPrepare(message,sender){
3
+ if(!sessionPage(sender,'start',message.requestId))
4
+ return {status:'DENIED',code:'INVALID_START_SOURCE'};
5
+ const prior=await readRun();
6
+ // Read the single authenticated intent BEFORE deciding whether a previously
7
+ // BLOCKED session can be explicitly superseded. Never infer consent from
8
+ // a failed page or an old session pointer alone.
9
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,
10
+ {op:'acquire',id:message.requestId,action:'start'}).catch(()=>null);
11
+ const intent=proof?.intent;
12
+ if(proof?.status!=='OK'||intent?.confirmed!==true
13
+ ||typeof intent.projectId!=='string'
14
+ ||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.projectId)
15
+ ||(intent.taskId!==undefined
16
+ && !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.taskId))
17
+ ||(intent.purpose!==undefined
18
+ &&(intent.purpose!=='REPAIR_SAME_SCOPE'||intent.mode!=='adopt'
19
+ ||!intent.taskId||!intent.contextLeaseRef))
20
+ ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
21
+ .some(k=>Object.hasOwn(intent,k))
22
+ &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
23
+ ||intent.contextLeaseRef.length<8||typeof intent.contextStoreEpoch!=='string'
24
+ ||intent.contextStoreEpoch.length<10
25
+ ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
26
+ ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
27
+ ||(intent.chatUrl!==undefined
28
+ && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'
29
+ ||!pathOf(intent.chatUrl)
30
+ ||intent.chatUrl!=='https://chatgpt.com'+pathOf(intent.chatUrl)))
31
+ ||(intent.mode==='adopt' ? Object.hasOwn(intent,'prompt')
32
+ : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000)
33
+ ||(intent.mode!==undefined && intent.mode!=='adopt')
34
+ ||(intent.replaceBlockedSessionId!==undefined
35
+ && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId)))
36
+ return {status:'DENIED',code:'START_INTENT_UNVERIFIED'};
37
+ // Native DONE is required before the private terminal fence IPC, but
38
+ // DONE without CONFIRMED fencing must never release Start admission.
39
+ if(prior?.contextManaged && prior.taskId
40
+ && (prior.contextTerminalFence==='UNVERIFIED'
41
+ || prior.phase==='DONE'&&!terminalFenceVerified(prior)))
42
+ return {status:'DENIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
43
+ const replace=intent.replaceBlockedSessionId||null;
44
+ // Project is shared context, not Task identity. Same-Project replacement
45
+ // requires a freshly approved, Context-backed Adopt into a distinct Task.
46
+ // Legacy sessions without taskId can only yield to that verified new Task.
47
+ const independentTask=Boolean(intent.mode==='adopt'&&intent.contextLeaseRef
48
+ &&intent.taskId && (!prior?.taskId && !prior?.contextManaged
49
+ ||prior?.taskId&&prior.taskId!==intent.taskId));
50
+ // A first Adopt that failed BEFORE permit.consume completed has no Chat
51
+ // send, tab binding, or Context writer. A fresh Context lease (which
52
+ // independently requires runRef=null) may replace this exact BLOCKED
53
+ // pre-permit Session at most once for the SAME approved Task. Unknown
54
+ // post-permit / browser outcomes are never eligible for this route.
55
+ const prePermitRecovery=Boolean(prior?.phase==='BLOCKED'
56
+ &&prior.reason==='CONTEXT_START_PERMIT_UNVERIFIED'
57
+ &&prior.action==='START'&&prior.mode==='adopt'
58
+ &&prior.contextLeaseRef&&!prior.prePermitRetryUsed
59
+ &&!prior.contextManaged&&prior.projectId===intent.projectId
60
+ &&prior.taskId===intent.taskId&&intent.mode==='adopt'
61
+ &&intent.contextLeaseRef&&intent.contextLeaseRef!==prior.contextLeaseRef
62
+ &&prior.contextStoreEpoch===intent.contextStoreEpoch
63
+ &&prior.contextTaskRevision===intent.contextTaskRevision
64
+ &&prior.contextApprovalRevision===intent.contextApprovalRevision
65
+ &&prior.generation===0&&prior.tabId===null&&prior.page==='/'&&!prior.newUserKey
66
+ &&!prior.userKey&&!prior.assistantKey&&!prior.attemptedNewTabId&&!prior.lastStartActionTabId
67
+ &&!!intent.chatUrl&&prior.adoptPage===pathOf(intent.chatUrl)
68
+ &&Number.isInteger(prior.adoptTabId)
69
+ &&typeof prior.adoptUserKey==='string');
70
+ // If the previous pre-permit replacement wrote Worker STARTING but Native
71
+ // rejected its CAS, Worker/Native disagree. No send was attempted, but this
72
+ // is NOT a free retry: one exact native-BLOCKED repair with a fresh lease
73
+ // is allowed; any managed writer, late send or second repair remains denied.
74
+ const timedOutGhost=prior?.phase==='BLOCKED'
75
+ &&prior.reason==='ACTION_RESULT_TIMEOUT_UNVERIFIED';
76
+ const preNativeGhost=Boolean((prior?.phase==='STARTING'||timedOutGhost)
77
+ &&prior.action==='START'&&prior.mode==='adopt'
78
+ &&prior.prePermitRetryUsed===true&&!prior.preNativeRepairUsed
79
+ &&prior.replacedBlockedSessionId===replace
80
+ &&prior.sessionId!==replace&&prior.contextLeaseRef
81
+ &&intent.contextLeaseRef&&intent.contextLeaseRef!==prior.contextLeaseRef
82
+ &&!prior.contextManaged&&prior.projectId===intent.projectId
83
+ &&prior.taskId===intent.taskId
84
+ &&prior.contextStoreEpoch===intent.contextStoreEpoch
85
+ &&prior.contextTaskRevision===intent.contextTaskRevision
86
+ &&prior.contextApprovalRevision===intent.contextApprovalRevision
87
+ &&prior.generation===0&&prior.tabId===null&&prior.page==='/'&&!prior.newUserKey
88
+ &&!prior.userKey&&!prior.assistantKey&&!prior.attemptedNewTabId&&!prior.lastStartActionTabId
89
+ &&!!intent.chatUrl&&prior.adoptPage===pathOf(intent.chatUrl)
90
+ &&Number.isInteger(prior.adoptTabId)
91
+ &&typeof prior.adoptUserKey==='string');
92
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
93
+ if(disk?.status!=='OK')return {status:'DENIED',code:'SESSION_STATE_UNVERIFIED'};
94
+ // A Worker ghost from a timed-out, no-send Adopt may disagree with the
95
+ // durable Native BLOCKED ID. Only an independently approved DIFFERENT Task
96
+ // may supersede the exact Native pointer, never the same old Task or Chat.
97
+ const driftReplacement=Boolean(independentTask&&replace
98
+ &&replace===disk.session?.sessionId
99
+ &&independentBlockedAdoptDrift(prior,disk.session)
100
+ &&!!intent.chatUrl&&pathOf(intent.chatUrl)!==prior.adoptPage);
101
+ const matchingBlocked=Boolean(prior?.phase==='BLOCKED'
102
+ &&prior.sessionId===replace
103
+ &&(prior.projectId!==intent.projectId||independentTask
104
+ ||prePermitRecovery)||preNativeGhost||driftReplacement);
105
+ if(replace&&!matchingBlocked)return {status:'DENIED',code:'BLOCKED_REPLACEMENT_MISMATCH'};
106
+ if(prior&&!['DONE','CANCELLED'].includes(prior.phase)&&!matchingBlocked)
107
+ return {status:'DENIED',code:'LOOP_ALREADY_ACTIVE'};
108
+ const ownerMatches=Boolean(prior?.sessionId&&disk.session
109
+ &&matchesNativeProjection(sessionProjection(prior),disk.session));
110
+ const sameTaskNative=Boolean((prePermitRecovery||preNativeGhost)
111
+ &&disk.session?.sessionId===replace&&disk.session.phase==='BLOCKED'
112
+ &&disk.session.projectId===intent.projectId
113
+ &&disk.session.taskId===intent.taskId&&disk.session.generation===0
114
+ &&disk.session.activeChatId===null&&disk.session.activeChatUrl===null
115
+ &&Number.isSafeInteger(disk.session.updatedAt)
116
+ &&disk.session.updatedAt>0);
117
+ if((matchingBlocked&&!(ownerMatches||(preNativeGhost&&sameTaskNative)
118
+ ||driftReplacement))
119
+ ||((prePermitRecovery||preNativeGhost)&&!sameTaskNative)
120
+ ||(preNativeGhost&&timedOutGhost&&!independentBlockedAdoptDrift(prior,disk.session)))
121
+ return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
122
+ if(prePermitRecovery||preNativeGhost){
123
+ // Native's durable old pointer scopes this read. A new lease or null
124
+ // runRef alone cannot prove the old START permit was never consumed.
125
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
126
+ op:'context-control',command:'run.terminalStatus',
127
+ args:{startRecoveryLeaseRef:intent.contextLeaseRef}}).catch(()=>null);
128
+ const s=proof?.result;
129
+ if(proof?.status!=='OK'||s?.projectId!==intent.projectId||s?.taskId!==intent.taskId
130
+ ||s.storeEpoch!==intent.contextStoreEpoch||s.taskRevision!==intent.contextTaskRevision
131
+ ||s.approvalRevision!==intent.contextApprovalRevision||s.bindingRevision!==0
132
+ ||s.runRef!==null||s.unknownEffectCount!==0||s.executionOutcome!==null
133
+ ||s.startRecovery?.status!=='UNBOUND_NO_PERMIT'
134
+ ||s.startRecovery.leaseRef!==intent.contextLeaseRef)
135
+ return {status:'DENIED',code:'START_RECOVERY_PERMIT_UNVERIFIED'};
136
+ }
137
+ // A terminal Worker record cannot authorize a new Start if a different
138
+ // durable Native Owner exists under the same Browser installation.
139
+ if(['DONE','CANCELLED'].includes(prior?.phase)&&prior.sessionId
140
+ &&disk.session&&!ownerMatches)
141
+ return {status:'DENIED',code:'SESSION_OWNER_MISMATCH'};
142
+ if(prior?.phase==='CANCELLED'){
143
+ // Never treat Worker CANCELLED alone as a fresh Start permit.
144
+ const verified=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
145
+ op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
146
+ const canceled=verified?.result?.sessionCancellation;
147
+ if(disk.session?.phase!=='CANCELLED'||verified?.status!=='OK'
148
+ ||verified.result.runRef!==null||canceled?.status!=='CANCELLED_NOT_DELIVERED'
149
+ ||canceled.sessionId!==prior.sessionId
150
+ ||canceled.generation!==prior.generation)
151
+ return {status:'DENIED',code:'CONTEXT_CANCEL_FENCE_UNVERIFIED'};
152
+ }
153
+ // An abandoned Managed Context writer can outlive its Browser Owner.
154
+ // Replacing the Native session without first verifying its terminal fence
155
+ // would strand a live runRef (and an old write credential) in the Store.
156
+ // Never make that replacement based solely on BLOCKED or absent Owner.
157
+ if(matchingBlocked&&prior.contextManaged){
158
+ const terminal=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
159
+ op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
160
+ const state=terminal?.result;
161
+ if(terminal?.status!=='OK'||!state
162
+ ||state.projectId!==prior.projectId||state.taskId!==prior.taskId
163
+ ||state.runRef!==null||state.executionOutcome!=='DONE'
164
+ ||typeof state.deliveryRef!=='string'||!state.deliveryRef)
165
+ return {status:'DENIED',code:'CONTEXT_BLOCKED_RUN_UNFENCED'};
166
+ }
167
+ if(disk.session&&!['DONE','CANCELLED'].includes(disk.session.phase)
168
+ &&!matchingBlocked)
169
+ return {status:'DENIED',code:'SESSION_ALREADY_ACTIVE'};
170
+ const capacity=await resources.admit(prior,{kind:intent.mode==='adopt'?'action':'chat'});
171
+ if(!capacity.ok)return {status:'DENIED',code:capacity.code};
172
+ const adoption=intent.mode==='adopt'
173
+ ?intent.purpose==='REPAIR_SAME_SCOPE'
174
+ ?await approvedRepairTarget(prior,intent)
175
+ :await approvedAdoptionTarget(intent.chatUrl||null,
176
+ intent.contextLeaseRef?intent.taskId:null):null;
177
+ if(adoption?.error)return {status:'DENIED',code:adoption.error};
178
+ if((prePermitRecovery||preNativeGhost)&&adoption?.target?.userKey!==prior.adoptUserKey)
179
+ return {status:'DENIED',code:'START_RECOVERY_APPROVAL_CHANGED'};
180
+ if((matchingBlocked&&adoption?.target?.page===prior.page&&prior.page)
181
+ ||(driftReplacement&&adoption?.target?.page===prior.adoptPage))
182
+ return {status:'DENIED',code:'BLOCKED_REPLACEMENT_CHAT_REUSE'};
183
+ // A Project-scoped Chat cannot safely hand off to the ordinary home route:
184
+ // reject BEFORE claiming Owner instead of failing after four hours.
185
+ // Explicit /g/ intent remains Project-scoped even if Chrome aliases the
186
+ // same conversation under /c/<id>.
187
+ if(intent.mode==='adopt'&&(
188
+ pathOf(intent.chatUrl||'').startsWith('/g/')
189
+ ||adoption?.target?.page?.startsWith('/g/')))
190
+ return {status:'DENIED',code:'AUTO_HANDOFF_ROUTE_UNSUPPORTED'};
191
+ // Replacement must not replay the old Task. A new independent Task may
192
+ // share its Project after exact blocked Owner and Context-fence checks.
193
+ const promptDigest=adoption?null:await startPromptFingerprint(intent.prompt);
194
+ const next={sessionId:crypto.randomUUID(),projectId:intent.projectId,
195
+ ...(intent.taskId?{taskId:intent.taskId}:{}),
196
+ ...(intent.purpose?{purpose:intent.purpose}:{}),
197
+ ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
198
+ contextStoreEpoch:intent.contextStoreEpoch,
199
+ contextTaskRevision:intent.contextTaskRevision,
200
+ contextApprovalRevision:intent.contextApprovalRevision,
201
+ contextInitialCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
202
+ x=>x.toString(16).padStart(2,'0')).join('')}:{}),
203
+ generation:0,phase:'STARTING',action:'START',token:crypto.randomUUID(),
204
+ page:'/',tabId:null,startedAt:Date.now(),
205
+ machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
206
+ ...(matchingBlocked?{replacedBlockedSessionId:replace}:{}),
207
+ ...(prePermitRecovery||preNativeGhost?{
208
+ prePermitRetryUsed:true,
209
+ ...(preNativeGhost?{preNativeRepairUsed:true}:{}),
210
+ sameTaskPrePermitUpdatedAt:disk.session.updatedAt}:{}),
211
+ ...(adoption?{mode:'adopt',adoptTabId:adoption.target.tabId,
212
+ adoptPage:adoption.target.page,adoptUserKey:adoption.target.userKey,
213
+ ...((intent.chatUrl||adoption.target.explicitChatId)
214
+ ?{adoptExplicitChatId:chatIdOf(intent.chatUrl)||adoption.target.explicitChatId}:{}),
215
+ ...(adoption.target.expectedTaskId
216
+ ?{adoptExpectedTaskId:adoption.target.expectedTaskId}:{}),
217
+ adoptPriorAssistantKey:adoption.target.priorAssistantKey,
218
+ adoptPostApprovalAssistantKey:adoption.target.postApprovalAssistantKey||null,
219
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'?{}:{
220
+ adoptRVersion:adoption.target.rVersion,
221
+ adoptPVersion:adoption.target.pVersion}),
222
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'
223
+ ?{repairUserText:adoption.target.repairUserText,
224
+ repairDoneAssistantKey:adoption.target.repairDoneAssistantKey}:{})}
225
+ :{startPrompt:intent.prompt,...(promptDigest?{startPromptDigest:promptDigest}:{})})};
226
+ await saveRun(next); // Reserve BEFORE any new Chrome tab or send.
227
+ return {status:'PREPARED',token:next.token,sessionId:next.sessionId,
228
+ ...(next.taskId?{taskId:next.taskId}:{})};
229
+ }
230
+ async function sessionStartTake(message,sender){
231
+ const run=await readRun();
232
+ if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
233
+ ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
234
+ ||run.phase!=='STARTING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
235
+ // Verify the real R/P source again immediately before asking Context to
236
+ // consume the Start lease. Never persist approval text in Worker storage.
237
+ let approvalEvidence=null;
238
+ if(run.contextLeaseRef&&run.mode==='adopt'
239
+ &&run.purpose!=='REPAIR_SAME_SCOPE'){
240
+ const proof=await chrome.tabs.sendMessage(run.adoptTabId,{
241
+ type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
242
+ ...(run.adoptExplicitChatId?{explicitChatId:run.adoptExplicitChatId}:{}),
243
+ ...(run.adoptExpectedTaskId?{expectedTaskId:run.adoptExpectedTaskId}:{})
244
+ }).catch(()=>null);
245
+ const current=policy.normalizeAdoptionEvidence(proof,{page:run.adoptPage});
246
+ const original={page:run.adoptPage,userKey:run.adoptUserKey,
247
+ priorAssistantKey:run.adoptPriorAssistantKey||null,
248
+ postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
249
+ rVersion:run.adoptRVersion,pVersion:run.adoptPVersion};
250
+ const source=proof?.approvalTurns;
251
+ if(!policy.sameAdoptionEvidence(original,current)
252
+ ||!source||typeof source.rUserKey!=='string'
253
+ ||!/^user:[^\s]{8,}$/.test(source.rUserKey)
254
+ ||source.rUserKey===run.adoptUserKey
255
+ ||!['rUserText','pUserText'].every(k=>typeof source[k]==='string'
256
+ &&source[k].length>0&&source[k].length<=1000)){
257
+ await saveRun({...run,phase:'BLOCKED',
258
+ reason:'ADOPTION_APPROVAL_SOURCE_UNVERIFIED'});
259
+ return {status:'DENIED',code:'ADOPTION_APPROVAL_SOURCE_UNVERIFIED'};
260
+ }
261
+ approvalEvidence={rUserText:source.rUserText,rUserKey:source.rUserKey,
262
+ rVersion:run.adoptRVersion,pUserText:source.pUserText,
263
+ pUserKey:run.adoptUserKey,pVersion:run.adoptPVersion};
264
+ }
265
+ await saveRun({...run,phase:'PENDING'});
266
+ // Native validates current durable Session and signs the narrow Context IPC.
267
+ // No Context adapter? Legacy Start behavior remains unchanged.
268
+ if(run.contextLeaseRef){
269
+ const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
270
+ op:'context-control',command:'permit.consume',
271
+ args:{expectedStoreEpoch:run.contextStoreEpoch,writeRequestId:run.token,
272
+ expectedTaskRevision:run.contextTaskRevision,
273
+ expectedApprovalRevision:run.contextApprovalRevision,
274
+ actionToken:run.token,kind:'START',leaseRef:run.contextLeaseRef,
275
+ ...(run.mode==='adopt'&&run.purpose!=='REPAIR_SAME_SCOPE'
276
+ ?{adopt:true,approvalEvidence}:{})}
277
+ }).catch(()=>null);
278
+ if(allowed?.status!=='OK'||allowed.result?.status!=='PERMITTED'){
279
+ await saveRun({...run,phase:'BLOCKED',reason:'CONTEXT_START_PERMIT_UNVERIFIED'});
280
+ return {status:'DENIED',code:allowed?.code||'CONTEXT_START_PERMIT_UNVERIFIED'};
281
+ }
282
+ }
283
+ return {status:'OK',sessionId:run.sessionId,
284
+ ...(run.taskId?{taskId:run.taskId}:{}),
285
+ ...(run.mode==='adopt'?{mode:'adopt',tabId:run.adoptTabId,
286
+ page:run.adoptPage,userKey:run.adoptUserKey,
287
+ ...(run.adoptExplicitChatId?{explicitChatId:run.adoptExplicitChatId}:{}),
288
+ ...(run.adoptExpectedTaskId?{expectedTaskId:run.adoptExpectedTaskId}:{}),
289
+ priorAssistantKey:run.adoptPriorAssistantKey,
290
+ postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
291
+ ...(run.purpose==='REPAIR_SAME_SCOPE'
292
+ ?{purpose:'REPAIR_SAME_SCOPE',repairUserText:run.repairUserText,
293
+ priorDoneAssistantKey:run.repairDoneAssistantKey}
294
+ :{rVersion:run.adoptRVersion,pVersion:run.adoptPVersion})}
295
+ :{prompt:run.startPrompt})};
296
+ }
@@ -0,0 +1,186 @@
1
+ // Chat Loop Worker — adopt-recovery. Imported in order by background.js; no independent Browser Owner.
2
+ // An adopted, already-approved original Chat has an idle historical Pn answer.
3
+ // This one-shot kickoff is the missing bridge into the FIRST controlled execution
4
+ // Turn. Only the formal Continue Action may request it, with exact Native CAS.
5
+ // There is no direct Worker send, second Owner, or replay of prior approval.
6
+ async function onAdoptKickoffPrepare(message,sender){
7
+ const run=await readRun();
8
+ if(run?.phase!=='WAITING_REPLY'||run.reason!=='ADOPTED_IDLE_BASELINE'
9
+ ||run.action!=='START'||!run.contextManaged||!run.taskId
10
+ ||!run.sessionId||run.generation!==0||run.kickoffAttempted
11
+ ||!Number.isInteger(run.tabId)||run.tabId!==message.tabId
12
+ ||!run.page||run.newUserKey!==run.userKey
13
+ ||!/^assistant:[^\s]{8,}$/.test(run.assistantKey||'')
14
+ ||!Number.isSafeInteger(message.nativeUpdatedAt)
15
+ ||!Number.isInteger(sender.tab?.id)||Date.now()>=deadlineOf(run))
16
+ return {status:'DENIED',code:'ADOPT_KICKOFF_NOT_ELIGIBLE'};
17
+ if(sender.url!==chrome.runtime.getURL('continue.html')
18
+ +'?tabId='+run.tabId+'&adoptKickoffAt='+message.nativeUpdatedAt)
19
+ return {status:'DENIED',code:'ADOPT_KICKOFF_ACTION_INVALID'};
20
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
21
+ if(pathOf(tab?.url)!==run.page)
22
+ return {status:'DENIED',code:'ADOPT_KICKOFF_CHAT_CHANGED'};
23
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
24
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
25
+ ||disk.session.phase!=='WAITING_REPLY'
26
+ ||disk.session.updatedAt!==message.nativeUpdatedAt)
27
+ return {status:'DENIED',code:'ADOPT_KICKOFF_NATIVE_CHANGED'};
28
+ // run.snapshot requires a business checkpoint. A freshly adopted Task has
29
+ // no checkpoint yet, so use the existing read-only live terminalStatus
30
+ // which verifies the current bound holder without inventing one.
31
+ const status=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
32
+ op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
33
+ if(status?.status!=='OK'
34
+ ||status.result?.runRef!==run.sessionId+':'+run.taskId+':0'
35
+ ||!Number.isSafeInteger(status.result?.approvalRevision)
36
+ ||status.result.approvalRevision<1
37
+ ||status.result?.unknownEffectCount!==0
38
+ ||status.result?.executionOutcome==='DONE'
39
+ ||status.result?.deliveryRef)
40
+ return {status:'DENIED',code:'ADOPT_KICKOFF_CONTEXT_UNVERIFIED'};
41
+ const exactId=chatIdOf(tab.url);
42
+ const read=async()=>{
43
+ const approval=await chrome.tabs.sendMessage(tab.id,{
44
+ type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
45
+ explicitChatId:exactId,expectedTaskId:run.taskId}).catch(()=>null);
46
+ const turn=await chrome.tabs.sendMessage(tab.id,{
47
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
48
+ const evidence=policy.normalizeAdoptionEvidence(approval,{
49
+ page:run.page,userKey:run.userKey,
50
+ postApprovalAssistantKey:run.assistantKey,
51
+ ...(run.adoptRVersion?{rVersion:run.adoptRVersion}:{}),
52
+ ...(run.adoptPVersion?{pVersion:run.adoptPVersion}:{})
53
+ });
54
+ if(!evidence||turn?.contract!=='chat-loop.turn-observer.v1'
55
+ ||turn.status!=='READY'||turn.page!==run.page
56
+ ||turn.userKey!==run.userKey||turn.assistantKey!==run.assistantKey
57
+ ||turn.pendingConfirmation
58
+ ||workerApi.parseStatus(turn.replyText)!=='UNKNOWN')
59
+ return null;
60
+ return {userKey:turn.userKey,assistantKey:turn.assistantKey,
61
+ replyText:turn.replyText,rVersion:evidence.rVersion,pVersion:evidence.pVersion};
62
+ };
63
+ const first=await read();
64
+ if(!first)return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_UNVERIFIED'};
65
+ await new Promise(resolve=>setTimeout(resolve,2300));
66
+ const second=await read();
67
+ if(!second||JSON.stringify(first)!==JSON.stringify(second))
68
+ return {status:'DENIED',code:'ADOPT_KICKOFF_APPROVAL_CHANGED'};
69
+ const token=crypto.randomUUID();
70
+ await saveRun({...run,phase:'RESERVED',action:'CONTINUE',token,
71
+ manualActionTabId:sender.tab.id,
72
+ recoveryMode:'ADOPT_KICKOFF',kickoffAttempted:true});
73
+ return {status:'PREPARED',token,tabId:run.tabId};
74
+ }
75
+ // One-shot recovery of an ALREADY committed same-Chat Adopt whose historical
76
+ // post-approval reply was wrongly classified UNKNOWN. Never writes a composer,
77
+ // retries an action or replaces Context/Owner. Requires exact Native BLOCKED CAS.
78
+ async function onAdoptBaselineRepair(message,sender){
79
+ const prior=await readRun();
80
+ if(prior?.phase!=='BLOCKED'||prior.reason!=='UNKNOWN'
81
+ ||prior.action!=='START'||!prior.contextManaged||!prior.taskId
82
+ ||(prior.recoveryAttempts||0)!==0
83
+ ||!prior.sessionId||!Number.isInteger(prior.tabId)
84
+ ||prior.tabId!==message.tabId||!prior.page
85
+ ||!/^user:[^\s]{8,}$/.test(prior.newUserKey||'')
86
+ ||!/^assistant:[^\s]{8,}$/.test(prior.assistantKey||'')
87
+ ||prior.userKey!==prior.newUserKey)
88
+ return {status:'DENIED',code:'ADOPT_BASELINE_NOT_ELIGIBLE'};
89
+ if(!Number.isSafeInteger(message.nativeUpdatedAt)||message.nativeUpdatedAt<=0
90
+ ||!Number.isInteger(sender.tab?.id))
91
+ return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_SOURCE'};
92
+ const expected=chrome.runtime.getURL('continue.html')
93
+ +'?tabId='+prior.tabId+'&adoptBaselineAt='+message.nativeUpdatedAt;
94
+ if(sender.url!==expected)
95
+ return {status:'DENIED',code:'ADOPT_BASELINE_INVALID_ACTION'};
96
+ const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
97
+ if(pathOf(tab?.url)!==prior.page)
98
+ return {status:'DENIED',code:'ADOPT_BASELINE_CHAT_CHANGED'};
99
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
100
+ {op:'session-read'}).catch(()=>null);
101
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(prior),disk.session)
102
+ ||disk.session?.phase!=='BLOCKED'
103
+ ||disk.session.updatedAt!==message.nativeUpdatedAt)
104
+ return {status:'DENIED',code:'ADOPT_BASELINE_NATIVE_CHANGED'};
105
+ const exactChatId=chatIdOf(tab.url);
106
+ const read=async()=>{
107
+ const approval=await chrome.tabs.sendMessage(tab.id,
108
+ {type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
109
+ explicitChatId:exactChatId,expectedTaskId:prior.taskId}).catch(()=>null);
110
+ const turn=await chrome.tabs.sendMessage(tab.id,
111
+ {type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
112
+ const evidence=policy.normalizeAdoptionEvidence(approval,{
113
+ page:prior.page,userKey:prior.newUserKey,
114
+ postApprovalAssistantKey:prior.assistantKey,
115
+ ...(prior.adoptRVersion?{rVersion:prior.adoptRVersion}:{}),
116
+ ...(prior.adoptPVersion?{pVersion:prior.adoptPVersion}:{})
117
+ });
118
+ if(!evidence||turn?.contract!=='chat-loop.turn-observer.v1'
119
+ ||turn.status!=='READY'||turn.page!==prior.page
120
+ ||turn.userKey!==prior.newUserKey||turn.assistantKey!==prior.assistantKey
121
+ ||turn.pendingConfirmation
122
+ ||workerApi.parseStatus(turn.replyText)!=='UNKNOWN')
123
+ return null;
124
+ return {userKey:turn.userKey,assistantKey:turn.assistantKey,
125
+ replyText:turn.replyText,rVersion:evidence.rVersion,pVersion:evidence.pVersion};
126
+ };
127
+ const a=await read();
128
+ if(!a)return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_MISSING'};
129
+ await new Promise(resolve=>setTimeout(resolve,2300));
130
+ const b=await read();
131
+ if(!b||JSON.stringify(a)!==JSON.stringify(b))
132
+ return {status:'DENIED',code:'ADOPT_BASELINE_PROOF_CHANGED'};
133
+ // Re-arm the observer as a historical baseline BEFORE Native CAS. Failure
134
+ // cannot leave Native in a half-resumed state. This sends no Chat message.
135
+ const armed=await chrome.tabs.sendMessage(tab.id,{
136
+ type:'CHAT_LOOP_TURN_RESUME_V1',
137
+ page:prior.page,userKey:prior.newUserKey,
138
+ assistantKey:prior.assistantKey,baselineOnly:true,
139
+ startedAt:prior.startedAt
140
+ }).catch(()=>null);
141
+ if(armed?.status!=='RESUMED'||armed.baselineOnly!==true)
142
+ return {status:'DENIED',code:'ADOPT_BASELINE_OBSERVER_UNVERIFIED'};
143
+ await saveRun({...prior,phase:'RESERVED',
144
+ reason:'ADOPT_BASELINE_RECOVERY',
145
+ recoveryMode:'ADOPT_IDLE_BASELINE',recoveryAttempts:1,
146
+ recoveryExpectedNativeAt:disk.session.updatedAt});
147
+ const clean={...prior,phase:'WAITING_REPLY',reason:'ADOPTED_IDLE_BASELINE',
148
+ recoveryAttempts:1,userKey:prior.newUserKey,assistantKey:prior.assistantKey};
149
+ delete clean.recoveryMode;
150
+ await saveRun(clean);
151
+ return {status:'REPAIRED',sessionId:prior.sessionId,taskId:prior.taskId,
152
+ activeChatId:exactChatId,baselineAssistantKey:prior.assistantKey,
153
+ generation:prior.generation||0};
154
+ }
155
+ // Only an explicitly opened, existing Continue Action may reveal a
156
+ // scroll-virtualized *terminal Owner* before the normal double Turn check.
157
+ // This grants no send permit and changes neither Worker nor Native state.
158
+ // The Action alone may scroll the verified Chat UI; the Worker never does.
159
+ async function onManualReveal(message,sender) {
160
+ const run=await readRun();
161
+ if(!run?.sessionId||run.phase!=='BLOCKED'||run.reason!=='BLOCKED'
162
+ ||run.action!=='CONTINUE'||run.recoveryProtocol!==1
163
+ ||!(run.recoveryAttempts>0)
164
+ ||run.recoverySourceAssistantKey===run.assistantKey
165
+ ||run.newUserKey!==run.userKey
166
+ ||!Number.isInteger(run.tabId)||message.tabId!==run.tabId
167
+ ||!Number.isSafeInteger(message.resumeBlockedAt)
168
+ ||message.resumeBlockedAt<=0 ||!Number.isInteger(sender.tab?.id))
169
+ return {status:'DENIED',code:'REVEAL_OWNER_UNVERIFIED'};
170
+ let url;
171
+ try{url=new URL(sender.url);}catch{return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};}
172
+ if(url.origin!==new URL(chrome.runtime.getURL('continue.html')).origin
173
+ ||url.pathname!=='/continue.html'
174
+ ||url.searchParams.size!==2
175
+ ||url.searchParams.get('tabId')!==String(run.tabId)
176
+ ||url.searchParams.get('resumeBlockedAt')!==String(message.resumeBlockedAt))
177
+ return {status:'DENIED',code:'REVEAL_SOURCE_INVALID'};
178
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
179
+ if(!tab||pathOf(tab.url)!==run.page)
180
+ return {status:'DENIED',code:'REVEAL_CHAT_CHANGED'};
181
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
182
+ if(disk?.status!=='OK'||!matchesNativeProjection(sessionProjection(run),disk.session)
183
+ ||disk.session.updatedAt!==message.resumeBlockedAt)
184
+ return {status:'DENIED',code:'REVEAL_NATIVE_CAS_UNVERIFIED'};
185
+ return {status:'OK',page:run.page};
186
+ }
@@ -0,0 +1,126 @@
1
+ // Chat Loop Worker — adopt-result. Imported in order by background.js; no independent Browser Owner.
2
+ async function sessionStartResult(message,sender){
3
+ const run=await readRun();
4
+ if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
5
+ ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
6
+ ||run.phase!=='PENDING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
7
+ const adopted=run.mode==='adopt';
8
+ let confirmed=(adopted?message.result==='ADOPTED_CONFIRMED'
9
+ :message.result==='SENT_CONFIRMED')
10
+ &&Number.isInteger(message.newTabId)
11
+ &&typeof message.newPage==='string'&&pathOf('https://chatgpt.com'+message.newPage)===message.newPage
12
+ &&typeof message.newUserKey==='string'&&/^user:[^\s]{8,}$/.test(message.newUserKey);
13
+ if(confirmed){
14
+ const tab=await chrome.tabs.get(message.newTabId).catch(()=>null);
15
+ confirmed=!!tab&&pathOf(tab.url)===message.newPage;
16
+ }
17
+ if(confirmed && adopted){
18
+ confirmed=message.newTabId===run.adoptTabId
19
+ &&message.newPage===run.adoptPage
20
+ &&message.newUserKey===run.adoptUserKey;
21
+ if(confirmed){
22
+ const repair=run.purpose==='REPAIR_SAME_SCOPE';
23
+ const proof=await chrome.tabs.sendMessage(run.adoptTabId,
24
+ {type:repair?'CHAT_LOOP_REPAIR_EVIDENCE_V1':'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
25
+ ...(run.adoptExplicitChatId
26
+ ?{explicitChatId:run.adoptExplicitChatId}:{}),
27
+ ...(run.adoptExpectedTaskId
28
+ ?{expectedTaskId:run.adoptExpectedTaskId}:{})}).catch(()=>null);
29
+ const original={page:run.adoptPage,userKey:run.adoptUserKey,
30
+ priorAssistantKey:run.adoptPriorAssistantKey||null,
31
+ postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
32
+ rVersion:run.adoptRVersion,pVersion:run.adoptPVersion};
33
+ confirmed=repair
34
+ ?proof?.contract==='chat-loop.turn-observer.v1'
35
+ &&proof.status==='VERIFIED'&&proof.page===run.adoptPage
36
+ &&proof.userKey===run.adoptUserKey
37
+ &&proof.userText===run.repairUserText
38
+ &&proof.priorDoneAssistantKey===run.repairDoneAssistantKey
39
+ :policy.sameAdoptionEvidence(original,
40
+ policy.normalizeAdoptionEvidence(proof,{page:run.adoptPage}));
41
+ }
42
+ }
43
+ // Four-hour execution clock begins at confirmed enrollment, not at
44
+ // the UI approval or potentially long Start readiness/preparation.
45
+ const adoptedIdle=confirmed&&adopted&&!!run.adoptPostApprovalAssistantKey;
46
+ const next={...run,
47
+ // Protect the crash window between a confirmed browser send and Native
48
+ // run.bind.initial. This marks the session as Context-governed, NOT as
49
+ // successfully bound; subsequent DONE/Continue must verify the real Store.
50
+ ...(confirmed&&run.contextLeaseRef
51
+ ?{contextManaged:{storeEpoch:run.contextStoreEpoch}}:{}),
52
+ phase:confirmed?'WAITING_REPLY':'BLOCKED',
53
+ startedAt:confirmed?Date.now():run.startedAt,
54
+ lastStartActionTabId:sender.tab.id,
55
+ ...(adoptedIdle?{assistantKey:run.adoptPostApprovalAssistantKey,
56
+ userKey:run.adoptUserKey}:{}),
57
+ reason:confirmed?(adoptedIdle?'ADOPTED_IDLE_BASELINE':'')
58
+ :adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED',
59
+ ...(!confirmed&&['START_HOME_URL_UNVERIFIED','NEW_CHAT_NOT_READY',
60
+ 'START_COMPOSER_NOT_EMPTY','START_ACCOUNT_SWITCH_VISIBLE',
61
+ 'FIRST_TURN_OBSERVER_UNAVAILABLE','START_SEND_BUTTON_UNAVAILABLE','START_INPUT_CHANGED',
62
+ 'START_INPUT_UNVERIFIED','START_INPUT_REJECTED',
63
+ 'START_CLICK_UNVERIFIED','FIRST_SEND_RECEIPT_UNKNOWN']
64
+ .includes(message.failureCode)
65
+ ?{lastStartFailureCode:message.failureCode}:{}),
66
+ ...(confirmed?{tabId:message.newTabId,page:message.newPage,
67
+ newUserKey:message.newUserKey}:{attemptedNewTabId:Number.isInteger(message.newTabId)?message.newTabId:null})};
68
+ if(confirmed){
69
+ delete next.handoffPending;
70
+ delete next.handoffPendingAt;
71
+ }
72
+ delete next.startPrompt;
73
+ delete next.adoptTabId;
74
+ delete next.adoptPage;
75
+ delete next.adoptUserKey;
76
+ delete next.adoptExplicitChatId;
77
+ delete next.adoptExpectedTaskId;
78
+ delete next.adoptPriorAssistantKey;
79
+ delete next.adoptPostApprovalAssistantKey;
80
+ delete next.adoptRVersion;
81
+ delete next.adoptPVersion;
82
+ delete next.repairUserText;
83
+ delete next.repairDoneAssistantKey;
84
+ delete next.purpose;
85
+ delete next.mode;
86
+ delete next.machineRequestId;
87
+ delete next.machineActionTabId;
88
+ delete next.replacedBlockedSessionId;
89
+ await saveRun(next);
90
+ let privateContext=null;
91
+ if(confirmed&&run.contextLeaseRef){
92
+ const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
93
+ op:'context-control',command:'run.bind.initial',
94
+ args:{expectedStoreEpoch:run.contextStoreEpoch,
95
+ writeRequestId:run.token+':initial-bind',
96
+ expectedTaskRevision:run.contextTaskRevision,expectedBindingRevision:0,
97
+ actionToken:run.token,leaseRef:run.contextLeaseRef,
98
+ runCredential:run.contextInitialCredential}
99
+ }).catch(()=>null);
100
+ if(bound?.status!=='OK'||bound.result?.status!=='BOUND'){
101
+ // First Chat may already exist. Never re-send merely to fix Context.
102
+ const stopped={...next,phase:'BLOCKED',reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
103
+ delete stopped.contextInitialCredential;
104
+ await saveRun(stopped);
105
+ return {status:'BLOCKED',code:bound?.code||'CONTEXT_INITIAL_BIND_UNVERIFIED'};
106
+ }
107
+ privateContext={runRef:bound.result.runRef,
108
+ runCredential:run.contextInitialCredential,
109
+ storeEpoch:run.contextStoreEpoch,
110
+ bindingRevision:bound.result.bindingRevision,
111
+ taskRevision:run.contextTaskRevision};
112
+ // Capability is delivered once in the private Start result, not Status.
113
+ const clean={...next,contextManaged:{storeEpoch:run.contextStoreEpoch}};
114
+ for(const key of ['contextInitialCredential','contextLeaseRef','contextStoreEpoch',
115
+ 'contextTaskRevision','contextApprovalRevision'])delete clean[key];
116
+ await saveRun(clean);
117
+ }
118
+ if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
119
+ 'https://chatgpt.com'+message.newPage).catch(()=>{});
120
+ return confirmed?{status:'OK',sessionId:next.sessionId,
121
+ activeChatId:sessionProjection(next).activeChatId,
122
+ activeChatUrl:sessionProjection(next).activeChatUrl,
123
+ ...(next.taskId?{taskId:next.taskId}:{}),
124
+ ...(privateContext?{context:privateContext}:{})}
125
+ :{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
126
+ }