@tomflow/chatloop-extension 0.4.12 → 0.4.14

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 (36) hide show
  1. package/README.md +2 -2
  2. package/actions.generated.mjs +2 -1
  3. package/bin/cli.mjs +17 -8
  4. package/bin/native-host.mjs +26 -7
  5. package/capabilities/entry_test.mjs +1 -0
  6. package/extension/actions/clean.js +6 -3
  7. package/extension/actions/common.js +5 -2
  8. package/extension/actions/continue.js +22 -4
  9. package/extension/actions/entry_test.js +186 -0
  10. package/extension/actions/handoff.js +19 -4
  11. package/extension/actions/model-intent.js +4 -2
  12. package/extension/actions/start.js +11 -3
  13. package/extension/actions/status.js +2 -1
  14. package/extension/entry-test.html +6 -0
  15. package/extension/loop/api-observation-queue.generated.js +11 -3
  16. package/extension/loop/observer-approval.js +10 -9
  17. package/extension/manifest.json +1 -1
  18. package/extension/popup.js +9 -3
  19. package/extension/worker/action-result.js +2 -2
  20. package/extension/worker/action-take.js +8 -10
  21. package/extension/worker/adopt-prepare.js +7 -2
  22. package/extension/worker/adopt-recovery.js +2 -1
  23. package/extension/worker/adopt-result.js +7 -1
  24. package/extension/worker/bootstrap.js +16 -5
  25. package/extension/worker/manual.js +5 -7
  26. package/extension/worker/router.js +12 -3
  27. package/extension/worker/scheduler.js +35 -21
  28. package/extension/worker/turn-finished.js +11 -6
  29. package/lib/action-routing.mjs +1 -1
  30. package/lib/api-observation-queue.mjs +11 -3
  31. package/lib/bridge.mjs +50 -6
  32. package/lib/context-ipc.mjs +5 -1
  33. package/lib/owner-evidence.mjs +5 -1
  34. package/lib/session-file.mjs +27 -3
  35. package/package.json +3 -3
  36. package/scripts/build-actions.mjs +6 -2
package/README.md CHANGED
@@ -42,7 +42,7 @@ The builder creates their isolated Action HTML, which uses the same
42
42
  dispatch switch needs modification. The builder refuses duplicate names,
43
43
  privileged type changes, invalid read modes, missing assets and stale output.
44
44
 
45
- **A declaration does not grant sending authority.** Start, Continue, Handoff,
45
+ **A declaration does not grant sending authority.** The separately reviewed `entry test` Action is a TEST_ONLY, Native-authorized first-turn fixture: it requires an explicit confirmation, creates one ordinary Chat with a real structured @ App mention, and must prove the unique user message without a Browser Owner; it cannot approve R/P or invoke Start/Continue/Handoff. Its explicit privilege review is allowlisted by exact ID, route, page, deadline and receipt format. Any other new sending declaration is denied. Start, Continue, Handoff,
46
46
  Clean, Status, screenshot and reload keep their reviewed, explicit Worker
47
47
  handlers and existing trust boundaries. New send/Owner/Native mutation
48
48
  requires a separate authorized security review and implementation; it cannot
@@ -72,7 +72,7 @@ Run: chatloop-extension <command> --help
72
72
 
73
73
  ```text
74
74
  Usage: chatloop-extension extension <command>
75
- Commands: chat text | chat dom | chat screenshot | reload | continue | handoff | clean <tab-id> | status | start
75
+ Commands: chat text | chat dom | chat screenshot | reload | continue | handoff | clean <tab-id> | status | start | entry test
76
76
  Run: chatloop-extension extension <command> --help
77
77
  ```
78
78
 
@@ -8,4 +8,5 @@ import {capability as a5} from './capabilities/handoff.mjs';
8
8
  import {capability as a6} from './capabilities/clean.mjs';
9
9
  import {capability as a7} from './capabilities/status.mjs';
10
10
  import {capability as a8} from './capabilities/start.mjs';
11
- export const actionCapabilities=Object.freeze([a0,a1,a2,a3,a4,a5,a6,a7,a8]);
11
+ import {capability as a9} from './capabilities/entry_test.mjs';
12
+ export const actionCapabilities=Object.freeze([a0,a1,a2,a3,a4,a5,a6,a7,a8,a9]);
package/bin/cli.mjs CHANGED
@@ -20,7 +20,8 @@ const HELP={
20
20
  'extension continue':'Usage: chatloop-extension extension continue (JSON intent on stdin)\nSubmit next-turn text or query receipt; does not send directly.',
21
21
  'extension handoff':'Usage: chatloop-extension extension handoff (JSON intent on stdin)\nRequest early handoff or query receipt; does not transfer directly.',
22
22
  'extension status':'Usage: chatloop-extension extension status\nRead-only, verified active Web Chat status.',
23
- 'extension start':'Usage: chatloop-extension extension start (JSON on stdin)\nStart a new task with prompt, or use mode=adopt (no prompt) to bind the only R/P-approved existing Chat without sending.'
23
+ 'extension start':'Usage: chatloop-extension extension start (JSON on stdin)\nStart a new task with prompt, or use mode=adopt (no prompt) to bind the only R/P-approved existing Chat without sending.',
24
+ 'extension entry test':'Usage: chatloop-extension extension entry test (JSON intent on stdin)\nTEST_ONLY: use the built-in Extension Action to create a new normal Chat, choose the actual native @ App, and send exactly once without a Browser Owner.'
24
25
  };
