@tomflow/chatloop-extension 0.3.84 → 0.4.0

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 (54) hide show
  1. package/README.md +74 -73
  2. package/actions.generated.mjs +11 -0
  3. package/bin/cli.mjs +22 -24
  4. package/bin/native-host.mjs +14 -5
  5. package/capabilities/chat_dom.mjs +1 -0
  6. package/capabilities/chat_screenshot.mjs +1 -0
  7. package/capabilities/chat_text.mjs +1 -0
  8. package/capabilities/clean.mjs +1 -0
  9. package/capabilities/continue.mjs +1 -0
  10. package/capabilities/handoff.mjs +1 -0
  11. package/capabilities/reload.mjs +1 -0
  12. package/capabilities/start.mjs +1 -0
  13. package/capabilities/status.mjs +1 -0
  14. package/extension/actions/common.js +14 -3
  15. package/extension/actions/continue.js +1 -1
  16. package/extension/actions/handoff.js +5 -3
  17. package/extension/actions/index.js +2 -0
  18. package/extension/actions/read-mode.js +9 -0
  19. package/extension/actions/start.js +1 -1
  20. package/extension/background.js +16 -2202
  21. package/extension/loop/action-catalog.generated.js +2 -0
  22. package/extension/loop/api-aspect.generated.js +192 -0
  23. package/extension/loop/core.js +81 -3
  24. package/extension/loop/index.js +34 -0
  25. package/extension/loop/observer-approval.js +227 -0
  26. package/extension/loop/observer-inspect.js +144 -0
  27. package/extension/loop/observer-poll.js +171 -0
  28. package/extension/loop/observer-recovery.js +109 -0
  29. package/extension/loop/observer.js +27 -630
  30. package/extension/loop/resources.js +8 -1
  31. package/extension/manifest.json +6 -2
  32. package/extension/worker/action-result.js +136 -0
  33. package/extension/worker/action-take.js +220 -0
  34. package/extension/worker/admission.js +122 -0
  35. package/extension/worker/adopt-prepare.js +155 -0
  36. package/extension/worker/adopt-recovery.js +185 -0
  37. package/extension/worker/adopt-result.js +120 -0
  38. package/extension/worker/bootstrap.js +172 -0
  39. package/extension/worker/manual.js +165 -0
  40. package/extension/worker/readiness.js +242 -0
  41. package/extension/worker/router.js +150 -0
  42. package/extension/worker/scheduler.js +147 -0
  43. package/extension/worker/turn-failure.js +197 -0
  44. package/extension/worker/turn-finished.js +200 -0
  45. package/index.mjs +62 -0
  46. package/lib/action-routing.mjs +18 -0
  47. package/lib/api-aspect.mjs +190 -0
  48. package/lib/bridge.mjs +26 -7
  49. package/lib/context-binding.mjs +6 -1
  50. package/lib/context-ipc.mjs +44 -2
  51. package/lib/owner-evidence.mjs +67 -0
  52. package/lib/session-file.mjs +20 -8
  53. package/package.json +13 -3
  54. package/scripts/build-actions.mjs +133 -0
