@tomflow/chatloop-context 0.6.0 → 0.6.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/README.md CHANGED
@@ -182,7 +182,7 @@ The npm executable is `chatloop-context`, installed by a fixed dependency
182
182
  or invoked separately through a **pinned, available** npm version:
183
183
 
184
184
  ```sh
185
- npm install --save-exact @tomflow/chatloop-context@0.6.0
185
+ npm install --save-exact @tomflow/chatloop-context@0.6.1
186
186
  chatloop-context methods groups
187
187
  chatloop-context methods list project
188
188
  chatloop-context methods describe project.open
@@ -223,7 +223,7 @@ ownership boundaries and known coupling risks.
223
223
 
224
224
  ## Deployment is separate from source
225
225
 
226
- Local npm source version `0.6.0` does **not** establish the connected MCP
226
+ Local npm source version `0.6.1` does **not** establish the connected MCP
227
227
  version. Verify the real `sdk.methods.list` response, Node runtime,
228
228
  pinned Tools dependency, package bytes and Project authority before any
229
229
  separately authorized installation. Source refactoring does **not** migrate
@@ -1,6 +1,6 @@
1
1
  # Context npm package — actual interface, consumer and dependency map
2
2
 
3
- > Applies to the **source** package `@tomflow/chatloop-context@0.6.0`.
3
+ > Applies to the **source** package `@tomflow/chatloop-context@0.6.1`.
4
4
  > The connected MCP may still be running an earlier installed release.
5
5
  > This document describes source contracts, not production cutover approval.
6
6
 
@@ -82,7 +82,7 @@ Ordinary MCP **never exposes** `permit.consume`, `run.bind.initial`,
82
82
  | Context CLI | `project init/register/bind`, `task fence-orphan` and others | Local reviewed operator | Filesystem/path, SourceUnit, TTY and durable evidence gates |
83
83
  | Context CLI/package | packaged `index.mjs`, `bin/cli.mjs`, `lib/core/**` | Tools release/bundle | Exact file fingerprint verification; no npm subpath |
84
84
 
85
- All 34 public operations and the Gateway/Trusted/Operator entrypoints pass the **single AOP Proxy** in `lib/api-log.mjs`, not domain code. Tools maps payload-free events to Trace v2 fixed `event=context.api` and `api={name,surface,mode}`, with `traceId=callId`; the SDK does not write a second log database. API observations never replace the SQLite CAS receipt.
85
+ All 34 public operations and the Gateway/Trusted/Operator entrypoints pass the `lib/api-log.mjs` Context adapter backed by the **single public AOP implementation** exported from `@tomflow/chatloop-trace`; domain code does not implement logging. Tools maps payload-free events to Trace v2 fixed `event=context.api` and `api={name,surface,mode}`. Each call has its own `callId=spanId`; `traceId` is inherited from the verified correlation parent when available, otherwise equals `callId`. The SDK does not write a second log database. API observations never replace the SQLite CAS receipt.
86
86
 
87
87
  The authoritative SQLite state owner is **Context Core**; Tools is an
88
88
  adapter and Supervisor, not another Context database writer. The Chrome
package/index.mjs CHANGED
@@ -3,10 +3,7 @@
3
3
  import {fileURLToPath} from 'node:url';
4
4
  import {capabilities} from './capabilities.generated.mjs';
5
5
  import {createCapabilityRouter} from './lib/capability-router.mjs';
6
- import {auditFunction,auditMethods,subscribeContextApiLog,
7
- configureApiLogCorrelation} from './lib/api-log.mjs';
8
- import {currentApiTrace,withApiTraceParent} from './lib/api-aspect.mjs';
9
- configureApiLogCorrelation({current:currentApiTrace,withParent:withApiTraceParent});
6
+ import {auditFunction,auditMethods,subscribeContextApiLog} from './lib/api-log.mjs';
10
7
  export {subscribeContextApiLog};
11
8
  import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,methodById,methodDefinitions,
12
9
  contextGatewayTools,validateContextCall,parseContextAllowedProjects,
package/lib/api-log.mjs CHANGED
@@ -1,161 +1,86 @@
1
- // Context public AOP boundary. No domain implementation imports this module.
2
- // Proxy preserves call arguments, this, sync/async return and thrown errors.
3
- import {randomUUID} from 'node:crypto';
4
- // The npm root injects the generated observation context port. Private
5
- // modules never import another private module, even for optional telemetry.
6
- let currentApiTrace=()=>null,withApiTraceParent=(_parent,execute)=>execute();
7
- export function configureApiLogCorrelation({current,withParent}){
8
- if(typeof current!=='function'||typeof withParent!=='function')
9
- throw TypeError('API_LOG_CORRELATION_PORT_INVALID');
10
- currentApiTrace=current;
11
- withApiTraceParent=withParent;
12
- }
1
+ // Context-specific evidence adapter for the one canonical API AOP runtime.
2
+ // Public functions, promise/throw semantics, correlation and queue handling
3
+ // belong to the public @tomflow/chatloop-trace API, not a copied runtime.
4
+ import {createApiAspect} from '@tomflow/chatloop-trace';
13
5
 
14
6
  export const API_LOG_CONTRACT='chat-loop.context-api-log.v1';
15
7
  const API=/^[a-z][A-Za-z0-9._-]{1,89}$/;
16
- const PROJECT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
17
- const TASK=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
8
+ const REF=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
18
9
  const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
19
- const listeners=new Set();
20
- // Registration begins before its own subscriber exists. Keep only this
21
- // single, sanitized, synchronous bootstrap span for that new subscriber.
22
- let recentSubscribeBegin=null;
23
- const safeName=name=>typeof name==='string'&&API.test(name)?name:'api.invalid';
24
- const safeProject=value=>typeof value==='string'&&PROJECT.test(value)?value:null;
25
- const safeTask=value=>typeof value==='string'&&TASK.test(value)?value:null;
26
- const safeCode=error=>typeof error?.code==='string'&&CODE.test(error.code)
27
- ?error.code:'CONTEXT_FAILED';
10
+ const listeners=new Set(),metadata=new Map();
11
+ const safe=(value,re)=>typeof value==='string'&&re.test(value)?value:null;
12
+ const adapter=createApiAspect('@tomflow/chatloop-context',{sink:deliver});
13
+
14
+ // At the public boundary capture only safe, bounded identifiers. Never log
15
+ // method arguments, bodies, workspace paths or tool return values.
16
+ function capture(detail,ids){
17
+ // If a Promise never settles, evict its oldest soft span rather than
18
+ // permanently disabling observation of all future business calls.
19
+ // Evicted spans report a transport failure if/when delivery is attempted.
20
+ if(metadata.size>=4096)metadata.delete(metadata.keys().next().value);
21
+ metadata.set(ids.spanId,{
22
+ api:safe(detail.api,API)||'api.invalid',
23
+ surface:safe(detail.surface,API)||'sdk',
24
+ mode:safe(detail.mode,API)||'read',
25
+ projectRef:safe(detail.projectRef,REF),
26
+ taskRef:safe(detail.taskRef,REF),
27
+ targets:[...listeners]
28
+ });
29
+ }
30
+ function deliver(raw){
31
+ const meta=metadata.get(raw.callId);
32
+ if(!meta)return false;
33
+ if(raw.phase!=='BEGIN')metadata.delete(raw.callId);
34
+ const event=Object.freeze({
35
+ contract:API_LOG_CONTRACT,callId:raw.callId,traceId:raw.traceId,
36
+ spanId:raw.spanId,parentSpanId:raw.parentSpanId,
37
+ api:meta.api,surface:meta.surface,mode:meta.mode,
38
+ projectRef:meta.projectRef,taskRef:meta.taskRef,phase:raw.phase,
39
+ time:raw.time,durationMs:raw.durationMs,
40
+ errorCode:raw.phase==='FAILED'
41
+ ?safe(raw.errorCode,CODE)==='API_FAILED'?'CONTEXT_FAILED':
42
+ safe(raw.errorCode,CODE)||'CONTEXT_FAILED'
43
+ :null
44
+ });
45
+ let attempted=false,failed=false;
46
+ if(process.env.CHAT_LOOP_CONTEXT_API_LOG_STDERR==='1'){
47
+ attempted=true;
48
+ try{process.stderr.write('CHAT_LOOP_CONTEXT_API_LOG '+JSON.stringify(event)+'\n')}
49
+ catch{failed=true}
50
+ }
51
+ const pending=[];
52
+ for(const listener of meta.targets){
53
+ attempted=true;
54
+ try{
55
+ const result=listener(event);
56
+ if(result&&typeof result.then==='function')
57
+ pending.push(Promise.resolve(result).then(value=>value!==false,()=>false));
58
+ else if(result===false)failed=true;
59
+ }catch{failed=true}
60
+ }
61
+ // A different successful observer cannot conceal a failed writer.
62
+ // All registered sinks must acknowledge; none may affect the API result.
63
+ return pending.length?Promise.all(pending).then(values=>
64
+ attempted&&!failed&&values.every(Boolean)):attempted&&!failed;
65
+ }
66
+
67
+ // Context's public SDK retains the established descriptor contracts, but
68
+ // uses the shared AOP for every intercepted callable and its child spans.
69
+ export const auditFunction=(target,describe)=>adapter.described(target,describe,capture);
70
+ export const auditMethods=(target,descriptors)=>
71
+ adapter.describedMethods(target,descriptors,capture);
28
72
 
29
- // The sole sink subscription (Tools may route to its existing Supervisor).
30
73
  function subscribe(listener){
31
74
  if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
32
75
  listeners.add(listener);
33
- // Deliver the BEGIN of this subscribe API call to its newly added
34
- // listener. Other, pre-existing listeners already received it through
35
- // the ordinary queue; the new listener must not see an orphan OK.
36
- const active=currentApiTrace();
37
- const begin=recentSubscribeBegin;
38
- if(begin&&begin.spanId===active?.spanId){
39
- recentSubscribeBegin=null;
40
- if(pendingEvents.length<MAX_AUDIT_PENDING){
41
- pendingEvents.push({safe:begin,targets:[listener],stderr:false});
42
- if(!scheduled){scheduled=true;setImmediate(drainAudit)}
43
- }
44
- }
76
+ // Own subscription begins before registration; attach this subscriber to
77
+ // exactly its own span without inventing a second bootstrap event.
78
+ const spanId=adapter.current()?.spanId;
79
+ const current=spanId?metadata.get(spanId):null;
80
+ if(current&&current.api==='sdk.subscribe_log'&&!current.targets.includes(listener))
81
+ current.targets.push(listener);
45
82
  return auditFunction(()=>listeners.delete(listener),
46
83
  ()=>({api:'sdk.unsubscribe_log',mode:'internal'}));
47
84
  }
48
85
  export const subscribeContextApiLog=auditFunction(subscribe,
49
86
  ()=>({api:'sdk.subscribe_log',mode:'internal'}));
50
-
51
- // Audit is a bounded asynchronous side channel, not part of the API's
52
- // execution stack. Observers never run while the business call is executing;
53
- // a slow observer cannot postpone an already available API result. Saturation
54
- // drops telemetry, never business calls or authoritative receipts.
55
- const MAX_AUDIT_PENDING=4096;
56
- const AUDIT_BATCH_SIZE=128;
57
- const pendingEvents=[];
58
- let scheduled=false;
59
- function drainAudit(){
60
- scheduled=false;
61
- for(let i=0;i<AUDIT_BATCH_SIZE&&pendingEvents.length;i++){
62
- const {safe,targets,stderr}=pendingEvents.shift();
63
- if(stderr){
64
- try{process.stderr.write('CHAT_LOOP_CONTEXT_API_LOG '+JSON.stringify(safe)+'\n')}
65
- catch{/* stderr is not an authority. */}
66
- }
67
- for(const listener of targets){
68
- try{
69
- const pending=listener(safe);
70
- if(pending&&typeof pending.then==='function')
71
- Promise.resolve(pending).catch(()=>{});
72
- }catch{/* A broken observation sink cannot alter business semantics. */}
73
- }
74
- }
75
- if(pendingEvents.length){scheduled=true;setImmediate(drainAudit)}
76
- }
77
- function emit(event){
78
- if(pendingEvents.length>=MAX_AUDIT_PENDING)return;
79
- const safe=Object.freeze(event);
80
- if(safe.api==='sdk.subscribe_log'&&safe.phase==='BEGIN')
81
- recentSubscribeBegin=safe;
82
- const stderr=process.env.CHAT_LOOP_CONTEXT_API_LOG_STDERR==='1';
83
- const targets=[...listeners];
84
- if(!stderr&&!targets.length)return;
85
- pendingEvents.push({safe,targets,stderr});
86
- if(!scheduled){scheduled=true;setImmediate(drainAudit)}
87
- }
88
-
89
- function observe({api,mode='read',surface='sdk',projectRef=null,taskRef=null},execute){
90
- const callId=randomUUID(),started=performance.now(),parent=currentApiTrace();
91
- const base={contract:API_LOG_CONTRACT,callId,
92
- traceId:parent?.traceId||callId,spanId:callId,parentSpanId:parent?.spanId||null,
93
- api:safeName(api),
94
- surface,mode,projectRef:safeProject(projectRef),taskRef:safeTask(taskRef)};
95
- const record=(phase,error)=>emit({
96
- ...base,phase,time:new Date().toISOString(),
97
- durationMs:phase==='BEGIN'?null:Math.max(0,Math.round(performance.now()-started)),
98
- errorCode:phase==='FAILED'?safeCode(error):null
99
- });
100
- record('BEGIN');
101
- try{
102
- const value=withApiTraceParent({traceId:base.traceId,spanId:callId},execute);
103
- // Unknown thenables must not be invoked twice by the audit observer.
104
- // A real Promise can be observed without changing its identity.
105
- let nativePromise=false;
106
- try{nativePromise=value instanceof Promise}catch{/* observer-only test */}
107
- if(nativePromise){
108
- // Preserve the original Promise/thenable identity and rejection.
109
- try{Promise.resolve(value).then(
110
- ()=>record('OK'),error=>record('FAILED',error)
111
- ).catch(()=>{});}catch{/* logging must never replace the result */}
112
- return value;
113
- }
114
- record('OK');return value;
115
- }catch(error){
116
- record('FAILED',error);
117
- throw error;
118
- }
119
- }
120
-
121
- // One reusable interception implementation, not per-operation logging code.
122
- // describe(args) is private metadata extraction, never receives control of
123
- // the original argument array or function execution.
124
- export function auditFunction(target,describe){
125
- if(typeof target!=='function')throw TypeError('API_TARGET_REQUIRED');
126
- return new Proxy(target,{
127
- get(fn,key,receiver){
128
- if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
129
- return Reflect.get(fn,key,receiver);
130
- },
131
- apply(fn,thisArg,args){
132
- let detail;
133
- try{detail=describe(args)??{}}catch{detail={api:'api.invalid',mode:'unknown'}}
134
- return observe(detail,()=>Reflect.apply(fn,thisArg,args));
135
- }});
136
- }
137
-
138
- // Lazily proxy selected callable properties, without changing object keys,
139
- // descriptors, non-function fields or the implementation's own method body.
140
- export function auditMethods(target,descriptors){
141
- // JS Proxy cannot override a frozen target's non-configurable data method.
142
- // Proxy a private shallow facade, with the same keys and immutable behavior.
143
- // Capability addition must not silently bypass its observation metadata.
144
- for(const [key,descriptor] of Object.entries(
145
- Object.getOwnPropertyDescriptors(target)))
146
- if(typeof descriptor.value==='function'&&!Object.hasOwn(descriptors,key))
147
- throw TypeError('API_AUDIT_DESCRIPTOR_MISSING:'+key);
148
- const facade={...target},cached=new Map();
149
- return new Proxy(facade,{
150
- set(){return false},
151
- defineProperty(){return false},
152
- deleteProperty(){return false},
153
- get(object,key,receiver){
154
- const value=Reflect.get(object,key,receiver);
155
- if(typeof value!=='function'||!Object.hasOwn(descriptors,key))return value;
156
- if(!cached.has(key))
157
- cached.set(key,auditFunction(value,descriptors[key]));
158
- return cached.get(key);
159
- }
160
- });
161
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-context",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
5
  "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
6
  "publishConfig": {
@@ -34,6 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "ps-list": "9.0.0",
37
- "@tomflow/chatloop-extension": "0.4.0"
37
+ "@tomflow/chatloop-extension": "0.4.2",
38
+ "@tomflow/chatloop-trace": "0.4.2"
38
39
  }
39
40
  }
@@ -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
- }