@tomflow/chatloop-tools 0.4.33 → 0.9.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 (50) hide show
  1. package/README.md +117 -127
  2. package/bin/cli.mjs +48 -38
  3. package/bin/supervisor.mjs +4 -0
  4. package/index.mjs +238 -0
  5. package/lib/adapters/fixture.mjs +3 -2
  6. package/lib/adapters/index.mjs +14 -5
  7. package/lib/adapters/mcp-child.mjs +29 -7
  8. package/lib/adapters/tunnel.mjs +25 -7
  9. package/lib/api-aspect.mjs +190 -0
  10. package/lib/cli-command-router.mjs +34 -0
  11. package/lib/context-control-auth.mjs +12 -1
  12. package/lib/context-control-run.mjs +17 -79
  13. package/lib/context-gateway.mjs +108 -15
  14. package/lib/control.mjs +3 -2
  15. package/lib/extension-cli-contract.mjs +22 -0
  16. package/lib/extension-proxy.mjs +48 -19
  17. package/lib/gateway.mjs +46 -176
  18. package/lib/mcp-tool-router.mjs +60 -0
  19. package/lib/release-owner-preflight.mjs +41 -0
  20. package/lib/release.mjs +94 -49
  21. package/lib/{supervisor.mjs → supervisor-runtime.mjs} +143 -80
  22. package/lib/trace-gateway.mjs +12 -1
  23. package/lib/trace-observation.mjs +118 -0
  24. package/lib/tunnel.mjs +17 -29
  25. package/package.json +20 -14
  26. package/providers/context.mjs +20 -0
  27. package/providers/desktop.mjs +80 -0
  28. package/{lib/extension-contract.mjs → providers/extension.mjs} +36 -0
  29. package/providers/runtime.mjs +32 -0
  30. package/providers/trace.mjs +25 -0
  31. package/providers.generated.mjs +8 -0
  32. package/scripts/build-providers.mjs +69 -0
  33. package/lib/context-cli.mjs +0 -2
  34. package/lib/context-migration.mjs +0 -2
  35. package/lib/context-protocol.mjs +0 -2
  36. package/lib/task-registry-managed.mjs +0 -38
  37. package/lib/task-registry.mjs +0 -221
  38. package/node_modules/@tomflow/chatloop-context/README.md +0 -271
  39. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -273
  40. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -301
  41. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -272
  42. package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +0 -1615
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -264
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -219
  45. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -455
  46. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -159
  47. package/node_modules/@tomflow/chatloop-context/package.json +0 -21
  48. package/node_modules/@tomflow/chatloop-trace/README.md +0 -13
  49. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -259
  50. package/node_modules/@tomflow/chatloop-trace/package.json +0 -11
@@ -1,86 +1,140 @@
1
1
  import {randomUUID} from 'node:crypto';
2
- import {createTraceWriter} from '@tomflow/chatloop-trace';
2
+ import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
3
3
  import {closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, chmodSync} from 'node:fs';
4
4
  import {createServer} from 'node:net';
5
- import {CONTRACT,VERSION,PACKAGE_VERSION,registry,paths,ensurePrivateDir,ACTIONS} from './control.mjs';
6
- import {createAdapter} from './adapters/index.mjs';
7
- import {loadContextControlSecret} from './context-control-auth.mjs';
8
- import {handleContextControl} from './context-control-run.mjs';
5
+ // All internal dependencies are supplied as API contracts by index.mjs.
6
+ // Private modules never import or resolve another private implementation.
7
+ let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl;
8
+ let connected=false;
9
+ export function configureSupervisor(ports){
10
+ if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
11
+ for(const name of ['CONTRACT', 'VERSION', 'PACKAGE_VERSION', 'registry', 'paths', 'ensurePrivateDir', 'ACTIONS', 'createAdapter', 'createSupervisorTraceBridge', 'loadContextControlSecret', 'handleContextControl'])
12
+ if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
13
+ ({CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl}=ports);
14
+ connected=true;
15
+ }
16
+
9
17
 