@@ -0,0 +1,190 @@
1
+ // Canonical AOP observer, generated into independently installable npm packages and MV3.
2
+ // Soft evidence only: no parameters, results, URLs, secrets or model content.
3
+ const SAFE=/^[a-zA-Z][a-zA-Z0-9_.:-]{0,126}$/;
4
+ const PACKAGE=/^@[a-z0-9][a-z0-9._-]{0,45}\/[a-z0-9][a-z0-9._-]{0,80}$/;
5
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6
+ const safe=(s,fallback='api.unknown')=>typeof s==='string'&&SAFE.test(s)?s:fallback;
7
+ const code=e=>typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
8
+ ?e.code:'API_FAILED';
9
+ const uid=()=>{
10
+ try{return globalThis.crypto.randomUUID()}catch{
11
+ const hex='0123456789abcdef',h=n=>Array.from({length:n},
12
+ ()=>hex[Math.floor(Math.random()*16)]).join('');
13
+ return h(8)+'-'+h(4)+'-4'+h(3)+'-a'+h(3)+'-'+h(12);
14
+ }
15
+ };
16
+ const schedule=typeof setImmediate==='function'?setImmediate:fn=>setTimeout(fn,0);
17
+ const clock=()=>typeof performance!=='undefined'&&typeof performance.now==='function'
18
+ ?performance.now():Date.now();
19
+ const MAX_PENDING=4096,MAX_BATCH=128;
20
+ const CONTEXT_KEY=Symbol.for('chat-loop.observation.async-context.v1');
21
+ // Process-local correlation only, never an authorization or plugin registry.
22
+ const contextStore=()=>{
23
+ if(typeof process==='undefined'||typeof process.getBuiltinModule!=='function')return null;
24
+ try{
25
+ if(!process[CONTEXT_KEY]){
26
+ const {AsyncLocalStorage}=process.getBuiltinModule('node:async_hooks');
27
+ Object.defineProperty(process,CONTEXT_KEY,{
28
+ value:new AsyncLocalStorage(),enumerable:false,configurable:false
29
+ });
30
+ }
31
+ return process[CONTEXT_KEY];
32
+ }catch{return null}
33
+ };
34
+ const validParent=v=>v&&UUID.test(v.traceId||'')&&UUID.test(v.spanId||'');
35
+ export function currentApiTrace(){
36
+ try{
37
+ const local=contextStore()?.getStore();
38
+ if(validParent(local))return {traceId:local.traceId,spanId:local.spanId};
39
+ // Child-process context is sanitized correlation metadata, not trust.
40
+ const value=typeof process!=='undefined'?process.env?.CHAT_LOOP_API_PARENT:null;
41
+ if(typeof value!=='string'||value.length>180)return null;
42
+ const parsed=JSON.parse(value);
43
+ return validParent(parsed)?{traceId:parsed.traceId,spanId:parsed.spanId}:null;
44
+ }catch{return null}
45
+ }
46
+ export function withApiTraceParent(parent,fn){
47
+ if(typeof fn!=='function')throw TypeError('API_TRACE_CALLBACK_REQUIRED');
48
+ if(!validParent(parent))throw TypeError('API_TRACE_PARENT_INVALID');
49
+ const storage=contextStore();
50
+ return storage?storage.run({traceId:parent.traceId,spanId:parent.spanId},fn):fn();
51
+ }
52
+ export function createApiAspect(packageName,{sink}={}){
53
+ const packageId=typeof packageName==='string'&&PACKAGE.test(packageName)
54
+ ?packageName:'unknown';
55
+ const queue=[],listeners=new Set(),
56
+ stats={emitted:0,delivered:0,dropped:0,sinkFailures:0};
57
+ let scheduled=false;
58
+ const output=typeof sink==='function'?sink:record=>{
59
+ if(listeners.size){
60
+ for(const listener of [...listeners]){
61
+ try{
62
+ const result=listener(record);
63
+ if(result&&typeof result.then==='function')
64
+ Promise.resolve(result).catch(()=>{stats.sinkFailures++});
65
+ }catch{stats.sinkFailures++}
66
+ }
67
+ return;
68
+ }
69
+ if(typeof process==='undefined'||!process.stderr?.write||
70
+ process.env.CHAT_LOOP_API_LOG_STDERR==='0')return;
71
+ process.stderr.write('CHAT_LOOP_API_LOG '+JSON.stringify(record)+'\n');
72
+ };
73
+ const flush=()=>{
74
+ scheduled=false;
75
+ for(let i=0;i<MAX_BATCH&&queue.length;i++){
76
+ const item=queue.shift();
77
+ try{
78
+ const result=output(item);
79
+ stats.delivered++;
80
+ if(result&&typeof result.then==='function')
81
+ Promise.resolve(result).catch(()=>{stats.sinkFailures++});
82
+ }catch{stats.sinkFailures++}
83
+ }
84
+ if(queue.length){scheduled=true;schedule(flush)}
85
+ };
86
+ const emit=event=>{
87
+ try{
88
+ if(queue.length>=MAX_PENDING){stats.dropped++;return}
89
+ queue.push(Object.freeze(event));stats.emitted++;
90
+ if(!scheduled){scheduled=true;schedule(flush)}
91
+ }catch{stats.dropped++}
92
+ };
93
+ function observe(name,fn,surface='sdk',options={}){
94
+ if(typeof fn!=='function')throw TypeError('API_ASPECT_TARGET_REQUIRED');
95
+ const api=safe(name),layer=safe(surface,'sdk');
96
+ return new Proxy(fn,{
97
+ get(target,key,receiver){
98
+ if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
99
+ return Reflect.get(target,key,receiver);
100
+ },
101
+ apply(target,thisArg,args){
102
+ let started,base;
103
+ try{
104
+ // MCP requests are fresh user operations, not children of a
105
+ // long-lived CLI/server bootstrap event listener registration.
106
+ // Browser callbacks lack Node AsyncLocalStorage; a narrowly scoped
107
+ // explicit parent links the async reply to its actual dispatch span.
108
+ const explicit=validParent(options?.parent)?options.parent:null;
109
+ const callId=uid(),parent=explicit||(layer==='mcp'?null:currentApiTrace());
110
+ started=clock();
111
+ base={contract:'chat-loop.api-call.v1',package:packageId,
112
+ api,surface:layer,callId,
113
+ traceId:parent?.traceId||callId,spanId:callId,
114
+ parentSpanId:parent?.spanId||null};
115
+ }catch{/* Never fail a target due to tracing. */}
116
+ const mark=(phase,error)=>{
117
+ if(!base)return;
118
+ try{
119
+ emit({...base,phase,time:new Date().toISOString(),
120
+ durationMs:phase==='BEGIN'?null:Math.max(0,Math.round(clock()-started)),
121
+ errorCode:phase==='FAILED'?code(error):null});
122
+ }catch{/* Non-authoritative telemetry. */}
123
+ };
124
+ mark('BEGIN');
125
+ // Only sanitized correlation IDs may cross from the AOP boundary into
126
+ // the hosting callback. A faulty observer must never affect the call.
127
+ if(base&&typeof options?.onBegin==='function'){
128
+ try{options.onBegin(Object.freeze({traceId:base.traceId,spanId:base.spanId}));}
129
+ catch{stats.sinkFailures++}
130
+ }
131
+ const execute=()=>Reflect.apply(target,thisArg,args);
132
+ let result;
133
+ try{
134
+ const storage=base?contextStore():null;
135
+ result=storage?storage.run({traceId:base.traceId,spanId:base.spanId},execute)
136
+ :execute();
137
+ }catch(e){mark('FAILED',e);throw e}
138
+ const failed=value=>{
139
+ try{return (layer==='mcp'&&value?.isError===true)
140
+ ||(layer==='browser'&&api.startsWith('browser.dispatch.')&&value===false)}
141
+ catch{stats.sinkFailures++;return false}
142
+ };
143
+ const failureCode=()=>({code:layer==='browser'
144
+ ?'BROWSER_MESSAGE_UNHANDLED':'MCP_TOOL_ERROR'});
145
+ // Do not assimilate arbitrary user thenables for telemetry: invoking
146
+ // their then() could cause a second business side effect. Observe native
147
+ // Promises only, otherwise record the synchronous return boundary.
148
+ let nativePromise=false;
149
+ try{nativePromise=result instanceof Promise}catch{stats.sinkFailures++}
150
+ if(nativePromise){
151
+ // Preserve the exact native Promise object and rejection semantics.
152
+ try{Promise.resolve(result).then(
153
+ value=>{
154
+ const isError=failed(value);
155
+ mark(isError?'FAILED':'OK',
156
+ isError?failureCode():undefined);
157
+ },
158
+ error=>mark('FAILED',error)
159
+ ).catch(()=>{stats.sinkFailures++});}
160
+ catch{stats.sinkFailures++}
161
+ return result;
162
+ }
163
+ const isError=failed(result);
164
+ mark(isError?'FAILED':'OK',
165
+ isError?failureCode():undefined);
166
+ return result;
167
+ }});
168
+ }
169
+ function methods(instance,prefix,surface='sdk'){
170
+ if(!instance||typeof instance!=='object')return instance;
171
+ const facade={...instance},cache=new Map();
172
+ return new Proxy(facade,{
173
+ get(object,key,receiver){
174
+ const v=Reflect.get(object,key,receiver);
175
+ if(typeof v!=='function'||typeof key!=='string')return v;
176
+ if(!cache.has(key))cache.set(key,observe(prefix+'.'+key,v,surface));
177
+ return cache.get(key);
178
+ },
179
+ set(){return false},defineProperty(){return false},deleteProperty(){return false}
180
+ });
181
+ }
182
+ const subscribe=observe('subscribeApiLog',listener=>{
183
+ if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
184
+ listeners.add(listener);
185
+ return ()=>listeners.delete(listener);
186
+ },'internal');
187
+ return Object.freeze({observe,methods,subscribe,
188
+ health:()=>Object.freeze({...stats,pending:queue.length}),
189
+ current:currentApiTrace,withParent:withApiTraceParent});
190
+ }
package/lib/bridge.mjs CHANGED
@@ -4,12 +4,23 @@ import {homedir, tmpdir} from 'node:os';
4
4
  import {join} from 'node:path';