25
26
  function helpFor(args){
26
27
  if(args.length===1&&['-h','--help','help'].includes(args[0]))return HELP[''];
@@ -108,7 +109,7 @@ async function execute(argv) {
108
109
  return {implemented:['capabilities','host install <extension-id>',
109
110
  ...actionCapabilities.map(cap=>'extension '+cap.cli.join(' ')+
110
111
  (cap.kind==='owner-clean'?' <tab-id>':
111
- ['owner-intent','owner-start'].includes(cap.kind)?' (JSON on stdin)':''))],
112
+ ['owner-intent','owner-start','entry-test'].includes(cap.kind)?' (JSON on stdin)':''))],
112
113
  available:existsSync(configFile()),hostConfigured:existsSync(configFile())};
113
114
  }
114
115
  if(argv[0]==='host'&&argv[1]==='install'&&argv.length===3)return installHost(argv[2]);
@@ -127,15 +128,23 @@ if(help!==null){
127
128
  const data=await execute(args);
128
129
  emit('RESULT',command,{ok:true,value:data});
129
130
  }catch(e){
130
- emit('RESULT',command,{ok:false,error:{code:e.code||'UNKNOWN_RESULT',message:e.message}});
131
+ const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
132
+ ?e.code:'UNKNOWN_RESULT';
133
+ // Preserve the versioned CLI error shape but never publish arbitrary
134
+ // native/OS error messages or absolute paths through stdout.
135
+ emit('RESULT',command,{ok:false,error:{code,message:code}});
131
136
  process.exitCode=1;
132
137
  }
133
138
  }
134
139
  // After the CLI reply is produced, allow bounded observation delivery.
135
140
  // This never changes its result or retries its business side effect.
136
- const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(5000);
137
- if(audit?.status!=='OK'){
138
- // Sanitized counters only; the already-emitted RESULT is authoritative.
139
- process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
140
- component:'extension.cli',...audit})+'\n');
141
+ try{
142
+ const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(5000);
143
+ if(audit?.status!=='OK'){
144
+ // The already-emitted RESULT remains authoritative even if Trace stalls.
145
+ process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
146
+ component:'extension.cli',...audit})+'\n');
147
+ }
148
+ }catch{
149
+ // Soft telemetry must not change the CLI exit code after its business reply.
141
150
  }
@@ -8,13 +8,24 @@ const hostContract=nativeHostApi();
8
8
  const {readRequest,finish,readSession,writeSession,registeredContext,
9
9
  nativeContextControl,nativeApiObservation,observeNativeOperation}=hostContract;
10
10
  const MAX_INPUT=48*1024*1024;
11
+ let replied=false;
11
12
  const write=obj=>{
13
+ // One Native Messaging process may return exactly one business frame.
14
+ // A later observer/drain failure must not append a contradictory result.
15
+ if(replied)return;
12
16
  const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
13
- len.writeUInt32LE(b.length);process.stdout.write(Buffer.concat([len,b]));
17
+ len.writeUInt32LE(b.length);
18
+ replied=true;
19
+ process.stdout.write(Buffer.concat([len,b]));
14
20
  };
15
21
  let buf=Buffer.alloc(0),handled=false,observationOnly=false;
16
22
  process.stdin.on('data',async chunk=>{
17
23
  if(handled)return;
24
+ // Bound accumulated bytes before Buffer.concat allocates. A claimed small
25
+ // frame length cannot justify unbounded piped input or retained memory.
26
+ if(buf.length+chunk.length>MAX_INPUT+4){
27
+ handled=true;write({status:'FAILED',code:'MESSAGE_TOO_LARGE'});return;
28
+ }
18
29
  buf=Buffer.concat([buf,chunk]);
19
30
  if(buf.length<4)return;
20
31
  const n=buf.readUInt32LE();
@@ -93,16 +104,24 @@ process.stdin.on('data',async chunk=>{
93
104
  }catch{/* Non-authoritative parent cannot modify Native business outcome. */}
94
105
  await observeNativeOperation(m.op,dispatch,parent);
95
106
  }
96
- }catch(e){write({status:'FAILED',code:e.code||'NATIVE_HOST_ERROR'});}
107
+ }catch(e){
108
+ const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
109
+ ?e.code:'NATIVE_HOST_ERROR';
110
+ write({status:'FAILED',code});
111
+ }
97
112
  finally{
98
113
  // Observation-only requests cannot recursively generate Native audit.
99
114
  // Never delay their Writer receipt for an unrelated drain timeout.
100
115
  if(!observationOnly){
101
- const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
102
- if(audit?.status!=='OK'){
103
- // The business reply is already written and remains authoritative.
104
- process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
105
- component:'extension.native',...audit})+'\n');
116
+ try{
117
+ const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
118
+ if(audit?.status!=='OK'){
119
+ // Never expose audit internals or change an already-written reply.
120
+ process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
121
+ component:'extension.native',...audit})+'\n');
122
+ }
123
+ }catch{
124
+ // A logging failure must not reject this one-shot Native handler.
106
125
  }
