@tomflow/chatloop-extension 0.3.84 → 0.4.0

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 (54) hide show
  1. package/README.md +74 -73
  2. package/actions.generated.mjs +11 -0
  3. package/bin/cli.mjs +22 -24
  4. package/bin/native-host.mjs +14 -5
  5. package/capabilities/chat_dom.mjs +1 -0
  6. package/capabilities/chat_screenshot.mjs +1 -0
  7. package/capabilities/chat_text.mjs +1 -0
  8. package/capabilities/clean.mjs +1 -0
  9. package/capabilities/continue.mjs +1 -0
  10. package/capabilities/handoff.mjs +1 -0
  11. package/capabilities/reload.mjs +1 -0
  12. package/capabilities/start.mjs +1 -0
  13. package/capabilities/status.mjs +1 -0
  14. package/extension/actions/common.js +14 -3
  15. package/extension/actions/continue.js +1 -1
  16. package/extension/actions/handoff.js +5 -3
  17. package/extension/actions/index.js +2 -0
  18. package/extension/actions/read-mode.js +9 -0
  19. package/extension/actions/start.js +1 -1
  20. package/extension/background.js +16 -2202
  21. package/extension/loop/action-catalog.generated.js +2 -0
  22. package/extension/loop/api-aspect.generated.js +192 -0
  23. package/extension/loop/core.js +81 -3
  24. package/extension/loop/index.js +34 -0
  25. package/extension/loop/observer-approval.js +227 -0
  26. package/extension/loop/observer-inspect.js +144 -0
  27. package/extension/loop/observer-poll.js +171 -0
  28. package/extension/loop/observer-recovery.js +109 -0
  29. package/extension/loop/observer.js +27 -630
  30. package/extension/loop/resources.js +8 -1
  31. package/extension/manifest.json +6 -2
  32. package/extension/worker/action-result.js +136 -0
  33. package/extension/worker/action-take.js +220 -0
  34. package/extension/worker/admission.js +122 -0
  35. package/extension/worker/adopt-prepare.js +155 -0
  36. package/extension/worker/adopt-recovery.js +185 -0
  37. package/extension/worker/adopt-result.js +120 -0
  38. package/extension/worker/bootstrap.js +172 -0
  39. package/extension/worker/manual.js +165 -0
  40. package/extension/worker/readiness.js +242 -0
  41. package/extension/worker/router.js +150 -0
  42. package/extension/worker/scheduler.js +147 -0
  43. package/extension/worker/turn-failure.js +197 -0
  44. package/extension/worker/turn-finished.js +200 -0
  45. package/index.mjs +62 -0
  46. package/lib/action-routing.mjs +18 -0
  47. package/lib/api-aspect.mjs +190 -0
  48. package/lib/bridge.mjs +26 -7
  49. package/lib/context-binding.mjs +6 -1
  50. package/lib/context-ipc.mjs +44 -2
  51. package/lib/owner-evidence.mjs +67 -0
  52. package/lib/session-file.mjs +20 -8
  53. package/package.json +13 -3
  54. package/scripts/build-actions.mjs +133 -0
