@tomflow/chatloop-tools 0.9.17 → 0.9.19

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 (140) hide show
  1. package/package.json +3 -11
  2. package/providers/form.mjs +13 -5
  3. package/ui/form/review-app.js +122 -71
  4. package/ui/form/review.html +1 -814
  5. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  6. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  7. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  8. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  9. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  10. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  11. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  12. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  13. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  14. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  15. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  16. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  17. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -182
  18. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  19. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -233
  20. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  21. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -24
  22. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  23. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -67
  24. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -280
  25. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  26. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -280
  27. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  28. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  29. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -55
  30. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  31. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  32. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  33. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -343
  34. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -391
  35. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -166
  36. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  37. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  38. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  39. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -117
  40. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  41. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -312
  42. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  43. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  44. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -115
  45. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -86
  46. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  47. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  48. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  49. package/node_modules/@tomflow/chatloop-extension/README.md +0 -94
  50. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -11
  51. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -141
  52. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -109
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -120
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -180
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -322
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -378
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -54
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -69
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -287
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -23
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  75. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -16
  76. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  77. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  78. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  80. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  81. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -76
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -227
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -254
  92. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  93. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  94. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -93
  95. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  96. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  97. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  98. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  99. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  100. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -220
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -122
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -155
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -185
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -120
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -172
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -165
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -244
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -181
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -147
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -200
  113. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  114. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -18
  115. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -74
  116. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -208
  117. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -40
  118. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  119. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -111
  120. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -67
  121. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -120
  122. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  123. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -133
  124. package/node_modules/@tomflow/chatloop-trace/README.md +0 -105
  125. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  126. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  127. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  128. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  129. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  130. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -265
  131. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -205
  132. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  133. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  134. package/node_modules/ps-list/index.d.ts +0 -76
  135. package/node_modules/ps-list/index.js +0 -366
  136. package/node_modules/ps-list/license +0 -9
  137. package/node_modules/ps-list/package.json +0 -44
  138. package/node_modules/ps-list/readme.md +0 -56
  139. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  140. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,378 +0,0 @@
