@tomflow/chatloop-extension 0.4.0 → 0.4.2

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
@@ -6,7 +6,8 @@ import {homedir} from 'node:os';
6
6
  import {dirname,join,resolve} from 'node:path';
7
7
  import {fileURLToPath} from 'node:url';
8
8
  import {extensionCliApi} from '../index.mjs';
9
- const {ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId}=extensionCliApi();
9
+ const cliContract=extensionCliApi();
10
+ const {ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId}=cliContract;
10
11
  const actionById=new Map(actionCapabilities.map(cap=>[cap.id,cap]));
11
12
  const actionHelp=actionCapabilities.map(cap=>cap.cli.join(' ')+
12
13
  (cap.kind==='owner-clean'?' <tab-id>':'')).join(' | ');
@@ -122,12 +123,18 @@ async function execute(argv) {
122
123
  }
123
124
  const args=process.argv.slice(2),command=args.join(' ')||'capabilities';
124
125
  const help=helpFor(args);
125
- if(help!==null){process.stdout.write(help+'\n');process.exit(0);}
126
- emit('STARTED',command);
127
- try{
128
- const data=await execute(args);
129
- emit('RESULT',command,{ok:true,value:data});
130
- }catch(e){
131
- emit('RESULT',command,{ok:false,error:{code:e.code||'UNKNOWN_RESULT',message:e.message}});
132
- process.exitCode=1;
126
+ if(help!==null){
127
+ process.stdout.write(help+'\n');
128
+ }else{
129
+ emit('STARTED',command);
130
+ try{
131
+ const data=await execute(args);
132
+ emit('RESULT',command,{ok:true,value:data});
133
+ }catch(e){
134
+ emit('RESULT',command,{ok:false,error:{code:e.code||'UNKNOWN_RESULT',message:e.message}});
135
+ process.exitCode=1;
136
+ }
133
137
  }
138
+ // After the CLI reply is produced, allow bounded observation delivery.
139
+ // This never changes its result or retries its business side effect.
140
+ await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(300);
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // Chrome Native Messaging: one request per process, no persistent server.
3
3
  import {nativeHostApi} from '../index.mjs';
4
+ const hostContract=nativeHostApi();
4
5
  const {readRequest,finish,readSession,writeSession,registeredContext,
5
- nativeContextControl,nativeApiObservation,observeNativeOperation}=nativeHostApi();
6
+ nativeContextControl,nativeApiObservation,observeNativeOperation}=hostContract;
6
7
  const MAX_INPUT=48*1024*1024;
7
8
  const write=obj=>{
8
9
  const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
@@ -71,4 +72,9 @@ process.stdin.on('data',async chunk=>{
71
72
  if(m.op==='api-observation')await dispatch();
72
73
  else await observeNativeOperation(m.op,dispatch);
73
74
  }catch(e){write({status:'FAILED',code:e.code||'NATIVE_HOST_ERROR'});}
75
+ 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);
79
+ }
74
80
  });
@@ -1,4 +1,4 @@
1
- // Canonical AOP observer, generated into independently installable npm packages and MV3.
1
+ // Canonical Node AOP observer exported by Trace; only MV3 uses a generated copy.
2
2
  // Soft evidence only: no parameters, results, URLs, secrets or model content.
3
3
  const SAFE=/^[a-zA-Z][a-zA-Z0-9_.:-]{0,126}$/;
4
4
  const PACKAGE=/^@[a-z0-9][a-z0-9._-]{0,45}\/[a-z0-9][a-z0-9._-]{0,80}$/;
@@ -49,25 +49,42 @@ function withApiTraceParent(parent,fn){
49
49
  const storage=contextStore();
50
50
  return storage?storage.run({traceId:parent.traceId,spanId:parent.spanId},fn):fn();
51
51
  }