@@ -0,0 +1,147 @@
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
+ async function reconnectOpenChats() {
4
+ const tabs = await chrome.tabs.query({url: "https://chatgpt.com/*"});
5
+ for (const tab of tabs) {
6
+ if (!Number.isInteger(tab.id) || !pathOf(tab.url) && !/^https:\/\/chatgpt\.com\/$/.test(tab.url)) continue;
7
+ try {
8
+ await chrome.scripting.executeScript({target: {tabId: tab.id},
9
+ files: ["content.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
10
+ const owner = await readRun();
11
+ if (owner?.phase === "WAITING_REPLY" && owner.tabId === tab.id
12
+ && owner.page === pathOf(tab.url) && owner.newUserKey) {
13
+ // Normal WAITING_REPLY uses its original zero-extra-read resume.
14
+ // Only a previously seen pending confirmation needs an extra DOM
15
+ // identity check for a human response that arrived during reload.
16
+ const proof=owner.reason==="PENDING_CONFIRMATION_DOM"
17
+ ? await chrome.tabs.sendMessage(tab.id,
18
+ {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null)
19
+ :null;
20
+ const freshUser=proof?.page===owner.page
21
+ && proof.userKey!==owner.newUserKey
22
+ && proof.priorAssistantKey===owner.assistantKey
23
+ && proof.priorAssistantUserKey===owner.userKey
24
+ && proof.directReplyAfterPriorAssistant===true;
25
+ const res = await chrome.tabs.sendMessage(tab.id, {
26
+ type: "CHAT_LOOP_TURN_RESUME_V1", page: owner.page,
27
+ userKey:freshUser?proof.userKey:owner.newUserKey,
28
+ assistantKey: owner.assistantKey || null,
29
+ ...(owner.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
30
+ startedAt: owner.startedAt
31
+ }).catch(() => null);
32
+ if (res?.status !== "RESUMED" && res?.status !== "ALREADY_MONITORING")
33
+ console.warn("Chat Loop pending Turn resume not yet verified:", res?.reason || res?.status);
34
+ }
35
+ } catch (error) {console.warn("Chat Loop observer reconnect unavailable:", error?.message);}
36
+ }
37
+ }
38
+ // MV3 background service workers can suspend, and hidden-page setInterval
39
+ // may be throttled. An alarm asks the Observer to sample, never acts directly.
40
+ async function ensureAlarm() {
41
+ if (!chrome.alarms?.create) return;
42
+ const existing = await chrome.alarms.get?.(ALARM_NAME).catch(() => null);
43
+ if (!existing) await chrome.alarms.create(ALARM_NAME, {periodInMinutes: 1});
44
+ }
45
+ async function watchActiveTurn() {
46
+ // One bounded reconciliation on the existing 1-minute Worker alarm.
47
+ await serial(async()=>{await expireStaleAction();
48
+ await resources.reconcile(await readRun()).catch(()=>{});});
49
+ // Normal periodic wakeups also reconcile a delayed one-shot deadline.
50
+ // All state changes share the same serial queue as Turn/Action receipts.
51
+ await serial(async()=>{await expireStaleModelIntent();await prepareHandoffIfDue();});
52
+ const run = await readRun();
53
+ // While an Action is pending, never dispatch competing operations.
54
+ if (run && ["RESERVED", "PENDING"].includes(run.phase)) return;
55
+ const tabs = run?.phase === "WAITING_REPLY"
56
+ ? [await chrome.tabs.get(run.tabId).catch(() => null)]
57
+ : await chrome.tabs.query({url: "https://chatgpt.com/*"});
58
+ for (const tab of tabs) {
59
+ if (!tab?.id || !pathOf(tab.url)) continue;
60
+ try {
61
+ const proof = await chrome.tabs.sendMessage(tab.id,
62
+ {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true});
63
+ // A reloaded Observer may have mistaken the in-flight user Turn for
64
+ // historical baseline. Its IDLE state is not proof of completion.
65
+ // Rebind the exact persisted owner using read-only verification.
66
+ const freshHuman=run?.phase==="WAITING_REPLY" && run.tabId===tab.id
67
+ && proof?.page===run.page && proof.userKey!==run.newUserKey
68
+ && proof.priorAssistantKey===run.assistantKey
69
+ && proof.priorAssistantUserKey===run.userKey
70
+ && proof.directReplyAfterPriorAssistant===true;
71
+ if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
72
+ && proof?.page === run.page
73
+ && (proof.userKey === run.newUserKey || freshHuman)
74
+ && (proof.status === "IDLE"
75
+ || proof.status === "UNKNOWN"
76
+ && ["ATTACHING_CHAT", "WAITING_CHAT_HYDRATION"].includes(proof.reason))) {
77
+ await chrome.tabs.sendMessage(tab.id, {
78
+ type: "CHAT_LOOP_TURN_RESUME_V1", page: run.page,
79
+ userKey: freshHuman?proof.userKey:run.newUserKey,
80
+ assistantKey: run.assistantKey || null,
81
+ ...(run.reason==='ADOPTED_IDLE_BASELINE'?{baselineOnly:true}:{}),
82
+ startedAt: run.startedAt
83
+ }).catch(() => null);
84
+ }
85
+ // A human response can fail after the previous question was kept in
86
+ // WAITING_REPLY. Do not let this become an indefinite silent wait.
87
+ if(freshHuman && proof.status==="BLOCKED") {
88
+ void serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
89
+ reason:proof.reason||"PAGE_ERROR"},
90
+ {tab,url:tab.url}));
91
+ }
92
+ // Alarm is still read-only. It may reconcile a verified page failure if
93
+ // the observer's original notification was lost while Worker slept.
94
+ if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
95
+ && proof?.status === "BLOCKED" && ["PAGE_ERROR","CONTEXT_LIMIT","SECURITY_CHALLENGE"].includes(proof.reason)
96
+ && proof.page === run.page && proof.userKey === run.newUserKey) {
97
+ void serial(() => onTurnBlocked({page: run.page,
98
+ userKey: run.newUserKey, reason: proof.reason},
99
+ {tab, url: tab.url}));
100
+ }
101
+ } catch { /* Observer unavailable; never infer Turn completion. */ }
102
+ }
103
+ }
104
+ chrome.alarms?.onAlarm?.addListener(alarm => {
105
+ if (alarm?.name === ALARM_NAME) void watchActiveTurn();
106
+ if (alarm?.name === DEADLINE_ALARM_NAME)
107
+ void serial(prepareHandoffIfDue);
108
+ });
109
+ chrome.runtime.onInstalled?.addListener(() => {
110
+ void ensureAlarm();
111
+ void serial(async()=>{await expireStaleAction();
112
+ await resources.reconcile(await readRun()).catch(()=>{});});
113
+ void reconnectOpenChats();
114
+ });
115
+ chrome.runtime.onStartup?.addListener(() => {
116
+ void ensureAlarm();
117
+ void serial(async()=>{await expireStaleAction();
118
+ await resources.reconcile(await readRun()).catch(()=>{});});
119
+ void reconnectOpenChats();
120
+ });
121
+ void ensureAlarm();
122
+ // Reconcile an elapsed deadline after MV3 Worker suspension/reload.
123
+ void serial(async()=>{await expireStaleAction();
124
+ await resources.reconcile(await readRun()).catch(()=>{});
125
+ await prepareHandoffIfDue();});
126
+ // A manual extension Reload does not necessarily fire onInstalled/onStartup.
127
+ // Reattach the two idempotent read-only scripts to existing ChatGPT tabs.
128
+ void reconnectOpenChats();
129
+ // User-clicked popup Clean must share the same Action quota as Worker actions.
130
+ // The popup cannot create extra Chrome tabs directly.
131
+ async function openPopupClean(message,sender) {
132
+ if(sender?.url!==chrome.runtime.getURL('popup.html')
133
+ ||!Number.isSafeInteger(message?.tabId)||message.tabId<=0)
134
+ return {status:'DENIED',code:'POPUP_SOURCE_INVALID'};
135
+ const target=await chrome.tabs.get(message.tabId).catch(()=>null);
136
+ let valid=false;
137
+ try {valid=target?.active===true && Number.isSafeInteger(target.windowId)
138
+ && new URL(target.url).origin==='https://chatgpt.com';} catch {}
139
+ if(!valid)return {status:'DENIED',code:'CLEAN_TARGET_UNVERIFIED'};
140
+ try {
141
+ const action=await createBoundedAction({url:chrome.runtime.getURL('clean.html')
142
+ +'?tabId='+target.id,windowId:target.windowId,active:true});
143
+ return {status:'OK',actionTabId:action.id};
144
+ } catch(error) {
145
+ return {status:'BLOCKED',code:error?.message||'CLEAN_ACTION_UNVERIFIED'};
146
+ }
147
+ }
@@ -0,0 +1,197 @@
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
+ }
@@ -0,0 +1,200 @@
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
+ // A clicked ChatGPT choice creates a regular NEW user Turn. Its preceding
27
+ // assistant must be the exact already-handled question from this Owner, with
28
+ // no intervening user messages. This keeps the old identity boundary
29
+ // without adding a WAITING_USER phase or a second communication channel.
30
+ const humanReply=["PENDING_CONFIRMATION_DOM","ADOPTED_IDLE_BASELINE"].includes(previous.reason)
31
+ && message.userKey!==previous.newUserKey
32
+ && previous.userKey && previous.assistantKey
33
+ && message.userKey!==previous.userKey
34
+ && message.priorAssistantKey===previous.assistantKey
35
+ && message.priorAssistantUserKey===previous.userKey
36
+ && message.directReplyAfterPriorAssistant===true;
37
+ if (message.userKey !== previous.newUserKey && !humanReply) {
38
+ await saveRun({...previous, phase: "BLOCKED", reason: "REPLY_USER_MISMATCH"});
39
+ return {status: "BLOCKED", code: "REPLY_USER_MISMATCH"};
40
+ }
41
+ const confirmation=await currentConfirmation(tabId,message.page,
42
+ message.userKey,message.assistantKey);
43
+ if (message.pendingConfirmation===true || confirmation===true) {
44
+ // The current assistant still has an unanswered confirmation widget.
45
+ // Do not open a Continue/Handoff Action, even after its old deadline.
46
+ const held=settleModelIntent({...previous,phase:"WAITING_REPLY",
47
+ userKey:message.userKey,assistantKey:message.assistantKey,
48
+ reason:"PENDING_CONFIRMATION_DOM"},
49
+ "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
50
+ await saveRun(held);
51
+ return {status:"IGNORED",code:"PENDING_CONFIRMATION_DOM"};
52
+ }
53
+ if (confirmation===null) {
54
+ await saveRun({...previous,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
55
+ return {status:"BLOCKED",code:"CONFIRMATION_DOM_UNVERIFIED"};
56
+ }
57
+ let replyText = message.replyText;
58
+ let status = workerApi.parseStatus(replyText);
59
+ if (status === "UNKNOWN") {
60
+ const recovery = await recheckUnknownTurn(message, previous, tabId);
61
+ if (recovery) {status = recovery.status; replyText = recovery.replyText;}
62
+ }
63
+ const now = Date.now();
64
+ // Keep the same clock throughout one Chat. A successful Handoff resets it.
65
+ const initial = Number.isSafeInteger(message.startedAt) && message.startedAt > 0
66
+ && message.startedAt <= now ? message.startedAt : now;
67
+ const startedAt = previous?.phase === "WAITING_REPLY"
68
+ ? previous.startedAt || now : initial;
69
+ const timeExpired = now >= startedAt + windowMsOf(previous);
70
+ // Deadline intent can be persisted by the timer even while a Turn RUNS.
71
+ // The decision below still waits for the observer's complete Turn proof.
72
+ const queued = !humanReply && previous?.modelIntent?.page===message.page
73
+ && previous.modelIntent.userKey===message.userKey ? previous.modelIntent : null;
74
+ // Existing DONE/BLOCKED, deadline and page-error policies still win.
75
+ // A queued model request only changes a still-eligible CONTINUE Turn.
76
+ let nextAction = status === "HANDOFF" ? "UNSUPPORTED_MODEL_HANDOFF"
77
+ : (previous?.handoffPending || timeExpired) && status === "CONTINUE"
78
+ ? "HANDOFF" : status === "CONTINUE" && queued
79
+ ? queued.action : status;
80
+ if (nextAction !== "CONTINUE" && nextAction !== "HANDOFF") {
81
+ if (previous?.phase === "WAITING_REPLY" && previous.tabId === tabId) {
82
+ const terminal={...previous, phase:status==="DONE"?"DONE":"BLOCKED",
83
+ reason:status,userKey:message.userKey,assistantKey:message.assistantKey};
84
+ if(status==="DONE"&&previous.contextManaged&&previous.taskId){
85
+ // Check the actual Context delivery BEFORE publishing a durable DONE.
86
+ // A model's machine marker alone is never a committed Task outcome.
87
+ const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
88
+ op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
89
+ const fact=observed?.result;
90
+ if(observed?.status!=="OK"||fact?.executionOutcome!=="DONE"
91
+ ||!fact.deliveryRef
92
+ ||fact.runRef!==previous.sessionId+":"+previous.taskId+":"+(previous.generation||0)){
93
+ await saveRun({...terminal,phase:"BLOCKED",
94
+ reason:"CONTEXT_TERMINAL_NOT_COMMITTED",contextTerminalFence:"UNVERIFIED"});
95
+ return {status:"BLOCKED",code:"CONTEXT_TERMINAL_NOT_COMMITTED"};
96
+ }
97
+ // The signed Native fence requires phase DONE; keep a durable
98
+ // PENDING marker that denies IDLE/Start until the fence is verified.
99
+ await saveRun({...terminal,contextTerminalFence:"PENDING"});
100
+ const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
101
+ op:"context-control",command:"run.fence.terminal",
102
+ args:{expectedStoreEpoch:previous.contextManaged.storeEpoch,
103
+ writeRequestId:"terminal:"+previous.sessionId+":"+(previous.generation||0),
104
+ expectedTaskRevision:fact.taskRevision,
105
+ expectedBindingRevision:fact.bindingRevision}
106
+ }).catch(()=>null);
107
+ if(fenced?.status!=="OK"||fenced.result?.status!=="TERMINAL_FENCED"){
108
+ // Native DONE cannot regress to BLOCKED. Leave that truthful
109
+ // projection in place, but never treat it as released write rights.
110
+ await saveRun({...terminal,reason:"CONTEXT_TERMINAL_FENCE_UNVERIFIED",
111
+ contextTerminalFence:"UNVERIFIED"});
112
+ return {status:"BLOCKED",code:"CONTEXT_TERMINAL_FENCE_UNVERIFIED"};
113
+ }
114
+ await saveRun({...terminal,contextTerminalFence:"CONFIRMED"});
115
+ }else await saveRun(terminal);
116
+ }
117
+ return {status: "IGNORED", code: nextAction === "UNSUPPORTED_MODEL_HANDOFF"
118
+ ? "MODEL_HANDOFF_DISABLED" : status};
119
+ }
120
+ // Recheck at the last new-authorization boundary, even if a periodic or
121
+ // one-shot alarm was delayed while the Worker handled completion evidence.
122
+ const newlyDue = Date.now() >= startedAt + windowMsOf(previous);
123
+ if (nextAction === "CONTINUE" && newlyDue) nextAction = "HANDOFF";
124
+ const token = crypto.randomUUID();
125
+ const run = {...(previous?.sessionId ? {sessionId: previous.sessionId,
126
+ projectId: previous.projectId,...(previous.taskId?{taskId:previous.taskId}:{}),
127
+ ...(previous.contextManaged?{contextManaged:previous.contextManaged}:{}),
128
+ generation: previous.generation || 0} : {}),
129
+ tabId, page: message.page, userKey: message.userKey,
130
+ assistantKey: message.assistantKey, phase: "RESERVED", token,
131
+ action: nextAction, startedAt, modelReceipts:receiptHistory(previous),
132
+ // Preserve the last recovered message across normal progress: a repair
133
+ // acknowledgement cannot replay that same failed Turn.
134
+ ...(previous?.recoveryAttempts ? {recoveryAttempts:previous.recoveryAttempts,
135
+ ...(previous.recoveryProtocol?{recoveryProtocol:previous.recoveryProtocol}:{}),
136
+ ...(previous.recoverySourceAssistantKey?{recoverySourceAssistantKey:previous.recoverySourceAssistantKey}:{})} : {}),
137
+ // Preserve an explicitly configured window through every Continue and
138
+ // Handoff. Otherwise the clock silently falls back to the default
139
+ // after the first completed Turn, breaking the persisted deadline.
140
+ ...(Number.isSafeInteger(previous?.windowMs) && previous.windowMs > 0
141
+ ? {windowMs:previous.windowMs} : {}),
142
+ ...(previous?.lastFaultProof ? {lastFaultProof:previous.lastFaultProof} : {}),
143
+ ...((previous?.handoffPending || newlyDue) ? {
144
+ handoffPending: true,
145
+ handoffPendingAt: previous?.handoffPendingAt || Date.now()} : {}),
146
+ // A completed Turn is a successful recovery and clears the consecutive error-Handoff guard.
147
+ errorHandoffCount: 0,
148
+ // A timed Handoff uses an Action-local read-only snapshot. Do not keep
149
+ // the entire conversation in storage or embed it in the Action URL.
150
+ handoffMode: nextAction === "HANDOFF" ? "TIMED" : null,
151
+ ...(status==="CONTINUE" && queued
152
+ && (queued.action===nextAction
153
+ ||queued.action==="CONTINUE"&&nextAction==="HANDOFF")
154
+ ? {modelIntent:queued} : {})};
155
+ // Deadline wins, but the queued continuation is retained as a *proposal*
156
+ // in the bounded Handoff packet instead of silently losing task progress.
157
+ const overridden=queued?.action==="CONTINUE"&&nextAction==="HANDOFF";
158
+ const recorded=queued?updateModelReceipt(run,queued.id,{
159
+ status:overridden?"OVERRIDDEN_BY_DEADLINE":"RESERVED",
160
+ actualAction:nextAction,
161
+ reason:overridden?"OVERRIDDEN_BY_DEADLINE":null,
162
+ checkpointForwarded:false}):run;
163
+ // Durable before opening an Action; an uncertain outcome must never be retried.
164
+ await saveRun(recorded);
165
+ try {
166
+ const url = chrome.runtime.getURL(nextAction === "HANDOFF" ? "handoff.html" : "continue.html")
167
+ + "?tabId=" + tabId + "&token=" + encodeURIComponent(token);
168
+ const actionTab = await createBoundedAction({url, active: false, windowId: sender.tab.windowId});
169
+ return {status: "QUEUED", actionTabId: actionTab.id};
170
+ } catch (error) {
171
+ await saveRun({...recorded, phase: "BLOCKED", reason: "ACTION_PAGE_CREATE_FAILED"});
172
+ return {status: "BLOCKED", code: error.message || "ACTION_PAGE_CREATE_FAILED"};
173
+ }
174
+ }
175
+ // Recover ONLY an interrupted pre-send reservation from the old Worker
176
+ // implementation: Chrome said RESERVED, native still said BLOCKED, so no
177
+ // ACTION_TAKE/PENDING/DOM click could have occurred. Invalidate that token
178
+ // through the same authorized scheduler, never by editing the disk file.
179
+ async function repairUncommittedBlockedRecovery(){
180
+ const run=await readRun();
181
+ if(run?.phase!=="RESERVED"
182
+ ||run.recoveryMode!=="TOOL_PREFLIGHT_REPAIRED"
183
+ ||run.recoveryAttempts!==1 || run.recoveryProtocol || !run.sessionId
184
+ ||!Number.isInteger(run.manualActionTabId))
185
+ return run;
186
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
187
+ {op:"session-read"}).catch(()=>null);
188
+ if(disk?.status!=="OK"||disk.session?.phase!=="BLOCKED"
189
+ ||disk.session.sessionId!==run.sessionId
190
+ ||disk.session.projectId!==run.projectId
191
+ ||disk.session.generation!==(run.generation||0)
192
+ ||disk.session.activeChatId!==chatIdOf("https://chatgpt.com"+run.page))
193
+ return run;
194
+ const restored={...run,phase:"BLOCKED",reason:"BLOCKED",recoveryAttempts:0};
195
+ for(const field of ["recoveryMode","recoverySourceAssistantKey","token",
196
+ "manualActionTabId","actionPendingAt","resourceToken"])
197
+ delete restored[field];
198
+ await saveRun(restored);
199
+ return restored;
200
+ }
package/index.mjs ADDED
@@ -0,0 +1,62 @@
1
+ // Sole npm SDK entry: all private module dependencies are composed here.
2
+ // Node-native Worker entrypoints consume these APIs, never lib/* paths.
3
+ import {fileURLToPath} from 'node:url';
4
+ import {actionCapabilities} from './actions.generated.mjs';
5
+ import {matchExtensionAction} from './lib/action-routing.mjs';
6
+ import {createApiAspect} from './lib/api-aspect.mjs';
7
+ const apiAspect=createApiAspect('@tomflow/chatloop-extension',{
8
+ sink:record=>{
9
+ // The audit transport itself must never trigger another Native audit.
10
+ // The wrapper still intercepts it, but re-emitting it would recurse.
11
+ if(record.api==='nativeHostApi'||
12
+ record.api==='nativeHostApi.nativeApiObservation')return;
13
+ return ipc.nativeApiObservation({
14
+ callId:record.callId,traceId:record.traceId,spanId:record.spanId,
15
+ ...(record.parentSpanId?{parentSpanId:record.parentSpanId}:{}),
16
+ apiName:'extension.'+record.surface+'.'+record.api,
17
+ phase:record.phase,
18
+ ...(record.durationMs!==null?{durationMs:record.durationMs}:{}),
19
+ ...(record.errorCode?{errorCode:record.errorCode}:{})
20
+ });
21
+ }
22
+ });
23
+ import * as bridge from './lib/bridge.mjs';
24
+ import * as session from './lib/session-file.mjs';
25
+ import * as binding from './lib/context-binding.mjs';
26
+ import * as ipc from './lib/context-ipc.mjs';
27
+ import * as evidence from './lib/owner-evidence.mjs';
28
+
29
+ bridge.configureBridgeActions(actionCapabilities);
30
+ binding.configureContextBinding({configFile:bridge.configFile});
31
+ evidence.configureOwnerEvidence({
32
+ readSession:session.readSession,sessionPath:session.sessionPath,
33
+ cliPath:()=>fileURLToPath(new URL('./bin/cli.mjs',import.meta.url))
34
+ });
35
+
36
+ // Bounded provider contract for Context's reviewed orphan fence.
37
+ export const verifyOrphanOwnerIdle=apiAspect.observe(
38
+ 'verifyOrphanOwnerIdle',evidence.verifyOrphanOwnerIdle);
39
+
40
+ // Internal entrypoint contracts, not a second npm subpath.
41
+ export const extensionCliApi=apiAspect.observe('extensionCliApi',
42
+ ()=>apiAspect.methods(Object.freeze({
43
+ ACTIONS:bridge.ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME:bridge.HOST_NAME,
44
+ configFile:bridge.configFile,prepare:bridge.prepare,
45
+ readResult:bridge.readResult,privateDir:bridge.privateDir,
46
+ validateExtensionId:bridge.validateExtensionId
47
+ }), 'extensionCliApi','cli'));
48
+ export const nativeHostApi=apiAspect.observe('nativeHostApi',
49
+ ()=>apiAspect.methods(Object.freeze({
50
+ readRequest:bridge.readRequest,finish:bridge.finish,
51
+ readSession:session.readSession,writeSession:session.writeSession,
52
+ registeredContext:binding.registeredContext,
53
+ nativeContextControl:ipc.nativeContextControl,
54
+ // One named, non-authoritative span for each Native messaging operation.
55
+ observeNativeOperation:(op,perform)=>{
56
+ if(typeof perform!=='function')throw TypeError('NATIVE_OPERATION_REQUIRED');
57
+ const name=typeof op==='string'&&/^[a-z][a-z0-9-]{0,60}$/.test(op)
58
+ ?op:'invalid';
59
+ return apiAspect.observe('native.op.'+name,perform,'native')();
60
+ },
61
+ nativeApiObservation:ipc.nativeApiObservation
62
+ }), 'nativeHostApi','native'));
@@ -0,0 +1,18 @@
1
+ // One CLI interpretation rule for every statically declared browser Action.
2
+ // Only the three reviewed owner-control kinds can request privileged intent.
3
+ export function matchExtensionAction(catalog,argv){
4
+ if(!Array.isArray(argv)||argv[0]!=='extension')return null;
5
+ const input=argv.slice(1);
6
+ for(const cap of catalog){
7
+ if(!Array.isArray(cap.cli))continue;
8
+ const route=cap.cli;
9
+ if(input.length===route.length+1&&cap.kind==='owner-clean'
10
+ &&input.slice(0,route.length).join(' ')===route.join(' ')
11
+ &&/^[1-9][0-9]*$/.test(input.at(-1))
12
+ &&Number.isSafeInteger(Number(input.at(-1))))
13
+ return {id:cap.id,intent:{tabId:Number(input.at(-1))}};
14
+ if(input.length===route.length&&input.join(' ')===route.join(' '))
15
+ return {id:cap.id,needsIntent:['owner-intent','owner-start'].includes(cap.kind)};
16
+ }
17
+ return null;
18
+ }