107
126
  }
108
127
  }
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'entry_test',page:'entry-test.html',cli:['entry','test'],kind:'entry-test',waitMs:310000,textResult:true,description:'One TEST_ONLY native @ App new-Chat entry; no Browser Owner'});
@@ -106,9 +106,11 @@ async function run(){
106
106
  }catch(e){
107
107
  if(machine&&receipt?.nonce){
108
108
  try{
109
+ const rawCode=e?.code||e?.message;
110
+ const code=typeof rawCode==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
111
+ ?rawCode:'CLEAN_UNVERIFIED';
109
112
  const saved=await chrome.runtime.sendNativeMessage(host,{
110
- op:'complete',id:reqId,nonce:receipt.nonce,action,status:'FAILED',
111
- code:String(e.message||'CLEAN_UNVERIFIED').slice(0,120)});
113
+ op:'complete',id:reqId,nonce:receipt.nonce,action,status:'FAILED',code});
112
114
  if(saved?.status==='SAVED'&&saved.id===reqId){
113
115
  await chrome.tabs.remove(own.id).catch(()=>{});
114
116
  }
@@ -117,4 +119,5 @@ async function run(){
117
119
  throw e;
118
120
  }
119
121
  }
120
- run().catch(e=>show('BLOCKED',e.message||'CLEAN_FAILED'));
122
+ run().catch(e=>show('BLOCKED',
123
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message:'CLEAN_FAILED'));
@@ -126,9 +126,12 @@ function copyText(value) {
126
126
  const req=await chrome.runtime.sendNativeMessage(nativeHost,
127
127
  {op:"acquire",id:machineId,action});
128
128
  if(req?.status==="OK") {
129
+ const rawCode=error?.code||error?.message;
130
+ const code=typeof rawCode==='string'
131
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
132
+ ?rawCode:'ACTION_FAILED';
129
133
  const saved = await chrome.runtime.sendNativeMessage(nativeHost,{
130
- op:"complete",id:machineId,nonce:req.nonce,action,status:"FAILED",
131
- code:String(error?.message||"ACTION_FAILED").slice(0,120)
134
+ op:"complete",id:machineId,nonce:req.nonce,action,status:"FAILED",code
132
135
  });
133
136
  // Machine errors already have a durable CLI receipt. They must not
134
137
  // accumulate as abandoned tabs; manual/unverified errors remain open.
@@ -2,6 +2,11 @@
2
2
  // The background schedules an Action page; this page alone performs the DOM mutation.
3
3
  const statusNode = document.getElementById("status");
4
4
  const detailsNode = document.getElementById("details");
5
+ const actionErrorCode=(error,fallback='SEND_ERROR')=>{
6
+ const code=error?.code||error?.message;
7
+ return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
8
+ ?code:fallback;
9
+ };
5
10
  function show(status, details) {
6
11
  statusNode.textContent = status;
7
12
  detailsNode.textContent = details;
@@ -139,7 +144,11 @@ async function sendOnce(target, text) {
139
144
  await new Promise(resolve => setTimeout(resolve, 250));
140
145
  }
141
146
  throw Error("SEND_UNVERIFIED"); // Side effect may exist: block, don't retry.
142
- } catch (error) {return {status: "UNVERIFIED", reason: error.message || "SEND_ERROR"};}
147
+ } catch (error) {
148
+ const code=error?.code||error?.message;
149
+ return {status:"UNVERIFIED",reason:
150
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:"SEND_ERROR"};
151
+ }
143
152
  },
144
153
  args: [target, text]
145
154
  });
@@ -197,7 +206,11 @@ async function retryNativeOnce(target) {
197
206
  if (!latest) return {status: 'RETRY_CLICKED'};
198
207
  }
199
208
  throw Error("NATIVE_RETRY_NOT_ACKNOWLEDGED");
200
- } catch(error) {return {status:'UNVERIFIED',reason:error.message||'RETRY_FAILED'};}
209
+ } catch(error) {
210
+ const code=error?.code||error?.message;
211
+ return {status:'UNVERIFIED',reason:
212
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'RETRY_FAILED'};
213
+ }
201
214
  }, args: [target]
202
215
  });
203
216
  return execution?.result || {status:'UNVERIFIED',reason:'RETRY_RESULT_UNKNOWN'};
