@tomflow/chatloop-extension 0.4.4 → 0.4.6

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/bin/cli.mjs CHANGED
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  // CLI is owned by the Extension package; local-tools delegates, never implements actions.
3
- import {spawnSync} from 'node:child_process';
4
3
  import {existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync} from 'node:fs';
5
4
  import {homedir} from 'node:os';
6
5
  import {dirname,join,resolve} from 'node:path';
7
6
  import {fileURLToPath} from 'node:url';
8
7
  import {extensionCliApi} from '../index.mjs';
9
8
  const cliContract=extensionCliApi();
10
- const {ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId}=cliContract;
9
+ const {ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId,openExtensionActionPage}=cliContract;
11
10
  const actionById=new Map(actionCapabilities.map(cap=>[cap.id,cap]));
12
11
  const actionHelp=actionCapabilities.map(cap=>cap.cli.join(' ')+
13
12
  (cap.kind==='owner-clean'?' <tab-id>':'')).join(' | ');
@@ -62,10 +61,7 @@ function configuration() {
62
61
  return config;
63
62
  }
64
63
  function openAction(url) {
65
- if(process.platform==='darwin') {
66
- const r=spawnSync('open',['-a','Google Chrome',url],{encoding:'utf8',timeout:5000});
67
- if(r.error||r.status!==0)throw Object.assign(Error('Could not open formal Extension Action page'),{code:'CHROME_OPEN_FAILED'});
68
- }else throw Object.assign(Error('Browser launcher not yet verified on this OS'),{code:'BROWSER_LAUNCH_UNSUPPORTED'});
64
+ return openExtensionActionPage(url);
69
65
  }
70
66
  async function executeAction(action,intent) {
71
67
  if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
@@ -137,4 +133,9 @@ if(help!==null){
137
133
  }
138
134
  // After the CLI reply is produced, allow bounded observation delivery.
139
135
  // This never changes its result or retries its business side effect.
140
- await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(300);
136
+ const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
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
+ }
@@ -9,7 +9,7 @@ const write=obj=>{
9
9
  const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
10
10
  len.writeUInt32LE(b.length);process.stdout.write(Buffer.concat([len,b]));
11
11
  };
