@tomflow/chatloop-tools 0.9.64 → 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 (175) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +296 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  45. package/node_modules/@tomflow/chatloop-context/package.json +38 -0
  46. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  47. package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
  48. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
  49. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.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/session.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  126. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  127. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  128. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  129. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  130. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  131. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  132. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  133. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  134. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  135. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
  136. package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
  137. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
  138. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
  139. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
  140. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
  141. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  142. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
  143. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
  144. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  145. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  146. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  147. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  148. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  149. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  150. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  151. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  152. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  153. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  154. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
  155. package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
  156. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
  157. package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
  158. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  159. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  160. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  161. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  162. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  163. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
  164. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
  165. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
  166. package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
  167. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  168. package/node_modules/ps-list/index.d.ts +76 -0
  169. package/node_modules/ps-list/index.js +366 -0
  170. package/node_modules/ps-list/license +9 -0
  171. package/node_modules/ps-list/package.json +44 -0
  172. package/node_modules/ps-list/readme.md +56 -0
  173. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  174. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  175. package/package.json +12 -4
@@ -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 Adopt kickoff exception applies only to the verified pre-Adopt
82
+ // assistant reply. Remove it after this send; later 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,218 @@
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 || 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】这是已批准任务的首个受控执行轮次,不是新的需求或审批。先核实当前 Project/Task、Context 写权、R/P 精确有效版本、已批准的 Pn 工作项和未知副作用;按现行计划执行,不套用其他项目的旧任务、文档或测试报告。不要新建执行 Chat,不得重复 R/P 或重试未知副作用。所有必需工作与验收证据齐全后,按 Context SDK 正式完成 Task,并在终态门禁成立后才报 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
+ // Only the verified HANDOFF_NOT_SENT recovery may receive a write
206
+ // credential. Healthy continuation must not inherit engineering-specific
207
+ // failure instructions or unrelated historical Task details.
208
+ if(run.action==="CONTINUE" && typeof permit.text==="string" && recoveredContext){
209
+ permit.text += "\n\n【Chat Loop Context|HANDOFF_NOT_SENT 单次恢复写凭据】\n"
210
+ +JSON.stringify({projectId:run.projectId,taskId:run.taskId,
211
+ sessionId:run.sessionId,generation:run.generation||0,
212
+ ...recoveredContext})+"\n请先按原 Session 核实 Context 与未知副作用,"
213
+ +"此凭据仅用于当前任务 Context 写入;旧 Handoff 不得重新发送。";
214
+ }
215
+ if (modelTurnToken && typeof permit.text === "string")
216
+ permit.text += permit.modelTurnNote;
217
+ return permit;
218
+ }
@@ -0,0 +1,127 @@
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
+ // 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});
15
+ let opened;
16
+ try{opened=await chrome.tabs.create({url:chatUrl,active:true});}
17
+ catch{return {error:"ADOPTION_CHAT_OPEN_FAILED"};}
18
+ if(!Number.isSafeInteger(opened?.id))
19
+ return {error:"ADOPTION_CHAT_OPEN_UNVERIFIED"};
20
+ // Content scripts have document_idle timing. A bounded wait allows
21
+ // authentication/hydration; an error or CAPTCHA is NOT approval.
22
+ let ready=false;
23
+ for(let attempt=0;attempt<60;attempt++){
24
+ const current=await chrome.tabs.get(opened.id).catch(()=>null);
25
+ if(!current)return {error:"ADOPTION_CHAT_CLOSED"};
26
+ if(current.url && chatIdOf(current.url)!==requestedId){
27
+ if(current.url!=="about:blank"&&current.url!=="chrome://newtab/")
28
+ return {error:"ADOPTION_CHAT_REDIRECTED"};
29
+ }
30
+ const proof=await chrome.tabs.sendMessage(opened.id,
31
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
32
+ explicitChatId:requestedId,
33
+ ...(!requestedId&&taskId?{expectedTaskId:taskId}:{})}).catch(()=>null);
34
+ if(proof?.contract==="chat-loop.turn-observer.v1"
35
+ &&proof.status==="VERIFIED"
36
+ &&chatIdOf('https://chatgpt.com'+proof.page)===requestedId){
37
+ ready=true;break;
38
+ }
39
+ await new Promise(resolve=>setTimeout(resolve,500));
40
+ }
41
+ if(!ready)return {error:"ADOPTION_APPROVAL_NOT_FOUND"};
42
+ tabs=await chrome.tabs.query({url:"https://chatgpt.com/*"});
43
+ }
44
+ }
45
+ const matched=[];
46
+ for(const tab of tabs) {
47
+ const page=pathOf(tab.url);
48
+ if(!page||!Number.isSafeInteger(tab.id)
49
+ ||(requestedId && chatIdOf(tab.url)!==requestedId))continue;
50
+ // No chatUrl means the caller does not authorize opening any Chat.
51
+ // For the approved Task only, inspect each ALREADY OPEN tab by its own
52
+ // immutable Chat ID. An exact live Form A pair may be a candidate, but
53
+ // only the later Native Context permit proves its Task identity. Idle
54
+ // no-URL candidates still require Task-scoped issued user Turns.
55
+ const scopedId=requestedId||taskId&&chatIdOf(tab.url);
56
+ const proof=await chrome.tabs.sendMessage(tab.id,
57
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
58
+ ...(scopedId?{explicitChatId:scopedId}:{}),
59
+ ...(!requestedId&&taskId?{expectedTaskId:taskId}:{})}).catch(()=>null);
60
+ const evidence=policy.normalizeAdoptionEvidence(proof,{page});
61
+ if(!evidence)continue;
62
+ matched.push({tabId:tab.id,...evidence,
63
+ ...(!requestedId&&taskId?{explicitChatId:scopedId,expectedTaskId:taskId}:{})});
64
+ }
65
+ if(matched.length!==1)return {error:matched.length
66
+ ?"ADOPTION_APPROVAL_AMBIGUOUS":"ADOPTION_APPROVAL_NOT_FOUND"};
67
+ const target=matched[0];
68
+ await new Promise(resolve=>setTimeout(resolve,400));
69
+ const second=await chrome.tabs.sendMessage(target.tabId,
70
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
71
+ ...((requestedId||target.explicitChatId)
72
+ ?{explicitChatId:requestedId||target.explicitChatId}:{}),
73
+ ...(target.expectedTaskId?{expectedTaskId:target.expectedTaskId}:{})}).catch(()=>null);
74
+ const repeated=policy.normalizeAdoptionEvidence(second,{page:target.page});
75
+ if(!policy.sameAdoptionEvidence(target,repeated))
76
+ return {error:"ADOPTION_APPROVAL_CHANGED"};
77
+ return {target};
78
+ }
79
+ async function approvedRepairTarget(prior,intent){
80
+ // Repair is a new explicit USER request in the SAME exact Chat after the
81
+ // original Task's machine DONE, never a synthetic P approval or replacement.
82
+ if(!prior||prior.phase!=='DONE'||prior.projectId!==intent.projectId
83
+ ||prior.taskId!==intent.taskId||!prior.sessionId
84
+ ||!Number.isSafeInteger(prior.tabId)||!prior.page)
85
+ return {error:'REPAIR_PREVIOUS_DONE_MISSING'};
86
+ const tab=await chrome.tabs.get(prior.tabId).catch(()=>null);
87
+ if(!tab||pathOf(tab.url)!==prior.page
88
+ ||intent.chatUrl&&intent.chatUrl!=='https://chatgpt.com'+prior.page)
89
+ return {error:'REPAIR_OLD_CHAT_CHANGED'};
90
+ const durable=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
91
+ op:'session-read'}).catch(()=>null);
92
+ if(durable?.status!=='OK'||!durable.session
93
+ ||durable.session.phase!=='DONE'
94
+ ||durable.session.sessionId!==prior.sessionId
95
+ ||durable.session.projectId!==intent.projectId
96
+ ||durable.session.taskId!==intent.taskId
97
+ ||durable.session.activeChatId!==chatIdOf(tab.url)
98
+ ||durable.session.generation!==(prior.generation||0))
99
+ return {error:'REPAIR_DONE_OWNER_UNVERIFIED'};
100
+ const context=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
101
+ op:'context-control',command:'run.reopenStatus',args:{}}).catch(()=>null);
102
+ const reopen=context?.result;
103
+ if(context?.status!=='OK'||reopen?.stage!=='REOPENED'
104
+ ||reopen.taskRevision!==intent.contextTaskRevision
105
+ ||reopen.approvalRevision!==intent.contextApprovalRevision
106
+ ||typeof reopen.reopenUserTurn!=='string')
107
+ return {error:'REPAIR_CONTEXT_UNVERIFIED'};
108
+ const explicitChatId=chatIdOf(tab.url);
109
+ const observe=()=>chrome.tabs.sendMessage(prior.tabId,{
110
+ type:'CHAT_LOOP_REPAIR_EVIDENCE_V1',explicitChatId}).catch(()=>null);
111
+ const first=await observe();
112
+ await new Promise(resolve=>setTimeout(resolve,400));
113
+ const second=await observe();
114
+ const matching=proof=>proof?.contract==='chat-loop.turn-observer.v1'
115
+ &&proof.status==='VERIFIED'&&proof.page===prior.page
116
+ &&proof.priorDoneAssistantKey===prior.assistantKey
117
+ &&typeof proof.userKey==='string'
118
+ &&(reopen.reopenUserTurn===proof.userKey
119
+ ||reopen.reopenUserTurn===proof.userText);
120
+ if(!matching(first)||!matching(second)
121
+ ||first.userKey!==second.userKey
122
+ ||first.userText!==second.userText)
123
+ return {error:'REPAIR_USER_INTENT_UNVERIFIED'};
124
+ return {target:{tabId:prior.tabId,page:prior.page,
125
+ userKey:first.userKey,priorAssistantKey:prior.assistantKey,
126
+ repairUserText:first.userText,repairDoneAssistantKey:prior.assistantKey}};
127
+ }