18
+ export function runSupervisor(){
10
19
  const catalog=registry(), records=new Map(), queues=new Map(), seen=new Map(), receipts=new Map();
20
+ // Completed result payloads are bounded; issued IDs are NOT reusable after
21
+ // eviction. Tombstones are kept for this Supervisor lifetime and overflow
22
+ // fails closed rather than re-dispatching a previously executed request.
23
+ const issuedIds=new Set();
24
+ const MAX_ISSUED_IDS=100000;
25
+ const MAX_REPLAY_RESULTS=128;
26
+ function priorRequest(req,payload){
27
+ const old=seen.get(req.requestId);
28
+ if(old)return old.payload===payload?old.promise:bad(req,'REQUEST_ID_REUSE');
29
+ if(issuedIds.has(req.requestId))return bad(req,'REQUEST_ID_EVICTED');
30
+ if(issuedIds.size>=MAX_ISSUED_IDS)return bad(req,'IDEMPOTENCY_CAPACITY');
31
+ return null;
32
+ }
33
+ function rememberRequest(id,payload,promise){
34
+ issuedIds.add(id);
35
+ seen.set(id,{payload,promise});
36
+ if(seen.size>MAX_REPLAY_RESULTS)seen.delete(seen.keys().next().value);
37
+ }
11
38
  const p=paths(), nonce=randomUUID();
12
39
  const traceWriter=createTraceWriter({
13
40
  filePath:p.log,enableRotation:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1'
14
41
  });
42
+ // One exact Context grant may contribute only sanitized method counts to
43
+ // the local usage view. Never widen authorization with a multi-project string.
44
+ const contextUsageGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
45
+ const usageScopes=['api_system',...(
46
+ typeof contextUsageGrant==='string'&&
47
+ /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
48
+ ?[contextUsageGrant]:[])];
49
+ const usageReader=createTraceReader({
50
+ filePath:p.log,allowedProjects:usageScopes
51
+ });
52
+ const OBSERVER_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
53
+ // Namespaced, sanitized public entrypoints: MCP, SDK, CLI, Native and Browser.
54
+ // Never accept raw UI text, arguments, URLs or other caller payloads.
55
+ const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
56
+ const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
57
+ 'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode']);
58
+ function recordApiObservation(req){
59
+ if(req?.contract!==CONTRACT||!OBSERVER_ID.test(req.requestId||'')||
60
+ !OBSERVER_ID.test(req.callId||'')||
61
+ (req.traceId!==undefined&&!OBSERVER_ID.test(req.traceId))||
62
+ (req.spanId!==undefined&&!OBSERVER_ID.test(req.spanId))||
63
+ (req.parentSpanId!==undefined&&!OBSERVER_ID.test(req.parentSpanId))||
64
+ (req.spanId!==undefined&&req.spanId!==req.callId)||
65
+ !OBSERVER_NAME.test(req.apiName||'')||
66
+ !['BEGIN','OK','FAILED'].includes(req.phase)||
67
+ Object.keys(req).some(k=>!OBSERVER_KEYS.has(k))||
68
+ (req.phase==='BEGIN'
69
+ ?req.durationMs!==undefined||req.errorCode!==undefined
70
+ :!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
71
+ (req.phase==='FAILED'
72
+ ?req.errorCode!=='MCP_TOOL_ERROR'&&
73
+ !/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode||'')
74
+ :req.errorCode!==undefined)))
75
+ throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
76
+ const written=traceWriter.record({
77
+ event:'typed.api.call',component:'gateway',projectRef:'api_system',
78
+ traceId:req.traceId||req.callId,spanId:req.callId,
79
+ ...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
80
+ apiName:req.apiName,
81
+ status:req.phase==='BEGIN'?'BEGIN':req.phase==='OK'?'CONFIRMED':'FAILED',
82
+ ...(req.phase!=='BEGIN'?{durationMs:req.durationMs}:{}),
83
+ ...(req.phase==='FAILED'?{errorCode:req.errorCode}:{})
84
+ });
85
+ return {contract:CONTRACT,requestId:req.requestId,status:'OK',
86
+ eventId:written.eventId};
87
+ }
88
+ async function apiUsage(req){
89
+ if(req?.contract!==CONTRACT||
90
+ Object.keys(req).some(k=>!['contract','action','requestId',
91
+ 'windowMinutes','limit'].includes(k))||
92
+ !OBSERVER_ID.test(req.requestId||''))
93
+ throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
94
+ const summary=await usageReader.apiUsage({
95
+ windowMinutes:req.windowMinutes??60,limit:req.limit??100});
96
+ return {contract:CONTRACT,requestId:req.requestId,status:'OK',summary};
97
+ }
15
98
  const desiredTunnel=new Set(), recoveryAttempts=new Map();
16
99
  let lockFd, server, idleTimer;