@@ -307,7 +320,11 @@ async function run() {
307
320
  let result;
308
321
  try { result = permit.retryMode === "NATIVE"
309
322
  ? await retryNativeOnce(permit.target) : await sendOnce(permit.target, permit.text); }
310
- catch (error) { result = {status: "UNVERIFIED", reason: error.message || "SEND_ERROR"}; }
323
+ catch (error) {
324
+ result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
325
+ }
326
+ if(result.status==='UNVERIFIED')
327
+ result.reason=actionErrorCode({code:result.reason});
311
328
  const final = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
312
329
  result: result.status, reason: result.reason, newUserKey: result.newUserKey, newPage: result.newPage});
313
330
  if (!(result.status === "SENT_CONFIRMED" || permit.retryMode === "NATIVE"
@@ -319,4 +336,5 @@ async function run() {
319
336
  }
320
337
  (new URLSearchParams(location.search).has("requestId")
321
338
  ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("continue")) : run())
322
- .catch(error => show("BLOCKED", error.message || "ACTION_FAILED"));
339
+ .catch(error => show("BLOCKED",
340
+ actionErrorCode(error,"ACTION_FAILED")));
@@ -0,0 +1,186 @@
1
+ // Reviewed TEST_ONLY native @ App entry. Never owns a Loop Session or uses Continue.
2
+ const HOST='com.tomflow.chatloop.extension';
3
+ const statusNode=document.getElementById('status');
4
+ const detailNode=document.getElementById('details');
5
+ const show=(status,detail)=>{statusNode.textContent=status;detailNode.textContent=detail;document.body.dataset.result=status==='SUCCESS'?'success':'error';};
6
+ const pause=ms=>new Promise(r=>setTimeout(r,ms));
7
+ const safeCode=code=>/^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'ENTRY_TEST_UNVERIFIED';
8
+ async function readNewChat(id){
9
+ const end=Date.now()+90000;
10
+ while(Date.now()<end){
11
+ const tab=await chrome.tabs.get(id).catch(()=>null);
12
+ if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
13
+ if(tab.url==='https://chatgpt.com/'){
14
+ const proof=await chrome.scripting.executeScript({target:{tabId:id},func:()=>{
15
+ if(location.origin!=='https://chatgpt.com'||location.pathname!=='/')return false;
16
+ const mains=[...document.querySelectorAll('main')].filter(e=>e.getClientRects().length);
17
+ const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
18
+ ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
19
+ return mains.length===1&&editor?.getClientRects().length>0
20
+ &&editor.isContentEditable&&!((editor.innerText||'').trim())
21
+ &&!mains[0].querySelector('[data-chatgpt-search-message-ids],[data-message-author-role]');
22
+ }}).catch(()=>null);
23
+ if(proof?.[0]?.result===true)return;
24
+ }
25
+ await pause(320);
26
+ }
27
+ throw Error('ENTRY_COMPOSER_NOT_READY');
28
+ }
29
+ async function nativeMentionAndSend(id,appId,prompt){
30
+ const response=await chrome.scripting.executeScript({target:{tabId:id},
31
+ func:async(appId,prompt)=>{
32
+ const wait=ms=>new Promise(r=>setTimeout(r,ms));
33
+ const visible=e=>Boolean(e?.getClientRects?.().length);
34
+ const canonical=v=>String(v||'').replace(/\s+/g,'');
35
+ const fail=(code,diagnostic='')=>({status:'FAILED',code,diagnostic:diagnostic.slice(0,180)});
36
+ const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
37
+ ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
38
+ if(location.origin!=='https://chatgpt.com'||location.pathname!=='/'
39
+ ||!editor||!visible(editor)||!editor.isContentEditable
40
+ ||(editor.innerText||editor.textContent||'').trim())
41
+ return fail('ENTRY_EDITOR_UNVERIFIED');
42
+ editor.focus();
43
+ if(!document.execCommand('insertText',false,'@'))return fail('ENTRY_AT_INPUT_FAILED');
44
+ let choice=null,diagnostic='';
45
+ const selectors=['[role="option"]','[role="menuitem"]','[cmdk-item]',
46
+ '[data-testid*="app-item"]','[data-testid*="mention-item"]'];
47
+ for(let i=0;i<55;i++){
48
+ if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
49
+ const nodes=[...document.querySelectorAll(selectors.join(','))]
50
+ .filter(visible).filter(e=>(e.innerText||'').includes('Chat Loop'));
51
+ const exact=nodes.filter(e=>{
52
+ const t=(e.innerText||'').trim();
53
+ return t==='Chat Loop'||t.startsWith('Chat Loop\n');
54
+ });
55
+ if(exact.length===1){choice=exact[0];break;}
56
+ if(!exact.length && nodes.length===1){choice=nodes[0];break;}
57
+ diagnostic=nodes.slice(0,4).map(e=>e.getAttribute('role')+':'+(e.innerText||'').slice(0,55)).join('|');
58
+ await wait(220);
59
+ }
60
+ if(!choice)return fail('ENTRY_NATIVE_APP_OPTION_MISSING',diagnostic);
61
+ choice.click();
62
+ // A native mention is a structured composer node, not a literal "@Chat Loop" string.
63
+ let native=false;
64
+ for(let i=0;i<38;i++){
65
+ const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
66
+ native=tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
67
+ ||(e.getAttribute('data-app-mention-path')||'').includes(appId)
68
+ ||(e.getAttribute('href')||'').includes(appId));
69
+ if(native)break;
70
+ await wait(120);
71
+ }
72
+ if(!native)return fail('ENTRY_NATIVE_MENTION_UNVERIFIED',editor.innerHTML);
73
+ editor.focus();
74
+ if(!document.execCommand('insertText',false,' '+prompt))return fail('ENTRY_PROMPT_INPUT_FAILED');
75
+ for(let i=0;i<25;i++){
76
+ if(canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))break;
77
+ await wait(130);
78
+ }
79
+ if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
80
+ return fail('ENTRY_PROMPT_NOT_VISIBLE');
81
+ const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
82
+ if(!tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
83
+ ||(e.getAttribute('data-app-mention-path')||'').includes(appId)
84
+ ||(e.getAttribute('href')||'').includes(appId)))
85
+ return fail('ENTRY_NATIVE_MENTION_LOST');
86
+ const send=document.querySelector('button[data-testid="send-button"]')
87
+ ||document.querySelector('button[data-testid="composer-send-button"]')
88
+ ||document.querySelector('button[aria-label="发送"]')
89
+ ||document.querySelector('button[aria-label="Send message"]');
90
+ if(!send||send.disabled||!visible(send))return fail('ENTRY_SEND_UNAVAILABLE');
91
+ if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
92
+ send.click(); // Exactly once. No caller retries on an uncertain receipt.
93
+ return {status:'CLICKED_ONCE'};
94
+ },args:[appId,prompt]}).catch(()=>null);
95
+ const r=response?.[0]?.result;
96
+ if(!r)throw Error('ENTRY_SEND_RESULT_UNKNOWN');
97
+ if(r.status!=='CLICKED_ONCE')throw Error(safeCode(r.code));
98
+ }
99
+ async function verifyNativeUserTurn(id,appId,prompt){
100
+ const end=Date.now()+120000;let last=null,stable=0;
101
+ while(Date.now()<end){
102
+ const tab=await chrome.tabs.get(id).catch(()=>null);
103
+ if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
104
+ const path=tab.url&&new URL(tab.url).pathname;
105
+ if(/^\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(path||'')){
106
+ const r=await chrome.scripting.executeScript({target:{tabId:id},
107
+ func:(appId,prompt)=>{
108
+ if(location.origin!=='https://chatgpt.com')return null;
109
+ const main=document.querySelector('main');
110
+ const users=[...main.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]
111
+ .filter(x=>x.getAttribute('data-chatgpt-search-unit-key')?.endsWith(':user'));
112
+ if(!users.length){
113
+ users.push(...main.querySelectorAll('[data-message-author-role="user"]'));
114
+ }
115
+ const u=users.at(-1);
116
+ const key=u?.getAttribute('data-message-id')
117
+ ||u?.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0];
118
+ const bubble=u?.querySelector('[data-user-message-bubble="true"]')||u;
119
+ const m=bubble?.querySelector('[data-prompt-link-href="app://'+appId+'"]');
120
+ const canonical=v=>String(v||'').replace(/\s+/g,'');
121
+ return {path:location.pathname,userCount:users.length,
122
+ ids:users.map(x=>x.getAttribute('data-message-id')
123
+ ||x.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0]),
124
+ userKey:typeof key==='string'&&m
125
+ &&canonical(bubble.innerText||bubble.textContent).includes(canonical(prompt))
126
+ ?'user:'+key:null,hasNativeApp:Boolean(m)};
127
+ },args:[appId,prompt]}).catch(()=>null);
128
+ const v=r?.[0]?.result;
129
+ if(v?.userCount>1||v?.ids?.some(x=>x!==v.ids[0]))
130
+ throw Error('ENTRY_DUPLICATE_USER_TURN');
131
+ if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&v.userKey){
132
+ const k=path+'|'+v.userKey;
133
+ stable=last===k?stable+1:1;last=k;
134
+ if(stable>=4){
135
+ const chatId=path.slice(3);
136
+ return {status:'OK',testOnly:true,appId,
137
+ activeChatId:chatId,activeChatUrl:'https://chatgpt.com'+path,
138
+ userKey:v.userKey};
139
+ }
140
+ }else{stable=0;last=null;}
141
+ }
142
+ await pause(350);
143
+ }
144
+ throw Error('ENTRY_NATIVE_TURN_RECEIPT_UNKNOWN');
145
+ }
146
+ async function run(){
147
+ const own=await chrome.tabs.getCurrent();
148
+ const params=new URLSearchParams(location.search),id=params.get('requestId');
149
+ if(!own?.id||own.url!==location.href||[...params.keys()].length!==1
150
+ ||!/^[a-f0-9]{32}$/.test(id||'')
151
+ ||location.href!==chrome.runtime.getURL('entry-test.html')+'?requestId='+id)
152
+ throw Error('ENTRY_TEST_ACTION_SOURCE_INVALID');
153
+ const proof=await chrome.runtime.sendNativeMessage(HOST,{op:'acquire',id,action:'entry_test'});
154
+ if(proof?.status!=='OK'||proof.action!=='entry_test'||proof.id!==id
155
+ ||!proof.nonce||proof.intent?.confirmed!==true||proof.intent?.testOnly!==true)
156
+ throw Error('ENTRY_TEST_NATIVE_UNAUTHORIZED');
157
+ const intent=proof.intent;
158
+ let tab,clicked=false;
159
+ try{
160
+ // An entry test may not take over a live managed session or grant itself Owner.
161
+ const durable=await chrome.runtime.sendNativeMessage(HOST,{op:'session-read'});
162
+ if(durable?.status!=='OK'||durable.session&&!['DONE'].includes(durable.session.phase))
163
+ throw Error('ENTRY_TEST_ACTIVE_OWNER');
164
+ show('RUNNING','新普通 Chat 正在加载;仅验证原生 App 入口,不进行批准或 Start。');
165
+ tab=await chrome.tabs.create({url:'https://chatgpt.com/',active:true,
166
+ windowId:own.windowId,openerTabId:own.id});
167
+ if(!Number.isSafeInteger(tab?.id))throw Error('ENTRY_NEW_TAB_UNVERIFIED');
168
+ await readNewChat(tab.id);
169
+ await nativeMentionAndSend(tab.id,intent.appId,intent.prompt);
170
+ clicked=true;
171
+ const result=await verifyNativeUserTurn(tab.id,intent.appId,intent.prompt);
172
+ const stored=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
173
+ nonce:proof.nonce,action:'entry_test',status:'OK',payload:JSON.stringify(result)});
174
+ if(stored?.status!=='SAVED'||stored.id!==id)throw Error('ENTRY_TEST_NATIVE_RECEIPT_UNVERIFIED');
175
+ show('SUCCESS','已确认唯一原生 @ App 用户消息,未创建 Browser Owner。');
176
+ await chrome.tabs.remove(own.id);
177
+ }catch(error){
178
+ const code=safeCode(error?.message);
179
+ // After an uncertain click, never send again. Preserve created chat for audit.
180
+ const saved=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
181
+ nonce:proof.nonce,action:'entry_test',status:'FAILED',code}).catch(()=>null);
182
+ show('BLOCKED',code+(clicked?';已发送或副作用未知,禁止重试。':';尚未验证发送。'));
183
+ if(saved?.status==='SAVED')await chrome.tabs.remove(own.id).catch(()=>{});
184
+ }
185
+ }
186
+ void run().catch(error=>show('BLOCKED',safeCode(error?.message)));
@@ -3,6 +3,11 @@
3
3
  const statusNode = document.getElementById("status");
