@tomflow/chatloop-extension 0.4.13 → 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.
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]);
@@ -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'});
@@ -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)));
@@ -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>
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.13",
4
+ "version": "0.4.14",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -12,7 +12,7 @@ export function matchExtensionAction(catalog,argv){
12
12
  &&Number.isSafeInteger(Number(input.at(-1))))
13
13
  return {id:cap.id,intent:{tabId:Number(input.at(-1))}};
14
14
  if(input.length===route.length&&input.join(' ')===route.join(' '))
15
- return {id:cap.id,needsIntent:['owner-intent','owner-start'].includes(cap.kind)};
15
+ return {id:cap.id,needsIntent:['owner-intent','owner-start','entry-test'].includes(cap.kind)};
16
16
  }
17
17
  return null;
18
18
  }
package/lib/bridge.mjs CHANGED
@@ -49,6 +49,16 @@ export function requestDir(id) {
49
49
  return join(tempRoot(),id);
50
50
  }
51
51
  function validateIntent(action, intent) {
52
+ if(action==='entry_test'){
53
+ if(!intent||typeof intent!=='object'||Array.isArray(intent)
54
+ ||Object.keys(intent).some(k=>!['prompt','appId','testOnly','confirmed'].includes(k))
55
+ ||typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
56
+ ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)
57
+ ||typeof intent.appId!=='string'||!/^asdk_app_[a-z0-9]{20,64}$/.test(intent.appId)
58
+ ||intent.testOnly!==true||intent.confirmed!==true)
59
+ throw Object.assign(Error('Explicit test-only entry intent required'),{code:'INVALID_ENTRY_TEST_INTENT'});
60
+ return {prompt:intent.prompt,appId:intent.appId,testOnly:true,confirmed:true};
61
+ }
52
62
  if(action==='start'){
53
63
  if(!intent||typeof intent!=='object'||Array.isArray(intent)
54
64
  ||Object.keys(intent).some(k=>!['projectId','taskId','purpose','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl','contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision'].includes(k))
@@ -144,7 +154,7 @@ export function readRequest(id) {
144
154
  const r=JSON.parse(readFileSync(p,'utf8'));
145
155
  if(r.id!==id||!ACTIONS.includes(r.action)||Date.now()>r.expiresAt)
146
156
  throw Object.assign(Error('Request expired or changed'),{code:'REQUEST_EXPIRED'});
147
- if(['continue','handoff','clean','start'].includes(r.action))validateIntent(r.action,r.intent);
157
+ if(['continue','handoff','clean','start','entry_test'].includes(r.action))validateIntent(r.action,r.intent);
148
158
  if(r.traceParent!==undefined&&!validParent(r.traceParent))delete r.traceParent;
149
159
  return r;
150
160
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.13",
3
+ "version": "0.4.14",
4
4
  "type": "module",
5
- "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
5
+ "description": "Chat Loop Extension: reviewed formal Action pages, including TEST_ONLY native App entry",
6
6
  "bin": {
7
7
  "chatloop-extension": "bin/cli.mjs"
8
8
  },
@@ -64,12 +64,16 @@ export async function compileActions(source=join(root,'capabilities'),
64
64
  if(c.kind==='eye-read'&&(!c.id.startsWith('chat_')||
65
65
  !['text','dom'].includes(c.readMode)))
66
66
  throw fail('EXTENSION_EYE_READ_MODE_INVALID');
67
- if(newAction && c.kind!=='eye-read')
67
+ const reviewedEntry=c.id==='entry_test' && c.kind==='entry-test'
68
+ &&c.page==='entry-test.html' &&c.cli.join(' ')==='entry test'
69
+ &&c.waitMs===310000 &&c.textResult===true;
70
+ if(newAction && c.kind!=='eye-read' && !reviewedEntry)
68
71
  throw fail('EXTENSION_PRIVILEGED_ACTION_REVIEW_REQUIRED');
69
72
  if((c.id==='chat_text'&&c.readMode!=='text')||
70
73
  (c.id==='chat_dom'&&c.readMode!=='dom'))
71
74
  throw fail('EXTENSION_BUILTIN_EYE_MODE_CHANGED');
72
75
  const page=join(extension,c.page);
76
+ if(reviewedEntry&&!existsSync(page))throw fail('EXTENSION_ENTRY_ACTION_PAGE_MISSING');
73
77
  const generated=existsSync(page)&&
74
78
  readFileSync(page,'utf8').startsWith(generatedMarker);
75
79
  if(!existsSync(page) && !newAction)
@@ -79,7 +83,7 @@ export async function compileActions(source=join(root,'capabilities'),
79
83
  if(!readFileSync(page,'utf8').includes(expected))
80
84
  throw fail('EXTENSION_ACTION_EXECUTOR_MISMATCH');
81
85
  }
82
- actions.push({...c,file,generated:newAction});
86
+ actions.push({...c,file,generated:newAction && c.kind==='eye-read'});
83
87
  }
84
88
  actions.sort((a,b)=>(
85
89
  (originals.indexOf(a.id)<0?99:originals.indexOf(a.id))-