@tomflow/chatloop-extension 0.3.59 → 0.3.63

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.
@@ -53,6 +53,8 @@ const windowMsOf = run => Number.isSafeInteger(run?.windowMs) && run.windowMs >
53
53
  const deadlineOf = run => Number.isSafeInteger(run?.startedAt) && run.startedAt > 0
54
54
  ? run.startedAt + windowMsOf(run) : null;
55
55
  const clockActive = run => run && ["RESERVED", "PENDING", "WAITING_REPLY"].includes(run.phase);
56
+ const terminalFenceVerified = run => !run?.contextManaged || !run?.taskId
57
+ || run.contextTerminalFence === "CONFIRMED";
56
58
  // Durable, bounded metadata for model intent receipts. The prompt text remains only
57
59
  // in the active run while its Action is pending; history never stores the prompt.
58
60
  const MODEL_RECEIPT_TTL_MS = 24 * 60 * 60 * 1000;
@@ -100,7 +102,7 @@ async function saveRun(run) {
100
102
  }
101
103
  const stored=await readRun();
102
104
  const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
103
- &&next.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
105
+ &&["TOOL_PREFLIGHT_REPAIRED","HANDOFF_NOT_SENT"].includes(next.recoveryMode)
104
106
  &&next.recoveryAttempts>=1&&stored?.phase==="BLOCKED";
