@tomflow/chatloop-tools 0.9.21 → 0.9.23

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