52
- function createApiAspect(packageName,{sink}={}){
52
+ function createApiAspect(packageName,{sink,bufferUntilSubscribe=false}={}){
53
53
  const packageId=typeof packageName==='string'&&PACKAGE.test(packageName)
54
54
  ?packageName:'unknown';
55
- const queue=[],listeners=new Set(),
55
+ const queue=[],bootstrap=[],listeners=new Set(),inFlight=new Set(),
56
56
  stats={emitted:0,delivered:0,dropped:0,sinkFailures:0};
57
57
  let scheduled=false;
58
58
  const output=typeof sink==='function'?sink:record=>{
59
+ // Trace's own public factory is called before the Tools observer can
60
+ // subscribe. Retain only bounded metadata until its first subscriber.
61
+ if(bufferUntilSubscribe&&!listeners.size){
62
+ if(bootstrap.length>=MAX_PENDING){stats.dropped++;return false}
63
+ bootstrap.push(record);
64
+ return;
65
+ }
59
66
  if(listeners.size){
67
+ const pending=[];
60
68
  for(const listener of [...listeners]){
61
69
  try{
62
70
  const result=listener(record);
63
71
  if(result&&typeof result.then==='function')
64
- Promise.resolve(result).catch(()=>{stats.sinkFailures++});
72
+ pending.push(Promise.resolve(result).then(
73
+ value=>{if(value===false)stats.sinkFailures++},
74
+ ()=>{stats.sinkFailures++}
75
+ ));
76
+ else if(result===false)stats.sinkFailures++;
65
77
  }catch{stats.sinkFailures++}
66
78
  }
67
- return;
79
+ // The drain boundary must also wait for async subscribers, not merely
80
+ // the event queue. A listener failure stays soft but is diagnosed.
81
+ return pending.length?Promise.all(pending):undefined;
68
82
  }
69
83
  if(typeof process==='undefined'||!process.stderr?.write||
70
- process.env.CHAT_LOOP_API_LOG_STDERR==='0')return;
84
+ process.env.CHAT_LOOP_API_LOG_STDERR==='0'){
85
+ stats.dropped++;
86
+ return false;
87
+ }
71
88
  process.stderr.write('CHAT_LOOP_API_LOG '+JSON.stringify(record)+'\n');
72
89
  };
73
90
  const flush=()=>{
@@ -77,8 +94,16 @@ function createApiAspect(packageName,{sink}={}){
77
94
  try{
78
95
  const result=output(item);
79
96
  stats.delivered++;
80
- if(result&&typeof result.then==='function')
81
- Promise.resolve(result).catch(()=>{stats.sinkFailures++});
97
+ // A synchronous explicit rejection must never count as successful
98
+ // delivery merely because the queue is empty.
99
+ if(result===false)stats.sinkFailures++;
100
+ if(result&&typeof result.then==='function'){
101
+ const pending=Promise.resolve(result);
102
+ inFlight.add(pending);
103
+ pending.then(value=>{if(value===false)stats.sinkFailures++},
104
+ ()=>{stats.sinkFailures++}).finally(()=>{inFlight.delete(pending)})
105
+ .catch(()=>{stats.sinkFailures++});
106
+ }
82
107
  }catch{stats.sinkFailures++}
83
108
  }
84
109
  if(queue.length){scheduled=true;schedule(flush)}
@@ -166,26 +191,79 @@ function createApiAspect(packageName,{sink}={}){
166
191
  return result;
167
192
  }});
168
193
  }
169
- function methods(instance,prefix,surface='sdk'){
194
+ // A contract-driven facade for APIs whose safe name/ACL references
195
+ // depend on their arguments (Context). Domain code stays unaware of AOP.
196
+ function described(target,describe,onBegin){
197
+ if(typeof target!=='function'||typeof describe!=='function')
198
+ throw TypeError('API_ASPECT_TARGET_REQUIRED');
199
+ return new Proxy(target,{
200
+ get(fn,key,receiver){
201
+ if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
202
+ return Reflect.get(fn,key,receiver);
203
+ },
204
+ apply(fn,thisArg,args){
205
+ let detail;
206
+ try{detail=describe(args)??{}}catch{detail={api:'api.invalid',mode:'unknown'}}
207
+ const wrapped=observe(detail.api,()=>Reflect.apply(fn,thisArg,args),
208
+ detail.surface??'sdk',{
209
+ onBegin:ids=>{if(typeof onBegin==='function')onBegin(detail,ids)}
210
+ });
211
+ return wrapped();
212
+ }
213
+ });
214
+ }
215
+ // One public method facade for both fixed-name SDK APIs and Context's
216
+ // descriptor-driven APIs. Neither case duplicates Proxy/cache mechanics.
217
+ function mapMethods(instance,wrap,descriptors=null){
170
218
  if(!instance||typeof instance!=='object')return instance;
219
+ if(descriptors)
220
+ for(const [key,item] of Object.entries(Object.getOwnPropertyDescriptors(instance)))
221
+ if(typeof item.value==='function'&&!Object.hasOwn(descriptors,key))
222
+ throw TypeError('API_AUDIT_DESCRIPTOR_MISSING:'+key);
171
223
  const facade={...instance},cache=new Map();
172
224
  return new Proxy(facade,{
173
225
  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));
226
+ const value=Reflect.get(object,key,receiver);
227
+ if(typeof value!=='function'||typeof key!=='string'
228
+ ||(descriptors&&!Object.hasOwn(descriptors,key)))return value;
229
+ if(!cache.has(key))cache.set(key,wrap(key,value));
177
230
  return cache.get(key);
178
231
  },
179
232
  set(){return false},defineProperty(){return false},deleteProperty(){return false}
180
233
  });
