@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,299 +0,0 @@
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
- // Current independent Form App submits exactly one original user Turn.
20
- // Its A-choice receipt differs from older issue-scoped prose. Match the
21
- // full bounded host template, two UUIDs, choice and R/P-labelled version;
22
- // a summary, B-choice or casual affirmation is not Form evidence.
23
- // This is SOFT evidence only: a text-shaped copy is not host-signed,
24
- // so Context's independent Start lease remains mandatory.
25
- const formApprovalVersion=(value,type)=>{
26
- const lines=value.split(/\r?\n/).map(x=>x.trim()).filter(Boolean);
27
- if(lines.length!==6
28
- ||lines[0]!=='Chat Loop Form 提交结果(由用户点击表单提交)'
29
- ||!/^formId:\s*[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(lines[1])
30
- ||!/^traceRef:\s*[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(lines[2])
31
- ||lines[3]!=='选项值: A'
32
- ||lines[5]!=='请核对当前业务任务、文档与 Issue 版本及原生消息身份后处理本次选择;表单回执本身不构成审批或写权。')
33
- return null;
34
- const label=lines[4].match(/^选项标签:\s*A[||]\s*确认当前\s*([RP][1-9][0-9]*)\s*(需求|技术与验证方案|技术方案|方案)$/i);
35
- if(!label||label[1][0].toUpperCase()!==type
36
- ||(type==='R')!==(label[2]==='需求'))return null;
37
- const formId=lines[1].slice('formId:'.length).trim().toLowerCase();
38
- const traceRef=lines[2].slice('traceRef:'.length).trim().toLowerCase();
39
- return formId===traceRef?null:{version:label[1].toUpperCase(),formId,traceRef};
40
- };
41
- const confirms=(value,type)=>{
42
- const line=value.replace(/\s+/g," ").trim();
43
- if(!line||line.length>500)return false;
44
- if(formApprovalVersion(value,type))return true;
45
- // Native R/P review controls send two explicit, task-scoped fields:
46
- // "TASK|Rn-ISSUE:<uuid>|我确认 Rn vN。" (and the Pn equivalent).
47
- // Accept only a matching kind+version from a genuine user message,
48
- // never arbitrary prose containing an approval quote or TEST_ONLY.
49
- 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);
50
- if(native){
51
- const declared=native[2].toUpperCase(),approved=native[4].toUpperCase();
52
- if(declared[0]!==type||declared!==approved
53
- ||Number(declared.slice(1))!==Number(native[5]))return false;
54
- const note=native[6];
55
- if(/TEST_ONLY|NOT_APPROVED|只是测试|仅供测试|仅为引用|复制示例|不作为.{0,15}(?:审批|批准)|此确认无效/i.test(note))return false;
56
- if(type==="R"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:需求|R[1-9][0-9]*)/i.test(note)
57
- ||type==="P"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:方案|计划|P[1-9][0-9]*)/i.test(note)
58
- ||type==="P"&&/(?:不授权|未授权|禁止|不要|不能).{0,15}(?:Start|执行|实施|开始|启动)/i.test(note))
59
- return false;
60
- return true;
61
- }
62
- const target=type==="R"
63
- ? "(?:这份|当前|本版|上述)?(?:需求(?:R[1-9][0-9]*)?|R[1-9][0-9]*)"
64
- : "(?:这份|当前|本版|上述)?(?:方案(?:与|及|和)?计划|实施计划|方案|计划|P[1-9][0-9]*)(?:P[1-9][0-9]*)?";
65
- const affirmative=new RegExp("^(?:我)?(?:已经|已)?(?:确认|同意|批准)"+target+"[。.!!]?$","i");
66
- // Keep the original standalone approval. Some real native R/P forms
67
- // submit a scoped request ID followed by a direct affirmative sentence
68
- // and bounded next-stage context in ONE genuine user message.
69
- if(line.length<=100&&affirmative.test(line.replace(/\s+/g,"")))return true;
70
- const scoped=line.match(/^([A-Z][A-Z0-9._:-]{7,120})[||]\s*([^。.!!]+[。.!!])\s*(.{1,320})$/i);
71
- if(!scoped||!affirmative.test(scoped[2].replace(/\s+/g,"")))return false;
72
- const note=scoped[3];
73
- // A form's scope note cannot revoke approval, request the model to
74
- // merely quote it, or explicitly withhold the approved plan's start.
75
- if(/(?:TEST_ONLY|NOT_APPROVED|只是测试文字|只是引用|仅为引用|复制示例|不授权|未授权|并非授权|不代表.{0,15}(?:授权|确认|批准)|不作为.{0,10}(?:审批|批准|授权)|(?:仅|只是)(?:用|供|用于).{0,5}(?:测试|演示|验证))/i.test(note)
76
- ||/(?:撤销|取消|拒绝|不通过|不同意|不批准)(?:当前|本次|这份)?(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(note)
77
- ||type==="P"&&/(?:暂不|先不|不要|不能|不允许|禁止).{0,15}(?:执行|Start|实施|开始|启动|做)/i.test(note)
78
- ||/(?:但|不过|只是).{0,12}(?:先不要|先不做|不做|不要做)/.test(note))return false;
79
- return true;
80
- };
81
- // Prefer an explicit current-version declaration. Historical mentions
82
- // must not choose a version; ambiguous prose is not approval evidence.
83
- const versionOf=(value,type)=>{
84
- // Real formal reviews may start with a status recap mentioning an
85
- // an older plan version before the current issued revision heading.
86
- // A unique, version-consistent line title outranks historical prose.
87
- const issued=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?("+type+"[1-9][0-9]*)\\s+v([1-9][0-9]*)\\s*[||]", "gi"))]
88
- .filter(x=>Number(x[1].slice(1))===Number(x[2]))
89
- .map(x=>x[1].toUpperCase());
90
- const issuedVersions=[...new Set(issued)];
91
- if(issuedVersions.length===1)return issuedVersions[0];
92
- if(issuedVersions.length>1)return null;
93
- const declared=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?(?:方案版本|需求版本|当前版本|版本)?[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
94
- const current=[...value.matchAll(new RegExp("(?:本次|当前|本版)[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
95
- 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()))];
96
- return versions.length===1?versions[0]:null;
97
- };
98
- const lastUser=rows.findLastIndex(x=>x.role==="user");
99
- // ChatGPT can virtualize the initial R issuing assistant while keeping
100
- // both original Form A user Turns and the issued P assistant mounted.
101
- // Only an explicitly named current Chat plus the exact Form template
102
- // may use this bounded partial-DOM proof. A Context Start lease must
103
- // still independently authorize the R/P approvals and current Task.
104
- const currentChatId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
105
- const explicitFormChat=typeof message.explicitChatId==='string'
106
- &&message.explicitChatId.toLowerCase()===currentChatId;
107
- const virtualizedR=lastUser===2&&explicitFormChat
108
- &&rows[0]?.role==='user'&&!!formApprovalVersion(textOf(rows[0]),'R')
109
- &&rows[1]?.role==='assistant'&&rows[2]?.role==='user';
110
- if((lastUser<3&&!virtualizedR)||rows[lastUser-1]?.role!=="assistant") {
111
- fail("APPROVAL_SEQUENCE_UNVERIFIED");return false;
112
- }
113
- const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
114
- // A plan document explicitly withheld in PLAN_DRAFT is not an issued
115
- // review. A user cannot make it effective by typing a plan approval after
116
- // the assistant said the current plan was not presented for approval.
117
- if(/(?:当前阶段[::]\s*PLAN_DRAFT|(?:维持|保持|仍为|停留在)\s*PLAN_DRAFT|方案(?:草稿)?.{0,20}(?:尚未|未曾|没有)正式(?:发布|提交)|(?:暂不|不(?:予|会|再)?)展示.{0,12}提交方案评审)/i.test(textOf(pAssistant))){
118
- fail("APPROVAL_PLAN_NOT_ISSUED");return false;
119
- }
120
- if(!confirms(textOf(pUser),"P")
121
- || !/(?:方案|计划)/.test(textOf(pAssistant))
122
- || !/\bP[1-9][0-9]*\b/i.test(textOf(pAssistant))) {
123
- fail("APPROVAL_PLAN_MISSING");return false;
124
- }
125
- const pVersion=versionOf(textOf(pAssistant),"P");
126
- const pUserVersion=textOf(pUser).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
127
- if(pUserVersion && pVersion!==pUserVersion){
128
- fail("APPROVAL_PLAN_VERSION_MISMATCH");return false;
129
- }
130
- const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
131
- &&confirms(textOf(x),"R"));
132
- // Long chats virtualize old turns. A still-mounted native Rn user
133
- // approval at index 0 retains its exact issue identity, even when
134
- // the issuing assistant has scrolled out of the DOM window.
135
- // This fallback is ONLY for native issue-scoped approvals. The Native
136
- // Context Start lease independently verifies the effective R approval.
137
- const rUser=rIndex>=0?rows[rIndex]:null;
138
- const rForm=rUser?formApprovalVersion(textOf(rUser),'R'):null;
139
- const pForm=formApprovalVersion(textOf(pUser),'P');
140
- if(rForm&&pForm&&(rForm.formId===pForm.formId
141
- ||rForm.traceRef===pForm.traceRef)){
142
- fail('APPROVAL_FORM_REUSED');return false;
143
- }
144
- 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);
145
- const nativeRVersion=nativeR
146
- &&nativeR[1].toUpperCase()===nativeR[2].toUpperCase()
147
- &&Number(nativeR[1].slice(1))===Number(nativeR[3])
148
- ?nativeR[1].toUpperCase():null;
149
- const rAssistant=rIndex>0?rows[rIndex-1]:null;
150
- if(rIndex<0 || rIndex===0&&!nativeRVersion
151
- &&!(virtualizedR&&rForm)
152
- ||rIndex>0&&rAssistant?.role!=="assistant"){
153
- fail("APPROVAL_REQUIREMENTS_MISSING");return false;
154
- }
155
- // For a managed no-URL Start the Worker supplies each already-open
156
- // Chat's own ID. Exact current Form A pairs are *candidates* only while
157
- // the P-confirmation Turn is live. The Task is NOT inferred from Form
158
- // prose; Native Context must compare both original approval sources
159
- // against the reserved Task before any Owner can be committed.
160
- const task=message.expectedTaskId;
161
- const formPairCandidate=Boolean(typeof task==='string'
162
- &&/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(task)
163
- &&explicitFormChat&&rForm&&pForm);
164
- if(task!==undefined&&!formPairCandidate){
165
- // A no-URL idle adoption still needs both Task-scoped issued turns.
166
- // No standalone historical affirmations or copied Task summaries.
167
- const nativeIssue=(row,type)=>typeof task==="string"
168
- &&/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(task)
169
- &&textOf(row).startsWith(task+"|")
170
- &&new RegExp("^"+type+"[1-9][0-9]*-ISSUE:"
171
- +"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]\\s*我确认\\s+"
172
- +type+"[1-9][0-9]*\\s+v[1-9][0-9]*","i")
173
- .test(textOf(row).slice(task.length+1));
174
- if(!nativeRVersion||!nativeIssue(rUser,"R")
175
- ||!nativeIssue(pUser,"P")){
176
- fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
177
- }
178
- }
179
- // Only document-level TEST_ONLY markers deny production adoption:
180
- // normal P plans can legitimately mention test-only scenarios.
181
- const testOnlyReview=x=>
182
- /(?:^|\n)\s*(?:#{1,6}\s*|>\s*)?(?:\*\*)?TEST_ONLY(?:\*\*)?(?:\s*$|\s*[/||:]\s*NOT_APPROVED)/mi
183
- .test(textOf(x));
184
- if(rAssistant&&testOnlyReview(rAssistant)||testOnlyReview(pAssistant)){
185
- fail("APPROVAL_TEST_ONLY");return false;
186
- }
187
- if(rAssistant&&(!/(?:需求|范围|验收)/.test(textOf(rAssistant))
188
- || !/\bR[1-9][0-9]*\b/i.test(textOf(rAssistant)))) {
189
- fail("APPROVAL_REQUIREMENTS_MISSING");return false;
190
- }
191
- const rVersion=rAssistant?versionOf(textOf(rAssistant),"R")
192
- :nativeRVersion||virtualizedR&&rForm?.version;
193
- // A stage-02 plan can generate an immutable Rn synchronization SNAPSHOT
194
- // after its P approval. It is not a new R approval: Context retains the
195
- // original R/P approvals and exact P.requirementRef. Only a precisely
196
- // linked notice is exempt from the "new R version" visual alarm.
197
- const planDerivedSync=text=>{
198
- const m=text.match(/(?:^|\n)需求文档派生同步[::]\s*(R[1-9][0-9]*)\s*←\s*已批准\s*(P[1-9][0-9]*)[((]保留原批准\s*(R[1-9][0-9]*)[,,]不签发新 R 审批[))]/);
199
- return Boolean(m&&m[1]!==rVersion&&m[2]===pVersion
200
- &&m[3]===rVersion
201
- &&!/(?:REQUIREMENTS_REVIEW|提交需求评审|R[1-9][0-9]*-ISSUE|已撤销|撤销需求|拒绝需求)/i.test(text)
202
- &&!/(?:^|\n)\s*#{1,6}\s*R[1-9][0-9]*\s+v[1-9][0-9]*/i.test(text));
203
- };
204
- const intervening=rows.slice(rIndex+1,lastUser-1);
205
- const invalidated=intervening.some(x=>{
206
- const text=textOf(x);
207
- if(x.role==="assistant"){
208
- if(/需求文档派生同步/.test(text)&&!planDerivedSync(text))return true;
209
- const next=versionOf(text,"R");
210
- return !planDerivedSync(text)&&/需求|范围|验收/.test(text)&&next&&next!==rVersion;
211
- }
212
- // Updating a plan while retaining the approved requirement is NOT
213
- // a requirement revocation.
214
- // Only an explicit requirement-targeted change invalidates this R.
215
- const planSyncRequest=(/(?:修改|修订|调整).{0,14}方案.{0,80}(?:同步|更新|改).{0,14}需求/.test(text)
216
- ||/(?:方案|计划|P[1-9][0-9]*).{0,50}(?:同步|更新|修改|调整|改).{0,50}(?:需求|R[1-9][0-9]*)/.test(text))
217
- &&!/(?:撤销|取消|拒绝|不批准|不同意|不确认)/.test(text);
218
- if(planSyncRequest)return false;
219
- return /(?:撤销|取消|拒绝|不同意|不批准|修改|修订|变更)\s*(?:(?:当前|本次|这份|上述)\s*)?(?:需求|R[1-9][0-9]*)/i.test(text)
220
- || /\bR[1-9][0-9]*\b\s*(?:需求)?\s*(?:需要|应当|应该)?\s*(?:撤销|取消|拒绝|修改|修订|变更)/i.test(text);
221
- });
222
- if(!pVersion||!rVersion||invalidated){
223
- fail("APPROVAL_REVISED_OR_REVOKED");return false;
224
- }
225
- const rUserVersion=textOf(rUser).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
226
- const referencedR=textOf(pAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
227
- if(!referencedR || referencedR!==rVersion){
228
- fail("APPROVAL_PLAN_REQUIREMENT_MISMATCH");return false;
229
- }
230
- if(rUserVersion && rVersion!==rUserVersion){
231
- fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
232
- }
233
- // An explicit Chat URL may be adopted after the P-approval assistant
234
- // finishes, but that reply might instead have issued newer R/P
235
- // revisions, invalidating an earlier P approval even if the last user
236
- // message is still the old standalone confirmation.
237
- const revisedAfterApproval=rows.slice(lastUser+1).some(x=>{
238
- if(x.role!=="assistant")return false;
239
- const text=textOf(x),nextR=versionOf(text,"R"),
240
- nextP=versionOf(text,"P");
241
- return Boolean(
242
- /需求文档派生同步/.test(text)&&!planDerivedSync(text)
243
- ||!planDerivedSync(text)&&/(?:需求|范围|验收)/.test(text)&&nextR&&nextR!==rVersion
244
- ||/(?:方案|计划)/.test(text)&&nextP&&nextP!==pVersion
245
- ||/(?:SUPERSEDED|已失效|已废弃|已撤销)/i.test(text)
246
- &&/(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(text)
247
- );
248
- });
249
- if(revisedAfterApproval){
250
- fail("APPROVAL_REVISED_AFTER_CONFIRMATION");return false;
251
- }
252
- const userKey=messageId(pUser.el,"user");
253
- const snap=inspect();
254
- // Normally the model calls Start during its P-confirmation Turn.
255
- // A fresh, explicitly scoped native Start intent can also adopt AFTER
256
- // that assistant Turn ends (e.g. MCP schema was stale in the same Chat).
257
- // Only the exact current Chat ID, last R/P approval user identity and
258
- // completed assistant reply qualify. A historical unscoped idle Chat
259
- // must never become an Owner just because R/P messages are visible.
260
- const explicitChatId=typeof message.explicitChatId==="string"
261
- ? message.explicitChatId.toLowerCase():null;
262
- const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
263
- // The managed lease may scope an idle, already-open Chat by the exact
264
- // Task ID in BOTH real native R/P approval turns. No task scope from
265
- // copied Context prose or generic unscoped historical confirmations.
266
- const issueTask=x=>textOf(x).match(
267
- /^([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;
268
- const taskScoped=typeof message.expectedTaskId==="string"
269
- &&message.expectedTaskId.length>=8
270
- &&issueTask(rUser)===message.expectedTaskId
271
- &&issueTask(pUser)===message.expectedTaskId;
272
- if(message.expectedTaskId!==undefined&&!taskScoped
273
- &&!(formPairCandidate&&(snap.stop||snap.busy)&&!snap.pendingConfirmation)){
274
- fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
275
- }
276
- const scopedIdle=Boolean(
277
- (explicitChatId&&explicitChatId===currentId||taskScoped)
278
- &&!snap.stop&&!snap.busy&&snap.assistantKey
279
- &&snap.composerReady&&snap.copyAction&&snap.text
280
- &&!snap.pendingConfirmation);
281
- if(!userKey ||snap.path!==path||snap.userKey!==userKey
282
- ||!(snap.stop||snap.busy||scopedIdle)
283
- ||snap.fatal||snap.dialog||snap.toolUnknown){
284
- fail("APPROVAL_LAST_TURN_UNVERIFIED");return false;
285
- }
286
- reply({contract:CONTRACT,status:"VERIFIED",page:path,
287
- userKey,rVersion,pVersion,priorAssistantKey:messageId(pAssistant.el,"assistant"),
288
- // Ephemeral approval source for Native/Context comparison at permit
289
- // consumption. Never persisted in Chrome storage, logs or Owner state.
290
- approvalTurns:{rUserKey:messageId(rUser.el,"user"),
291
- rUserText:textOf(rUser),pUserText:textOf(pUser)},
292
- // Idle post-approval assistant was completed BEFORE adoption.
293
- // This is a historical baseline, never a fresh execution Turn.
294
- ...(scopedIdle?{postApprovalAssistantKey:snap.assistantKey}:{})});
295
- return false;
296
- }
297
- return false;
298
- };
299
- })();
@@ -1,144 +0,0 @@
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
- })();
@@ -1,171 +0,0 @@
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
- })();