@tomflow/chatloop-tools 0.9.63 → 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 (83) 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 +16 -7
  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/node_modules/@tomflow/chatloop-context/README.md +56 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +24 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +1 -1
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +2 -2
  12. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +69 -0
  13. package/node_modules/@tomflow/chatloop-context/index.mjs +3 -1
  14. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +50 -3
  15. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +54 -1
  16. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +2 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +61 -2
  18. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +33 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +14 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +31 -39
  22. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +6 -5
  23. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +84 -3
  24. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +52 -7
  25. package/node_modules/@tomflow/chatloop-context/package.json +2 -4
  26. package/node_modules/@tomflow/chatloop-extension/README.md +66 -0
  27. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +19 -4
  28. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +40 -1
  29. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -1
  30. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +54 -4
  31. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +9 -3
  33. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +9 -5
  34. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +53 -10
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +34 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +16 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +1 -1
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +7 -6
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +64 -7
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +235 -95
  43. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/session.html +1 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +3 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +73 -16
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +23 -6
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +237 -13
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  65. package/node_modules/@tomflow/chatloop-extension/index.mjs +7 -0
  66. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +94 -19
  67. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +3 -3
  68. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +9 -2
  69. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  74. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  75. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  76. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  77. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  78. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  79. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +50 -7
  80. package/node_modules/@tomflow/chatloop-extension/package.json +1 -3
  81. package/node_modules/@tomflow/chatloop-trace/package.json +1 -3
  82. package/package.json +9 -11
  83. package/providers/extension.mjs +59 -16