181
234
  }
235
+ const describedMethods=(instance,descriptors,onBegin)=>mapMethods(
236
+ instance,(key,value)=>described(value,descriptors[key],onBegin),descriptors);
237
+ const methods=(instance,prefix,surface='sdk')=>mapMethods(
238
+ instance,(key,value)=>observe(prefix+'.'+key,value,surface));
239
+ // Short-lived CLI/Native entrypoints may wait for telemetry *after* replying.
240
+ // No call to drain is made from a business execution path.
241
+ async function drain(timeoutMs=300){
242
+ const budget=Number.isSafeInteger(timeoutMs)?Math.max(0,Math.min(timeoutMs,750)):300;
243
+ const deadline=Date.now()+budget;
244
+ while(queue.length||bootstrap.length||scheduled||inFlight.size){
245
+ if(Date.now()>=deadline)return false;
246
+ await new Promise(resolve=>setTimeout(resolve,Math.min(10,deadline-Date.now())));
247
+ }
248
+ // Clearing a queue is not evidence of successful transport. A failed
249
+ // sink or overflow remains an explicit incomplete audit outcome.
250
+ return stats.dropped===0&&stats.sinkFailures===0;
251
+ }
182
252
  const subscribe=observe('subscribeApiLog',listener=>{
183
253
  if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
184
254
  listeners.add(listener);
255
+ if(bootstrap.length){
256
+ const capacity=Math.max(0,MAX_PENDING-queue.length);
257
+ const replay=bootstrap.splice(0,capacity);
258
+ if(bootstrap.length){stats.dropped+=bootstrap.length;bootstrap.length=0}
259
+ queue.unshift(...replay);
260
+ if(queue.length&&!scheduled){scheduled=true;schedule(flush)}
261
+ }
185
262
  return ()=>listeners.delete(listener);
186
263
  },'internal');
