@tomflow/chatloop-extension 0.3.84 → 0.4.0

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 (54) hide show
  1. package/README.md +74 -73
  2. package/actions.generated.mjs +11 -0
  3. package/bin/cli.mjs +22 -24
  4. package/bin/native-host.mjs +14 -5
  5. package/capabilities/chat_dom.mjs +1 -0
  6. package/capabilities/chat_screenshot.mjs +1 -0
  7. package/capabilities/chat_text.mjs +1 -0
  8. package/capabilities/clean.mjs +1 -0
  9. package/capabilities/continue.mjs +1 -0
  10. package/capabilities/handoff.mjs +1 -0
  11. package/capabilities/reload.mjs +1 -0
  12. package/capabilities/start.mjs +1 -0
  13. package/capabilities/status.mjs +1 -0
  14. package/extension/actions/common.js +14 -3
  15. package/extension/actions/continue.js +1 -1
  16. package/extension/actions/handoff.js +5 -3
  17. package/extension/actions/index.js +2 -0
  18. package/extension/actions/read-mode.js +9 -0
  19. package/extension/actions/start.js +1 -1
  20. package/extension/background.js +16 -2202
  21. package/extension/loop/action-catalog.generated.js +2 -0
  22. package/extension/loop/api-aspect.generated.js +192 -0
  23. package/extension/loop/core.js +81 -3
  24. package/extension/loop/index.js +34 -0
  25. package/extension/loop/observer-approval.js +227 -0
  26. package/extension/loop/observer-inspect.js +144 -0
  27. package/extension/loop/observer-poll.js +171 -0
  28. package/extension/loop/observer-recovery.js +109 -0
  29. package/extension/loop/observer.js +27 -630
  30. package/extension/loop/resources.js +8 -1
  31. package/extension/manifest.json +6 -2
  32. package/extension/worker/action-result.js +136 -0
  33. package/extension/worker/action-take.js +220 -0
  34. package/extension/worker/admission.js +122 -0
  35. package/extension/worker/adopt-prepare.js +155 -0
  36. package/extension/worker/adopt-recovery.js +185 -0
  37. package/extension/worker/adopt-result.js +120 -0
  38. package/extension/worker/bootstrap.js +172 -0
  39. package/extension/worker/manual.js +165 -0
  40. package/extension/worker/readiness.js +242 -0
  41. package/extension/worker/router.js +150 -0
  42. package/extension/worker/scheduler.js +147 -0
  43. package/extension/worker/turn-failure.js +197 -0
  44. package/extension/worker/turn-finished.js +200 -0
  45. package/index.mjs +62 -0
  46. package/lib/action-routing.mjs +18 -0
  47. package/lib/api-aspect.mjs +190 -0
  48. package/lib/bridge.mjs +26 -7
  49. package/lib/context-binding.mjs +6 -1
  50. package/lib/context-ipc.mjs +44 -2
  51. package/lib/owner-evidence.mjs +67 -0
  52. package/lib/session-file.mjs +20 -8
  53. package/package.json +13 -3
  54. package/scripts/build-actions.mjs +133 -0
@@ -38,135 +38,19 @@
38
38
  }
