@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
@@ -9,6 +9,9 @@ async function approvedAdoptionTarget(chatUrl=null,taskId=null){
9
9
  const existing=tabs.filter(t=>chatIdOf(t.url)===requestedId);
10
10
  if(existing.length>1)return {error:"ADOPTION_CHAT_DUPLICATE_TABS"};
11
11
  if(existing.length===0){
12
+ // Opening the user-specified existing Chat is a Browser side effect.
13
+ // An active V2 Task must not be bypassed by this legacy V1 helper.
14
+ await assertLegacyWorkerWritable({native:true});
12
15
  let opened;
13
16
  try{opened=await chrome.tabs.create({url:chatUrl,active:true});}
14
17
  catch{return {error:"ADOPTION_CHAT_OPEN_FAILED"};}
@@ -6,6 +6,22 @@ const ALARM_NAME = "chat-loop.turn-watch.v1";
6
6
  const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
7
7
  const CONTINUE_TEXT = "继续当前已授权任务,先核实真实进度、权限和已发生副作用;UNKNOWN 只查原回执,不盲目重试,也不把续接视为新增授权。完成本轮后末行只写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
8
8
  const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
9
+ // V2 differs from V1: EVERY continuing Task Turn registers a future
10
+ // private intent BEFORE its assistant reply ends. A naked CONTINUE marker
11
+ // has no signed nextPrompt and MUST NOT be converted to an implicit send.
12
+ const scopedTurnToolNote = token =>
13
+ "\n\n【Chat Loop Task-first 本轮续接协议】" +
14
+ "本 Task 的 turnToken 为 " + token + "(不要在助手正文复述)。" +
15
+ "如果仍有已授权工作,必须在本轮助手回复尚未结束时调用 " +
16
+ "chat_loop_extension__continue,参数 taskFirst:true、turnToken " +
17
+ "及下一步 nextPrompt(无特殊内容时使用“继续当前已授权任务,核实进度、权限和副作用;UNKNOWN 只查原回执,不重发。”)。" +
18
+ "工具只登记 QUEUED,不会立即发送。随后整轮回答最后独立一行" +
19
+ "输出 [CHAT_LOOP_STATUS:CONTINUE]。" +
20
+ "如需提前交接,先核实可交接 Checkpoint,再在本轮调用 " +
21
+ "chat_loop_extension__handoff(taskFirst:true,turnToken)," +
22
+ "末行输出 [CHAT_LOOP_STATUS:HANDOFF]。" +
23
+ "任务完成或必须停止时不登记新发送,分别输出 DONE/BLOCKED。" +
24
+ "不允许只输出 CONTINUE/HANDOFF 而不登记对应的本 Task 意图。";
9
25
  let queue = Promise.resolve();
10
26
  // Business callbacks expose typed, bounded error codes only; raw messages can
11
27
  // contain native paths, browser state or extension internals.
@@ -21,23 +37,62 @@ const serial = fn => {
21
37
  };
22
38
  // Admission and recovery run in this same Worker, never another browser executor.
23
39
  const resources = workerApi.resources;
40
+ const policy=workerApi.policy;
41
+ const {pathOf,chatIdOf}=policy;
42
+ // The V2 store is Task-addressed, but it is not a replacement Browser Owner.
43
+ // Until scoped Router/Native/Context activation is verified, V1 must not write
44
+ // over an active V2 Task. Never fall back to the latest V2 Task.
45
+ const scopedTaskRuns=globalThis.ChatLoopTaskRunStoreV2?.create(chrome.storage.local);
46
+ const scopedTaskScheduler=scopedTaskRuns
47
+ ?globalThis.ChatLoopTaskSchedulerV2?.create(scopedTaskRuns):null;
48
+ const scopedTaskOwnerResolver=scopedTaskRuns
49
+ ?globalThis.ChatLoopTaskOwnerResolverV2?.create({
50
+ store:scopedTaskRuns,getTab:id=>chrome.tabs.get(id),
51
+ readNative:scope=>chrome.runtime.sendNativeMessage(SESSION_HOST,{
52
+ op:'session-snapshot-v2',...scope}),
53
+ checkWriter:scope=>chrome.runtime.sendNativeMessage(SESSION_HOST,{
54
+ op:'context-writer-check-v2',...scope}),
55
+ pathOf,chatIdOf}):null;
56
+ // These are dormant V2 route/dispatch primitives until every sender
57
+ // boundary uses exact TaskKey + Session generation; never auto-dispatch here.
58
+ async function hasActiveScopedTask(){
59
+ if(!scopedTaskRuns)return false;
60
+ const state=await scopedTaskRuns.read();
61
+ return Object.values(state.items).some(({run})=>
62
+ !['DONE','CANCELLED'].includes(run.phase));
63
+ }
64
+ async function assertLegacyWorkerWritable({native=false}={}){
65
+ if(await hasActiveScopedTask())throw Error('TASK_SCOPED_ROUTER_NOT_READY');
66
+ if(!native)return;
67
+ // The Worker snapshot may be stale after MV3 suspension or after another
68
+ // Profile committed a Native Owner. The existing V1 Native read refuses
69
+ // every live V2 Ledger, including ones not present in this Worker store.
70
+ const observed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
71
+ op:'session-read'}).catch(()=>null);
72
+ if(observed?.status!=='OK')
73
+ throw Error(observed?.code==='OWNER_LEDGER_ACTIVE_USE_SCOPED_QUERY'
74
+ ?'TASK_SCOPED_ROUTER_NOT_READY':'LEGACY_NATIVE_OWNER_UNVERIFIED');
75
+ // An in-flight V2 Worker update after Native read must also be rejected.
76
+ if(await hasActiveScopedTask())throw Error('TASK_SCOPED_ROUTER_NOT_READY');
77
+ }
24
78
  async function createBoundedAction(options) {
25
79
  // Validate BEFORE creating a tab. No caller may open an arbitrary URL
26
80
  // through the privileged Worker Action quota.
27
81
  if(typeof options?.url!=='string'
28
82
  ||!options.url.startsWith(chrome.runtime.getURL('')))
29
83
  throw Error('ACTION_URL_UNVERIFIED');
30
- const quota=await resources.admit(await readRun(),{kind:'action'});
31
- if (!quota.ok) throw Error(quota.code);
32
- const tab=await chrome.tabs.create(options);
33
- if (!Number.isSafeInteger(tab?.id)||tab.id<=0)
34
- throw Error('ACTION_CREATED_ID_UNVERIFIED');
35
- // MV3 tabs.create may return about:blank + pendingUrl. Register the exact
36
- // Extension URL requested rather than the transitional snapshot.
37
- let registered=false;
38
- try{registered=await resources.registerAction({id:tab.id,url:options.url});}
39
- catch{ /* The newly created page is not trusted without its registration. */ }
40
- if(!registered){
84
+ // One Worker resource critical section encloses quota admission,
85
+ // actual tab creation and exact URL registration. Another Task cannot
86
+ // pass admission against a stale count while this side effect is in flight.
87
+ const receipt=await resources.withRegisteredAction(await readRun(),{
88
+ url:options.url,create:async()=>{
89
+ await assertLegacyWorkerWritable({native:true});
90
+ return chrome.tabs.create(options);
91
+ }});
92
+ const tab=receipt.tab;
93
+ if(!receipt.ok){
94
+ if(!Number.isSafeInteger(tab?.id)||tab.id<=0)
95
+ throw Error(receipt.code||'ACTION_CREATED_ID_UNVERIFIED');
41
96
  // Failed registration must not strand another Action tab. Remove only
42
97
  // this tab if its fresh, read-back URL still proves Extension identity;
43
98
  // never close a changed, active or pinned tab and never retry a send.
@@ -52,8 +107,6 @@ async function createBoundedAction(options) {
52
107
  }
53
108
  // Identity and receipt policy are shared deterministic helpers. This Worker
54
109
  // remains the only Chrome action/state owner.
55
- const policy=workerApi.policy;
56
- const {pathOf,chatIdOf}=policy;
57
110
  const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
58
111
  // Keep only a fixed-size fingerprint after Start's one-shot prompt is erased.
59
112
  // A missing historical fingerprint means NOT_COMPARABLE, not "zero matches".
@@ -70,6 +123,9 @@ const windowMsOf=policy.windowMsOf;
70
123
  const {deadlineOf,clockActive,terminalFenceVerified,MODEL_RECEIPT_TTL_MS,
71
124
  receiptHistory,updateModelReceipt,settleModelIntent}=policy;
72
125
  async function saveRun(run) {
126
+ // Last Worker write fence: an independently committed V2 Native Owner
127
+ // must not be overwritten even if the caller skipped an earlier route.
128
+ await assertLegacyWorkerWritable({native:true});
73
129
  if (run && ["DONE","BLOCKED"].includes(run.phase))
74
130
  run = settleModelIntent(run, run.phase==="DONE"?"CANCELLED_DONE":"BLOCKED", run.reason);
75
131
  const now = Date.now(), deadlineAt = deadlineOf(run);
@@ -205,8 +261,8 @@ async function resourceChatGate(message,sender) {
205
261
  {tabId:run.tabId,token:run.token},run);
206
262
  if(!authorized)return {status:'DENIED',code:'RESOURCE_ACTION_SOURCE_INVALID'};
207
263
  if(message.stage==='preflight') {
208
- const quota=await resources.admit(run,{kind:'chat'});
209
- return quota.ok?{status:'OK',code:'RESOURCE_CHAT_PERMITTED'}
264
+ const quota=await resources.reserveChat(run,sender.tab.id);
265
+ return quota.ok?{status:'OK',code:'RESOURCE_CHAT_RESERVED'}
210
266
  :{status:'DENIED',code:quota.code};
211
267
  }
212
268
  if(message.stage==='adopt' && run.mode==='adopt'
@@ -221,7 +277,8 @@ async function resourceChatGate(message,sender) {
221
277
  return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
222
278
  const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
223
279
  if (!tab || tab.id===run.tabId || tab.id===sender.tab.id
224
- || !await resources.registerChat(tab,run))
280
+ || tab.openerTabId!==sender.tab.id
281
+ || !await resources.registerReservedChat(tab,run))
225
282
  return {status:'DENIED',code:'RESOURCE_CHAT_NOT_VERIFIED'};
226
283
  const inventory=await resources.reconcile(run);
227
284
  if(inventory.activeChatCount>resources.CHAT_LIMIT)
@@ -2,6 +2,9 @@
2
2
  // Read-only target resolver for a CLI-created formal Eye Action.
3
3
  // This never starts a Loop, changes Owner, or sends a chat message.
4
4
  async function onExtensionCliTarget(message,sender) {
5
+ // V1 Eye must never target an unrelated stale global Run while a scoped
6
+ // Task owner exists. A future V2 Eye uses the exact Task resolver instead.
7
+ await assertLegacyWorkerWritable({native:true});
5
8
  const entry=workerApi.eyeCatalog?.[message?.action];
6
9
  const page=entry?.page;
7
10
  // Catalog only grants the existing read-only Eye permission category. It
@@ -75,16 +78,26 @@ const SERIAL_ROUTES=new Map([
75
78
  ]);
76
79
  const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
77
80
  const type=message?.type;
81
+ if(typeof type==='string'&&type.startsWith('CHAT_LOOP_TASK_'))
82
+ return onScopedBrowserMessage(message,sender,reply);
78
83
  const handle=SERIAL_ROUTES.get(type);
79
84
  if(handle){
80
85
  void serial(async()=>{
81
- let result;
82
- try{result=await handle(type==='CHAT_LOOP_SESSION_STATUS_V1'
83
- ?{...message,auditDispatchParent:dispatchParent}:message,sender);}
86
+ let result,legacyAllowed=false;
87
+ try{
88
+ // Fail BEFORE any old handler reads/consumes a permission or opens
89
+ // an Action. saveRun's later guard is not early enough by itself.
90
+ await assertLegacyWorkerWritable({native:![
91
+ 'CHAT_LOOP_SESSION_STATUS_V1','CHAT_LOOP_MODEL_INTENT_STATUS_V1'
92
+ ].includes(type)});
93
+ legacyAllowed=true;
94
+ result=await handle(type==='CHAT_LOOP_SESSION_STATUS_V1'
95
+ ?{...message,auditDispatchParent:dispatchParent}:message,sender);
96
+ }
84
97
  catch(error){result={status:'BLOCKED',code:safeWorkerErrorCode(error,'SCHEDULER_ERROR')};}
85
98
  // A bounded diagnostic receipt, never permission or a second state store.
86
99
  // In particular a rejected manual recovery must be observable remotely.
87
- if(type==='CHAT_LOOP_ACTION_MANUAL_PREPARE_V1'){
100
+ if(legacyAllowed&&type==='CHAT_LOOP_ACTION_MANUAL_PREPARE_V1'){
88
101
  const current=await readRun();
89
102
  if(current)await chrome.storage.local.set({[RUN_KEY]:{...current,
90
103
  lastManualFeedback:{status:result.status,
@@ -95,7 +108,10 @@ const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
95
108
  return true;
96
109
  }
97
110
  if (type === 'CHAT_LOOP_POPUP_CLEAN_OPEN_V1') {
98
- void serial(()=>openPopupClean(message,sender)).then(reply,
111
+ void serial(async()=>{
112
+ await assertLegacyWorkerWritable({native:true});
113
+ return openPopupClean(message,sender);
114
+ }).then(reply,
99
115
  ()=>reply({status:'BLOCKED',code:'CLEAN_ACTION_UNVERIFIED'}));
100
116
  return true;
101
117
  }
@@ -109,6 +125,7 @@ const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
109
125
  let acknowledged=false;
110
126
  void (async () => {
111
127
  try {
128
+ await assertLegacyWorkerWritable({native:true});
112
129
  if (!Number.isInteger(id)) throw Error("NO_ACTION_TAB");
113
130
  const tab = await chrome.tabs.get(id);
114
131
  const reloadBase=chrome.runtime.getURL("reload.html");
@@ -189,4 +206,4 @@ chrome.runtime.onMessage.addListener((message,sender,reply)=>{
189
206
  ...(actionSource&&message.traceParent?{parent:message.traceParent}:{}),
190
207
  onBegin:ids=>{dispatchSpan=ids;}
191
208
  })(message,sender,respond);
192
- });
209
+ });
@@ -6,13 +6,63 @@ const observeBackground=(work,scope)=>{
6
6
  void work.catch(error=>console.warn('CHAT_LOOP_SCHEDULER_UNVERIFIED',
7
7
  scope,safeWorkerErrorCode(error,'SCHEDULER_ERROR')));
8
8
  };
9
+ async function reconnectScopedObservers(){
10
+ if(!scopedTaskRuns||!scopedTaskOwnerResolver||!scopedTaskScheduler)return;
11
+ const state=await scopedTaskRuns.read();
12
+ const tasks=Object.values(state.items).filter(({run})=>
13
+ run.phase==='WAITING_REPLY');
14
+ const jobs=tasks.map(({run,revision})=>scopedTaskScheduler.perTask(
15
+ run.projectId,run.taskId,async()=>{
16
+ const tab=Number.isSafeInteger(run.tabId)&&run.tabId>0
17
+ ?await chrome.tabs.get(run.tabId).catch(()=>null):null;
18
+ if(!tab||pathOf(tab.url)!==run.page)return;
19
+ const route=await scopedTaskOwnerResolver.resolve({
20
+ id:chrome.runtime.id,frameId:0,tab:{id:tab.id},url:tab.url});
21
+ if(route.projectId!==run.projectId||route.taskId!==run.taskId
22
+ ||route.sessionId!==run.sessionId
23
+ ||route.generation!==run.generation
24
+ ||route.nativeOwnerRevision!==run.nativeOwnerRevision
25
+ ||route.runRevision!==revision)return;
26
+ const latest=await chrome.tabs.get(tab.id).catch(()=>null);
27
+ if(!latest||latest.url!==tab.url)return;
28
+ // Only install the existing Observer on its CURRENT owner. Its
29
+ // baseline is historical unless this Task has the exact user Turn
30
+ // from an already committed SEND_BEGIN+DOM+Native+Context receipt.
31
+ await chrome.scripting.executeScript({target:{tabId:tab.id},
32
+ files:["content.js","loop/core.js","loop/observer-inspect.js",
33
+ "loop/observer-poll.js","loop/observer-recovery.js",
34
+ "loop/observer-approval.js","loop/observer.js"]});
35
+ if(run.awaitingUserKey){
36
+ const owner=await scopedTaskRuns.get(run.projectId,run.taskId);
37
+ if(owner.runRevision!==revision
38
+ ||owner.run?.awaitingUserKey!==run.awaitingUserKey)return;
39
+ const response=await chrome.tabs.sendMessage(tab.id,{
40
+ type:'CHAT_LOOP_TURN_RESUME_V1',page:run.page,
41
+ userKey:run.awaitingUserKey,assistantKey:null,
42
+ startedAt:run.startedAt||Date.now()}).catch(()=>null);
43
+ if(response?.status!=='RESUMED'
44
+ &&response?.status!=='ALREADY_MONITORING')
45
+ console.warn('TASK_SCOPED_AWAITED_OBSERVER_UNVERIFIED',
46
+ response?.reason||response?.status||'UNVERIFIED');
47
+ }
48
+ }));
49
+ const settled=await Promise.allSettled(jobs);
50
+ for(const item of settled)if(item.status==='rejected')
51
+ console.warn('CHAT_LOOP_SCOPED_RECONNECT_UNVERIFIED',
52
+ safeWorkerErrorCode(item.reason,'TASK_SCOPED_OWNER_UNVERIFIED'));
53
+ }
9
54
  async function reconnectOpenChats() {
55
+ // Native and Worker must both prove V1 may reconnect. A scoped Task gets
56
+ // only its own read-only Observer, never legacy Turn RESUME.
57
+ if(await hasActiveScopedTask())return reconnectScopedObservers();
58
+ await assertLegacyWorkerWritable({native:true});
10
59
  const tabs = await chrome.tabs.query({url: "https://chatgpt.com/*"});
11
60
  for (const tab of tabs) {
61
+ await assertLegacyWorkerWritable({native:true});
12
62
  if (!Number.isInteger(tab.id) || !pathOf(tab.url) && !/^https:\/\/chatgpt\.com\/$/.test(tab.url)) continue;
13
63
  try {
14
64
  await chrome.scripting.executeScript({target: {tabId: tab.id},
15
- files: ["content.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
65
+ files: ["content.js", "loop/core.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
16
66
  const owner = await readRun();
17
67
  if (owner?.phase === "WAITING_REPLY" && owner.tabId === tab.id
18
68
  && owner.page === pathOf(tab.url) && owner.newUserKey) {
@@ -28,6 +78,7 @@ async function reconnectOpenChats() {
28
78
  && proof.priorAssistantKey===owner.assistantKey
29
79
  && proof.priorAssistantUserKey===owner.userKey
30
80
  && proof.directReplyAfterPriorAssistant===true;
81
+ await assertLegacyWorkerWritable({native:true});
31
82
  const res = await chrome.tabs.sendMessage(tab.id, {
32
83
  type: "CHAT_LOOP_TURN_RESUME_V1", page: owner.page,
33
84
  userKey:freshUser?proof.userKey:owner.newUserKey,
@@ -53,13 +104,168 @@ async function ensureAlarm() {
53
104
  const existing = await chrome.alarms.get?.(ALARM_NAME).catch(() => null);
54
105
  if (!existing) await chrome.alarms.create(ALARM_NAME, {periodInMinutes: 1});
55
106
  }
107
+ async function retireScopedFinished(){
108
+ if(!scopedTaskRuns||!scopedTaskScheduler)return;
109
+ const state=await scopedTaskRuns.read(),now=Date.now();
110
+ const candidates=Object.values(state.items).filter(({run})=>
111
+ ['DONE','CANCELLED'].includes(run.phase)
112
+ &&!run.resourceTransfer
113
+ &&Number.isSafeInteger(run.terminalAt)
114
+ &&now-run.terminalAt>=24*60*60*1000);
115
+ const jobs=candidates.map(({run})=>scopedTaskScheduler.perTask(
116
+ run.projectId,run.taskId,async()=>{
117
+ const current=await scopedTaskRuns.get(run.projectId,run.taskId);
118
+ const exact=current.run;
119
+ if(!exact||exact.resourceTransfer||!['DONE','CANCELLED'].includes(exact.phase)
120
+ ||exact.sessionId!==run.sessionId
121
+ ||exact.generation!==run.generation
122
+ ||exact.nativeOwnerRevision!==run.nativeOwnerRevision
123
+ ||exact.terminalAt!==run.terminalAt
124
+ ||!await scopedEnsureTerminalQuota(exact))return;
125
+ const receipt=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
126
+ op:'task-retire-v2',projectId:run.projectId,
127
+ taskId:run.taskId,sessionId:run.sessionId,
128
+ generation:run.generation,
129
+ expectedSessionRevision:run.nativeOwnerRevision}).catch(()=>null);
130
+ if(receipt?.status!=='OK'
131
+ ||receipt.scope!=='TASK_SCOPED_RETIRED')return;
132
+ // A lost deletion ACK never reclaims another Task slot. Context
133
+ // remains the permanent history; Native already reverified terminal.
134
+ await scopedTaskRuns.retire(run.projectId,run.taskId,{
135
+ expectedRunRevision:current.runRevision,receipt});
136
+ }));
137
+ const outcomes=await Promise.allSettled(jobs);
138
+ for(const item of outcomes)if(item.status==='rejected')
139
+ console.warn('CHAT_LOOP_RETIRE_UNVERIFIED',
140
+ safeWorkerErrorCode(item.reason,'SCOPED_RETIRE_UNVERIFIED'));
141
+ }
142
+ async function observeScopedDueTasks(){
143
+ if(!scopedTaskScheduler||!scopedTaskRuns)return;
144
+ // This is the SAME one-minute Worker alarm. Per-Task queues may overlap
145
+ // read-only observations; no new timer, browser sender or Task writer.
146
+ const candidates=await scopedTaskScheduler.due();
147
+ for(const candidate of candidates){
148
+ const observation=scopedTaskScheduler.dispatchDue(candidate,async()=>{
149
+ if(candidate.phase==='PENDING'){
150
+ const state=await scopedTaskRuns.get(
151
+ candidate.projectId,candidate.taskId);
152
+ if(state.run?.handoffReceipt)
153
+ await scopedTaskReconcileHandoffPending(state.run);
154
+ else if(state.run?.continueReceipt)
155
+ await scopedTaskReconcileContinuePending(state.run);
156
+ return;
157
+ }
158
+ if(candidate.phase!=='WAITING_REPLY')return;
159
+ const state=await scopedTaskRuns.get(candidate.projectId,candidate.taskId);
160
+ const run=state.run;
161
+ if(!Number.isSafeInteger(run?.tabId)||run.tabId<=0
162
+ ||typeof run.page!=='string')return;
163
+ const tab=await chrome.tabs.get(run.tabId).catch(()=>null);
164
+ if(!tab||pathOf(tab.url)!==run.page||!scopedTaskOwnerResolver)return;
165
+ // A DONE marker may predate Context delivery. Retry only the SAME
166
+ // stored Turn's read-only proof on the existing alarm; this queues
167
+ // behind the present Task without waiting on its own queue.
168
+ if(['DONE','BLOCKED'].includes(run.lastObservedTurn?.outcome)
169
+ &&!run.modelIntent&&!run.nextAttempt){
170
+ const proof=run.lastObservedTurn;
171
+ void scopedTaskTerminalObserved({
172
+ page:proof.page,userKey:proof.userKey,
173
+ assistantKey:proof.assistantKey,outcome:proof.outcome
174
+ },{id:chrome.runtime.id,frameId:0,
175
+ tab:{id:tab.id},url:tab.url}).catch(error=>{
176
+ if(error?.code!=='SCOPED_DONE_DELIVERY_NOT_COMMITTED')
177
+ console.warn('TASK_SCOPED_TERMINAL_RETRY_UNVERIFIED',
178
+ safeWorkerErrorCode(error,'SCOPED_TERMINAL_UNVERIFIED'));
179
+ });
180
+ return;
181
+ }
182
+ // Even a read-only V2 timer must not inspect a stale or re-assigned
183
+ // Task Tab. The exact owner resolver reads Native and Context again;
184
+ // its result cannot become a Turn token or a send permit.
185
+ const route=await scopedTaskOwnerResolver.resolve({
186
+ id:chrome.runtime.id,frameId:0,tab:{id:tab.id},url:tab.url});
187
+ if(route.projectId!==candidate.projectId
188
+ ||route.taskId!==candidate.taskId
189
+ ||route.sessionId!==candidate.sessionId
190
+ ||route.generation!==candidate.generation
191
+ ||route.nativeOwnerRevision!==candidate.nativeOwnerRevision
192
+ ||route.runRevision!==candidate.runRevision)return;
193
+ // Observe a page fault before considering any queued Action.
194
+ // This is the existing read-only snapshot, not a fresh DOM poll.
195
+ const sample=await chrome.tabs.sendMessage(tab.id,{
196
+ type:'CHAT_LOOP_TURN_OBSERVE_V1'}).catch(()=>null);
197
+ if(sample?.page!==route.page
198
+ ||sample.contract!=='chat-loop.turn-observer.v1')return;
199
+ if(scopedReconcileObservedFault(run,tab,route,sample))return;
200
+ // Even an unrecognized visible failure never launches a queued sender.
201
+ if(sample.status==='BLOCKED')return;
202
+ // A tab created before a lost Chrome ACK is reconciled by its
203
+ // unique existing URL. Never create a second Action for LAUNCHING
204
+ // or ACTION_UNVERIFIED, and never infer a send from a tab alone.
205
+ if(['LAUNCHING','ACTION_UNVERIFIED'].includes(run.modelIntent?.state)
206
+ &&run.modelIntent.actionTabId===null){
207
+ await scopedRecoverLaunchedIntent(run.projectId,run.taskId);
208
+ return;
209
+ }
210
+ // The model may have queued an intent DURING the assistant Turn,
211
+ // while its eventual Observer ACK was lost. A stored exact completed
212
+ // Turn permits only a once-fenced original Action creation.
213
+ if(['QUEUED','CAPACITY_BLOCKED'].includes(run.modelIntent?.state)
214
+ &&run.modelIntent.targetUserKey===run.lastObservedTurn?.userKey
215
+ &&run.lastObservedTurn.pendingConfirmation===false){
216
+ if(run.modelIntent.action===run.lastObservedTurn.outcome)
217
+ await scopedLaunchReadyIntent(run.projectId,run.taskId);
218
+ else await scopedSettleMismatchedIntent(
219
+ run.projectId,run.taskId);
220
+ return;
221
+ }
222
+ // A Task whose *confirmed* send produced this precise User Turn
223
+ // cannot silently lose the subsequent assistant Turn on MV3 restart
224
+ // or a Native transfer race. Re-arm the existing observer only for
225
+ // the same ID; never infer a new sender, never retry a send.
226
+ const rearmUserKey=run.awaitingUserKey
227
+ ||(run.modelIntent?.state==='QUEUED'
228
+ ?run.modelIntent.targetUserKey:null);
229
+ if(rearmUserKey&&rearmUserKey===sample.userKey
230
+ &&['IDLE','UNKNOWN','TURN_FINISHED'].includes(sample.status)){
231
+ await chrome.tabs.sendMessage(tab.id,{
232
+ type:'CHAT_LOOP_TURN_RESUME_V1',page:run.page,
233
+ userKey:rearmUserKey,assistantKey:null,
234
+ startedAt:run.startedAt||Date.now()}).catch(()=>null);
235
+ }
236
+ // The sample and bounded re-arm are Observer-only. Context and
237
+ // the Chrome composer are not written by this Alarm.
238
+ });
239
+ observeBackground(observation,'TASK_SCOPED_READ_ONLY_POLL');
240
+ }
241
+ }
56
242
  async function watchActiveTurn() {
243
+ // Exactly the existing Worker alarm. Reconcile the original Resource
244
+ // Ledger with ALL retained Task receipts; no second scheduler or sender.
245
+ observeBackground(reconcileScopedResourceInventory(),
246
+ 'TASK_SCOPED_RESOURCE_RECONCILE');
247
+ // Archive terminal Task slots only after Native+Context prove finality.
248
+ observeBackground(retireScopedFinished(),'TASK_TERMINAL_RETIRE');
249
+ observeBackground(reconcileScopedAbortedHolds(),
250
+ 'TASK_PRE_SEND_HOLD_RECONCILE');
251
+ observeBackground(reconcileScopedHandoffResources(),
252
+ 'TASK_HANDOFF_RESOURCE_RECONCILE');
253
+ observeBackground(reconcileScopedCancelled(),
254
+ 'TASK_CANCEL_ACK_RECONCILE');
255
+ if(await hasActiveScopedTask()){
256
+ await observeScopedDueTasks();
257
+ return;
258
+ }
259
+ await assertLegacyWorkerWritable({native:true});
57
260
  // One bounded reconciliation on the existing 1-minute Worker alarm.
58
- await serial(async()=>{await expireStaleAction();
261
+ await serial(async()=>{await assertLegacyWorkerWritable();
262
+ await expireStaleAction();
59
263
  await resources.reconcile(await readRun()).catch(()=>{});});
60
264
  // Normal periodic wakeups also reconcile a delayed one-shot deadline.
61
265
  // All state changes share the same serial queue as Turn/Action receipts.
62
- await serial(async()=>{await expireStaleModelIntent();await prepareHandoffIfDue();});
266
+ await serial(async()=>{await assertLegacyWorkerWritable();
267
+ await expireStaleModelIntent();await prepareHandoffIfDue();});
268
+ await assertLegacyWorkerWritable();
63
269
  const run = await readRun();
64
270
  // While an Action is pending, never dispatch competing operations.
65
271
  if (run && ["RESERVED", "PENDING"].includes(run.phase)) return;
@@ -67,6 +273,7 @@ async function watchActiveTurn() {
67
273
  ? [await chrome.tabs.get(run.tabId).catch(() => null)]
68
274
  : await chrome.tabs.query({url: "https://chatgpt.com/*"});
69
275
  for (const tab of tabs) {
276
+ await assertLegacyWorkerWritable({native:true});
70
277
  if (!tab?.id || !pathOf(tab.url)) continue;
71
278
  try {
72
279
  const proof = await chrome.tabs.sendMessage(tab.id,
@@ -85,6 +292,7 @@ async function watchActiveTurn() {
85
292
  && (proof.status === "IDLE"
86
293
  || proof.status === "UNKNOWN"
87
294
  && ["ATTACHING_CHAT", "WAITING_CHAT_HYDRATION"].includes(proof.reason))) {
295
+ await assertLegacyWorkerWritable({native:true});
88
296
  await chrome.tabs.sendMessage(tab.id, {
89
297
  type: "CHAT_LOOP_TURN_RESUME_V1", page: run.page,
90
298
  userKey: freshHuman?proof.userKey:run.newUserKey,
@@ -96,18 +304,22 @@ async function watchActiveTurn() {
96
304
  // A human response can fail after the previous question was kept in
97
305
  // WAITING_REPLY. Do not let this become an indefinite silent wait.
98
306
  if(freshHuman && proof.status==="BLOCKED") {
99
- observeBackground(serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
100
- reason:proof.reason||"PAGE_ERROR"},
101
- {tab,url:tab.url})),'HUMAN_TURN_RECOVERY');
307
+ observeBackground(serial(async()=>{
308
+ await assertLegacyWorkerWritable({native:true});
309
+ return onTurnBlocked({page:run.page,userKey:proof.userKey,
310
+ reason:proof.reason||"PAGE_ERROR"},{tab,url:tab.url});
311
+ }),'HUMAN_TURN_RECOVERY');
102
312
  }
103
313
  // Alarm is still read-only. It may reconcile a verified page failure if
104
314
  // the observer's original notification was lost while Worker slept.
105
315
  if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
106
316
  && proof?.status === "BLOCKED" && ["PAGE_ERROR","CONTEXT_LIMIT","SECURITY_CHALLENGE"].includes(proof.reason)
107
317
  && proof.page === run.page && proof.userKey === run.newUserKey) {
108
- observeBackground(serial(() => onTurnBlocked({page: run.page,
109
- userKey: run.newUserKey, reason: proof.reason},
110
- {tab, url: tab.url})),'TURN_FAILURE_RECOVERY');
318
+ observeBackground(serial(async()=>{
319
+ await assertLegacyWorkerWritable({native:true});
320
+ return onTurnBlocked({page:run.page,
321
+ userKey:run.newUserKey,reason:proof.reason},{tab,url:tab.url});
322
+ }),'TURN_FAILURE_RECOVERY');
111
323
  }
112
324
  } catch { /* Observer unavailable; never infer Turn completion. */ }
113
325
  }
@@ -116,25 +328,37 @@ chrome.alarms?.onAlarm?.addListener(alarm => {
116
328
  if (alarm?.name === ALARM_NAME)
117
329
  observeBackground(watchActiveTurn(),'TURN_WATCH_ALARM');
118
330
  if (alarm?.name === DEADLINE_ALARM_NAME)
119
- observeBackground(serial(prepareHandoffIfDue),'HANDOFF_DEADLINE_ALARM');
331
+ observeBackground(serial(async()=>{
332
+ await assertLegacyWorkerWritable({native:true});
333
+ return prepareHandoffIfDue();
334
+ }),'HANDOFF_DEADLINE_ALARM');
120
335
  });
121
336
  chrome.runtime.onInstalled?.addListener(() => {
122
337
  observeBackground(ensureAlarm(),'ALARM_SETUP');
123
- observeBackground(serial(async()=>{await expireStaleAction();
338
+ observeBackground(serial(async()=>{
339
+ if(await hasActiveScopedTask())return observeScopedDueTasks();
340
+ await assertLegacyWorkerWritable({native:true});
341
+ await expireStaleAction();
124
342
  await resources.reconcile(await readRun()).catch(()=>{});}),
125
343
  'INSTALL_RECONCILIATION');
126
344
  observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
127
345
  });
128
346
  chrome.runtime.onStartup?.addListener(() => {
129
347
  observeBackground(ensureAlarm(),'ALARM_SETUP');
130
- observeBackground(serial(async()=>{await expireStaleAction();
348
+ observeBackground(serial(async()=>{
349
+ if(await hasActiveScopedTask())return observeScopedDueTasks();
350
+ await assertLegacyWorkerWritable({native:true});
351
+ await expireStaleAction();
131
352
  await resources.reconcile(await readRun()).catch(()=>{});}),
132
353
  'INSTALL_RECONCILIATION');
133
354
  observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
134
355
  });
135
356
  observeBackground(ensureAlarm(),'ALARM_SETUP');
136
357
  // Reconcile an elapsed deadline after MV3 Worker suspension/reload.
137
- observeBackground(serial(async()=>{await expireStaleAction();
358
+ observeBackground(serial(async()=>{
359
+ if(await hasActiveScopedTask())return observeScopedDueTasks();
360
+ await assertLegacyWorkerWritable({native:true});
361
+ await expireStaleAction();
138
362
  await resources.reconcile(await readRun()).catch(()=>{});
139
363
  await prepareHandoffIfDue();}),'STARTUP_RECONCILIATION');
140
364
  // A manual extension Reload does not necessarily fire onInstalled/onStartup.