100
+ // Internal process/control events never perform disk I/O on a business
101
+ // response path. This queue is bounded, asynchronous, and drops telemetry
102
+ // rather than delaying or replaying a confirmed/unknown operation.
103
+ const MAX_CONTROL_AUDIT=1024,CONTROL_AUDIT_BATCH=64,controlAudit=[];
104
+ let controlAuditScheduled=false,controlAuditDropped=0;
105
+ const flushControlAudit=()=>{
106
+ controlAuditScheduled=false;
107
+ for(let i=0;i<CONTROL_AUDIT_BATCH&&controlAudit.length;i++){
108
+ const {event,detail}=controlAudit.shift();
109
+ try{traceWriter.recordControl(event,detail);}
110
+ catch{/* Writer health carries the last error, never a business error. */}
111
+ }
112
+ if(controlAudit.length){
113
+ controlAuditScheduled=true;setImmediate(flushControlAudit);
114
+ }
115
+ };
17
116
  const log=(event,detail={})=>{
18
- try{traceWriter.recordLegacy(event,detail);}catch{
19
- // Observability is never permission to replay an unknown business action.
20
- // The failure is retained by traceWriter.health and surfaced in __ping.
117
+ if(controlAudit.length>=MAX_CONTROL_AUDIT){controlAuditDropped++;return}
118
+ // Project only the fields the existing Trace recordControl consumes.
119
+ controlAudit.push({event,detail:{
120
+ status:detail?.status,requestId:detail?.requestId,
121
+ errorCode:detail?.errorCode
122
+ }});
123
+ if(!controlAuditScheduled){
124
+ controlAuditScheduled=true;setImmediate(flushControlAudit);
21
125
  }
22
126
  };
23
- const error=(code,message=code)=>({code,message});
24
- const allowedTraceProjects=()=>{
25
- const entries=(process.env.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
26
- .split(',').map(x=>x.trim());
27
- // Apply the same single-project, fail-closed boundary to log submission.
28
- return new Set(entries.length===1 && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(entries[0])
29
- ? entries : []);
127
+ const traceHealth=()=>{
128
+ const health=traceWriter.health();
129
+ return {...health,controlAuditDropped,controlAuditPending:controlAudit.length,
130
+ ...(controlAuditDropped>0&&health.status==='OK'
131
+ ?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
30
132
  };
31
- const traceEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1';
32
- const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
33
- function handleTraceObservation(req){
34
- if(!traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
35
- throw error('TRACE_PROJECT_ACCESS_DENIED');
36
- const intent=/^extension\.(continue|handoff)\.(intent\.queued|receipt\.observed)$/.test(req?.event||'');
37
- const agent=/^agent\.(intent|project|tooling)\.soft_(observed|blocked|unverified)$/.test(req?.event||'');
38
- const agentStatus=req?.event?.endsWith('_observed')?'CONFIRMED':
39
- req?.event?.endsWith('_blocked')?'BLOCKED':'UNKNOWN';
40
- const validEvent=['extension.start.observed','extension.status.observed'].includes(req?.event)
41
- ||intent||agent;
42
- if(req?.contract!==CONTRACT||!validEvent
43
- ||!(agent?req.status===agentStatus:
44
- intent?(req.event.endsWith('.intent.queued')?req.status==='BEGIN'
45
- :['CONFIRMED','UNKNOWN'].includes(req.status))
46
- :['CONFIRMED','UNKNOWN','BLOCKED'].includes(req.status))
47
- ||typeof req.traceId!=='string'
48
- ||(agent&&(req.sessionRef!==undefined||req.taskRef!==undefined||
49
- req.generation!==undefined||req.evidenceRef!==undefined||
50
- req.actionId!==undefined||req.errorCode!==undefined||!UUID_RE.test(req.traceId)))
51
- ||(intent&&(!/^[a-f0-9]{32}$/.test(req.actionId||'')
52
- ||req.evidenceRef!==req.actionId)))throw error('TRACE_INVALID_ARGUMENT');
53
- const errorCode=typeof req.errorCode==='string'&&
54
- /^[A-Z][A-Z0-9_]{0,95}$/.test(req.errorCode)?req.errorCode:null;
55
- const written=traceWriter.record({
56
- traceId:req.traceId,sessionRef:req.sessionRef,projectRef:req.projectRef,
57
- taskRef:req.taskRef??null,generation:req.generation??null,
58
- requestId:req.requestId,component:'gateway',
59
- ...(intent?{actionId:req.actionId,evidenceRef:req.evidenceRef}
60
- :req.event==='extension.status.observed'&&typeof req.evidenceRef==='string'
61
- &&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(req.evidenceRef)
62
- ?{evidenceRef:req.evidenceRef}:{}),
63
- ...(req.status==='BLOCKED'&&errorCode?{errorCode}:{}),
64
- event:req.event,status:req.status
65
- });
66
- return {contract:CONTRACT,requestId:req.requestId,status:'OK',eventId:written.eventId};
67
- }
68
- function traceNativeReceipt(req){
69
- if(!traceEnabled())return;
70
- // This is called ONLY after handleContextControl verifies Native HMAC and
71
- // successfully executes the Context command; it is not a Browser send proof.
72
- const command=req?.payload?.command,args=req?.payload?.args;
73
- if(!command||!args||!allowedTraceProjects().has(args.projectId))return;
74
- try{
75
- traceWriter.record({traceId:args.sessionId,sessionRef:args.sessionId,
76
- projectRef:args.projectId,taskRef:args.taskId,
77
- generation:args.generation,component:'native',requestId:req.requestId,
78
- event:'native.context.'+command+'.confirmed',status:'CONFIRMED'});
79
- }catch{
80
- // Trace failure is surfaced by health(), never treated as a failed
81
- // Context mutation; its write result must not be replayed.
82
- }
83
- }
133
+ const error=(code,message=code)=>({code,message});
134
+ // One Trace owner; this module only handles native/soft event admission.
135
+ const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
136
+ traceWriter,contract:CONTRACT,error
137
+ });
84
138
 
85
139
  const after=rec=>rec ? rec.state : 'STOPPED';
86
140
  function saveReceipt(id,state,result=null,errorCode=null){
@@ -144,8 +198,8 @@ async function executeCall(req){
144
198
  if(!tool)return bad(req,'UNKNOWN_TOOL');
145
199
  if(!tool.enabled)return bad(req,'DISABLED_TOOL');
146
200
  const argsKey=JSON.stringify([req.action,req.scope,req.toolId,req.name,req.args,req.deadlineMs]);
147
- const prev=seen.get(req.requestId);
148
- if(prev)return prev.payload===argsKey?prev.promise:bad(req,'REQUEST_ID_REUSE');
201
+ const prev=priorRequest(req,argsKey);
202
+ if(prev)return prev;
149
203
  const expires=Date.now()+req.deadlineMs;
150
204
  saveReceipt(req.requestId,'RUNNING');
151
205
  const promise=serial(tool.id,async()=>{
@@ -166,8 +220,7 @@ async function executeCall(req){
166
220
  return bad(req,code);
167
221
  }
168
222
  });
169
- seen.set(req.requestId,{payload:argsKey,promise});
170
- if(seen.size>128)seen.delete(seen.keys().next().value);
223
+ rememberRequest(req.requestId,argsKey,promise);
171
224
  return promise;
172
225
  }
173
226
  async function execute(req){
@@ -179,8 +232,8 @@ async function execute(req){
179
232
  !Number.isInteger(req.deadlineMs)||req.deadlineMs<1000||req.deadlineMs>30000)return bad(req,'INVALID_ARGUMENT');
180
233
  let found;try{found=targets(req);}catch(e){return bad(req,e.code);}
181
234
  const payload=JSON.stringify([req.action,req.scope,req.toolId||null,req.deadlineMs]);
182
- const hit=seen.get(req.requestId);
183
- if(hit)return hit.payload===payload?hit.promise:bad(req,'REQUEST_ID_REUSE');
235
+ const hit=priorRequest(req,payload);
236
+ if(hit)return hit;
184
237
  // Read-only status must never cancel idle shutdown.
185
238
  if(req.action==='start'||req.action==='restart')clearTimeout(idleTimer);
186
239
  const expiresAt=Date.now()+req.deadlineMs;
@@ -227,12 +280,13 @@ async function execute(req){
227
280
  }
228
281
  return response;
229
282
  })();
230
- seen.set(req.requestId,{payload,promise});
231
- if(seen.size>128)seen.delete(seen.keys().next().value);
283
+ rememberRequest(req.requestId,payload,promise);
232
284
  return promise;
233
285
  }
234
286
  async function shutdown(){
235
287
  if([...records.values()].some(r=>!r.exited))return;
288
+ // Closeout may flush final soft evidence, but never re-authorizes an action.
289
+ while(controlAudit.length)flushControlAudit();
236
290
  server?.close();
237
291
  try{if(existsSync(p.socket))unlinkSync(p.socket);}catch{}
238
292
  try{if(existsSync(p.lock) && JSON.parse(readFileSync(p.lock,'utf8')).nonce===nonce)unlinkSync(p.lock);}catch{}
@@ -256,21 +310,28 @@ async function main(){
256
310
  }
257
311
  server=createServer(socket=>{
258
312
  let buf='', handled=false;
313
+ socket.setEncoding('utf8'); // Authorized Context actions can contain Unicode.
259
314
  socket.on('data',chunk=>{
260
315
  if(handled)return;
261
- buf+=chunk.toString();
262
- if(buf.length>1048576){socket.destroy();return;}
316
+ buf+=chunk;
317
+ if(Buffer.byteLength(buf,'utf8')>1048576){socket.destroy();return;}
263
318
  const n=buf.indexOf('\n');if(n<0)return;
264
319
  handled=true;
265
320
  let req;try{req=JSON.parse(buf.slice(0,n));}catch{socket.end(JSON.stringify(bad({},'INVALID_ARGUMENT'))+'\n');return;}
266
321
  const work=req?.action==='__ping'?
267
322
  Promise.resolve({contract:CONTRACT,version:VERSION,packageVersion:PACKAGE_VERSION,registrySignature:catalog.map(t=>t.id+':'+t.enabled).join('|'),ownerNonce:nonce,
268
- managerPid:process.pid,traceHealth:traceWriter.health()}):req?.action==='__trace_health'
323
+ managerPid:process.pid,traceHealth:traceHealth()}):req?.action==='__trace_health'
269
324
  ?Promise.resolve({contract:CONTRACT,requestId:req.requestId,
270
- status:'OK',traceHealth:traceWriter.health()})
325
+ status:'OK',traceHealth:traceHealth()})
271
326
  :req?.action==='__trace_observation'
272
327
  ?Promise.resolve().then(()=>handleTraceObservation(req))
273
328
  .catch(e=>bad(req,e.code||'TRACE_RECORD_FAILED'))
329
+ :req?.action==='__api_observation'
330
+ ?Promise.resolve().then(()=>recordApiObservation(req))
331
+ .catch(e=>bad(req,e.code||'TRACE_RECORD_FAILED'))
332
+ :req?.action==='__api_usage'
333
+ ?Promise.resolve().then(()=>apiUsage(req))
334
+ .catch(e=>bad(req,e.code||'TRACE_USAGE_FAILED'))
274
335
  :req?.action==='context-control'
275
336
  ?handleContextControl(req).then(result=>{
276
337
  traceNativeReceipt(req);
@@ -299,3 +360,5 @@ async function main(){
299
360
  });
300
361
  }
301
362
  main().catch(err=>{log('manager-fatal',{code:err.code||'ERROR'});process.exit(1);});
363
+
364
+ }
@@ -1,7 +1,18 @@
1
1
  // Scoped read-only MCP exposure. Trace SDK is imported, never spawned as a CLI.
2
2
  import {createTraceReader} from '@tomflow/chatloop-trace';
3
3
  import {randomUUID} from 'node:crypto';
4
- import {paths,talk,CONTRACT} from './control.mjs';
4
+ // All internal dependencies are supplied as API contracts by index.mjs.
5
+ // Private modules never import or resolve another private implementation.
6
+ let paths, talk, CONTRACT;
7
+ let connected=false;
8
+ export function configureTraceGateway(ports){
9
+ if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
10
+ for(const name of ['paths', 'talk', 'CONTRACT'])
11
+ if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
12
+ ({paths, talk, CONTRACT}=ports);
13
+ connected=true;
14
+ }
15
+
5
16
 
6
17
  const PROJECT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
7
18
  const UUID='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$';
@@ -0,0 +1,118 @@
1
+ // Internal Supervisor Trace bridge: one writer owned by the Supervisor.
2
+ // Trace events are soft evidence; they never grant Context or Browser Owner.
3
+ export function createSupervisorTraceBridge({traceWriter,contract,error}){
4
+ const CONTRACT=contract;
5
+ const allowedTraceProjects=()=>{
6
+ const entries=(process.env.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
7
+ .split(',').map(x=>x.trim());
8
+ // Apply the same single-project, fail-closed boundary to log submission.
9
+ return new Set(entries.length===1 && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(entries[0])
10
+ ? entries : []);
11
+ };
12
+ const traceEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1';
13
+ const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
14
+ function handleTraceObservation(req){
15
+ // Internal Context audit collection uses its own exact single-project
16
+ // grant. Public Trace MCP observation/diagnosis remains opt-in and does
17
+ // not become reachable merely because Context collection is active.
18
+ const isContextApi=req?.event==='context.api';
19
+ const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
20
+ const contextAuthorized=process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
21
+ &&typeof contextGrant==='string'
22
+ &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextGrant)
23
+ &&req?.projectRef===contextGrant;
24
+ if(isContextApi?!contextAuthorized:
25
+ !traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
26
+ throw error('TRACE_PROJECT_ACCESS_DENIED');
27
+ // Context call observation has a stable event ID and typed API fields.
28
+ // It never grants write permission or impersonates an action receipt.
29
+ if(req?.event==='context.api'){
30
+ const allowed=new Set(['contract','action','requestId','traceId',
31
+ 'spanId','parentSpanId','projectRef','taskRef','event','api','status',
32
+ 'errorCode','durationMs']);
33
+ const terminal=['CONFIRMED','FAILED'].includes(req.status);
34
+ if(req.contract!==CONTRACT
35
+ ||!['BEGIN','CONFIRMED','FAILED'].includes(req.status)
36
+ ||!UUID_RE.test(req.traceId||'')||!UUID_RE.test(req.requestId||'')
37
+ ||(req.spanId!==undefined&&!UUID_RE.test(req.spanId))
38
+ ||(req.parentSpanId!==undefined&&!UUID_RE.test(req.parentSpanId))
39
+ ||Object.keys(req).some(k=>!allowed.has(k))
40
+ ||req.taskRef!==undefined&&!(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).test(req.taskRef)
41
+ ||!req.api||typeof req.api!=='object'||Array.isArray(req.api)
42
+ ||Object.keys(req.api).length!==3
43
+ ||Object.keys(req.api).some(k=>!['name','surface','mode'].includes(k))
44
+ ||typeof req.api.name!=='string'
45
+ ||!(/^[a-z][A-Za-z0-9._-]{1,89}$/).test(req.api.name)
46
+ ||!['sdk','gateway','operator','trusted'].includes(req.api.surface)
47
+ ||!['read','write','internal','operator','unknown'].includes(req.api.mode)
48
+ ||(req.status==='FAILED'
49
+ ?!(/^[A-Z][A-Z0-9_]{1,95}$/).test(req.errorCode||'')
50
+ :req.errorCode!==undefined)
51
+ ||(terminal
52
+ ?!Number.isSafeInteger(req.durationMs)||req.durationMs<0
53
+ :req.durationMs!==undefined))
54
+ throw error('TRACE_INVALID_ARGUMENT');
55
+ const recorded=traceWriter.record({
56
+ traceId:req.traceId,projectRef:req.projectRef,
57
+ ...(req.spanId?{spanId:req.spanId}:{}),
58
+ ...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
59
+ ...(req.taskRef?{taskRef:req.taskRef}:{}),
60
+ requestId:req.requestId,component:'context',event:'context.api',
61
+ api:{name:req.api.name,surface:req.api.surface,mode:req.api.mode},
62
+ status:req.status,
63
+ ...(req.errorCode?{errorCode:req.errorCode}:{}),
64
+ ...(terminal?{durationMs:req.durationMs}:{})
65
+ });
66
+ return {contract:CONTRACT,requestId:req.requestId,status:'OK',
67
+ eventId:recorded.eventId};
68
+ }
69
+ const intent=/^extension\.(continue|handoff)\.(intent\.queued|receipt\.observed)$/.test(req?.event||'');
70
+ const agent=/^agent\.(intent|project|tooling)\.soft_(observed|blocked|unverified)$/.test(req?.event||'');
71
+ const agentStatus=req?.event?.endsWith('_observed')?'CONFIRMED':
72
+ req?.event?.endsWith('_blocked')?'BLOCKED':'UNKNOWN';
73
+ const validEvent=['extension.start.observed','extension.status.observed'].includes(req?.event)
74
+ ||intent||agent;
75
+ if(req?.contract!==CONTRACT||!validEvent
76
+ ||!(agent?req.status===agentStatus:
77
+ intent?(req.event.endsWith('.intent.queued')?req.status==='BEGIN'
78
+ :['CONFIRMED','UNKNOWN'].includes(req.status))
79
+ :['CONFIRMED','UNKNOWN','BLOCKED'].includes(req.status))
80
+ ||typeof req.traceId!=='string'
81
+ ||(agent&&(req.sessionRef!==undefined||req.taskRef!==undefined||
82
+ req.generation!==undefined||req.evidenceRef!==undefined||
83
+ req.actionId!==undefined||req.errorCode!==undefined||!UUID_RE.test(req.traceId)))
84
+ ||(intent&&(!/^[a-f0-9]{32}$/.test(req.actionId||'')
85
+ ||req.evidenceRef!==req.actionId)))throw error('TRACE_INVALID_ARGUMENT');
86
+ const errorCode=typeof req.errorCode==='string'&&
87
+ /^[A-Z][A-Z0-9_]{0,95}$/.test(req.errorCode)?req.errorCode:null;
88
+ const written=traceWriter.record({
89
+ traceId:req.traceId,sessionRef:req.sessionRef,projectRef:req.projectRef,
90
+ taskRef:req.taskRef??null,generation:req.generation??null,
91
+ requestId:req.requestId,component:'gateway',
92
+ ...(intent?{actionId:req.actionId,evidenceRef:req.evidenceRef}
93
+ :req.event==='extension.status.observed'&&typeof req.evidenceRef==='string'
94
+ &&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(req.evidenceRef)
95
+ ?{evidenceRef:req.evidenceRef}:{}),
96
+ ...(req.status==='BLOCKED'&&errorCode?{errorCode}:{}),
97
+ event:req.event,status:req.status
98
+ });
99
+ return {contract:CONTRACT,requestId:req.requestId,status:'OK',eventId:written.eventId};
100
+ }
101
+ function traceNativeReceipt(req){
102
+ if(!traceEnabled())return;
103
+ // This is called ONLY after handleContextControl verifies Native HMAC and
104
+ // successfully executes the Context command; it is not a Browser send proof.
105
+ const command=req?.payload?.command,args=req?.payload?.args;
106
+ if(!command||!args||!allowedTraceProjects().has(args.projectId))return;
107
+ try{
108
+ traceWriter.record({traceId:args.sessionId,sessionRef:args.sessionId,
109
+ projectRef:args.projectId,taskRef:args.taskId,
110
+ generation:args.generation,component:'native',requestId:req.requestId,
111
+ event:'native.context.'+command+'.confirmed',status:'CONFIRMED'});
112
+ }catch{
113
+ // Trace failure is surfaced by health(), never treated as a failed
114
+ // Context mutation; its write result must not be replayed.
115
+ }
116
+ }
117
+ return {handleTraceObservation,traceNativeReceipt};
118
+ }
package/lib/tunnel.mjs CHANGED
@@ -1,39 +1,27 @@
1
1
  // Bundled OpenAI tunnel-client: never resolve from PATH, Homebrew or Local Dev.
2
- import {createHash} from 'node:crypto';
3
- import {createRequire} from 'node:module';
4
2
  import {spawn} from 'node:child_process';
5
- import {readFileSync,statSync} from 'node:fs';
6
3
  import {homedir} from 'node:os';
7
- import {join,dirname} from 'node:path';
8
- import {fileURLToPath} from 'node:url';
9
- const require=createRequire(import.meta.url);
4
+ import {join} from 'node:path';
10
5
 
11
6
  const supported=new Set(['darwin-x64','darwin-arm64']);
7
+ let loadPlatformBundle;
8
+ export function configureTunnelProvider(ports){
9
+ if(loadPlatformBundle)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
10
+ if(typeof ports?.loadPlatformBundle!=='function')
11
+ throw Error('TOOLS_PORT_MISSING:loadPlatformBundle');
12
+ loadPlatformBundle=ports.loadPlatformBundle;
13
+ }
12
14
  export function bundledTunnel(){
13
15
  const platform=process.platform+'-'+process.arch;
14
- if(!supported.has(platform))throw Object.assign(Error('Bundled tunnel-client is not available on '+platform),
15
- {code:'UNSUPPORTED_PLATFORM'});
16
- const platformPackage='@tomflow/chatloop-tunnel-'+platform;
17
- let base;
18
- try{base=join(dirname(require.resolve(platformPackage+'/package.json')),'bin');}
19
- catch{
20
- // Repo-only test fallback. No sibling workspace in a published npm consumer.
21
- base=fileURLToPath(new URL('../../tunnel-client-'+platform+'/bin/',import.meta.url));
22
- }
23
- const info=JSON.parse(readFileSync(join(base,'provenance.json'),'utf8'));
24
- const binary=join(base,'tunnel-client');
25
- const st=statSync(binary);
26
- if(!st.isFile()||!(st.mode&0o111))
27
- throw Object.assign(Error('Bundled executable missing'),{code:'INVALID_BUNDLE'});
28
- const checksum=createHash('sha256').update(readFileSync(binary)).digest('hex');
29
- if(checksum!==info.tunnelClientSha256)
30
- throw Object.assign(Error('Bundled executable checksum mismatch'),{code:'INVALID_BUNDLE'});
31
- const cloudflared=join(base,'cloudflared');
32
- const cs=statSync(cloudflared);
33
- const cloudHash=createHash('sha256').update(readFileSync(cloudflared)).digest('hex');
34
- if(!cs.isFile()||!(cs.mode&0o111)||cloudHash!==info.cloudflaredSha256)
35
- throw Object.assign(Error('Bundled cloudflared checksum mismatch'),{code:'INVALID_BUNDLE'});
36
- return {binary,cloudflared,release:info.release,platform,checksum,base};
16
+ if(!supported.has(platform))
17
+ throw Object.assign(Error('Unsupported tunnel platform'),{code:'UNSUPPORTED_PLATFORM'});
18
+ if(!loadPlatformBundle)throw Error('TOOLS_PORT_MISSING:loadPlatformBundle');
19
+ // Resolve only the declared public npm root API. No package.json subpath,
20
+ // no sibling repo fallback and no private binary path construction.
21
+ const provider=loadPlatformBundle(platform);
22
+ if(typeof provider?.getTunnelBundle!=='function')
23
+ throw Object.assign(Error('Tunnel provider API missing'),{code:'TUNNEL_PROVIDER_INVALID'});
24
+ return provider.getTunnelBundle();
37
25
  }
38
26
  export function tunnelDoctor(){
39
27
  try{
package/package.json CHANGED
@@ -3,37 +3,43 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.4.33",
6
+ "version": "0.9.0",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
10
- "chatloop-tools": "bin/cli.mjs",
11
- "chat-loop-local": "bin/cli.mjs"
10
+ "chatloop-tools": "bin/cli.mjs"
12
11
  },
13
12
  "files": [
14
- "bin/",
13
+ "index.mjs",
14
+ "providers.generated.mjs",
15
+ "providers/",
15
16
  "lib/",
17
+ "bin/",
18
+ "scripts/",
16
19
  "fixtures/",
17
20
  "README.md"
18
21
  ],
19
22
  "scripts": {
20
23
  "doctor": "node ./bin/cli.mjs doctor",
21
- "test": "node --test ./test/*.test.mjs"
24
+ "test": "node --test ./test/*.test.mjs",
25
+ "build:providers": "node ./scripts/build-providers.mjs",
26
+ "build:providers:check": "node ./scripts/build-providers.mjs --check",
27
+ "pretest": "node ./scripts/build-providers.mjs --check",
28
+ "prepack": "node ./scripts/build-providers.mjs --check"
22
29
  },
23
30
  "dependencies": {
24
31
  "@wonderwhy-er/desktop-commander": "0.2.44",
25
- "@tomflow/chatloop-context": "0.1.3",
26
- "@tomflow/chatloop-trace": "0.1.0"
32
+ "@tomflow/chatloop-context": "0.6.0",
33
+ "@tomflow/chatloop-trace": "0.4.0"
27
34
  },
28
35
  "engines": {
29
- "node": ">=20"
36
+ "node": ">=24"
30
37
  },
31
38
  "optionalDependencies": {
32
- "@tomflow/chatloop-tunnel-darwin-x64": "0.0.19",
33
- "@tomflow/chatloop-tunnel-darwin-arm64": "0.0.19"
39
+ "@tomflow/chatloop-tunnel-darwin-x64": "0.0.21",
40
+ "@tomflow/chatloop-tunnel-darwin-arm64": "0.0.21"
34
41
  },
35
- "bundleDependencies": [
36
- "@tomflow/chatloop-context",
37
- "@tomflow/chatloop-trace"
38
- ]
42
+ "exports": {
43
+ ".": "./index.mjs"
44
+ }
39
45
  }
@@ -0,0 +1,20 @@
1
+ // Context owns its own schemas, permissions and receipt protocol.
2
+ import {contextGateway} from '@tomflow/chatloop-context';
3
+ const names=contextGateway.tools.map(tool=>tool.name);
4
+ const fail=code=>({isError:true,content:[{type:'text',text:code}]});
5
+ export const provider=Object.freeze({
6
+ id:'context',order:3,names,
7
+ create({context}){
8
+ return Object.freeze({
9
+ tools:()=>context.contextGatewayEnabled()?context.contextGatewayTools:[],
10
+ async call(name,args){
11
+ if(!context.contextGatewayEnabled()||!names.includes(name))
12
+ return fail('UNKNOWN_TOOL');
13
+ try{
14
+ const result=await context.runContextGateway(name,args);
15
+ return {content:[{type:'text',text:JSON.stringify(result)}]};
16
+ }catch(e){return fail(e.code||e.message||'CONTEXT_OPERATION_FAILED')}
17
+ }
18
+ });
19
+ }
20
+ });
@@ -0,0 +1,80 @@
1
+ // Owned Desktop Commander/fixture MCP tools: one allowlist, one call path.
2
+ import {readFileSync} from 'node:fs';
3
+ import {randomUUID} from 'node:crypto';
4
+ const allowedDesktopTools=new Set([
5
+ 'get_config','read_file','read_multiple_files','write_file','write_pdf',
6
+ 'create_directory','list_directory','move_file','start_search',
7
+ 'get_more_search_results','stop_search','list_searches','get_file_info',
8
+ 'edit_block','start_process','read_process_output','interact_with_process',
9
+ 'force_terminate','list_sessions','list_processes','kill_process'
10
+ ]);
11
+ // The vendor descriptions contain long onboarding instructions and even
12
+ // directives to start unnecessary REPLs. Keep the exact vendor inputSchema,
13
+ // but describe the supported API succinctly at this single MCP boundary.
14
+ const desktopDescriptions={
15
+ read_file:'Read a file or URL (text, images, PDF, DOCX, spreadsheets). Use absolute path and optional offset/length to limit output; respect allowed directories.',
16
+ read_multiple_files:'Read several authorized absolute file paths in one request. Returns each result with its source path.',
17
+ write_file:'Create/replace or append to a file. mode is rewrite or append; prefer small chunks. Check the existing file and user authorization before overwriting.',
18
+ write_pdf:'Create or modify a PDF with markdown/operations. Use a new outputPath for modifications; never silently overwrite the original.',
19
+ list_directory:'List files and folders under an authorized absolute path; depth limits recursion and output.',
20
+ start_search:'Search filenames (searchType=files) or file contents (searchType=content) from an authorized root. Returns a session for paginated results.',
21
+ get_more_search_results:'Get additional results from an existing search session using sessionId and pagination.',
22
+ edit_block:'Apply an exact targeted edit; pass file_path and old_string/new_string for text, or range/content for spreadsheets. Refuse ambiguous replacements.',
23
+ start_process:'Run CLI commands through the MCP process, never launch macOS Terminal/iTerm apps. A PID is not completion; read its output.',
24
+ read_process_output:'Read output of an already-started PID with optional offset/length/timeout_ms. Does not start the command again.',
25
+ interact_with_process:'Send input to an existing interactive PID and obtain output. Do not repeat commands with unknown side effects.',
26
+ get_config:'Read Desktop Commander configuration/allowed directories for diagnosis; does not grant or change permissions.'
27
+ };
28
+ const desktopTools=JSON.parse(readFileSync(
29
+ new URL('../lib/desktop-commander-tools.json',import.meta.url),'utf8'))
30
+ .filter(t=>allowedDesktopTools.has(t.name))
31
+ .map(t=>({...t,description:desktopDescriptions[t.name]||t.description.trim()}));
32
+
33
+ const fixtureTool={name:'ping',description:'Inert lifecycle test health check',
34
+ inputSchema:{type:'object',properties:{},additionalProperties:false}};
35
+ const toolsFor=t=>t.kind==='mcp-child'?desktopTools:t.kind==='fixture'?[fixtureTool]:[];
36
+ const prefix=id=>id.replaceAll('-','_')+'__';
37
+ const fail=code=>({isError:true,content:[{type:'text',text:code}]});
38
+ export const provider=Object.freeze({
39
+ id:'desktop',order:0,
40
+ names:[...desktopTools.map(t=>'desktop_commander__'+t.name),
41
+ 'mock_alpha__ping','mock_beta__ping'],
42
+ create({control,release,terminal}){
43
+ const registry=control.registry;
44
+ const active=()=>registry().filter(t=>t.enabled).flatMap(t=>
45
+ toolsFor(t).map(({_meta,...tool})=>({
46
+ tool:{...tool,name:prefix(t.id)+tool.name},
47
+ toolId:t.id,localName:tool.name
48
+ })));
49
+ return Object.freeze({
50
+ tools:()=>active().map(x=>x.tool),
51
+ async call(name,args){
52
+ const route=active().find(x=>x.tool.name===name);
53
+ if(!route)return fail('UNKNOWN_TOOL');
54
+ // No-argument MCP calls are equivalent to an empty arguments object.
55
+ args=args??{};
56
+ if(typeof args!=='object'||Array.isArray(args))
57
+ return fail('INVALID_ARGUMENT');
58
+ if(route.toolId==='desktop-commander'&&
59
+ terminal.isGraphicalTerminalCommand(route.localName,args))
60
+ return fail('GUI_TERMINAL_LAUNCH_PROHIBITED');
61
+ if(!process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR&&
62
+ !process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES&&release.runtimeNeedsUpgrade())
63
+ return fail('RUNTIME_UPGRADE_REQUIRED');
64
+ try{
65
+ const deadlineMs=control.toolCallDeadlineMs(args),requestId=randomUUID();
66
+ const res=await control.talk({contract:control.CONTRACT,requestId,
67
+ action:'call',scope:'tool',toolId:route.toolId,
68
+ name:route.localName,args,deadlineMs},deadlineMs+2000);
69
+ if(res.status!=='OK')return fail(res.error?.code==='TIMEOUT'
70
+ ?'OPERATION_UNCONFIRMED:'+requestId
71
+ :res.error?.code||'TOOL_UNAVAILABLE');
72
+ return res.result;
73
+ }catch(e){
74
+ return fail(['ENOENT','ECONNREFUSED'].includes(e.code)
75
+ ?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE');
76
+ }
77
+ }
78
+ });
79
+ }
80
+ });