4
4
  const detailsNode = document.getElementById("details");
5
5
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
6
+ const actionErrorCode=(error,fallback='HANDOFF_ERROR')=>{
7
+ const code=error?.code||error?.message;
8
+ return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
9
+ ?code:fallback;
10
+ };
6
11
  function show(status, details) {
7
12
  statusNode.textContent = status;
8
13
  detailsNode.textContent = details;
@@ -178,7 +183,11 @@ async function sendHandoffOnce(tabId, text) {
178
183
  throw Error("HANDOFF_INPUT_CHANGED_BEFORE_SEND");
179
184
  button.click();
180
185
  return {clickedOnce: true};
181
- } catch (error) {return {clickedOnce: false, reason: error.message || "HANDOFF_SEND_ERROR"};}
186
+ } catch (error) {
187
+ const code=error?.code||error?.message;
188
+ return {clickedOnce:false,reason:
189
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'HANDOFF_SEND_ERROR'};
190
+ }
182
191
  }, args: [text]
183
192
  });
184
193
  if (dispatch?.result?.clickedOnce !== true) throw Error(dispatch?.result?.reason || "HANDOFF_SEND_UNVERIFIED");
@@ -354,7 +363,11 @@ async function run() {
354
363
  }
355
364
  result = await sendHandoffOnce(newTab.id,
356
365
  message + notice + checkpoint + resumeCapability + (permit.modelTurnNote || ""));