12
- let buf=Buffer.alloc(0),handled=false;
12
+ let buf=Buffer.alloc(0),handled=false,observationOnly=false;
13
13
  process.stdin.on('data',async chunk=>{
14
14
  if(handled)return;
15
15
  buf=Buffer.concat([buf,chunk]);
@@ -20,6 +20,7 @@ process.stdin.on('data',async chunk=>{
20
20
  handled=true;
21
21
  try{
22
22
  const m=JSON.parse(buf.subarray(4,4+n).toString('utf8'));
23
+ observationOnly=m.op==='api-observation';
23
24
  const dispatch=async()=>{
24
25
  if(m.op==='acquire'){
25
26
  const r=readRequest(m.id);
@@ -73,8 +74,15 @@ process.stdin.on('data',async chunk=>{
73
74
  else await observeNativeOperation(m.op,dispatch);
74
75
  }catch(e){write({status:'FAILED',code:e.code||'NATIVE_HOST_ERROR'});}
75
76
  finally{
76
- // The Native business reply has already been written. Allow the one
77
- // existing Supervisor writer to receive pending soft evidence.
78
- await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(300);
77
+ // Observation-only requests cannot recursively generate Native audit.
78
+ // Never delay their Writer receipt for an unrelated drain timeout.
79
+ if(!observationOnly){
80
+ const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(2500);
81
+ if(audit?.status!=='OK'){
82
+ // The business reply is already written and remains authoritative.
83
+ process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
84
+ component:'extension.native',...audit})+'\n');
85
+ }
86
+ }
79
87
  }
80
88
  });
@@ -42,4 +42,29 @@ function createOrderedApiObservationSender(deliver,{parallel=16,capacity=2048}={
42
42
  health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
43
43
  }
44
44
 
45
+ // One bounded CLI/Native process-exit gate, after the business reply.
46
+ // The Trace AOP queue and this transport have separate async backlogs.
47
+ // Never count "queue empty" as "Writer accepted the records".
48
+ function createObservationDrain(aspect,sender){
49
+ if(typeof aspect?.drain!=='function'||typeof aspect?.health!=='function'
50
+ ||typeof sender?.health!=='function')throw TypeError('OBSERVATION_DRAIN_INVALID');
51
+ return async function drain(timeoutMs=4200){
52
+ const budget=Number.isSafeInteger(timeoutMs)
53
+ ?Math.max(0,Math.min(timeoutMs,6000)):4200;
54
+ const deadline=Date.now()+budget;
55
+ let state;
56
+ do{
57
+ const remaining=Math.max(1,deadline-Date.now());
58
+ await aspect.drain(Math.min(750,remaining));
59
+ const a=aspect.health(),s=sender.health();
60
+ state={pending:a.pending+s.pending,inFlight:a.inFlight+s.inFlight,
61
+ dropped:a.dropped+s.dropped,failed:a.sinkFailures+s.failed,
62
+ submitted:s.submitted,confirmed:s.confirmed};
63
+ if(state.pending===0&&state.inFlight===0)break;
64
+ }while(Date.now()<deadline);
65
+ return Object.freeze({...state,status:state.pending||state.inFlight
66
+ ?'TIMEOUT':state.dropped||state.failed?'LOG_GAP':'OK'});
67
+ };
68
+ }
69
+
45
70
  globalThis.ChatLoopApiObservationV1=Object.freeze({createOrderedApiObservationSender});
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.4",
4
+ "version": "0.4.6",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -20,6 +20,10 @@ function requestProof(tabId) {
20
20
  }
21
21
 
22
22
  async function check() {
23
+ if(typeof chrome.tabs?.query!=='function'){
24
+ show('EXTENSION_API_UNAVAILABLE','Chrome 标签页 API 不可用,请检查扩展状态。');
25
+ return;
26
+ }
23
27
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
24
28
  const tab = tabs[0];
25
29
  if (!tab || !tab.url) {
@@ -72,7 +76,13 @@ chrome.storage.onChanged.addListener(() => {void showActionState();});
72
76
 
73
77
  // User-clicked menu action only; bind to the single active ChatGPT tab.
74
78
  document.getElementById('clean-action').addEventListener('click',async()=>{
75
- const selected=(await chrome.tabs.query({active:true,currentWindow:true}))[0];
79
+ if(typeof chrome.tabs?.query!=='function'){
80
+ show('CLEAN_BLOCKED','Chrome 标签页 API 不可用,未执行清理。');
81
+ return;
82
+ }
83
+ let selected;
84
+ try{selected=(await chrome.tabs.query({active:true,currentWindow:true}))[0]}
85
+ catch{show('CLEAN_BLOCKED','当前标签页无法验证,未执行清理。');return;}
76
86
  if(!selected?.id||!selected?.url?.startsWith('https://chatgpt.com/')){
77
87
  show('CLEAN_NOT_AVAILABLE','请先选中要清理的 ChatGPT 标签页。');return;
78
88
  }
package/index.mjs CHANGED
@@ -3,8 +3,9 @@
3
3
  import {fileURLToPath} from 'node:url';
4
4
  import {actionCapabilities} from './actions.generated.mjs';
5
5
  import {matchExtensionAction} from './lib/action-routing.mjs';
6
+ import {openExtensionActionPage} from './lib/browser-launch.mjs';
6
7
  import {createApiAspect} from '@tomflow/chatloop-trace';
7
- import {createOrderedApiObservationSender} from './lib/api-observation-queue.mjs';
8
+ import {createOrderedApiObservationSender,createObservationDrain} from './lib/api-observation-queue.mjs';
8
9
  const observationSender=createOrderedApiObservationSender(record=>
9
10
  ipc.nativeApiObservation(record));
10
11
  const INTERNAL_DRAIN=Symbol.for('chat-loop.telemetry.drain.internal');
@@ -24,6 +25,7 @@ const apiAspect=createApiAspect('@tomflow/chatloop-extension',{
24
25
  });
25
26
  }
26
27
  });
28
+ const drainTelemetry=createObservationDrain(apiAspect,observationSender);
27
29
  import * as bridge from './lib/bridge.mjs';
28
30
  import * as session from './lib/session-file.mjs';
29
31
  import * as binding from './lib/context-binding.mjs';
@@ -44,15 +46,16 @@ export const verifyOrphanOwnerIdle=apiAspect.observe(
44
46
  // Internal entrypoint contracts, not a second npm subpath.
45
47
  export const extensionCliApi=apiAspect.observe('extensionCliApi',
46
48
  ()=>apiAspect.methods(Object.freeze({
47
- [INTERNAL_DRAIN]:apiAspect.drain,
49
+ [INTERNAL_DRAIN]:drainTelemetry,
48
50
  ACTIONS:bridge.ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME:bridge.HOST_NAME,
49
51
  configFile:bridge.configFile,prepare:bridge.prepare,
50
52
  readResult:bridge.readResult,privateDir:bridge.privateDir,
51
- validateExtensionId:bridge.validateExtensionId
53
+ validateExtensionId:bridge.validateExtensionId,
54
+ openExtensionActionPage
52
55
  }), 'extensionCliApi','cli'));
53
56
  export const nativeHostApi=apiAspect.observe('nativeHostApi',
54
57
  ()=>apiAspect.methods(Object.freeze({
55
- [INTERNAL_DRAIN]:apiAspect.drain,
58
+ [INTERNAL_DRAIN]:drainTelemetry,
56
59
  readRequest:bridge.readRequest,finish:bridge.finish,
57
60
  readSession:session.readSession,writeSession:session.writeSession,
58
61
  registeredContext:binding.registeredContext,
@@ -41,3 +41,28 @@ export function createOrderedApiObservationSender(deliver,{parallel=16,capacity=
41
41
  return Object.freeze({send,
42
42
  health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
43
43
  }
44
+
45
+ // One bounded CLI/Native process-exit gate, after the business reply.
46
+ // The Trace AOP queue and this transport have separate async backlogs.
47
+ // Never count "queue empty" as "Writer accepted the records".
48
+ export function createObservationDrain(aspect,sender){
49
+ if(typeof aspect?.drain!=='function'||typeof aspect?.health!=='function'
50
+ ||typeof sender?.health!=='function')throw TypeError('OBSERVATION_DRAIN_INVALID');
51
+ return async function drain(timeoutMs=4200){
52
+ const budget=Number.isSafeInteger(timeoutMs)
53
+ ?Math.max(0,Math.min(timeoutMs,6000)):4200;
54
+ const deadline=Date.now()+budget;
55
+ let state;
56
+ do{
57
+ const remaining=Math.max(1,deadline-Date.now());
58
+ await aspect.drain(Math.min(750,remaining));
59
+ const a=aspect.health(),s=sender.health();
60
+ state={pending:a.pending+s.pending,inFlight:a.inFlight+s.inFlight,
61
+ dropped:a.dropped+s.dropped,failed:a.sinkFailures+s.failed,
62
+ submitted:s.submitted,confirmed:s.confirmed};
63
+ if(state.pending===0&&state.inFlight===0)break;
64
+ }while(Date.now()<deadline);
65
+ return Object.freeze({...state,status:state.pending||state.inFlight
66
+ ?'TIMEOUT':state.dropped||state.failed?'LOG_GAP':'OK'});
67
+ };
68
+ }
@@ -0,0 +1,40 @@
1
+ import {spawnSync} from 'node:child_process';
2
+
3
+ // Open a formal extension Action page in the existing Chrome window that owns
4
+ // the ChatGPT conversation. "open -a Google Chrome <url>" chooses the last
5
+ // active *profile*, which can be a different profile without this extension.
6
+ // This script does not read or modify a Chat tab; it creates only an Action tab.
7
+ // Ambiguous ownership fails closed rather than sending an Action elsewhere.
8
+ const OPEN_IN_CHAT_WINDOW = `on run argv
9
+ set destination to item 1 of argv
10
+ tell application "Google Chrome"
11
+ set candidateIds to {}
12
+ repeat with w in windows
13
+ set hasChat to false
14
+ repeat with t in tabs of w
15
+ try
16
+ if (URL of t) starts with "https://chatgpt.com/" then set hasChat to true
17
+ end try
18
+ end repeat
19
+ if hasChat then set end of candidateIds to id of w
20
+ end repeat
21
+ if (count of candidateIds) is not 1 then error "CHATGPT_WINDOW_AMBIGUOUS_OR_ABSENT" number 103
22
+ set ownWindow to window id (item 1 of candidateIds)
23
+ make new tab at end of tabs of ownWindow with properties {URL:destination}
24
+ return "WINDOW=" & (id of ownWindow)
25
+ end tell
26
+ end run`;
27
+
28
+ export function openExtensionActionPage(url,{platform=process.platform,spawn=spawnSync}={}){
29
+ if(platform!=='darwin')
30
+ throw Object.assign(Error('Browser launcher not yet verified on this OS'),
31
+ {code:'BROWSER_LAUNCH_UNSUPPORTED'});
32
+ if(!/^chrome-extension:\/\/[a-p]{32}\/[a-z_]+\.html\?requestId=[a-f0-9]{32}$/.test(url))
33
+ throw Object.assign(Error('Untrusted Extension Action URL'),{code:'INVALID_ACTION_URL'});
34
+ const receipt=spawn('osascript',['-e',OPEN_IN_CHAT_WINDOW,url],
35
+ {encoding:'utf8',timeout:7000});
36
+ if(receipt.error||receipt.status!==0||!/\bWINDOW=\d+\b/.test(receipt.stdout||''))
37
+ throw Object.assign(Error('Existing ChatGPT Chrome window unavailable or ambiguous'),
38
+ {code:'CHROME_TARGET_WINDOW_UNVERIFIED'});
39
+ return {status:'OPENED',windowVerified:true};
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
6
6
  "bin": {