@tomflow/chatloop-tools 0.9.21 → 0.9.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +3 -1
  2. package/node_modules/@tomflow/chatloop-context/package.json +3 -3
  3. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  4. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  5. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  6. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  7. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  8. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  9. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  10. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  11. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  12. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  13. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  14. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  15. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  16. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  17. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  18. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  19. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  20. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  21. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  22. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  23. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  24. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  25. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  26. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  27. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  28. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  29. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  30. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  31. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  33. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  34. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  35. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  37. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  43. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  47. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  48. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  49. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  67. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  68. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  69. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  74. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  75. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  76. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  78. package/node_modules/@tomflow/chatloop-trace/README.md +10 -3
  79. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +4 -2
  80. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +109 -0
  81. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +12 -5
  82. package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
  83. package/node_modules/ps-list/index.d.ts +76 -0
  84. package/node_modules/ps-list/index.js +366 -0
  85. package/node_modules/ps-list/license +9 -0
  86. package/node_modules/ps-list/package.json +44 -0
  87. package/node_modules/ps-list/readme.md +56 -0
  88. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  89. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  90. package/package.json +9 -5
@@ -0,0 +1,227 @@
1
+ // Read-only Observer helper: no composer writes, Chrome Owner or sends.
2
+ (() => {
3
+ globalThis.ChatLoopObserverApprovalV1=({CONTRACT,inspect,
4
+ activeEvidenceConversation,messageId})=>
5
+ (message,reply)=>{
6
+ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
7
+ // Read-only, fail-closed two-stage approval proof for same-Chat adoption.
8
+ // An explicit model assertion or a copied task Context is never evidence.
9
+ const view=activeEvidenceConversation();
10
+ const fail = reason => reply({contract: CONTRACT, status:"UNVERIFIED",reason});
11
+ if (!view) {
12
+ fail("APPROVAL_CHAT_UNVERIFIED");return false;
13
+ }
14
+ const {path,nodes,role}=view;
15
+ const rows=nodes.map(el=>({el,role:role(el)}))
16
+ .filter(x=>["user","assistant"].includes(x.role));
17
+ const textOf=x=>(x.el.querySelector?.(".markdown")?.innerText
18
+ ||x.el.innerText||x.el.textContent||"").trim();
19
+ const confirms=(value,type)=>{
20
+ const line=value.replace(/\s+/g," ").trim();
21
+ if(!line||line.length>500)return false;
22
+ // Native R/P review controls send two explicit, task-scoped fields:
23
+ // "TASK|R2-ISSUE:<uuid>|我确认 R2 v2。..." (and likewise P2).
24
+ // Accept only a matching kind+version from a genuine user message,
25
+ // never arbitrary prose containing an approval quote or TEST_ONLY.
26
+ 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);
27
+ if(native){
28
+ const declared=native[2].toUpperCase(),approved=native[4].toUpperCase();
29
+ if(declared[0]!==type||declared!==approved
30
+ ||Number(declared.slice(1))!==Number(native[5]))return false;
31
+ const note=native[6];
32
+ if(/TEST_ONLY|NOT_APPROVED|只是测试|仅供测试|仅为引用|复制示例|不作为.{0,15}(?:审批|批准)|此确认无效/i.test(note))return false;
33
+ if(type==="R"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:需求|R[1-9][0-9]*)/i.test(note)
34
+ ||type==="P"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:方案|计划|P[1-9][0-9]*)/i.test(note)
35
+ ||type==="P"&&/(?:不授权|未授权|禁止|不要|不能).{0,15}(?:Start|执行|实施|开始|启动)/i.test(note))
36
+ return false;
37
+ return true;
38
+ }
39
+ const target=type==="R"
40
+ ? "(?:这份|当前|本版|上述)?(?:需求(?:R[1-9][0-9]*)?|R[1-9][0-9]*)"
41
+ : "(?:这份|当前|本版|上述)?(?:方案(?:与|及|和)?计划|实施计划|方案|计划|P[1-9][0-9]*)(?:P[1-9][0-9]*)?";
42
+ const affirmative=new RegExp("^(?:我)?(?:已经|已)?(?:确认|同意|批准)"+target+"[。.!!]?$","i");
43
+ // Keep the original standalone approval. Some real native R/P forms
44
+ // submit a scoped request ID followed by a direct affirmative sentence
45
+ // and bounded next-stage context in ONE genuine user message.
46
+ if(line.length<=100&&affirmative.test(line.replace(/\s+/g,"")))return true;
47
+ const scoped=line.match(/^([A-Z][A-Z0-9._:-]{7,120})[||]\s*([^。.!!]+[。.!!])\s*(.{1,320})$/i);
48
+ if(!scoped||!affirmative.test(scoped[2].replace(/\s+/g,"")))return false;
49
+ const note=scoped[3];
50
+ // A form's scope note cannot revoke approval, request the model to
51
+ // merely quote it, or explicitly withhold the approved plan's start.
52
+ if(/(?:TEST_ONLY|NOT_APPROVED|只是测试文字|只是引用|仅为引用|复制示例|不授权|未授权|并非授权|不代表.{0,15}(?:授权|确认|批准)|不作为.{0,10}(?:审批|批准|授权)|(?:仅|只是)(?:用|供|用于).{0,5}(?:测试|演示|验证))/i.test(note)
53
+ ||/(?:撤销|取消|拒绝|不通过|不同意|不批准)(?:当前|本次|这份)?(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(note)
54
+ ||type==="P"&&/(?:暂不|先不|不要|不能|不允许|禁止).{0,15}(?:执行|Start|实施|开始|启动|做)/i.test(note)
55
+ ||/(?:但|不过|只是).{0,12}(?:先不要|先不做|不做|不要做)/.test(note))return false;
56
+ return true;
57
+ };
58
+ // Prefer an explicit current-version declaration. Historical mentions
59
+ // must not choose a version; ambiguous prose is not approval evidence.
60
+ const versionOf=(value,type)=>{
61
+ // Real formal reviews may start with a status recap mentioning an
62
+ // older P2 before the issued heading "P3 v3|正式修订方案".
63
+ // A unique, version-consistent line title outranks historical prose.
64
+ const issued=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?("+type+"[1-9][0-9]*)\\s+v([1-9][0-9]*)\\s*[||]", "gi"))]
65
+ .filter(x=>Number(x[1].slice(1))===Number(x[2]))
66
+ .map(x=>x[1].toUpperCase());
67
+ const issuedVersions=[...new Set(issued)];
68
+ if(issuedVersions.length===1)return issuedVersions[0];
69
+ if(issuedVersions.length>1)return null;
70
+ const declared=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?(?:方案版本|需求版本|当前版本|版本)?[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
71
+ const current=[...value.matchAll(new RegExp("(?:本次|当前|本版)[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
72
+ 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()))];
73
+ return versions.length===1?versions[0]:null;
74
+ };
75
+ const lastUser=rows.findLastIndex(x=>x.role==="user");
76
+ if(lastUser<3 || rows[lastUser-1].role!=="assistant") {
77
+ fail("APPROVAL_SEQUENCE_UNVERIFIED");return false;
78
+ }
79
+ const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
80
+ // A plan document explicitly withheld in PLAN_DRAFT is not an issued
81
+ // review. A user cannot make it effective by typing a P1 approval after
82
+ // the assistant said the current plan was not presented for approval.
83
+ if(/(?:当前阶段[::]\s*PLAN_DRAFT|(?:维持|保持|仍为|停留在)\s*PLAN_DRAFT|方案(?:草稿)?.{0,20}(?:尚未|未曾|没有)正式(?:发布|提交)|(?:暂不|不(?:予|会|再)?)展示.{0,12}提交方案评审)/i.test(textOf(pAssistant))){
84
+ fail("APPROVAL_PLAN_NOT_ISSUED");return false;
85
+ }
86
+ if(!confirms(textOf(pUser),"P")
87
+ || !/(?:方案|计划)/.test(textOf(pAssistant))
88
+ || !/\bP[1-9][0-9]*\b/i.test(textOf(pAssistant))) {
89
+ fail("APPROVAL_PLAN_MISSING");return false;
90
+ }
91
+ const pVersion=versionOf(textOf(pAssistant),"P");
92
+ const pUserVersion=textOf(pUser).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
93
+ if(pUserVersion && pVersion!==pUserVersion){
94
+ fail("APPROVAL_PLAN_VERSION_MISMATCH");return false;
95
+ }
96
+ const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
97
+ &&confirms(textOf(x),"R"));
98
+ // Long chats virtualize old turns. A still-mounted native R2 user
99
+ // approval at index 0 has its exact issued R2-ISSUE identity, even when
100
+ // the original R2 assistant has scrolled out of the DOM window.
101
+ // This fallback is ONLY for native issue-scoped approvals. The Native
102
+ // Context Start lease independently verifies the effective R approval.
103
+ const rUser=rIndex>=0?rows[rIndex]:null;
104
+ 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);
105
+ const nativeRVersion=nativeR
106
+ &&nativeR[1].toUpperCase()===nativeR[2].toUpperCase()
107
+ &&Number(nativeR[1].slice(1))===Number(nativeR[3])
108
+ ?nativeR[1].toUpperCase():null;
109
+ const rAssistant=rIndex>0?rows[rIndex-1]:null;
110
+ if(rIndex<0 || rIndex===0&&!nativeRVersion
111
+ ||rIndex>0&&rAssistant?.role!=="assistant"){
112
+ fail("APPROVAL_REQUIREMENTS_MISSING");return false;
113
+ }
114
+ if(message.expectedTaskId!==undefined){
115
+ // A no-URL idle adoption is only eligible for its exact Managed
116
+ // Task's TWO native issued approval messages in the same DOM Chat.
117
+ // No standalone historical affirmations or copied Task summaries.
118
+ const task=message.expectedTaskId;
119
+ const nativeIssue=(row,type)=>typeof task==="string"
120
+ &&/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(task)
121
+ &&textOf(row).startsWith(task+"|")
122
+ &&new RegExp("^"+type+"[1-9][0-9]*-ISSUE:"
123
+ +"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]\\s*我确认\\s+"
124
+ +type+"[1-9][0-9]*\\s+v[1-9][0-9]*","i")
125
+ .test(textOf(row).slice(task.length+1));
126
+ if(!nativeRVersion||!nativeIssue(rUser,"R")
127
+ ||!nativeIssue(pUser,"P")){
128
+ fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
129
+ }
130
+ }
131
+ // Only document-level TEST_ONLY markers deny production adoption:
132
+ // normal P plans can legitimately mention test-only scenarios.
133
+ const testOnlyReview=x=>
134
+ /(?:^|\n)\s*(?:#{1,6}\s*|>\s*)?(?:\*\*)?TEST_ONLY(?:\*\*)?(?:\s*$|\s*[/||:]\s*NOT_APPROVED)/mi
135
+ .test(textOf(x));
136
+ if(rAssistant&&testOnlyReview(rAssistant)||testOnlyReview(pAssistant)){
137
+ fail("APPROVAL_TEST_ONLY");return false;
138
+ }
139
+ if(rAssistant&&(!/(?:需求|范围|验收)/.test(textOf(rAssistant))
140
+ || !/\bR[1-9][0-9]*\b/i.test(textOf(rAssistant)))) {
141
+ fail("APPROVAL_REQUIREMENTS_MISSING");return false;
142
+ }
143
+ const rVersion=rAssistant?versionOf(textOf(rAssistant),"R"):nativeRVersion;
144
+ const intervening=rows.slice(rIndex+1,lastUser-1);
145
+ const invalidated=intervening.some(x=>{
146
+ const text=textOf(x);
147
+ if(x.role==="assistant"){
148
+ const next=versionOf(text,"R");
149
+ return /需求|范围|验收/.test(text)&&next&&next!==rVersion;
150
+ }
151
+ // "修订 P3、保留 R2" is a plan update, NOT an R2 revocation.
152
+ // Only an explicit requirement-targeted change invalidates this R.
153
+ return /(?:撤销|取消|拒绝|不同意|不批准|修改|修订|变更)\s*(?:(?:当前|本次|这份|上述)\s*)?(?:需求|R[1-9][0-9]*)/i.test(text)
154
+ || /\bR[1-9][0-9]*\b\s*(?:需求)?\s*(?:需要|应当|应该)?\s*(?:撤销|取消|拒绝|修改|修订|变更)/i.test(text);
155
+ });
156
+ if(!pVersion||!rVersion||invalidated){
157
+ fail("APPROVAL_REVISED_OR_REVOKED");return false;
158
+ }
159
+ const rUserVersion=textOf(rUser).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
160
+ const referencedR=textOf(pAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
161
+ if(!referencedR || referencedR!==rVersion){
162
+ fail("APPROVAL_PLAN_REQUIREMENT_MISMATCH");return false;
163
+ }
164
+ if(rUserVersion && rVersion!==rUserVersion){
165
+ fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
166
+ }
167
+ // An explicit Chat URL may be adopted after the P-approval assistant
168
+ // finishes, but that reply might instead have issued R2/P2. Such a
169
+ // revision invalidates the earlier P1 approval even if the last user
170
+ // message is still the old standalone confirmation.
171
+ const revisedAfterApproval=rows.slice(lastUser+1).some(x=>{
172
+ if(x.role!=="assistant")return false;
173
+ const text=textOf(x),nextR=versionOf(text,"R"),
174
+ nextP=versionOf(text,"P");
175
+ return Boolean(
176
+ /(?:需求|范围|验收)/.test(text)&&nextR&&nextR!==rVersion
177
+ ||/(?:方案|计划)/.test(text)&&nextP&&nextP!==pVersion
178
+ ||/(?:SUPERSEDED|已失效|已废弃|已撤销)/i.test(text)
179
+ &&/(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(text)
180
+ );
181
+ });
182
+ if(revisedAfterApproval){
183
+ fail("APPROVAL_REVISED_AFTER_CONFIRMATION");return false;
184
+ }
185
+ const userKey=messageId(pUser.el,"user");
186
+ const snap=inspect();
187
+ // Normally the model calls Start during its P-confirmation Turn.
188
+ // A fresh, explicitly scoped native Start intent can also adopt AFTER
189
+ // that assistant Turn ends (e.g. MCP schema was stale in the same Chat).
190
+ // Only the exact current Chat ID, last R/P approval user identity and
191
+ // completed assistant reply qualify. A historical unscoped idle Chat
192
+ // must never become an Owner just because R/P messages are visible.
193
+ const explicitChatId=typeof message.explicitChatId==="string"
194
+ ? message.explicitChatId.toLowerCase():null;
195
+ const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
196
+ // The managed lease may scope an idle, already-open Chat by the exact
197
+ // Task ID in BOTH real native R/P approval turns. No task scope from
198
+ // copied Context prose or generic unscoped historical confirmations.
199
+ const issueTask=x=>textOf(x).match(
200
+ /^([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;
201
+ const taskScoped=typeof message.expectedTaskId==="string"
202
+ &&message.expectedTaskId.length>=8
203
+ &&issueTask(rUser)===message.expectedTaskId
204
+ &&issueTask(pUser)===message.expectedTaskId;
205
+ if(message.expectedTaskId!==undefined&&!taskScoped){
206
+ fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
207
+ }
208
+ const scopedIdle=Boolean(
209
+ (explicitChatId&&explicitChatId===currentId||taskScoped)
210
+ &&!snap.stop&&!snap.busy&&snap.assistantKey
211
+ &&snap.composerReady&&snap.copyAction&&snap.text
212
+ &&!snap.pendingConfirmation);
213
+ if(!userKey ||snap.path!==path||snap.userKey!==userKey
214
+ ||!(snap.stop||snap.busy||scopedIdle)
215
+ ||snap.fatal||snap.dialog||snap.toolUnknown){
216
+ fail("APPROVAL_LAST_TURN_UNVERIFIED");return false;
217
+ }
218
+ reply({contract:CONTRACT,status:"VERIFIED",page:path,
219
+ userKey,rVersion,pVersion,priorAssistantKey:messageId(pAssistant.el,"assistant"),
220
+ // Idle post-approval assistant was completed BEFORE adoption.
221
+ // This is a historical baseline, never a fresh execution Turn.
222
+ ...(scopedIdle?{postApprovalAssistantKey:snap.assistantKey}:{})});
223
+ return false;
224
+ }
225
+ return false;
226
+ };
227
+ })();
@@ -0,0 +1,144 @@
1
+ // Read-only Observer helper: no composer writes, Chrome Owner or sends.
2
+ (() => {
3
+ globalThis.ChatLoopObserverInspectV1=({conversationPath,visible,messageId})=>{
4
+ function activeEvidenceConversation() {
5
+ const path=conversationPath();
6
+ if(!path)return null;
7
+ const mains=[...document.querySelectorAll("main")].filter(visible);
8
+ if(mains.length!==1)return null;
9
+ const main=mains[0];
10
+ const legacy=[...main.querySelectorAll(
11
+ '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
12
+ const nodes=legacy.length?legacy:[...main.querySelectorAll(
13
+ '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
14
+ const role=node=>node.getAttribute("data-message-author-role")
15
+ ||node.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
16
+ return {path,nodes,role};
17
+ }
18
+ function inspect() {
19
+ const path = conversationPath();
20
+ if (!path) return {path: "", unavailable: "CHAT_NOT_IDENTIFIED"};
21
+ // ChatGPT can keep multiple conversation <main> nodes in the DOM;
22
+ // only the currently rendered one may supply Turn identity or status.
23
+ const mains = [...document.querySelectorAll("main")].filter(visible);
24
+ if (mains.length !== 1) return {path,
25
+ unavailable: mains.length ? "MAIN_AMBIGUOUS" : "MAIN_UNAVAILABLE"};
26
+ const main = mains[0];
27
+ const legacy = [...main.querySelectorAll(
28
+ '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
29
+ const roles = legacy.length ? legacy : [...main.querySelectorAll(
30
+ '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
31
+ const roleOf = el => el.getAttribute?.("data-message-author-role")
32
+ || el.getAttribute?.("data-chatgpt-search-unit-key")?.split(":").at(-1);
33
+ const userIndex = roles.findLastIndex(el => roleOf(el) === "user");
34
+ const lastUser = userIndex >= 0 ? roles[userIndex] : null;
35
+ const afterUser = roles.slice(userIndex + 1).filter(el => roleOf(el) === "assistant");
36
+ const lastAssistant = afterUser.at(-1) || null;
37
+ const lastHistoricAssistant = roles.filter(el => roleOf(el) === "assistant").at(-1);
38
+ const userKey = messageId(lastUser, "user");
39
+ const assistantKey = messageId(lastAssistant, "assistant");
40
+ const historicAssistantKey = messageId(lastHistoricAssistant, "assistant");
41
+ // The immediately preceding assistant before a NEW user Turn is the
42
+ // only eligible confirmation anchor. Historical interactive cards do
43
+ // not block a later assistant Turn or authorize a new action.
44
+ const priorIndex = roles.findLastIndex((el, i) =>
45
+ i < userIndex && roleOf(el) === "assistant");
46
+ const priorAssistant = priorIndex >= 0 ? roles[priorIndex] : null;
47
+ const priorAssistantKey = messageId(priorAssistant, "assistant");
48
+ const priorUser = priorIndex > 0 ? roles.slice(0,priorIndex)
49
+ .filter(el=>roleOf(el)==="user").at(-1) : null;
50
+ const priorAssistantUserKey = messageId(priorUser,"user");
51
+ const directReplyAfterPriorAssistant = priorIndex>=0
52
+ && !roles.slice(priorIndex+1,userIndex).some(el=>roleOf(el)==="user");
53
+ const scope = lastAssistant?.closest?.('[data-testid^="conversation-turn-"]')
54
+ || lastAssistant?.closest?.('[data-talvt-turn-state]') || lastAssistant;
55
+ const reply = lastAssistant?.querySelector?.(".markdown") || lastAssistant;
56
+ const text = (reply?.innerText ?? reply?.textContent ?? "").trim();
57
+ // A Chat Loop confirmation is a REAL actionable choice surface in the
58
+ // latest assistant Turn, never a form elsewhere on the page. Disabled
59
+ // Submit still means pending: no user message has yet been submitted.
60
+ const controls = [...scope?.querySelectorAll?.(
61
+ '[role="radiogroup"],[role="radio"],input[type="radio"],' +
62
+ 'select,[role="combobox"],textarea,[role="textbox"],' +
63
+ 'input[type="checkbox"],[role="checkbox"]') || []];
64
+ const submit = [...scope?.querySelectorAll?.('button') || []].some(button =>
65
+ visible(button) && /(?:提交|确认|submit|confirm)/i.test(
66
+ (button.innerText || button.textContent ||
67
+ button.getAttribute?.("aria-label") || "").trim()));
68
+ const labels = (scope?.innerText || scope?.textContent || "").slice(-2000);
69
+ const pendingConfirmation = Boolean(lastAssistant && submit
70
+ && controls.some(visible)
71
+ && /(?:确认|修改|不通过|拒绝|自定义|approval|revise|reject|choice)/i.test(labels));
72
+ const stop = [...document.querySelectorAll(
73
+ 'button[data-testid="stop-button"],button[aria-label="Stop generating"],' +
74
+ 'button[aria-label="Stop"],button[aria-label="停止生成"],' +
75
+ 'button[aria-label="停止响应"]')].some(visible);
76
+ const busy = afterUser.some(node => {
77
+ const part = node.closest?.('[data-testid^="conversation-turn-"]')
78
+ || node.closest?.('[data-talvt-turn-state]') || node;
79
+ return [...part.querySelectorAll?.('[aria-busy="true"],[data-tool-status="running"],' +
80
+ '[data-state="running"],[data-testid="tool-running"]') || []].some(visible);
81
+ });
82
+ const toolParts = afterUser.flatMap(node => {
83
+ const part = node.closest?.('[data-testid^="conversation-turn-"]')
84
+ || node.closest?.('[data-talvt-turn-state]') || node;
85
+ return [...part.querySelectorAll?.('[data-testid*="tool"],[data-tool-status]') || []];
86
+ });
87
+ const toolUnknown = toolParts.some(el => {
88
+ if (!visible(el)) return false;
89
+ if (el.matches?.('[data-tool-status="running"],[data-testid="tool-running"]')) {
90
+ return false;
91
+ }
92
+ const status = el.getAttribute?.("data-tool-status")
93
+ || el.getAttribute?.("data-state") || "";
94
+ // A failed/cancelled tool call can be terminal as a *tool result* while
95
+ // the assistant may continue and finish its own Turn. Page-level errors
96
+ // are handled separately by snap.fatal; never equate tool failure to
97
+ // a completed assistant reply.
98
+ return !/^(done|complete|completed|success|succeeded|finished|failed|error|cancelled|canceled)$/i.test(status)
99
+ && !el.matches?.('[data-testid*="tool-completed"],[data-testid*="tool-finished"]');
100
+ });
101
+ const editor = document.querySelector(
102
+ '#prompt-textarea[contenteditable="true"],' +
103
+ '[data-testid="composer-input"][contenteditable="true"],' +
104
+ '[contenteditable="true"][data-composer-markdown],' +
105
+ '[contenteditable="true"][data-placeholder]');
106
+ const composerReady = visible(editor) && !editor.closest?.('[aria-disabled="true"]');
107
+ const copyAction = scope && [...scope.querySelectorAll?.(
108
+ 'button[data-testid="copy-turn-action-button"],' +
109
+ 'button[aria-label="Copy"],button[aria-label="Copy response"],' +
110
+ 'button[aria-label="复制"],button[aria-label="复制回复"]') || []].some(visible);
111
+ // A visible interruption banner is not a completed assistant Turn, even
112
+ // when a partial reply has Copy and no Stop button.
113
+ const errorPattern = /unknown error|something went wrong|an error occurred|unable to load|connection (?:lost|interrupted)|waiting for (?:full|complete) response|发生错误|出错了|请求失败|网络错误|连接已中断|正在等待完整答复/i;
114
+ const errorNodes = [...main.querySelectorAll(
115
+ '[role="alert"],[role="status"],[data-testid="conversation-error"],' +
116
+ '[data-testid*="connection-status"]')].filter(visible);
117
+ // Only explicit conversation/context exhaustion is eligible for error Handoff.
118
+ // Generic Unknown error is never evidence of a capacity limit.
119
+ 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;
120
+ const contextLimit = errorNodes.some(el => contextLimitPattern.test(el.innerText ?? el.textContent ?? ""));
121
+ // An anti-bot/security challenge is not an ordinary generation failure.
122
+ // A visible native Retry is NOT permission to automate bypass attempts.
123
+ const securityChallenge = errorNodes.some(el =>
124
+ /\bcloudflare_challenge\b/i.test(el.innerText ?? el.textContent ?? ""));
125
+ const fatal = contextLimit || securityChallenge || errorNodes.some(el =>
126
+ errorPattern.test(el.innerText ?? el.textContent ?? ""));
127
+ const retryAvailable = !contextLimit && !securityChallenge && errorNodes.some(el =>
128
+ [...el.querySelectorAll?.('button') || []].some(button => visible(button)
129
+ && /^(?:retry|try again|重试|再试一次)$/i.test(
130
+ (button.innerText || button.textContent || button.getAttribute?.('aria-label') || '').trim())));
131
+ const dialog = [...document.querySelectorAll(
132
+ '[role="dialog"][aria-modal="true"],dialog[open]')].some(visible);
133
+ const turnState = scope?.getAttribute?.("data-talvt-turn-state") || null;
134
+ return {path, userKey, assistantKey, historicAssistantKey, priorAssistantKey,
135
+ priorAssistantUserKey, directReplyAfterPriorAssistant,
136
+ pendingConfirmation, text,
137
+ hasUser: Boolean(lastUser), hasAssistant: Boolean(lastAssistant),
138
+ stop, busy, toolUnknown, turnState, composerReady, copyAction,
139
+ fatal, errorReason: securityChallenge ? "SECURITY_CHALLENGE"
140
+ : contextLimit ? "CONTEXT_LIMIT" : "PAGE_ERROR", retryAvailable, dialog};
141
+ }
142
+ return {activeEvidenceConversation,inspect};
143
+ };
144
+ })();
@@ -0,0 +1,171 @@
1
+ // Read-only Observer helper: no composer writes, Chrome Owner or sends.
2
+ (() => {
3
+ globalThis.ChatLoopObserverPollV1=({session,inspect,emit,resetCandidate,
4
+ fingerprint,STABLE_MS,getState})=>{
5
+ function poll() {
6
+ try {
7
+ const snap = inspect();
8
+ if (!snap.path) {
9
+ // Preserve a fresh homepage submit, but discard stale submit intent
10
+ // when leaving an already identified conversation.
11
+ if (session.path) session.firstSendSeen = false;
12
+ session.path = "";
13
+ session.sawHomepage = true;
14
+ session.attaching = false;
15
+ session.attachingFirstTurn = false;
16
+ resetCandidate();
17
+ return emit("UNKNOWN", snap.unavailable, snap);
18
+ }
19
+ if (snap.unavailable || snap.hasUser && !snap.userKey) {
20
+ resetCandidate();
21
+ return emit("UNKNOWN", snap.unavailable || "USER_ID_MISSING", snap);
22
+ }
23
+ if (snap.path !== session.path) {
24
+ const cameFromAnotherPage = Boolean(session.path) || session.sawHomepage;
25
+ const recentSend = !session.path && session.firstSendSeen
26
+ && Date.now() - session.firstSendAt <= 30000;
27
+ const firstTurn = recentSend && Boolean(snap.userKey);
28
+ session.firstSendSeen = false;
29
+ session.sawHomepage = false;
30
+ const previousUser = getState().userKey || null;
31
+ session.path = snap.path;
32
+ session.baselineUser = firstTurn ? null : snap.userKey;
33
+ session.baselineAssistant = firstTurn ? null : snap.historicAssistantKey;
34
+ session.pendingUser = firstTurn ? snap.userKey : null;
35
+ session.completedUser = null;
36
+ resetCandidate();
37
+ session.attachingFirstTurn = recentSend && !snap.userKey;
38
+ // Cold content-script startup can precede historical message hydration.
39
+ // An empty /c/ route is not proof the conversation has no history.
40
+ session.attaching = !recentSend && (cameFromAnotherPage || !snap.userKey);
41
+ session.priorUser = cameFromAnotherPage ? previousUser : null;
42
+ session.attachSignature = "";
43
+ session.attachSince = 0;
44
+ if (firstTurn) return emit("RUNNING", "FIRST_CHAT_TURN_SUBMITTED", snap);
45
+ if (session.attachingFirstTurn) {
46
+ session.baselineUser = null;
47
+ session.baselineAssistant = null;
48
+ return emit("RUNNING", "WAITING_FIRST_USER", snap);
49
+ }
50
+ if (session.attaching) {
51
+ session.baselineUser = null;
52
+ session.baselineAssistant = null;
53
+ return emit("UNKNOWN", "ATTACHING_CHAT", snap);
54
+ }
55
+ return emit(snap.stop || snap.busy ? "UNKNOWN" : "IDLE",
56
+ snap.stop || snap.busy ? "ATTACHED_MID_TURN" : "BASELINE_ESTABLISHED", snap);
57
+ }
58
+
59
+ if (session.attachingFirstTurn) {
60
+ if (Date.now() - session.firstSendAt > 30000) {
61
+ session.firstSendSeen = false;
62
+ session.attachingFirstTurn = false;
63
+ session.attaching = true;
64
+ return emit("UNKNOWN", "FIRST_USER_NOT_CONFIRMED", snap);
65
+ }
66
+ if (!snap.userKey) return emit("RUNNING", "WAITING_FIRST_USER", snap);
67
+ session.firstSendSeen = false;
68
+ session.attachingFirstTurn = false;
69
+ session.pendingUser = snap.userKey;
70
+ return emit("RUNNING", "FIRST_CHAT_TURN_SUBMITTED", snap);
71
+ }
72
+ if (session.attaching) {
73
+ if (!snap.userKey) return emit("UNKNOWN", "WAITING_CHAT_HYDRATION", snap);
74
+ if (session.priorUser && snap.userKey === session.priorUser) {
75
+ session.attachSignature = "";
76
+ return emit("UNKNOWN", "STALE_PREVIOUS_CHAT_DOM", snap);
77
+ }
78
+ if (snap.stop || snap.busy || snap.turnState && snap.turnState !== "complete") {
79
+ session.attachSignature = "";
80
+ return emit("UNKNOWN", "ATTACHED_MID_TURN", snap);
81
+ }
82
+ if (!snap.composerReady || snap.hasAssistant && !snap.assistantKey) {
83
+ session.attachSignature = "";
84
+ return emit("UNKNOWN", "ATTACHING_CHAT", snap);
85
+ }
86
+ const signature = snap.userKey + "|" + (snap.historicAssistantKey || "");
87
+ if (signature !== session.attachSignature) {
88
+ session.attachSignature = signature;
89
+ session.attachSince = Date.now();
90
+ return emit("UNKNOWN", "ATTACHING_CHAT", snap);
91
+ }
92
+ if (Date.now() - session.attachSince < STABLE_MS) {
93
+ return emit("UNKNOWN", "WAITING_CHAT_HYDRATION", snap);
94
+ }
95
+ session.attaching = false;
96
+ session.priorUser = null;
97
+ session.baselineUser = snap.userKey;
98
+ session.baselineAssistant = snap.historicAssistantKey;
99
+ session.pendingUser = null;
100
+ return emit("IDLE", "BASELINE_ESTABLISHED", snap);
101
+ }
102
+ if (snap.fatal || snap.dialog) {
103
+ resetCandidate();
104
+ // A visible page failure must reach the owner, not merely update the
105
+ // content-script's local status. Report once for the specific pending
106
+ // user Turn; Worker independently verifies the same error twice.
107
+ if (snap.fatal && snap.userKey && snap.userKey !== session.completedUser
108
+ && (snap.userKey === session.pendingUser
109
+ || session.baselineUser && snap.userKey !== session.baselineUser)
110
+ && session.reportedErrorUser !== snap.userKey) {
111
+ session.reportedErrorUser = snap.userKey;
112
+ void Promise.resolve(chrome.runtime.sendMessage({
113
+ type: "CHAT_LOOP_TURN_BLOCKED_V1", page: snap.path,
114
+ userKey: snap.userKey, reason: snap.errorReason,
115
+ retryAvailable: snap.retryAvailable === true
116
+ })).catch(() => {});
117
+ }
118
+ return emit(snap.fatal ? "BLOCKED" : "UNKNOWN",
119
+ snap.fatal ? snap.errorReason : "MODAL_PRESENT", snap);
120
+ }
121
+ if (!snap.userKey || snap.userKey === session.baselineUser
122
+ && session.pendingUser === null) {
123
+ return emit("IDLE", "NO_NEW_USER_TURN", snap);
124
+ }
125
+ if (snap.userKey === session.completedUser) {
126
+ return emit("IDLE", "TURN_ALREADY_EMITTED", snap);
127
+ }
128
+ if (snap.userKey !== session.pendingUser) {
129
+ if (!session.firstTurnAt) session.firstTurnAt = Date.now();
130
+ session.pendingUser = snap.userKey;
131
+ session.candidate = "";
132
+ session.stableSince = 0;
133
+ }
134
+ if (snap.hasAssistant && !snap.assistantKey) {
135
+ resetCandidate();
136
+ return emit("UNKNOWN", "ASSISTANT_ID_MISSING", snap);
137
+ }
138
+ if (!snap.assistantKey || snap.assistantKey === session.baselineAssistant) {
139
+ return emit("RUNNING", "WAITING_FOR_NEW_ASSISTANT", snap);
140
+ }
141
+ if (snap.stop || snap.busy || snap.turnState && snap.turnState !== "complete") {
142
+ session.candidate = "";
143
+ return emit("RUNNING", snap.busy ? "TOOL_OR_ASSISTANT_BUSY" : "STOP_BUTTON_PRESENT", snap);
144
+ }
145
+ if (snap.toolUnknown) {
146
+ session.candidate = "";
147
+ return emit("UNKNOWN", "TOOL_COMPLETION_UNVERIFIED", snap);
148
+ }
149
+ if (!snap.composerReady || !snap.copyAction || !snap.text) {
150
+ session.candidate = "";
151
+ return emit("UNKNOWN", "FINAL_UI_EVIDENCE_MISSING", snap);
152
+ }
153
+ const signature = snap.userKey + "|" + snap.assistantKey + "|" + fingerprint(snap.text);
154
+ if (signature !== session.candidate) {
155
+ session.candidate = signature;
156
+ session.stableSince = Date.now();
157
+ return emit("RUNNING", "ANSWER_NOT_YET_STABLE", snap);
158
+ }
159
+ if (Date.now() - session.stableSince < STABLE_MS) {
160
+ return emit("RUNNING", "WAITING_FOR_STABILITY", snap);
161
+ }
162
+ session.completedUser = snap.userKey;
163
+ return emit("TURN_FINISHED", "EVIDENCE_CONFIRMED", snap, true);
164
+ } catch (error) {
165
+ resetCandidate();
166
+ return emit("UNKNOWN", "OBSERVER_EXCEPTION", {path: session.path});
167
+ }
168
+ }
169
+ return poll;
170
+ };
171
+ })();
@@ -0,0 +1,109 @@
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
+ })();