187
- return Object.freeze({observe,methods,subscribe,
188
- health:()=>Object.freeze({...stats,pending:queue.length}),
264
+ return Object.freeze({observe,methods,described,describedMethods,subscribe,drain,
265
+ health:()=>Object.freeze({...stats,pending:queue.length+bootstrap.length,
266
+ bootstrap:bootstrap.length,inFlight:inFlight.size}),
189
267
  current:currentApiTrace,withParent:withApiTraceParent});
190
268
  }
191
269
 
@@ -0,0 +1,45 @@
1
+ // Keep each API span ordered at the existing single Supervisor writer.
2
+ // Telemetry is best-effort: it neither changes nor retries the business call.
3
+ // Concurrent spans are allowed; BEGIN and terminal of one call never race.
4
+ function createOrderedApiObservationSender(deliver,{parallel=16,capacity=2048}={}){
5
+ if(typeof deliver!=='function'||!Number.isInteger(parallel)||parallel<1||
6
+ !Number.isInteger(capacity)||capacity<2)throw TypeError('OBSERVATION_SENDER_INVALID');
7
+ const waiting=[],active=new Set();
8
+ const health={submitted:0,confirmed:0,dropped:0,failed:0};
9
+ let running=0,scheduled=false;
10
+ function pump(){
11
+ scheduled=false;
12
+ while(running<parallel){
13
+ const position=waiting.findIndex(({record})=>!active.has(record.callId));
14
+ if(position<0)return;
15
+ const [{record,resolve}]=waiting.splice(position,1),id=record.callId;
16
+ running++;active.add(id);
17
+ let success=false;
18
+ Promise.resolve().then(()=>deliver(record)).then(result=>{
19
+ success=result!==false;
20
+ if(success)health.confirmed++;
21
+ else health.failed++;
22
+ },()=>{health.failed++}).finally(()=>{
23
+ // Keep later terminal evidence even when BEGIN transport failed:
24
+ // an orphan terminal is an auditable gap, not an invisible call.
25
+ active.delete(id);running--;resolve(success);schedule();
26
+ });
27
+ }
28
+ }
29
+ function schedule(){
30
+ if(scheduled)return;
31
+ scheduled=true;queueMicrotask(pump);
32
+ }
33
+ function send(record){
34
+ health.submitted++;
35
+ if(waiting.length>=capacity){
36
+ health.dropped++;
37
+ return Promise.resolve(false);
38
+ }
39
+ return new Promise(resolve=>{waiting.push({record,resolve});schedule()});
40
+ }
41
+ return Object.freeze({send,
42
+ health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
43
+ }
44
+
45
+ globalThis.ChatLoopApiObservationV1=Object.freeze({createOrderedApiObservationSender});
@@ -2,27 +2,29 @@
2
2
  importScripts('loop/core.js','loop/resources.js');
3
3
  importScripts('loop/action-catalog.generated.js');
4
4
  importScripts('loop/api-aspect.generated.js');
5
+ importScripts('loop/api-observation-queue.generated.js');
5
6
  if(typeof globalThis.ChatLoopCoreV1?.parseStatus!=='function'
6
7
  ||!globalThis.ChatLoopPolicyV1||!globalThis.ChatLoopResourcesV1)
7
8
  throw Error('CHAT_LOOP_WORKER_API_UNAVAILABLE');
9
+ const auditSender=globalThis.ChatLoopApiObservationV1
10
+ ?.createOrderedApiObservationSender(entry=>{
11
+ const native=globalThis.chrome?.runtime?.sendNativeMessage;
12
+ if(typeof native!=='function')return false;
13
+ return Promise.resolve(native('com.tomflow.chatloop.extension',
14
+ {op:'api-observation',record:entry}))
15
+ .then(result=>result?.status==='RECORDED');
16
+ });
8
17
  const apiAudit=globalThis.ChatLoopApiAspectV1?.createApiAspect(
9
18
  '@tomflow/chatloop-extension',{sink:record=>{
10
- // An independent Native telemetry request, never in the Action/Owner path.
11
- // Only a sanitized event is transmitted; no raw page, prompt or receipt.
12
- try{
13
- const native=globalThis.chrome?.runtime?.sendNativeMessage;
14
- if(typeof native!=='function')return;
15
- const entry={callId:record.callId,
19
+ // The Native transport never changes an Action/Owner result.
20
+ // Per-call ordering avoids a terminal overtaking its BEGIN.
21
+ const entry={callId:record.callId,
16
22
  traceId:record.traceId,spanId:record.spanId,
17
23
  ...(record.parentSpanId?{parentSpanId:record.parentSpanId}:{}),
18
24
  apiName:'extension.'+record.api,phase:record.phase,
19
25
  ...(record.durationMs!==null?{durationMs:record.durationMs}:{}),
20
26
  ...(record.errorCode?{errorCode:record.errorCode}:{})};
21
- const pending=native('com.tomflow.chatloop.extension',{
22
- op:'api-observation',record:entry});
23
- if(pending&&typeof pending.then==='function')
24
- Promise.resolve(pending).catch(()=>{});
25
- }catch{/* Telemetry failure may never change a Browser action. */}
27
+ return auditSender?.send(entry);
26
28
  }});
27
29
  if(!apiAudit)throw Error('CHAT_LOOP_WORKER_API_OBSERVER_UNAVAILABLE');
28
30
  globalThis.ChatLoopWorkerApiV1=Object.freeze({
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.0",
4
+ "version": "0.4.2",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
package/index.mjs CHANGED
@@ -3,14 +3,18 @@
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 {createApiAspect} from './lib/api-aspect.mjs';
6
+ import {createApiAspect} from '@tomflow/chatloop-trace';
7
+ import {createOrderedApiObservationSender} from './lib/api-observation-queue.mjs';
8
+ const observationSender=createOrderedApiObservationSender(record=>
9
+ ipc.nativeApiObservation(record));
10
+ const INTERNAL_DRAIN=Symbol.for('chat-loop.telemetry.drain.internal');
7
11
  const apiAspect=createApiAspect('@tomflow/chatloop-extension',{
8
12
  sink:record=>{
9
13
  // The audit transport itself must never trigger another Native audit.
10
14
  // The wrapper still intercepts it, but re-emitting it would recurse.
11
15
  if(record.api==='nativeHostApi'||
12
16
  record.api==='nativeHostApi.nativeApiObservation')return;
13
- return ipc.nativeApiObservation({
17
+ return observationSender.send({
14
18
  callId:record.callId,traceId:record.traceId,spanId:record.spanId,
15
19
  ...(record.parentSpanId?{parentSpanId:record.parentSpanId}:{}),
16
20
  apiName:'extension.'+record.surface+'.'+record.api,
@@ -40,6 +44,7 @@ export const verifyOrphanOwnerIdle=apiAspect.observe(
40
44
  // Internal entrypoint contracts, not a second npm subpath.
41
45
  export const extensionCliApi=apiAspect.observe('extensionCliApi',
42
46
  ()=>apiAspect.methods(Object.freeze({
47
+ [INTERNAL_DRAIN]:apiAspect.drain,
43
48
  ACTIONS:bridge.ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME:bridge.HOST_NAME,
44
49
  configFile:bridge.configFile,prepare:bridge.prepare,
45
50
  readResult:bridge.readResult,privateDir:bridge.privateDir,
@@ -47,6 +52,7 @@ export const extensionCliApi=apiAspect.observe('extensionCliApi',
47
52
  }), 'extensionCliApi','cli'));
48
53
  export const nativeHostApi=apiAspect.observe('nativeHostApi',
49
54
  ()=>apiAspect.methods(Object.freeze({
55
+ [INTERNAL_DRAIN]:apiAspect.drain,
50
56
  readRequest:bridge.readRequest,finish:bridge.finish,
51
57
  readSession:session.readSession,writeSession:session.writeSession,
52
58
  registeredContext:binding.registeredContext,
@@ -0,0 +1,43 @@
1
+ // Keep each API span ordered at the existing single Supervisor writer.
2
+ // Telemetry is best-effort: it neither changes nor retries the business call.
3
+ // Concurrent spans are allowed; BEGIN and terminal of one call never race.
4
+ export function createOrderedApiObservationSender(deliver,{parallel=16,capacity=2048}={}){
5
+ if(typeof deliver!=='function'||!Number.isInteger(parallel)||parallel<1||
6
+ !Number.isInteger(capacity)||capacity<2)throw TypeError('OBSERVATION_SENDER_INVALID');
7
+ const waiting=[],active=new Set();
8
+ const health={submitted:0,confirmed:0,dropped:0,failed:0};
9
+ let running=0,scheduled=false;
10
+ function pump(){
11
+ scheduled=false;
12
+ while(running<parallel){
13
+ const position=waiting.findIndex(({record})=>!active.has(record.callId));
14
+ if(position<0)return;
15
+ const [{record,resolve}]=waiting.splice(position,1),id=record.callId;
16
+ running++;active.add(id);
17
+ let success=false;
18
+ Promise.resolve().then(()=>deliver(record)).then(result=>{
19
+ success=result!==false;
20
+ if(success)health.confirmed++;
21
+ else health.failed++;
22
+ },()=>{health.failed++}).finally(()=>{
23
+ // Keep later terminal evidence even when BEGIN transport failed:
24
+ // an orphan terminal is an auditable gap, not an invisible call.
25
+ active.delete(id);running--;resolve(success);schedule();
26
+ });
27
+ }
28
+ }
29
+ function schedule(){
30
+ if(scheduled)return;
31
+ scheduled=true;queueMicrotask(pump);
32
+ }
33
+ function send(record){
34
+ health.submitted++;
35
+ if(waiting.length>=capacity){
36
+ health.dropped++;
37
+ return Promise.resolve(false);
38
+ }
39
+ return new Promise(resolve=>{waiting.push({record,resolve});schedule()});
40
+ }
41
+ return Object.freeze({send,
42
+ health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
43
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
6
6
  "bin": {
@@ -31,5 +31,8 @@
31
31
  },
32
32
  "exports": {
33
33
  ".": "./index.mjs"
34
+ },
35
+ "dependencies": {
36
+ "@tomflow/chatloop-trace": "0.4.2"
34
37
  }
35
38
  }
@@ -1,190 +0,0 @@
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
- }