@tomflow/chatloop-tools 0.9.16 → 0.9.17

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 (145) hide show
  1. package/index.mjs +4 -0
  2. package/lib/gateway.mjs +15 -3
  3. package/lib/mcp-tool-router.mjs +50 -3
  4. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  5. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  13. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  14. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  15. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  16. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  17. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  18. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  45. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  46. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  47. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  48. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  49. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  51. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  112. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  113. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  114. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  118. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  119. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  120. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  121. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  122. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  123. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  124. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  125. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  126. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  127. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  128. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  129. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  130. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  131. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  132. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  133. package/node_modules/ps-list/index.d.ts +76 -0
  134. package/node_modules/ps-list/index.js +366 -0
  135. package/node_modules/ps-list/license +9 -0
  136. package/node_modules/ps-list/package.json +44 -0
  137. package/node_modules/ps-list/readme.md +56 -0
  138. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  139. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  140. package/package.json +23 -8
  141. package/providers/form.mjs +68 -8
  142. package/scripts/build-form-app.mjs +27 -0
  143. package/ui/form/review-app.js +128 -0
  144. package/ui/form/review.html +859 -0
  145. package/ui/form/review.template.html +45 -0
@@ -0,0 +1,136 @@
1
+ // Chat Loop Worker — action-result. Imported in order by background.js; no independent Browser Owner.
2
+ // Durable pre-send evidence; once recorded a browser send may have happened.
3
+ // A later timeout is UNKNOWN, never equivalent to NOT_SENT.
4
+ async function onHandoffSendBegin(message,sender){
5
+ const run=await readRun();
6
+ if(!isAction(sender,message,run)||run?.action!=="HANDOFF"
7
+ ||run.phase!=="PENDING"||!run.contextHandoff
8
+ ||run.token!==message.token||run.tabId!==message.tabId)
9
+ return {status:"DENIED",code:"HANDOFF_SEND_SOURCE_INVALID"};
10
+ if(run.contextHandoff.sendBeginAt)
11
+ return {status:"DENIED",code:"HANDOFF_SEND_ALREADY_BEGUN"};
12
+ await saveRun({...run,contextHandoff:{...run.contextHandoff,sendBeginAt:Date.now()}});
13
+ return {status:"RECORDED"};
14
+ }
15
+ async function onResult(message, sender) {
16
+ const run = await readRun();
17
+ if (!isAction(sender, message, run)) return {status: "DENIED", code: "ACTION_SOURCE_INVALID"};
18
+ if (run?.phase !== "PENDING" || run.token !== message.token)
19
+ return {status: "DENIED", code: "ACTION_NOT_PENDING"};
20
+ // Native Retry does not submit another user message. One-time click is
21
+ // confirmed separately and re-arms the already-owned pending user Turn.
22
+ if (run.retryMode === "NATIVE") {
23
+ const tab = await chrome.tabs.get(run.tabId).catch(() => null);
24
+ const confirmedRetry = message.result === "RETRY_CLICKED" && tab
25
+ && pathOf(tab.url) === run.page && run.retryCount === 1;
26
+ const nextRetry = {...run, phase: confirmedRetry ? "WAITING_REPLY" : "BLOCKED",
27
+ reason: confirmedRetry ? "" : "RETRY_UNVERIFIED"};
28
+ delete nextRetry.retryMode;
29
+ await saveRun(nextRetry);
30
+ if (confirmedRetry) {
31
+ const reset = await chrome.tabs.sendMessage(run.tabId,
32
+ {type: "CHAT_LOOP_TURN_RETRY_MONITOR_V1", page: run.page,
33
+ userKey: run.newUserKey}).catch(() => null);
34
+ if (reset?.status !== "REARMED") {
35
+ await saveRun({...nextRetry, phase: "BLOCKED", reason: "RETRY_OBSERVER_UNVERIFIED"});
36
+ return {status: "BLOCKED", code: "RETRY_OBSERVER_UNVERIFIED"};
37
+ }
38
+ }
39
+ return {status: confirmedRetry ? "OK" : "BLOCKED"};
40
+ }
41
+ let confirmed = message.result === "SENT_CONFIRMED"
42
+ && typeof message.newUserKey === "string"
43
+ && /^user:[^\s]{8,}$/.test(message.newUserKey)
44
+ && message.newUserKey !== run.userKey;
45
+ const failure = typeof message.reason === "string" && /^[A-Z0-9_]{4,100}$/.test(message.reason)
46
+ ? message.reason : "SEND_UNVERIFIED";
47
+ let next = {...run, phase: "BLOCKED", reason: failure};
48
+ // Diagnostic only: retain the possibly-created target without granting ownership.
49
+ if (run.action === "HANDOFF" && Number.isInteger(message.newTabId))
50
+ next.attemptedNewTabId = message.newTabId;
51
+ if (confirmed && run.action === "HANDOFF") {
52
+ const newTab = Number.isInteger(message.newTabId)
53
+ ? await chrome.tabs.get(message.newTabId).catch(() => null) : null;
54
+ confirmed = Boolean(newTab && message.newTabId !== run.tabId
55
+ && pathOf(newTab.url) && pathOf(newTab.url) === message.newPage);
56
+ if (confirmed) {
57
+ // Transfer the single loop owner. The old Chat remains open for audit.
58
+ next = {...run, action: "HANDOFF", sourceTabId: run.tabId,
59
+ sourcePage: run.page, tabId: newTab.id, page: message.newPage,
60
+ // Keep source identities as the already-processed baseline; the new
61
+ // user's first reply must not be suppressed by duplicate detection.
62
+ newUserKey: message.newUserKey, phase: "WAITING_REPLY", reason: "",
63
+ ...(run.sessionId?{generation:(run.generation||0)+1}:{}),
64
+ // The new Chat has no previous assistant message. Never authenticate
65
+ // its first Retry/Error Handoff using the OLD Chat's assistant ID.
66
+ userKey: null, assistantKey: null, startedAt: Date.now(),
67
+ errorHandoffCount: run.handoffMode === "ERROR" ? (run.errorHandoffCount || 0) + 1 : 0,
68
+ };
69
+ delete next.handoffText;
70
+ delete next.errorReason;
71
+ delete next.handoffPending;
72
+ delete next.handoffPendingAt;
73
+ delete next.deadlineAt;
74
+ }
75
+ } else if (confirmed) {
76
+ next = {...run, phase: "WAITING_REPLY", reason: "",
77
+ newUserKey: message.newUserKey};
78
+ }
79
+ // A model prompt is one-shot. Keep only a short receipt, not the prompt
80
+ // body, after the Action has reached a confirmed or blocked terminal state.
81
+ // The kickoff exception applies to ONE historical P3 reply only.
82
+ // Remove it after this send attempt; subsequent Continue Turns must carry
83
+ // ordinary independent terminal markers and never inherit the exception.
84
+ if(run.recoveryMode==="ADOPT_KICKOFF")delete next.recoveryMode;
85
+ if(run.modelIntent){
86
+ const override=run.action==="HANDOFF"&&run.modelIntent.action==="CONTINUE";
87
+ const finalStatus=confirmed?"SENT_CONFIRMED":"BLOCKED";
88
+ next=updateModelReceipt(next,run.modelIntent.id,{
89
+ status:finalStatus,actualAction:run.action,
90
+ reason:override?"OVERRIDDEN_BY_DEADLINE":confirmed?null:failure,
91
+ checkpointForwarded:confirmed&&override});
92
+ // The bounded modelReceipts entry above is the unique final intent record.
93
+ delete next.modelIntent;
94
+ }
95
+ if (!confirmed) delete next.modelTurnToken;
96
+ if(confirmed&&run.recoveryMode==="HANDOFF_NOT_SENT"){
97
+ for(const key of ["contextRecoveryCredential","contextRecoveryBound",
98
+ "contextHandoff","recoveryMode","contextSourceMarker",
99
+ "recoveryExpectedNativeAt","recoverySourceAssistantKey",
100
+ "recoveryProtocol","recoveryAttempts","contextRecoveryAttempted"])
101
+ delete next[key];
102
+ }
103
+ if(!confirmed && run.action==="HANDOFF" && run.contextHandoff){
104
+ const notSent=!run.contextHandoff.sendBeginAt;
105
+ next={...next,reason:notSent?"CONTEXT_HANDOFF_NOT_SENT":"CONTEXT_HANDOFF_SEND_UNKNOWN",
106
+ contextHandoff:{...run.contextHandoff,
107
+ sendOutcome:notSent?"NOT_SENT":"SEND_UNKNOWN",
108
+ // This is derived ONLY after original Action Result is received.
109
+ terminalActionResultAt:Date.now()}};
110
+ }
111
+ await saveRun(next);
112
+ if(confirmed && run.action==="HANDOFF" && run.contextHandoff){
113
+ const h=run.contextHandoff;
114
+ const bound=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
115
+ op:"context-control",command:"run.bind.handoff",
116
+ args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:h.attemptId+":bind",
117
+ expectedTaskRevision:h.taskRevision,expectedBindingRevision:h.bindingRevision,
118
+ attemptId:h.attemptId,checkpointId:h.checkpointId,
119
+ targetGeneration:h.targetGeneration,runCredential:h.nextRunCredential}
120
+ }).catch(()=>null);
121
+ if(bound?.status!=="OK"||bound.result?.status!=="BOUND"){
122
+ const failed={...next,phase:"BLOCKED",reason:"CONTEXT_NEW_OWNER_BIND_UNVERIFIED"};
123
+ // Retain the exact original attempt and pending credential in private
124
+ // Worker storage for receipt-only diagnosis. Never re-send the message.
125
+ await saveRun(failed);
126
+ return {status:"BLOCKED",code:bound?.code||"CONTEXT_NEW_OWNER_BIND_UNVERIFIED"};
127
+ }
128
+ const clean={...next,contextManaged:{storeEpoch:h.storeEpoch}};
129
+ delete clean.contextHandoff;
130
+ await saveRun(clean); // secret has already been delivered in the unique first message
131
+ }
132
+ if(confirmed && run.action==="HANDOFF" && Number.isInteger(message.newTabId))
133
+ await resources.confirmChat(message.newTabId,next.sessionId||next.token,
134
+ "https://chatgpt.com"+message.newPage).catch(()=>{});
135
+ return {status: confirmed ? "OK" : "BLOCKED"};
136
+ }
@@ -0,0 +1,220 @@
1
+ // Chat Loop Worker — action-take. Imported in order by background.js; no independent Browser Owner.
2
+ async function onTake(message, sender) {
3
+ const run = await readRun();
4
+ if (!isAction(sender, message, run)) return {status: "DENIED", code: "ACTION_SOURCE_INVALID"};
5
+ if (run?.phase !== "RESERVED" || run.token !== message.token
6
+ || run.tabId !== message.tabId) return {status: "DENIED", code: "ACTION_NOT_RESERVED"};
7
+ const tab = await chrome.tabs.get(run.tabId).catch(() => null);
8
+ if (!tab || pathOf(tab.url) !== run.page) {
9
+ await saveRun({...run, phase: "BLOCKED", reason: "CHAT_TARGET_CHANGED"});
10
+ return {status: "DENIED", code: "CHAT_TARGET_CHANGED"};
11
+ }
12
+ if (run.retryMode!=="NATIVE" && run.handoffMode!=="ERROR") {
13
+ const pending=await currentConfirmation(run.tabId,run.page,
14
+ run.userKey,run.assistantKey);
15
+ if(pending===true) {
16
+ // A widget appeared after the scheduler decided to Continue.
17
+ // Cancel this Action without a send; the same owner observes a fresh
18
+ // user reply through the existing Turn observer.
19
+ const held=settleModelIntent({...run,phase:"WAITING_REPLY",
20
+ newUserKey:run.userKey,reason:"PENDING_CONFIRMATION_DOM"},
21
+ "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
22
+ await saveRun(held);
23
+ return {status:"DENIED",code:"PENDING_CONFIRMATION_DOM"};
24
+ }
25
+ if(pending===null) {
26
+ await saveRun({...run,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
27
+ return {status:"DENIED",code:"CONFIRMATION_DOM_UNVERIFIED"};
28
+ }
29
+ }
30
+ let projectContext=null;
31
+ if(run.action==='HANDOFF'&&run.sessionId){
32
+ const durable=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
33
+ const projection=sessionProjection(run);
34
+ if(durable?.status!=='OK'
35
+ ||!matchesNativeProjection(projection,durable.session)
36
+ ||durable.contextStatus==='UNVERIFIED'
37
+ ||durable.projectContext&&durable.projectContext.projectId!==run.projectId){
38
+ await saveRun({...run,phase:'BLOCKED',reason:'HANDOFF_CONTEXT_UNVERIFIED'});
39
+ return {status:'DENIED',code:'HANDOFF_CONTEXT_UNVERIFIED'};
40
+ }
41
+ projectContext=durable.projectContext||null;
42
+ }
43
+ // Bind a model-control capability to the next *user* Turn, not to a tab or to another Chat.
44
+ // Acceptance fixtures retain their existing prompts; native Retry keeps its original Turn token.
45
+ const modelTurnToken = run.retryMode === "NATIVE"
46
+ ? run.modelTurnToken || null : crypto.randomUUID();
47
+ let recoveredContext=null;
48
+ if(run.action==="CONTINUE" && run.recoveryMode==="HANDOFF_NOT_SENT"){
49
+ const h=run.contextHandoff;
50
+ if(!run.contextRecoveryCredential || !h || h.sendOutcome!=="NOT_SENT"
51
+ ||h.sendBeginAt ||h.attemptId===run.token){
52
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_NOT_SENT_PROOF_INVALID"});
53
+ return {status:"DENIED",code:"CONTEXT_NOT_SENT_PROOF_INVALID"};
54
+ }
55
+ const snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
56
+ op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
57
+ const cp=snapshot?.result;
58
+ if(snapshot?.status!=="OK" || cp.taskRevision!==h.taskRevision
59
+ ||cp.bindingRevision!==h.bindingRevision ||cp.runRef!==null
60
+ ||cp.checkpointId!==h.checkpointId ||cp.unknownEffectCount!==0){
61
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_SNAPSHOT_UNVERIFIED"});
62
+ return {status:"DENIED",code:"CONTEXT_RESTORE_SNAPSHOT_UNVERIFIED"};
63
+ }
64
+ const approval=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
65
+ op:"context-control",command:"permit.consume",
66
+ args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:run.token+":permit",
67
+ actionToken:run.token,kind:"CONTINUE",expectedTaskRevision:h.taskRevision,
68
+ expectedApprovalRevision:cp.approvalRevision}
69
+ }).catch(()=>null);
70
+ if(approval?.status!=="OK"||approval.result?.status!=="PERMITTED"){
71
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_PERMIT_UNVERIFIED"});
72
+ return {status:"DENIED",code:"CONTEXT_RESTORE_PERMIT_UNVERIFIED"};
73
+ }
74
+ const restored=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
75
+ op:"context-control",command:"run.restore-same-owner",
76
+ args:{expectedStoreEpoch:h.storeEpoch,writeRequestId:run.token+":restore",
77
+ expectedTaskRevision:h.taskRevision,expectedBindingRevision:h.bindingRevision,
78
+ attemptId:h.attemptId,checkpointId:h.checkpointId,
79
+ recoveryCredential:run.contextRecoveryCredential,
80
+ recoveryActionToken:run.token,sendState:"NOT_SENT"}
81
+ }).catch(()=>null);
82
+ if(restored?.status!=="OK"||restored.result?.status!=="RESTORED_SAME_OWNER"){
83
+ await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_BIND_UNVERIFIED"});
84
+ return {status:"DENIED",code:"CONTEXT_RESTORE_BIND_UNVERIFIED"};
85
+ }
86
+ recoveredContext={runRef:restored.result.runRef,
87
+ runCredential:run.contextRecoveryCredential,storeEpoch:h.storeEpoch,
88
+ bindingRevision:restored.result.bindingRevision,taskRevision:h.taskRevision};
89
+ }
90
+ const pending={...run, phase: "PENDING", modelTurnToken,
91
+ ...(recoveredContext?{contextRecoveryBound:recoveredContext}:{})};
92
+ await saveRun(run.modelIntent ? updateModelReceipt(pending,run.modelIntent.id,{
93
+ status:run.action==="HANDOFF"&&run.modelIntent.action==="CONTINUE"
94
+ ?"OVERRIDDEN_BY_DEADLINE":"PENDING"}) : pending);
95
+ if(run.action==="CONTINUE" &&run.contextManaged &&!recoveredContext &&run.retryMode!=="NATIVE"){
96
+ let snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
97
+ op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
98
+ // First controlled Continue may precede the FIRST business checkpoint.
99
+ // Only a proven CHECKPOINT_NOT_FOUND may use the current live task/run
100
+ // projection. Network errors and all other snapshot failures stay BLOCKED.
101
+ if(snapshot?.status!=="OK"&&snapshot?.code==="CHECKPOINT_NOT_FOUND")
102
+ snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
103
+ op:"context-control",command:"run.terminalStatus",args:{}}).catch(()=>null);
104
+ const cp=snapshot?.result;
105
+ if(snapshot?.status!=="OK"||!cp ||cp.runRef!==
106
+ run.sessionId+":"+run.taskId+":"+(run.generation||0)
107
+ ||!Number.isSafeInteger(cp.taskRevision)||cp.taskRevision<1
108
+ ||!Number.isSafeInteger(cp.approvalRevision)||cp.approvalRevision<1
109
+ ||cp.unknownEffectCount!==0||cp.executionOutcome==="DONE"){
110
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CONTINUE_SNAPSHOT_UNVERIFIED"});
111
+ return {status:"DENIED",code:"CONTEXT_CONTINUE_SNAPSHOT_UNVERIFIED"};
112
+ }
113
+ const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
114
+ op:"context-control",command:"permit.consume",
115
+ args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
116
+ writeRequestId:run.token+":permit",expectedTaskRevision:cp.taskRevision,
117
+ expectedApprovalRevision:cp.approvalRevision,
118
+ actionToken:run.token,kind:"CONTINUE"}
119
+ }).catch(()=>null);
120
+ if(allowed?.status!=="OK"||allowed.result?.status!=="PERMITTED"){
121
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CONTINUE_PERMIT_UNVERIFIED"});
122
+ return {status:"DENIED",code:"CONTEXT_CONTINUE_PERMIT_UNVERIFIED"};
123
+ }
124
+ }
125
+ let managedHandoff=null;
126
+ if(run.action==="HANDOFF"&&run.contextManaged){
127
+ if(!run.taskId||!run.sessionId){
128
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_TASK_IDENTITY_MISSING"});
129
+ return {status:"DENIED",code:"CONTEXT_TASK_IDENTITY_MISSING"};
130
+ }
131
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
132
+ op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
133
+ const cp=proof?.result;
134
+ if(proof?.status!=="OK"||!cp?.checkpointCurrent||cp.unknownEffectCount!==0
135
+ ||cp.runRef!==run.sessionId+":"+run.taskId+":"+(run.generation||0)){
136
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_CHECKPOINT_UNVERIFIED"});
137
+ return {status:"DENIED",code:"CONTEXT_CHECKPOINT_UNVERIFIED"};
138
+ }
139
+ const permitProof=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
140
+ op:"context-control",command:"permit.consume",
141
+ args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
142
+ writeRequestId:run.token+":permit",actionToken:run.token,kind:"HANDOFF",
143
+ expectedTaskRevision:cp.taskRevision,
144
+ expectedApprovalRevision:cp.approvalRevision}
145
+ }).catch(()=>null);
146
+ if(permitProof?.status!=="OK"||permitProof.result?.status!=="PERMITTED"){
147
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_HANDOFF_PERMIT_UNVERIFIED"});
148
+ return {status:"DENIED",code:"CONTEXT_HANDOFF_PERMIT_UNVERIFIED"};
149
+ }
150
+ const nextRunCredential=Array.from(crypto.getRandomValues(new Uint8Array(32)),
151
+ x=>x.toString(16).padStart(2,"0")).join("");
152
+ const targetGeneration=(run.generation||0)+1;
153
+ const nextRunRef=run.sessionId+":"+run.taskId+":"+targetGeneration;
154
+ const fenced=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
155
+ op:"context-control",command:"run.fence",
156
+ args:{expectedStoreEpoch:run.contextManaged.storeEpoch,
157
+ writeRequestId:run.token+":fence",expectedTaskRevision:cp.taskRevision,
158
+ expectedBindingRevision:cp.bindingRevision,checkpointId:cp.checkpointId,
159
+ attemptId:run.token,actionToken:run.token,targetGeneration,
160
+ nextRunRef,nextRunCredential}
161
+ }).catch(()=>null);
162
+ if(fenced?.status!=="OK"||fenced.result?.status!=="FENCED"){
163
+ await saveRun({...pending,phase:"BLOCKED",reason:"CONTEXT_HANDOFF_FENCE_UNVERIFIED"});
164
+ return {status:"DENIED",code:"CONTEXT_HANDOFF_FENCE_UNVERIFIED"};
165
+ }
166
+ managedHandoff={attemptId:run.token,checkpointId:cp.checkpointId,
167
+ taskRevision:cp.taskRevision,bindingRevision:fenced.result.bindingRevision,
168
+ targetGeneration,nextRunRef,nextRunCredential,
169
+ storeEpoch:run.contextManaged.storeEpoch};
170
+ await saveRun({...pending,contextHandoff:managedHandoff});
171
+ }
172
+ const permit = {status: "OK", action: run.action || "CONTINUE",
173
+ modelTurnToken,
174
+ modelTurnNote: modelTurnToken ? turnToolNote(modelTurnToken) : "",
175
+ handoffMode: run.handoffMode || null, retryMode: run.retryMode || null,
176
+ ...(projectContext?{projectContext}:{}),
177
+ ...(managedHandoff?{contextHandoff:{...managedHandoff,
178
+ projectId:run.projectId,taskId:run.taskId,sessionId:run.sessionId}}:{}),
179
+ target: {tabId: run.tabId, page: run.page,
180
+ ...(run.sessionId?{sessionId:run.sessionId,projectId:run.projectId,
181
+ ...(run.taskId?{taskId:run.taskId}:{}),generation:run.generation||0}:{}),
182
+ recoveryMode:run.recoveryMode||null,
183
+ ...(run.contextSourceMarker?{contextSourceMarker:run.contextSourceMarker}:{}),
184
+ assistantKey: run.assistantKey,
185
+ userKey: run.retryMode === "NATIVE" || run.handoffMode === "ERROR"
186
+ ? run.newUserKey : run.userKey,
187
+ },
188
+ modelIntent: run.action==="HANDOFF" && run.modelIntent?.action==="HANDOFF"
189
+ ? {id:run.modelIntent.id,reason:run.modelIntent.reason||""} : null,
190
+ pendingPlan: run.action==="HANDOFF" && run.modelIntent?.action==="CONTINUE"
191
+ ? {id:run.modelIntent.id,nextPrompt:run.modelIntent.nextPrompt} : null,
192
+ text: run.action === "HANDOFF" ? run.handoffText || null
193
+ : run.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
194
+ ? "【Chat Loop 同 Chat 受控恢复】上一轮以 BLOCKED 结束;当前恢复已通过唯一 Owner、原 Chat 和 Native 身份核验,但不代表工程问题已自动解决。不要再次调用 Start、不要新建 Chat、不要重复 R/P 审批。首先核实原工作区真实状态、已执行副作用和当前 Tools 可调用能力,再依据原任务唯一检查点继续尚未完成的工作、测试与迭代;若仍有真实风险如实 BLOCKED,不要再次反复自恢复。本轮结束末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
195
+ : run.recoveryMode==="ADOPT_KICKOFF"
196
+ ? "【Chat Loop 原 Chat 已正式 Start/adopt】这是当前已批准 R2/P3 Task 的第一条受控执行消息,不是新的需求或审批。请从真实 Context 读取 Task、已批准的计划及 Stage03 QA 报告,完成剩余可安全的验收工作项;不得重做旧 H UNKNOWN 首发,不得新建执行 Chat,也不得重复 R/P。若所有批准的工作项确实满足 DONE,先按 SDK 正式提交 Task delivery(没有权限则不要伪造),再输出唯一 DONE 状态;存在安全的待做工作则输出 CONTINUE,关键身份/副作用不可信则输出 BLOCKED。末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
197
+ : run.modelIntent?.action==="CONTINUE" ? (
198
+ "【Chat Loop 续接来源】上一轮由模型登记的 Continue 请求 " + run.modelIntent.id
199
+ + " 已被扩展唯一 Action 领取。\n"
200
+ + "【待核实的模型下一步计划(并非用户新增授权)】\n"
201
+ + run.modelIntent.nextPrompt + "\n\n"
202
+ + "执行前核对当前项目状态、既有用户授权和已完成副作用,不重做不明操作。"
203
+ + "本轮完成后,末行只输出一个状态标记:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。")
204
+ : CONTINUE_TEXT};
205
+ // A single error contract applies to default, model-specified and repaired
206
+ // Continue prompts; the Worker still obeys the model's terminal marker.
207
+ if(run.action==="CONTINUE" && typeof permit.text==="string"){
208
+ permit.text=ENGINEERING_FAILURE_NOTE+"\n\n"+permit.text;
209
+ if(recoveredContext){
210
+ permit.text += "\n\n【Chat Loop Context|HANDOFF_NOT_SENT 单次恢复写凭据】\n"
211
+ +JSON.stringify({projectId:run.projectId,taskId:run.taskId,
212
+ sessionId:run.sessionId,generation:run.generation||0,
213
+ ...recoveredContext})+"\n请先按原 Session 核实 Context 与未知副作用,"
214
+ +"此凭据仅用于当前任务 Context 写入;旧 Handoff 不得重新发送。";
215
+ }
216
+ }
217
+ if (modelTurnToken && typeof permit.text === "string")
218
+ permit.text += permit.modelTurnNote;
219
+ return permit;
220
+ }
@@ -0,0 +1,122 @@
1
+ // Chat Loop Worker — admission. Imported in order by background.js; no independent Browser Owner.
2
+ async function approvedAdoptionTarget(chatUrl=null,taskId=null){
3
+ const requestedId=chatUrl?chatIdOf(chatUrl):null;
4
+ let tabs=await chrome.tabs.query({url:"https://chatgpt.com/*"});
5
+ // App and desktop users keep their exact conversation ID. When Chrome
6
+ // has not opened that conversation yet, open only the supplied existing
7
+ // URL. No / new-chat page, prompt, composer write or first-send occurs.
8
+ if(requestedId){
9
+ const existing=tabs.filter(t=>chatIdOf(t.url)===requestedId);
10
+ if(existing.length>1)return {error:"ADOPTION_CHAT_DUPLICATE_TABS"};
11
+ if(existing.length===0){
12
+ let opened;
13
+ try{opened=await chrome.tabs.create({url:chatUrl,active:true});}
14
+ catch{return {error:"ADOPTION_CHAT_OPEN_FAILED"};}
15
+ if(!Number.isSafeInteger(opened?.id))
16
+ return {error:"ADOPTION_CHAT_OPEN_UNVERIFIED"};
17
+ // Content scripts have document_idle timing. A bounded wait allows
18
+ // authentication/hydration; an error or CAPTCHA is NOT approval.
19
+ let ready=false;
20
+ for(let attempt=0;attempt<60;attempt++){
21
+ const current=await chrome.tabs.get(opened.id).catch(()=>null);
22
+ if(!current)return {error:"ADOPTION_CHAT_CLOSED"};
23
+ if(current.url && chatIdOf(current.url)!==requestedId){
24
+ if(current.url!=="about:blank"&&current.url!=="chrome://newtab/")
25
+ return {error:"ADOPTION_CHAT_REDIRECTED"};
26
+ }
27
+ const proof=await chrome.tabs.sendMessage(opened.id,
28
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
29
+ explicitChatId:requestedId,
30
+ ...(taskId?{expectedTaskId:taskId}:{})}).catch(()=>null);
31
+ if(proof?.contract==="chat-loop.turn-observer.v1"
32
+ &&proof.status==="VERIFIED"
33
+ &&chatIdOf('https://chatgpt.com'+proof.page)===requestedId){
34
+ ready=true;break;
35
+ }
36
+ await new Promise(resolve=>setTimeout(resolve,500));
37
+ }
38
+ if(!ready)return {error:"ADOPTION_APPROVAL_NOT_FOUND"};
39
+ tabs=await chrome.tabs.query({url:"https://chatgpt.com/*"});
40
+ }
41
+ }
42
+ const matched=[];
43
+ for(const tab of tabs) {
44
+ const page=pathOf(tab.url);
45
+ if(!page||!Number.isSafeInteger(tab.id)
46
+ ||(requestedId && chatIdOf(tab.url)!==requestedId))continue;
47
+ // No chatUrl means the caller does not authorize opening any Chat.
48
+ // For the approved Task only, inspect each ALREADY OPEN tab by its own
49
+ // immutable Chat ID and require exact native R/P issue-scoped user Turns.
50
+ const scopedId=requestedId||taskId&&chatIdOf(tab.url);
51
+ const proof=await chrome.tabs.sendMessage(tab.id,
52
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
53
+ ...(scopedId?{explicitChatId:scopedId}:{}),
54
+ ...(!requestedId&&taskId?{expectedTaskId:taskId}:{})}).catch(()=>null);
55
+ const evidence=policy.normalizeAdoptionEvidence(proof,{page});
56
+ if(!evidence)continue;
57
+ matched.push({tabId:tab.id,...evidence,
58
+ ...(!requestedId&&taskId?{explicitChatId:scopedId,expectedTaskId:taskId}:{})});
59
+ }
60
+ if(matched.length!==1)return {error:matched.length
61
+ ?"ADOPTION_APPROVAL_AMBIGUOUS":"ADOPTION_APPROVAL_NOT_FOUND"};
62
+ const target=matched[0];
63
+ await new Promise(resolve=>setTimeout(resolve,400));
64
+ const second=await chrome.tabs.sendMessage(target.tabId,
65
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
66
+ ...((requestedId||target.explicitChatId)
67
+ ?{explicitChatId:requestedId||target.explicitChatId}:{}),
68
+ ...(target.expectedTaskId?{expectedTaskId:target.expectedTaskId}:{})}).catch(()=>null);
69
+ const repeated=policy.normalizeAdoptionEvidence(second,{page:target.page});
70
+ if(!policy.sameAdoptionEvidence(target,repeated))
71
+ return {error:"ADOPTION_APPROVAL_CHANGED"};
72
+ return {target};
73
+ }
74
+ async function approvedRepairTarget(prior,intent){
75
+ // Repair is a new explicit USER request in the SAME exact Chat after the
76
+ // original Task's machine DONE, never a synthetic P approval or replacement.
77
+ if(!prior||prior.phase!=='DONE'||prior.projectId!==intent.projectId
78
+ ||prior.taskId!==intent.taskId||!prior.sessionId
79
+ ||!Number.isSafeInteger(prior.tabId)||!prior.page)
80
+ return {error:'REPAIR_PREVIOUS_DONE_MISSING'};
81
+ const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
82
+ if(!tab||pathOf(tab.url)!==prior.page
83
+ ||intent.chatUrl&&intent.chatUrl!=='https://chatgpt.com'+prior.page)
84
+ return {error:'REPAIR_OLD_CHAT_CHANGED'};
85
+ const durable=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
86
+ op:'session-read'}).catch(()=>null);
87
+ if(durable?.status!=='OK'||!durable.session
88
+ ||durable.session.phase!=='DONE'
89
+ ||durable.session.sessionId!==prior.sessionId
90
+ ||durable.session.projectId!==intent.projectId
91
+ ||durable.session.taskId!==intent.taskId
92
+ ||durable.session.activeChatId!==chatIdOf(tab.url)
93
+ ||durable.session.generation!==(prior.generation||0))
94
+ return {error:'REPAIR_DONE_OWNER_UNVERIFIED'};
95
+ const context=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
96
+ op:'context-control',command:'run.reopenStatus',args:{}}).catch(()=>null);
97
+ const reopen=context?.result;
98
+ if(context?.status!=='OK'||reopen?.stage!=='REOPENED'
99
+ ||reopen.taskRevision!==intent.contextTaskRevision
100
+ ||reopen.approvalRevision!==intent.contextApprovalRevision
101
+ ||typeof reopen.reopenUserTurn!=='string')
102
+ return {error:'REPAIR_CONTEXT_UNVERIFIED'};
103
+ const explicitChatId=chatIdOf(tab.url);
104
+ const observe=()=>chrome.tabs.sendMessage(prior.tabId,{
105
+ type:'CHAT_LOOP_REPAIR_EVIDENCE_V1',explicitChatId}).catch(()=>null);
106
+ const first=await observe();
107
+ await new Promise(resolve=>setTimeout(resolve,400));
108
+ const second=await observe();
109
+ const matching=proof=>proof?.contract==='chat-loop.turn-observer.v1'
110
+ &&proof.status==='VERIFIED'&&proof.page===prior.page
111
+ &&proof.priorDoneAssistantKey===prior.assistantKey
112
+ &&typeof proof.userKey==='string'
113
+ &&(reopen.reopenUserTurn===proof.userKey
114
+ ||reopen.reopenUserTurn===proof.userText);
115
+ if(!matching(first)||!matching(second)
116
+ ||first.userKey!==second.userKey
117
+ ||first.userText!==second.userText)
118
+ return {error:'REPAIR_USER_INTENT_UNVERIFIED'};
119
+ return {target:{tabId:prior.tabId,page:prior.page,
120
+ userKey:first.userKey,priorAssistantKey:prior.assistantKey,
121
+ repairUserText:first.userText,repairDoneAssistantKey:prior.assistantKey}};
122
+ }
@@ -0,0 +1,155 @@
1
+ // Chat Loop Worker — adopt-prepare. Imported in order by background.js; no independent Browser Owner.
2
+ async function sessionStartPrepare(message,sender){
3
+ if(!sessionPage(sender,'start',message.requestId))
4
+ return {status:'DENIED',code:'INVALID_START_SOURCE'};
5
+ const prior=await readRun();
6
+ // Read the single authenticated intent BEFORE deciding whether a previously
7
+ // BLOCKED session can be explicitly superseded. Never infer consent from
8
+ // a failed page or an old session pointer alone.
9
+ const proof=await chrome.runtime.sendNativeMessage(SESSION_HOST,
10
+ {op:'acquire',id:message.requestId,action:'start'}).catch(()=>null);
11
+ const intent=proof?.intent;
12
+ if(proof?.status!=='OK'||intent?.confirmed!==true
13
+ ||typeof intent.projectId!=='string'
14
+ ||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.projectId)
15
+ ||(intent.taskId!==undefined
16
+ && !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.taskId))
17
+ ||(intent.purpose!==undefined
18
+ &&(intent.purpose!=='REPAIR_SAME_SCOPE'||intent.mode!=='adopt'
19
+ ||!intent.taskId||!intent.contextLeaseRef))
20
+ ||(['contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision']
21
+ .some(k=>Object.hasOwn(intent,k))
22
+ &&(!intent.taskId||typeof intent.contextLeaseRef!=='string'
23
+ ||intent.contextLeaseRef.length<8||typeof intent.contextStoreEpoch!=='string'
24
+ ||intent.contextStoreEpoch.length<10
25
+ ||!Number.isSafeInteger(intent.contextTaskRevision)||intent.contextTaskRevision<1
26
+ ||!Number.isSafeInteger(intent.contextApprovalRevision)||intent.contextApprovalRevision<1))
27
+ ||(intent.chatUrl!==undefined
28
+ && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'
29
+ ||!pathOf(intent.chatUrl)
30
+ ||intent.chatUrl!=='https://chatgpt.com'+pathOf(intent.chatUrl)))
31
+ ||(intent.mode==='adopt' ? Object.hasOwn(intent,'prompt')
32
+ : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000)
33
+ ||(intent.mode!==undefined && intent.mode!=='adopt')
34
+ ||(intent.replaceBlockedSessionId!==undefined
35
+ && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId)))
36
+ return {status:'DENIED',code:'START_INTENT_UNVERIFIED'};
37
+ // Native DONE is required before the private terminal fence IPC, but
38
+ // DONE without CONFIRMED fencing must never release Start admission.
39
+ if(prior?.contextManaged && prior.taskId
40
+ && (prior.contextTerminalFence==='UNVERIFIED'
41
+ || prior.phase==='DONE'&&!terminalFenceVerified(prior)))
42
+ return {status:'DENIED',code:'CONTEXT_TERMINAL_FENCE_UNVERIFIED'};
43
+ const replace=intent.replaceBlockedSessionId||null;
44
+ const matchingBlocked=prior?.phase==='BLOCKED' && prior.sessionId===replace
45
+ && prior.projectId!==intent.projectId;
46
+ if(replace&&!matchingBlocked)return {status:'DENIED',code:'BLOCKED_REPLACEMENT_MISMATCH'};
47
+ if(prior&&prior.phase!=='DONE'&&!matchingBlocked)
48
+ return {status:'DENIED',code:'LOOP_ALREADY_ACTIVE'};
49
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
50
+ if(disk?.status!=='OK')return {status:'DENIED',code:'SESSION_STATE_UNVERIFIED'};
51
+ if(matchingBlocked&&(!disk.session||disk.session.phase!=='BLOCKED'
52
+ ||disk.session.sessionId!==replace||disk.session.projectId!==prior.projectId))
53
+ return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
54
+ // An abandoned Managed Context writer can outlive its Browser Owner.
55
+ // Replacing the Native session without first verifying its terminal fence
56
+ // would strand a live runRef (and an old write credential) in the Store.
57
+ // Never make that replacement based solely on BLOCKED or absent Owner.
58
+ if(matchingBlocked&&prior.contextManaged){
59
+ const terminal=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
60
+ op:'context-control',command:'run.terminalStatus',args:{}}).catch(()=>null);
61
+ const state=terminal?.result;
62
+ if(terminal?.status!=='OK'||!state
63
+ ||state.projectId!==prior.projectId||state.taskId!==prior.taskId
64
+ ||state.runRef!==null||state.executionOutcome!=='DONE'
65
+ ||typeof state.deliveryRef!=='string'||!state.deliveryRef)
66
+ return {status:'DENIED',code:'CONTEXT_BLOCKED_RUN_UNFENCED'};
67
+ }
68
+ if(disk.session&&disk.session.phase!=='DONE'&&!matchingBlocked)
69
+ return {status:'DENIED',code:'SESSION_ALREADY_ACTIVE'};
70
+ const capacity=await resources.admit(prior,{kind:intent.mode==='adopt'?'action':'chat'});
71
+ if(!capacity.ok)return {status:'DENIED',code:capacity.code};
72
+ const adoption=intent.mode==='adopt'
73
+ ?intent.purpose==='REPAIR_SAME_SCOPE'
74
+ ?await approvedRepairTarget(prior,intent)
75
+ :await approvedAdoptionTarget(intent.chatUrl||null,
76
+ intent.contextLeaseRef?intent.taskId:null):null;
77
+ if(adoption?.error)return {status:'DENIED',code:adoption.error};
78
+ // A Project-scoped Chat cannot safely hand off to the ordinary home route:
79
+ // reject BEFORE claiming Owner instead of failing after four hours.
80
+ // Explicit /g/ intent remains Project-scoped even if Chrome aliases the
81
+ // same conversation under /c/<id>.
82
+ if(intent.mode==='adopt'&&(
83
+ pathOf(intent.chatUrl||'').startsWith('/g/')
84
+ ||adoption?.target?.page?.startsWith('/g/')))
85
+ return {status:'DENIED',code:'AUTO_HANDOFF_ROUTE_UNSUPPORTED'};
86
+ // The same blocked task may never be replayed implicitly: a replacement
87
+ // requires a new project ID and leaves the old Chat intact for audit.
88
+ const promptDigest=adoption?null:await startPromptFingerprint(intent.prompt);
89
+ const next={sessionId:crypto.randomUUID(),projectId:intent.projectId,
90
+ ...(intent.taskId?{taskId:intent.taskId}:{}),
91
+ ...(intent.purpose?{purpose:intent.purpose}:{}),
92
+ ...(intent.contextLeaseRef?{contextLeaseRef:intent.contextLeaseRef,
93
+ contextStoreEpoch:intent.contextStoreEpoch,
94
+ contextTaskRevision:intent.contextTaskRevision,
95
+ contextApprovalRevision:intent.contextApprovalRevision,
96
+ contextInitialCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
97
+ x=>x.toString(16).padStart(2,'0')).join('')}:{}),
98
+ generation:0,phase:'STARTING',action:'START',token:crypto.randomUUID(),
99
+ page:'/',tabId:null,startedAt:Date.now(),
100
+ machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
101
+ ...(matchingBlocked?{replacedBlockedSessionId:replace}:{}),
102
+ ...(adoption?{mode:'adopt',adoptTabId:adoption.target.tabId,
103
+ adoptPage:adoption.target.page,adoptUserKey:adoption.target.userKey,
104
+ ...((intent.chatUrl||adoption.target.explicitChatId)
105
+ ?{adoptExplicitChatId:chatIdOf(intent.chatUrl)||adoption.target.explicitChatId}:{}),
106
+ ...(adoption.target.expectedTaskId
107
+ ?{adoptExpectedTaskId:adoption.target.expectedTaskId}:{}),
108
+ adoptPriorAssistantKey:adoption.target.priorAssistantKey,
109
+ adoptPostApprovalAssistantKey:adoption.target.postApprovalAssistantKey||null,
110
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'?{}:{
111
+ adoptRVersion:adoption.target.rVersion,
112
+ adoptPVersion:adoption.target.pVersion}),
113
+ ...(intent.purpose==='REPAIR_SAME_SCOPE'
114
+ ?{repairUserText:adoption.target.repairUserText,
115
+ repairDoneAssistantKey:adoption.target.repairDoneAssistantKey}:{})}
116
+ :{startPrompt:intent.prompt,...(promptDigest?{startPromptDigest:promptDigest}:{})})};
117
+ await saveRun(next); // Reserve BEFORE any new Chrome tab or send.
118
+ return {status:'PREPARED',token:next.token,sessionId:next.sessionId,
119
+ ...(next.taskId?{taskId:next.taskId}:{})};
120
+ }
121
+ async function sessionStartTake(message,sender){
122
+ const run=await readRun();
123
+ if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
124
+ ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
125
+ ||run.phase!=='STARTING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
126
+ await saveRun({...run,phase:'PENDING'});
127
+ // Native validates current durable Session and signs the narrow Context IPC.
128
+ // No Context adapter? Legacy Start behavior remains unchanged.
129
+ if(run.contextLeaseRef){
130
+ const allowed=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
131
+ op:'context-control',command:'permit.consume',
132
+ args:{expectedStoreEpoch:run.contextStoreEpoch,writeRequestId:run.token,
133
+ expectedTaskRevision:run.contextTaskRevision,
134
+ expectedApprovalRevision:run.contextApprovalRevision,
135
+ actionToken:run.token,kind:'START',leaseRef:run.contextLeaseRef}
136
+ }).catch(()=>null);
137
+ if(allowed?.status!=='OK'||allowed.result?.status!=='PERMITTED'){
138
+ await saveRun({...run,phase:'BLOCKED',reason:'CONTEXT_START_PERMIT_UNVERIFIED'});
139
+ return {status:'DENIED',code:allowed?.code||'CONTEXT_START_PERMIT_UNVERIFIED'};
140
+ }
141
+ }
142
+ return {status:'OK',sessionId:run.sessionId,
143
+ ...(run.taskId?{taskId:run.taskId}:{}),
144
+ ...(run.mode==='adopt'?{mode:'adopt',tabId:run.adoptTabId,
145
+ page:run.adoptPage,userKey:run.adoptUserKey,
146
+ ...(run.adoptExplicitChatId?{explicitChatId:run.adoptExplicitChatId}:{}),
147
+ ...(run.adoptExpectedTaskId?{expectedTaskId:run.adoptExpectedTaskId}:{}),
148
+ priorAssistantKey:run.adoptPriorAssistantKey,
149
+ postApprovalAssistantKey:run.adoptPostApprovalAssistantKey||null,
150
+ ...(run.purpose==='REPAIR_SAME_SCOPE'
151
+ ?{purpose:'REPAIR_SAME_SCOPE',repairUserText:run.repairUserText,
152
+ priorDoneAssistantKey:run.repairDoneAssistantKey}
153
+ :{rVersion:run.adoptRVersion,pVersion:run.adoptPVersion})}
154
+ :{prompt:run.startPrompt})};
155
+ }