357
- } catch (error) {result = {status: "UNVERIFIED", reason: error.message || "HANDOFF_ERROR"};}
366
+ } catch (error) {
367
+ result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
368
+ }
369
+ if(result.status!=="SENT_CONFIRMED")
370
+ result.reason=actionErrorCode({code:result.reason});
358
371
  const committed = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
359
372
  result: result.status, reason: result.reason,
360
373
  newUserKey: result.newUserKey, newTabId: result.newTabId ?? newTab?.id,
@@ -367,7 +380,8 @@ async function run() {
367
380
  if (old && old.id !== newTab?.id && old.id !== own.id
368
381
  && old.url === "https://chatgpt.com" + permit.target.page) {
369
382
  await chrome.tabs.remove(old.id).catch(error => {
370
- console.warn("OLD_CHAT_TAB_CLEANUP_UNVERIFIED", error?.message);
383
+ console.warn("OLD_CHAT_TAB_CLEANUP_UNVERIFIED",
384
+ actionErrorCode(error,"TAB_CLEANUP_UNVERIFIED"));
371
385
  });
372
386
  }
373
387
  show("SUCCESS", "新 Chat 已收到交接包;旧 Chat 标签已尝试安全清理。");
@@ -375,4 +389,5 @@ async function run() {
375
389
  }
376
390
  (new URLSearchParams(location.search).has("requestId")
377
391
  ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("handoff")) : run())