105
107
  const syncNative=async()=>{
106
108
  if(!next.sessionId)return;
@@ -122,7 +124,9 @@ async function saveRun(run) {
122
124
  await chrome.storage.local.set({[RUN_KEY]:next});
123
125
  if(!recoveryCommit)await syncNative();
124
126
  // The resource inventory is derived evidence; it never grants browser Owner.
125
- if (["DONE","BLOCKED"].includes(next.phase))
127
+ if (["DONE","BLOCKED"].includes(next.phase)
128
+ && next.contextTerminalFence !== "PENDING"
129
+ && next.contextTerminalFence !== "UNVERIFIED")
126
130
  await resources.terminal(next).catch(()=>{});
127
131
 
128
132
  try {
@@ -140,11 +144,11 @@ function sessionProjection(run) {
140
144
  const match=page.match(/\/c\/([0-9a-f-]{12,})$/i);
141
145
  const activeChatId=match?.[1]||null;
142
146
  return {sessionId:run.sessionId,projectId:run.projectId,
143
- phase:run.phase,generation:run.generation||0,activeChatId,
147
+ ...(run.taskId?{taskId:run.taskId}:{}),phase:run.phase,generation:run.generation||0,activeChatId,
144
148
  activeChatUrl:activeChatId?"https://chatgpt.com"+page:null,
145
149
  updatedAt:Date.now()};
146
150
  }
147
- const SESSION_POINTER_KEYS=Object.freeze(['sessionId','projectId','phase',
151
+ const SESSION_POINTER_KEYS=Object.freeze(['sessionId','projectId','taskId','phase',
148
152
  'generation','activeChatId','activeChatUrl']);
149
153
  const matchesNativeProjection=(projected,native)=>Boolean(native
150
154
  &&SESSION_POINTER_KEYS.every(key=>projected[key]===native[key]));
@@ -235,7 +239,9 @@ async function approvedAdoptionTarget(chatUrl=null){
235
239
  ...(requestedId?{explicitChatId:requestedId}:{})}).catch(()=>null);
236
240
  if(proof?.contract!=="chat-loop.turn-observer.v1"
237
241
  ||proof.status!=="VERIFIED"||proof.page!==page
238
- ||typeof proof.userKey!=="string"||!/^user:[^\s]{8,}$/.test(proof.userKey))
242
+ ||typeof proof.userKey!=="string"||!/^user:[^\s]{8,}$/.test(proof.userKey)
243
+ ||!/^R[1-9][0-9]*$/.test(proof.rVersion||"")
244
+ ||!/^P[1-9][0-9]*$/.test(proof.pVersion||""))
239
245
  continue;
240
246
  matched.push({tabId:tab.id,page,userKey:proof.userKey,
241
247
  priorAssistantKey:proof.priorAssistantKey||null,
@@ -250,10 +256,60 @@ async function approvedAdoptionTarget(chatUrl=null){
250
256
  ...(requestedId?{explicitChatId:requestedId}:{})}).catch(()=>null);
251
257
  if(second?.status!=="VERIFIED"
252
258
  ||second.page!==target.page||second.userKey!==target.userKey
253
- ||second.rVersion!==target.rVersion||second.pVersion!==target.pVersion)
259
+ ||second.rVersion!==target.rVersion||second.pVersion!==target.pVersion
260
+ ||(second.priorAssistantKey||null)!==(target.priorAssistantKey||null))
254
261
  return {error:"ADOPTION_APPROVAL_CHANGED"};
255
262
  return {target};
256
263
  }
264
+ async function approvedRepairTarget(prior,intent){
265
+ // Repair is a new explicit USER request in the SAME exact Chat after the
266
+ // original Task's machine DONE, never a synthetic P approval or replacement.
267
+ if(!prior||prior.phase!=='DONE'||prior.projectId!==intent.projectId
268
+ ||prior.taskId!==intent.taskId||!prior.sessionId
269
+ ||!Number.isSafeInteger(prior.tabId)||!prior.page)
270
+ return {error:'REPAIR_PREVIOUS_DONE_MISSING'};
271
+ const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
272
+ if(!tab||pathOf(tab.url)!==prior.page
273
+ ||intent.chatUrl&&intent.chatUrl!=='https://chatgpt.com'+prior.page)
274
+ return {error:'REPAIR_OLD_CHAT_CHANGED'};
275
+ const durable=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
276
+ op:'session-read'}).catch(()=>null);
277
+ if(durable?.status!=='OK'||!durable.session
278
+ ||durable.session.phase!=='DONE'
279
+ ||durable.session.sessionId!==prior.sessionId
280
+ ||durable.session.projectId!==intent.projectId
281
+ ||durable.session.taskId!==intent.taskId
282
+ ||durable.session.activeChatId!==chatIdOf(tab.url)
283
+ ||durable.session.generation!==(prior.generation||0))
284
+ return {error:'REPAIR_DONE_OWNER_UNVERIFIED'};
285
+ const context=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
286
+ op:'context-control',command:'run.reopenStatus',args:{}}).catch(()=>null);
287
+ const reopen=context?.result;
288
+ if(context?.status!=='OK'||reopen?.stage!=='REOPENED'
289
+ ||reopen.taskRevision!==intent.contextTaskRevision
290
+ ||reopen.approvalRevision!==intent.contextApprovalRevision
291
+ ||typeof reopen.reopenUserTurn!=='string')
292
+ return {error:'REPAIR_CONTEXT_UNVERIFIED'};
293
+ const explicitChatId=chatIdOf(tab.url);
294
+ const observe=()=>chrome.tabs.sendMessage(prior.tabId,{
295
+ type:'CHAT_LOOP_REPAIR_EVIDENCE_V1',explicitChatId}).catch(()=>null);
296
+ const first=await observe();
297
+ await new Promise(resolve=>setTimeout(resolve,400));
298
+ const second=await observe();
299
+ const matching=proof=>proof?.contract==='chat-loop.turn-observer.v1'
300
+ &&proof.status==='VERIFIED'&&proof.page===prior.page
301
+ &&proof.priorDoneAssistantKey===prior.assistantKey
302
+ &&typeof proof.userKey==='string'
303
+ &&(reopen.reopenUserTurn===proof.userKey
304
+ ||reopen.reopenUserTurn===proof.userText);
305
+ if(!matching(first)||!matching(second)
306
+ ||first.userKey!==second.userKey
307
+ ||first.userText!==second.userText)
308
+ return {error:'REPAIR_USER_INTENT_UNVERIFIED'};
309
+ return {target:{tabId:prior.tabId,page:prior.page,
310
+ userKey:first.userKey,priorAssistantKey:prior.assistantKey,
311
+ repairUserText:first.userText,repairDoneAssistantKey:prior.assistantKey}};
312
+ }
257
313
  async function sessionStartPrepare(message,sender){
258
314
  if(!sessionPage(sender,'start',message.requestId))
259
315
  return {status:'DENIED',code:'INVALID_START_SOURCE'};
@@ -267,6 +323,18 @@ async function sessionStartPrepare(message,sender){
267
323
  if(proof?.status!=='OK'||intent?.confirmed!==true
268
324
  ||typeof intent.projectId!=='string'
269
325
  ||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.projectId)
326
+ ||(intent.taskId!==undefined
327
+ && !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.taskId))
328
+ ||(intent.purpose!==undefined
329
+ &&(intent.purpose!=='REPAIR_SAME_SCOPE'||intent.mode!=='adopt'
330
+ ||!intent.taskId||!intent.contextLeaseRef))
331
+ ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
332
+ .some(k=>Object.hasOwn(intent,k))
333
+ &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
334
+ ||intent.contextLeaseRef.length<8||typeof intent.contextStoreEpoch!=='string'
335
+ ||intent.contextStoreEpoch.length<10
336
+ ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
337
+ ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
270
338
  ||(intent.chatUrl!==undefined
271
339
  && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'
272
340
  ||!pathOf(intent.chatUrl)
@@ -277,6 +345,12 @@ async function sessionStartPrepare(message,sender){
277
345
  ||(intent.replaceBlockedSessionId!==undefined
278
346
  && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId)))
279
347
  return {status:'DENIED',code:'START_INTENT_UNVERIFIED'};
348
+ // Native DONE is required before the private terminal fence IPC, but
349
+ // DONE without CONFIRMED fencing must never release Start admission.
350
+ if(prior?.contextManaged && prior.taskId
351
+ && (prior.contextTerminalFence==='UNVERIFIED'
352
+ || prior.phase==='DONE'&&!terminalFenceVerified(prior)))
353
+ return {status:'DENIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
280
354
  const replace=intent.replaceBlockedSessionId||null;
281
355
  const matchingBlocked=prior?.phase==='BLOCKED' && prior.sessionId===replace
282
356
  && prior.projectId!==intent.projectId;
@@ -293,11 +367,29 @@ async function sessionStartPrepare(message,sender){
293
367
  const capacity=await resources.admit(prior,{kind:intent.mode==='adopt'?'action':'chat'});
294
368
  if(!capacity.ok)return {status:'DENIED',code:capacity.code};
295
369
  const adoption=intent.mode==='adopt'
296
- ?await approvedAdoptionTarget(intent.chatUrl||null):null;
370
+ ?intent.purpose==='REPAIR_SAME_SCOPE'
371
+ ?await approvedRepairTarget(prior,intent)
372
+ :await approvedAdoptionTarget(intent.chatUrl||null):null;
297
373
  if(adoption?.error)return {status:'DENIED',code:adoption.error};
374
+ // A Project-scoped Chat cannot safely hand off to the ordinary home route:
375
+ // reject BEFORE claiming Owner instead of failing after four hours.
376
+ // Explicit /g/ intent remains Project-scoped even if Chrome aliases the
377
+ // same conversation under /c/<id>.
378
+ if(intent.mode==='adopt'&&(
379
+ pathOf(intent.chatUrl||'').startsWith('/g/')
380
+ ||adoption?.target?.page?.startsWith('/g/')))
381
+ return {status:'DENIED',code:'AUTO_HANDOFF_ROUTE_UNSUPPORTED'};
298
382
  // The same blocked task may never be replayed implicitly: a replacement
299
383
  // requires a new project ID and leaves the old Chat intact for audit.
300
384
  const next={sessionId:crypto.randomUUID(),projectId:intent.projectId,
385
+ ...(intent.taskId?{taskId:intent.taskId}:{}),
386
+ ...(intent.purpose?{purpose:intent.purpose}:{}),
387
+ ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
388
+ contextStoreEpoch:intent.contextStoreEpoch,
389
+ contextTaskRevision:intent.contextTaskRevision,
390
+ contextApprovalRevision:intent.contextApprovalRevision,
391
+ contextInitialCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
392
+ x=>x.toString(16).padStart(2,'0')).join('')}:{}),
301
393
  generation:0,phase:'STARTING',action:'START',token:crypto.randomUUID(),
302
394
  page:'/',tabId:null,startedAt:Date.now(),
303
395
  machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
@@ -305,10 +397,17 @@ async function sessionStartPrepare(message,sender){
305
397
  ...(adoption?{mode:'adopt',adoptTabId:adoption.target.tabId,
306
398
  adoptPage:adoption.target.page,adoptUserKey:adoption.target.userKey,
307
399
  ...(intent.chatUrl?{adoptExplicitChatId:chatIdOf(intent.chatUrl)}:{}),
308
- adoptPriorAssistantKey:adoption.target.priorAssistantKey}
400
+ adoptPriorAssistantKey:adoption.target.priorAssistantKey,
401
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'?{}:{
402
+ adoptRVersion:adoption.target.rVersion,
403
+ adoptPVersion:adoption.target.pVersion}),
404
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'
405
+ ?{repairUserText:adoption.target.repairUserText,
406
+ repairDoneAssistantKey:adoption.target.repairDoneAssistantKey}:{})}
309
407
  :{startPrompt:intent.prompt})};