5
5
 
6
6
  export const HOST_NAME = 'com.tomflow.chatloop.extension';
7
- export const ACTIONS = ['chat_text', 'chat_dom', 'chat_screenshot', 'reload', 'continue', 'handoff', 'clean', 'status', 'start'];
7
+ export let ACTIONS=Object.freeze([]);
8
+ export function configureBridgeActions(actions){
9
+ if(ACTIONS.length)throw Error('EXTENSION_ACTIONS_ALREADY_CONFIGURED');
10
+ if(!Array.isArray(actions)||!actions.length||
11
+ actions.some(action=>typeof action?.id!=='string'))
12
+ throw Error('EXTENSION_ACTIONS_INVALID');
13
+ ACTIONS=Object.freeze(actions.map(action=>action.id));
14
+ }
8
15
  const ID = /^[a-f0-9]{32}$/;
9
16
  const MAX_TEXT = 8 * 1024 * 1024;
10
17
  const MAX_PNG = 24 * 1024 * 1024;
11
18
  const TTL_MS = 20 * 60 * 1000;
12
19
  const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
20
+ function pathEntryExists(path){
21
+ try{lstatSync(path);return true}
22
+ catch(error){if(error.code==='ENOENT')return false;throw error}
23
+ }
13
24
  export const configFile = () => join(homedir(), '.chat-loop', 'extension', 'config.json');
14
25
  export const tempRoot = () => join(tmpdir(), 'chatloop-extension-' + (process.getuid?.() ?? process.env.USERNAME ?? 'user'));
