@tomflow/chatloop-tools 0.9.4 → 0.9.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 +12 -0
- package/index.mjs +22 -5
- package/lib/context-gateway.mjs +35 -17
- package/lib/extension-proxy.mjs +42 -22
- package/package.json +3 -3
- package/lib/api-aspect.mjs +0 -190
package/bin/cli.mjs
CHANGED
|
@@ -196,3 +196,15 @@ else if(command==='doctor'){
|
|
|
196
196
|
}else{emit({contract:'chat-loop.local-tools.v1',command,status:'FAILED',code:'UNKNOWN_COMMAND'});process.exitCode=1;}
|
|
197
197
|
});
|
|
198
198
|
}
|
|
199
|
+
// The public result was already emitted. Allow bounded soft telemetry delivery
|
|
200
|
+
// before a short-lived CLI exits, without changing the business exit status.
|
|
201
|
+
if(helpSection!==null||process.argv[2]!=='mcp'){
|
|
202
|
+
try{
|
|
203
|
+
const flushed=await cliApi[Symbol.for('chat-loop.telemetry.drain.internal')]?.(300);
|
|
204
|
+
if(flushed===false&&process.env.CHAT_LOOP_API_LOG_STDERR!=='0')
|
|
205
|
+
process.stderr.write('CHAT_LOOP_AUDIT_UNVERIFIED:pending_or_dropped\n');
|
|
206
|
+
}catch{
|
|
207
|
+
if(process.env.CHAT_LOOP_API_LOG_STDERR!=='0')
|
|
208
|
+
process.stderr.write('CHAT_LOOP_AUDIT_UNVERIFIED:drain_failed\n');
|
|
209
|
+
}
|
|
210
|
+
}
|
package/index.mjs
CHANGED
|
@@ -2,17 +2,16 @@
|
|
|
2
2
|
// Modules declare named API ports. No lib module imports another lib module.
|
|
3
3
|
import {randomUUID} from 'node:crypto';
|
|
4
4
|
import {subscribeContextApiLog} from '@tomflow/chatloop-context';
|
|
5
|
-
import {subscribeTraceApiLog} from '@tomflow/chatloop-trace';
|
|
5
|
+
import {createApiAspect,subscribeTraceApiLog} from '@tomflow/chatloop-trace';
|
|
6
6
|
import {providerDefinitions} from './providers.generated.mjs';
|
|
7
7
|
import {createMcpToolRouter} from './lib/mcp-tool-router.mjs';
|
|
8
8
|
import {createCliCommandRouter} from './lib/cli-command-router.mjs';
|
|
9
|
-
import {createApiAspect} from './lib/api-aspect.mjs';
|
|
10
9
|
// One bounded SDK/CLI/MCP side channel; the Supervisor is the only writer.
|
|
11
10
|
// Cold-start observations are held until the port is composed, never on an
|
|
12
11
|
// API's business execution stack.
|
|
13
12
|
let auditPort=null;
|
|
14
13
|
const auditBacklog=[];
|
|
15
|
-
let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0;
|
|
14
|
+
let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
|
|
16
15
|
const MAX_AUDIT_BACKLOG=1024,MAX_NO_OWNER_RETRIES=20;
|
|
17
16
|
// The CLI can emit BEGIN before a cold Supervisor has opened its IPC socket.
|
|
18
17
|
// Keep ordered, bounded soft observations until that exact socket exists;
|
|
@@ -30,6 +29,7 @@ async function drainAudit(){
|
|
|
30
29
|
if(['ENOENT','ECONNREFUSED'].includes(error?.code)&&
|
|
31
30
|
auditNoOwnerRetries++<MAX_NO_OWNER_RETRIES)break;
|
|
32
31
|
auditBacklog.shift(); // unknown telemetry is dropped, not retried
|
|
32
|
+
auditLost++;
|
|
33
33
|
auditNoOwnerRetries=0;
|
|
34
34
|
}
|
|
35
35
|
}
|
|
@@ -45,7 +45,7 @@ async function drainAudit(){
|
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
const recordApi=event=>{
|
|
48
|
-
if(auditBacklog.length>=MAX_AUDIT_BACKLOG)return;
|
|
48
|
+
if(auditBacklog.length>=MAX_AUDIT_BACKLOG){auditLost++;return;}
|
|
49
49
|
auditBacklog.push(event);
|
|
50
50
|
if(auditPort){
|
|
51
51
|
if(auditRetryTimer){clearTimeout(auditRetryTimer);auditRetryTimer=null;}
|
|
@@ -53,6 +53,18 @@ const recordApi=event=>{
|
|
|
53
53
|
}
|
|
54
54
|
};
|
|
55
55
|
const apiAspect=createApiAspect('@tomflow/chatloop-tools',{sink:recordApi});
|
|
56
|
+
// A short-lived CLI may finish producing its reply before its soft audit queue
|
|
57
|
+
// is delivered. Drain only *after* that reply; never delay an API or replay it.
|
|
58
|
+
async function drainCliTelemetry(timeoutMs=300){
|
|
59
|
+
const deadline=Date.now()+Math.max(0,Math.min(timeoutMs,750));
|
|
60
|
+
const aspectFlushed=await apiAspect.drain(Math.max(0,deadline-Date.now()));
|
|
61
|
+
while(auditBacklog.length||auditDraining){
|
|
62
|
+
if(Date.now()>=deadline)return false;
|
|
63
|
+
await new Promise(resolve=>setTimeout(resolve,Math.min(10,deadline-Date.now())));
|
|
64
|
+
}
|
|
65
|
+
return aspectFlushed&&auditLost===0;
|
|
66
|
+
}
|
|
67
|
+
const INTERNAL_DRAIN=Symbol.for('chat-loop.telemetry.drain.internal');
|
|
56
68
|
// The CLI and Supervisor executable import only this package root.
|
|
57
69
|
let runtimePromise;
|
|
58
70
|
async function runtime(){
|
|
@@ -181,7 +193,11 @@ async function runtime(){
|
|
|
181
193
|
phase:event.phase,
|
|
182
194
|
...(event.durationMs!==null?{durationMs:event.durationMs}:{}),
|
|
183
195
|
...(event.errorCode?{errorCode:event.errorCode}:{})
|
|
184
|
-
},900)
|
|
196
|
+
},900).then(reply=>{
|
|
197
|
+
if(reply?.status!=='OK')throw Object.assign(Error('TRACE_RECORD_FAILED'),
|
|
198
|
+
{code:'TRACE_RECORD_FAILED'});
|
|
199
|
+
return reply;
|
|
200
|
+
});
|
|
185
201
|
void drainAudit();
|
|
186
202
|
const mcpAudit=createApiAspect('@tomflow/chatloop-tools',
|
|
187
203
|
{sink:recordApi});
|
|
@@ -230,6 +246,7 @@ async function runtime(){
|
|
|
230
246
|
async function loadToolsCliCore(){
|
|
231
247
|
const {control,tunnel,tunnelAuth,release,gateway}=await runtime();
|
|
232
248
|
return apiAspect.methods(Object.freeze({
|
|
249
|
+
[INTERNAL_DRAIN]:drainCliTelemetry,
|
|
233
250
|
cliExtensions:apiAspect.methods(createCliCommandRouter(providerDefinitions),
|
|
234
251
|
'cliExtensions','cli'),
|
|
235
252
|
lifecycleDeadlineMs:control.lifecycleDeadlineMs,
|
package/lib/context-gateway.mjs
CHANGED
|
@@ -40,24 +40,25 @@ export async function forwardContextApiLog(event,request={}){
|
|
|
40
40
|
||(event.phase==='BEGIN'?event.durationMs!==null
|
|
41
41
|
:!Number.isSafeInteger(event.durationMs)||event.durationMs<0)
|
|
42
42
|
||(event.phase==='FAILED'?!CODE.test(event.errorCode||'')
|
|
43
|
-
:event.errorCode!==null))return;
|
|
43
|
+
:event.errorCode!==null))return false;
|
|
44
44
|
// Do not call the instrumented validator from an audit callback: that
|
|
45
45
|
// would recursively audit the audit. A single exact Context Project grant
|
|
46
46
|
// is required; public Trace MCP authorization remains independent.
|
|
47
47
|
const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
|
|
48
48
|
if(typeof contextGrant!=='string'
|
|
49
|
-
||!(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).test(contextGrant))return;
|
|
49
|
+
||!(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).test(contextGrant))return false;
|
|
50
50
|
const projectRef=event.projectRef??contextGrant;
|
|
51
51
|
if(event.taskRef!==null&&event.taskRef!==undefined
|
|
52
52
|
&&(!(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).test(event.taskRef)
|
|
53
|
-
||request?.taskId!==undefined&&request.taskId!==event.taskRef))return;
|
|
53
|
+
||request?.taskId!==undefined&&request.taskId!==event.taskRef))return false;
|
|
54
54
|
if(projectRef!==contextGrant
|
|
55
|
-
||(request?.projectId!==undefined&&request.projectId!==projectRef))return;
|
|
55
|
+
||(request?.projectId!==undefined&&request.projectId!==projectRef))return false;
|
|
56
56
|
// The event name stays fixed. API name, surface and mode are typed fields,
|
|
57
57
|
// not concatenated strings or borrowed action/receipt identifiers.
|
|
58
58
|
try{
|
|
59
|
-
|
|
60
|
-
|
|
59
|
+
const requestId=randomUUID();
|
|
60
|
+
const receipt=await recordContextApiLog({
|
|
61
|
+
requestId,traceId:event.traceId||event.callId,
|
|
61
62
|
spanId:event.spanId||event.callId,
|
|
62
63
|
...(event.parentSpanId?{parentSpanId:event.parentSpanId}:{}),
|
|
63
64
|
projectRef,
|
|
@@ -68,16 +69,20 @@ export async function forwardContextApiLog(event,request={}){
|
|
|
68
69
|
...(event.phase==='FAILED'?{errorCode:event.errorCode}:{}),
|
|
69
70
|
...(event.durationMs!==null?{durationMs:event.durationMs}:{})
|
|
70
71
|
});
|
|
71
|
-
|
|
72
|
+
// IPC completed does not imply the Trace Writer accepted the event.
|
|
73
|
+
return receipt?.status==='OK'&&receipt.requestId===requestId
|
|
74
|
+
&&UUID.test(receipt.eventId||'');
|
|
75
|
+
}catch{return false; /* Never affect a Context business result. */}
|
|
72
76
|
}
|
|
73
77
|
function parseContextLog(stderr){
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
// Do not silently treat malformed or absent records as a complete audit.
|
|
79
|
+
const records=[];let malformed=0;
|
|
80
|
+
for(const line of stderr.split('\n').filter(x=>x.startsWith(PREFIX))){
|
|
81
|
+
if(line.length>640){malformed++;continue}
|
|
82
|
+
try{records.push(JSON.parse(line.slice(PREFIX.length)))}
|
|
83
|
+
catch{malformed++}
|
|
84
|
+
}
|
|
85
|
+
return {records,malformed};
|
|
81
86
|
}
|
|
82
87
|
|
|
83
88
|
const supportedContextNode=()=>{
|
|
@@ -129,7 +134,7 @@ export async function runContextGateway(name,args){
|
|
|
129
134
|
env.PATH=dirname(env.CHAT_LOOP_CONTEXT_NODE_BIN)+delimiter+(env.PATH||'');
|
|
130
135
|
}
|
|
131
136
|
// Never forward MCP arguments into env, executable, package spec or a shell.
|
|
132
|
-
let auditText='';
|
|
137
|
+
let auditText='',auditTruncated=false;
|
|
133
138
|
try{return await new Promise((resolve,reject)=>{
|
|
134
139
|
const p=spawn(bin,argv,{env,stdio:['pipe','pipe','pipe'],shell:false,windowsHide:true});
|
|
135
140
|
let stdout='',stdoutBytes=0,settled=false,started=false;
|
|
@@ -159,6 +164,7 @@ export async function runContextGateway(name,args){
|
|
|
159
164
|
// Diagnostic stderr is deliberately lossy; never kill an already
|
|
160
165
|
// authorized Context operation merely because telemetry is verbose.
|
|
161
166
|
const remaining=32768-Buffer.byteLength(auditText,'utf8');
|
|
167
|
+
if(Buffer.byteLength(chunk,'utf8')>remaining)auditTruncated=true;
|
|
162
168
|
if(remaining>0)
|
|
163
169
|
auditText+=Buffer.from(chunk,'utf8').subarray(0,remaining).toString('utf8');
|
|
164
170
|
});
|
|
@@ -184,7 +190,19 @@ export async function runContextGateway(name,args){
|
|
|
184
190
|
// The Gateway returns the actual Context result without awaiting the
|
|
185
191
|
// Supervisor telemetry socket. Best-effort delivery is explicitly NOT
|
|
186
192
|
// a business receipt, and never causes a side-effect retry.
|
|
187
|
-
|
|
188
|
-
|
|
193
|
+
const audit=parseContextLog(auditText);
|
|
194
|
+
void Promise.allSettled(audit.records
|
|
195
|
+
.map(event=>forwardContextApiLog(event,args))).then(outcomes=>{
|
|
196
|
+
const failed=outcomes.filter(item=>item.status!=='fulfilled'
|
|
197
|
+
||item.value!==true).length;
|
|
198
|
+
const missing=audit.records.length===0;
|
|
199
|
+
if(!auditTruncated&&!missing&&!audit.malformed&&failed===0)return;
|
|
200
|
+
// Diagnostic fallback, not a fabricated Trace record or a new writer.
|
|
201
|
+
// Never expose request bodies or repeat an UNKNOWN Context mutation.
|
|
202
|
+
try{process.stderr.write('CHAT_LOOP_AUDIT_GAP '+
|
|
203
|
+
JSON.stringify({component:'context',failed,missing,
|
|
204
|
+
malformed:audit.malformed,truncated:auditTruncated})+'\n')}
|
|
205
|
+
catch{/* Telemetry must not affect the settled Context result. */}
|
|
206
|
+
}).catch(()=>{});
|
|
189
207
|
}
|
|
190
208
|
}
|
package/lib/extension-proxy.mjs
CHANGED
|
@@ -22,8 +22,8 @@ export function configureExtensionProxy(ports){
|
|
|
22
22
|
// The package/version are exact and checked against the same Context
|
|
23
23
|
// dependency deployed with the Tools release.
|
|
24
24
|
export {extensionTools};
|
|
25
|
-
const EXTENSION_PACKAGE='@tomflow/chatloop-extension@0.4.
|
|
26
|
-
const EXTENSION_VERSION='0.4.
|
|
25
|
+
const EXTENSION_PACKAGE='@tomflow/chatloop-extension@0.4.2';
|
|
26
|
+
const EXTENSION_VERSION='0.4.2';
|
|
27
27
|
const NPX_COMMAND=process.platform==='win32'?'npx.cmd':'npx';
|
|
28
28
|
export const extensionInvocation=name=>{
|
|
29
29
|
const command=extensionCommand(name);
|
|
@@ -41,37 +41,57 @@ export async function forwardExtensionAction(name,args={}) {
|
|
|
41
41
|
const response=await new Promise(resolve=>{
|
|
42
42
|
const child=spawn(invocation.executable,invocation.args,{stdio:[control?'pipe':'ignore','pipe','pipe'],
|
|
43
43
|
cwd:tmpdir(),windowsHide:true,env:process.env});
|
|
44
|
-
let stdout='',stdoutBytes=0,finished=false;
|
|
45
|
-
const settle=
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
44
|
+
let stdout='',stdoutBytes=0,finished=false,closed=false,tailTimer=null;
|
|
45
|
+
const settle=(value,receiptCompleted=false)=>{
|
|
46
|
+
if(finished)return;
|
|
47
|
+
finished=true;clearTimeout(timer);resolve(value);
|
|
48
|
+
if(receiptCompleted&&!closed){
|
|
49
|
+
// A verified RESULT ends the business operation. Only the owned
|
|
50
|
+
// child's audit tail is eligible for bounded cleanup.
|
|
51
|
+
tailTimer=setTimeout(()=>child.kill('SIGTERM'),2500);
|
|
52
|
+
tailTimer.unref?.();
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const timer=setTimeout(()=>{child.kill('SIGTERM');settle(fail('RESULT_TIMEOUT'));},
|
|
56
|
+
name==='start'?330000:90000);
|
|
57
|
+
const command=name==='clean'?'extension clean '+args.tabId:extensionCommand(name).join(' ');
|
|
58
|
+
const consume=line=>{
|
|
59
|
+
let msg;try{msg=JSON.parse(line)}catch{return false}
|
|
60
|
+
if(msg?.event!=='RESULT')return false;
|
|
61
|
+
// The CLI emits RESULT only after its business outcome is known.
|
|
62
|
+
// Subsequent exit/drain belongs to soft telemetry, not the receipt.
|
|
63
|
+
const result=acceptExtensionCliReceipt(msg,command,msg.ok===true?0:1);
|
|
64
|
+
if(result.ok&&result.providerVersion!==invocation.providerVersion)
|
|
65
|
+
settle(fail('EXTENSION_PROVIDER_VERSION_MISMATCH'),true);
|
|
66
|
+
else settle(result.ok?result.value:fail(result.code),true);
|
|
67
|
+
return true;
|
|
68
|
+
};
|
|
69
|
+
// Decode UTF-8 incrementally, and accept the completed RESULT frame
|
|
70
|
+
// without holding the MCP tool response for the CLI's audit tail.
|
|
49
71
|
child.stdout.setEncoding('utf8');
|
|
50
72
|
if(control){
|
|
51
|
-
// A CLI which closes stdin early must not crash the Gateway with an
|
|
52
|
-
// unhandled EPIPE; only the final CLI receipt establishes the outcome.
|
|
53
73
|
child.stdin.on('error',()=>{});
|
|
54
74
|
child.stdin.end(JSON.stringify(args));
|
|
55
75
|
}
|
|
56
|
-
child.stdout.on('data',
|
|
57
|
-
|
|
76
|
+
child.stdout.on('data',chunk=>{
|
|
77
|
+
if(finished)return;
|
|
78
|
+
stdoutBytes+=Buffer.byteLength(chunk,'utf8');
|
|
58
79
|
if(stdoutBytes>9*1024*1024){
|
|
59
80
|
child.kill('SIGTERM');settle(fail('RESULT_TOO_LARGE'));return;
|
|
60
81
|
}
|
|
61
|
-
stdout+=
|
|
82
|
+
stdout+=chunk;
|
|
83
|
+
for(let n;(n=stdout.indexOf('\n'))>=0;){
|
|
84
|
+
const line=stdout.slice(0,n);stdout=stdout.slice(n+1);
|
|
85
|
+
if(consume(line))return;
|
|
86
|
+
}
|
|
62
87
|
});
|
|
63
|
-
child.stderr.on('data',()=>{}); //
|
|
88
|
+
child.stderr.on('data',()=>{}); // Never expose private Chrome diagnostics.
|
|
64
89
|
child.on('error',()=>settle(fail('EXTENSION_CLI_UNAVAILABLE')));
|
|
65
|
-
// 'exit' can precede the last stdout chunk; 'close' waits until the
|
|
66
|
-
// CLI and any inherited stdio handles have closed before parsing proof.
|
|
67
90
|
child.on('close',code=>{
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
if(result.ok&&result.providerVersion!==invocation.providerVersion)
|
|
73
|
-
return settle(fail('EXTENSION_PROVIDER_VERSION_MISMATCH'));
|
|
74
|
-
settle(result.ok?result.value:fail(result.code));
|
|
91
|
+
closed=true;
|
|
92
|
+
if(tailTimer)clearTimeout(tailTimer);
|
|
93
|
+
if(finished)return;
|
|
94
|
+
if(!consume(stdout.trim()))settle(fail('INVALID_EXTENSION_REPLY'));
|
|
75
95
|
});
|
|
76
96
|
});
|
|
77
97
|
return formatExtensionResult(name,response);
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.9.
|
|
6
|
+
"version": "0.9.6",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
|
|
9
9
|
"bin": {
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
31
|
"@wonderwhy-er/desktop-commander": "0.2.44",
|
|
32
|
-
"@tomflow/chatloop-context": "0.6.
|
|
33
|
-
"@tomflow/chatloop-trace": "0.4.
|
|
32
|
+
"@tomflow/chatloop-context": "0.6.2",
|
|
33
|
+
"@tomflow/chatloop-trace": "0.4.2"
|
|
34
34
|
},
|
|
35
35
|
"engines": {
|
|
36
36
|
"node": ">=24"
|
package/lib/api-aspect.mjs
DELETED
|
@@ -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
|
-
}
|