310
408
  await saveRun(next); // Reserve BEFORE any new Chrome tab or send.
311
- return {status:'PREPARED',token:next.token,sessionId:next.sessionId};
409
+ return {status:'PREPARED',token:next.token,sessionId:next.sessionId,
410
+ ...(next.taskId?{taskId:next.taskId}:{})};
312
411
  }
313
412
  async function sessionStartTake(message,sender){
314
413
  const run=await readRun();
@@ -316,11 +415,31 @@ async function sessionStartTake(message,sender){
316
415
  ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
317
416
  ||run.phase!=='STARTING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
318
417
  await saveRun({...run,phase:'PENDING'});
418
+ // Native validates current durable Session and signs the narrow Context IPC.
419
+ // No Context adapter? Legacy Start behavior remains unchanged.
420
+ if(run.contextLeaseRef){
421
+ const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
422
+ op:'context-control',command:'permit.consume',
423
+ args:{expectedStoreEpoch:run.contextStoreEpoch,writeRequestId:run.token,
424
+ expectedTaskRevision:run.contextTaskRevision,
425
+ expectedApprovalRevision:run.contextApprovalRevision,
426
+ actionToken:run.token,kind:'START',leaseRef:run.contextLeaseRef}
427
+ }).catch(()=>null);
428
+ if(allowed?.status!=='OK'||allowed.result?.status!=='PERMITTED'){
429
+ await saveRun({...run,phase:'BLOCKED',reason:'CONTEXT_START_PERMIT_UNVERIFIED'});
430
+ return {status:'DENIED',code:allowed?.code||'CONTEXT_START_PERMIT_UNVERIFIED'};
431
+ }
432
+ }
319
433
  return {status:'OK',sessionId:run.sessionId,
434
+ ...(run.taskId?{taskId:run.taskId}:{}),
320
435
  ...(run.mode==='adopt'?{mode:'adopt',tabId:run.adoptTabId,
321
436
  page:run.adoptPage,userKey:run.adoptUserKey,
322
437
  ...(run.adoptExplicitChatId?{explicitChatId:run.adoptExplicitChatId}:{}),
323
- priorAssistantKey:run.adoptPriorAssistantKey}
438
+ priorAssistantKey:run.adoptPriorAssistantKey,
439
+ ...(run.purpose==='REPAIR_SAME_SCOPE'
440
+ ?{purpose:'REPAIR_SAME_SCOPE',repairUserText:run.repairUserText,
441
+ priorDoneAssistantKey:run.repairDoneAssistantKey}
442
+ :{rVersion:run.adoptRVersion,pVersion:run.adoptPVersion})}
324
443
  :{prompt:run.startPrompt})};
325
444
  }
326
445
  async function sessionStartResult(message,sender){
@@ -343,12 +462,20 @@ async function sessionStartResult(message,sender){
343
462
  &&message.newPage===run.adoptPage
344
463
  &&message.newUserKey===run.adoptUserKey;
345
464
  if(confirmed){
465
+ const repair=run.purpose==='REPAIR_SAME_SCOPE';
346
466
  const proof=await chrome.tabs.sendMessage(run.adoptTabId,
347
- {type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
467
+ {type:repair?'CHAT_LOOP_REPAIR_EVIDENCE_V1':'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
348
468
  ...(run.adoptExplicitChatId
349
469
  ?{explicitChatId:run.adoptExplicitChatId}:{})}).catch(()=>null);
350
- confirmed=proof?.status==='VERIFIED'&&proof.page===run.adoptPage
351
- &&proof.userKey===run.adoptUserKey;
470
+ confirmed=proof?.contract==='chat-loop.turn-observer.v1'
471
+ &&proof.status==='VERIFIED'&&proof.page===run.adoptPage
472
+ &&proof.userKey===run.adoptUserKey
473
+ &&(repair
474
+ ? proof.userText===run.repairUserText
475
+ &&proof.priorDoneAssistantKey===run.repairDoneAssistantKey
476
+ :proof.rVersion===run.adoptRVersion
477
+ &&proof.pVersion===run.adoptPVersion
478
+ &&(proof.priorAssistantKey||null)===(run.adoptPriorAssistantKey||null));
352
479
  }
353
480
  }
354
481
  // Four-hour execution clock begins at confirmed enrollment, not at
@@ -372,18 +499,74 @@ async function sessionStartResult(message,sender){
372
499
  delete next.adoptUserKey;
373
500
  delete next.adoptExplicitChatId;
374
501
  delete next.adoptPriorAssistantKey;
502
+ delete next.adoptRVersion;
503
+ delete next.adoptPVersion;
504
+ delete next.repairUserText;
505
+ delete next.repairDoneAssistantKey;
506
+ delete next.purpose;
375
507
  delete next.mode;
376
508
  delete next.machineRequestId;
377
509
  delete next.machineActionTabId;
378
510
  delete next.replacedBlockedSessionId;
379
511
  await saveRun(next);
512
+ let privateContext=null;
513
+ if(confirmed&&run.contextLeaseRef){
514
+ const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
515
+ op:'context-control',command:'run.bind.initial',
516
+ args:{expectedStoreEpoch:run.contextStoreEpoch,
517
+ writeRequestId:run.token+':initial-bind',
518
+ expectedTaskRevision:run.contextTaskRevision,expectedBindingRevision:0,
519
+ actionToken:run.token,leaseRef:run.contextLeaseRef,
520
+ runCredential:run.contextInitialCredential}
521
+ }).catch(()=>null);
522
+ if(bound?.status!=='OK'||bound.result?.status!=='BOUND'){
523
+ // First Chat may already exist. Never re-send merely to fix Context.
524
+ const stopped={...next,phase:'BLOCKED',reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
525
+ delete stopped.contextInitialCredential;
526
+ await saveRun(stopped);
527
+ return {status:'BLOCKED',code:bound?.code||'CONTEXT_INITIAL_BIND_UNVERIFIED'};
528
+ }
529
+ privateContext={runRef:bound.result.runRef,
530
+ runCredential:run.contextInitialCredential,
531
+ storeEpoch:run.contextStoreEpoch,
532
+ bindingRevision:bound.result.bindingRevision,
533
+ taskRevision:run.contextTaskRevision};
534
+ // Capability is delivered once in the private Start result, not Status.
535
+ const clean={...next,contextManaged:{storeEpoch:run.contextStoreEpoch}};
536
+ for(const key of ['contextInitialCredential','contextLeaseRef','contextStoreEpoch',
537
+ 'contextTaskRevision','contextApprovalRevision'])delete clean[key];
538
+ await saveRun(clean);
539
+ }
380
540
  if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
381
541
  'https://chatgpt.com'+message.newPage).catch(()=>{});
382
542
  return confirmed?{status:'OK',sessionId:next.sessionId,
383
543
  activeChatId:sessionProjection(next).activeChatId,
384
- activeChatUrl:sessionProjection(next).activeChatUrl}
544
+ activeChatUrl:sessionProjection(next).activeChatUrl,
545
+ ...(next.taskId?{taskId:next.taskId}:{}),
546
+ ...(privateContext?{context:privateContext}:{})}
385
547
  :{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
386
548
  }