15
26
  export function privateDir(path) {
@@ -20,6 +31,14 @@ export function privateDir(path) {
20
31
  throw Object.assign(Error('Untrusted extension state directory'),{code:'UNTRUSTED_STATE'});
21
32
  return path;
22
33
  }
34
+ // Both request and reply are private IPC records; never trust a symlink or
35
+ // a file with broader permissions merely because its directory is private.
36
+ function privateRecord(file,code){
37
+ const st=lstatSync(file);
38
+ if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
39
+ ||(process.platform!=='win32'&&(st.mode&0o077)))
40
+ throw Object.assign(Error('Untrusted extension record'),{code});
41
+ }
23
42
  export function requestDir(id) {
24
43
  if(typeof id!=='string'||!ID.test(id))throw Object.assign(Error('Invalid request ID'),{code:'INVALID_REQUEST_ID'});
25
44
  return join(tempRoot(),id);
@@ -109,11 +128,10 @@ export function prepare(action,intent) {
109
128
  }
110
129
  export function readRequest(id) {
111
130
  const dir=requestDir(id);
112
- if(!existsSync(dir))throw Object.assign(Error('No request'),{code:'NO_REQUEST'});
131
+ if(!pathEntryExists(dir))throw Object.assign(Error('No request'),{code:'NO_REQUEST'});
113
132
  privateDir(dir);
114
- const p=join(dir,'request.json'), st=lstatSync(p);
115
- if(!st.isFile()||st.isSymbolicLink() || (process.getuid && st.uid!==process.getuid()))
116
- throw Object.assign(Error('Invalid request record'),{code:'UNTRUSTED_REQUEST'});
133
+ const p=join(dir,'request.json');
134
+ privateRecord(p,'UNTRUSTED_REQUEST');
117
135
  const r=JSON.parse(readFileSync(p,'utf8'));
118
136
  if(r.id!==id||!ACTIONS.includes(r.action)||Date.now()>r.expiresAt)
119
137
  throw Object.assign(Error('Request expired or changed'),{code:'REQUEST_EXPIRED'});
@@ -126,7 +144,7 @@ export function finish({id,nonce,action,status,payload='',code=null}) {
126
144
  if(status!=='OK'&&status!=='FAILED')throw Object.assign(Error('Invalid status'),{code:'INVALID_RESULT'});
127
145
  const dir=requestDir(id);
128
146
  const resultPath=join(dir,'result.json');
129
- if(existsSync(resultPath))throw Object.assign(Error('Duplicate result'),{code:'ALREADY_FINISHED'});
147
+ if(pathEntryExists(resultPath))throw Object.assign(Error('Duplicate result'),{code:'ALREADY_FINISHED'});
130
148
  let bytes=0,mimeType=null,filename=null;
131
149
  if(status==='OK'){
132
150
  if(typeof payload!=='string')throw Object.assign(Error('Invalid payload'),{code:'INVALID_PAYLOAD'});
@@ -155,8 +173,9 @@ export function finish({id,nonce,action,status,payload='',code=null}) {
155
173
  }
156
174
  export function readResult(id) {
157
175
  const p=join(requestDir(id),'result.json');
158
- if(!existsSync(p))return null;
176
+ if(!pathEntryExists(p))return null;
159
177
  privateDir(requestDir(id));
178
+ privateRecord(p,'UNTRUSTED_RESULT');
160
179
  return JSON.parse(readFileSync(p,'utf8'));
161
180
  }
162
181
  export function cleanup(){
@@ -2,7 +2,12 @@
2
2
  // The files retain the task/approval truth; this index never grants execution.
3
3
  import {existsSync,lstatSync,readFileSync,realpathSync} from 'node:fs';
4
4
  import {dirname,isAbsolute} from 'node:path';
5
- import {configFile} from './bridge.mjs';
5
+ let configFile;
6
+ export function configureContextBinding(api){
7
+ if(configFile)throw Error('EXTENSION_MODULE_ALREADY_COMPOSED');
8
+ if(typeof api?.configFile!=='function')throw Error('EXTENSION_PORT_MISSING:configFile');
9
+ configFile=api.configFile;
10
+ }
6
11
  const invalid=()=>Object.assign(Error('CONTEXT_BINDING_UNVERIFIED'),{code:'CONTEXT_BINDING_UNVERIFIED'});
7
12
  const trusted=(p,directory=false)=>{
8
13
  const s=lstatSync(p);
@@ -20,6 +20,7 @@ function privateFile(path,type){
20
20
  }
21
21
  const ipc=(request,timeout=4000)=>new Promise((resolve,reject)=>{
22
22
  const socket=connect(join(base(),'control.sock'));
23
+ socket.setEncoding('utf8'); // Preserve JSON code points split by socket chunks.
23
24
  let text='',done=false;
24
25
  const timer=setTimeout(()=>finish(fail('CONTEXT_CONTROL_TIMEOUT')),timeout);
25
26
  function finish(error,value){
@@ -30,8 +31,8 @@ const ipc=(request,timeout=4000)=>new Promise((resolve,reject)=>{
30
31
  socket.on('error',e=>finish(e));
31
32
  socket.on('end',()=>{if(!done)finish(fail('CONTEXT_CONTROL_UNCONFIRMED'))});
32
33
  socket.on('data',chunk=>{
33
- text+=chunk.toString();
34
- if(text.length>1_000_000)return finish(fail('CONTEXT_CONTROL_REPLY_TOO_LARGE'));
34
+ text+=chunk;
35
+ if(Buffer.byteLength(text,'utf8')>1_000_000)return finish(fail('CONTEXT_CONTROL_REPLY_TOO_LARGE'));
35
36
  const n=text.indexOf('\n');if(n<0)return;
36
37
  try{finish(null,JSON.parse(text.slice(0,n)))}catch{finish(fail('CONTEXT_CONTROL_REPLY_INVALID'))}
37
38
  });
@@ -63,3 +64,44 @@ export async function nativeContextControl(command,args){
63
64
  if(reply.status!=='OK')throw fail(reply.error?.code||'CONTEXT_CONTROL_FAILED');
64
65
  return reply.result;
65
66
  }
67
+
68
+ // Independent, best-effort observation channel. These records contain only
69
+ // generated call IDs, allowlisted API names and timings; never business data.
70
+ // A missing Supervisor only drops telemetry, never retries a native action.
71
+ const API_UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
72
+ const API_NAME=/^extension\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
73
+ const API_CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
74
+ export async function nativeApiObservation(record){
75
+ if(!record||typeof record!=='object'||Array.isArray(record)||
76
+ Object.keys(record).some(key=>!['callId','traceId','spanId','parentSpanId',
77
+ 'apiName','phase','durationMs','errorCode'].includes(key))||
78
+ !API_UUID.test(record.callId||'')||
79
+ (record.traceId!==undefined&&!API_UUID.test(record.traceId))||
80
+ (record.spanId!==undefined&&record.spanId!==record.callId)||
81
+ (record.parentSpanId!==undefined&&!API_UUID.test(record.parentSpanId))||
82
+ !API_NAME.test(record.apiName||'')||
83
+ !['BEGIN','OK','FAILED'].includes(record.phase)||
84
+ (record.phase==='BEGIN'
85
+ ?record.durationMs!==undefined||record.errorCode!==undefined
86
+ :!Number.isSafeInteger(record.durationMs)||record.durationMs<0||
87
+ (record.phase==='FAILED'?!API_CODE.test(record.errorCode||'')
88
+ :record.errorCode!==undefined)))
89
+ throw fail('API_OBSERVATION_INVALID');
90
+ const dir=base(),stat=lstatSync(dir);
91
+ if(!stat.isDirectory()||stat.isSymbolicLink()||(stat.mode&0o077)||
92
+ (process.getuid&&stat.uid!==process.getuid()))
93
+ throw fail('API_OBSERVATION_UNTRUSTED');
94
+ privateFile(join(dir,'control.sock'),'socket');
95
+ privateFile(join(dir,'manager.lock'),'file');
96
+ const hello=await ipc({action:'__ping'},700);
97
+ const owner=JSON.parse(readFileSync(join(dir,'manager.lock'),'utf8'));
98
+ if(hello.contract!=='chat-loop.local-control.v1'||
99
+ hello.ownerNonce!==owner.nonce||hello.managerPid!==owner.pid||
100
+ hello.version!==owner.version||hello.version!==hello.packageVersion)
101
+ throw fail('API_OBSERVATION_OWNER_MISMATCH');
102
+ const request={contract:hello.contract,action:'__api_observation',
103
+ requestId:randomUUID(),...record};
104
+ const response=await ipc(request,1100);
105
+ return response.contract===hello.contract&&
106
+ response.requestId===request.requestId&&response.status==='OK';
107
+ }
@@ -0,0 +1,67 @@
1
+ // Official Extension/Native owner-evidence contract for Context's reviewed
2
+ // orphan fence. Browser Owner remains Extension's authority, not Context's.
3
+ import {execFileSync} from 'node:child_process';
4
+ import {createHash} from 'node:crypto';
5
+ import {readFileSync,lstatSync} from 'node:fs';
6
+ let readSession,sessionPath,cliPath;
7
+ export function configureOwnerEvidence(api){
8
+ if(readSession)throw Error('EXTENSION_MODULE_ALREADY_COMPOSED');
9
+ for(const name of ['readSession','sessionPath','cliPath'])
10
+ if(typeof api?.[name]!=='function')throw Error('EXTENSION_PORT_MISSING:'+name);
11
+ ({readSession,sessionPath,cliPath}=api);
12
+ }
13
+
14
+ const fail=code=>Object.assign(new Error(code),{code});
15
+ const ensure=(ok,code)=>{if(!ok)throw fail(code)};
16
+ const sha=raw=>createHash('sha256').update(raw).digest('hex');
17
+
18
+ function checkedNative(){
19
+ const session=readSession();
20
+ ensure(session?.phase==='DONE'&&typeof session.sessionId==='string'
21
+ &&Number.isSafeInteger(session.updatedAt),'NATIVE_NOT_TERMINAL');
22
+ const raw=readFileSync(sessionPath());
23
+ ensure(sha(Buffer.from(JSON.stringify(session)))===
24
+ sha(Buffer.from(JSON.stringify(JSON.parse(raw.toString('utf8'))))),
25
+ 'NATIVE_POINTER_UNTRUSTED');
26
+ return {sessionId:session.sessionId,projectId:session.projectId,
27
+ taskId:session.taskId||null,phase:session.phase,
28
+ updatedAt:session.updatedAt,rawHash:sha(raw)};
29
+ }
30
+
31
+ function checkedExtensionIdle(){
32
+ // This is the Extension-owned CLI, resolved from this installed package.
33
+ // Context never composes an Extension install path or parses its CLI output.
34
+ const cli=cliPath();
35
+ const st=lstatSync(cli);
36
+ ensure(st.isFile()&&!st.isSymbolicLink(),'EXTENSION_CLI_UNTRUSTED');
37
+ const out=execFileSync(process.execPath,[cli,'extension','status'],{
38
+ encoding:'utf8',timeout:14000,maxBuffer:524288,stdio:['ignore','pipe','pipe']});
39
+ const rows=out.trim().split('\n').map(s=>JSON.parse(s));
40
+ const result=rows.findLast(x=>x.event==='RESULT');
41
+ ensure(result?.ok===true&&result.value?.verified===true
42
+ &&result.value?.truncated===false,'EXTENSION_STATUS_UNVERIFIED');
43
+ const v=JSON.parse(result.value.content||'{}');
44
+ ensure(v.status==='OK'&&v.state==='IDLE'
45
+ &&v.lastSession?.phase==='DONE','EXTENSION_OWNER_NOT_IDLE');
46
+ return v;
47
+ }
48
+
49
+ /**
50
+ * Read-only owner proof; NEVER grants execution or signs R/P approval.
51
+ * Re-run before the final Context fence to detect Native/Worker drift.
52
+ */
53
+ export function verifyOrphanOwnerIdle({oldRunRef,projectId}){
54
+ const native=checkedNative(),extension=checkedExtensionIdle();
55
+ const oldId=oldRunRef.split(':')[0];
56
+ ensure(native.sessionId!==oldId&&native.projectId!==projectId,
57
+ 'ORPHAN_OWNER_STILL_CURRENT');
58
+ const live=readSession();
59
+ ensure(live?.phase==='DONE'&&
60
+ extension.lastSession.sessionId===native.sessionId
61
+ &&extension.lastSession.projectId===native.projectId
62
+ &&extension.lastSession.updatedAt===native.updatedAt
63
+ &&extension.lastSession.activeChatId===live.activeChatId
64
+ &&checkedNative().rawHash===native.rawHash,
65
+ 'EXTENSION_NATIVE_POINTER_MISMATCH');
66
+ return native;
67
+ }
@@ -1,6 +1,6 @@
1
1
  // Single-Mac durable session pointer. Extension Worker is the only admission/sending authority.
2
2
  // This file is a checked, minimal projection, not a second executor or task engine.
3
- import {openSync,closeSync,readFileSync,writeFileSync,renameSync,unlinkSync,lstatSync,existsSync,mkdirSync} from 'node:fs';
3
+ import {openSync,closeSync,readFileSync,writeFileSync,renameSync,unlinkSync,lstatSync,mkdirSync} from 'node:fs';
4
4
  import {homedir} from 'node:os';
5
5
  import {join,dirname} from 'node:path';
6
6
  import {randomUUID} from 'node:crypto';
@@ -11,11 +11,23 @@ const PROJECT=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
11
11
  const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY','DONE','BLOCKED']);
12
12
  const fail=code=>Object.assign(Error(code),{code});
13
13
  export const sessionPath=()=>join(homedir(),'.chat-loop','session','active-session.json');
14
+ // An absent path differs from a dangling symlink: existsSync follows the
15
+ // link and would otherwise silently erase the Native Owner projection.
16
+ const entryOrMissing=path=>{
17
+ try{return lstatSync(path)}
18
+ catch(error){if(error.code==='ENOENT')return null;throw error}
19
+ };
20
+ const verifyPrivateDirectory=dir=>{
21
+ const st=entryOrMissing(dir);
22
+ if(st&&(!st.isDirectory()||st.isSymbolicLink()
23
+ ||(process.getuid&&st.uid!==process.getuid())
24
+ ||(process.platform!=='win32'&&(st.mode&0o077))))
25
+ throw fail('SESSION_DIRECTORY_UNTRUSTED');
26
+ return Boolean(st);
27
+ };
14
28
  const ensurePrivate=dir=>{
15
- if(!existsSync(dir))mkdirSync(dir,{recursive:true,mode:0o700});
16
- const st=lstatSync(dir);
17
- if(!st.isDirectory()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())||
18
- (process.platform!=='win32'&&(st.mode&0o077)))throw fail('SESSION_DIRECTORY_UNTRUSTED');
29
+ if(!verifyPrivateDirectory(dir))mkdirSync(dir,{recursive:true,mode:0o700});
30
+ if(!verifyPrivateDirectory(dir))throw fail('SESSION_DIRECTORY_UNTRUSTED');
19
31
  };
20
32
  const validate=r=>{
21
33
  if(!r||typeof r!=='object'||Array.isArray(r)||
@@ -40,9 +52,9 @@ const validate=r=>{
40
52
  };
41
53
  export function readSession(){
42
54
  const file=sessionPath();
43
- if(!existsSync(file))return null;
44
- ensurePrivate(dirname(file));
45
- const st=lstatSync(file);
55
+ if(!verifyPrivateDirectory(dirname(file)))return null;
56
+ const st=entryOrMissing(file);
57
+ if(!st)return null;
46
58
  if(!st.isFile()||st.isSymbolicLink()||(process.getuid&&st.uid!==process.getuid())
47
59
  ||(process.platform!=='win32'&&(st.mode&0o077)))throw fail('SESSION_FILE_UNTRUSTED');
48
60
  try{return validate(JSON.parse(readFileSync(file,'utf8')));}
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.3.84",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
6
6
  "bin": {
7
- "chatloop-extension": "bin/cli.mjs",
8
- "chat-loop-browser": "bin/cli.mjs"
7
+ "chatloop-extension": "bin/cli.mjs"
9
8
  },
10
9
  "engines": {
11
10
  "node": ">=20"
@@ -14,12 +13,23 @@
14
13
  "access": "public"
15
14
  },
16
15
  "files": [
16
+ "index.mjs",
17
+ "actions.generated.mjs",
18
+ "capabilities/",
19
+ "scripts/",
17
20
  "extension/",
18
21
  "bin/",
19
22
  "lib/",
20
23
  "README.md"
21
24
  ],
22
25
  "scripts": {
26
+ "build:actions": "node ./scripts/build-actions.mjs",
27
+ "build:actions:check": "node ./scripts/build-actions.mjs --check",
28
+ "pretest": "node ./scripts/build-actions.mjs --check",
29
+ "prepack": "node ./scripts/build-actions.mjs --check",
23
30
  "test": "node --test ./test/*.test.mjs"
31
+ },
32
+ "exports": {
33
+ ".": "./index.mjs"
24
34
  }
25
35
  }
@@ -0,0 +1,133 @@
1
+ // Extension action definitions are assembled at build time, never discovered
2
+ // by a privileged running Chrome Worker or Native Host.
3
+ import {readFileSync,readdirSync,writeFileSync,unlinkSync,existsSync} from 'node:fs';
4
+ import {dirname,join,resolve} from 'node:path';
5
+ import {fileURLToPath,pathToFileURL} from 'node:url';
6
+ import {createHash} from 'node:crypto';
7
+ const root=dirname(dirname(fileURLToPath(import.meta.url)));
8
+ const fail=code=>Object.assign(Error(code),{code});
9
+ const originals=['chat_text','chat_dom','chat_screenshot','reload',
10
+ 'continue','handoff','clean','status','start'];
11
+ const privilegedKinds=Object.freeze({chat_text:'eye-read',chat_dom:'eye-read',
12
+ chat_screenshot:'eye-screenshot',reload:'eye-reload',
13
+ continue:'owner-intent',handoff:'owner-intent',clean:'owner-clean',
14
+ status:'owner-status',start:'owner-start'});
15
+ // Existing timeout and receipt projection are part of the public action
16
+ // behavior; a descriptor edit must not silently change side-effect handling.
17
+ const builtinBehavior=Object.freeze({
18
+ chat_text:[27000,true],chat_dom:[27000,true],
19
+ chat_screenshot:[27000,false],reload:[27000,false],
20
+ continue:[27000,true],handoff:[27000,true],clean:[27000,true],
21
+ status:[27000,true],start:[310000,true]
22
+ });
23
+ const builtinRoute=Object.freeze({
24
+ chat_text:['text.html','chat text'],chat_dom:['dom.html','chat dom'],
25
+ chat_screenshot:['screenshot.html','chat screenshot'],
26
+ reload:['reload.html','reload'],continue:['continue.html','continue'],
27
+ handoff:['handoff.html','handoff'],clean:['clean.html','clean'],
28
+ status:['status.html','status'],start:['start.html','start']
29
+ });
30
+ const generatedMarker='<!-- GENERATED BY build-actions.mjs -->';
31
+ export async function compileActions(source=join(root,'capabilities'),
32
+ extension=join(root,'extension')){
33
+ const files=readdirSync(source).filter(f=>f.endsWith('.mjs')).sort();
34
+ const ids=new Set(),pages=new Set(),clis=new Set(),actions=[];
35
+ if(!files.length)throw fail('EXTENSION_ACTIONS_EMPTY');
36
+ for(const file of files){
37
+ if(!/^[a-z][a-z0-9_]*\.mjs$/.test(file))
38
+ throw fail('EXTENSION_CAPABILITY_FILENAME_INVALID');
39
+ const path=join(source,file);
40
+ const hash=createHash('sha256').update(readFileSync(path)).digest('hex');
41
+ const {capability:c}=await import(pathToFileURL(path).href+'?sha256='+hash);
42
+ if(!c||c.id!==file.slice(0,-4)||
43
+ !/^[a-z][a-z0-9_]*$/.test(c.id)||
44
+ !/^[a-z][a-z0-9-]*\.html$/.test(c.page)||
45
+ !Array.isArray(c.cli)||!c.cli.length||
46
+ c.cli.some(t=>typeof t!=='string'||!/^[a-z][a-z0-9-]*$/.test(t))||
47
+ !Number.isSafeInteger(c.waitMs)||c.waitMs<1||c.waitMs>310000||
48
+ typeof c.textResult!=='boolean'||typeof c.description!=='string'||
49
+ !c.description.trim()||ids.has(c.id)||pages.has(c.page)||
50
+ clis.has(c.cli.join(' ')))
51
+ throw fail('EXTENSION_CAPABILITY_INVALID');
52
+ ids.add(c.id);pages.add(c.page);clis.add(c.cli.join(' '));
53
+ const newAction=!originals.includes(c.id);
54
+ if(!newAction && privilegedKinds[c.id]!==c.kind)
55
+ throw fail('EXTENSION_ACTION_AUTHORITY_CHANGED');
56
+ if(!newAction && (c.page!==builtinRoute[c.id][0]||
57
+ c.cli.join(' ')!==builtinRoute[c.id][1]))
58
+ throw fail('EXTENSION_BUILTIN_ROUTE_CHANGED');
59
+ if(!newAction && (c.waitMs!==builtinBehavior[c.id][0]||
60
+ c.textResult!==builtinBehavior[c.id][1]))
61
+ throw fail('EXTENSION_BUILTIN_BEHAVIOR_CHANGED');
62
+ if(newAction && !c.textResult)
63
+ throw fail('EXTENSION_READ_RESULT_REQUIRED');
64
+ if(c.kind==='eye-read'&&(!c.id.startsWith('chat_')||
65
+ !['text','dom'].includes(c.readMode)))
66
+ throw fail('EXTENSION_EYE_READ_MODE_INVALID');
67
+ if(newAction && c.kind!=='eye-read')
68
+ throw fail('EXTENSION_PRIVILEGED_ACTION_REVIEW_REQUIRED');
69
+ if((c.id==='chat_text'&&c.readMode!=='text')||
70
+ (c.id==='chat_dom'&&c.readMode!=='dom'))
71
+ throw fail('EXTENSION_BUILTIN_EYE_MODE_CHANGED');
72
+ const page=join(extension,c.page);
73
+ const generated=existsSync(page)&&
74
+ readFileSync(page,'utf8').startsWith(generatedMarker);
75
+ if(!existsSync(page) && !newAction)
76
+ throw fail('EXTENSION_ACTION_PAGE_MISSING');
77
+ if(existsSync(page)&&!generated){
78
+ const expected='actions/'+(c.id.startsWith('chat_')?c.id.slice(5):c.id)+'.js';
79
+ if(!readFileSync(page,'utf8').includes(expected))
80
+ throw fail('EXTENSION_ACTION_EXECUTOR_MISMATCH');
81
+ }
82
+ actions.push({...c,file,generated:newAction});
83
+ }
84
+ actions.sort((a,b)=>(
85
+ (originals.indexOf(a.id)<0?99:originals.indexOf(a.id))-
86
+ (originals.indexOf(b.id)<0?99:originals.indexOf(b.id))
87
+ ||a.id.localeCompare(b.id)));
88
+ const imports=actions.map((a,i)=>
89
+ "import {capability as a"+i+"} from './capabilities/"+a.file+"';").join('\n');
90
+ const node='// GENERATED by scripts/build-actions.mjs — do not edit.\n'+
91
+ imports+'\nexport const actionCapabilities=Object.freeze(['+
92
+ actions.map((_,i)=>'a'+i).join(',')+']);\n';
93
+ const eye=Object.fromEntries(actions.filter(a=>a.kind.startsWith('eye-'))
94
+ .map(a=>[a.id,{page:a.page,kind:a.kind,readMode:a.readMode??null}]));
95
+ const browser='// GENERATED by scripts/build-actions.mjs — do not edit.\n'+
96
+ 'globalThis.ChatLoopEyeCatalogV1=Object.freeze('+JSON.stringify(eye)+');\n';
97
+ const aliases={};
98
+ for(const a of actions.filter(a=>a.generated)){
99
+ aliases[a.page]=generatedMarker+'\n<!doctype html><html><head><meta charset="utf-8">'+
100
+ '<title>Chat Loop read action</title></head><body>'+
101
+ '<p id="status"></p><p id="details"></p>'+
102
+ '<script src="actions/common.js"></script>'+
103
+ '<script src="actions/read-mode.js" data-action="'+a.id+
104
+ '" data-read-mode="'+a.readMode+'"></script></body></html>\n';
105
+ }
106
+ return {node,browser,aliases};
107
+ }
108
+ async function main(){
109
+ const ext=join(root,'extension'),expected=await compileActions();
110
+ const manifest=JSON.parse(readFileSync(join(ext,'manifest.json'),'utf8'));
111
+ const pkg=JSON.parse(readFileSync(join(root,'package.json'),'utf8'));
112
+ if(manifest.version!==pkg.version||manifest.manifest_version!==3)
113
+ throw fail('EXTENSION_PACKAGE_VERSION_MISMATCH');
114
+ const targets=[[join(root,'actions.generated.mjs'),expected.node],
115
+ [join(ext,'loop','action-catalog.generated.js'),expected.browser],
116
+ ...Object.entries(expected.aliases).map(([page,html])=>[join(ext,page),html])];
117
+ const orphan=readdirSync(ext).filter(f=>f.endsWith('.html')&&
118
+ !Object.hasOwn(expected.aliases,f)&&
119
+ readFileSync(join(ext,f),'utf8').startsWith(generatedMarker));
120
+ if(process.argv.includes('--check')){
121
+ if(orphan.length||targets.some(([file,value])=>!existsSync(file)||
122
+ readFileSync(file,'utf8')!==value))
123
+ throw fail('EXTENSION_ACTIONS_STALE');
124
+ if(process.env.npm_lifecycle_event!=='prepack')
125
+ console.log('EXTENSION_ACTIONS_CURRENT');
126
+ }else{
127
+ for(const page of orphan)unlinkSync(join(ext,page));
128
+ for(const [file,value] of targets)writeFileSync(file,value);
129
+ console.log('EXTENSION_ACTIONS_BUILT');
130
+ }
131
+ }
132
+ if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))
133
+ await main();