1
- // Sole executor for a cross-Chat handoff. Worker only schedules/authorizes.
2
- // Never auto-retry a write or a tab creation after the result is uncertain.
3
- const statusNode = document.getElementById("status");
4
- const detailsNode = document.getElementById("details");
5
- const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
6
- function show(status, details) {
7
- statusNode.textContent = status;
8
- detailsNode.textContent = details;
9
- document.body.dataset.result = status === "SUCCESS" ? "success" : "error";
10
- }
11
- async function verifyOldChat(target, summary, mode = "EXPLICIT") {
12
- const [execution] = await chrome.scripting.executeScript({
13
- target: {tabId: target.tabId},
14
- func: (expected, handoffText, handoffMode) => {
15
- if (location.origin !== "https://chatgpt.com" || location.pathname !== expected.page)
16
- throw Error("SOURCE_CHAT_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("SOURCE_MAIN_UNVERIFIED");
22
- const main = mains[0];
23
- const modern = [...main.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
24
- const legacy = [...main.querySelectorAll('[data-message-author-role]')];
25
- const role = n => n.getAttribute("data-message-author-role")
26
- || n.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
27
- const id = n => n?.getAttribute("data-message-id")
28
- || n?.getAttribute("data-chatgpt-search-message-ids")?.trim().split(/\s+/)[0]
29
- || n?.closest('[data-testid^="conversation-turn-"]')?.getAttribute("data-testid");
30
- const rows = modern.length ? modern : legacy;
31
- const user = rows.filter(n => role(n) === "user").at(-1);
32
- const assistant = rows.filter(n => role(n) === "assistant").at(-1);
33
- if ("user:" + id(user) !== expected.userKey
34
- || (assistant ? "assistant:" + id(assistant) : null) !== expected.assistantKey)
35
- throw Error("SOURCE_TURN_CHANGED");
36
- const content = (assistant?.querySelector('.markdown')?.innerText || assistant?.innerText || '').trim();
37
- if (handoffMode === "ERROR") {
38
- // No completed assistant response after the pending user Turn.
39
- // Require an explicit context limit on the *same* visible chat.
40
- const lastUserIndex = rows.findLastIndex(n => role(n) === "user");
41
- if (rows.slice(lastUserIndex + 1).some(n => role(n) === "assistant"))
42
- throw Error("ERROR_HANDOFF_NEW_ASSISTANT_EXISTS");
43
- const contextPattern = /(?:conversation (?:has (?:reached|exceeded) (?:its |the )?(?:maximum|context)|is too long)|context (?:window|length|limit) (?:has been |was )?(?:exceeded|reached)|maximum conversation (?:length|limit) (?:reached|exceeded)|对话(?:上下文|长度)(?:已)?(?:达到|超过)(?:上限|限制)|上下文(?:窗口|长度)(?:已)?(?:达到|超过)(?:上限|限制))/i;
44
- if (![...main.querySelectorAll('[role="alert"],[role="status"],[data-testid="conversation-error"]')]
45
- .some(el => visible(el) && contextPattern.test(el.innerText || el.textContent || '')))
46
- throw Error("CONTEXT_ERROR_NOT_CONFIRMED");
47
- } else if (handoffMode === "EXPLICIT") {
48
- if (!content.endsWith('\n[CHAT_LOOP_STATUS:HANDOFF]')
49
- || content.slice(0, -'[CHAT_LOOP_STATUS:HANDOFF]'.length).trim() !== handoffText)
50
- throw Error("SOURCE_HANDOFF_TEXT_CHANGED");
51
- } else if (handoffMode !== "TIMED" || !content
52
- || /\[CHAT_LOOP_STATUS:(?:DONE|BLOCKED)\]$/.test(content)) {
53
- throw Error("TIMED_HANDOFF_NOT_ELIGIBLE");
54
- }
55
- const scope = assistant?.closest('[data-testid^="conversation-turn-"]')
56
- || assistant?.closest('[data-talvt-turn-state]') || assistant;
57
- const state = scope?.getAttribute?.('data-talvt-turn-state');
58
- if (handoffMode !== "ERROR" && state && state !== "complete") throw Error("SOURCE_TURN_STILL_RUNNING");
59
- if ([...document.querySelectorAll('button[data-testid="stop-button"],button[aria-label="Stop generating"],button[aria-label="停止响应"]')].some(visible)
60
- || [...scope?.querySelectorAll?.('[aria-busy="true"],[data-tool-status="running"]') || []].some(visible))
61
- throw Error("SOURCE_GENERATION_STILL_RUNNING");
62
- if (handoffMode !== "ERROR" && ![...scope.querySelectorAll('button[aria-label="复制"],button[aria-label="Copy"],button[data-testid="copy-turn-action-button"]')].some(visible))
63
- throw Error("SOURCE_NOT_FINAL");
64
- // Last read-only guard before the Action creates any successor Chat:
65
- // an unanswered confirmation in the current assistant Turn wins.
66
- if (handoffMode !== "ERROR") {
67
- const gate = globalThis.ChatLoopTurnObserverV1?.poll?.();
68
- if (gate?.contract !== "chat-loop.turn-observer.v1"
69
- || gate.page !== expected.page
70
- || gate.userKey !== expected.userKey
71
- || gate.assistantKey !== expected.assistantKey
72
- || gate.reason === "WAITING_CHAT_HYDRATION"
73
- || typeof gate.pendingConfirmation !== "boolean")
74
- throw Error("CONFIRMATION_OBSERVER_UNVERIFIED");
75
- if (gate.pendingConfirmation) throw Error("CONFIRMATION_PENDING_DOM");
76
- }
77
- // Timed handoff must not modify the original Chat. Capture a bounded
78
- // read-only evidence snapshot here, not through URL or Worker storage.
79
- if (handoffMode === "TIMED" || handoffMode === "ERROR") {
80
- const entries = rows.map(node => ({role: role(node),
81
- text: (node.querySelector?.('.markdown')?.innerText
82
- || node.innerText || node.textContent || '').trim()}))
83
- .filter(item => (item.role === "user" || item.role === "assistant") && item.text);
84
- const head = entries.find(item => item.role === "user");
85
- if (!head) throw Error("SOURCE_CONTEXT_TOO_SHORT");
86
- const headText = head.text.slice(0, 6000);
87
- const tailText = entries.slice(-24).filter(item => item !== head).map(item =>
88
- (item.role === "user" ? "用户:" : "助手:") + item.text.slice(-3000))
89
- .join("\n\n").slice(-21000);
90
- const excerpt = "【当前可见片段首条用户消息|可能不是原始任务】\n" + headText
91
- + "\n\n【最近轮次证据】\n" + tailText;
92
- if (excerpt.length < 120) throw Error("SOURCE_CONTEXT_TOO_SHORT");
93
- const identity="【来源 Chat】https://chatgpt.com"+expected.page
94
- +(expected.sessionId?"\n【来源 Session】"+expected.sessionId:"")
95
- +(expected.projectId?"\n【项目标识】"+expected.projectId:"")
96
- +(Number.isSafeInteger(expected.generation)?"\n【来源 generation】"+expected.generation:"");
97
- return {ok: true, snapshot: "【交接参考:只读网页片段,可能截断】\n"+identity+"\n"+excerpt
98
- + (handoffMode === "ERROR" ? "\n【中断说明】当前 Chat 明确出现上下文容量错误,最后一条用户消息未收到完整助手回复;任何上轮工具副作用均需先核实,不得盲目重复。" : "")
99
- + "\n【证据边界】DOM可能虚拟化,首条可见消息不保证是原始任务,也不能作为新增批准。此片段不等于完整记录;必须通过实际工具、唯一Context和来源核对任务进展。"};
100
- }
101
- return {ok: true};
102
- }, args: [target, summary, mode]
103
- });
104
- if (execution?.result?.ok !== true) throw Error("SOURCE_HANDOFF_UNVERIFIED");
105
- if (["TIMED", "ERROR"].includes(mode) && (typeof execution.result.snapshot !== "string"
106
- || execution.result.snapshot.length < 120)) throw Error("SOURCE_SNAPSHOT_UNVERIFIED");
107
- return execution.result.snapshot || summary;
108
- }
109
- // Read-only readiness of the new, strictly blank Chat home. Never clear a
110
- // restored human draft, even if its text resembles a historical test prompt.
111
- async function waitForNewChat(tabId) {
112
- // An API promise can stall even if the bounded loop itself is short. The
113
- // timeout races READ-ONLY probes only; it never schedules a second send.
114
- const started = Date.now(), maxWaitMs = 45_000;
115
- const boundedRead = (promise, ms) => Promise.race([
116
- promise.catch(() => null), delay(ms).then(() => null)
117
- ]);
118
- for (let attempt = 0; attempt < 100 && Date.now()-started<maxWaitMs; attempt++) {
119
- const remaining = maxWaitMs-(Date.now()-started);
120
- const tab = await boundedRead(chrome.tabs.get(tabId),Math.min(1500,remaining));
121
- if (tab?.url?.startsWith("https://chatgpt.com/")) {
122
- const [check] = await boundedRead(chrome.scripting.executeScript({target: {tabId}, func: () => {
123
- if (location.origin !== "https://chatgpt.com" || location.pathname !== "/") return false;
124
- const input = document.querySelector('[contenteditable="true"][data-composer-markdown]')
125
- || document.querySelector('#prompt-textarea[contenteditable="true"]');
126
- return !!input?.getClientRects?.().length
127
- && !(input.innerText || input.textContent || "").trim();
128
- }}),Math.min(1500,maxWaitMs-(Date.now()-started))) || [];
129
- if (check?.result === true) return;
130
- }
131
- await delay(Math.min(450,Math.max(0,maxWaitMs-(Date.now()-started))));
132
- }
133
- throw Error("NEW_CHAT_NOT_READY");
134
- }
135
- async function sendHandoffOnce(tabId, text) {
136
- const [dispatch] = await chrome.scripting.executeScript({target: {tabId},
137
- func: async instruction => {
138
- try {
139
- if (location.origin !== "https://chatgpt.com" || location.pathname !== "/")
140
- throw Error("NEW_CHAT_NOT_BLANK");
141
- const input = document.querySelector('[contenteditable="true"][data-composer-markdown]')
142
- || document.querySelector('#prompt-textarea[contenteditable="true"]');
143
- if (!input?.getClientRects?.().length || (input.innerText || '').trim())
144
- throw Error("NEW_CHAT_COMPOSER_NOT_EMPTY");
145
- input.focus();
146
- // The ProseMirror editor may normalize paragraph boundaries after
147
- // execCommand returns. Check its actual rendered state without editing
148
- // or sending again, rather than treating a transient mismatch as proof
149
- // that the whole insertion failed.
150
- const canonical = value => String(value || '').replace(/\s+/g, '');
151
- if (!document.execCommand("insertText", false, instruction))
152
- throw Error("HANDOFF_INPUT_REJECTED");
153
- await new Promise(resolve => setTimeout(resolve, 400));
154
- const expected = canonical(instruction);
155
- let verified = false;
156
- for (let i = 0; i < 30; i++) {
157
- if (location.pathname !== "/") throw Error("NEW_CHAT_CHANGED_DURING_INPUT");
158
- if (canonical(input.innerText) === expected
159
- || canonical(input.textContent) === expected) {
160
- verified = true;
161
- break;
162
- }
163
- await new Promise(resolve => setTimeout(resolve, 120));
164
- }
165
- if (!verified) throw Error("HANDOFF_INPUT_UNVERIFIED");
166
- let button;
167
- for (let i = 0; i < 18; i++) {
168
- button = document.querySelector('button[type="submit"][aria-label="发送"]')
169
- || document.querySelector('button[data-testid="send-button"]')
170
- || document.querySelector('button[data-testid="composer-send-button"]');
171
- if (button && !button.disabled && button.getClientRects().length) break;
172
- await new Promise(resolve => setTimeout(resolve, 120));
173
- }
174
- if (!button || button.disabled || !button.getClientRects().length)
175
- throw Error("HANDOFF_SEND_NOT_READY");
176
- if (location.pathname !== "/") throw Error("NEW_CHAT_CHANGED_BEFORE_SEND");
177
- if (canonical(input.innerText) !== expected && canonical(input.textContent) !== expected)
178
- throw Error("HANDOFF_INPUT_CHANGED_BEFORE_SEND");
179
- button.click();
180
- return {clickedOnce: true};
181
- } catch (error) {return {clickedOnce: false, reason: error.message || "HANDOFF_SEND_ERROR"};}
182
- }, args: [text]
183
- });
184
- if (dispatch?.result?.clickedOnce !== true) throw Error(dispatch?.result?.reason || "HANDOFF_SEND_UNVERIFIED");
185
- // Once clicked, only observe. A missing or ambiguous receipt must BLOCK;
186
- // no second Chat and no retry can be authorized from this Action.
187
- let candidateKey = null, candidateSince = 0;
188
- for (let attempt = 0; attempt < 75; attempt++) {
189
- const tab = await chrome.tabs.get(tabId);
190
- const path = new URL(tab.url || "https://chatgpt.com/").pathname;
191
- if (/^\/c\/[0-9a-f-]{12,}$/i.test(path)) {
192
- const [read] = await chrome.scripting.executeScript({target: {tabId},func: expected => {
193
- const visible = n => Boolean(n?.getClientRects?.().length);
194
- const mains = [...document.querySelectorAll("main")].filter(visible);
195
- if (mains.length !== 1) return null;
196
- const modern = [...mains[0].querySelectorAll(
197
- '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
198
- const rows = modern.length ? modern : [...mains[0].querySelectorAll('[data-message-author-role]')];
199
- const role = n => n.getAttribute('data-message-author-role')
200
- || n.getAttribute('data-chatgpt-search-unit-key')?.split(':').at(-1);
201
- const idOf = n => n.getAttribute('data-message-id')
202
- || n.getAttribute('data-chatgpt-search-message-ids')?.trim().split(/\s+/)[0];
203
- const users = rows.filter(n => role(n) === 'user');
204
- const keys = [...new Set(users.map(idOf).filter(Boolean))];
205
- // The successor was verified to be a blank Chat home. More than one
206
- // user identity after our single click is an ambiguous send, NOT a
207
- // successful Handoff (even if the last bubble matches).
208
- if (keys.length > 1) return {reason:'HANDOFF_DUPLICATE_USER_TURNS'};
209
- if (keys.length !== 1) return null;
210
- const user = users.at(-1), id = idOf(user);
211
- const bubble = user.querySelector?.('[data-search-result-target]')
212
- || user.querySelector?.('[data-user-message-bubble="true"]') || user;
213
- const canonical = v => String(v || '').replace(/\s+/g, '');
214
- return id && id === keys[0]
215
- // A substring match may accept an extra or corrupted user message.
216
- // The sole successor Turn must contain exactly the sent handoff text.
217
- && canonical(bubble.innerText || bubble.textContent)===canonical(expected)
218
- ? {userKey: 'user:' + id} : null;
219
- },args: [text]});
220
- if (read?.result?.reason) throw Error(read.result.reason);
221
- if (read?.result?.userKey) {
222
- if (candidateKey !== read.result.userKey) {
223
- candidateKey = read.result.userKey;
224
- candidateSince = Date.now();
225
- }
226
- // Re-read over a bounded stability window before transferring the
227
- // original Owner, so immediately visible duplicate messages fail.
228
- if (Date.now() - candidateSince >= 900)
229
- return {status: "SENT_CONFIRMED", newTabId: tabId,
230
- newPage: path, newUserKey: read.result.userKey};
231
- }
232
- }
233
- await delay(450);
234
- }
235
- throw Error("NEW_CHAT_SEND_RECEIPT_UNKNOWN");
236
- }
237
- async function run() {
238
- const own = await chrome.tabs.getCurrent();
239
- const params = new URLSearchParams(location.search);
240
- const raw = params.get("tabId") || "";
241
- let token = params.get("token") || "";
242
- let tabId = Number(raw);
243
- if (!own?.id || own.url !== location.href || raw && !/^[1-9][0-9]*$/.test(raw)
244
- || token && !/^[0-9a-f-]{36}$/.test(token)
245
- || token && !raw) throw Error("HANDOFF_ACTION_PARAMETERS_INVALID");
246
- if (!token) {
247
- show("VERIFYING", "手动打开 Handoff:核对已完成的旧 Chat,申请单次新 Chat 交接许可。");
248
- const prepared = await chrome.runtime.sendMessage({
249
- type: "CHAT_LOOP_ACTION_MANUAL_PREPARE_V1", action: "HANDOFF",
250
- ...(raw ? {tabId} : {})
251
- });
252
- if (prepared?.status !== "PREPARED")
253
- throw Error(prepared?.code || "MANUAL_PREPARE_DENIED");
254
- tabId = prepared.tabId;
255
- token = prepared.token;
256
- }
257
- const request = {tabId, token};
258
- const permit = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_TAKE_V1", ...request});
259
- if (permit?.status === "DENIED" && permit.code === "PENDING_CONFIRMATION_DOM") {
260
- // A choice appeared after timed Handoff was reserved. Worker retains
261
- // the same Owner and no new Chat was created; close this stale Action.
262
- await chrome.tabs.remove(own.id);
263
- return;
264
- }
265
- if (permit?.status !== "OK" || permit.action !== "HANDOFF"
266
- || permit.target?.tabId !== request.tabId
267
- || (permit.handoffMode === "EXPLICIT" && typeof permit.text !== "string")
268
- || !["TIMED", "EXPLICIT", "ERROR"].includes(permit.handoffMode))
269
- throw Error("HANDOFF_NOT_AUTHORIZED");
270
- const quota=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
271
- action:'handoff',stage:'preflight'});
272
- if(quota?.status!=='OK') {
273
- await chrome.runtime.sendMessage({type:'CHAT_LOOP_ACTION_RESULT_V1',...request,
274
- result:'UNVERIFIED',reason:quota?.code||'RESOURCE_QUOTA_UNVERIFIED'}).catch(()=>{});
275
- throw Error(quota?.code||'RESOURCE_QUOTA_UNVERIFIED');
276
- }
277
- show("RUNNING", "已领取不可重试的一次性授权,验证旧会话交接信息。");
278
- let result;
279
- let newTab;
280
- try {
281
- const contextPacket = await verifyOldChat(permit.target, permit.text, permit.handoffMode);
282
- const source = await chrome.tabs.get(request.tabId);
283
- if (permit.target.page.startsWith('/g/')) throw Error('PROJECT_HANDOFF_ROUTE_UNVERIFIED');
284
- // Opening a new Chat is itself a side effect; never create another on failure.
285
- newTab = await chrome.tabs.create({url: "https://chatgpt.com/", active: true,
286
- windowId: source.windowId, openerTabId: own.id});
287
- // Chrome may initially report about:blank while the requested home URL loads.
288
- let homeUrlReady=false;
289
- for(let i=0;i<40;i++){
290
- const candidate=await chrome.tabs.get(newTab.id).catch(()=>null);
291
- if(candidate?.url==='https://chatgpt.com/'){homeUrlReady=true;break;}
292
- await new Promise(resolve=>setTimeout(resolve,250));
293
- }
294
- if(!homeUrlReady)throw Error('HANDOFF_HOME_URL_UNVERIFIED');
295
- const registered=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
296
- action:'handoff',stage:'register',tabId:newTab.id});
297
- if(registered?.status!=='OK')throw Error(registered?.code||'RESOURCE_REGISTER_UNVERIFIED');
298
- await waitForNewChat(newTab.id);
299
- // The observer must exist before the first user click on the new home page.
300
- // A successful send without an observer cannot be automatically continued.
301
- let observed;
302
- try { observed = await chrome.tabs.sendMessage(newTab.id,
303
- {type: "CHAT_LOOP_TURN_OBSERVE_V1"}); } catch { /* Reconnect below. */ }
304
- if (observed?.contract !== "chat-loop.turn-observer.v1") {
305
- await chrome.scripting.executeScript({target: {tabId: newTab.id},
306
- files: ["content.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
307
- observed = await chrome.tabs.sendMessage(newTab.id,
308
- {type: "CHAT_LOOP_TURN_OBSERVE_V1"});
309
- }
310
- if (observed?.contract !== "chat-loop.turn-observer.v1")
311
- throw Error("NEW_CHAT_OBSERVER_UNAVAILABLE");
312
- const contextReferences=permit.projectContext
313
- ?"\n\n【已核实的恢复入口|仅引用,不代表新增批准】\n"
314
- +JSON.stringify(permit.projectContext)
315
- +"\n先读取contextPath与taskDocPath,核实当前R/P有效版本、允许工作区和未知副作用;approvalDocPath如有仅是历史批准原文附件,不可替代当前任务有效性判断。"
316
- :"";
317
- const message = "你正在接手上一 Chat 未完成的任务。旧 Chat 的网页历史仍可核实,但当前 Chat 没有其隐式上下文。若为项目任务,先按已授权的项目 Skill 或目标仓库真实入口核实规则、进度和上一轮副作用;不要假定每个项目都有 AGENTS.md 或固定 context 目录,也不要重复未知副作用。\n\n交接资料:\n" + contextPacket + contextReferences
318
- + "\n\n本轮最终回复末行只能输出一个状态标记:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。是否跨 Chat 由扩展决定,不要主动要求 Handoff。";
319
- // The new run capability belongs ONLY in the successor Chat's first
320
- // formal user message. It is not a proof that Worker/Native already
321
- // committed ownership: the recipient must verify CommitProof first.
322
- const managed=permit.contextHandoff;
323
- const resumeCapability=managed
324
- ? "\n\n【Chat Loop Context 恢复凭证|目标 Chat 首消息专用】\n"
325
- + JSON.stringify({projectId:managed.projectId,taskId:managed.taskId,
326
- sessionId:managed.sessionId,attemptId:managed.attemptId,
327
- checkpointId:managed.checkpointId,storeEpoch:managed.storeEpoch,
328
- targetGeneration:managed.targetGeneration,
329
- taskRevision:managed.taskRevision,
330
- bindingRevision:managed.bindingRevision+1,
331
- runRef:managed.nextRunRef,runCredential:managed.nextRunCredential})
332
- + "\n【重要边界】凭证仅用于 Context 写入校验,不能凭它抢占网页 Owner。收到消息后先只读核对"
333
- + " Worker/Native 当前 Chat、Session、generation、原 attempt 和 Context 绑定已提交,"
334
- + "再根据唯一 Checkpoint 与未知副作用决定下一工作项。未确认只能只读,不得重复旧工具或 Handoff。"
335
- : "";
336
- const notice=permit.modelIntent?.id
337
- ? "\n\n【扩展控制回执】本次交接由上一 Chat 的工具意图 "
338
- + permit.modelIntent.id + " 触发;已通过唯一 Action 发送。"
339
- + (permit.modelIntent.reason ? "\n【交接原因(待核实)】"
340
- + permit.modelIntent.reason : "") : "";
341
- const checkpoint=permit.pendingPlan?.id&&typeof permit.pendingPlan.nextPrompt==="string"
342
- ? "\n\n【上一 Chat 暂存的下一步检查点|到期交接覆盖了 Continue】请求 "
343
- + permit.pendingPlan.id + " 原计划:\n"
344
- + permit.pendingPlan.nextPrompt
345
- + "\n【边界】这只是上一轮模型提出的计划,不代表用户新增批准。新 Chat 必须先核实任务状态、项目规则及已发生的副作用,不能盲目重复。"
346
- : "";
347
- // Durable SEND_BEGIN must precede the only possible send call. A lost
348
- // receipt after this point is SEND_UNKNOWN, NEVER NOT_SENT.
349
- if(managed){
350
- const begun=await chrome.runtime.sendMessage({
351
- type:'CHAT_LOOP_HANDOFF_SEND_BEGIN_V1',...request});
352
- if(begun?.status!=='RECORDED')
353
- throw Error(begun?.code||'HANDOFF_SEND_BEGIN_UNVERIFIED');
354
- }
355
- result = await sendHandoffOnce(newTab.id,
356
- message + notice + checkpoint + resumeCapability + (permit.modelTurnNote || ""));
357
- } catch (error) {result = {status: "UNVERIFIED", reason: error.message || "HANDOFF_ERROR"};}
358
- const committed = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
359
- result: result.status, reason: result.reason,
360
- newUserKey: result.newUserKey, newTabId: result.newTabId ?? newTab?.id,
361
- newPage: result.newPage});
362
- if (result.status !== "SENT_CONFIRMED" || committed?.status !== "OK")
363
- throw Error(result.reason || committed?.code || "HANDOFF_TRANSFER_UNVERIFIED");
364
- // The old Chat is closed only after the Worker confirms ownership transfer.
365
- // Its canonical conversation URL remains in ChatGPT history.
366
- const old = await chrome.tabs.get(request.tabId).catch(() => null);
367
- if (old && old.id !== newTab?.id && old.id !== own.id
368
- && old.url === "https://chatgpt.com" + permit.target.page) {
369
- await chrome.tabs.remove(old.id).catch(error => {
370
- console.warn("OLD_CHAT_TAB_CLEANUP_UNVERIFIED", error?.message);
371
- });
372
- }
373
- show("SUCCESS", "新 Chat 已收到交接包;旧 Chat 标签已尝试安全清理。");
374
- await chrome.tabs.remove(own.id);
375
- }
376
- (new URLSearchParams(location.search).has("requestId")
377
- ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("handoff")) : run())
378
- .catch(error => show("BLOCKED", error.message || "HANDOFF_ACTION_FAILED"));
@@ -1,2 +0,0 @@
1
- // Browser Action API root. Actions only import this, not private helpers.
2
- export {queueModelIntent} from './model-intent.js';
@@ -1,54 +0,0 @@
1
- // The only model-driven entrance reuses the two existing formal Action pages.
2
- // It registers a decision; it never edits ChatGPT, creates a new Chat, or sends.
3
- export async function queueModelIntent(action) {
4
- const params = new URLSearchParams(location.search);
5
- const id = params.get('requestId');
6
- if([...params.keys()].length !== 1 || !/^[a-f0-9]{32}$/.test(id||''))
7
- throw Error('INVALID_MODEL_REQUEST');
8
- const own = await chrome.tabs.getCurrent();
9
- if(!own?.id || own.url !== location.href)
10
- throw Error('MODEL_ACTION_TAB_UNVERIFIED');
11
- const host='com.tomflow.chatloop.extension';
12
- const auth = await chrome.runtime.sendNativeMessage(host,{op:'acquire',id,action});
13
- if(auth?.status!=='OK'||auth.id!==id||auth.action!==action
14
- ||typeof auth.nonce!=='string'||!auth.intent)
15
- throw Error(auth?.code||'MODEL_REQUEST_UNVERIFIED');
16
- let outcome;
17
- try {
18
- const query=typeof auth.intent.intentId==='string'||auth.intent.lookup===true;
19
- outcome = await chrome.runtime.sendMessage({
20
- type:query?'CHAT_LOOP_MODEL_INTENT_STATUS_V1':'CHAT_LOOP_MODEL_INTENT_V1',
21
- id, action:action.toUpperCase(),intent:auth.intent,
22
- ...(auth.traceParent?{traceParent:auth.traceParent}:{})
23
- });
24
- if(outcome?.status!==(query?'STATUS':'QUEUED')
25
- || !/^[a-f0-9]{32}$/.test(outcome.intentId||'')
26
- || (query&&auth.intent.intentId&&outcome.intentId!==auth.intent.intentId)
27
- || (!query&&outcome.intentId!==id)
28
- ||outcome.action!==action.toUpperCase())
29
- throw Error(outcome?.code||'MODEL_INTENT_DENIED');
30
- const saved = await chrome.runtime.sendNativeMessage(host,{
31
- op:'complete',id,nonce:auth.nonce,action,status:'OK',
32
- payload:JSON.stringify(outcome)
33
- });
34
- if(saved?.status!=='SAVED'||saved.id!==id)
35
- throw Error(saved?.code||'INTENT_RECEIPT_UNVERIFIED');
36
- await chrome.tabs.remove(own.id);
37
- } catch(e) {
38
- // An already-queued intent is not retried. Native failure is diagnostic only.
39
- try {
40
- const saved=await chrome.runtime.sendNativeMessage(host,{
41
- op:'complete',id,nonce:auth.nonce,action,status:'FAILED',
42
- code:String(e.message||'INTENT_UNVERIFIED').slice(0,120)
43
- });
44
- // The CLI already has a durable failure receipt. Keep the page only
45
- // when that receipt could not be verified; never resubmit the intent.
46
- if(saved?.status==='SAVED'&&saved.id===id) {
47
- const live=await chrome.tabs.getCurrent();
48
- if(live?.id===own.id&&live.url===location.href)
49
- await chrome.tabs.remove(own.id).catch(()=>{});
50
- }
51
- } catch {}
52
- throw e;
53
- }
54
- };
@@ -1,9 +0,0 @@
1
- // Stateless Eye executor: read only a declared text/DOM mode with the same
2
- // trusted Owner/Native admission as the two original Eye pages.
3
- const script=document.currentScript;
4
- const action=script?.dataset?.action;
5
- const mode=script?.dataset?.readMode;
6
- if(!/^chat_[a-z0-9_]+$/.test(action||'')||!['text','dom'].includes(mode))
7
- throw Error('EYE_CAPABILITY_INVALID');
8
- void globalThis.ChatLoopActionCommonV1.runReadAction(
9
- mode,mode==='text'?250:1000,action);
@@ -1,20 +0,0 @@
1
- // Reload Action: request reloading this extension, not other tabs/extensions.
2
- (() => {
3
- const {show, fail, requireOwnTab, machineBinding, machineResult, machineFailure} = globalThis.ChatLoopActionCommonV1;
4
- async function run() {
5
- const machine = await machineBinding("reload");
6
- const own = requireOwnTab(await chrome.tabs.getCurrent());
7
- show("RELOADING", "正在刷新 Chat Loop 扩展...");
8
- // Save an ACCEPTED-but-unverified receipt before reload destroys this page.
9
- if(machine)await machineResult(machine,"ACCEPTED");
10
- const response = await chrome.runtime.sendMessage({
11
- type: "CHAT_LOOP_EYE_RELOAD_V1", tabId: own.id
12
- });
13
- if (response?.status !== "ACCEPTED") throw Error("RELOAD_UNVERIFIED");
14
- }
15
- run().catch(async error => {
16
- await machineFailure("reload",error);
17
- fail(error.message || "UNEXPECTED_ERROR",
18
- "操作未完成;动作页已保留,未对其他 ChatGPT 标签页进行操作。");
19
- });
20
- })();
@@ -1,69 +0,0 @@
1
- // Screenshot Action: capture only the selected ChatGPT tab; wait for download completion.
2
- (() => {
3
- const {show, fail, findTarget, done, requireOwnTab,
4
- machineBinding, machineTarget, machineResult, machineFailure} = globalThis.ChatLoopActionCommonV1;
5
- async function saveScreenshot(tab,machine) {
6
- await chrome.windows.update(tab.windowId, {focused: true});
7
- await chrome.tabs.update(tab.id, {active: true});
8
- // captureVisibleTab may otherwise return a stale compositor frame from an
9
- // unfocused window even when tabs.query already reports the requested tab.
10
- const [paint] = await chrome.scripting.executeScript({target: {tabId: tab.id},
11
- func: async () => {
12
- await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
13
- return {visible: document.visibilityState === "visible", url: location.href};
14
- }});
15
- if (paint?.result?.visible !== true || paint.result.url !== tab.url)
16
- throw Error("TARGET_PAINT_UNVERIFIED");
17
- await new Promise(resolve => setTimeout(resolve, 600));
18
- const [active] = await chrome.tabs.query({windowId: tab.windowId, active: true});
19
- if (active?.id !== tab.id) throw Error("TARGET_NOT_VISIBLE");
20
- const current = await chrome.tabs.get(tab.id);
21
- if (current.url !== tab.url) throw Error("TARGET_CHANGED_BEFORE_CAPTURE");
22
- const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {format: "png"});
23
- if (!dataUrl?.startsWith("data:image/png;base64,")) throw Error("CAPTURE_FAILED");
24
- if(machine) { await machineResult(machine,dataUrl.slice("data:image/png;base64,".length)); return; }
25
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
26
- const filename = "ChatLoop/eye/chat-" + tab.id + "-" + stamp + ".png";
27
- const downloadId = await chrome.downloads.download({
28
- url: dataUrl, filename, saveAs: false, conflictAction: "uniquify"
29
- });
30
- if (!Number.isInteger(downloadId)) throw Error("DOWNLOAD_NOT_STARTED");
31
- await new Promise((resolve, reject) => {
32
- let settled = false;
33
- const timer = setTimeout(() => finish("DOWNLOAD_TIMEOUT"), 30000);
34
- function finish(error) {
35
- if (settled) return;
36
- settled = true;
37
- clearTimeout(timer);
38
- chrome.downloads.onChanged.removeListener(onChanged);
39
- if (error) reject(Error(error));
40
- else resolve();
41
- }
42
- function onChanged(delta) {
43
- if (delta.id !== downloadId) return;
44
- if (delta.error?.current) return finish("DOWNLOAD_FAILED: " + delta.error.current);
45
- if (delta.state?.current === "complete") return finish();
46
- if (delta.state?.current === "interrupted") return finish("DOWNLOAD_INTERRUPTED");
47
- }
48
- chrome.downloads.onChanged.addListener(onChanged);
49
- void chrome.downloads.search({id: downloadId}).then(items => {
50
- if (items[0]?.state === "complete") finish();
51
- if (items[0]?.state === "interrupted") finish("DOWNLOAD_INTERRUPTED");
52
- }).catch(() => finish("DOWNLOAD_STATUS_UNVERIFIED"));
53
- });
54
- }
55
- let machine;
56
- async function run() {
57
- machine = await machineBinding("chat_screenshot");
58
- const own = requireOwnTab(await chrome.tabs.getCurrent());
59
- const target = machine ? await machineTarget(machine) : await findTarget(own);
60
- show("RUNNING", "screenshot → ChatGPT tab " + target.id);
61
- await saveScreenshot(target,machine);
62
- await done(own, "screenshot", target);
63
- }
64
- run().catch(async error => {
65
- await machineFailure("chat_screenshot",error);
66
- fail(error.message || "UNEXPECTED_ERROR",
67
- "操作未完成;动作页已保留,未对其他 ChatGPT 标签页进行操作。");
68
- });
69
- })();