549
+ // Read the existing resource index without reconciliation, tab mutation or
550
+ // Owner changes. A registered blank successor proves only tab creation,
551
+ // NEVER a click, user message or successful Handoff.
552
+ async function handoffTabEvidence(run){
553
+ if(run?.phase!=="BLOCKED"||run.action!=="HANDOFF"||!run.sessionId)
554
+ return null;
555
+ const saved=(await chrome.storage.local.get(resources.KEY).catch(()=>null))
556
+ ?.[resources.KEY];
557
+ const candidates=Array.isArray(saved?.entries)?saved.entries.filter(entry=>
558
+ entry?.kind==="chat"&&entry.confirmed===false
559
+ &&entry.sessionId===run.sessionId&&Number.isInteger(entry.id)
560
+ &&entry.id!==run.tabId):[];
561
+ if(candidates.length!==1)return null;
562
+ const entry=candidates[0];
563
+ const tab=await chrome.tabs.get(entry.id).catch(()=>null);
564
+ if(!tab||typeof tab.url!=="string"||!tab.url.startsWith("https://chatgpt.com/"))
565
+ return null;
566
+ return {tabId:entry.id,recorded:true,confirmed:false,
567
+ pageState:tab.url==="https://chatgpt.com/"?"BLANK_HOME":"CHANGED_UNVERIFIED",
568
+ sendReceipt:"UNVERIFIED"};
569
+ }
387
570
  async function sessionStatus(message,sender){
388
571
  if(!sessionPage(sender,'status',message.requestId))
389
572
  return {status:'DENIED',code:'INVALID_STATUS_SOURCE'};
@@ -397,6 +580,8 @@ async function sessionStatus(message,sender){
397
580
  return {status:'UNVERIFIED',code:'SESSION_OWNER_MISMATCH'};
398
581
  if(run&&run.phase!=='DONE'&&!run.sessionId)
399
582
  return {status:'OK',state:'LEGACY_OWNER',phase:run.phase};
583
+ if(run?.phase==='DONE'&&!terminalFenceVerified(run))
584
+ return {status:'UNVERIFIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
400
585
  if(!run||run.phase==='DONE')return {status:'OK',state:'IDLE',
401
586
  ...(disk.session?{lastSession:disk.session}:{} )};
402
587
  const record=sessionProjection(run);
@@ -413,8 +598,10 @@ async function sessionStatus(message,sender){
413
598
  // Identity comes from the verified Worker projection, but updatedAt is
414
599
  // Native's durable CAS revision. Never report a synthetic timestamp as a
415
600
  // usable recovery credential.
601
+ const tabEvidence=await handoffTabEvidence(run);
416
602
  return {status:'OK',state:run.phase==='BLOCKED'?'BLOCKED':'ACTIVE',session:disk.session,
417
603
  diagnostics:{extensionVersion:chrome.runtime.getManifest?.().version||null,
604
+ ...(tabEvidence?{handoffTabEvidence:tabEvidence}:{}),
418
605
  // The numeric tab ID is a locator, never a send capability. Expose only
419
606
  // for an exactly verified terminal/awaiting Owner, not a guessed tab.
420
607
  ownerTabId:['WAITING_REPLY','BLOCKED'].includes(run.phase)?run.tabId:null,
@@ -673,9 +860,15 @@ async function onModelIntent(message,sender) {
673
860
  ...(action==='CONTINUE'?{nextPrompt:intent.nextPrompt}
674
861
  :{reason:intent.reason||''}), queuedAt:Date.now()
675
862
  }};
863
+ const correlation=run.sessionId&&run.projectId?{
864
+ sessionId:run.sessionId,projectId:run.projectId,
865
+ ...(run.taskId?{taskId:run.taskId}:{}),generation:run.generation||0}:{};
676
866
  await saveRun(updateModelReceipt(next,id,{action,turnToken:intent.turnToken,
677
- status:'QUEUED',reason:null,actualAction:null,checkpointForwarded:false}));
678
- return {status:'QUEUED',action,intentId:id};
867
+ ...correlation,status:'QUEUED',reason:null,actualAction:null,
868
+ checkpointForwarded:false}));
869
+ // Scoped correlation metadata only. This is an intent queue receipt,
870
+ // never proof that a browser send happened.
871
+ return {status:'QUEUED',action,intentId:id,...correlation};
679
872
  }
680
873
  async function onModelIntentStatus(message,sender) {
681
874
  const action=message?.action;
@@ -697,6 +890,10 @@ async function onModelIntentStatus(message,sender) {
697
890
  :receipts.find(x=>x.id===intent.intentId);
698
891
  if(!receipt)return {status:'DENIED',code:'INTENT_RECEIPT_NOT_FOUND'};
699
892
  return {status:'STATUS',action,intentId:receipt.id,phase:receipt.status,
893
+ ...(receipt.sessionId&&receipt.projectId?{
894
+ sessionId:receipt.sessionId,projectId:receipt.projectId,
895
+ ...(receipt.taskId?{taskId:receipt.taskId}:{}),
896
+ generation:receipt.generation}:{}),
700
897
  actualAction:receipt.actualAction||null,reason:receipt.reason||null,
701
898
  checkpointForwarded:receipt.checkpointForwarded===true,
702
899
  updatedAt:receipt.updatedAt};
@@ -781,9 +978,40 @@ async function onTurnFinished(message, sender) {
781
978
  ? queued.action : status;
782
979
  if (nextAction !== "CONTINUE" && nextAction !== "HANDOFF") {
783
980
  if (previous?.phase === "WAITING_REPLY" && previous.tabId === tabId) {
784
- await saveRun({...previous, phase: status === "DONE" ? "DONE" : "BLOCKED",
785
- reason: status, userKey: message.userKey, assistantKey: message.assistantKey,
786
- });
981
+ const terminal={...previous, phase:status==="DONE"?"DONE":"BLOCKED",
982
+ reason:status,userKey:message.userKey,assistantKey:message.assistantKey};
983
+ if(status==="DONE"&&previous.contextManaged&&previous.taskId){
984
+ // Check the actual Context delivery BEFORE publishing a durable DONE.
985
+ // A model's machine marker alone is never a committed Task outcome.
986
+ const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
987
+ op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
988
+ const fact=observed?.result;
989
+ if(observed?.status!=="OK"||fact?.executionOutcome!=="DONE"
990
+ ||!fact.deliveryRef
991
+ ||fact.runRef!==previous.sessionId+":"+previous.taskId+":"+(previous.generation||0)){
992
+ await saveRun({...terminal,phase:"BLOCKED",
993
+ reason:"CONTEXT_TERMINAL_NOT_COMMITTED",contextTerminalFence:"UNVERIFIED"});
994
+ return {status:"BLOCKED",code:"CONTEXT_TERMINAL_NOT_COMMITTED"};
995
+ }
996
+ // The signed Native fence requires phase DONE; keep a durable
997
+ // PENDING marker that denies IDLE/Start until the fence is verified.
998
+ await saveRun({...terminal,contextTerminalFence:"PENDING"});
999
+ const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1000
+ op:"context-control",command:"run.fence.terminal",
1001
+ args:{expectedStoreEpoch:previous.contextManaged.storeEpoch,
1002
+ writeRequestId:"terminal:"+previous.sessionId+":"+(previous.generation||0),
1003
+ expectedTaskRevision:fact.taskRevision,
1004
+ expectedBindingRevision:fact.bindingRevision}
1005
+ }).catch(()=>null);
1006
+ if(fenced?.status!=="OK"||fenced.result?.status!=="TERMINAL_FENCED"){
1007
+ // Native DONE cannot regress to BLOCKED. Leave that truthful
1008
+ // projection in place, but never treat it as released write rights.
1009
+ await saveRun({...terminal,reason:"CONTEXT_TERMINAL_FENCE_UNVERIFIED",
1010
+ contextTerminalFence:"UNVERIFIED"});
1011
+ return {status:"BLOCKED",code:"CONTEXT_TERMINAL_FENCE_UNVERIFIED"};
1012
+ }
1013
+ await saveRun({...terminal,contextTerminalFence:"CONFIRMED"});
1014
+ }else await saveRun(terminal);
787
1015
  }
788
1016
  return {status: "IGNORED", code: nextAction === "UNSUPPORTED_MODEL_HANDOFF"
789
1017
  ? "MODEL_HANDOFF_DISABLED" : status};
@@ -794,7 +1022,9 @@ async function onTurnFinished(message, sender) {
794
1022
  if (nextAction === "CONTINUE" && newlyDue) nextAction = "HANDOFF";
795
1023
  const token = crypto.randomUUID();
796
1024
  const run = {...(previous?.sessionId ? {sessionId: previous.sessionId,
797
- projectId: previous.projectId, generation: previous.generation || 0} : {}),
1025
+ projectId: previous.projectId,...(previous.taskId?{taskId:previous.taskId}:{}),
1026
+ ...(previous.contextManaged?{contextManaged:previous.contextManaged}:{}),
1027
+ generation: previous.generation || 0} : {}),
798
1028
  tabId, page: message.page, userKey: message.userKey,
799
1029
  assistantKey: message.assistantKey, phase: "RESERVED", token,
800
1030
  action: nextAction, startedAt, modelReceipts:receiptHistory(previous),
@@ -913,6 +1143,11 @@ async function onManualPrepare(message, sender) {
913
1143
  // Modern unknown sends are never eligible, even with the query parameter.
914
1144
  // Explicit repair acknowledgement binds the operator to the exact disk
915
1145
  // blocker. It does not claim that the browser can verify business repair.
1146
+ const contextRaw=url.searchParams.get("recoverContextNotSentAt");
1147
+ const contextAt=contextRaw!==null?Number(contextRaw):null;
1148
+ if(contextRaw!==null&&(requested!=="CONTINUE"||!rawTabId
1149
+ ||!Number.isSafeInteger(contextAt)||contextAt<=0))
1150
+ return {status:"DENIED",code:"INVALID_CONTEXT_NOT_SENT_RECOVERY"};
916
1151
  const resumeRaw=url.searchParams.get("resumeBlockedAt");
917
1152
  const resumeAt=resumeRaw!==null?Number(resumeRaw):null;
918
1153
  if(resumeRaw!==null&&(requested!=="CONTINUE"||!rawTabId
@@ -927,7 +1162,8 @@ async function onManualPrepare(message, sender) {
927
1162
  return {status:"DENIED",code:"INVALID_LEGACY_REPAIR"};
928
1163
  if (url.origin !== new URL(chrome.runtime.getURL(filename)).origin
929
1164
  || url.pathname !== "/" + filename || url.searchParams.has("token")
930
- || Array.from(url.searchParams.keys()).some(key => key !== "tabId"&&key!=="repairLegacyReservation"&&key!=="resumeBlockedAt")
1165
+ || Array.from(url.searchParams.keys()).some(key => key !== "tabId"&&key!=="repairLegacyReservation"&&key!=="resumeBlockedAt"
1166
+ &&key!=="recoverContextNotSentAt")
931
1167
  || url.searchParams.size!==new Set(url.searchParams.keys()).size
932
1168
  || (rawTabId !== null && (!/^[1-9][0-9]*$/.test(rawTabId)
933
1169
  || message.tabId !== Number(rawTabId))))
@@ -943,10 +1179,21 @@ async function onManualPrepare(message, sender) {
943
1179
  &&previous.recoveryAttempts===1&&!previous.recoveryProtocol
944
1180
  &&previous.newUserKey===previous.userKey
945
1181
  &&previous.recoverySourceAssistantKey===previous.assistantKey);
1182
+ const contextNotSent=Boolean(contextAt&&requested==="CONTINUE"
1183
+ &&previous?.sessionId&&previous.taskId&&previous.phase==="BLOCKED"
1184
+ &&previous.action==="HANDOFF"
1185
+ &&previous.reason==="CONTEXT_HANDOFF_NOT_SENT"
1186
+ &&previous.contextHandoff?.sendOutcome==="NOT_SENT"
1187
+ &&!previous.contextHandoff.sendBeginAt
1188
+ &&Number.isSafeInteger(previous.contextHandoff.terminalActionResultAt)
1189
+ &&previous.contextHandoff.attemptId===previous.token
1190
+ &&!previous.contextRecoveryAttempted
1191
+ &&previous.contextManaged
1192
+ &&previous.contextHandoff.targetGeneration===(previous.generation||0)+1);
946
1193
  const recoveryCandidate=requested==="CONTINUE"
947
1194
  &&previous?.sessionId&&previous.phase==="BLOCKED"
948
1195
  &&Number.isInteger(previous.tabId)
949
- &&(legacyUnsent||previous.reason==="BLOCKED"
1196
+ &&(contextNotSent||legacyUnsent||previous.reason==="BLOCKED"
950
1197
  &&((previous.recoveryAttempts||0)===0||resumeAt
951
1198
  &&previous.recoverySourceAssistantKey!==previous.assistantKey));
952
1199
  if (previous && (previous.sessionId&&previous.phase!=="DONE"&&!recoveryCandidate
@@ -972,14 +1219,16 @@ async function onManualPrepare(message, sender) {
972
1219
  || second.userKey !== first.userKey || second.assistantKey !== first.assistantKey
973
1220
  || second.replyText !== first.replyText) return {status: "DENIED", code: "TURN_NOT_STABLE"};
974
1221
  const modelStatus = globalThis.ChatLoopCoreV1.parseStatus(first.replyText);
975
- const ownedRecovery=Boolean(recoveryCandidate && modelStatus==="BLOCKED"
1222
+ const ownedRecovery=Boolean(recoveryCandidate
1223
+ &&(modelStatus==="BLOCKED"
1224
+ ||contextNotSent&&["HANDOFF","CONTINUE"].includes(modelStatus))
976
1225
  &&Number.isInteger(message.tabId) && message.tabId===previous.tabId
977
1226
  &&previous.tabId===tab.id&&previous.page===first.page
978
1227
  &&previous.userKey===first.userKey
979
1228
  &&previous.assistantKey===first.assistantKey
980
1229
  // Specific repaired tool capability, not generic BLOCKED, human
981
1230
  // approval failure, unknown browser send or context exhaustion.
982
- &&(resumeAt||/\b(?:adopt|Start)\b/i.test(first.replyText))
1231
+ &&(contextNotSent||resumeAt||/\b(?:adopt|Start)\b/i.test(first.replyText))
983
1232
  &&!first.pendingConfirmation
984
1233
  &&!second.pendingConfirmation);
985
1234
  if (recoveryCandidate && !ownedRecovery)
@@ -1006,6 +1255,7 @@ async function onManualPrepare(message, sender) {
1006
1255
  ||disk.session.generation!==(previous.generation||0)
1007
1256
  ||disk.session.activeChatId!==chatIdOf(tab.url)
1008
1257
  ||resumeAt&&disk.session.updatedAt!==resumeAt
1258
+ ||contextAt&&disk.session.updatedAt!==contextAt
1009
1259
  ||legacyAt&&(!legacyUnsent||disk.session.updatedAt!==legacyAt))
1010
1260
  return {status:"DENIED",code:"BLOCKED_OWNER_PERSISTENCE_UNVERIFIED"};
1011
1261
  }
@@ -1015,9 +1265,14 @@ async function onManualPrepare(message, sender) {
1015
1265
  assistantKey: first.assistantKey, phase: "RESERVED", token,
1016
1266
  action: requested, startedAt:ownedRecovery?previous.startedAt:Date.now(),
1017
1267
  manualActionTabId: sender.tab.id,
1018
- ...(ownedRecovery?{recoveryMode:"TOOL_PREFLIGHT_REPAIRED",
1268
+ ...(ownedRecovery?{recoveryMode:contextNotSent?"HANDOFF_NOT_SENT":"TOOL_PREFLIGHT_REPAIRED",
1019
1269
  recoveryAttempts:(previous.recoveryAttempts||0)+1,recoveryProtocol:1,
1020
- ...(resumeAt||legacyUnsent?{recoveryExpectedNativeAt:resumeAt||legacyAt}:{}),
1270
+ ...(resumeAt||legacyUnsent||contextNotSent
1271
+ ?{recoveryExpectedNativeAt:contextAt||resumeAt||legacyAt}:{}),
1272
+ ...(contextNotSent?{contextSourceMarker:"[CHAT_LOOP_STATUS:"+modelStatus+"]",
1273
+ contextRecoveryCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
1274
+ x=>x.toString(16).padStart(2,"0")).join(""),
1275
+ contextRecoveryAttempted:true}:{}),
1021
1276
  recoverySourceAssistantKey:first.assistantKey}:{}),
1022
1277
  handoffMode: requested === "HANDOFF"
1023
1278
  ? (modelStatus === "HANDOFF" ? "EXPLICIT" : "TIMED") : null,
@@ -1083,19 +1338,134 @@ async function onTake(message, sender) {
1083
1338
  // Acceptance fixtures retain their existing prompts; native Retry keeps its original Turn token.
1084
1339
  const modelTurnToken = run.retryMode === "NATIVE"
1085
1340
  ? run.modelTurnToken || null : crypto.randomUUID();
1086
- const pending={...run, phase: "PENDING", modelTurnToken};
1341
+ let recoveredContext=null;
1342
+ if(run.action==="CONTINUE" && run.recoveryMode==="HANDOFF_NOT_SENT"){
1343
+ const h=run.contextHandoff;
1344
+ if(!run.contextRecoveryCredential || !h || h.sendOutcome!=="NOT_SENT"
1345
+ ||h.sendBeginAt ||h.attemptId===run.token){
1346
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_NOT_SENT_PROOF_INVALID"});
1347
+ return {status:"DENIED",code:"CONTEXT_NOT_SENT_PROOF_INVALID"};
1348
+ }
1349
+ const snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1350
+ op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
1351
+ const cp=snapshot?.result;
1352
+ if(snapshot?.status!=="OK" || cp.taskRevision!==h.taskRevision
1353
+ ||cp.bindingRevision!==h.bindingRevision ||cp.runRef!==null
1354
+ ||cp.checkpointId!==h.checkpointId ||cp.unknownEffectCount!==0){
1355
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_SNAPSHOT_UNVERIFIED"});
1356
+ return {status:"DENIED",code:"CONTEXT_RESTORE_SNAPSHOT_UNVERIFIED"};
1357
+ }
1358
+ const approval=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1359
+ op:"context-control",command:"permit.consume",
1360
+ args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:run.token+":permit",
1361
+ actionToken:run.token,kind:"CONTINUE",expectedTaskRevision:h.taskRevision,
1362
+ expectedApprovalRevision:cp.approvalRevision}
1363
+ }).catch(()=>null);
1364
+ if(approval?.status!=="OK"||approval.result?.status!=="PERMITTED"){
1365
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_PERMIT_UNVERIFIED"});
1366
+ return {status:"DENIED",code:"CONTEXT_RESTORE_PERMIT_UNVERIFIED"};
1367
+ }
1368
+ const restored=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1369
+ op:"context-control",command:"run.restore-same-owner",
1370
+ args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:run.token+":restore",
1371
+ expectedTaskRevision:h.taskRevision,expectedBindingRevision:h.bindingRevision,
1372
+ attemptId:h.attemptId,checkpointId:h.checkpointId,
1373
+ recoveryCredential:run.contextRecoveryCredential,
1374
+ recoveryActionToken:run.token,sendState:"NOT_SENT"}
1375
+ }).catch(()=>null);
1376
+ if(restored?.status!=="OK"||restored.result?.status!=="RESTORED_SAME_OWNER"){
1377
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_BIND_UNVERIFIED"});
1378
+ return {status:"DENIED",code:"CONTEXT_RESTORE_BIND_UNVERIFIED"};
1379
+ }
1380
+ recoveredContext={runRef:restored.result.runRef,
1381
+ runCredential:run.contextRecoveryCredential,storeEpoch:h.storeEpoch,
1382
+ bindingRevision:restored.result.bindingRevision,taskRevision:h.taskRevision};
1383
+ }
1384
+ const pending={...run, phase: "PENDING", modelTurnToken,
1385
+ ...(recoveredContext?{contextRecoveryBound:recoveredContext}:{})};
1087
1386
  await saveRun(run.modelIntent ? updateModelReceipt(pending,run.modelIntent.id,{
1088
1387
  status:run.action==="HANDOFF"&&run.modelIntent.action==="CONTINUE"
1089
1388
  ?"OVERRIDDEN_BY_DEADLINE":"PENDING"}) : pending);
1389
+ if(run.action==="CONTINUE" &&run.contextManaged &&!recoveredContext &&run.retryMode!=="NATIVE"){
1390
+ const snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1391
+ op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
1392
+ const cp=snapshot?.result;
1393
+ if(snapshot?.status!=="OK"||!cp ||cp.runRef!==
1394
+ run.sessionId+":"+run.taskId+":"+(run.generation||0)){
1395
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CONTINUE_SNAPSHOT_UNVERIFIED"});
1396
+ return {status:"DENIED",code:"CONTEXT_CONTINUE_SNAPSHOT_UNVERIFIED"};
1397
+ }
1398
+ const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1399
+ op:"context-control",command:"permit.consume",
1400
+ args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
1401
+ writeRequestId:run.token+":permit",expectedTaskRevision:cp.taskRevision,
1402
+ expectedApprovalRevision:cp.approvalRevision,
1403
+ actionToken:run.token,kind:"CONTINUE"}
1404
+ }).catch(()=>null);
1405
+ if(allowed?.status!=="OK"||allowed.result?.status!=="PERMITTED"){
1406
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CONTINUE_PERMIT_UNVERIFIED"});
1407
+ return {status:"DENIED",code:"CONTEXT_CONTINUE_PERMIT_UNVERIFIED"};
1408
+ }
1409
+ }
1410
+ let managedHandoff=null;
1411
+ if(run.action==="HANDOFF"&&run.contextManaged){
1412
+ if(!run.taskId||!run.sessionId){
1413
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_TASK_IDENTITY_MISSING"});
1414
+ return {status:"DENIED",code:"CONTEXT_TASK_IDENTITY_MISSING"};
1415
+ }
1416
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1417
+ op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
1418
+ const cp=proof?.result;
1419
+ if(proof?.status!=="OK"||!cp?.checkpointCurrent||cp.unknownEffectCount!==0
1420
+ ||cp.runRef!==run.sessionId+":"+run.taskId+":"+(run.generation||0)){
1421
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CHECKPOINT_UNVERIFIED"});
1422
+ return {status:"DENIED",code:"CONTEXT_CHECKPOINT_UNVERIFIED"};
1423
+ }
1424
+ const permitProof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1425
+ op:"context-control",command:"permit.consume",
1426
+ args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
1427
+ writeRequestId:run.token+":permit",actionToken:run.token,kind:"HANDOFF",
1428
+ expectedTaskRevision:cp.taskRevision,
1429
+ expectedApprovalRevision:cp.approvalRevision}
1430
+ }).catch(()=>null);
1431
+ if(permitProof?.status!=="OK"||permitProof.result?.status!=="PERMITTED"){
1432
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_HANDOFF_PERMIT_UNVERIFIED"});
1433
+ return {status:"DENIED",code:"CONTEXT_HANDOFF_PERMIT_UNVERIFIED"};
1434
+ }
1435
+ const nextRunCredential=Array.from(crypto.getRandomValues(new Uint8Array(32)),
1436
+ x=>x.toString(16).padStart(2,"0")).join("");
1437
+ const targetGeneration=(run.generation||0)+1;
1438
+ const nextRunRef=run.sessionId+":"+run.taskId+":"+targetGeneration;
1439
+ const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1440
+ op:"context-control",command:"run.fence",
1441
+ args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
1442
+ writeRequestId:run.token+":fence",expectedTaskRevision:cp.taskRevision,
1443
+ expectedBindingRevision:cp.bindingRevision,checkpointId:cp.checkpointId,
1444
+ attemptId:run.token,actionToken:run.token,targetGeneration,
1445
+ nextRunRef,nextRunCredential}
1446
+ }).catch(()=>null);
1447
+ if(fenced?.status!=="OK"||fenced.result?.status!=="FENCED"){
1448
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_HANDOFF_FENCE_UNVERIFIED"});
1449
+ return {status:"DENIED",code:"CONTEXT_HANDOFF_FENCE_UNVERIFIED"};
1450
+ }
1451
+ managedHandoff={attemptId:run.token,checkpointId:cp.checkpointId,
1452
+ taskRevision:cp.taskRevision,bindingRevision:fenced.result.bindingRevision,
1453
+ targetGeneration,nextRunRef,nextRunCredential,
1454
+ storeEpoch:run.contextManaged.storeEpoch};
1455
+ await saveRun({...pending,contextHandoff:managedHandoff});
1456
+ }
1090
1457
  const permit = {status: "OK", action: run.action || "CONTINUE",
1091
1458
  modelTurnToken,
1092
1459
  modelTurnNote: modelTurnToken ? turnToolNote(modelTurnToken) : "",
1093
1460
  handoffMode: run.handoffMode || null, retryMode: run.retryMode || null,
1094
1461
  ...(projectContext?{projectContext}:{}),
1462
+ ...(managedHandoff?{contextHandoff:{...managedHandoff,
1463
+ projectId:run.projectId,taskId:run.taskId,sessionId:run.sessionId}}:{}),
1095
1464
  target: {tabId: run.tabId, page: run.page,
1096
1465
  ...(run.sessionId?{sessionId:run.sessionId,projectId:run.projectId,
1097
- generation:run.generation||0}:{}),
1466
+ ...(run.taskId?{taskId:run.taskId}:{}),generation:run.generation||0}:{}),
1098
1467
  recoveryMode:run.recoveryMode||null,