378
- .catch(error => show("BLOCKED", error.message || "HANDOFF_ACTION_FAILED"));
392
+ .catch(error => show("BLOCKED",
393
+ actionErrorCode(error,"HANDOFF_ACTION_FAILED")));
@@ -37,9 +37,11 @@ export async function queueModelIntent(action) {
37
37
  } catch(e) {
38
38
  // An already-queued intent is not retried. Native failure is diagnostic only.
39
39
  try {
40
+ const rawCode=e?.code||e?.message;
41
+ const code=typeof rawCode==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
42
+ ?rawCode:'INTENT_UNVERIFIED';
40
43
  const saved=await chrome.runtime.sendNativeMessage(host,{
41
- op:'complete',id,nonce:auth.nonce,action,status:'FAILED',
42
- code:String(e.message||'INTENT_UNVERIFIED').slice(0,120)
44
+ op:'complete',id,nonce:auth.nonce,action,status:'FAILED',code
43
45
  });
44
46
  // The CLI already has a durable failure receipt. Keep the page only
45
47
  // when that receipt could not be verified; never resubmit the intent.
@@ -111,7 +111,11 @@ async function sendFirst(id,text){
111
111
  throw Error('START_INPUT_CHANGED');
112
112
  send.click(); // Once only. Worker persisted PENDING before this point.
113
113
  return {clickedOnce:true};
114
- }catch(e){return {clickedOnce:false,reason:e.message||'START_INPUT_UNKNOWN'};}
114
+ }catch(e){
115
+ const code=e?.code||e?.message;
116
+ return {clickedOnce:false,reason:
117
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'START_INPUT_UNKNOWN'};
118
+ }
115
119
  },args:[text]});
116
120
  if(clicked?.result?.clickedOnce!==true)
117
121
  throw Error(clicked?.result?.reason||'START_CLICK_UNVERIFIED');
@@ -275,8 +279,11 @@ async function run(){
275
279
  ...(proof.traceParent?{traceParent:proof.traceParent}:{}),
276
280
  ...(failureCode?{failureCode}:{})}).catch(()=>{});
277
281
  }
282
+ const rawCode=e?.code||e?.message;
283
+ const code=typeof rawCode==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
284
+ ?rawCode:'START_UNVERIFIED';
278
285
  const failed=await chrome.runtime.sendNativeMessage(host,{op:'complete',id,nonce:proof.nonce,
279
- action:'start',status:'FAILED',code:String(e.message||'START_UNVERIFIED').slice(0,100)}).catch(()=>null);
286
+ action:'start',status:'FAILED',code}).catch(()=>null);
280
287
  // Only the Action page closes after its durable FAILED receipt; the
281
288
  // possibly-sent Chat and any unverified draft remain untouched.
282
289
  if(failed?.status==='SAVED' && failed.id===id)
@@ -284,4 +291,5 @@ async function run(){
284
291
  throw e; // Never auto-retry a possibly clicked first user Turn.
285
292
  }
286
293
  }
287
- void run().catch(e=>show('BLOCKED',e.message||'START_UNVERIFIED'));
294
+ void run().catch(e=>show('BLOCKED',
295
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message:'START_UNVERIFIED'));
@@ -19,5 +19,6 @@ async function run(){
19
19
  }
20
20
  void run().catch(e=>{
21
21
  document.getElementById('status').textContent='UNVERIFIED';
22
- document.getElementById('details').textContent=e.message||'STATUS_UNKNOWN';
22
+ document.getElementById('details').textContent=
23
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message:'STATUS_UNKNOWN';
23
24
  });