39
39
  function fingerprint(text) {
40
40
  let hash = 2166136261;
41
- for (const char of text) {
42
- hash = Math.imul(hash ^ char.charCodeAt(0), 16777619);
41
+ // Hash every UTF-16 code unit: for...of exposes whole Unicode code points
42
+ // and charCodeAt(0) would ignore the LOW surrogate of different emoji.
43
+ for (let i=0;i<text.length;i++) {
44
+ hash = Math.imul(hash ^ text.charCodeAt(i), 16777619);
43
45
  }
44
46
  return (hash >>> 0).toString(16) + ":" + text.length;
45
47
  }
46
- function inspect() {
47
- const path = conversationPath();
48
- if (!path) return {path: "", unavailable: "CHAT_NOT_IDENTIFIED"};
49
- // ChatGPT can keep multiple conversation <main> nodes in the DOM;
50
- // only the currently rendered one may supply Turn identity or status.
51
- const mains = [...document.querySelectorAll("main")].filter(visible);
52
- if (mains.length !== 1) return {path,
53
- unavailable: mains.length ? "MAIN_AMBIGUOUS" : "MAIN_UNAVAILABLE"};
54
- const main = mains[0];
55
- const legacy = [...main.querySelectorAll(
56
- '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
57
- const roles = legacy.length ? legacy : [...main.querySelectorAll(
58
- '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
59
- const roleOf = el => el.getAttribute?.("data-message-author-role")
60
- || el.getAttribute?.("data-chatgpt-search-unit-key")?.split(":").at(-1);
61
- const userIndex = roles.findLastIndex(el => roleOf(el) === "user");
62
- const lastUser = userIndex >= 0 ? roles[userIndex] : null;
63
- const afterUser = roles.slice(userIndex + 1).filter(el => roleOf(el) === "assistant");
64
- const lastAssistant = afterUser.at(-1) || null;
65
- const lastHistoricAssistant = roles.filter(el => roleOf(el) === "assistant").at(-1);
66
- const userKey = messageId(lastUser, "user");
67
- const assistantKey = messageId(lastAssistant, "assistant");
68
- const historicAssistantKey = messageId(lastHistoricAssistant, "assistant");
69
- // The immediately preceding assistant before a NEW user Turn is the
70
- // only eligible confirmation anchor. Historical interactive cards do
71
- // not block a later assistant Turn or authorize a new action.
72
- const priorIndex = roles.findLastIndex((el, i) =>
73
- i < userIndex && roleOf(el) === "assistant");
74
- const priorAssistant = priorIndex >= 0 ? roles[priorIndex] : null;
75
- const priorAssistantKey = messageId(priorAssistant, "assistant");
76
- const priorUser = priorIndex > 0 ? roles.slice(0,priorIndex)
77
- .filter(el=>roleOf(el)==="user").at(-1) : null;
78
- const priorAssistantUserKey = messageId(priorUser,"user");
79
- const directReplyAfterPriorAssistant = priorIndex>=0
80
- && !roles.slice(priorIndex+1,userIndex).some(el=>roleOf(el)==="user");
81
- const scope = lastAssistant?.closest?.('[data-testid^="conversation-turn-"]')
82
- || lastAssistant?.closest?.('[data-talvt-turn-state]') || lastAssistant;
83
- const reply = lastAssistant?.querySelector?.(".markdown") || lastAssistant;
84
- const text = (reply?.innerText ?? reply?.textContent ?? "").trim();
85
- // A Chat Loop confirmation is a REAL actionable choice surface in the
86
- // latest assistant Turn, never a form elsewhere on the page. Disabled
87
- // Submit still means pending: no user message has yet been submitted.
88
- const controls = [...scope?.querySelectorAll?.(
89
- '[role="radiogroup"],[role="radio"],input[type="radio"],' +
90
- 'select,[role="combobox"],textarea,[role="textbox"],' +
91
- 'input[type="checkbox"],[role="checkbox"]') || []];
92
- const submit = [...scope?.querySelectorAll?.('button') || []].some(button =>
93
- visible(button) && /(?:提交|确认|submit|confirm)/i.test(
94
- (button.innerText || button.textContent ||
95
- button.getAttribute?.("aria-label") || "").trim()));
96
- const labels = (scope?.innerText || scope?.textContent || "").slice(-2000);
97
- const pendingConfirmation = Boolean(lastAssistant && submit
98
- && controls.some(visible)
99
- && /(?:确认|修改|不通过|拒绝|自定义|approval|revise|reject|choice)/i.test(labels));
100
- const stop = [...document.querySelectorAll(
101
- 'button[data-testid="stop-button"],button[aria-label="Stop generating"],' +
102
- 'button[aria-label="Stop"],button[aria-label="停止生成"],' +
103
- 'button[aria-label="停止响应"]')].some(visible);
104
- const busy = afterUser.some(node => {
105
- const part = node.closest?.('[data-testid^="conversation-turn-"]')
106
- || node.closest?.('[data-talvt-turn-state]') || node;
107
- return [...part.querySelectorAll?.('[aria-busy="true"],[data-tool-status="running"],' +
108
- '[data-state="running"],[data-testid="tool-running"]') || []].some(visible);
109
- });
110
- const toolParts = afterUser.flatMap(node => {
111
- const part = node.closest?.('[data-testid^="conversation-turn-"]')
112
- || node.closest?.('[data-talvt-turn-state]') || node;
113
- return [...part.querySelectorAll?.('[data-testid*="tool"],[data-tool-status]') || []];
114
- });
115
- const toolUnknown = toolParts.some(el => {
116
- if (!visible(el)) return false;
117
- if (el.matches?.('[data-tool-status="running"],[data-testid="tool-running"]')) {
118
- return false;
119
- }
120
- const status = el.getAttribute?.("data-tool-status")
121
- || el.getAttribute?.("data-state") || "";
122
- // A failed/cancelled tool call can be terminal as a *tool result* while
123
- // the assistant may continue and finish its own Turn. Page-level errors
124
- // are handled separately by snap.fatal; never equate tool failure to
125
- // a completed assistant reply.
126
- return !/^(done|complete|completed|success|succeeded|finished|failed|error|cancelled|canceled)$/i.test(status)
127
- && !el.matches?.('[data-testid*="tool-completed"],[data-testid*="tool-finished"]');
128
- });
129
- const editor = document.querySelector(
130
- '#prompt-textarea[contenteditable="true"],' +
131
- '[data-testid="composer-input"][contenteditable="true"],' +
132
- '[contenteditable="true"][data-composer-markdown],' +
133
- '[contenteditable="true"][data-placeholder]');
134
- const composerReady = visible(editor) && !editor.closest?.('[aria-disabled="true"]');
135
- const copyAction = scope && [...scope.querySelectorAll?.(
136
- 'button[data-testid="copy-turn-action-button"],' +
137
- 'button[aria-label="Copy"],button[aria-label="Copy response"],' +
138
- 'button[aria-label="复制"],button[aria-label="复制回复"]') || []].some(visible);
139
- // A visible interruption banner is not a completed assistant Turn, even
140
- // when a partial reply has Copy and no Stop button.
141
- const errorPattern = /unknown error|something went wrong|an error occurred|unable to load|connection (?:lost|interrupted)|waiting for (?:full|complete) response|发生错误|出错了|请求失败|网络错误|连接已中断|正在等待完整答复/i;
142
- const errorNodes = [...main.querySelectorAll(
143
- '[role="alert"],[role="status"],[data-testid="conversation-error"],' +
144
- '[data-testid*="connection-status"]')].filter(visible);
145
- // Only explicit conversation/context exhaustion is eligible for error Handoff.
146
- // Generic Unknown error is never evidence of a capacity limit.
147
- const contextLimitPattern = /(?: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;
148
- const contextLimit = errorNodes.some(el => contextLimitPattern.test(el.innerText ?? el.textContent ?? ""));
149
- // An anti-bot/security challenge is not an ordinary generation failure.
150
- // A visible native Retry is NOT permission to automate bypass attempts.
151
- const securityChallenge = errorNodes.some(el =>
152
- /\bcloudflare_challenge\b/i.test(el.innerText ?? el.textContent ?? ""));
153
- const fatal = contextLimit || securityChallenge || errorNodes.some(el =>
154
- errorPattern.test(el.innerText ?? el.textContent ?? ""));
155
- const retryAvailable = !contextLimit && !securityChallenge && errorNodes.some(el =>
156
- [...el.querySelectorAll?.('button') || []].some(button => visible(button)
157
- && /^(?:retry|try again|重试|再试一次)$/i.test(
158
- (button.innerText || button.textContent || button.getAttribute?.('aria-label') || '').trim())));
159
- const dialog = [...document.querySelectorAll(
160
- '[role="dialog"][aria-modal="true"],dialog[open]')].some(visible);
161
- const turnState = scope?.getAttribute?.("data-talvt-turn-state") || null;
162
- return {path, userKey, assistantKey, historicAssistantKey, priorAssistantKey,
163
- priorAssistantUserKey, directReplyAfterPriorAssistant,
164
- pendingConfirmation, text,
165
- hasUser: Boolean(lastUser), hasAssistant: Boolean(lastAssistant),
166
- stop, busy, toolUnknown, turnState, composerReady, copyAction,
167
- fatal, errorReason: securityChallenge ? "SECURITY_CHALLENGE"
168
- : contextLimit ? "CONTEXT_LIMIT" : "PAGE_ERROR", retryAvailable, dialog};
169
- }
48
+ // Formal approval and repair are two independent evidence consumers, but
49
+ // both must read the ONE visible Chat, not merge hidden/virtualized mains.
50
+ // Keep this read-only snapshot separate from the Turn polling state machine.
51
+ const {activeEvidenceConversation,inspect}=
52
+ globalThis.ChatLoopObserverInspectV1({conversationPath,visible,messageId});
53
+
170
54
  function emit(status, reason, snap, event = null) {
171
55
  if (event) session.emittedCount += 1;
172
56
  state = {contract: CONTRACT, status, reason, page: snap.path || null,
@@ -202,170 +86,8 @@
202
86
  session.candidate = "";
203
87
  session.stableSince = 0;
204
88
  }
205
- function poll() {
206
- try {
207
- const snap = inspect();
208
- if (!snap.path) {
209
- // Preserve a fresh homepage submit, but discard stale submit intent
210
- // when leaving an already identified conversation.
211
- if (session.path) session.firstSendSeen = false;
212
- session.path = "";
213
- session.sawHomepage = true;
214
- session.attaching = false;
215
- session.attachingFirstTurn = false;
216
- resetCandidate();
217
- return emit("UNKNOWN", snap.unavailable, snap);
218
- }
219
- if (snap.unavailable || snap.hasUser && !snap.userKey) {
220
- resetCandidate();
221
- return emit("UNKNOWN", snap.unavailable || "USER_ID_MISSING", snap);
222
- }
223
- if (snap.path !== session.path) {
224
- const cameFromAnotherPage = Boolean(session.path) || session.sawHomepage;
225
- const recentSend = !session.path && session.firstSendSeen
226
- && Date.now() - session.firstSendAt <= 30000;
227
- const firstTurn = recentSend && Boolean(snap.userKey);
228
- session.firstSendSeen = false;
229
- session.sawHomepage = false;
230
- const previousUser = state.userKey || null;
231
- session.path = snap.path;
232
- session.baselineUser = firstTurn ? null : snap.userKey;
233
- session.baselineAssistant = firstTurn ? null : snap.historicAssistantKey;
234
- session.pendingUser = firstTurn ? snap.userKey : null;
235
- session.completedUser = null;
236
- resetCandidate();
237
- session.attachingFirstTurn = recentSend && !snap.userKey;
238
- // Cold content-script startup can precede historical message hydration.
239
- // An empty /c/ route is not proof the conversation has no history.
240
- session.attaching = !recentSend && (cameFromAnotherPage || !snap.userKey);
241
- session.priorUser = cameFromAnotherPage ? previousUser : null;
242
- session.attachSignature = "";
243
- session.attachSince = 0;
244
- if (firstTurn) return emit("RUNNING", "FIRST_CHAT_TURN_SUBMITTED", snap);
245
- if (session.attachingFirstTurn) {
246
- session.baselineUser = null;
247
- session.baselineAssistant = null;
248
- return emit("RUNNING", "WAITING_FIRST_USER", snap);
249
- }
250
- if (session.attaching) {
251
- session.baselineUser = null;
252
- session.baselineAssistant = null;
253
- return emit("UNKNOWN", "ATTACHING_CHAT", snap);
254
- }
255
- return emit(snap.stop || snap.busy ? "UNKNOWN" : "IDLE",
256
- snap.stop || snap.busy ? "ATTACHED_MID_TURN" : "BASELINE_ESTABLISHED", snap);
257
- }
258
-
259
- if (session.attachingFirstTurn) {
260
- if (Date.now() - session.firstSendAt > 30000) {
261
- session.firstSendSeen = false;
262
- session.attachingFirstTurn = false;
263
- session.attaching = true;
264
- return emit("UNKNOWN", "FIRST_USER_NOT_CONFIRMED", snap);
265
- }
266
- if (!snap.userKey) return emit("RUNNING", "WAITING_FIRST_USER", snap);
267
- session.firstSendSeen = false;
268
- session.attachingFirstTurn = false;
269
- session.pendingUser = snap.userKey;
270
- return emit("RUNNING", "FIRST_CHAT_TURN_SUBMITTED", snap);
271
- }
272
- if (session.attaching) {
273
- if (!snap.userKey) return emit("UNKNOWN", "WAITING_CHAT_HYDRATION", snap);
274
- if (session.priorUser && snap.userKey === session.priorUser) {
275
- session.attachSignature = "";
276
- return emit("UNKNOWN", "STALE_PREVIOUS_CHAT_DOM", snap);
277
- }
278
- if (snap.stop || snap.busy || snap.turnState && snap.turnState !== "complete") {
279
- session.attachSignature = "";
280
- return emit("UNKNOWN", "ATTACHED_MID_TURN", snap);
281
- }
282
- if (!snap.composerReady || snap.hasAssistant && !snap.assistantKey) {
283
- session.attachSignature = "";
284
- return emit("UNKNOWN", "ATTACHING_CHAT", snap);
285
- }
286
- const signature = snap.userKey + "|" + (snap.historicAssistantKey || "");
287
- if (signature !== session.attachSignature) {
288
- session.attachSignature = signature;
289
- session.attachSince = Date.now();
290
- return emit("UNKNOWN", "ATTACHING_CHAT", snap);
291
- }
292
- if (Date.now() - session.attachSince < STABLE_MS) {
293
- return emit("UNKNOWN", "WAITING_CHAT_HYDRATION", snap);
294
- }
295
- session.attaching = false;
296
- session.priorUser = null;
297
- session.baselineUser = snap.userKey;
298
- session.baselineAssistant = snap.historicAssistantKey;
299
- session.pendingUser = null;
300
- return emit("IDLE", "BASELINE_ESTABLISHED", snap);
301
- }
302
- if (snap.fatal || snap.dialog) {
303
- resetCandidate();
304
- // A visible page failure must reach the owner, not merely update the
305
- // content-script's local status. Report once for the specific pending
306
- // user Turn; Worker independently verifies the same error twice.
307
- if (snap.fatal && snap.userKey && snap.userKey !== session.completedUser
308
- && (snap.userKey === session.pendingUser
309
- || session.baselineUser && snap.userKey !== session.baselineUser)
310
- && session.reportedErrorUser !== snap.userKey) {
311
- session.reportedErrorUser = snap.userKey;
312
- void Promise.resolve(chrome.runtime.sendMessage({
313
- type: "CHAT_LOOP_TURN_BLOCKED_V1", page: snap.path,
314
- userKey: snap.userKey, reason: snap.errorReason,
315
- retryAvailable: snap.retryAvailable === true
316
- })).catch(() => {});
317
- }
318
- return emit(snap.fatal ? "BLOCKED" : "UNKNOWN",
319
- snap.fatal ? snap.errorReason : "MODAL_PRESENT", snap);
320
- }
321
- if (!snap.userKey || snap.userKey === session.baselineUser
322
- && session.pendingUser === null) {
323
- return emit("IDLE", "NO_NEW_USER_TURN", snap);
324
- }
325
- if (snap.userKey === session.completedUser) {
326
- return emit("IDLE", "TURN_ALREADY_EMITTED", snap);
327
- }
328
- if (snap.userKey !== session.pendingUser) {
329
- if (!session.firstTurnAt) session.firstTurnAt = Date.now();
330
- session.pendingUser = snap.userKey;
331
- session.candidate = "";
332
- session.stableSince = 0;
333
- }
334
- if (snap.hasAssistant && !snap.assistantKey) {
335
- resetCandidate();
336
- return emit("UNKNOWN", "ASSISTANT_ID_MISSING", snap);
337
- }
338
- if (!snap.assistantKey || snap.assistantKey === session.baselineAssistant) {
339
- return emit("RUNNING", "WAITING_FOR_NEW_ASSISTANT", snap);
340
- }
341
- if (snap.stop || snap.busy || snap.turnState && snap.turnState !== "complete") {
342
- session.candidate = "";
343
- return emit("RUNNING", snap.busy ? "TOOL_OR_ASSISTANT_BUSY" : "STOP_BUTTON_PRESENT", snap);
344
- }
345
- if (snap.toolUnknown) {
346
- session.candidate = "";
347
- return emit("UNKNOWN", "TOOL_COMPLETION_UNVERIFIED", snap);
348
- }
349
- if (!snap.composerReady || !snap.copyAction || !snap.text) {
350
- session.candidate = "";
351
- return emit("UNKNOWN", "FINAL_UI_EVIDENCE_MISSING", snap);
352
- }
353
- const signature = snap.userKey + "|" + snap.assistantKey + "|" + fingerprint(snap.text);
354
- if (signature !== session.candidate) {
355
- session.candidate = signature;
356
- session.stableSince = Date.now();
357
- return emit("RUNNING", "ANSWER_NOT_YET_STABLE", snap);
358
- }
359
- if (Date.now() - session.stableSince < STABLE_MS) {
360
- return emit("RUNNING", "WAITING_FOR_STABILITY", snap);
361
- }
362
- session.completedUser = snap.userKey;
363
- return emit("TURN_FINISHED", "EVIDENCE_CONFIRMED", snap, true);
364
- } catch (error) {
365
- resetCandidate();
366
- return emit("UNKNOWN", "OBSERVER_EXCEPTION", {path: session.path});
367
- }
368
- }
89
+ const poll=globalThis.ChatLoopObserverPollV1({session,inspect,emit,
90
+ resetCandidate,fingerprint,STABLE_MS,getState:()=>state});
369
91
  function recordFirstChatSubmission(event) {
370
92
  if (!event?.target?.closest) return;
371
93
  const fromHome = !conversationPath() && !session.path;
@@ -398,342 +120,17 @@
398
120
  globalThis.ChatLoopTurnObserverV1 = Object.freeze({
399
121
  poll, read: () => ({...state})
400
122
  });
401
- chrome.runtime.onMessage.addListener((message, _sender, reply) => {
402
- if (message?.type === "CHAT_LOOP_TURN_RETRY_MONITOR_V1") {
403
- const snap = inspect();
404
- if (snap.path !== message.page || snap.userKey !== message.userKey
405
- || session.reportedErrorUser !== message.userKey
406
- || session.completedUser === message.userKey) {
407
- reply({contract: CONTRACT, status: "UNVERIFIED", reason: "RETRY_OWNER_CHANGED"});
408
- return false;
409
- }
410
- session.reportedErrorUser = null;
411
- reply({contract: CONTRACT, status: "REARMED", userKey: snap.userKey});
412
- // Re-read after the Worker has committed WAITING_REPLY; if the same red
413
- // error is still visible this is the second failure, not a new Continue.
414
- void Promise.resolve().then(poll);
415
- return false;
416
- }
417
- if (message?.type === "CHAT_LOOP_TURN_RESUME_V1") {
418
- // Rebind only the exact Worker-owned Turn after Extension reload.
419
- // A dedicated baseline-only mode never reports an already-completed
420
- // pre-adoption assistant as a new execution Turn.
421
- const snap = inspect();
422
- if (!snap.path || snap.unavailable || snap.path !== message.page
423
- || !/^user:[^\s]{8,}$/.test(message.userKey || "")
424
- || snap.userKey !== message.userKey
425
- || message.assistantKey && !/^assistant:[^\s]{8,}$/.test(message.assistantKey)) {
426
- reply({contract: CONTRACT, status: "UNVERIFIED", reason: "RESUME_IDENTITY_MISMATCH"});
427
- return false;
428
- }
429
- // The Worker can still be WAITING_REPLY after our completion report was
430
- // lost (e.g. MV3 worker suspension). Only that Worker-owned exact Turn
431
- // may request a new stable read. Never replay on ordinary DOM polling.
432
- if (session.pendingUser === message.userKey && !session.attaching
433
- && session.completedUser !== message.userKey && message.baselineOnly!==true) {
434
- reply({contract: CONTRACT, status: "ALREADY_MONITORING"});
435
- return false;
436
- }
437
- if(message.baselineOnly===true &&
438
- (!message.assistantKey || snap.assistantKey!==message.assistantKey
439
- || snap.stop||snap.busy||snap.pendingConfirmation||!snap.copyAction)){
440
- reply({contract:CONTRACT,status:"UNVERIFIED",reason:"ADOPT_BASELINE_UNVERIFIED"});
441
- return false;
442
- }
443
- session.path = snap.path;
444
- session.sawHomepage = false;
445
- session.attaching = false;
446
- session.attachingFirstTurn = false;
447
- session.firstSendSeen = false;
448
- session.priorUser = null;
449
- session.baselineUser = message.baselineOnly===true ? message.userKey : null;
450
- session.baselineAssistant = message.assistantKey || null;
451
- session.pendingUser = message.baselineOnly===true ? null : message.userKey;
452
- session.completedUser = message.baselineOnly===true ? message.userKey : null;
453
- session.firstTurnAt = Number.isSafeInteger(message.startedAt)
454
- && message.startedAt > 0 ? message.startedAt : Date.now();
455
- session.attachSignature = "";
456
- resetCandidate();
457
- const observation = poll();
458
- reply({contract: CONTRACT, status: "RESUMED",
459
- observation: observation.status, reason: observation.reason,
460
- userKey: observation.userKey,
461
- ...(message.baselineOnly===true?{baselineOnly:true}:{})});
462
- return false;
463
- }
464
- if (message?.type === "CHAT_LOOP_REPAIR_EVIDENCE_V1") {
465
- // Read-only proof of a NEW repair request in the EXACT Chat whose
466
- // previous assistant finished with machine DONE. Not a new R/P approval.
467
- const path=conversationPath();
468
- const mains=[...document.querySelectorAll("main")].filter(visible);
469
- const fail=reason=>reply({contract:CONTRACT,status:"UNVERIFIED",reason});
470
- if(!path||mains.length!==1){fail("REPAIR_CHAT_UNVERIFIED");return false;}
471
- const main=mains[0];
472
- const legacy=[...main.querySelectorAll(
473
- '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
474
- const nodes=legacy.length?legacy:[...main.querySelectorAll(
475
- '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
476
- const role=el=>el.getAttribute("data-message-author-role")
477
- ||el.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
478
- const userIdx=nodes.findLastIndex(el=>role(el)==="user");
479
- if(userIdx<1||role(nodes[userIdx-1])!=="assistant"){
480
- fail("REPAIR_SEQUENCE_UNVERIFIED");return false;
481
- }
482
- const text=el=>(el.querySelector?.(".markdown")?.innerText
483
- ||el.innerText||el.textContent||"").trim();
484
- const lastUser=nodes[userIdx],priorAssistant=nodes[userIdx-1];
485
- const userText=text(lastUser).replace(/\s+/g," ");
486
- if(userText.length<4||userText.length>2000
487
- ||!/(?:修复|修正|返工|修改|补完|不通过|重新做|继续完成|改好|fix|repair|rework|correct)/i.test(userText)
488
- ||/(?:不要|不用|无需|拒绝).{0,8}(?:修复|修改|继续|fix|repair)/i.test(userText)
489
- ||!/\[CHAT_LOOP_STATUS:DONE\]\s*$/.test(text(priorAssistant))){
490
- fail("REPAIR_EXPLICIT_INTENT_NOT_FOUND");return false;
491
- }
492
- const snap=inspect(),userKey=messageId(lastUser,"user"),
493
- doneAssistantKey=messageId(priorAssistant,"assistant");
494
- const requestedId=typeof message.explicitChatId==="string"
495
- ?message.explicitChatId.toLowerCase():null;
496
- const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
497
- if(requestedId&&requestedId!==currentId){
498
- fail("REPAIR_CHAT_ID_CHANGED");return false;
499
- }
500
- if(!userKey||snap.path!==path||snap.userKey!==userKey
501
- ||snap.fatal||snap.dialog||snap.toolUnknown
502
- ||!(snap.stop||snap.busy||requestedId
503
- &&!snap.pendingConfirmation&&snap.composerReady)){
504
- fail("REPAIR_LAST_USER_UNVERIFIED");return false;
505
- }
506
- reply({contract:CONTRACT,status:"VERIFIED",page:path,
507
- userKey,userText,priorDoneAssistantKey:doneAssistantKey});
508
- return false;
509
- }
510
- if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
511
- // Read-only, fail-closed two-stage approval proof for same-Chat adoption.
512
- // An explicit model assertion or a copied task Context is never evidence.
513
- const path = conversationPath();
514
- const mains = [...document.querySelectorAll("main")].filter(visible);
515
- const fail = reason => reply({contract: CONTRACT, status:"UNVERIFIED",reason});
516
- if (!path || mains.length !== 1) {
517
- fail("APPROVAL_CHAT_UNVERIFIED");return false;
518
- }
519
- const main=mains[0];
520
- const legacy=[...main.querySelectorAll(
521
- '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
522
- const nodes=legacy.length?legacy:[...main.querySelectorAll(
523
- '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
524
- const role=node=>node.getAttribute("data-message-author-role")
525
- ||node.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
526
- const rows=nodes.map(el=>({el,role:role(el)}))
527
- .filter(x=>["user","assistant"].includes(x.role));
528
- const textOf=x=>(x.el.querySelector?.(".markdown")?.innerText
529
- ||x.el.innerText||x.el.textContent||"").trim();
530
- const confirms=(value,type)=>{
531
- const line=value.replace(/\s+/g," ").trim();
532
- if(!line||line.length>500)return false;
533
- // Native R/P review controls send two explicit, task-scoped fields:
534
- // "TASK|R2-ISSUE:<uuid>|我确认 R2 v2。..." (and likewise P2).
535
- // Accept only a matching kind+version from a genuine user message,
536
- // never arbitrary prose containing an approval quote or TEST_ONLY.
537
- const native=line.match(/^([A-Z][A-Z0-9._:-]{7,120})[||]\s*([RP][1-9][0-9]*)-ISSUE:([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})[||]\s*我确认\s+([RP][1-9][0-9]*)\s+v([1-9][0-9]*)[。.!!]\s*(.{0,320})$/i);
538
- if(native){
539
- const declared=native[2].toUpperCase(),approved=native[4].toUpperCase();
540
- if(declared[0]!==type||declared!==approved
541
- ||Number(declared.slice(1))!==Number(native[5]))return false;
542
- const note=native[6];
543
- if(/TEST_ONLY|NOT_APPROVED|只是测试|仅供测试|仅为引用|复制示例|不作为.{0,15}(?:审批|批准)|此确认无效/i.test(note))return false;
544
- if(type==="R"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:需求|R[1-9][0-9]*)/i.test(note)
545
- ||type==="P"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:方案|计划|P[1-9][0-9]*)/i.test(note)
546
- ||type==="P"&&/(?:不授权|未授权|禁止|不要|不能).{0,15}(?:Start|执行|实施|开始|启动)/i.test(note))
547
- return false;
548
- return true;
549
- }
550
- const target=type==="R"
551
- ? "(?:这份|当前|本版|上述)?(?:需求(?:R[1-9][0-9]*)?|R[1-9][0-9]*)"
552
- : "(?:这份|当前|本版|上述)?(?:方案(?:与|及|和)?计划|实施计划|方案|计划|P[1-9][0-9]*)(?:P[1-9][0-9]*)?";
553
- const affirmative=new RegExp("^(?:我)?(?:已经|已)?(?:确认|同意|批准)"+target+"[。.!!]?$","i");
554
- // Keep the original standalone approval. Some real native R/P forms
555
- // submit a scoped request ID followed by a direct affirmative sentence
556
- // and bounded next-stage context in ONE genuine user message.
557
- if(line.length<=100&&affirmative.test(line.replace(/\s+/g,"")))return true;
558
- const scoped=line.match(/^([A-Z][A-Z0-9._:-]{7,120})[||]\s*([^。.!!]+[。.!!])\s*(.{1,320})$/i);
559
- if(!scoped||!affirmative.test(scoped[2].replace(/\s+/g,"")))return false;
560
- const note=scoped[3];
561
- // A form's scope note cannot revoke approval, request the model to
562
- // merely quote it, or explicitly withhold the approved plan's start.
563
- if(/(?:TEST_ONLY|NOT_APPROVED|只是测试文字|只是引用|仅为引用|复制示例|不授权|未授权|并非授权|不代表.{0,15}(?:授权|确认|批准)|不作为.{0,10}(?:审批|批准|授权)|(?:仅|只是)(?:用|供|用于).{0,5}(?:测试|演示|验证))/i.test(note)
564
- ||/(?:撤销|取消|拒绝|不通过|不同意|不批准)(?:当前|本次|这份)?(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(note)
565
- ||type==="P"&&/(?:暂不|先不|不要|不能|不允许|禁止).{0,15}(?:执行|Start|实施|开始|启动|做)/i.test(note)
566
- ||/(?:但|不过|只是).{0,12}(?:先不要|先不做|不做|不要做)/.test(note))return false;
567
- return true;
568
- };
569
- // Prefer an explicit current-version declaration. Historical mentions
570
- // must not choose a version; ambiguous prose is not approval evidence.
571
- const versionOf=(value,type)=>{
572
- // Real formal reviews may start with a status recap mentioning an
573
- // older P2 before the issued heading "P3 v3|正式修订方案".
574
- // A unique, version-consistent line title outranks historical prose.
575
- const issued=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?("+type+"[1-9][0-9]*)\\s+v([1-9][0-9]*)\\s*[||]", "gi"))]
576
- .filter(x=>Number(x[1].slice(1))===Number(x[2]))
577
- .map(x=>x[1].toUpperCase());
578
- const issuedVersions=[...new Set(issued)];
579
- if(issuedVersions.length===1)return issuedVersions[0];
580
- if(issuedVersions.length>1)return null;
581
- const declared=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?(?:方案版本|需求版本|当前版本|版本)?[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
582
- const current=[...value.matchAll(new RegExp("(?:本次|当前|本版)[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
583
- const versions=[...new Set(current.length?current:declared.length?declared:(value.match(new RegExp("\\b"+type+"[1-9][0-9]*\\b","gi"))||[]).map(x=>x.toUpperCase()))];
584
- return versions.length===1?versions[0]:null;
585
- };
586
- const lastUser=rows.findLastIndex(x=>x.role==="user");
587
- if(lastUser<3 || rows[lastUser-1].role!=="assistant") {
588
- fail("APPROVAL_SEQUENCE_UNVERIFIED");return false;
589
- }
590
- const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
591
- // A plan document explicitly withheld in PLAN_DRAFT is not an issued
592
- // review. A user cannot make it effective by typing a P1 approval after
593
- // the assistant said the current plan was not presented for approval.
594
- if(/(?:当前阶段[::]\s*PLAN_DRAFT|(?:维持|保持|仍为|停留在)\s*PLAN_DRAFT|方案(?:草稿)?.{0,20}(?:尚未|未曾|没有)正式(?:发布|提交)|(?:暂不|不(?:予|会|再)?)展示.{0,12}提交方案评审)/i.test(textOf(pAssistant))){
595
- fail("APPROVAL_PLAN_NOT_ISSUED");return false;
596
- }
597
- if(!confirms(textOf(pUser),"P")
598
- || !/(?:方案|计划)/.test(textOf(pAssistant))
599
- || !/\bP[1-9][0-9]*\b/i.test(textOf(pAssistant))) {
600
- fail("APPROVAL_PLAN_MISSING");return false;
601
- }
602
- const pVersion=versionOf(textOf(pAssistant),"P");
603
- const pUserVersion=textOf(pUser).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
604
- if(pUserVersion && pVersion!==pUserVersion){
605
- fail("APPROVAL_PLAN_VERSION_MISMATCH");return false;
606
- }
607
- const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
608
- &&confirms(textOf(x),"R"));
609
- // Long chats virtualize old turns. A still-mounted native R2 user
610
- // approval at index 0 has its exact issued R2-ISSUE identity, even when
611
- // the original R2 assistant has scrolled out of the DOM window.
612
- // This fallback is ONLY for native issue-scoped approvals. The Native
613
- // Context Start lease independently verifies the effective R approval.
614
- const rUser=rIndex>=0?rows[rIndex]:null;
615
- const nativeR=rUser&&textOf(rUser).match(/^[A-Z][A-Z0-9._:-]{7,120}[||]\s*(R[1-9][0-9]*)-ISSUE:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]\s*我确认\s+(R[1-9][0-9]*)\s+v([1-9][0-9]*)[。.!!]/i);
616
- const nativeRVersion=nativeR
617
- &&nativeR[1].toUpperCase()===nativeR[2].toUpperCase()
618
- &&Number(nativeR[1].slice(1))===Number(nativeR[3])
619
- ?nativeR[1].toUpperCase():null;
620
- const rAssistant=rIndex>0?rows[rIndex-1]:null;
621
- if(rIndex<0 || rIndex===0&&!nativeRVersion
622
- ||rIndex>0&&rAssistant?.role!=="assistant"){
623
- fail("APPROVAL_REQUIREMENTS_MISSING");return false;
624
- }
625
- if(message.expectedTaskId!==undefined){
626
- // A no-URL idle adoption is only eligible for its exact Managed
627
- // Task's TWO native issued approval messages in the same DOM Chat.
628
- // No standalone historical affirmations or copied Task summaries.
629
- const task=message.expectedTaskId;
630
- const nativeIssue=(row,type)=>typeof task==="string"
631
- &&/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(task)
632
- &&textOf(row).startsWith(task+"|")
633
- &&new RegExp("^"+type+"[1-9][0-9]*-ISSUE:"
634
- +"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]\\s*我确认\\s+"
635
- +type+"[1-9][0-9]*\\s+v[1-9][0-9]*","i")
636
- .test(textOf(row).slice(task.length+1));
637
- if(!nativeRVersion||!nativeIssue(rUser,"R")
638
- ||!nativeIssue(pUser,"P")){
639
- fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
640
- }
641
- }
642
- // Only document-level TEST_ONLY markers deny production adoption:
643
- // normal P plans can legitimately mention test-only scenarios.
644
- const testOnlyReview=x=>
645
- /(?:^|\n)\s*(?:#{1,6}\s*|>\s*)?(?:\*\*)?TEST_ONLY(?:\*\*)?(?:\s*$|\s*[/||:]\s*NOT_APPROVED)/mi
646
- .test(textOf(x));
647
- if(rAssistant&&testOnlyReview(rAssistant)||testOnlyReview(pAssistant)){
648
- fail("APPROVAL_TEST_ONLY");return false;
649
- }
650
- if(rAssistant&&(!/(?:需求|范围|验收)/.test(textOf(rAssistant))
651
- || !/\bR[1-9][0-9]*\b/i.test(textOf(rAssistant)))) {
652
- fail("APPROVAL_REQUIREMENTS_MISSING");return false;
653
- }
654
- const rVersion=rAssistant?versionOf(textOf(rAssistant),"R"):nativeRVersion;
655
- const intervening=rows.slice(rIndex+1,lastUser-1);
656
- const invalidated=intervening.some(x=>{
657
- const text=textOf(x);
658
- if(x.role==="assistant"){
659
- const next=versionOf(text,"R");
660
- return /需求|范围|验收/.test(text)&&next&&next!==rVersion;
661
- }
662
- // "修订 P3、保留 R2" is a plan update, NOT an R2 revocation.
663
- // Only an explicit requirement-targeted change invalidates this R.
664
- return /(?:撤销|取消|拒绝|不同意|不批准|修改|修订|变更)\s*(?:(?:当前|本次|这份|上述)\s*)?(?:需求|R[1-9][0-9]*)/i.test(text)
665
- || /\bR[1-9][0-9]*\b\s*(?:需求)?\s*(?:需要|应当|应该)?\s*(?:撤销|取消|拒绝|修改|修订|变更)/i.test(text);
666
- });
667
- if(!pVersion||!rVersion||invalidated){
668
- fail("APPROVAL_REVISED_OR_REVOKED");return false;
669
- }
670
- const rUserVersion=textOf(rUser).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
671
- const referencedR=textOf(pAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
672
- if(!referencedR || referencedR!==rVersion){
673
- fail("APPROVAL_PLAN_REQUIREMENT_MISMATCH");return false;
674
- }
675
- if(rUserVersion && rVersion!==rUserVersion){
676
- fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
677
- }
678
- // An explicit Chat URL may be adopted after the P-approval assistant
679
- // finishes, but that reply might instead have issued R2/P2. Such a
680
- // revision invalidates the earlier P1 approval even if the last user
681
- // message is still the old standalone confirmation.
682
- const revisedAfterApproval=rows.slice(lastUser+1).some(x=>{
683
- if(x.role!=="assistant")return false;
684
- const text=textOf(x),nextR=versionOf(text,"R"),
685
- nextP=versionOf(text,"P");
686
- return Boolean(
687
- /(?:需求|范围|验收)/.test(text)&&nextR&&nextR!==rVersion
688
- ||/(?:方案|计划)/.test(text)&&nextP&&nextP!==pVersion
689
- ||/(?:SUPERSEDED|已失效|已废弃|已撤销)/i.test(text)
690
- &&/(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(text)
691
- );
692
- });
693
- if(revisedAfterApproval){
694
- fail("APPROVAL_REVISED_AFTER_CONFIRMATION");return false;
695
- }
696
- const userKey=messageId(pUser.el,"user");
697
- const snap=inspect();
698
- // Normally the model calls Start during its P-confirmation Turn.
699
- // A fresh, explicitly scoped native Start intent can also adopt AFTER
700
- // that assistant Turn ends (e.g. MCP schema was stale in the same Chat).
701
- // Only the exact current Chat ID, last R/P approval user identity and
702
- // completed assistant reply qualify. A historical unscoped idle Chat
703
- // must never become an Owner just because R/P messages are visible.
704
- const explicitChatId=typeof message.explicitChatId==="string"
705
- ? message.explicitChatId.toLowerCase():null;
706
- const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
707
- // The managed lease may scope an idle, already-open Chat by the exact
708
- // Task ID in BOTH real native R/P approval turns. No task scope from
709
- // copied Context prose or generic unscoped historical confirmations.
710
- const issueTask=x=>textOf(x).match(
711
- /^([A-Z][A-Z0-9._:-]{7,120})[||]\s*[RP][1-9][0-9]*-ISSUE:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]/i)?.[1]||null;
712
- const taskScoped=typeof message.expectedTaskId==="string"
713
- &&message.expectedTaskId.length>=8
714
- &&issueTask(rUser)===message.expectedTaskId
715
- &&issueTask(pUser)===message.expectedTaskId;
716
- if(message.expectedTaskId!==undefined&&!taskScoped){
717
- fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
718
- }
719
- const scopedIdle=Boolean(
720
- (explicitChatId&&explicitChatId===currentId||taskScoped)
721
- &&!snap.stop&&!snap.busy&&snap.assistantKey
722
- &&snap.composerReady&&snap.copyAction&&snap.text
723
- &&!snap.pendingConfirmation);
724
- if(!userKey ||snap.path!==path||snap.userKey!==userKey
725
- ||!(snap.stop||snap.busy||scopedIdle)
726
- ||snap.fatal||snap.dialog||snap.toolUnknown){
727
- fail("APPROVAL_LAST_TURN_UNVERIFIED");return false;
728
- }
729
- reply({contract:CONTRACT,status:"VERIFIED",page:path,
730
- userKey,rVersion,pVersion,priorAssistantKey:messageId(pAssistant.el,"assistant"),
731
- // Idle post-approval assistant was completed BEFORE adoption.
732
- // This is a historical baseline, never a fresh execution Turn.
733
- ...(scopedIdle?{postApprovalAssistantKey:snap.assistantKey}:{})});
734
- return false;
735
- }
736
- if (message?.type === "CHAT_LOOP_TURN_VERIFY_V1") {
123
+ const onRecovery=globalThis.ChatLoopObserverRecoveryV1({
124
+ CONTRACT,session,inspect,poll,resetCandidate,activeEvidenceConversation,messageId});
125
+ const onApproval=globalThis.ChatLoopObserverApprovalV1({
126
+ CONTRACT,inspect,activeEvidenceConversation,messageId});
127
+ chrome.runtime.onMessage.addListener((message,_sender,reply)=>{
128
+ if(['CHAT_LOOP_TURN_RETRY_MONITOR_V1','CHAT_LOOP_TURN_RESUME_V1',
129
+ 'CHAT_LOOP_REPAIR_EVIDENCE_V1'].includes(message?.type))
130
+ return onRecovery(message,reply);
131
+ if(message?.type==='CHAT_LOOP_APPROVAL_EVIDENCE_V1')
132
+ return onApproval(message,reply);
133
+ if (message?.type === "CHAT_LOOP_TURN_VERIFY_V1") {
737
134
  // Explicit manual Action: only a fresh read-only completed-Turn candidate.
738
135
  // This does not emit a completion event or write anything to the page.
739
136
  const snap = inspect();
@@ -747,10 +144,10 @@
747
144
  replyText: ready ? snap.text : null});
748
145
  return false;
749
146
  }
750
- if (message?.type !== "CHAT_LOOP_TURN_OBSERVE_V1") return false;
751
- if (message.poll === true) poll();
752
- reply({...state});
753
- return false;
147
+ if (message?.type !== "CHAT_LOOP_TURN_OBSERVE_V1") return false;
148
+ if (message.poll === true) poll();
149
+ reply({...state});
150
+ return false;
754
151
  });
755
152
  setInterval(poll, POLL_MS);
756
153
  poll();