1468
+ ...(run.contextSourceMarker?{contextSourceMarker:run.contextSourceMarker}:{}),
1099
1469
  assistantKey: run.assistantKey,
1100
1470
  userKey: run.retryMode === "NATIVE" || run.handoffMode === "ERROR"
1101
1471
  ? run.newUserKey : run.userKey,
@@ -1117,12 +1487,33 @@ async function onTake(message, sender) {
1117
1487
  : CONTINUE_TEXT};
1118
1488
  // A single error contract applies to default, model-specified and repaired
1119
1489
  // Continue prompts; the Worker still obeys the model's terminal marker.
1120
- if(run.action==="CONTINUE" && typeof permit.text==="string")
1490
+ if(run.action==="CONTINUE" && typeof permit.text==="string"){
1121
1491
  permit.text=ENGINEERING_FAILURE_NOTE+"\n\n"+permit.text;
1492
+ if(recoveredContext){
1493
+ permit.text += "\n\n【Chat Loop Context|HANDOFF_NOT_SENT 单次恢复写凭据】\n"
1494
+ +JSON.stringify({projectId:run.projectId,taskId:run.taskId,
1495
+ sessionId:run.sessionId,generation:run.generation||0,
1496
+ ...recoveredContext})+"\n请先按原 Session 核实 Context 与未知副作用,"
1497
+ +"此凭据仅用于当前任务 Context 写入;旧 Handoff 不得重新发送。";
1498
+ }
1499
+ }
1122
1500
  if (modelTurnToken && typeof permit.text === "string")
