@tomflow/chatloop-tools 0.9.63 → 0.9.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +16 -7
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/package.json +2 -12
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -89
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,109 +0,0 @@
1
- // Read-only Observer helper: no composer writes, Chrome Owner or sends.
2
- (() => {
3
- globalThis.ChatLoopObserverRecoveryV1=({CONTRACT,session,inspect,poll,
4
- resetCandidate,activeEvidenceConversation,messageId})=>
5
- (message,reply)=>{
6
- if (message?.type === "CHAT_LOOP_TURN_RETRY_MONITOR_V1") {
7
- const snap = inspect();
8
- if (snap.path !== message.page || snap.userKey !== message.userKey
9
- || session.reportedErrorUser !== message.userKey
10
- || session.completedUser === message.userKey) {
11
- reply({contract: CONTRACT, status: "UNVERIFIED", reason: "RETRY_OWNER_CHANGED"});
12
- return false;
13
- }
14
- session.reportedErrorUser = null;
15
- reply({contract: CONTRACT, status: "REARMED", userKey: snap.userKey});
16
- // Re-read after the Worker has committed WAITING_REPLY; if the same red
17
- // error is still visible this is the second failure, not a new Continue.
18
- void Promise.resolve().then(poll);
19
- return false;
20
- }
21
- if (message?.type === "CHAT_LOOP_TURN_RESUME_V1") {
22
- // Rebind only the exact Worker-owned Turn after Extension reload.
23
- // A dedicated baseline-only mode never reports an already-completed
24
- // pre-adoption assistant as a new execution Turn.
25
- const snap = inspect();
26
- if (!snap.path || snap.unavailable || snap.path !== message.page
27
- || !/^user:[^\s]{8,}$/.test(message.userKey || "")
28
- || snap.userKey !== message.userKey
29
- || message.assistantKey && !/^assistant:[^\s]{8,}$/.test(message.assistantKey)) {
30
- reply({contract: CONTRACT, status: "UNVERIFIED", reason: "RESUME_IDENTITY_MISMATCH"});
31
- return false;
32
- }
33
- // The Worker can still be WAITING_REPLY after our completion report was
34
- // lost (e.g. MV3 worker suspension). Only that Worker-owned exact Turn
35
- // may request a new stable read. Never replay on ordinary DOM polling.
36
- if (session.pendingUser === message.userKey && !session.attaching
37
- && session.completedUser !== message.userKey && message.baselineOnly!==true) {
38
- reply({contract: CONTRACT, status: "ALREADY_MONITORING"});
39
- return false;
40
- }
41
- if(message.baselineOnly===true &&
42
- (!message.assistantKey || snap.assistantKey!==message.assistantKey
43
- || snap.stop||snap.busy||snap.pendingConfirmation||!snap.copyAction)){
44
- reply({contract:CONTRACT,status:"UNVERIFIED",reason:"ADOPT_BASELINE_UNVERIFIED"});
45
- return false;
46
- }
47
- session.path = snap.path;
48
- session.sawHomepage = false;
49
- session.attaching = false;
50
- session.attachingFirstTurn = false;
51
- session.firstSendSeen = false;
52
- session.priorUser = null;
53
- session.baselineUser = message.baselineOnly===true ? message.userKey : null;
54
- session.baselineAssistant = message.assistantKey || null;
55
- session.pendingUser = message.baselineOnly===true ? null : message.userKey;
56
- session.completedUser = message.baselineOnly===true ? message.userKey : null;
57
- session.firstTurnAt = Number.isSafeInteger(message.startedAt)
58
- && message.startedAt > 0 ? message.startedAt : Date.now();
59
- session.attachSignature = "";
60
- resetCandidate();
61
- const observation = poll();
62
- reply({contract: CONTRACT, status: "RESUMED",
63
- observation: observation.status, reason: observation.reason,
64
- userKey: observation.userKey,
65
- ...(message.baselineOnly===true?{baselineOnly:true}:{})});
66
- return false;
67
- }
68
- if (message?.type === "CHAT_LOOP_REPAIR_EVIDENCE_V1") {
69
- // Read-only proof of a NEW repair request in the EXACT Chat whose
70
- // previous assistant finished with machine DONE. Not a new R/P approval.
71
- const view=activeEvidenceConversation();
72
- const fail=reason=>reply({contract:CONTRACT,status:"UNVERIFIED",reason});
73
- if(!view){fail("REPAIR_CHAT_UNVERIFIED");return false;}
74
- const {path,nodes,role}=view;
75
- const userIdx=nodes.findLastIndex(el=>role(el)==="user");
76
- if(userIdx<1||role(nodes[userIdx-1])!=="assistant"){
77
- fail("REPAIR_SEQUENCE_UNVERIFIED");return false;
78
- }
79
- const text=el=>(el.querySelector?.(".markdown")?.innerText
80
- ||el.innerText||el.textContent||"").trim();
81
- const lastUser=nodes[userIdx],priorAssistant=nodes[userIdx-1];
82
- const userText=text(lastUser).replace(/\s+/g," ");
83
- if(userText.length<4||userText.length>2000
84
- ||!/(?:修复|修正|返工|修改|补完|不通过|重新做|继续完成|改好|fix|repair|rework|correct)/i.test(userText)
85
- ||/(?:不要|不用|无需|拒绝).{0,8}(?:修复|修改|继续|fix|repair)/i.test(userText)
86
- ||!/\[CHAT_LOOP_STATUS:DONE\]\s*$/.test(text(priorAssistant))){
87
- fail("REPAIR_EXPLICIT_INTENT_NOT_FOUND");return false;
88
- }
89
- const snap=inspect(),userKey=messageId(lastUser,"user"),
90
- doneAssistantKey=messageId(priorAssistant,"assistant");
91
- const requestedId=typeof message.explicitChatId==="string"
92
- ?message.explicitChatId.toLowerCase():null;
93
- const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
94
- if(requestedId&&requestedId!==currentId){
95
- fail("REPAIR_CHAT_ID_CHANGED");return false;
96
- }
97
- if(!userKey||snap.path!==path||snap.userKey!==userKey
98
- ||snap.fatal||snap.dialog||snap.toolUnknown
99
- ||!(snap.stop||snap.busy||requestedId
100
- &&!snap.pendingConfirmation&&snap.composerReady)){
101
- fail("REPAIR_LAST_USER_UNVERIFIED");return false;
102
- }
103
- reply({contract:CONTRACT,status:"VERIFIED",page:path,
104
- userKey,userText,priorDoneAssistantKey:doneAssistantKey});
105
- return false;
106
- }
107
- return false;
108
- };
109
- })();
@@ -1,154 +0,0 @@
1
- // Read-only ChatGPT Turn observation. No composer writes, clicks, or task decisions.
2
- // Candidate DOM selectors must be verified against an authorized real ChatGPT tab.
3
- (() => {
4
- if (globalThis.__CHAT_LOOP_OBSERVER_V1__) return;
5
- globalThis.__CHAT_LOOP_OBSERVER_V1__ = true;
6
- const CONTRACT = "chat-loop.turn-observer.v1";
7
- const STABLE_MS = 2200;
8
- const POLL_MS = 60_000; // Temporary: check Turn status once per minute, independent of Handoff clock.
9
- const session = {
10
- path: "", baselineUser: null, baselineAssistant: null,
11
- pendingUser: null, completedUser: null,
12
- candidate: "", stableSince: 0, firstSendSeen: false, firstSendAt: 0,
13
- sawHomepage: false, attaching: false, attachingFirstTurn: false,
14
- priorUser: null, attachSignature: "", attachSince: 0,
15
- emittedCount: 0, firstTurnAt: 0, reportedErrorUser: null
16
- };
17
- let state = {contract: CONTRACT, status: "UNKNOWN", reason: "INITIALIZING", eventCount: 0};
18
-
19
- const conversationPath = () => {
20
- if (location.protocol !== "https:" || location.hostname !== "chatgpt.com") return "";
21
- const path = location.pathname.replace(/\/$/, "");
22
- return /^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(path)
23
- ? path : "";
24
- };
25
- function visible(el) {
26
- if (!el || !el.getClientRects?.().length) return false;
27
- if (el.closest?.('[hidden],[aria-hidden="true"]')) return false;
28
- const style = globalThis.getComputedStyle?.(el);
29
- return style?.display !== "none" && style?.visibility !== "hidden";
30
- }
31
- function messageId(node, role) {
32
- if (!node) return null;
33
- const container = node.closest?.('[data-testid^="conversation-turn-"]');
34
- const ids = node.getAttribute?.("data-chatgpt-search-message-ids") || "";
35
- const id = node.getAttribute?.("data-message-id")
36
- || ids.trim().split(/\s+/)[0] || container?.getAttribute?.("data-testid");
37
- return id ? role + ":" + id : null;
38
- }
39
- function fingerprint(text) {
40
- let hash = 2166136261;
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);
45
- }
46
- return (hash >>> 0).toString(16) + ":" + text.length;
47
- }
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
-
54
- function emit(status, reason, snap, event = null) {
55
- if (event) session.emittedCount += 1;
56
- state = {contract: CONTRACT, status, reason, page: snap.path || null,
57
- userKey: snap.userKey || null, assistantKey: snap.assistantKey || null,
58
- retryAvailable: status === "BLOCKED" && snap.retryAvailable === true,
59
- eventCount: session.emittedCount, observedAt: Date.now(),
60
- pendingConfirmation: snap.pendingConfirmation === true,
61
- priorAssistantKey: snap.priorAssistantKey || null,
62
- priorAssistantUserKey:snap.priorAssistantUserKey || null,
63
- directReplyAfterPriorAssistant:snap.directReplyAfterPriorAssistant===true};
64
- if (event) {
65
- document.dispatchEvent(new CustomEvent("CHAT_LOOP_TURN_FINISHED_V1", {
66
- detail: {contract: CONTRACT, page: snap.path,
67
- userKey: snap.userKey, assistantKey: snap.assistantKey}
68
- }));
69
- // Sensor -> extension scheduler: no composer writes or action decisions here.
70
- // Only a freshly verified Turn can request autonomous scheduling.
71
- if (typeof chrome.runtime.sendMessage === "function") {
72
- void Promise.resolve(chrome.runtime.sendMessage({
73
- type: "CHAT_LOOP_TURN_FINISHED_V1", page: snap.path,
74
- userKey: snap.userKey, assistantKey: snap.assistantKey,
75
- replyText: snap.text, startedAt: session.firstTurnAt || Date.now(),
76
- pendingConfirmation: snap.pendingConfirmation === true,
77
- priorAssistantKey: snap.priorAssistantKey || null,
78
- priorAssistantUserKey:snap.priorAssistantUserKey || null,
79
- directReplyAfterPriorAssistant:snap.directReplyAfterPriorAssistant===true
80
- })).catch(() => {});
81
- }
82
- }
83
- return state;
84
- }
85
- function resetCandidate() {
86
- session.candidate = "";
87
- session.stableSince = 0;
88
- }
89
- const poll=globalThis.ChatLoopObserverPollV1({session,inspect,emit,
90
- resetCandidate,fingerprint,STABLE_MS,getState:()=>state});
91
- function recordFirstChatSubmission(event) {
92
- if (!event?.target?.closest) return;
93
- const fromHome = !conversationPath() && !session.path;
94
- const fromEmptyChat = Boolean(conversationPath()) && session.attaching
95
- && !session.baselineUser && !session.attachSignature;
96
- if (!fromHome && !fromEmptyChat) return;
97
- const sendClick = event.type === "click" && event.target.closest(
98
- 'button[type="submit"][aria-label="发送"],button[data-testid="send-button"],' +
99
- 'button[data-testid="composer-send-button"],button[aria-label="Send message"]');
100
- const sendEnter = event.type === "keydown" && event.key === "Enter"
101
- && !event.shiftKey && !event.isComposing && event.target.closest(
102
- '[contenteditable="true"][data-composer-markdown],#prompt-textarea');
103
- if (!sendClick && !sendEnter) return;
104
- const editor = document.querySelector('[contenteditable="true"][data-composer-markdown]')
105
- || document.querySelector('#prompt-textarea[contenteditable="true"]');
106
- if (!visible(editor) || !(editor.innerText ?? editor.textContent ?? "").trim()) return;
107
- session.firstSendSeen = true;
108
- session.firstSendAt = Date.now();
109
- if (!session.firstTurnAt) session.firstTurnAt = session.firstSendAt;
110
- if (fromEmptyChat) {
111
- session.attaching = false;
112
- session.attachingFirstTurn = true;
113
- session.baselineUser = null;
114
- session.baselineAssistant = null;
115
- session.pendingUser = null;
116
- }
117
- }
118
- document.addEventListener?.("click", recordFirstChatSubmission, true);
119
- document.addEventListener?.("keydown", recordFirstChatSubmission, true);
120
- globalThis.ChatLoopTurnObserverV1 = Object.freeze({
121
- poll, read: () => ({...state})
122
- });
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") {
134
- // Explicit manual Action: only a fresh read-only completed-Turn candidate.
135
- // This does not emit a completion event or write anything to the page.
136
- const snap = inspect();
137
- const ready = Boolean(snap.path && snap.userKey && snap.assistantKey
138
- && snap.text && snap.composerReady && snap.copyAction
139
- && !snap.stop && !snap.busy && !snap.toolUnknown && !snap.fatal
140
- && !snap.dialog && (!snap.turnState || snap.turnState === "complete"));
141
- reply({contract: CONTRACT, status: ready ? "READY" : "UNVERIFIED",
142
- page: snap.path || null, userKey: snap.userKey || null,
143
- assistantKey: snap.assistantKey || null,
144
- replyText: ready ? snap.text : null});
145
- return false;
146
- }
147
- if (message?.type !== "CHAT_LOOP_TURN_OBSERVE_V1") return false;
148
- if (message.poll === true) poll();
149
- reply({...state});
150
- return false;
151
- });
152
- setInterval(poll, POLL_MS);
153
- poll();
154
- })();
@@ -1,259 +0,0 @@
1
- // One bounded inventory for the existing Extension Worker. It never sends,
2
- // types into, or otherwise drives a ChatGPT page.
3
- (() => {
4
- const KEY = 'chat-loop.resources.v1';
5
- const ACTION_LIMIT = 3; // Includes machine Eye, Start, manual and timed Actions.
6
- const CHAT_LIMIT = 2; // One owner plus at most one Handoff successor.
7
- const AUDIT_TTL = 60_000; // Reap obsolete audit pages from installed older Extension versions.
8
- const READ_TTL = 180_000;
9
- const TERMINAL_TTL = 30_000;
10
- const READ_ONLY = new Set(['status','text','dom','screenshot','reload']);
11
- const ACTIONS = new Set(['start','continue','handoff','status','text','dom',
12
- 'screenshot','reload','clean','session']);
13
- const validId = s => /^[a-f0-9]{32}$/.test(s || '');
14
- const validTabId = s => /^[1-9][0-9]*$/.test(s || '');
15
- const extensionBase = () => chrome.runtime.getURL('');
16
- function classify(tab) {
17
- if (!Number.isInteger(tab?.id) || !tab.url) return null;
18
- let u;
19
- try {u = new URL(tab.url);} catch {return null;}
20
- if (u.protocol !== 'chrome-extension:' || !tab.url.startsWith(extensionBase())
21
- || u.host !== new URL(extensionBase()).host) return null;
22
- if (u.pathname === '/popup.html' && u.search === '?audit=1')
23
- return {kind:'audit'}; // Legacy page reaping only; old audit UI is not executable.
24
- const name = u.pathname.match(/^\/([a-z]+)\.html$/)?.[1];
25
- if (!ACTIONS.has(name)) return null;
26
- if (name==='session' && u.searchParams.size===2
27
- && validId(u.searchParams.get('requestId'))
28
- && u.searchParams.get('operation')==='cancel')
29
- return {kind:'machine',name,requestId:u.searchParams.get('requestId')};
30
- if (u.searchParams.size === 1 && validId(u.searchParams.get('requestId')))
31
- return {kind:READ_ONLY.has(name) || ['continue','handoff'].includes(name)
32
- ? 'read-only' : 'machine', name, requestId:u.searchParams.get('requestId')};
33
- if (['continue','handoff'].includes(name)
34
- && u.searchParams.size === 2 && validTabId(u.searchParams.get('tabId'))
35
- && /^[0-9a-f-]{36}$/i.test(u.searchParams.get('token') || ''))
36
- return {kind:'send', name, token:u.searchParams.get('token'),
37
- targetId:Number(u.searchParams.get('tabId'))};
38
- // Manual pages count toward the quota but are never automatically closed.
39
- return {kind:'manual', name};
40
- }
41
- const initial = () => ({created:0, observed:0, closed:0, denied:0,
42
- peakActions:0, peakChats:0, lastDenial:null, entries:[]});
43
- const load = async () => {
44
- const value=(await chrome.storage.local.get(KEY))[KEY];
45
- return value && Array.isArray(value.entries) ? value : initial();
46
- };
47
- const save = state => chrome.storage.local.set({[KEY]:state});
48
- const cleanEntry = x => x && Number.isInteger(x.id) && typeof x.url === 'string';
49
- const safeRemove = async (tab,entry,state,reason) => {
50
- const live=await chrome.tabs.get(tab.id).catch(()=>null);
51
- if (!live || live.url !== entry.url || live.active || live.pinned) return false;
52
- try {await chrome.tabs.remove(tab.id);}
53
- catch (error) {
54
- // A user can close this tab after the final ownership check. Treat an
55
- // absent tab as unconfirmed cleanup and reconcile it on the next scan;
56
- // a still-live tab with a remove error must remain an explicit failure.
57
- if (await chrome.tabs.get(tab.id).catch(()=>null)) throw error;
58
- return false;
59
- }
60
- state.closed++;
61
- state.lastReaped={id:tab.id, reason, at:Date.now()};
62
- state.entries=state.entries.filter(e=>e.id!==tab.id);
63
- return true;
64
- };
65
- const noDraft = async tabId => {
66
- try {
67
- const [p]=await chrome.scripting.executeScript({target:{tabId},func:()=>{
68
- if (location.origin !== 'https://chatgpt.com' || !/^\/c\/[0-9a-f-]{12,}$/i.test(location.pathname)) return false;
69
- const editor=document.querySelector('[contenteditable="true"][data-composer-markdown]')
70
- ||document.querySelector('#prompt-textarea[contenteditable="true"]');
71
- return !!editor && !(editor.innerText || editor.textContent || '').trim()
72
- && !document.querySelector('[data-testid*="attachment-preview"], [data-testid*="image-preview"], [data-testid="composer-attachment"]');
73
- }});
74
- return p?.result===true;
75
- } catch {return false;}
76
- };
77
- async function reconcile(run, {reap=true}={}) {
78
- const state=await load(),now=Date.now();
79
- const all=await chrome.tabs.query({});
80
- const live=new Map(all.filter(t=>Number.isInteger(t.id)).map(t=>[t.id,t]));
81
- const kept=[];
82
- for (const entry of state.entries.filter(cleanEntry)) {
83
- const tab=live.get(entry.id);
84
- if (!tab || tab.url!==entry.url && entry.kind!=='chat') {
85
- if (!tab) state.closed++;
86
- continue;
87
- }
88
- // A Chat URL may change from blank to canonical only via markConfirmed.
89
- if (entry.kind==='chat' && tab.url!==entry.url) {
90
- kept.push(entry);continue; // Preserve provenance; never delete on unknown navigation.
91
- }
92
- kept.push(entry);
93
- }
94
- state.entries=kept;
95
- for (const tab of all) {
96
- const info=classify(tab);
97
- if (!info || state.entries.some(e=>e.id===tab.id)) continue;
98
- state.entries.push({id:tab.id,url:tab.url,kind:'action',type:info.kind,
99
- name:info.name||null,firstSeenAt:now,owned:false});
100
- state.observed++;
101
- }
102
- // A crashed Action may have created a Chat before calling registerChat.
103
- // Chrome's trusted openerTabId lets us recover that exact provenance,
104
- // including after an MV3 Worker restart. Unknown other Chats are not owned.
105
- for (const tab of all) {
106
- if (!Number.isInteger(tab.id)||!Number.isInteger(tab.openerTabId)
107
- || !/^https:\/\/chatgpt\.com\/(?:|c\/[0-9a-f-]{12,})$/i.test(tab.url||'')
108
- || state.entries.some(e=>e.id===tab.id)) continue;
109
- const opener=live.get(tab.openerTabId), proof=classify(opener);
110
- const exactStart=proof?.name==='start' && proof.kind==='machine'
111
- && [run?.machineActionTabId,run?.lastStartActionTabId].includes(opener?.id);
112
- const exactHandoff=proof?.name==='handoff' && proof.kind==='send'
113
- && proof.token===run?.token
114
- && [run?.tabId,run?.sourceTabId].includes(proof.targetId);
115
- if ((!exactStart&&!exactHandoff)||!(run?.sessionId||run?.token)) continue;
116
- state.entries.push({id:tab.id,url:tab.url,kind:'chat',
117
- sessionId:run.sessionId||run.token,firstSeenAt:now,confirmed:false,
118
- testOwned:/^cl-intent-e2e-[a-z0-9-]+$/i.test(run.projectId||'')});
119
- state.observed++;state.created++;
120
- }
121
- if (reap) {
122
- for (const entry of [...state.entries]) {
123
- const tab=live.get(entry.id);
124
- if (!tab || tab.active || tab.pinned) continue;
125
- const age=now-(entry.firstSeenAt||now);
126
- if (entry.kind==='action') {
127
- const info=classify(tab);
128
- if (!info || tab.url!==entry.url) continue;
129
- if (info.kind==='audit' && age>=AUDIT_TTL)
130
- await safeRemove(tab,entry,state,'STALE_AUDIT');
131
- else if (info.kind==='read-only' && age>=READ_TTL)
132
- await safeRemove(tab,entry,state,'STALE_READ_ONLY_NO_SEND');
133
- else if (info.kind==='send' && age>=TERMINAL_TTL
134
- && ['DONE','BLOCKED'].includes(run?.phase)
135
- && run?.token===info.token
136
- && [run.tabId,run.sourceTabId].includes(info.targetId))
137
- await safeRemove(tab,entry,state,'CONFIRMED_TERMINAL_ACTION');
138
- else if (info.kind==='machine' && info.name==='start'
139
- && age>=TERMINAL_TTL && ['DONE','BLOCKED'].includes(run?.phase)
140
- && [run?.lastStartActionTabId,run?.machineActionTabId].includes(tab.id))
141
- await safeRemove(tab,entry,state,'CONFIRMED_TERMINAL_START');
142
- } else if (entry.kind==='chat' && entry.confirmed
143
- && entry.testOwned===true && entry.terminal==='DONE' && age>=TERMINAL_TTL
144
- && tab.url===entry.url && await noDraft(tab.id)) {
145
- await safeRemove(tab,entry,state,'DONE_OWNED_CHAT');
146
- }
147
- }
148
- }
149
- // Count every live matching page, even when the bounded evidence index
150
- // cannot retain every item after an external flood of manual pages.
151
- const after=await chrome.tabs.query({});
152
- const actionCount=after.filter(t=>classify(t)).length;
153
- const afterIds=new Set(after.map(t=>t.id));
154
- const liveChatEntries=state.entries.filter(e=>e.kind==='chat'
155
- && afterIds.has(e.id));
156
- const chatCount=liveChatEntries.length;
157
- // The quota is for in-flight Owners and a Handoff successor, not for
158
- // retained historical Chat tabs. Keep terminal provenance and the tabs;
159
- // neither is permission to send. A recovered same-Session Owner counts
160
- // again even when its ledger still records an earlier BLOCKED phase.
161
- const activeChatCount=liveChatEntries.filter(e=>
162
- !['DONE','BLOCKED','CANCELLED'].includes(e.terminal)
163
- ||(e.sessionId===(run?.sessionId||run?.token)
164
- &&!['DONE','BLOCKED','CANCELLED'].includes(run?.phase))).length;
165
- const unownedHomes=after.filter(t=>t.url==='https://chatgpt.com/'
166
- && !state.entries.some(e=>e.kind==='chat'&&e.id===t.id)).length;
167
- state.peakActions=Math.max(state.peakActions,actionCount);
168
- state.peakChats=Math.max(state.peakChats,chatCount);
169
- // Retain tracked Chats first: evicting their provenance would weaken the
170
- // quota and could make an unknown send appear safe to replay.
171
- const chatEntries=state.entries.filter(e=>e.kind==='chat');
172
- const actionEntries=state.entries.filter(e=>e.kind==='action');
173
- const slots=Math.max(0,32-chatEntries.length);
174
- state.entries=[...chatEntries,...(slots?actionEntries.slice(-slots):[])];
175
- // Native/manual pages remain counted directly from the browser snapshot.
176
- state.current={actions:actionCount,chats:chatCount,
177
- activeChats:activeChatCount,unownedHomes,totalTabs:after.length,at:now};
178
- await save(state);
179
- return {state,actionCount,chatCount,activeChatCount,unownedHomes};
180
- }
181
- async function admit(run,{kind='action'}={}) {
182
- const {state,actionCount,chatCount,activeChatCount,unownedHomes}=await reconcile(run);
183
- const blocked=actionCount+(kind==='action'?1:0)>ACTION_LIMIT
184
- ? 'RESOURCE_ACTION_LIMIT' : activeChatCount+unownedHomes+(kind==='chat'?1:0)>CHAT_LIMIT
185
- ? 'RESOURCE_CHAT_LIMIT' : null;
186
- if (blocked) {
187
- state.denied++;state.lastDenial={code:blocked,at:Date.now()};
188
- await save(state);
189
- }
190
- return blocked?{ok:false,code:blocked,actionCount,chatCount}
191
- :{ok:true,actionCount,chatCount};
192
- }
193
- async function registerAction(tab) {
194
- const info=classify(tab);
195
- if (!info) return false;
196
- const state=await load();
197
- if (!state.entries.some(e=>e.id===tab.id)) {
198
- state.entries.push({id:tab.id,url:tab.url,kind:'action',
199
- type:info.kind,firstSeenAt:Date.now(),owned:true});
200
- state.created++;
201
- // Fast actions can finish before the next alarm/reconciliation. Count
202
- // their observed creation in peak metrics even if no later scan sees them.
203
- state.peakActions=Math.max(state.peakActions,
204
- state.entries.filter(e=>e.kind==='action').length);
205
- await save(state);
206
- }
207
- return true;
208
- }
209
- async function registerChat(tab,run) {
210
- if (!Number.isInteger(tab?.id) || tab.url!=='https://chatgpt.com/'
211
- || !(run?.sessionId || run?.token) || run.phase!=='PENDING') return false;
212
- const state=await load();
213
- const existing=state.entries.find(e=>e.id===tab.id);
214
- if(existing)return existing.kind==='chat'
215
- &&existing.sessionId===(run.sessionId||run.token);
216
- state.entries.push({id:tab.id,url:tab.url,kind:'chat',
217
- sessionId:run.sessionId||run.token,firstSeenAt:Date.now(),confirmed:false,
218
- testOwned:/^cl-intent-e2e-[a-z0-9-]+$/i.test(run.projectId||'')});
219
- state.created++;
220
- state.peakChats=Math.max(state.peakChats,
221
- state.entries.filter(e=>e.kind==='chat').length);
222
- await save(state);
223
- return true;
224
- }
225
- async function adoptChat(tab,run) {
226
- if(!Number.isInteger(tab?.id)||typeof tab.url!=="string"
227
- || !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(tab.url)
228
- ||!run?.sessionId||run.phase!=="PENDING"||run.adoptTabId!==tab.id)
229
- return false;
230
- const state=await load();
231
- if(state.entries.some(e=>e.id===tab.id))return false; // Existing Owner, even terminal, is not silently replaced.
232
- state.entries.push({id:tab.id,url:tab.url,kind:"chat",
233
- sessionId:run.sessionId,firstSeenAt:Date.now(),confirmed:true,
234
- adopted:true,testOwned:false});
235
- state.created++;
236
- state.peakChats=Math.max(state.peakChats,
237
- state.entries.filter(e=>e.kind==="chat").length);
238
- await save(state);
239
- return true;
240
- }
241
- async function confirmChat(id,sessionId,url) {
242
- const state=await load();
243
- const entry=state.entries.find(e=>e.id===id&&e.kind==='chat'
244
- &&e.sessionId===sessionId);
245
- if (!entry || !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(url)) return;
246
- entry.url=url;entry.confirmed=true;
247
- await save(state);
248
- }
249
- async function terminal(run) {
250
- if (!(run?.sessionId||run?.token)
251
- || !['DONE','BLOCKED','CANCELLED'].includes(run.phase)) return;
252
- const state=await load();
253
- for(const entry of state.entries) if(entry.kind==='chat'
254
- &&entry.sessionId===(run.sessionId||run.token)) entry.terminal=run.phase;
255
- await save(state);
256
- }
257
- globalThis.ChatLoopResourcesV1=Object.freeze({reconcile,admit,registerAction,
258
- registerChat,adoptChat,confirmChat,terminal,KEY,ACTION_LIMIT,CHAT_LIMIT});
259
- })();
@@ -1,42 +0,0 @@
1
- {
2
- "manifest_version": 3,
3
- "name": "Chat Loop Extension",
4
- "version": "0.4.34",
5
- "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
- "permissions": [
7
- "activeTab",
8
- "tabs",
9
- "downloads",
10
- "clipboardWrite",
11
- "nativeMessaging",
12
- "storage",
13
- "alarms",
14
- "scripting"
15
- ],
16
- "host_permissions": [
17
- "https://chatgpt.com/*"
18
- ],
19
- "background": {
20
- "service_worker": "background.js"
21
- },
22
- "action": {
23
- "default_title": "Check Chat Loop web environment",
24
- "default_popup": "popup.html"
25
- },
26
- "content_scripts": [
27
- {
28
- "matches": [
29
- "https://chatgpt.com/*"
30
- ],
31
- "js": [
32
- "content.js",
33
- "loop/observer-inspect.js",
34
- "loop/observer-poll.js",
35
- "loop/observer-recovery.js",
36
- "loop/observer-approval.js",
37
- "loop/observer.js"
38
- ],
39
- "run_at": "document_idle"
40
- }
41
- ]
42
- }
@@ -1,25 +0,0 @@
1
- <!doctype html>
2
- <html lang="zh-CN">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>Chat Loop Extension · 环境检测</title>
7
- <style>
8
- body { font-family: system-ui, sans-serif; width: 310px; margin: 0; padding: 18px; color: #242424; }
9
- h1 { font-size: 17px; margin: 0 0 12px; }
10
- #status { font-size: 15px; font-weight: 650; }
11
- #detail { color: #60636a; line-height: 1.5; font-size: 13px; }
12
- a { color: #1269c7; }
13
- </style>
14
- </head>
15
- <body>
16
- <h1>Chat Loop Extension · 环境检查</h1>
17
- <p id="status" role="status">正在检测…</p>
18
- <p id="detail">仅检查当前页面与浏览器类型,不读取聊天内容。</p>
19
- <p>打开动作页即执行,成功后自动关闭。多 Chat 标签页时请在动作页 URL 指定 <code>?tabId=...</code>。</p>
20
- <p><a href="screenshot.html" target="_blank">Screenshot</a> · <a href="dom.html" target="_blank">DOM</a> · <a href="text.html" target="_blank">Text</a> · <a href="reload.html" target="_blank">Reload</a> · <button id="clean-action" type="button">Clean 输入框</button></p>
21
- <p><a href="https://chatgpt.com/" target="_blank" rel="noopener noreferrer">打开 ChatGPT 网页版</a></p>
22
- <p id="action-state" role="status">最近发送动作:读取中…</p>
23
- <script src="popup.js"></script>
24
- </body>
25
- </html>