@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,390 @@
1
+ // Sole writer for one autonomous continuation. Never imported by the Chat page.
2
+ // The background schedules an Action page; this page alone performs the DOM mutation.
3
+ const statusNode = document.getElementById("status");
4
+ const detailsNode = document.getElementById("details");
5
+ const actionErrorCode=(error,fallback='SEND_ERROR')=>{
6
+ const code=error?.code||error?.message;
7
+ return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
8
+ ?code:fallback;
9
+ };
10
+ function show(status, details) {
11
+ statusNode.textContent = status;
12
+ detailsNode.textContent = details;
13
+ document.body.dataset.result = status === "SUCCESS" ? "success" : "error";
14
+ }
15
+ async function sendOnce(target, text) {
16
+ const [execution] = await chrome.scripting.executeScript({
17
+ target: {tabId: target.tabId},
18
+ func: async (expected, instruction) => {
19
+ try {
20
+ if (location.origin !== "https://chatgpt.com" || location.pathname !== expected.page)
21
+ throw Error("CHAT_PAGE_CHANGED");
22
+ const visible = node => Boolean(node?.getClientRects?.().length)
23
+ && !node.closest?.('[hidden],[aria-hidden="true"]')
24
+ && getComputedStyle(node).display !== "none";
25
+ const mains = [...document.querySelectorAll("main")].filter(visible);
26
+ if (mains.length !== 1) throw Error("CHAT_MAIN_UNVERIFIED");
27
+ const main = mains[0];
28
+ const modern = [...main.querySelectorAll(
29
+ '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
30
+ const legacy = [...main.querySelectorAll(
31
+ '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
32
+ const roles = legacy.length ? legacy : modern;
33
+ const role = node => node.getAttribute("data-message-author-role")
34
+ || node.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
35
+ const idOf = node => node?.getAttribute("data-message-id")
36
+ || node?.getAttribute("data-chatgpt-search-message-ids")?.trim().split(/\s+/)[0]
37
+ || node?.closest('[data-testid^="conversation-turn-"]')?.getAttribute("data-testid");
38
+ const user = roles.filter(node => role(node) === "user").at(-1);
39
+ const answer = roles.filter(node => role(node) === "assistant").at(-1);
40
+ if ("user:" + idOf(user) !== expected.userKey
41
+ || "assistant:" + idOf(answer) !== expected.assistantKey)
42
+ throw Error("TURN_IDENTITY_CHANGED");
43
+ const scope = answer.closest('[data-testid^="conversation-turn-"]')
44
+ || answer.closest('[data-talvt-turn-state]') || answer;
45
+ const replyText = (answer.querySelector('.markdown')?.innerText || answer.innerText || '').trim();
46
+ const lines = replyText.split(/\r?\n/);
47
+ const expectedMarker=expected.recoveryMode==="ADOPT_KICKOFF"
48
+ ? null : expected.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
49
+ ? "[CHAT_LOOP_STATUS:BLOCKED]" : expected.recoveryMode==="HANDOFF_NOT_SENT"
50
+ ? expected.contextSourceMarker : "[CHAT_LOOP_STATUS:CONTINUE]";
51
+ if ((expectedMarker===null
52
+ ? lines.some(line=>/^\[CHAT_LOOP_STATUS:(?:CONTINUE|DONE|BLOCKED|HANDOFF)\]$/.test(line.trim()))
53
+ : lines.at(-1)?.trim() !== expectedMarker
54
+ ||lines.filter(line=>/^\[CHAT_LOOP_STATUS:(?:CONTINUE|DONE|BLOCKED|HANDOFF)\]$/.test(line.trim())).length !== 1)) {
55
+ throw Error("CONTINUE_STATUS_CHANGED");
56
+ }
57
+ const turnState = scope.getAttribute?.('data-talvt-turn-state');
58
+ if (turnState && turnState !== "complete") throw Error("TURN_NOT_COMPLETE");
59
+ if ([...document.querySelectorAll('button[data-testid="stop-button"],button[aria-label="停止响应"],button[aria-label="Stop generating"]')].some(visible))
60
+ throw Error("GENERATION_STILL_RUNNING");
61
+ if (![...scope.querySelectorAll('button[aria-label="复制"],button[aria-label="Copy"],button[data-testid="copy-turn-action-button"]')].some(visible))
62
+ throw Error("FINAL_UI_EVIDENCE_MISSING");
63
+ let input = document.querySelector('[contenteditable="true"][data-composer-markdown]')
64
+ || document.querySelector('#prompt-textarea[contenteditable="true"]')
65
+ || document.querySelector('[data-testid="composer-input"][contenteditable="true"]');
66
+ if (!visible(input) || input.closest('[aria-disabled="true"]'))
67
+ throw Error("COMPOSER_UNAVAILABLE");
68
+ if ((input.innerText || input.textContent || '').trim())
69
+ throw Error("COMPOSER_NOT_EMPTY");
70
+ input.focus();
71
+ if (!document.execCommand("insertText", false, instruction)) throw Error("INPUT_NOT_ACCEPTED");
72
+ // DOM writes can precede React composer state. Do not click a stale
73
+ // enabled button in the same task as insertion (especially after reset).
74
+ await new Promise(resolve => setTimeout(resolve, 400));
75
+ const canonical = value => String(value || '').replace(/\s+/g, '');
76
+ let verified = false;
77
+ for (let n = 0; n < 30; n++) {
78
+ if (canonical(input.innerText) === canonical(instruction)
79
+ || canonical(input.textContent) === canonical(instruction)) {verified = true; break;}
80
+ await new Promise(resolve => setTimeout(resolve, 120));
81
+ }
82
+ if (!verified) throw Error("INPUT_NOT_VERIFIED");
83
+ let button;
84
+ for (let n = 0; n < 16; n++) {
85
+ button = document.querySelector('button[type="submit"][aria-label="发送"]')
86
+ || document.querySelector('button[data-testid="send-button"]')
87
+ || document.querySelector('button[data-testid="composer-send-button"]')
88
+ || document.querySelector('button[aria-label="Send message"]');
89
+ if (button && !button.disabled && visible(button)) break;
90
+ await new Promise(resolve => setTimeout(resolve, 120));
91
+ }
92
+ if (!button || button.disabled || !visible(button)) throw Error("SEND_BUTTON_UNAVAILABLE");
93
+ // Final same-page DOM guard. The Worker checked before Action Take; a
94
+ // confirmation may appear while React settles the composer. Reuse
95
+ // Observer's existing read-only detection, no new action or state.
96
+ const gate = globalThis.ChatLoopTurnObserverV1?.poll?.();
97
+ if (gate?.contract !== "chat-loop.turn-observer.v1"
98
+ || gate.page !== expected.page
99
+ || gate.userKey !== expected.userKey
100
+ || gate.assistantKey !== expected.assistantKey
101
+ || gate.reason === "WAITING_CHAT_HYDRATION"
102
+ || typeof gate.pendingConfirmation !== "boolean")
103
+ throw Error("CONFIRMATION_OBSERVER_UNVERIFIED");
104
+ if (gate.pendingConfirmation) throw Error("CONFIRMATION_PENDING_DOM");
105
+ if (location.pathname !== expected.page) throw Error("CHAT_PAGE_CHANGED_BEFORE_SEND");
106
+ if (canonical(input.innerText) !== canonical(instruction)
107
+ && canonical(input.textContent) !== canonical(instruction)) throw Error("INPUT_CHANGED_BEFORE_SEND");
108
+ // Snapshot the visible message identities before the ONE irreversible
109
+ // click. A matching latest bubble is not enough if the UI exposes TWO
110
+ // newly created user Turns for this one send.
111
+ const beforeUserIds = new Set(roles.filter(node => role(node) === "user")
112
+ .map(idOf).filter(Boolean));
113
+ button.click(); // Once, after durable PENDING commit in the worker. Never retry.
114
+ let candidateId = null, candidateStableAt = 0;
115
+ for (let n = 0; n < 32; n++) {
116
+ if (location.pathname !== expected.page) throw Error("CHAT_PAGE_CHANGED_AFTER_SEND");
117
+ const visibleMain = [...document.querySelectorAll("main")].filter(visible);
118
+ if (visibleMain.length !== 1) throw Error("CHAT_MAIN_CHANGED_AFTER_SEND");
119
+ const currentLegacy = [...visibleMain[0].querySelectorAll(
120
+ '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
121
+ const rows = currentLegacy.length ? currentLegacy
122
+ : [...visibleMain[0].querySelectorAll(
123
+ '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
124
+ const users = rows.filter(node => role(node) === "user");
125
+ const latest = users.at(-1), newId = idOf(latest);
126
+ const newIds = [...new Set(users.map(idOf)
127
+ .filter(id => id && !beforeUserIds.has(id)))];
128
+ if (newIds.length > 1) throw Error("DUPLICATE_USER_TURN_UNVERIFIED");
129
+ if (newId && 'user:' + newId !== expected.userKey) {
130
+ // On live ChatGPT the collapsed bubble has a "显示更多"
131
+ // button; only the actual message text qualifies as a receipt.
132
+ const message = latest?.querySelector('[data-search-result-target]')
133
+ || latest?.querySelector('[data-user-message-bubble="true"]') || latest;
134
+ if (newIds.length !== 1 || newIds[0] !== newId
135
+ || (canonical(message?.innerText) !== canonical(instruction)
136
+ && canonical(message?.textContent) !== canonical(instruction)))
137
+ throw Error("NEW_USER_TURN_UNVERIFIED");
138
+ if (candidateId !== newId) {
139
+ candidateId = newId;
140
+ candidateStableAt = Date.now();
141
+ }
142
+ // Recheck the DOM for a short stable window; one immediate new
143
+ // bubble does not prove that no duplicate followed the click.
144
+ if (Date.now() - candidateStableAt >= 750)
145
+ return {status: "SENT_CONFIRMED", newUserKey: 'user:' + newId,
146
+ newPage: location.pathname};
147
+ }
148
+ await new Promise(resolve => setTimeout(resolve, 250));
149
+ }
150
+ throw Error("SEND_UNVERIFIED"); // Side effect may exist: block, don't retry.
151
+ } catch (error) {
152
+ const code=error?.code||error?.message;
153
+ return {status:"UNVERIFIED",reason:
154
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:"SEND_ERROR"};
155
+ }
156
+ },
157
+ args: [target, text]
158
+ });
159
+ if (!execution?.result || execution.result.status !== "SENT_CONFIRMED")
160
+ throw Error(execution?.result?.reason || "SEND_RESULT_UNVERIFIED");
161
+ return execution.result;
162
+ }
163
+ // Reuse the formal Continue Action page for a *different* one-shot recovery
164
+ // operation. Native Retry targets the existing user Turn: never type or send.
165
+ async function retryNativeOnce(target) {
166
+ const [execution] = await chrome.scripting.executeScript({
167
+ target: {tabId: target.tabId},
168
+ func: async expected => {
169
+ try {
170
+ if (location.origin !== "https://chatgpt.com" || location.pathname !== expected.page)
171
+ throw Error("RETRY_CHAT_CHANGED");
172
+ const visible = node => Boolean(node?.getClientRects?.().length)
173
+ && !node.closest?.('[hidden],[aria-hidden="true"]')
174
+ && getComputedStyle(node).display !== "none";
175
+ const mains = [...document.querySelectorAll('main')].filter(visible);
176
+ if (mains.length !== 1) throw Error("RETRY_MAIN_UNVERIFIED");
177
+ const main = mains[0];
178
+ const rows = [...main.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
179
+ const messages = rows.length ? rows : [...main.querySelectorAll('[data-message-author-role]')];
180
+ const role = node => node.getAttribute('data-message-author-role')
181
+ || node.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
182
+ const id = node => node?.getAttribute('data-message-id')
183
+ || node?.getAttribute('data-chatgpt-search-message-ids')?.trim().split(/\s+/)[0]
184
+ || node?.closest('[data-testid^="conversation-turn-"]')?.getAttribute('data-testid');
185
+ const latestUser = messages.filter(node => role(node) === 'user').at(-1);
186
+ const latestAssistant = messages.filter(node => role(node) === 'assistant').at(-1);
187
+ if ('user:' + id(latestUser) !== expected.userKey
188
+ || (latestAssistant ? 'assistant:' + id(latestAssistant) : null) !== expected.assistantKey)
189
+ throw Error("RETRY_TURN_CHANGED");
190
+ if ([...document.querySelectorAll('button[data-testid="stop-button"],button[aria-label="停止响应"],button[aria-label="Stop generating"]')].some(visible))
191
+ throw Error("RETRY_STILL_GENERATING");
192
+ const alerts = [...main.querySelectorAll('[role="alert"],[role="status"],[data-testid="conversation-error"]')]
193
+ .filter(visible);
194
+ const failed = alerts.filter(el => /unknown error|something went wrong|an error occurred|unable to load|connection (?:lost|interrupted)|请求失败|网络错误|发生错误|出错了/i.test(el.innerText || el.textContent || ''));
195
+ if (failed.length !== 1) throw Error("RETRY_ERROR_NOT_UNIQUE");
196
+ const buttons = [...failed[0].querySelectorAll('button')].filter(button => visible(button)
197
+ && /^(?:retry|try again|重试|再试一次)$/i.test(
198
+ (button.innerText || button.textContent || button.getAttribute('aria-label') || '').trim()));
199
+ if (buttons.length !== 1 || buttons[0].disabled) throw Error("RETRY_BUTTON_UNVERIFIED");
200
+ buttons[0].click(); // Exact native retry on the existing user Turn, once.
201
+ // Require visible evidence that the page accepted the native retry,
202
+ // not merely that the click function returned without throwing.
203
+ for (let attempt = 0; attempt < 24; attempt++) {
204
+ await new Promise(resolve => setTimeout(resolve, 250));
205
+ if (location.pathname !== expected.page) throw Error("RETRY_PAGE_CHANGED_AFTER_CLICK");
206
+ const current = [...document.querySelectorAll('main')].filter(visible);
207
+ if (current.length !== 1) throw Error("RETRY_MAIN_CHANGED_AFTER_CLICK");
208
+ const latest = [...current[0].querySelectorAll('[role="alert"],[role="status"],[data-testid="conversation-error"]')]
209
+ .filter(visible).some(el => /unknown error|something went wrong|an error occurred|unable to load|connection (?:lost|interrupted)|请求失败|网络错误|发生错误|出错了/i.test(el.innerText || el.textContent || ''));
210
+ if (!latest) return {status: 'RETRY_CLICKED'};
211
+ }
212
+ throw Error("NATIVE_RETRY_NOT_ACKNOWLEDGED");
213
+ } catch(error) {
214
+ const code=error?.code||error?.message;
215
+ return {status:'UNVERIFIED',reason:
216
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'RETRY_FAILED'};
217
+ }
218
+ }, args: [target]
219
+ });
220
+ return execution?.result || {status:'UNVERIFIED',reason:'RETRY_RESULT_UNKNOWN'};
221
+ }
222
+ // Recovery-only UI reveal. A Worker+Native CAS check must grant the exact
223
+ // terminal Owner before this Action can move its viewport. No message is sent.
224
+ async function revealLatestOwnerTurn(tabId, expectedPage) {
225
+ const [execution]=await chrome.scripting.executeScript({
226
+ target:{tabId},
227
+ func: page => {
228
+ if(location.origin!=='https://chatgpt.com'||location.pathname!==page)
229
+ return 'CHAT_PAGE_CHANGED';
230
+ const marks=[...document.querySelectorAll('main [data-chatgpt-search-unit-key]')];
231
+ let ancestor=marks.at(-1);
232
+ if(!ancestor)return 'NO_VISIBLE_TURN';
233
+ while(ancestor){
234
+ const style=getComputedStyle(ancestor);
235
+ if(/^(auto|scroll)$/.test(style.overflowY)
236
+ &&ancestor.scrollHeight-ancestor.clientHeight>24){
237
+ ancestor.scrollTop=ancestor.scrollHeight;
238
+ return 'SCROLLED';
239
+ }
240
+ ancestor=ancestor.parentElement;
241
+ }
242
+ return 'CHAT_SCROLL_CONTAINER_UNVERIFIED';
243
+ },args:[expectedPage]
244
+ });
245
+ if(execution?.result!=='SCROLLED')
246
+ throw Error(execution?.result||'CHAT_SCROLL_UNVERIFIED');
247
+ }
248
+ async function runScopedContinue() {
249
+ const own=await chrome.tabs.getCurrent();
250
+ const params=new URLSearchParams(location.search);
251
+ const raw=params.get('tabId'),token=params.get('token');
252
+ if(!own?.id||own.url!==location.href
253
+ ||params.size!==3||params.get('taskFirst')!=='1'
254
+ ||!/^[1-9][0-9]*$/.test(raw||'')
255
+ ||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(token||''))
256
+ throw Error('SCOPED_ACTION_PARAMETERS_INVALID');
257
+ const request={tabId:Number(raw),token};
258
+ const reply=type=>chrome.runtime.sendMessage({type,...request});
259
+ // A newly created Action page can race with the single Worker's durable
260
+ // Action tab registration. Retries below are read-only pre-permit source
261
+ // checks; a consumed Context permit is NEVER retried.
262
+ let permit=null;
263
+ for(let i=0;i<12;i++){
264
+ permit=await reply('CHAT_LOOP_TASK_ACTION_TAKE_V2').catch(()=>null);
265
+ if(permit?.code!=='SCOPED_ACTION_REGISTRATION_PENDING')break;
266
+ await new Promise(resolve=>setTimeout(resolve,180));
267
+ }
268
+ if(permit?.status!=='OK'||permit.scope!=='TASK_SCOPED_ACTION_TAKEN'
269
+ ||permit.target?.tabId!==request.tabId
270
+ ||typeof permit.text!=='string'||!permit.text.trim())
271
+ throw Error(permit?.code||'SCOPED_ACTION_PERMIT_UNVERIFIED');
272
+ const started=await reply('CHAT_LOOP_TASK_SEND_BEGIN_V2').catch(()=>null);
273
+ if(started?.status!=='RECORDED'
274
+ ||started.scope!=='TASK_SCOPED_SEND_BEGIN')
275
+ throw Error(started?.code||'SCOPED_SEND_BEGIN_UNKNOWN');
276
+ show('RUNNING','当前 Task 已获得唯一发送许可,核对原 Chat 后执行一次发送。');
277
+ let result;
278
+ try{result=await sendOnce(permit.target,permit.text);}
279
+ catch(error){result={status:'UNVERIFIED',reason:actionErrorCode(error)};}
280
+ // SEND_BEGIN already exists: even an uncertain DOM send is terminal for
281
+ // this attempt until independent original-request evidence is reviewed.
282
+ const done=await chrome.runtime.sendMessage({
283
+ type:'CHAT_LOOP_TASK_ACTION_RESULT_V2',...request,
284
+ result:result.status,newUserKey:result.newUserKey||null,
285
+ newPage:result.newPage||null}).catch(()=>null);
286
+ if(result.status!=='SENT_CONFIRMED'
287
+ ||done?.status!=='OK'
288
+ ||done.scope!=='TASK_SCOPED_CONTINUE_CONFIRMED')
289
+ throw Error(done?.code||result.reason||'SCOPED_SEND_RECEIPT_UNKNOWN');
290
+ show('SUCCESS','当前 Task 原 Chat 已确认发送一次,等待自己的下一轮回复。');
291
+ await chrome.tabs.remove(own.id).catch(()=>{});
292
+ }
293
+ async function run() {
294
+ const params = new URLSearchParams(location.search);
295
+ if(params.has('taskFirst'))return runScopedContinue();
296
+ const raw = params.get("tabId") || "";
297
+ let token = params.get("token") || "";
298
+ let tabId = Number(raw);
299
+ if ([...params.keys()].some(k => k !== "tabId" && k !== "token" && k !== "repairLegacyReservation" && k !== "resumeBlockedAt" && k !== "recoverContextNotSentAt" && k !== "adoptBaselineAt" && k !== "adoptKickoffAt")
300
+ || [...params.keys()].length !== new Set(params.keys()).size)
301
+ throw Error("ACTION_PARAMETERS_INVALID");
302
+ if (raw && !/^[1-9][0-9]*$/.test(raw)
303
+ || token && !/^[0-9a-f-]{36}$/.test(token)
304
+ || token && (!raw||params.has("repairLegacyReservation")||params.has("resumeBlockedAt")
305
+ ||params.has("recoverContextNotSentAt"))) throw Error("ACTION_PARAMETERS_INVALID");
306
+ const own = await chrome.tabs.getCurrent();
307
+ if (!own?.id || own.url !== location.href) throw Error("ACTION_TAB_UNVERIFIED");
308
+ if(params.has("adoptBaselineAt")){
309
+ const rawAt=params.get("adoptBaselineAt"),at=Number(rawAt);
310
+ if(params.size!==2||!raw||token||!/^[1-9][0-9]{12}$/.test(rawAt||"")
311
+ ||!Number.isSafeInteger(at))
312
+ throw Error("ADOPT_BASELINE_PARAMETERS_INVALID");
313
+ show("VERIFYING","对同一原 Chat 的历史审批回复进行只读复核;绝不发送消息。");
314
+ const result=await chrome.runtime.sendMessage({
315
+ type:"CHAT_LOOP_ADOPT_BASELINE_REPAIR_V1",
316
+ tabId,nativeUpdatedAt:at});
317
+ if(result?.status!=="REPAIRED")
318
+ throw Error(result?.code||"ADOPT_BASELINE_REPAIR_UNVERIFIED");
319
+ show("SUCCESS","已对原 Chat 完成历史基线恢复;未创建 Chat、未发送消息。");
320
+ await chrome.tabs.remove(own.id);
321
+ return;
322
+ }
323
+ if(params.has("adoptKickoffAt")){
324
+ const rawAt=params.get("adoptKickoffAt"),at=Number(rawAt);
325
+ if(params.size!==2||!raw||token||!/^[1-9][0-9]{12}$/.test(rawAt||"")
326
+ ||!Number.isSafeInteger(at))
327
+ throw Error("ADOPT_KICKOFF_PARAMETERS_INVALID");
328
+ show("VERIFYING","核查当前 Managed Task、已批准 R/P 和原 Chat 的历史回复,再申请唯一首轮执行许可。");
329
+ const prepared=await chrome.runtime.sendMessage({
330
+ type:"CHAT_LOOP_ADOPT_KICKOFF_PREPARE_V1",tabId,nativeUpdatedAt:at});
331
+ if(prepared?.status!=="PREPARED")
332
+ throw Error(prepared?.code||"ADOPT_KICKOFF_NOT_PREPARED");
333
+ token=prepared.token;
334
+ }
335
+ if (!token) {
336
+ show("VERIFYING", "手动打开 Continue:核对当前已完成的 Turn,并申请单次发送许可。");
337
+ if(params.has("resumeBlockedAt")){
338
+ // A terminal Chat may be displaying an older virtualized segment. Only
339
+ // the exact operator-acknowledged Native revision can authorize a
340
+ // one-time scroll by this formal Action, before double identity proof.
341
+ const reveal=await chrome.runtime.sendMessage({
342
+ type:"CHAT_LOOP_ACTION_MANUAL_REVEAL_V1",
343
+ tabId,resumeBlockedAt:Number(params.get("resumeBlockedAt"))
344
+ });
345
+ if(reveal?.status!=="OK")throw Error(reveal?.code||"REVEAL_NOT_AUTHORIZED");
346
+ await revealLatestOwnerTurn(tabId,reveal.page);
347
+ await new Promise(resolve=>setTimeout(resolve,400));
348
+ }
349
+ const prepared = await chrome.runtime.sendMessage({
350
+ type: "CHAT_LOOP_ACTION_MANUAL_PREPARE_V1", action: "CONTINUE",
351
+ ...(raw ? {tabId} : {})
352
+ });
353
+ if (prepared?.status !== "PREPARED")
354
+ throw Error(prepared?.code || "MANUAL_PREPARE_DENIED");
355
+ tabId = prepared.tabId;
356
+ token = prepared.token;
357
+ }
358
+ const request = {token, tabId};
359
+ const permit = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_TAKE_V1", ...request});
360
+ if (permit?.status === "DENIED" && permit.code === "PENDING_CONFIRMATION_DOM") {
361
+ // The Worker durably returned the Owner to WAITING_REPLY before denying
362
+ // this Action. No click occurred; close the now-obsolete Action tab so
363
+ // pending human choices do not accumulate background Chrome tabs.
364
+ await chrome.tabs.remove(own.id);
365
+ return;
366
+ }
367
+ if (permit?.status !== "OK" || permit.target?.tabId !== tabId)
368
+ throw Error(permit?.code || "ACTION_NOT_AUTHORIZED");
369
+ show("RUNNING", "已独占一次发送许可,正在核验目标 Chat 和最新已完成 Turn。");
370
+ let result;
371
+ try { result = permit.retryMode === "NATIVE"
372
+ ? await retryNativeOnce(permit.target) : await sendOnce(permit.target, permit.text); }
373
+ catch (error) {
374
+ result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
375
+ }
376
+ if(result.status==='UNVERIFIED')
377
+ result.reason=actionErrorCode({code:result.reason});
378
+ const final = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
379
+ result: result.status, reason: result.reason, newUserKey: result.newUserKey, newPage: result.newPage});
380
+ if (!(result.status === "SENT_CONFIRMED" || permit.retryMode === "NATIVE"
381
+ && result.status === "RETRY_CLICKED") || final?.status !== "OK")
382
+ throw Error(result.reason || final?.code || "ACTION_RESULT_NOT_COMMITTED");
383
+ show("SUCCESS", permit.retryMode === "NATIVE" ? "已点击原消息的网页重试一次;没有发送新用户消息。"
384
+ : "已确认新增一次用户消息;Action 已完成,等待下一轮 Observer。");
385
+ await chrome.tabs.remove(own.id);
386
+ }
387
+ (new URLSearchParams(location.search).has("requestId")
388
+ ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("continue")) : run())
389
+ .catch(error => show("BLOCKED",
390
+ actionErrorCode(error,"ACTION_FAILED")));
@@ -0,0 +1,2 @@
1
+ // DOM Action: independent entrypoint; shared verified read path.
2
+ void globalThis.ChatLoopActionCommonV1.runReadAction('dom',1000);
@@ -0,0 +1,241 @@
1
+ // Reviewed TEST_ONLY native @ App entry. Never owns a Loop Session or uses Continue.
2
+ const HOST='com.tomflow.chatloop.extension';
3
+ const statusNode=document.getElementById('status');
4
+ const detailNode=document.getElementById('details');
5
+ const show=(status,detail)=>{statusNode.textContent=status;detailNode.textContent=detail;document.body.dataset.result=status==='SUCCESS'?'success':'error';};
6
+ const pause=ms=>new Promise(r=>setTimeout(r,ms));
7
+ const safeCode=code=>/^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'ENTRY_TEST_UNVERIFIED';
8
+ async function readNewChat(id,recoverTestAt=false,recoverExactDraft=''){
9
+ const end=Date.now()+90000;
10
+ let cleaned=false;
11
+ while(Date.now()<end){
12
+ const tab=await chrome.tabs.get(id).catch(()=>null);
13
+ if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
14
+ if(tab.url==='https://chatgpt.com/'){
15
+ const proof=await chrome.scripting.executeScript({target:{tabId:id},
16
+ func:(recover,exactDraft)=>{
17
+ if(location.origin!=='https://chatgpt.com'||location.pathname!=='/')return false;
18
+ const mains=[...document.querySelectorAll('main')].filter(e=>e.getClientRects().length);
19
+ const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
20
+ ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
21
+ if(mains.length!==1||!editor?.getClientRects().length||!editor.isContentEditable
22
+ ||mains[0].querySelector('[data-chatgpt-search-message-ids],[data-message-author-role]'))
23
+ return false;
24
+ const current=(editor.innerText||editor.textContent||'').trim();
25
+ if(!current)return 'READY';
26
+ const canonical=value=>String(value||'').replace(/\s+/g,'');
27
+ const exactRecovery=typeof exactDraft==='string'&&!!exactDraft
28
+ &&canonical(current)===canonical(exactDraft);
29
+ if(!recover&& !exactRecovery)return 'HAS_DRAFT';
30
+ if(recover&&current!=='@'&&!exactRecovery)return 'HAS_DRAFT';
31
+ // Only a verified leftover "@" or byte-equivalent earlier TEST_ONLY
32
+ // draft may be cleared, on the newly created empty Chat home. Never
33
+ // touch other drafts, user turns or existing Chat tabs.
34
+ editor.focus();
35
+ const selection=window.getSelection(),range=document.createRange();
36
+ range.selectNodeContents(editor);selection.removeAllRanges();selection.addRange(range);
37
+ if(!document.execCommand('delete',false))return 'RECOVERY_FAILED';
38
+ return !(editor.innerText||editor.textContent||'').trim()
39
+ ?'RECOVERED_DRAFT':'RECOVERY_FAILED';
40
+ },args:[recoverTestAt&&!cleaned,cleaned?'':recoverExactDraft]}).catch(()=>null);
41
+ const state=proof?.[0]?.result;
42
+ if(state==='READY')return;
43
+ if(state==='RECOVERED_DRAFT'){cleaned=true;continue;}
44
+ if(state==='HAS_DRAFT')throw Error('ENTRY_COMPOSER_HAS_DRAFT');
45
+ if(state==='RECOVERY_FAILED')throw Error('ENTRY_AT_RECOVERY_FAILED');
46
+ }
47
+ await pause(320);
48
+ }
49
+ throw Error('ENTRY_COMPOSER_NOT_READY');
50
+ }
51
+ async function nativeMentionAndSend(id,appId,prompt){
52
+ const response=await chrome.scripting.executeScript({target:{tabId:id},
53
+ func:async(appId,prompt)=>{
54
+ const wait=ms=>new Promise(r=>setTimeout(r,ms));
55
+ const visible=e=>Boolean(e?.getClientRects?.().length);
56
+ const canonical=v=>String(v||'').replace(/\s+/g,'');
57
+ const fail=(code,diagnostic='')=>({status:'FAILED',code,diagnostic:diagnostic.slice(0,180)});
58
+ const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
59
+ ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
60
+ if(location.origin!=='https://chatgpt.com'||location.pathname!=='/'
61
+ ||!editor||!visible(editor)||!editor.isContentEditable
62
+ ||(editor.innerText||editor.textContent||'').trim())
63
+ return fail('ENTRY_EDITOR_UNVERIFIED');
64
+ // Commit the natural-language task to the host editor first. Selecting
65
+ // a native App mention can rehydrate the composer and otherwise discard
66
+ // text entered immediately after the selection transaction.
67
+ editor.focus();
68
+ if(!document.execCommand('insertText',false,prompt))return fail('ENTRY_PROMPT_INPUT_FAILED');
69
+ await wait(700);
70
+ if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
71
+ return fail('ENTRY_PROMPT_NOT_VISIBLE');
72
+ const selection=window.getSelection(),range=document.createRange();
73
+ range.selectNodeContents(editor);range.collapse(true);
74
+ selection.removeAllRanges();selection.addRange(range);
75
+ if(!document.execCommand('insertText',false,'@'))return fail('ENTRY_AT_INPUT_FAILED');
76
+ let choice=null,diagnostic='';
77
+ const selectors=['button[data-plugin-impression-id]','[role="option"]','[role="menuitem"]','[cmdk-item]',
78
+ '[data-testid*="app-item"]','[data-testid*="mention-item"]'];
79
+ for(let i=0;i<55;i++){
80
+ if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
81
+ const nodes=[...document.querySelectorAll(selectors.join(','))]
82
+ .filter(visible).filter(e=>(e.innerText||'').includes('Chat Loop'));
83
+ const matching=nodes.filter(e=>e.getAttribute('data-plugin-impression-id')===appId);
84
+ if(matching.length===1){choice=matching[0];break;}
85
+ const exact=nodes.filter(e=>{
86
+ const t=(e.innerText||'').trim();
87
+ return t==='Chat Loop'||t.startsWith('Chat Loop\n');
88
+ });
89
+ if(exact.length===1){choice=exact[0];break;}
90
+ if(!exact.length && nodes.length===1){choice=nodes[0];break;}
91
+ diagnostic=nodes.slice(0,4).map(e=>e.getAttribute('data-plugin-impression-id')+':'+(e.innerText||'').slice(0,55)).join('|');
92
+ await wait(220);
93
+ }
94
+ if(!choice)return fail('ENTRY_NATIVE_APP_OPTION_MISSING',diagnostic);
95
+ choice.click();
96
+ // A native mention is a structured composer node, not a literal "@Chat Loop" string.
97
+ let native=false;
98
+ for(let i=0;i<38;i++){
99
+ const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
100
+ native=tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
101
+ ||(e.getAttribute('data-app-mention-path')||'').includes(appId)
102
+ ||(e.getAttribute('href')||'').includes(appId));
103
+ if(native)break;
104
+ await wait(120);
105
+ }
106
+ if(!native)return fail('ENTRY_NATIVE_MENTION_UNVERIFIED',editor.innerHTML);
107
+ // Wait for the host selection transaction to settle; never rely on
108
+ // a transient DOM text match before clicking its native send button.
109
+ for(let i=0;i<5;i++){
110
+ await wait(240);
111
+ if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED_BEFORE_SEND');
112
+ if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
113
+ return fail('ENTRY_PROMPT_LOST_ON_MENTION');
114
+ }
115
+ const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
116
+ if(!tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
117
+ ||(e.getAttribute('data-app-mention-path')||'').includes(appId)
118
+ ||(e.getAttribute('href')||'').includes(appId)))
119
+ return fail('ENTRY_NATIVE_MENTION_LOST');
120
+ const send=document.querySelector('button[data-testid="send-button"]')
121
+ ||document.querySelector('button[data-testid="composer-send-button"]')
122
+ ||document.querySelector('button[aria-label="发送"]')
123
+ ||document.querySelector('button[aria-label="Send message"]');
124
+ if(!send||send.disabled||!visible(send))return fail('ENTRY_SEND_UNAVAILABLE');
125
+ if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
126
+ send.click(); // Exactly once. No caller retries on an uncertain receipt.
127
+ return {status:'CLICKED_ONCE'};
128
+ },args:[appId,prompt]}).catch(()=>null);
129
+ const r=response?.[0]?.result;
130
+ if(!r)throw Error('ENTRY_SEND_RESULT_UNKNOWN');
131
+ if(r.status!=='CLICKED_ONCE')throw Error(safeCode(r.code));
132
+ }
133
+ async function verifyNativeUserTurn(id,appId,prompt){
134
+ const end=Date.now()+120000;let last=null,stable=0,mismatch=0;
135
+ while(Date.now()<end){
136
+ const tab=await chrome.tabs.get(id).catch(()=>null);
137
+ if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
138
+ const path=tab.url&&new URL(tab.url).pathname;
139
+ if(/^\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(path||'')){
140
+ const r=await chrome.scripting.executeScript({target:{tabId:id},
141
+ func:(appId,prompt)=>{
142
+ if(location.origin!=='https://chatgpt.com')return null;
143
+ // ChatGPT can render conversation turns outside its composer <main>.
144
+ // A main-scoped read silently misses real user turns in that layout.
145
+ const users=[...document.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]
146
+ .filter(x=>x.getAttribute('data-chatgpt-search-unit-key')?.endsWith(':user'));
147
+ if(!users.length){
148
+ users.push(...document.querySelectorAll('[data-message-author-role="user"]'));
149
+ }
150
+ const u=users.at(-1);
151
+ const key=u?.getAttribute('data-message-id')
152
+ ||u?.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0];
153
+ const bubble=u?.querySelector('[data-user-message-bubble="true"]')||u;
154
+ const m=bubble?.querySelector('[data-prompt-link-href="app://'+appId+'"]');
155
+ const canonical=v=>String(v||'').replace(/\s+/g,'');
156
+ return {path:location.pathname,userCount:users.length,
157
+ ids:users.map(x=>x.getAttribute('data-message-id')
158
+ ||x.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0]),
159
+ userKey:typeof key==='string'&&m
160
+ &&canonical(bubble.innerText||bubble.textContent).includes(canonical(prompt))
161
+ ?'user:'+key:null,hasNativeApp:Boolean(m)};
162
+ },args:[appId,prompt]}).catch(()=>null);
163
+ const v=r?.[0]?.result;
164
+ if(v?.userCount>1||v?.ids?.some(x=>x!==v.ids[0]))
165
+ throw Error('ENTRY_DUPLICATE_USER_TURN');
166
+ if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&!v.userKey){
167
+ if(++mismatch>=4)throw Error('ENTRY_USER_TURN_CONTENT_MISMATCH');
168
+ }else mismatch=0;
169
+ if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&v.userKey){
170
+ const k=path+'|'+v.userKey;
171
+ stable=last===k?stable+1:1;last=k;
172
+ if(stable>=4){
173
+ const chatId=path.slice(3);
174
+ return {status:'OK',testOnly:true,appId,
175
+ activeChatId:chatId,activeChatUrl:'https://chatgpt.com'+path,
176
+ userKey:v.userKey};
177
+ }
178
+ }else{stable=0;last=null;}
179
+ }
180
+ await pause(350);
181
+ }
182
+ throw Error('ENTRY_NATIVE_TURN_RECEIPT_UNKNOWN');
183
+ }
184
+ async function run(){
185
+ const own=await chrome.tabs.getCurrent();
186
+ const params=new URLSearchParams(location.search),id=params.get('requestId');
187
+ if(!own?.id||own.url!==location.href||[...params.keys()].length!==1
188
+ ||!/^[a-f0-9]{32}$/.test(id||'')
189
+ ||location.href!==chrome.runtime.getURL('entry_test.html')+'?requestId='+id)
190
+ throw Error('ENTRY_TEST_ACTION_SOURCE_INVALID');
191
+ const proof=await chrome.runtime.sendNativeMessage(HOST,{op:'acquire',id,action:'entry_test'});
192
+ if(proof?.status!=='OK'||proof.action!=='entry_test'||proof.id!==id
193
+ ||!proof.nonce||proof.intent?.confirmed!==true||proof.intent?.testOnly!==true)
194
+ throw Error('ENTRY_TEST_NATIVE_UNAUTHORIZED');
195
+ const intent=proof.intent;
196
+ let tab,clicked=false;
197
+ try{
198
+ // This read-only Worker/Native gate may admit a provably frozen orphan
199
+ // for an independent TEST_ONLY Chat; it never releases the old Session.
200
+ const admitted=async()=>{
201
+ const decision=await chrome.runtime.sendMessage({
202
+ type:'CHAT_LOOP_ENTRY_TEST_ADMISSION_V1',requestId:id}).catch(()=>null);
203
+ if(decision?.status!=='OK'||decision.scope!=='TEST_ONLY')
204
+ throw Error(safeCode(decision?.code||'ENTRY_TEST_OWNER_UNVERIFIED'));
205
+ };
206
+ await admitted();
207
+ let result;
208
+ if(intent.verifyChatUrl){
209
+ // Pure receipt recovery. Never click, resend, adopt or modify an existing Chat.
210
+ show('RUNNING','只读核对已存在 Chat 的唯一原生 @ App 用户消息。');
211
+ const candidates=await chrome.tabs.query({url:intent.verifyChatUrl});
212
+ const matches=candidates.filter(t=>t.url===intent.verifyChatUrl
213
+ &&Number.isSafeInteger(t.id));
214
+ if(matches.length!==1)throw Error('ENTRY_VERIFY_TAB_UNVERIFIED');
215
+ result=await verifyNativeUserTurn(matches[0].id,intent.appId,intent.prompt);
216
+ }else{
217
+ show('RUNNING','新普通 Chat 正在加载;仅验证原生 App 入口,不进行批准或 Start。');
218
+ tab=await chrome.tabs.create({url:'https://chatgpt.com/',active:true,
219
+ windowId:own.windowId,openerTabId:own.id});
220
+ if(!Number.isSafeInteger(tab?.id))throw Error('ENTRY_NEW_TAB_UNVERIFIED');
221
+ await readNewChat(tab.id,intent.recoverTestAt===true,intent.recoverExactDraft||'');
222
+ await admitted(); // Recheck before the only possible first send.
223
+ await nativeMentionAndSend(tab.id,intent.appId,intent.prompt);
224
+ clicked=true;
225
+ result=await verifyNativeUserTurn(tab.id,intent.appId,intent.prompt);
226
+ }
227
+ const stored=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
228
+ nonce:proof.nonce,action:'entry_test',status:'OK',payload:JSON.stringify(result)});
229
+ if(stored?.status!=='SAVED'||stored.id!==id)throw Error('ENTRY_TEST_NATIVE_RECEIPT_UNVERIFIED');
230
+ show('SUCCESS','已确认唯一原生 @ App 用户消息,未创建 Browser Owner。');
231
+ await chrome.tabs.remove(own.id);
232
+ }catch(error){
233
+ const code=safeCode(error?.message);
234
+ // After an uncertain click, never send again. Preserve created chat for audit.
235
+ const saved=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
236
+ nonce:proof.nonce,action:'entry_test',status:'FAILED',code}).catch(()=>null);
237
+ show('BLOCKED',code+(clicked?';已发送或副作用未知,禁止重试。':';尚未验证发送。'));
238
+ if(saved?.status==='SAVED')await chrome.tabs.remove(own.id).catch(()=>{});
239
+ }
240
+ }
241
+ void run().catch(error=>show('BLOCKED',safeCode(error?.message)));