1123
1501
  permit.text += permit.modelTurnNote;
1124
1502
  return permit;
1125
1503
  }
1504
+ // Durable pre-send evidence; once recorded a browser send may have happened.
1505
+ // A later timeout is UNKNOWN, never equivalent to NOT_SENT.
1506
+ async function onHandoffSendBegin(message,sender){
1507
+ const run=await readRun();
1508
+ if(!isAction(sender,message,run)||run?.action!=="HANDOFF"
1509
+ ||run.phase!=="PENDING"||!run.contextHandoff
1510
+ ||run.token!==message.token||run.tabId!==message.tabId)
1511
+ return {status:"DENIED",code:"HANDOFF_SEND_SOURCE_INVALID"};
1512
+ if(run.contextHandoff.sendBeginAt)
1513
+ return {status:"DENIED",code:"HANDOFF_SEND_ALREADY_BEGUN"};
1514
+ await saveRun({...run,contextHandoff:{...run.contextHandoff,sendBeginAt:Date.now()}});
1515
+ return {status:"RECORDED"};
1516
+ }
1126
1517
  async function onResult(message, sender) {
1127
1518
  const run = await readRun();
1128
1519
  if (!isAction(sender, message, run)) return {status: "DENIED", code: "ACTION_SOURCE_INVALID"};
@@ -1200,7 +1591,42 @@ async function onResult(message, sender) {
1200
1591
  delete next.modelIntent;
1201
1592
  }
1202
1593
  if (!confirmed) delete next.modelTurnToken;
1594
+ if(confirmed&&run.recoveryMode==="HANDOFF_NOT_SENT"){
1595
+ for(const key of ["contextRecoveryCredential","contextRecoveryBound",
1596
+ "contextHandoff","recoveryMode","contextSourceMarker",
1597
+ "recoveryExpectedNativeAt","recoverySourceAssistantKey",
1598
+ "recoveryProtocol","recoveryAttempts","contextRecoveryAttempted"])
1599
+ delete next[key];
1600
+ }
1601
+ if(!confirmed && run.action==="HANDOFF" && run.contextHandoff){
1602
+ const notSent=!run.contextHandoff.sendBeginAt;
1603
+ next={...next,reason:notSent?"CONTEXT_HANDOFF_NOT_SENT":"CONTEXT_HANDOFF_SEND_UNKNOWN",
1604
+ contextHandoff:{...run.contextHandoff,
1605
+ sendOutcome:notSent?"NOT_SENT":"SEND_UNKNOWN",
1606
+ // This is derived ONLY after original Action Result is received.
1607
+ terminalActionResultAt:Date.now()}};
1608
+ }
1203
1609
  await saveRun(next);
1610
+ if(confirmed && run.action==="HANDOFF" && run.contextHandoff){
1611
+ const h=run.contextHandoff;
1612
+ const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
1613
+ op:"context-control",command:"run.bind.handoff",
1614
+ args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:h.attemptId+":bind",
1615
+ expectedTaskRevision:h.taskRevision,expectedBindingRevision:h.bindingRevision,
1616
+ attemptId:h.attemptId,checkpointId:h.checkpointId,
1617
+ targetGeneration:h.targetGeneration,runCredential:h.nextRunCredential}
1618
+ }).catch(()=>null);
1619
+ if(bound?.status!=="OK"||bound.result?.status!=="BOUND"){
1620
+ const failed={...next,phase:"BLOCKED",reason:"CONTEXT_NEW_OWNER_BIND_UNVERIFIED"};
1621
+ // Retain the exact original attempt and pending credential in private
1622
+ // Worker storage for receipt-only diagnosis. Never re-send the message.
1623
+ await saveRun(failed);
1624
+ return {status:"BLOCKED",code:bound?.code||"CONTEXT_NEW_OWNER_BIND_UNVERIFIED"};
1625
+ }
1626
+ const clean={...next,contextManaged:{storeEpoch:h.storeEpoch}};
1627
+ delete clean.contextHandoff;
1628
+ await saveRun(clean); // secret has already been delivered in the unique first message
1629
+ }
1204
1630
  if(confirmed && run.action==="HANDOFF" && Number.isInteger(message.newTabId))
1205
1631
  await resources.confirmChat(message.newTabId,next.sessionId||next.token,
1206
1632
  "https://chatgpt.com"+message.newPage).catch(()=>{});
@@ -1382,6 +1808,7 @@ const SERIAL_ROUTES=new Map([
1382
1808
  ['CHAT_LOOP_TURN_BLOCKED_V1',onTurnBlocked],
1383
1809
  ['CHAT_LOOP_ACTION_TAKE_V1',onTake],
1384
1810
  ['CHAT_LOOP_ACTION_RESULT_V1',onResult],
1811
+ ['CHAT_LOOP_HANDOFF_SEND_BEGIN_V1',onHandoffSendBegin],
1385
1812
  ['CHAT_LOOP_ACTION_MANUAL_REVEAL_V1',onManualReveal],
1386
1813
  ['CHAT_LOOP_ACTION_MANUAL_PREPARE_V1',onManualPrepare],
1387
1814
  ['CHAT_LOOP_MODEL_INTENT_V1',onModelIntent],