@tomflow/chatloop-tools 0.9.62 → 0.9.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +29 -10
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/package.json +3 -13
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -83
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,161 +0,0 @@
1
- // Chat Loop Worker — scheduler. Imported in order by background.js; no independent Browser Owner.
2
- // Extension updates invalidate previous injected listeners. Reconnect only its own observers.
3
- // A detached alarm/reconnect must settle its own failure, not create a
4
- // second scheduler or implicitly repeat a browser Action.
5
- const observeBackground=(work,scope)=>{
6
- void work.catch(error=>console.warn('CHAT_LOOP_SCHEDULER_UNVERIFIED',
7
- scope,safeWorkerErrorCode(error,'SCHEDULER_ERROR')));
8
- };
9
- async function reconnectOpenChats() {
10
- const tabs = await chrome.tabs.query({url: "https://chatgpt.com/*"});
11
- for (const tab of tabs) {
12
- if (!Number.isInteger(tab.id) || !pathOf(tab.url) && !/^https:\/\/chatgpt\.com\/$/.test(tab.url)) continue;
13
- try {
14
- await chrome.scripting.executeScript({target: {tabId: tab.id},
15
- files: ["content.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
16
- const owner = await readRun();
17
- if (owner?.phase === "WAITING_REPLY" && owner.tabId === tab.id
18
- && owner.page === pathOf(tab.url) && owner.newUserKey) {
19
- // Normal WAITING_REPLY uses its original zero-extra-read resume.
20
- // Only a previously seen pending confirmation needs an extra DOM
21
- // identity check for a human response that arrived during reload.
22
- const proof=owner.reason==="PENDING_CONFIRMATION_DOM"
23
- ? await chrome.tabs.sendMessage(tab.id,
24
- {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null)
25
- :null;
26
- const freshUser=proof?.page===owner.page
27
- && proof.userKey!==owner.newUserKey
28
- && proof.priorAssistantKey===owner.assistantKey
29
- && proof.priorAssistantUserKey===owner.userKey
30
- && proof.directReplyAfterPriorAssistant===true;
31
- const res = await chrome.tabs.sendMessage(tab.id, {
32
- type: "CHAT_LOOP_TURN_RESUME_V1", page: owner.page,
33
- userKey:freshUser?proof.userKey:owner.newUserKey,
34
- assistantKey: owner.assistantKey || null,
35
- ...(owner.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
36
- startedAt: owner.startedAt
37
- }).catch(() => null);
38
- if (res?.status !== "RESUMED" && res?.status !== "ALREADY_MONITORING")
39
- console.warn("CHAT_LOOP_TURN_RESUME_UNVERIFIED",
40
- safeWorkerErrorCode({code:res?.reason||res?.status},
41
- "OBSERVER_RESUME_UNVERIFIED"));
42
- }
43
- } catch (error) {
44
- console.warn("CHAT_LOOP_OBSERVER_RECONNECT_UNVERIFIED",
45
- safeWorkerErrorCode(error,"OBSERVER_RECONNECT_UNVERIFIED"));
46
- }
47
- }
48
- }
49
- // MV3 background service workers can suspend, and hidden-page setInterval
50
- // may be throttled. An alarm asks the Observer to sample, never acts directly.
51
- async function ensureAlarm() {
52
- if (!chrome.alarms?.create) return;
53
- const existing = await chrome.alarms.get?.(ALARM_NAME).catch(() => null);
54
- if (!existing) await chrome.alarms.create(ALARM_NAME, {periodInMinutes: 1});
55
- }
56
- async function watchActiveTurn() {
57
- // One bounded reconciliation on the existing 1-minute Worker alarm.
58
- await serial(async()=>{await expireStaleAction();
59
- await resources.reconcile(await readRun()).catch(()=>{});});
60
- // Normal periodic wakeups also reconcile a delayed one-shot deadline.
61
- // All state changes share the same serial queue as Turn/Action receipts.
62
- await serial(async()=>{await expireStaleModelIntent();await prepareHandoffIfDue();});
63
- const run = await readRun();
64
- // While an Action is pending, never dispatch competing operations.
65
- if (run && ["RESERVED", "PENDING"].includes(run.phase)) return;
66
- const tabs = run?.phase === "WAITING_REPLY"
67
- ? [await chrome.tabs.get(run.tabId).catch(() => null)]
68
- : await chrome.tabs.query({url: "https://chatgpt.com/*"});
69
- for (const tab of tabs) {
70
- if (!tab?.id || !pathOf(tab.url)) continue;
71
- try {
72
- const proof = await chrome.tabs.sendMessage(tab.id,
73
- {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true});
74
- // A reloaded Observer may have mistaken the in-flight user Turn for
75
- // historical baseline. Its IDLE state is not proof of completion.
76
- // Rebind the exact persisted owner using read-only verification.
77
- const freshHuman=run?.phase==="WAITING_REPLY" && run.tabId===tab.id
78
- && proof?.page===run.page && proof.userKey!==run.newUserKey
79
- && proof.priorAssistantKey===run.assistantKey
80
- && proof.priorAssistantUserKey===run.userKey
81
- && proof.directReplyAfterPriorAssistant===true;
82
- if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
83
- && proof?.page === run.page
84
- && (proof.userKey === run.newUserKey || freshHuman)
85
- && (proof.status === "IDLE"
86
- || proof.status === "UNKNOWN"
87
- && ["ATTACHING_CHAT", "WAITING_CHAT_HYDRATION"].includes(proof.reason))) {
88
- await chrome.tabs.sendMessage(tab.id, {
89
- type: "CHAT_LOOP_TURN_RESUME_V1", page: run.page,
90
- userKey: freshHuman?proof.userKey:run.newUserKey,
91
- assistantKey: run.assistantKey || null,
92
- ...(run.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
93
- startedAt: run.startedAt
94
- }).catch(() => null);
95
- }
96
- // A human response can fail after the previous question was kept in
97
- // WAITING_REPLY. Do not let this become an indefinite silent wait.
98
- if(freshHuman && proof.status==="BLOCKED") {
99
- observeBackground(serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
100
- reason:proof.reason||"PAGE_ERROR"},
101
- {tab,url:tab.url})),'HUMAN_TURN_RECOVERY');
102
- }
103
- // Alarm is still read-only. It may reconcile a verified page failure if
104
- // the observer's original notification was lost while Worker slept.
105
- if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
106
- && proof?.status === "BLOCKED" && ["PAGE_ERROR","CONTEXT_LIMIT","SECURITY_CHALLENGE"].includes(proof.reason)
107
- && proof.page === run.page && proof.userKey === run.newUserKey) {
108
- observeBackground(serial(() => onTurnBlocked({page: run.page,
109
- userKey: run.newUserKey, reason: proof.reason},
110
- {tab, url: tab.url})),'TURN_FAILURE_RECOVERY');
111
- }
112
- } catch { /* Observer unavailable; never infer Turn completion. */ }
113
- }
114
- }
115
- chrome.alarms?.onAlarm?.addListener(alarm => {
116
- if (alarm?.name === ALARM_NAME)
117
- observeBackground(watchActiveTurn(),'TURN_WATCH_ALARM');
118
- if (alarm?.name === DEADLINE_ALARM_NAME)
119
- observeBackground(serial(prepareHandoffIfDue),'HANDOFF_DEADLINE_ALARM');
120
- });
121
- chrome.runtime.onInstalled?.addListener(() => {
122
- observeBackground(ensureAlarm(),'ALARM_SETUP');
123
- observeBackground(serial(async()=>{await expireStaleAction();
124
- await resources.reconcile(await readRun()).catch(()=>{});}),
125
- 'INSTALL_RECONCILIATION');
126
- observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
127
- });
128
- chrome.runtime.onStartup?.addListener(() => {
129
- observeBackground(ensureAlarm(),'ALARM_SETUP');
130
- observeBackground(serial(async()=>{await expireStaleAction();
131
- await resources.reconcile(await readRun()).catch(()=>{});}),
132
- 'INSTALL_RECONCILIATION');
133
- observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
134
- });
135
- observeBackground(ensureAlarm(),'ALARM_SETUP');
136
- // Reconcile an elapsed deadline after MV3 Worker suspension/reload.
137
- observeBackground(serial(async()=>{await expireStaleAction();
138
- await resources.reconcile(await readRun()).catch(()=>{});
139
- await prepareHandoffIfDue();}),'STARTUP_RECONCILIATION');
140
- // A manual extension Reload does not necessarily fire onInstalled/onStartup.
141
- // Reattach the two idempotent read-only scripts to existing ChatGPT tabs.
142
- observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
143
- // User-clicked popup Clean must share the same Action quota as Worker actions.
144
- // The popup cannot create extra Chrome tabs directly.
145
- async function openPopupClean(message,sender) {
146
- if(sender?.url!==chrome.runtime.getURL('popup.html')
147
- ||!Number.isSafeInteger(message?.tabId)||message.tabId<=0)
148
- return {status:'DENIED',code:'POPUP_SOURCE_INVALID'};
149
- const target=await chrome.tabs.get(message.tabId).catch(()=>null);
150
- let valid=false;
151
- try {valid=target?.active===true && Number.isSafeInteger(target.windowId)
152
- && new URL(target.url).origin==='https://chatgpt.com';} catch {}
153
- if(!valid)return {status:'DENIED',code:'CLEAN_TARGET_UNVERIFIED'};
154
- try {
155
- const action=await createBoundedAction({url:chrome.runtime.getURL('clean.html')
156
- +'?tabId='+target.id,windowId:target.windowId,active:true});
157
- return {status:'OK',actionTabId:action.id};
158
- } catch(error) {
159
- return {status:'BLOCKED',code:safeWorkerErrorCode(error,'CLEAN_ACTION_UNVERIFIED')};
160
- }
161
- }
@@ -1,75 +0,0 @@
1
- // Single Worker Owner lifecycle operation. This does not send Chat messages,
2
- // claim another Owner or finish the business Task.
3
- async function sessionControl(message,sender){
4
- if(!Number.isInteger(sender.tab?.id)
5
- ||sender.url!==chrome.runtime.getURL('session.html')
6
- +'?requestId='+message.requestId+'&operation=cancel'
7
- ||!/^[a-f0-9]{32}$/.test(message.requestId||''))
8
- return {status:'DENIED',code:'INVALID_SESSION_SOURCE'};
9
- // URL parameters locate a private request, never authorize mutation.
10
- const request=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
11
- op:'acquire',id:message.requestId,action:'session'
12
- }).catch(()=>null);
13
- const intent=request?.intent;
14
- if(request?.status!=='OK'||request.id!==message.requestId
15
- ||request.action!=='session'||intent?.operation!=='cancel'
16
- ||message.operation!=='cancel'||intent.confirmed!==true)
17
- return {status:'DENIED',code:'SESSION_INTENT_UNVERIFIED'};
18
- const run=await readRun();
19
- const id=run?.sessionId;
20
- // V1 intentionally supports ONLY a started but never executing Adopt.
21
- // A missing browser tab cannot be used to invent an Owner or cancel work.
22
- if(!id||id!==intent.sessionId
23
- ||run.projectId!==intent.projectId||run.taskId!==intent.taskId
24
- ||run.generation!==intent.generation||run.phase!=='WAITING_REPLY'
25
- ||run.reason!=='ADOPTED_IDLE_BASELINE'||run.action!=='START'
26
- ||!run.contextManaged?.storeEpoch
27
- ||run.contextManaged.storeEpoch!==intent.contextStoreEpoch
28
- ||run.modelIntent?.action ||run.pendingAttempt ||run.contextHandoff)
29
- return {status:'DENIED',code:'SESSION_CANCEL_NOT_IDLE'};
30
- const before=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
31
- op:'session-read'
32
- }).catch(()=>null);
33
- if(before?.status!=='OK'
34
- ||!matchesNativeProjection(sessionProjection(run),before.session)
35
- ||before.session.updatedAt!==intent.expectedNativeUpdatedAt)
36
- return {status:'DENIED',code:'SESSION_CANCEL_NATIVE_MISMATCH'};
37
- // Stop scheduling FIRST. Do not release Native ID or Context writer here.
38
- const stopped={...run,phase:'BLOCKED',
39
- reason:'SESSION_CANCEL_PENDING',cancelRequestId:message.requestId,
40
- cancelFreezeExpectedAt:intent.expectedNativeUpdatedAt};
41
- await saveRun(stopped);
42
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
43
- op:'session-read'
44
- }).catch(()=>null);
45
- if(disk?.status!=='OK'||disk.session?.phase!=='BLOCKED'
46
- ||!matchesNativeProjection(sessionProjection(stopped),disk.session))
47
- return {status:'BLOCKED',code:'SESSION_CANCEL_FREEZE_UNVERIFIED'};
48
- const writeRequestId='cancel-'+message.requestId;
49
- const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
50
- op:'context-control',command:'run.fence.cancel',
51
- args:{expectedStoreEpoch:intent.contextStoreEpoch,
52
- writeRequestId,expectedTaskRevision:intent.expectedTaskRevision,
53
- expectedBindingRevision:intent.expectedBindingRevision,
54
- actionToken:message.requestId,reason:'USER_CANCELLED'}
55
- }).catch(()=>null);
56
- if(fenced?.status!=='OK'||fenced.result?.status!=='CANCEL_FENCED')
57
- return {status:'BLOCKED',code:fenced?.code||'CONTEXT_CANCEL_FENCE_UNVERIFIED'};
58
- // A business receipt alone is not enough; read back the same durable state.
59
- const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
60
- op:'context-control',command:'run.terminalStatus',args:{}
61
- }).catch(()=>null);
62
- const c=observed?.result?.sessionCancellation;
63
- if(observed?.status!=='OK'||observed.result.runRef!==null
64
- ||c?.status!=='CANCELLED_NOT_DELIVERED'
65
- ||c.requestId!==writeRequestId||c.sessionId!==id
66
- ||c.generation!==run.generation)
67
- return {status:'BLOCKED',code:'CONTEXT_CANCEL_FENCE_UNVERIFIED'};
68
- const next={...stopped,phase:'CANCELLED',reason:'SESSION_CANCELLED',
69
- cancelBlockedUpdatedAt:disk.session.updatedAt,
70
- contextCancelFence:'CONFIRMED'};
71
- // The Native Host validates Context again, then exact BLOCKED CAS.
72
- await saveRun(next);
73
- return {status:'OK',state:'CANCELLED_NOT_DELIVERED',sessionId:id,
74
- taskId:run.taskId,bindingRevision:observed.result.bindingRevision};
75
- }
@@ -1,197 +0,0 @@
1
- // Chat Loop Worker — turn-failure. Imported in order by background.js; no independent Browser Owner.
2
- async function onTurnBlocked(message, sender) {
3
- const reason = message.reason;
4
- if (!["PAGE_ERROR", "CONTEXT_LIMIT", "SECURITY_CHALLENGE"].includes(reason)
5
- || !await eligible(sender, message.page)
6
- || typeof message.userKey !== "string" || !/^user:[^\s]{8,}$/.test(message.userKey))
7
- return {status: "DENIED", code: "ERROR_SOURCE_UNVERIFIED"};
8
- const previous = await readRun();
9
- if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== sender.tab.id
10
- || previous.page !== message.page)
11
- return {status: "IGNORED", code: "NOT_OWNED_RUNNING_TURN"};
12
- // An unanswered confirmation can be followed by a new human user Turn.
13
- // If THAT Turn fails, stop the same Owner; never silently ignore its error
14
- // or treat it as an automatically sent Turn eligible for Retry/Handoff.
15
- if(message.userKey!==previous.newUserKey){
16
- const proof=await chrome.tabs.sendMessage(previous.tabId,
17
- {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
18
- const humanFault=proof?.contract==="chat-loop.turn-observer.v1"
19
- &&proof.page===previous.page&&proof.status==="BLOCKED"
20
- &&proof.userKey===message.userKey
21
- &&proof.priorAssistantKey===previous.assistantKey
22
- &&proof.priorAssistantUserKey===previous.userKey
23
- &&proof.directReplyAfterPriorAssistant===true;
24
- if(!humanFault)return {status:"IGNORED",code:"NOT_OWNED_RUNNING_TURN"};
25
- await saveRun({...previous,phase:"BLOCKED",reason:"HUMAN_RESPONSE_PAGE_ERROR"});
26
- return {status:"BLOCKED",code:"HUMAN_RESPONSE_PAGE_ERROR"};
27
- }
28
- const verify = async () => {
29
- const proof = await chrome.tabs.sendMessage(previous.tabId,
30
- {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
31
- return proof?.contract === "chat-loop.turn-observer.v1"
32
- && proof.status === "BLOCKED" && proof.reason === reason
33
- && proof.page === previous.page && proof.userKey === previous.newUserKey
34
- ? proof : null;
35
- };
36
- const first = await verify();
37
- if (!first) return {status: "IGNORED", code: "ERROR_NOT_CONFIRMED"};
38
- await new Promise(resolve => setTimeout(resolve, 400));
39
- const second = await verify();
40
- if (!second || first.retryAvailable !== second.retryAvailable)
41
- return {status: "IGNORED", code: "ERROR_NOT_STABLE"};
42
- // A bounded non-content receipt lets the existing Audit prove which
43
- // decision the ONLY Worker actually took. Never log raw Chat text.
44
- const faultProof = code => ({code, reason, userKey: message.userKey, at: Date.now()});
45
- const recordFault = async code => {
46
- await saveRun({...previous, lastFaultProof: faultProof(code)});
47
- return {status: "IGNORED", code};
48
- };
49
- await saveRun({...previous, lastFaultProof: faultProof("ERROR_CONFIRMED")});
50
- // A network interruption may show a transient page error without a native
51
- // Retry button. Only *observe* for a bounded grace period: never resend an
52
- // uncertain user Turn. Resume normal observation only if the EXACT submitted
53
- // user identity stays present and two consecutive polls show no page fault.
54
- // If the optimistic user message disappears, this is NOT proof of no send.
55
- if (reason === "PAGE_ERROR" && second.retryAvailable !== true) {
56
- let recovered = 0;
57
- for (let attempt = 0; attempt < 4; attempt++) {
58
- await new Promise(resolve => setTimeout(resolve, 1000));
59
- const proof = await chrome.tabs.sendMessage(previous.tabId,
60
- {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
61
- const sameTurn = proof?.contract === "chat-loop.turn-observer.v1"
62
- && proof.page === previous.page
63
- && proof.userKey === previous.newUserKey;
64
- // The Observer may emit its verified completion while this error handler
65
- // owns the serialized Worker queue. That completion message is waiting
66
- // behind us: fail-closing here would discard a real, finished Turn.
67
- // TURN_FINISHED or the exact already-emitted state is sufficient proof
68
- // that the SAME user Turn recovered; do not invent/send another message.
69
- if (sameTurn && (proof.status === "TURN_FINISHED"
70
- || proof.status === "IDLE" && proof.reason === "TURN_ALREADY_EMITTED"))
71
- return recordFault("PAGE_ERROR_COMPLETION_QUEUED");
72
- if (sameTurn && ["RUNNING", "UNKNOWN"].includes(proof.status)) {
73
- recovered++;
74
- if (recovered === 2) return recordFault("PAGE_ERROR_CLEARED_SAME_TURN");
75
- } else recovered = 0;
76
- }
77
- }
78
- // A security challenge is an explicit stop condition, not a prompt to retry
79
- // or evade site access controls. Keep the original Chat and user Turn intact.
80
- if (reason === "SECURITY_CHALLENGE") {
81
- await saveRun({...previous, phase:"BLOCKED", reason,
82
- lastFaultProof:faultProof("SECURITY_CHALLENGE")});
83
- return {status:"BLOCKED", code:reason};
84
- }
85
- // The second capacity failure immediately after an ERROR Handoff must not
86
- // start an infinite series of new ChatGPT conversations.
87
- const errorHandoffCount = previous.errorHandoffCount || 0;
88
- if (reason === "CONTEXT_LIMIT" && errorHandoffCount < 1
89
- || reason === "PAGE_ERROR" && previous.retryCount !== 1 && second.retryAvailable === true) {
90
- const retry = reason === "PAGE_ERROR";
91
- const token = crypto.randomUUID();
92
- let next = {...previous, phase: "RESERVED", action: retry ? "CONTINUE" : "HANDOFF",
93
- token, reason: "", lastFaultProof:faultProof(retry ? "NATIVE_RETRY_ONCE" : "CONTEXT_HANDOFF"),
94
- ...(retry ? {retryMode: "NATIVE", retryCount: 1}
95
- : {handoffMode: "ERROR", errorReason: reason})};
96
- if (previous.modelIntent) {
97
- next=updateModelReceipt(next,previous.modelIntent.id,{
98
- status:"OVERRIDDEN_BY_ERROR",reason,actualAction:next.action});
99
- delete next.modelIntent;
100
- }
101
- await saveRun(next); // Durable before opening the only authorized Action.
102
- try {
103
- const url = chrome.runtime.getURL(retry ? "continue.html" : "handoff.html")
104
- + "?tabId=" + previous.tabId + "&token=" + encodeURIComponent(token);
105
- const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
106
- return {status: "QUEUED", actionTabId: actionTab.id, code: retry ? "NATIVE_RETRY_ONCE" : "CONTEXT_HANDOFF"};
107
- } catch {
108
- await saveRun({...next, phase: "BLOCKED", reason: "ERROR_ACTION_CREATE_FAILED"});
109
- return {status: "BLOCKED", code: "ERROR_ACTION_CREATE_FAILED"};
110
- }
111
- }
112
- const finalReason = reason === "PAGE_ERROR"
113
- ? previous.retryCount === 1 ? "PAGE_ERROR_AFTER_RETRY" : "PAGE_ERROR_NO_RETRY_BUTTON"
114
- : "CONTEXT_HANDOFF_REPEATED";
115
- await saveRun({...previous, phase:"BLOCKED", reason:finalReason,
116
- lastFaultProof:faultProof(finalReason)});
117
- return {status: "BLOCKED", code: reason === "PAGE_ERROR" ? "PAGE_ERROR" : "CONTEXT_HANDOFF_REPEATED"};
118
- }
119
- // A model-driven request can only be queued against a currently RUNNING,
120
- // already-owned user Turn. The MCP call returns immediately: waiting for this
121
- // assistant to finish inside the tool call would deadlock the Turn.
122
- async function onModelIntent(message,sender) {
123
- const action=message?.action;
124
- const file=action==='HANDOFF'?'handoff.html':action==='CONTINUE'?'continue.html':null;
125
- const id=message?.id;
126
- if(!file||!Number.isInteger(sender.tab?.id)||!/^[a-f0-9]{32}$/.test(id||'')
127
- ||sender.url!==chrome.runtime.getURL(file)+'?requestId='+id)
128
- return {status:'DENIED',code:'INVALID_MODEL_INTENT_SOURCE'};
129
- const intent=message.intent;
130
- if(!intent||typeof intent!=='object'||Array.isArray(intent)
131
- ||Object.keys(intent).some(k=>k!=='turnToken' && (action==='CONTINUE'?k!=='nextPrompt':k!=='reason'))
132
- ||typeof intent.turnToken!=='string'
133
- ||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(intent.turnToken))
134
- return {status:'DENIED',code:'INVALID_MODEL_INTENT'};
135
- if(action==='CONTINUE' && (typeof intent.nextPrompt!=='string'
136
- ||!intent.nextPrompt.trim()||intent.nextPrompt.length>4000
137
- ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.nextPrompt))
138
- ||action==='HANDOFF' && intent.reason!==undefined
139
- &&(typeof intent.reason!=='string'||intent.reason.length>400
140
- ||/[\x00-\x1f]/.test(intent.reason)))
141
- return {status:'DENIED',code:'INVALID_MODEL_INTENT'};
142
- const run=await readRun();
143
- if(!run||run.phase!=='WAITING_REPLY'||run.modelTurnToken!==intent.turnToken)
144
- return {status:'DENIED',code:'MODEL_INTENT_OWNER_NOT_RUNNING'};
145
- if(run.modelIntent)
146
- return {status:'DENIED',code:'MODEL_INTENT_ALREADY_QUEUED'};
147
- const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
148
- if(!tab||pathOf(tab.url)!==run.page)
149
- return {status:'DENIED',code:'MODEL_INTENT_OWNER_CHANGED'};
150
- const proof=await chrome.tabs.sendMessage(run.tabId,{
151
- type:'CHAT_LOOP_TURN_OBSERVE_V1',poll:true}).catch(()=>null);
152
- if(proof?.contract!=='chat-loop.turn-observer.v1'||proof.status!=='RUNNING'
153
- ||proof.page!==run.page||proof.userKey!==run.newUserKey)
154
- return {status:'DENIED',code:'MODEL_INTENT_TURN_NOT_RUNNING'};
155
- const next = {...run,modelIntent:{
156
- id, action, page:run.page, userKey:run.newUserKey,
157
- ...(action==='CONTINUE'?{nextPrompt:intent.nextPrompt}
158
- :{reason:intent.reason||''}), queuedAt:Date.now()
159
- }};
160
- const correlation=run.sessionId&&run.projectId?{
161
- sessionId:run.sessionId,projectId:run.projectId,
162
- ...(run.taskId?{taskId:run.taskId}:{}),generation:run.generation||0}:{};
163
- await saveRun(updateModelReceipt(next,id,{action,turnToken:intent.turnToken,
164
- ...correlation,status:'QUEUED',reason:null,actualAction:null,
165
- checkpointForwarded:false}));
166
- // Scoped correlation metadata only. This is an intent queue receipt,
167
- // never proof that a browser send happened.
168
- return {status:'QUEUED',action,intentId:id,...correlation};
169
- }
170
- async function onModelIntentStatus(message,sender) {
171
- const action=message?.action;
172
- const file=action==='HANDOFF'?'handoff.html':action==='CONTINUE'?'continue.html':null;
173
- const id=message?.id, intent=message?.intent;
174
- if(!file||!Number.isInteger(sender.tab?.id)||!/^[a-f0-9]{32}$/.test(id||'')
175
- ||sender.url!==chrome.runtime.getURL(file)+'?requestId='+id
176
- ||!intent||typeof intent!=='object'||Array.isArray(intent)
177
- ||typeof intent.turnToken!=='string'
178
- ||!(intent.lookup===true||typeof intent.intentId==='string')
179
- ||Object.keys(intent).some(k=>k!=='turnToken'&&
180
- k!==(intent.lookup===true?'lookup':'intentId'))
181
- ||intent.lookup!==true&& !/^[a-f0-9]{32}$/.test(intent.intentId||''))
182
- return {status:'DENIED',code:'INTENT_QUERY_UNAUTHORIZED'};
183
- const run=await readRun();
184
- const receipts=receiptHistory(run).filter(x=>x.turnToken===intent.turnToken
185
- &&x.action===action);
186
- const receipt=intent.lookup===true?receipts.at(-1)
187
- :receipts.find(x=>x.id===intent.intentId);
188
- if(!receipt)return {status:'DENIED',code:'INTENT_RECEIPT_NOT_FOUND'};
189
- return {status:'STATUS',action,intentId:receipt.id,phase:receipt.status,
190
- ...(receipt.sessionId&&receipt.projectId?{
191
- sessionId:receipt.sessionId,projectId:receipt.projectId,
192
- ...(receipt.taskId?{taskId:receipt.taskId}:{}),
193
- generation:receipt.generation}:{}),
194
- actualAction:receipt.actualAction||null,reason:receipt.reason||null,
195
- checkpointForwarded:receipt.checkpointForwarded===true,
196
- updatedAt:receipt.updatedAt};
197
- }
@@ -1,205 +0,0 @@
1
- // Chat Loop Worker — turn-finished. Imported in order by background.js; no independent Browser Owner.
2
- async function onTurnFinished(message, sender) {
3
- if (!await eligible(sender, message.page)
4
- || typeof message.userKey !== "string" || !/^user:[^\s]{8,}$/.test(message.userKey)
5
- || typeof message.assistantKey !== "string"
6
- || !/^assistant:[^\s]{8,}$/.test(message.assistantKey)
7
- || typeof message.replyText !== "string" || message.replyText.length > 100000) {
8
- return {status: "DENIED", code: "UNVERIFIED_TURN_SOURCE"};
9
- }
10
- const tabId = sender.tab.id;
11
- const previous = await readRun();
12
- // A Chat is owned only after an extension Action has explicitly reserved
13
- // and confirmed its user Turn. A status marker on an arbitrary Chat never
14
- // starts or reactivates a loop, including after DONE/BLOCKED.
15
- if (!previous || ["DONE", "BLOCKED"].includes(previous.phase))
16
- return {status: "IGNORED", code: "NO_ACTIVE_OWNER"};
17
- if (previous.tabId !== tabId || previous.page !== message.page)
18
- return {status: "IGNORED", code: "ANOTHER_CHAT_OWNS_LOOP"};
19
- if (["PENDING", "RESERVED"].includes(previous.phase))
20
- return {status: "IGNORED", code: previous.phase};
21
- if (previous.assistantKey === message.assistantKey
22
- || previous.userKey === message.userKey)
23
- return {status: "IGNORED", code: "ALREADY_HANDLED"};
24
- if (previous.phase !== "WAITING_REPLY")
25
- return {status: "IGNORED", code: "INVALID_PHASE"};
26
- // Previous extension versions may have persisted a confirmed first send
27
- // before recording whether its Context bind completed. Do not downgrade
28
- // such an Owner to unmanaged execution on Worker restart or upgrade.
29
- if(previous.contextLeaseRef&&!previous.contextManaged){
30
- await saveRun({...previous,phase:'BLOCKED',
31
- reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'});
32
- return {status:'BLOCKED',code:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
33
- }
34
- // A clicked ChatGPT choice creates a regular NEW user Turn. Its preceding
35
- // assistant must be the exact already-handled question from this Owner, with
36
- // no intervening user messages. This keeps the old identity boundary
37
- // without adding a WAITING_USER phase or a second communication channel.
38
- const humanReply=["PENDING_CONFIRMATION_DOM","ADOPTED_IDLE_BASELINE"].includes(previous.reason)
39
- && message.userKey!==previous.newUserKey
40
- && previous.userKey && previous.assistantKey
41
- && message.userKey!==previous.userKey
42
- && message.priorAssistantKey===previous.assistantKey
43
- && message.priorAssistantUserKey===previous.userKey
44
- && message.directReplyAfterPriorAssistant===true;
45
- if (message.userKey !== previous.newUserKey && !humanReply) {
46
- await saveRun({...previous, phase: "BLOCKED", reason: "REPLY_USER_MISMATCH"});
47
- return {status: "BLOCKED", code: "REPLY_USER_MISMATCH"};
48
- }
49
- const confirmation=await currentConfirmation(tabId,message.page,
50
- message.userKey,message.assistantKey);
51
- if (message.pendingConfirmation===true || confirmation===true) {
52
- // The current assistant still has an unanswered confirmation widget.
53
- // Do not open a Continue/Handoff Action, even after its old deadline.
54
- const held=settleModelIntent({...previous,phase:"WAITING_REPLY",
55
- userKey:message.userKey,assistantKey:message.assistantKey,
56
- reason:"PENDING_CONFIRMATION_DOM"},
57
- "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
58
- await saveRun(held);
59
- return {status:"IGNORED",code:"PENDING_CONFIRMATION_DOM"};
60
- }
61
- if (confirmation===null) {
62
- await saveRun({...previous,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
63
- return {status:"BLOCKED",code:"CONFIRMATION_DOM_UNVERIFIED"};
64
- }
65
- let replyText = message.replyText;
66
- let status = workerApi.parseStatus(replyText);
67
- if (status === "UNKNOWN") {
68
- const recovery = await recheckUnknownTurn(message, previous, tabId);
69
- if (recovery) {status = recovery.status; replyText = recovery.replyText;}
70
- }
71
- const now = Date.now();
72
- // Keep the same clock throughout one Chat. A successful Handoff resets it.
73
- const initial = Number.isSafeInteger(message.startedAt) && message.startedAt > 0
74
- && message.startedAt <= now ? message.startedAt : now;
75
- const startedAt = previous?.phase === "WAITING_REPLY"
76
- ? previous.startedAt || now : initial;
77
- const timeExpired = now >= startedAt + windowMsOf(previous);
78
- // Deadline intent can be persisted by the timer even while a Turn RUNS.
79
- // The decision below still waits for the observer's complete Turn proof.
80
- const queued = !humanReply && previous?.modelIntent?.page===message.page
81
- && previous.modelIntent.userKey===message.userKey ? previous.modelIntent : null;
82
- // Existing DONE/BLOCKED, deadline and page-error policies still win.
83
- // A queued model request only changes a still-eligible CONTINUE Turn.
84
- let nextAction = status === "HANDOFF" ? "UNSUPPORTED_MODEL_HANDOFF"
85
- : (previous?.handoffPending || timeExpired) && status === "CONTINUE"
86
- ? "HANDOFF" : status === "CONTINUE" && queued
87
- ? queued.action : status;
88
- if (nextAction !== "CONTINUE" && nextAction !== "HANDOFF") {
89
- if (previous?.phase === "WAITING_REPLY" && previous.tabId === tabId) {
90
- const terminal={...previous, phase:status==="DONE"?"DONE":"BLOCKED",
91
- reason:status,userKey:message.userKey,assistantKey:message.assistantKey};
92
- if(status==="DONE"&&previous.contextManaged&&previous.taskId){
93
- // Check the actual Context delivery BEFORE publishing a durable DONE.
94
- // A model's machine marker alone is never a committed Task outcome.
95
- const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
96
- op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
97
- const fact=observed?.result;
98
- if(observed?.status!=="OK"||fact?.executionOutcome!=="DONE"
99
- ||!fact.deliveryRef
100
- ||fact.runRef!==previous.sessionId+":"+previous.taskId+":"+(previous.generation||0)){
101
- await saveRun({...terminal,phase:"BLOCKED",
102
- reason:"CONTEXT_TERMINAL_NOT_COMMITTED",contextTerminalFence:"UNVERIFIED"});
103
- return {status:"BLOCKED",code:"CONTEXT_TERMINAL_NOT_COMMITTED"};
104
- }
105
- // The signed Native fence requires phase DONE; keep a durable
106
- // PENDING marker that denies IDLE/Start until the fence is verified.
107
- await saveRun({...terminal,contextTerminalFence:"PENDING"});
108
- const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
109
- op:"context-control",command:"run.fence.terminal",
110
- args:{expectedStoreEpoch:previous.contextManaged.storeEpoch,
111
- writeRequestId:"terminal:"+previous.sessionId+":"+(previous.generation||0),
112
- expectedTaskRevision:fact.taskRevision,
113
- expectedBindingRevision:fact.bindingRevision}
114
- }).catch(()=>null);
115
- if(fenced?.status!=="OK"||fenced.result?.status!=="TERMINAL_FENCED"){
116
- // Native DONE cannot regress to BLOCKED. Leave that truthful
117
- // projection in place, but never treat it as released write rights.
118
- await saveRun({...terminal,reason:"CONTEXT_TERMINAL_FENCE_UNVERIFIED",
119
- contextTerminalFence:"UNVERIFIED"});
120
- return {status:"BLOCKED",code:"CONTEXT_TERMINAL_FENCE_UNVERIFIED"};
121
- }
122
- await saveRun({...terminal,contextTerminalFence:"CONFIRMED"});
123
- }else await saveRun(terminal);
124
- }
125
- return {status: "IGNORED", code: nextAction === "UNSUPPORTED_MODEL_HANDOFF"
126
- ? "MODEL_HANDOFF_DISABLED" : status};
127
- }
128
- // Recheck at the last new-authorization boundary, even if a periodic or
129
- // one-shot alarm was delayed while the Worker handled completion evidence.
130
- const newlyDue = Date.now() >= startedAt + windowMsOf(previous);
131
- if (nextAction === "CONTINUE" && newlyDue) nextAction = "HANDOFF";
132
- const token = crypto.randomUUID();
133
- const run = {...(previous?.sessionId ? {sessionId: previous.sessionId,
134
- projectId: previous.projectId,...(previous.taskId?{taskId:previous.taskId}:{}),
135
- ...(previous.contextManaged?{contextManaged:previous.contextManaged}:{}),
136
- generation: previous.generation || 0} : {}),
137
- tabId, page: message.page, userKey: message.userKey,
138
- assistantKey: message.assistantKey, phase: "RESERVED", token,
139
- action: nextAction, startedAt, modelReceipts:receiptHistory(previous),
140
- // Preserve the last recovered message across normal progress: a repair
141
- // acknowledgement cannot replay that same failed Turn.
142
- ...(previous?.recoveryAttempts ? {recoveryAttempts:previous.recoveryAttempts,
143
- ...(previous.recoveryProtocol?{recoveryProtocol:previous.recoveryProtocol}:{}),
144
- ...(previous.recoverySourceAssistantKey?{recoverySourceAssistantKey:previous.recoverySourceAssistantKey}:{})} : {}),
145
- // Preserve an explicitly configured window through every Continue and
146
- // Handoff. Otherwise the clock silently falls back to the default
147
- // after the first completed Turn, breaking the persisted deadline.
148
- ...(Number.isSafeInteger(previous?.windowMs) && previous.windowMs > 0
149
- ? {windowMs:previous.windowMs} : {}),
150
- ...(previous?.lastFaultProof ? {lastFaultProof:previous.lastFaultProof} : {}),
151
- ...((previous?.handoffPending || newlyDue) ? {
152
- handoffPending: true,
153
- handoffPendingAt: previous?.handoffPendingAt || Date.now()} : {}),
154
- // A completed Turn is a successful recovery and clears the consecutive error-Handoff guard.
155
- errorHandoffCount: 0,
156
- // A timed Handoff uses an Action-local read-only snapshot. Do not keep
157
- // the entire conversation in storage or embed it in the Action URL.
158
- handoffMode: nextAction === "HANDOFF" ? "TIMED" : null,
159
- ...(status==="CONTINUE" && queued
160
- && (queued.action===nextAction
161
- ||queued.action==="CONTINUE"&&nextAction==="HANDOFF")
162
- ? {modelIntent:queued} : {})};
163
- // Deadline wins, but the queued continuation is retained as a *proposal*
164
- // in the bounded Handoff packet instead of silently losing task progress.
165
- const overridden=queued?.action==="CONTINUE"&&nextAction==="HANDOFF";
166
- const recorded=queued?updateModelReceipt(run,queued.id,{
167
- status:overridden?"OVERRIDDEN_BY_DEADLINE":"RESERVED",
168
- actualAction:nextAction,
169
- reason:overridden?"OVERRIDDEN_BY_DEADLINE":null,
170
- checkpointForwarded:false}):run;
171
- // Durable before opening an Action; an uncertain outcome must never be retried.
172
- await saveRun(recorded);
173
- try {
174
- const url = chrome.runtime.getURL(nextAction === "HANDOFF" ? "handoff.html" : "continue.html")
175
- + "?tabId=" + tabId + "&token=" + encodeURIComponent(token);
176
- const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
177
- return {status: "QUEUED", actionTabId: actionTab.id};
178
- } catch (error) {
179
- await saveRun({...recorded, phase: "BLOCKED", reason: "ACTION_PAGE_CREATE_FAILED"});
180
- return {status: "BLOCKED", code: safeWorkerErrorCode(error,"ACTION_PAGE_CREATE_FAILED")};
181
- }
182
- }
183
- // Recover ONLY an interrupted pre-send reservation from the old Worker
184
- // implementation: Chrome said RESERVED, native still said BLOCKED, so no
185
- // ACTION_TAKE/PENDING/DOM click could have occurred. Invalidate that token
186
- // through the same authorized scheduler, never by editing the disk file.
187
- async function repairUncommittedBlockedRecovery(){
188
- const run=await readRun();
189
- if(run?.phase!=="RESERVED"
190
- ||run.recoveryMode!=="TOOL_PREFLIGHT_REPAIRED"
191
- ||run.recoveryAttempts!==1 || run.recoveryProtocol || !run.sessionId
192
- ||!Number.isInteger(run.manualActionTabId))
193
- return run;
194
- const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
195
- {op:"session-read"}).catch(()=>null);
196
- if(disk?.status!=="OK"
197
- ||!matchesNativeProjection(sessionProjection({...run,phase:"BLOCKED"}),disk.session))
198
- return run;
199
- const restored={...run,phase:"BLOCKED",reason:"BLOCKED",recoveryAttempts:0};
200
- for(const field of ["recoveryMode","recoverySourceAssistantKey","token",
201
- "manualActionTabId","actionPendingAt","resourceToken"])
202
- delete restored[field];
203
- await saveRun(restored);
204
- return restored;
205
- }