@@ -0,0 +1,361 @@
1
+ // Task-first Adopt Start. One MV3 Worker, one existing approved Chat, no sends.
2
+ // Loaded after bootstrap/admission; the Native Ledger and Context remain Owners.
3
+ const scopedStartFail=code=>Object.assign(Error(code),{code});
4
+ const scopedStartAssert=(ok,code)=>{if(!ok)throw scopedStartFail(code)};
5
+ // The private CLI request ID already carries 128 bits of CSPRNG entropy.
6
+ // Bind the initial Session deterministically to that *same* issued request:
7
+ // if Native STARTING commits but Worker storage fails, the same signed
8
+ // request can identify its pre-Permit reservation without inventing an Owner.
9
+ // Hash separation prevents deriving the private request ID from Session ID.
10
+ async function scopedStartUUID(requestId){
11
+ scopedStartAssert(/^[a-f0-9]{32}$/.test(requestId||''),
12
+ 'SCOPED_START_REQUEST_ID_INVALID');
13
+ const digest=await crypto.subtle.digest('SHA-256',
14
+ new TextEncoder().encode('chatloop-start-v2:'+requestId));
15
+ const bytes=new Uint8Array(digest).slice(0,16);
16
+ bytes[6]=(bytes[6]&0x0f)|0x50;
17
+ bytes[8]=(bytes[8]&0x3f)|0x80;
18
+ const hex=[...bytes].map(x=>x.toString(16).padStart(2,'0')).join('');
19
+ return [hex.slice(0,8),hex.slice(8,12),hex.slice(12,16),
20
+ hex.slice(16,20),hex.slice(20)].join('-');
21
+ }
22
+ const scopedStartNative=m=>chrome.runtime.sendNativeMessage(SESSION_HOST,m);
23
+ async function scopedStartIntent(message,sender){
24
+ scopedStartAssert(sender?.id===chrome.runtime.id&&sender.frameId===0
25
+ &&sessionPage(sender,'start',message?.requestId),
26
+ 'SCOPED_START_ACTION_SOURCE_INVALID');
27
+ const id=message.requestId;
28
+ const proof=await scopedStartNative({op:'acquire',id,action:'start'});
29
+ const intent=proof?.intent;
30
+ scopedStartAssert(proof?.status==='OK'&&proof.id===id
31
+ &&proof.action==='start'&&intent?.taskFirst===true
32
+ &&intent.mode==='adopt'&&intent.confirmed===true
33
+ &&typeof intent.projectId==='string'
34
+ &&typeof intent.taskId==='string'
35
+ &&typeof intent.contextLeaseRef==='string'
36
+ &&typeof intent.contextStoreEpoch==='string'
37
+ &&Number.isSafeInteger(intent.contextTaskRevision)
38
+ &&Number.isSafeInteger(intent.contextApprovalRevision)
39
+ &&typeof intent.chatUrl==='string'
40
+ &&intent.chatUrl==='https://chatgpt.com'+pathOf(intent.chatUrl),
41
+ 'SCOPED_START_INTENT_UNVERIFIED');
42
+ return {requestId:id,intent,actionTabId:sender.tab.id};
43
+ }
44
+ async function scopedStartEvidence(intent){
45
+ const page=pathOf(intent.chatUrl),chatId=chatIdOf(intent.chatUrl);
46
+ scopedStartAssert(page&&chatId,'SCOPED_ADOPTION_URL_INVALID');
47
+ // Never implicitly open/select the latest Chat, including across Projects.
48
+ const tabs=await chrome.tabs.query({url:'https://chatgpt.com/*'});
49
+ const matches=tabs.filter(t=>Number.isSafeInteger(t.id)
50
+ &&pathOf(t.url)===page);
51
+ scopedStartAssert(matches.length===1,'SCOPED_ADOPTION_CHAT_UNVERIFIED');
52
+ const tab=matches[0];
53
+ const observe=()=>chrome.tabs.sendMessage(tab.id,{
54
+ type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',explicitChatId:chatId
55
+ }).catch(()=>null);
56
+ const first=await observe();
57
+ const candidate=policy.normalizeAdoptionEvidence(first,{page});
58
+ scopedStartAssert(candidate,'SCOPED_ADOPTION_APPROVAL_UNVERIFIED');
59
+ const second=await observe();
60
+ scopedStartAssert(policy.sameAdoptionEvidence(candidate,
61
+ policy.normalizeAdoptionEvidence(second,{page})),
62
+ 'SCOPED_ADOPTION_APPROVAL_CHANGED');
63
+ const source=second?.approvalTurns;
64
+ scopedStartAssert(source&&typeof source==='object'
65
+ &&typeof source.rUserText==='string'&&source.rUserText.length>0
66
+ &&source.rUserText.length<=1000
67
+ &&typeof source.pUserText==='string'&&source.pUserText.length>0
68
+ &&source.pUserText.length<=1000
69
+ &&/^user:[^\s]{8,}$/.test(source.rUserKey||'')
70
+ &&source.rUserKey!==candidate.userKey,
71
+ 'SCOPED_ADOPTION_SOURCE_UNVERIFIED');
72
+ const fresh=await chrome.tabs.get(tab.id).catch(()=>null);
73
+ scopedStartAssert(fresh&&pathOf(fresh.url)===page,
74
+ 'SCOPED_ADOPTION_TAB_CHANGED');
75
+ return {tabId:tab.id,chatId,page,
76
+ evidence:candidate,approvalEvidence:{
77
+ rUserText:source.rUserText,rUserKey:source.rUserKey,
78
+ rVersion:candidate.rVersion,
79
+ pUserText:source.pUserText,pUserKey:candidate.userKey,
80
+ pVersion:candidate.pVersion}};
81
+ }
82
+ const scopedStartRecord=(scope,phase,chatId=null)=>({
83
+ projectId:scope.projectId,taskId:scope.taskId,sessionId:scope.sessionId,
84
+ generation:0,phase,activeChatId:chatId,
85
+ activeChatUrl:chatId?scope.chatUrl:null,updatedAt:Date.now()
86
+ });
87
+ const scopedStartWorkerRecord=(intent,requestId,actionTabId,
88
+ sessionId,approved,phase='STARTING',nativeOwnerRevision=0)=>({
89
+ projectId:intent.projectId,taskId:intent.taskId,sessionId,
90
+ generation:0,phase,ownerChatId:null,nativeOwnerRevision,
91
+ contextBindingRevision:0,tabId:null,page:'/',
92
+ startRequestId:requestId,actionTabId,adoptTabId:approved.tabId,
93
+ adoptPage:approved.page,adoptUserKey:approved.evidence.userKey,
94
+ adoptRVersion:approved.evidence.rVersion,
95
+ adoptPVersion:approved.evidence.pVersion
96
+ });
97
+ const scopedStartCheckReply=(result,scope,phase,priorRevision)=>{
98
+ scopedStartAssert(result?.status==='OK'
99
+ &&result.session?.projectId===scope.projectId
100
+ &&result.session.taskId===scope.taskId
101
+ &&result.session.sessionId===scope.sessionId
102
+ &&result.session.generation===0
103
+ &&result.session.phase===phase
104
+ &&result.session.revision===(priorRevision??0)+1,
105
+ 'SCOPED_START_NATIVE_COMMIT_UNVERIFIED');
106
+ return result;
107
+ };
108
+ async function scopedTaskStartPrepare(message,sender,source){
109
+ const {intent,requestId,actionTabId}=source;
110
+ const existing=await scopedTaskRuns.get(intent.projectId,intent.taskId);
111
+ const native=await scopedStartNative({
112
+ op:'session-read-v2',sourceRequestId:requestId});
113
+ if(existing.run){
114
+ // Only resume the SAME private Start request before any Permit is
115
+ // consumed. The original random Session is never replaced or guessed.
116
+ const prior=existing.run,s=native?.session;
117
+ scopedStartAssert(prior.startRequestId===requestId
118
+ &&prior.actionTabId===actionTabId
119
+ &&['STARTING','RESERVED'].includes(prior.phase),
120
+ 'SCOPED_START_PREPERMIT_RESUME_DENIED');
121
+ scopedStartAssert(s?.sessionId===prior.sessionId
122
+ &&s.projectId===intent.projectId&&s.taskId===intent.taskId
123
+ &&s.generation===0&&s.activeChatId===null
124
+ &&s.activeChatUrl===null
125
+ &&['STARTING','RESERVED'].includes(s.phase),
126
+ 'SCOPED_START_NATIVE_PREPERMIT_CHANGED');
127
+ const proof=await scopedStartEvidence(intent);
128
+ scopedStartAssert(prior.adoptTabId===proof.tabId
129
+ &&prior.adoptPage===proof.page
130
+ &&prior.adoptUserKey===proof.evidence.userKey
131
+ &&prior.adoptRVersion===proof.evidence.rVersion
132
+ &&prior.adoptPVersion===proof.evidence.pVersion,
133
+ 'SCOPED_START_PREPERMIT_APPROVAL_CHANGED');
134
+ if(prior.phase==='RESERVED'){
135
+ scopedStartAssert(s.phase==='RESERVED'
136
+ &&s.revision===prior.nativeOwnerRevision,
137
+ 'SCOPED_START_RESERVATION_DRIFT');
138
+ return {status:'PREPARED',scope:'TASK_SCOPED_ADOPT_NO_SEND',
139
+ sessionId:prior.sessionId,tabId:proof.tabId,
140
+ page:proof.page,userKey:proof.evidence.userKey};
141
+ }
142
+ scopedStartAssert(prior.phase==='STARTING'
143
+ &&['STARTING','RESERVED'].includes(s.phase),
144
+ 'SCOPED_START_PREPERMIT_DRIFT');
145
+ const reserved=s.phase==='RESERVED'?native
146
+ :scopedStartCheckReply(await scopedStartNative({
147
+ op:'session-sync-v2',sourceRequestId:requestId,
148
+ expectedLedgerRevision:native.ledgerRevision,
149
+ expectedSessionRevision:s.revision,
150
+ session:scopedStartRecord({
151
+ projectId:intent.projectId,taskId:intent.taskId,
152
+ sessionId:prior.sessionId,chatUrl:intent.chatUrl},'RESERVED')
153
+ }),prior,'RESERVED',s.revision);
154
+ const updated=await scopedTaskRuns.put({...prior,phase:'RESERVED',
155
+ nativeOwnerRevision:reserved.session.revision},{
156
+ expectedStoreRevision:existing.storeRevision,
157
+ expectedRunRevision:existing.runRevision});
158
+ scopedStartAssert(updated.runRevision>existing.runRevision,
159
+ 'SCOPED_START_PREPERMIT_ACK_UNKNOWN');
160
+ return {status:'PREPARED',scope:'TASK_SCOPED_ADOPT_NO_SEND',
161
+ sessionId:prior.sessionId,tabId:proof.tabId,
162
+ page:proof.page,userKey:proof.evidence.userKey};
163
+ }
164
+ if(!existing.run&&native?.session){
165
+ // A Native STARTING/RESERVED reservation may have committed before
166
+ // its Worker write/ACK. The exact SHA-256-derived Session binds that
167
+ // reservation to THIS authenticated original Start request. Recovery
168
+ // never consumes a Permit or creates a new Session or Chat.
169
+ const s=native.session;
170
+ const signedSession=await scopedStartUUID(requestId);
171
+ scopedStartAssert(native.status==='OK'
172
+ &&native.projectId===intent.projectId
173
+ &&native.taskId===intent.taskId
174
+ &&s.projectId===intent.projectId&&s.taskId===intent.taskId
175
+ &&s.sessionId===signedSession
176
+ &&s.generation===0&&s.activeChatId===null
177
+ &&s.activeChatUrl===null
178
+ &&['STARTING','RESERVED'].includes(s.phase)
179
+ &&Number.isSafeInteger(s.revision)&&s.revision>=1,
180
+ 'SCOPED_START_ORPHAN_SOURCE_UNVERIFIED');
181
+ const proof=await scopedStartEvidence(intent);
182
+ const restored=scopedStartWorkerRecord(intent,requestId,actionTabId,
183
+ signedSession,proof,s.phase,s.revision);
184
+ const inserted=await scopedTaskRuns.put(restored,{
185
+ expectedStoreRevision:existing.storeRevision,
186
+ expectedRunRevision:null});
187
+ if(s.phase==='RESERVED')return {
188
+ status:'PREPARED',scope:'TASK_SCOPED_ADOPT_NO_SEND',
189
+ sessionId:signedSession,tabId:proof.tabId,page:proof.page,
190
+ userKey:proof.evidence.userKey};
191
+ const common={projectId:intent.projectId,taskId:intent.taskId,
192
+ sessionId:signedSession,chatUrl:intent.chatUrl};
193
+ const reserved=scopedStartCheckReply(await scopedStartNative({
194
+ op:'session-sync-v2',sourceRequestId:requestId,
195
+ expectedLedgerRevision:native.ledgerRevision,
196
+ expectedSessionRevision:s.revision,
197
+ session:scopedStartRecord(common,'RESERVED')}),common,'RESERVED',s.revision);
198
+ await scopedTaskRuns.put({...restored,phase:'RESERVED',
199
+ nativeOwnerRevision:reserved.session.revision},{
200
+ expectedStoreRevision:inserted.storeRevision,
201
+ expectedRunRevision:inserted.runRevision});
202
+ return {status:'PREPARED',scope:'TASK_SCOPED_ADOPT_NO_SEND',
203
+ sessionId:signedSession,tabId:proof.tabId,page:proof.page,
204
+ userKey:proof.evidence.userKey};
205
+ }
206
+ scopedStartAssert(native?.status==='OK'
207
+ &&native.projectId===intent.projectId&&native.taskId===intent.taskId
208
+ &&native.session===null&&Number.isSafeInteger(native.ledgerRevision),
209
+ 'SCOPED_TASK_NATIVE_ALREADY_OWNED');
210
+ const approved=await scopedStartEvidence(intent);
211
+ const sessionId=await scopedStartUUID(requestId);
212
+ const common={projectId:intent.projectId,taskId:intent.taskId,sessionId,
213
+ chatUrl:intent.chatUrl};
214
+ const run=scopedStartWorkerRecord(intent,requestId,actionTabId,
215
+ sessionId,approved);
216
+ // Native checks the older V1 Session fence BEFORE any V2 Worker entry
217
+ // exists. A still-active V1 Owner cannot be blocked by a failed V2 probe.
218
+ const started=scopedStartCheckReply(await scopedStartNative({
219
+ op:'session-sync-v2',sourceRequestId:requestId,
220
+ expectedLedgerRevision:native.ledgerRevision,
221
+ expectedSessionRevision:null,
222
+ session:scopedStartRecord(common,'STARTING')}),common,'STARTING',null);
223
+ const inserted=await scopedTaskRuns.put(run,{
224
+ expectedStoreRevision:existing.storeRevision,expectedRunRevision:null});
225
+ const reserved=scopedStartCheckReply(await scopedStartNative({
226
+ op:'session-sync-v2',sourceRequestId:requestId,
227
+ expectedLedgerRevision:started.ledgerRevision,
228
+ expectedSessionRevision:started.session.revision,
229
+ session:scopedStartRecord(common,'RESERVED')}),common,'RESERVED',
230
+ started.session.revision);
231
+ await scopedTaskRuns.put({...run,phase:'RESERVED',
232
+ nativeOwnerRevision:reserved.session.revision},{
233
+ expectedStoreRevision:inserted.storeRevision,
234
+ expectedRunRevision:inserted.runRevision});
235
+ return {status:'PREPARED',scope:'TASK_SCOPED_ADOPT_NO_SEND',
236
+ sessionId,tabId:approved.tabId,page:approved.page,
237
+ userKey:approved.evidence.userKey};
238
+ }
239
+ async function scopedTaskStartCommit(message,sender,source){
240
+ const {intent,requestId,actionTabId}=source;
241
+ const snapshot=await scopedTaskRuns.get(intent.projectId,intent.taskId);
242
+ const run=snapshot.run;
243
+ scopedStartAssert(run&&run.phase==='RESERVED'
244
+ &&run.startRequestId===requestId&&run.actionTabId===actionTabId
245
+ &&run.generation===0&&run.ownerChatId===null,
246
+ 'SCOPED_START_RESERVATION_MISSING');
247
+ const approved=await scopedStartEvidence(intent);
248
+ scopedStartAssert(approved.tabId===run.adoptTabId
249
+ &&approved.page===run.adoptPage
250
+ &&approved.evidence.userKey===run.adoptUserKey
251
+ &&approved.evidence.rVersion===run.adoptRVersion
252
+ &&approved.evidence.pVersion===run.adoptPVersion,
253
+ 'SCOPED_START_APPROVAL_CHANGED');
254
+ const owner=await scopedStartNative({
255
+ op:'session-read-v2',sourceRequestId:requestId});
256
+ scopedStartAssert(owner?.status==='OK'
257
+ &&owner.session?.sessionId===run.sessionId
258
+ &&owner.session?.phase==='RESERVED'
259
+ &&owner.session.revision===run.nativeOwnerRevision,
260
+ 'SCOPED_START_NATIVE_RESERVATION_CHANGED');
261
+ // Context consumes the original approved R/P and exact Task lease ONCE.
262
+ // Lost ACK blocks; do not issue a second permit.consume request.
263
+ const permission=await scopedStartNative({
264
+ op:'context-control-v2',sourceRequestId:requestId,
265
+ command:'permit.consume',
266
+ expectedSessionRevision:owner.session.revision,
267
+ args:{kind:'START',adopt:true,leaseRef:intent.contextLeaseRef,
268
+ expectedStoreEpoch:intent.contextStoreEpoch,
269
+ expectedTaskRevision:intent.contextTaskRevision,
270
+ expectedApprovalRevision:intent.contextApprovalRevision,
271
+ actionToken:requestId,writeRequestId:requestId+':permit',
272
+ approvalEvidence:approved.approvalEvidence}});
273
+ scopedStartAssert(permission?.status==='OK'
274
+ &&permission.scope==='TASK_SCOPED_PERMIT'
275
+ &&permission.result?.status==='PERMITTED'
276
+ &&permission.sessionRevision===owner.session.revision+1,
277
+ 'SCOPED_START_PERMIT_UNKNOWN');
278
+ const pending=await scopedTaskRuns.put({...run,phase:'PENDING',
279
+ nativeOwnerRevision:permission.sessionRevision},{
280
+ expectedStoreRevision:snapshot.storeRevision,
281
+ expectedRunRevision:snapshot.runRevision});
282
+ // Register the already-open, approved Chat resource BEFORE promoting the
283
+ // Native Owner. An uncertain registration leaves this Task pre-send.
284
+ const admission=await resources.adoptChat({
285
+ id:approved.tabId,url:intent.chatUrl},{
286
+ ...run,phase:'PENDING',adoptTabId:approved.tabId});
287
+ scopedStartAssert(admission,'SCOPED_ADOPTION_RESOURCE_UNVERIFIED');
288
+ const latest=await chrome.tabs.get(approved.tabId).catch(()=>null);
289
+ scopedStartAssert(latest&&pathOf(latest.url)===approved.page,
290
+ 'SCOPED_START_CHAT_CHANGED');
291
+ const nativePending=await scopedStartNative({
292
+ op:'session-read-v2',sourceRequestId:requestId});
293
+ scopedStartAssert(nativePending?.session?.phase==='PENDING'
294
+ &&nativePending.session.sessionId===run.sessionId
295
+ &&nativePending.session.revision===permission.sessionRevision,
296
+ 'SCOPED_START_PENDING_OWNER_CHANGED');
297
+ const common={projectId:run.projectId,taskId:run.taskId,
298
+ sessionId:run.sessionId,chatUrl:intent.chatUrl};
299
+ const committed=scopedStartCheckReply(await scopedStartNative({
300
+ op:'session-sync-v2',sourceRequestId:requestId,
301
+ expectedLedgerRevision:nativePending.ledgerRevision,
302
+ expectedSessionRevision:permission.sessionRevision,
303
+ session:scopedStartRecord(common,'WAITING_REPLY',approved.chatId),
304
+ ownerEvidence:{tabId:approved.tabId,page:approved.page,
305
+ userKey:approved.evidence.userKey}}),common,'WAITING_REPLY',
306
+ permission.sessionRevision);
307
+ // Once a Native claim exists, bind its one-use Context permit. No send
308
+ // occurs here. A failed bind leaves a fenced, unresolved Start.
309
+ const credential=Array.from(crypto.getRandomValues(new Uint8Array(32)),
310
+ x=>x.toString(16).padStart(2,'0')).join('');
311
+ const bound=await scopedStartNative({
312
+ op:'context-control-v2',sourceRequestId:requestId,
313
+ command:'run.bind.initial',
314
+ expectedSessionRevision:committed.session.revision,
315
+ args:{expectedStoreEpoch:intent.contextStoreEpoch,
316
+ writeRequestId:requestId+':bind',
317
+ expectedTaskRevision:intent.contextTaskRevision,
318
+ expectedBindingRevision:0,actionToken:requestId,
319
+ leaseRef:intent.contextLeaseRef,runCredential:credential}});
320
+ scopedStartAssert(bound?.status==='OK'
321
+ &&bound.scope==='TASK_SCOPED_BOUND'
322
+ &&bound.result?.status==='BOUND'
323
+ &&bound.result.runRef===run.sessionId+':'+run.taskId+':0'
324
+ &&bound.result.bindingRevision===1,
325
+ 'SCOPED_INITIAL_BIND_UNKNOWN');
326
+ const writer=await scopedStartNative({
327
+ op:'context-writer-check-v2',projectId:run.projectId,
328
+ taskId:run.taskId,sessionId:run.sessionId,generation:0,
329
+ expectedSessionRevision:committed.session.revision});
330
+ scopedStartAssert(writer?.status==='OK'
331
+ &&writer.scope==='TASK_SCOPED_WRITER_VERIFIED'
332
+ &&writer.nativeOwnerRevision===committed.session.revision
333
+ &&writer.contextBindingRevision===bound.result.bindingRevision,
334
+ 'SCOPED_WRITER_NOT_READY');
335
+ const turnToken=crypto.randomUUID(),startedAt=Date.now();
336
+ const final=await scopedTaskRuns.put({
337
+ projectId:run.projectId,taskId:run.taskId,sessionId:run.sessionId,
338
+ generation:0,phase:'WAITING_REPLY',ownerChatId:approved.chatId,
339
+ nativeOwnerRevision:committed.session.revision,
340
+ contextBindingRevision:bound.result.bindingRevision,
341
+ contextStoreEpoch:intent.contextStoreEpoch,
342
+ turnToken,tabId:approved.tabId,page:approved.page,
343
+ startRequestId:requestId,reason:'ADOPTED_IDLE_BASELINE',
344
+ startedAt,nextPollAt:startedAt+60000,
345
+ deadlineAt:startedAt+policy.windowMsOf(run)
346
+ },{expectedStoreRevision:pending.storeRevision,
347
+ expectedRunRevision:pending.runRevision});
348
+ scopedStartAssert(final.runRevision>pending.runRevision,
349
+ 'SCOPED_WORKER_BIND_UNVERIFIED');
350
+ return {status:'OK',scope:'TASK_SCOPED_ADOPTED_NO_SEND',
351
+ sessionId:run.sessionId,tabId:approved.tabId,page:approved.page,
352
+ // Official Tools/CLI start receipt must name the committed Chat Owner.
353
+ activeChatId:approved.chatId,
354
+ activeChatUrl:'https://chatgpt.com'+approved.page,
355
+ turnToken,userKey:approved.evidence.userKey,
356
+ assistantKey:approved.evidence.postApprovalAssistantKey||null,
357
+ context:{runRef:bound.result.runRef,runCredential:credential,
358
+ storeEpoch:intent.contextStoreEpoch,
359
+ bindingRevision:bound.result.bindingRevision,
360
+ taskRevision:intent.contextTaskRevision}};
361
+ }
@@ -0,0 +1,235 @@
1
+ // Terminal status belongs to Context; the Observer supplies only a stable
2
+ // final DOM identity. Native independently fences the exact Task before the
3
+ // Worker can mark DONE/BLOCKED. No Action or send is created here.
4
+ // A page fault is NOT a machine BLOCKED/DONE assistant reply. The
5
+ // original Context Writer remains untouched until Stage 06 proves a safe
6
+ // fence/recovery. Only record a bounded, Task-addressed diagnostic.
7
+ async function scopedTaskFaultObserved(message,sender){
8
+ const reasons=['PAGE_ERROR','CONTEXT_LIMIT','SECURITY_CHALLENGE'];
9
+ if(!message||Object.keys(message).length!==5
10
+ ||!['type','page','userKey','reason','retryAvailable']
11
+ .every(k=>Object.hasOwn(message,k))
12
+ ||!reasons.includes(message.reason)
13
+ ||sender?.id!==chrome.runtime.id||sender.frameId!==0
14
+ ||!Number.isSafeInteger(sender.tab?.id)||sender.tab.id<=0
15
+ ||typeof message.page!=='string'||message.page!==pathOf(sender.url)
16
+ ||typeof message.userKey!=='string'||message.userKey.length>1024
17
+ ||!/^user:[^\s]{8,}$/.test(message.userKey)
18
+ ||typeof message.retryAvailable!=='boolean')
19
+ return {status:'DENIED',code:'SCOPED_FAULT_SOURCE_INVALID'};
20
+ if(!await hasActiveScopedTask())return {
21
+ status:'UNSCOPED',code:'SCOPED_OBSERVER_TASK_NOT_FOUND'};
22
+ let initial;
23
+ try{initial=await scopedTaskOwnerResolver.resolve(sender);}
24
+ catch(error){
25
+ const code=safeWorkerErrorCode(error,'SCOPED_FAULT_OWNER_UNVERIFIED');
26
+ return code==='SCOPED_OBSERVER_TASK_NOT_FOUND'
27
+ ?{status:'UNSCOPED',code}:{status:'BLOCKED',code};
28
+ }
29
+ return scopedTaskScheduler.perTask(initial.projectId,initial.taskId,
30
+ async()=>{
31
+ const route=await scopedTaskOwnerResolver.resolve(sender);
32
+ const snapshot=await scopedTaskRuns.get(route.projectId,route.taskId);
33
+ const run=snapshot.run;
34
+ if(route.projectId!==initial.projectId
35
+ ||route.taskId!==initial.taskId
36
+ ||route.sessionId!==initial.sessionId
37
+ ||route.generation!==initial.generation
38
+ ||route.nativeOwnerRevision!==initial.nativeOwnerRevision
39
+ ||route.runRevision!==initial.runRevision
40
+ ||route.page!==message.page
41
+ ||route.runRevision!==snapshot.runRevision
42
+ ||run?.phase!=='WAITING_REPLY'
43
+ ||run.tabId!==sender.tab.id
44
+ ||run.awaitingUserKey&&run.awaitingUserKey!==message.userKey)
45
+ return {status:'BLOCKED',code:'SCOPED_FAULT_OWNER_CHANGED'};
46
+ const sample=()=>chrome.tabs.sendMessage(run.tabId,{
47
+ type:'CHAT_LOOP_TURN_OBSERVE_V1',poll:true}).catch(()=>null);
48
+ const a=await sample();
49
+ await new Promise(resolve=>setTimeout(resolve,350));
50
+ const b=await sample();
51
+ if(![a,b].every(p=>p?.contract==='chat-loop.turn-observer.v1'
52
+ &&p.status==='BLOCKED'&&p.page===message.page
53
+ &&p.userKey===message.userKey&&p.reason===message.reason
54
+ &&p.retryAvailable===message.retryAvailable))
55
+ return {status:'BLOCKED',code:'SCOPED_FAULT_DOM_UNVERIFIED'};
56
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
57
+ const latest=await scopedTaskRuns.get(run.projectId,run.taskId);
58
+ if(tab?.url!==sender.url||latest.runRevision!==snapshot.runRevision)
59
+ return {status:'BLOCKED',code:'SCOPED_FAULT_RUN_CHANGED'};
60
+ const old=run.lastFault;
61
+ if(old?.userKey===message.userKey&&old.reason===message.reason
62
+ &&old.retryAvailable===message.retryAvailable)
63
+ return {status:'RECORDED',scope:'TASK_SCOPED_FAULT_READ_ONLY'};
64
+ await scopedTaskRuns.put({...run,lastFault:{
65
+ userKey:message.userKey,reason:message.reason,
66
+ retryAvailable:message.retryAvailable,at:Date.now()
67
+ }},{expectedStoreRevision:latest.storeRevision,
68
+ expectedRunRevision:latest.runRevision});
69
+ return {status:'RECORDED',scope:'TASK_SCOPED_FAULT_READ_ONLY'};
70
+ });
71
+ }
72
+ // The sole Worker Alarm can lose the Observer's original fault message while
73
+ // its content-script dedupe flag survives MV3 suspension. Reuse the existing
74
+ // Task-scoped verifier; never schedule a nested perTask wait or a new sender.
75
+ function scopedReconcileObservedFault(run,tab,route,sample){
76
+ if(sample?.status!=='BLOCKED'
77
+ ||!['PAGE_ERROR','CONTEXT_LIMIT','SECURITY_CHALLENGE']
78
+ .includes(sample.reason)
79
+ ||typeof sample.userKey!=='string'
80
+ ||(run.awaitingUserKey&&run.awaitingUserKey!==sample.userKey))
81
+ return false;
82
+ if(run.lastFault?.userKey===sample.userKey
83
+ &&run.lastFault.reason===sample.reason
84
+ &&run.lastFault.retryAvailable===(sample.retryAvailable===true))
85
+ return true;
86
+ void scopedTaskFaultObserved({
87
+ type:'CHAT_LOOP_TASK_TURN_BLOCKED_V2',page:route.page,
88
+ userKey:sample.userKey,reason:sample.reason,
89
+ retryAvailable:sample.retryAvailable===true
90
+ },{id:chrome.runtime.id,frameId:0,
91
+ tab:{id:tab.id},url:tab.url}).catch(error=>
92
+ console.warn('TASK_SCOPED_FAULT_RECONCILE_UNVERIFIED',
93
+ safeWorkerErrorCode(error,'SCOPED_FAULT_UNVERIFIED')));
94
+ return true;
95
+ }
96
+ async function scopedTaskQueueTerminalObserver(message,sender){
97
+ // Actual terminal observation and any pre-Action intent cancellation
98
+ // belong inside the SAME Task queue, after final double DOM proof.
99
+ return scopedTaskTerminalObserved(message,sender);
100
+ }
101
+ async function scopedTaskTerminalObserved(message,sender){
102
+ const tabId=sender?.tab?.id,chatId=chatIdOf(sender?.url);
103
+ const binding=await scopedTaskRuns.resolveTab(tabId,chatId);
104
+ if(!binding)throw Object.assign(Error('Unknown Task Tab'),
105
+ {code:'SCOPED_TERMINAL_OWNER_NOT_FOUND'});
106
+ return scopedTaskScheduler.perTask(binding.projectId,binding.taskId,
107
+ async()=>{
108
+ const state=await scopedTaskRuns.get(binding.projectId,binding.taskId);
109
+ const run=state.run;
110
+ // Pre-final model proposals can be safely superseded by a proven
111
+ // DONE/BLOCKED response ONLY if no Action was ever launched. LAUNCHING
112
+ // is already an UNKNOWN browser-side-effect fence.
113
+ const unlaunched=run?.modelIntent
114
+ &&['QUEUED','CAPACITY_BLOCKED'].includes(run.modelIntent.state)
115
+ &&run.modelIntent.actionTabId===null
116
+ &&run.modelIntent.targetUserKey===message.userKey
117
+ &&!run.nextAttempt&&!run.handoffFence;
118
+ if(!run||run.phase!=='WAITING_REPLY'||run.nextAttempt
119
+ ||run.modelIntent&&!unlaunched
120
+ ||run.page!==message.page
121
+ ||run.awaitingUserKey&&run.awaitingUserKey!==message.userKey
122
+ ||run.tabId!==tabId||run.ownerChatId!==chatId
123
+ ||run.sessionId!==binding.sessionId
124
+ ||run.generation!==binding.generation)
125
+ throw Object.assign(Error('Terminal Owner not ready'),
126
+ {code:'SCOPED_TERMINAL_TASK_NOT_READY'});
127
+ const tab=await chrome.tabs.get(tabId).catch(()=>null);
128
+ if(!tab||tab.url!==sender.url)
129
+ throw Object.assign(Error('Terminal Tab drift'),
130
+ {code:'SCOPED_TERMINAL_TAB_CHANGED'});
131
+ const native=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
132
+ op:'session-snapshot-v2',projectId:run.projectId,
133
+ taskId:run.taskId,sessionId:run.sessionId,
134
+ generation:run.generation}).catch(()=>null);
135
+ const owner=native?.session;
136
+ const alreadyTerminal=owner?.phase===message.outcome
137
+ &&owner.revision===run.nativeOwnerRevision+1;
138
+ if(native?.status!=='OK'
139
+ ||!(owner?.phase==='WAITING_REPLY'
140
+ &&owner.revision===run.nativeOwnerRevision
141
+ ||alreadyTerminal)
142
+ ||owner.activeChatId!==chatId
143
+ ||owner.activeChatUrl!=='https://chatgpt.com'+message.page)
144
+ throw Object.assign(Error('Terminal Native drift'),
145
+ {code:'SCOPED_TERMINAL_NATIVE_UNVERIFIED'});
146
+ const read=()=>chrome.tabs.sendMessage(tabId,{
147
+ type:'CHAT_LOOP_TURN_VERIFY_V1'}).catch(()=>null);
148
+ const one=await read();
149
+ await new Promise(resolve=>setTimeout(resolve,350));
150
+ const two=await read();
151
+ if(one?.status!=='READY'||two?.status!=='READY'
152
+ ||one.page!==message.page||two.page!==message.page
153
+ ||one.userKey!==message.userKey
154
+ ||one.assistantKey!==message.assistantKey
155
+ ||two.userKey!==one.userKey
156
+ ||two.assistantKey!==one.assistantKey
157
+ ||one.replyText!==two.replyText
158
+ ||one.pendingConfirmation!==false
159
+ ||two.pendingConfirmation!==false
160
+ ||workerApi.parseStatus(one.replyText)!==message.outcome)
161
+ throw Object.assign(Error('Terminal DOM drift'),
162
+ {code:'SCOPED_TERMINAL_TURN_UNVERIFIED'});
163
+ let fresh=await scopedTaskRuns.get(run.projectId,run.taskId);
164
+ if(fresh.runRevision!==state.runRevision)
165
+ throw Object.assign(Error('Terminal Task drift'),
166
+ {code:'SCOPED_TERMINAL_RUN_STALE'});
167
+ // Persist the exact proven terminal Turn while this Task's queue is
168
+ // held. A later Context delivery may require read-only Alarm retry.
169
+ // A queued-but-never-launched model proposal is a NOT_SENT receipt,
170
+ // not a successful Continue or a consumable Permit.
171
+ const updated={...run,lastObservedTurn:{
172
+ page:message.page,userKey:message.userKey,
173
+ assistantKey:message.assistantKey,outcome:message.outcome,
174
+ pendingConfirmation:false,observedAt:Date.now()}};
175
+ delete updated.lastFault;
176
+ if(unlaunched){
177
+ updated.lastIntentReceipt={
178
+ turnToken:run.turnToken,id:run.modelIntent.id,
179
+ action:run.modelIntent.action,
180
+ status:'NOT_SENT',updatedAt:Date.now()};
181
+ delete updated.modelIntent;
182
+ }
183
+ const stored=await scopedTaskRuns.put(updated,{
184
+ expectedStoreRevision:fresh.storeRevision,
185
+ expectedRunRevision:fresh.runRevision});
186
+ fresh=await scopedTaskRuns.get(run.projectId,run.taskId);
187
+ if(fresh.runRevision!==stored.runRevision)
188
+ throw Object.assign(Error('Terminal store changed'),
189
+ {code:'SCOPED_TERMINAL_STORE_STALE'});
190
+ // The original Native terminal may have committed before the Worker
191
+ // received its one-shot ACK. Query its authoritative result, never
192
+ // rerun the Context/Native fence or create a replacement Turn.
193
+ const committed=await chrome.runtime.sendNativeMessage(SESSION_HOST,
194
+ alreadyTerminal?{
195
+ op:'task-terminal-read-v2',
196
+ projectId:run.projectId,taskId:run.taskId,
197
+ sessionId:run.sessionId,generation:run.generation,
198
+ expectedPriorSessionRevision:run.nativeOwnerRevision,
199
+ terminal:message.outcome,
200
+ activeChatUrl:'https://chatgpt.com'+message.page
201
+ }:{
202
+ op:'task-terminal-v2',projectId:run.projectId,
203
+ taskId:run.taskId,sessionId:run.sessionId,
204
+ generation:run.generation,
205
+ expectedSessionRevision:run.nativeOwnerRevision,
206
+ terminal:message.outcome,turnToken:run.turnToken,
207
+ sourceUserKey:message.userKey,
208
+ sourceAssistantKey:message.assistantKey,page:message.page
209
+ }).catch(()=>null);
210
+ if(committed?.status!=='CONFIRMED'
211
+ ||committed.scope!=='TASK_SCOPED_TERMINAL'
212
+ ||committed.terminal!==message.outcome
213
+ ||committed.nativeOwnerRevision!==run.nativeOwnerRevision+1)
214
+ throw Object.assign(Error('Terminal Native/Context UNKNOWN'),
215
+ {code:'SCOPED_TERMINAL_COMMIT_UNKNOWN'});
216
+ const next={...updated,phase:message.outcome,
217
+ // BLOCKED is an unresolved fence, never a recyclable terminal
218
+ // record; only Context-proven DONE receives a retention timestamp.
219
+ ...(message.outcome==='DONE'?{terminalAt:Date.now()}:{}),
220
+ nativeOwnerRevision:committed.nativeOwnerRevision,
221
+ lastObservedTurn:{page:message.page,userKey:message.userKey,
222
+ assistantKey:message.assistantKey,outcome:message.outcome,
223
+ pendingConfirmation:false,observedAt:Date.now()}};
224
+ delete next.awaitingUserKey;
225
+ await scopedTaskRuns.put(next,{
226
+ expectedStoreRevision:fresh.storeRevision,
227
+ expectedRunRevision:fresh.runRevision});
228
+ // Browser quota is a consequence of a proven terminal Task, never its
229
+ // authority. Lost inventory write cannot cause a second DOM send.
230
+ await resources.terminal(next).catch(()=>{});
231
+ return {status:'OBSERVED',code:'TASK_SCOPED_TERMINAL_CONFIRMED',
232
+ scope:'TASK_SCOPED_TERMINAL_OBSERVATION',
233
+ terminal:message.outcome};
234
+ });
235
+ }
@@ -27,6 +27,8 @@ const apiAspect=createApiAspect('@tomflow/chatloop-extension',{
27
27
  const drainTelemetry=createObservationDrain(apiAspect,observationSender);
28
28
  import * as bridge from './lib/bridge.mjs';
29
29
  import * as session from './lib/session-file.mjs';
30
+ import * as ownerLedger from './lib/owner-ledger.mjs';
31
+ import {createScopedNativeControl} from './lib/scoped-native-control.mjs';
30
32
  import * as binding from './lib/context-binding.mjs';
31
33
  import * as ipc from './lib/context-ipc.mjs';
32
34
  import * as evidence from './lib/owner-evidence.mjs';
@@ -57,6 +59,11 @@ export const nativeHostApi=apiAspect.observe('nativeHostApi',
57
59
  [INTERNAL_DRAIN]:drainTelemetry,
58
60
  readRequest:bridge.readRequest,finish:bridge.finish,
59
61
  readSession:session.readSession,writeSession:session.writeSession,
62
+ handleScopedNativeMessage:createScopedNativeControl({
63
+ readRequest:bridge.readRequest,readScopedOwner:ownerLedger.readOwnerLedgerTask,
64
+ writeScopedOwner:ownerLedger.writeOwnerLedgerSession,
65
+ retireScopedOwner:ownerLedger.retireOwnerLedgerTerminal,
66
+ nativeContextControl:ipc.nativeContextControl}),
60
67
  registeredContext:binding.registeredContext,
61
68
  nativeContextControl:ipc.nativeContextControl,
62
69
  // One named, non-authoritative span for each Native messaging operation.