@@ -0,0 +1,6 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN"><head><meta charset="utf-8"><title>Chat Loop · Stage 01 Entry Test</title>
3
+ <style>body{font:15px system-ui,sans-serif;padding:24px;max-width:650px;color:#222}#status{font-weight:bold}#details{white-space:pre-wrap;overflow-wrap:anywhere}body[data-result="error"] #status{color:#b00020}</style>
4
+ </head><body><h1>Chat Loop · Stage 01 TEST_ONLY</h1><p id="status" role="status">VERIFYING</p>
5
+ <p id="details">通过独立认证的 Extension Action,在新的普通 Chat 选择原生 @ App。不会建立 Browser Owner、批准 R/P 或 Start。</p>
6
+ <script src="actions/entry_test.js"></script></body></html>
@@ -10,9 +10,9 @@ function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2048}={}
10
10
  function pump(){
11
11
  scheduled=false;
12
12
  while(running<parallel){
13
- const position=waiting.findIndex(({record})=>!active.has(record.callId));
13
+ const position=waiting.findIndex(({callId})=>!active.has(callId));
14
14
  if(position<0)return;
15
- const [{record,resolve}]=waiting.splice(position,1),id=record.callId;
15
+ const [{record,callId,resolve}]=waiting.splice(position,1),id=callId;
16
16
  running++;active.add(id);
17
17
  let success=false;
18
18
  Promise.resolve().then(()=>deliver(record)).then(result=>{
@@ -36,12 +36,20 @@ function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2048}={}
36
36
  }
37
37
  function send(record){
38
38
  health.submitted++;
39
+ // A malformed telemetry record must not throw later inside an unhandled
40
+ // queueMicrotask or mutate its ordering key after being queued.
41
+ let callId;
42
+ try{callId=record?.callId}catch{}
43
+ if(typeof callId!=='string'||!callId||callId.length>128){
44
+ health.dropped++;health.lastFailureCode='OBSERVATION_INVALID';
45
+ return Promise.resolve(false);
46
+ }
39
47
  if(waiting.length>=capacity){
40
48
  health.dropped++;
41
49
  health.lastFailureCode='OBSERVATION_QUEUE_FULL';
42
50
  return Promise.resolve(false);
43
51
  }
44
- return new Promise(resolve=>{waiting.push({record,resolve});schedule()});
52
+ return new Promise(resolve=>{waiting.push({record,callId,resolve});schedule()});
45
53
  }
46
54
  return Object.freeze({send,
47
55
  health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
@@ -20,7 +20,7 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
20
20
  const line=value.replace(/\s+/g," ").trim();
21
21
  if(!line||line.length>500)return false;
22
22
  // Native R/P review controls send two explicit, task-scoped fields:
23
- // "TASK|R2-ISSUE:<uuid>|我确认 R2 v2。..." (and likewise P2).
23
+ // "TASK|Rn-ISSUE:<uuid>|我确认 Rn vN。" (and the Pn equivalent).
24
24
  // Accept only a matching kind+version from a genuine user message,
25
25
  // never arbitrary prose containing an approval quote or TEST_ONLY.
26
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);
@@ -59,7 +59,7 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
59
59
  // must not choose a version; ambiguous prose is not approval evidence.
60
60
  const versionOf=(value,type)=>{
61
61
  // Real formal reviews may start with a status recap mentioning an
62
- // older P2 before the issued heading "P3 v3|正式修订方案".
62
+ // an older plan version before the current issued revision heading.
63
63
  // A unique, version-consistent line title outranks historical prose.
64
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
65
  .filter(x=>Number(x[1].slice(1))===Number(x[2]))
@@ -78,7 +78,7 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
78
78
  }
79
79
  const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
80
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
81
+ // review. A user cannot make it effective by typing a plan approval after
82
82
  // the assistant said the current plan was not presented for approval.
83
83
  if(/(?:当前阶段[::]\s*PLAN_DRAFT|(?:维持|保持|仍为|停留在)\s*PLAN_DRAFT|方案(?:草稿)?.{0,20}(?:尚未|未曾|没有)正式(?:发布|提交)|(?:暂不|不(?:予|会|再)?)展示.{0,12}提交方案评审)/i.test(textOf(pAssistant))){
84
84
  fail("APPROVAL_PLAN_NOT_ISSUED");return false;
@@ -95,9 +95,9 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
95
95
  }
96
96
  const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
97
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.
98
+ // Long chats virtualize old turns. A still-mounted native Rn user
99
+ // approval at index 0 retains its exact issue identity, even when
100
+ // the issuing assistant has scrolled out of the DOM window.
101
101
  // This fallback is ONLY for native issue-scoped approvals. The Native
102
102
  // Context Start lease independently verifies the effective R approval.
103
103
  const rUser=rIndex>=0?rows[rIndex]:null;
@@ -148,7 +148,8 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
148
148
  const next=versionOf(text,"R");
149
149
  return /需求|范围|验收/.test(text)&&next&&next!==rVersion;
150
150
  }
151
- // "修订 P3、保留 R2" is a plan update, NOT an R2 revocation.
151
+ // Updating a plan while retaining the approved requirement is NOT
152
+ // a requirement revocation.
152
153
  // Only an explicit requirement-targeted change invalidates this R.
153
154
  return /(?:撤销|取消|拒绝|不同意|不批准|修改|修订|变更)\s*(?:(?:当前|本次|这份|上述)\s*)?(?:需求|R[1-9][0-9]*)/i.test(text)
154
155
  || /\bR[1-9][0-9]*\b\s*(?:需求)?\s*(?:需要|应当|应该)?\s*(?:撤销|取消|拒绝|修改|修订|变更)/i.test(text);
@@ -165,8 +166,8 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
165
166
  fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
166
167
  }
167
168
  // 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
169
+ // finishes, but that reply might instead have issued newer R/P
170
+ // revisions, invalidating an earlier P approval even if the last user
170
171
  // message is still the old standalone confirmation.
171
172
  const revisedAfterApproval=rows.slice(lastUser+1).some(x=>{
172
173
  if(x.role!=="assistant")return false;