@tomflow/chatloop-tools 0.9.62 → 0.9.64

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 (154) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +29 -10
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/package.json +3 -13
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -83
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,183 +0,0 @@
1
- // Shared Eye Action primitives only. No action is dispatched or executed here.
2
- (() => {
3
- const CONTRACT = "chat-loop.eye.v1";
4
- const params = new URLSearchParams(location.search);
5
- const statusNode = document.getElementById("status");
6
- const detailsNode = document.getElementById("details");
7
- function show(status, message) {
8
- statusNode.textContent = status;
9
- detailsNode.textContent = message;
10
- }
11
- function fail(code, message) {
12
- show(code, message);
13
- document.body.dataset.result = "error";
14
- console.error("Chat Loop eye:", code, message);
15
- }
16
- function isChatGPT(value) {
17
- try {
18
- const u = new URL(value);
19
- return u.protocol === "https:" && u.hostname === "chatgpt.com";
20
- } catch { return false; }
21
- }
22
- async function findTarget(ownTab) {
23
- // Action pages may open in a different window from the ChatGPT tab.
24
- const candidates = await chrome.tabs.query({url: "https://chatgpt.com/*"});
25
- const eligible = candidates.filter(tab => isChatGPT(tab.url));
26
- const requested = params.get("tabId");
27
- if (requested !== null) {
28
- if (!/^[1-9][0-9]*$/.test(requested)) throw Error("INVALID_TAB_ID");
29
- const match = eligible.find(tab => tab.id === Number(requested));
30
- if (!match) throw Error("TARGET_NOT_CHATGPT_OR_NOT_FOUND");
31
- return match;
32
- }
33
- // When an action page was opened from a ChatGPT tab, respect its opener.
34
- const opener = eligible.find(tab => tab.id === ownTab.openerTabId);
35
- if (opener) return opener;
36
- if (eligible.length === 0) throw Error("NO_CHATGPT_TAB");
37
- if (eligible.length !== 1) {
38
- const ids = eligible.map(tab => tab.id).join(", ");
39
- throw Error("AMBIGUOUS_CHATGPT_TABS: use ?tabId=... (available: " + ids + ")");
40
- }
41
- return eligible[0];
42
- }
43
- async function closeAction(ownTab) {
44
- await chrome.tabs.remove(ownTab.id);
45
- }
46
- async function readChat(tab, mode) {
47
- // Capture the original URL, not the mutable Chrome Tab object. A user may
48
- // navigate this same tab while a content-script read is in flight.
49
- const expectedUrl=tab.url;
50
- const verifyTarget=async()=>{
51
- const current=await chrome.tabs.get(tab.id).catch(()=>null);
52
- if(!current || current.url!==expectedUrl)throw Error('TARGET_CHANGED_DURING_READ');
53
- };
54
- const request = () => chrome.tabs.sendMessage(tab.id,
55
- {type: "CHAT_LOOP_EYE_READ_V1", mode});
56
- let response;
57
- try {
58
- response = await request();
59
- } catch {
60
- // Reload invalidates old content scripts. Never reinject after a tab has
61
- // navigated away from the original target during this read.
62
- await verifyTarget();
63
- try {
64
- await chrome.scripting.executeScript({target: {tabId: tab.id}, files: ["content.js"]});
65
- response = await request();
66
- } catch {
67
- throw Error("CONTENT_SCRIPT_UNAVAILABLE: could not reinject into ChatGPT tab");
68
- }
69
- }
70
- if (response?.contract !== CONTRACT || response?.status !== "OK"
71
- || response?.mode !== mode || typeof response?.value !== "string") {
72
- throw Error("INVALID_CONTENT_RESPONSE");
73
- }
74
- await verifyTarget();
75
- return response.value;
76
- }
77
- function copyText(value) {
78
- // Synchronous copy avoids losing the macOS pasteboard when this action tab closes.
79
- const field = document.createElement("textarea");
80
- field.value = value;
81
- field.setAttribute("readonly", "");
82
- field.style.position = "fixed";
83
- field.style.opacity = "0";
84
- document.body.appendChild(field);
85
- field.focus();
86
- field.select();
87
- const copied = document.execCommand("copy");
88
- field.remove();
89
- if (!copied) throw Error("CLIPBOARD_COPY_FAILED");
90
- }
91
- // Only requestId generated by the local CLI enables machine-result mode.
92
- // Manual Action pages keep the verified clipboard/download behavior.
93
- const nativeHost = "com.tomflow.chatloop.extension";
94
- const machineId = params.get("requestId");
95
- async function machineBinding(action) {
96
- if (machineId === null) return null;
97
- if (!/^[a-f0-9]{32}$/.test(machineId)) throw Error("INVALID_MACHINE_REQUEST");
98
- const request = await chrome.runtime.sendNativeMessage(nativeHost,
99
- {op:"acquire",id:machineId,action});
100
- if (request?.status !== "OK" || request.id !== machineId || request.action !== action
101
- || typeof request.nonce !== "string") throw Error(request?.code || "NATIVE_REQUEST_REJECTED");
102
- const target = await chrome.runtime.sendMessage({
103
- type:"CHAT_LOOP_EXTENSION_TARGET_V1",id:machineId,action
104
- });
105
- if (target?.status !== "OK") throw Error(target?.code || "OWNER_NOT_AVAILABLE");
106
- return {id:machineId,nonce:request.nonce,action,
107
- tabId:target.tabId??null,page:target.page??null};
108
- }
109
- async function machineTarget(binding) {
110
- if (!binding || !Number.isInteger(binding.tabId)
111
- || typeof binding.page !== "string") throw Error("OWNER_UNVERIFIED");
112
- const tab = await chrome.tabs.get(binding.tabId);
113
- if (!tab?.url || new URL(tab.url).pathname !== binding.page
114
- || new URL(tab.url).origin !== "https://chatgpt.com") throw Error("OWNER_CHANGED");
115
- return tab;
116
- }
117
- async function machineResult(binding,payload) {
118
- const response = await chrome.runtime.sendNativeMessage(nativeHost,{
119
- op:"complete",id:binding.id,nonce:binding.nonce,action:binding.action,status:"OK",payload
120
- });
121
- if(response?.status!=="SAVED"||response.id!==binding.id)throw Error(response?.code||"NATIVE_RESULT_UNVERIFIED");
122
- }
123
- async function machineFailure(action,error) {
124
- if (machineId === null || !/^[a-f0-9]{32}$/.test(machineId)) return;
125
- try {
126
- const req=await chrome.runtime.sendNativeMessage(nativeHost,
127
- {op:"acquire",id:machineId,action});
128
- if(req?.status==="OK") {
129
- const rawCode=error?.code||error?.message;
130
- const code=typeof rawCode==='string'
131
- &&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
132
- ?rawCode:'ACTION_FAILED';
133
- const saved = await chrome.runtime.sendNativeMessage(nativeHost,{
134
- op:"complete",id:machineId,nonce:req.nonce,action,status:"FAILED",code
135
- });
136
- // Machine errors already have a durable CLI receipt. They must not
137
- // accumulate as abandoned tabs; manual/unverified errors remain open.
138
- if(saved?.status==="SAVED" && saved.id===machineId) {
139
- const own = await chrome.tabs.getCurrent();
140
- if(own?.id && own.url===location.href)
141
- await chrome.tabs.remove(own.id).catch(()=>{});
142
- }
143
- }
144
- } catch { /* CLI timeout is UNKNOWN, never success. */ }
145
- }
146
- function requireOwnTab(tab) {
147
- if (!tab?.id) throw Error("ACTION_TAB_UNVERIFIED");
148
- return tab;
149
- }
150
- // Text and DOM share the same verified read path. Their separate pages
151
- // select a fixed mode and clipboard settling delay; no extra executor.
152
- async function runReadAction(mode, clipboardMs, action="chat_"+mode) {
153
- if(!['text','dom'].includes(mode)||!/^chat_[a-z0-9_]+$/.test(action))
154
- throw Error('EYE_MODE_UNSUPPORTED');
155
- try {
156
- const machine=await machineBinding(action);
157
- const own=requireOwnTab(await chrome.tabs.getCurrent());
158
- const target=machine ? await machineTarget(machine) : await findTarget(own);
159
- show("RUNNING", mode+" → ChatGPT tab "+target.id);
160
- const value=await readChat(target,mode);
161
- if(!value.length)throw Error("EMPTY_CONTENT");
162
- if(machine)await machineResult(machine,value);
163
- else {
164
- copyText(value);
165
- await new Promise(resolve=>setTimeout(resolve,clipboardMs));
166
- }
167
- await done(own,mode,target);
168
- }catch(error){
169
- await machineFailure(action,error);
170
- fail(error.message || "UNEXPECTED_ERROR",
171
- "操作未完成;动作页已保留,未对其他 ChatGPT 标签页进行操作。");
172
- }
173
- }
174
- function done(ownTab, action, target) {
175
- show("SUCCESS", action + " completed for tab " + target.id);
176
- document.body.dataset.result = "success";
177
- return closeAction(ownTab);
178
- }
179
- globalThis.ChatLoopActionCommonV1 = Object.freeze({
180
- show, fail, findTarget, readChat, copyText, closeAction, done, requireOwnTab,
181
- machineBinding, machineTarget, machineResult, machineFailure, runReadAction
182
- });
183
- })();
@@ -1,340 +0,0 @@
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('[data-message-author-role]')];
31
- const roles = modern.length ? modern : legacy;
32
- const role = node => node.getAttribute("data-message-author-role")
33
- || node.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
34
- const idOf = node => node?.getAttribute("data-message-id")
35
- || node?.getAttribute("data-chatgpt-search-message-ids")?.trim().split(/\s+/)[0]
36
- || node?.closest('[data-testid^="conversation-turn-"]')?.getAttribute("data-testid");
37
- const user = roles.filter(node => role(node) === "user").at(-1);
38
- const answer = roles.filter(node => role(node) === "assistant").at(-1);
39
- if ("user:" + idOf(user) !== expected.userKey
40
- || "assistant:" + idOf(answer) !== expected.assistantKey)
41
- throw Error("TURN_IDENTITY_CHANGED");
42
- const scope = answer.closest('[data-testid^="conversation-turn-"]')
43
- || answer.closest('[data-talvt-turn-state]') || answer;
44
- const replyText = (answer.querySelector('.markdown')?.innerText || answer.innerText || '').trim();
45
- const lines = replyText.split(/\r?\n/);
46
- const expectedMarker=expected.recoveryMode==="ADOPT_KICKOFF"
47
- ? null : expected.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
48
- ? "[CHAT_LOOP_STATUS:BLOCKED]" : expected.recoveryMode==="HANDOFF_NOT_SENT"
49
- ? expected.contextSourceMarker : "[CHAT_LOOP_STATUS:CONTINUE]";
50
- if ((expectedMarker===null
51
- ? lines.some(line=>/^\[CHAT_LOOP_STATUS:(?:CONTINUE|DONE|BLOCKED|HANDOFF)\]$/.test(line.trim()))
52
- : lines.at(-1)?.trim() !== expectedMarker
53
- ||lines.filter(line=>/^\[CHAT_LOOP_STATUS:(?:CONTINUE|DONE|BLOCKED|HANDOFF)\]$/.test(line.trim())).length !== 1)) {
54
- throw Error("CONTINUE_STATUS_CHANGED");
55
- }
56
- const turnState = scope.getAttribute?.('data-talvt-turn-state');
57
- if (turnState && turnState !== "complete") throw Error("TURN_NOT_COMPLETE");
58
- if ([...document.querySelectorAll('button[data-testid="stop-button"],button[aria-label="停止响应"],button[aria-label="Stop generating"]')].some(visible))
59
- throw Error("GENERATION_STILL_RUNNING");
60
- if (![...scope.querySelectorAll('button[aria-label="复制"],button[aria-label="Copy"],button[data-testid="copy-turn-action-button"]')].some(visible))
61
- throw Error("FINAL_UI_EVIDENCE_MISSING");
62
- let input = document.querySelector('[contenteditable="true"][data-composer-markdown]')
63
- || document.querySelector('#prompt-textarea[contenteditable="true"]')
64
- || document.querySelector('[data-testid="composer-input"][contenteditable="true"]');
65
- if (!visible(input) || input.closest('[aria-disabled="true"]'))
66
- throw Error("COMPOSER_UNAVAILABLE");
67
- if ((input.innerText || input.textContent || '').trim())
68
- throw Error("COMPOSER_NOT_EMPTY");
69
- input.focus();
70
- if (!document.execCommand("insertText", false, instruction)) throw Error("INPUT_NOT_ACCEPTED");
71
- // DOM writes can precede React composer state. Do not click a stale
72
- // enabled button in the same task as insertion (especially after reset).
73
- await new Promise(resolve => setTimeout(resolve, 400));
74
- const canonical = value => String(value || '').replace(/\s+/g, '');
75
- let verified = false;
76
- for (let n = 0; n < 30; n++) {
77
- if (canonical(input.innerText) === canonical(instruction)
78
- || canonical(input.textContent) === canonical(instruction)) {verified = true; break;}
79
- await new Promise(resolve => setTimeout(resolve, 120));
80
- }
81
- if (!verified) throw Error("INPUT_NOT_VERIFIED");
82
- let button;
83
- for (let n = 0; n < 16; n++) {
84
- button = document.querySelector('button[type="submit"][aria-label="发送"]')
85
- || document.querySelector('button[data-testid="send-button"]')
86
- || document.querySelector('button[data-testid="composer-send-button"]')
87
- || document.querySelector('button[aria-label="Send message"]');
88
- if (button && !button.disabled && visible(button)) break;
89
- await new Promise(resolve => setTimeout(resolve, 120));
90
- }
91
- if (!button || button.disabled || !visible(button)) throw Error("SEND_BUTTON_UNAVAILABLE");
92
- // Final same-page DOM guard. The Worker checked before Action Take; a
93
- // confirmation may appear while React settles the composer. Reuse
94
- // Observer's existing read-only detection, no new action or state.
95
- const gate = globalThis.ChatLoopTurnObserverV1?.poll?.();
96
- if (gate?.contract !== "chat-loop.turn-observer.v1"
97
- || gate.page !== expected.page
98
- || gate.userKey !== expected.userKey
99
- || gate.assistantKey !== expected.assistantKey
100
- || gate.reason === "WAITING_CHAT_HYDRATION"
101
- || typeof gate.pendingConfirmation !== "boolean")
102
- throw Error("CONFIRMATION_OBSERVER_UNVERIFIED");
103
- if (gate.pendingConfirmation) throw Error("CONFIRMATION_PENDING_DOM");
104
- if (location.pathname !== expected.page) throw Error("CHAT_PAGE_CHANGED_BEFORE_SEND");
105
- if (canonical(input.innerText) !== canonical(instruction)
106
- && canonical(input.textContent) !== canonical(instruction)) throw Error("INPUT_CHANGED_BEFORE_SEND");
107
- // Snapshot the visible message identities before the ONE irreversible
108
- // click. A matching latest bubble is not enough if the UI exposes TWO
109
- // newly created user Turns for this one send.
110
- const beforeUserIds = new Set(roles.filter(node => role(node) === "user")
111
- .map(idOf).filter(Boolean));
112
- button.click(); // Once, after durable PENDING commit in the worker. Never retry.
113
- let candidateId = null, candidateStableAt = 0;
114
- for (let n = 0; n < 32; n++) {
115
- if (location.pathname !== expected.page) throw Error("CHAT_PAGE_CHANGED_AFTER_SEND");
116
- const visibleMain = [...document.querySelectorAll("main")].filter(visible);
117
- if (visibleMain.length !== 1) throw Error("CHAT_MAIN_CHANGED_AFTER_SEND");
118
- const rows = [...visibleMain[0].querySelectorAll(
119
- '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids], [data-message-author-role]')];
120
- const users = rows.filter(node => role(node) === "user");
121
- const latest = users.at(-1), newId = idOf(latest);
122
- const newIds = [...new Set(users.map(idOf)
123
- .filter(id => id && !beforeUserIds.has(id)))];
124
- if (newIds.length > 1) throw Error("DUPLICATE_USER_TURN_UNVERIFIED");
125
- if (newId && 'user:' + newId !== expected.userKey) {
126
- // On live ChatGPT the collapsed bubble has a "显示更多"
127
- // button; only the actual message text qualifies as a receipt.
128
- const message = latest?.querySelector('[data-search-result-target]')
129
- || latest?.querySelector('[data-user-message-bubble="true"]') || latest;
130
- if (newIds.length !== 1 || newIds[0] !== newId
131
- || (canonical(message?.innerText) !== canonical(instruction)
132
- && canonical(message?.textContent) !== canonical(instruction)))
133
- throw Error("NEW_USER_TURN_UNVERIFIED");
134
- if (candidateId !== newId) {
135
- candidateId = newId;
136
- candidateStableAt = Date.now();
137
- }
138
- // Recheck the DOM for a short stable window; one immediate new
139
- // bubble does not prove that no duplicate followed the click.
140
- if (Date.now() - candidateStableAt >= 750)
141
- return {status: "SENT_CONFIRMED", newUserKey: 'user:' + newId,
142
- newPage: location.pathname};
143
- }
144
- await new Promise(resolve => setTimeout(resolve, 250));
145
- }
146
- throw Error("SEND_UNVERIFIED"); // Side effect may exist: block, don't retry.
147
- } catch (error) {
148
- const code=error?.code||error?.message;
149
- return {status:"UNVERIFIED",reason:
150
- /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:"SEND_ERROR"};
151
- }
152
- },
153
- args: [target, text]
154
- });
155
- if (!execution?.result || execution.result.status !== "SENT_CONFIRMED")
156
- throw Error(execution?.result?.reason || "SEND_RESULT_UNVERIFIED");
157
- return execution.result;
158
- }
159
- // Reuse the formal Continue Action page for a *different* one-shot recovery
160
- // operation. Native Retry targets the existing user Turn: never type or send.
161
- async function retryNativeOnce(target) {
162
- const [execution] = await chrome.scripting.executeScript({
163
- target: {tabId: target.tabId},
164
- func: async expected => {
165
- try {
166
- if (location.origin !== "https://chatgpt.com" || location.pathname !== expected.page)
167
- throw Error("RETRY_CHAT_CHANGED");
168
- const visible = node => Boolean(node?.getClientRects?.().length)
169
- && !node.closest?.('[hidden],[aria-hidden="true"]')
170
- && getComputedStyle(node).display !== "none";
171
- const mains = [...document.querySelectorAll('main')].filter(visible);
172
- if (mains.length !== 1) throw Error("RETRY_MAIN_UNVERIFIED");
173
- const main = mains[0];
174
- const rows = [...main.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
175
- const messages = rows.length ? rows : [...main.querySelectorAll('[data-message-author-role]')];
176
- const role = node => node.getAttribute('data-message-author-role')
177
- || node.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
178
- const id = node => node?.getAttribute('data-message-id')
179
- || node?.getAttribute('data-chatgpt-search-message-ids')?.trim().split(/\s+/)[0]
180
- || node?.closest('[data-testid^="conversation-turn-"]')?.getAttribute('data-testid');
181
- const latestUser = messages.filter(node => role(node) === 'user').at(-1);
182
- const latestAssistant = messages.filter(node => role(node) === 'assistant').at(-1);
183
- if ('user:' + id(latestUser) !== expected.userKey
184
- || (latestAssistant ? 'assistant:' + id(latestAssistant) : null) !== expected.assistantKey)
185
- throw Error("RETRY_TURN_CHANGED");
186
- if ([...document.querySelectorAll('button[data-testid="stop-button"],button[aria-label="停止响应"],button[aria-label="Stop generating"]')].some(visible))
187
- throw Error("RETRY_STILL_GENERATING");
188
- const alerts = [...main.querySelectorAll('[role="alert"],[role="status"],[data-testid="conversation-error"]')]
189
- .filter(visible);
190
- 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 || ''));
191
- if (failed.length !== 1) throw Error("RETRY_ERROR_NOT_UNIQUE");
192
- const buttons = [...failed[0].querySelectorAll('button')].filter(button => visible(button)
193
- && /^(?:retry|try again|重试|再试一次)$/i.test(
194
- (button.innerText || button.textContent || button.getAttribute('aria-label') || '').trim()));
195
- if (buttons.length !== 1 || buttons[0].disabled) throw Error("RETRY_BUTTON_UNVERIFIED");
196
- buttons[0].click(); // Exact native retry on the existing user Turn, once.
197
- // Require visible evidence that the page accepted the native retry,
198
- // not merely that the click function returned without throwing.
199
- for (let attempt = 0; attempt < 24; attempt++) {
200
- await new Promise(resolve => setTimeout(resolve, 250));
201
- if (location.pathname !== expected.page) throw Error("RETRY_PAGE_CHANGED_AFTER_CLICK");
202
- const current = [...document.querySelectorAll('main')].filter(visible);
203
- if (current.length !== 1) throw Error("RETRY_MAIN_CHANGED_AFTER_CLICK");
204
- const latest = [...current[0].querySelectorAll('[role="alert"],[role="status"],[data-testid="conversation-error"]')]
205
- .filter(visible).some(el => /unknown error|something went wrong|an error occurred|unable to load|connection (?:lost|interrupted)|请求失败|网络错误|发生错误|出错了/i.test(el.innerText || el.textContent || ''));
206
- if (!latest) return {status: 'RETRY_CLICKED'};
207
- }
208
- throw Error("NATIVE_RETRY_NOT_ACKNOWLEDGED");
209
- } catch(error) {
210
- const code=error?.code||error?.message;
211
- return {status:'UNVERIFIED',reason:
212
- /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'RETRY_FAILED'};
213
- }
214
- }, args: [target]
215
- });
216
- return execution?.result || {status:'UNVERIFIED',reason:'RETRY_RESULT_UNKNOWN'};
217
- }
218
- // Recovery-only UI reveal. A Worker+Native CAS check must grant the exact
219
- // terminal Owner before this Action can move its viewport. No message is sent.
220
- async function revealLatestOwnerTurn(tabId, expectedPage) {
221
- const [execution]=await chrome.scripting.executeScript({
222
- target:{tabId},
223
- func: page => {
224
- if(location.origin!=='https://chatgpt.com'||location.pathname!==page)
225
- return 'CHAT_PAGE_CHANGED';
226
- const marks=[...document.querySelectorAll('main [data-chatgpt-search-unit-key]')];
227
- let ancestor=marks.at(-1);
228
- if(!ancestor)return 'NO_VISIBLE_TURN';
229
- while(ancestor){
230
- const style=getComputedStyle(ancestor);
231
- if(/^(auto|scroll)$/.test(style.overflowY)
232
- &&ancestor.scrollHeight-ancestor.clientHeight>24){
233
- ancestor.scrollTop=ancestor.scrollHeight;
234
- return 'SCROLLED';
235
- }
236
- ancestor=ancestor.parentElement;
237
- }
238
- return 'CHAT_SCROLL_CONTAINER_UNVERIFIED';
239
- },args:[expectedPage]
240
- });
241
- if(execution?.result!=='SCROLLED')
242
- throw Error(execution?.result||'CHAT_SCROLL_UNVERIFIED');
243
- }
244
- async function run() {
245
- const params = new URLSearchParams(location.search);
246
- const raw = params.get("tabId") || "";
247
- let token = params.get("token") || "";
248
- let tabId = Number(raw);
249
- if ([...params.keys()].some(k => k !== "tabId" && k !== "token" && k !== "repairLegacyReservation" && k !== "resumeBlockedAt" && k !== "recoverContextNotSentAt" && k !== "adoptBaselineAt" && k !== "adoptKickoffAt")
250
- || [...params.keys()].length !== new Set(params.keys()).size)
251
- throw Error("ACTION_PARAMETERS_INVALID");
252
- if (raw && !/^[1-9][0-9]*$/.test(raw)
253
- || token && !/^[0-9a-f-]{36}$/.test(token)
254
- || token && (!raw||params.has("repairLegacyReservation")||params.has("resumeBlockedAt")
255
- ||params.has("recoverContextNotSentAt"))) throw Error("ACTION_PARAMETERS_INVALID");
256
- const own = await chrome.tabs.getCurrent();
257
- if (!own?.id || own.url !== location.href) throw Error("ACTION_TAB_UNVERIFIED");
258
- if(params.has("adoptBaselineAt")){
259
- const rawAt=params.get("adoptBaselineAt"),at=Number(rawAt);
260
- if(params.size!==2||!raw||token||!/^[1-9][0-9]{12}$/.test(rawAt||"")
261
- ||!Number.isSafeInteger(at))
262
- throw Error("ADOPT_BASELINE_PARAMETERS_INVALID");
263
- show("VERIFYING","对同一原 Chat 的历史审批回复进行只读复核;绝不发送消息。");
264
- const result=await chrome.runtime.sendMessage({
265
- type:"CHAT_LOOP_ADOPT_BASELINE_REPAIR_V1",
266
- tabId,nativeUpdatedAt:at});
267
- if(result?.status!=="REPAIRED")
268
- throw Error(result?.code||"ADOPT_BASELINE_REPAIR_UNVERIFIED");
269
- show("SUCCESS","已对原 Chat 完成历史基线恢复;未创建 Chat、未发送消息。");
270
- await chrome.tabs.remove(own.id);
271
- return;
272
- }
273
- if(params.has("adoptKickoffAt")){
274
- const rawAt=params.get("adoptKickoffAt"),at=Number(rawAt);
275
- if(params.size!==2||!raw||token||!/^[1-9][0-9]{12}$/.test(rawAt||"")
276
- ||!Number.isSafeInteger(at))
277
- throw Error("ADOPT_KICKOFF_PARAMETERS_INVALID");
278
- show("VERIFYING","核查当前 Managed Task、已批准 R/P 和原 Chat 的历史回复,再申请唯一首轮执行许可。");
279
- const prepared=await chrome.runtime.sendMessage({
280
- type:"CHAT_LOOP_ADOPT_KICKOFF_PREPARE_V1",tabId,nativeUpdatedAt:at});
281
- if(prepared?.status!=="PREPARED")
282
- throw Error(prepared?.code||"ADOPT_KICKOFF_NOT_PREPARED");
283
- token=prepared.token;
284
- }
285
- if (!token) {
286
- show("VERIFYING", "手动打开 Continue:核对当前已完成的 Turn,并申请单次发送许可。");
287
- if(params.has("resumeBlockedAt")){
288
- // A terminal Chat may be displaying an older virtualized segment. Only
289
- // the exact operator-acknowledged Native revision can authorize a
290
- // one-time scroll by this formal Action, before double identity proof.
291
- const reveal=await chrome.runtime.sendMessage({
292
- type:"CHAT_LOOP_ACTION_MANUAL_REVEAL_V1",
293
- tabId,resumeBlockedAt:Number(params.get("resumeBlockedAt"))
294
- });
295
- if(reveal?.status!=="OK")throw Error(reveal?.code||"REVEAL_NOT_AUTHORIZED");
296
- await revealLatestOwnerTurn(tabId,reveal.page);
297
- await new Promise(resolve=>setTimeout(resolve,400));
298
- }
299
- const prepared = await chrome.runtime.sendMessage({
300
- type: "CHAT_LOOP_ACTION_MANUAL_PREPARE_V1", action: "CONTINUE",
301
- ...(raw ? {tabId} : {})
302
- });
303
- if (prepared?.status !== "PREPARED")
304
- throw Error(prepared?.code || "MANUAL_PREPARE_DENIED");
305
- tabId = prepared.tabId;
306
- token = prepared.token;
307
- }
308
- const request = {token, tabId};
309
- const permit = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_TAKE_V1", ...request});
310
- if (permit?.status === "DENIED" && permit.code === "PENDING_CONFIRMATION_DOM") {
311
- // The Worker durably returned the Owner to WAITING_REPLY before denying
312
- // this Action. No click occurred; close the now-obsolete Action tab so
313
- // pending human choices do not accumulate background Chrome tabs.
314
- await chrome.tabs.remove(own.id);
315
- return;
316
- }
317
- if (permit?.status !== "OK" || permit.target?.tabId !== tabId)
318
- throw Error(permit?.code || "ACTION_NOT_AUTHORIZED");
319
- show("RUNNING", "已独占一次发送许可,正在核验目标 Chat 和最新已完成 Turn。");
320
- let result;
321
- try { result = permit.retryMode === "NATIVE"
322
- ? await retryNativeOnce(permit.target) : await sendOnce(permit.target, permit.text); }
323
- catch (error) {
324
- result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
325
- }
326
- if(result.status==='UNVERIFIED')
327
- result.reason=actionErrorCode({code:result.reason});
328
- const final = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
329
- result: result.status, reason: result.reason, newUserKey: result.newUserKey, newPage: result.newPage});
330
- if (!(result.status === "SENT_CONFIRMED" || permit.retryMode === "NATIVE"
331
- && result.status === "RETRY_CLICKED") || final?.status !== "OK")
332
- throw Error(result.reason || final?.code || "ACTION_RESULT_NOT_COMMITTED");
333
- show("SUCCESS", permit.retryMode === "NATIVE" ? "已点击原消息的网页重试一次;没有发送新用户消息。"
334
- : "已确认新增一次用户消息;Action 已完成,等待下一轮 Observer。");
335
- await chrome.tabs.remove(own.id);
336
- }
337
- (new URLSearchParams(location.search).has("requestId")
338
- ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("continue")) : run())
339
- .catch(error => show("BLOCKED",
340
- actionErrorCode(error,"ACTION_FAILED")));
@@ -1,2 +0,0 @@
1
- // DOM Action: independent entrypoint; shared verified read path.
2
- void globalThis.ChatLoopActionCommonV1.runReadAction('dom',1000);