@tomflow/chatloop-tools 0.9.30 → 0.9.31

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/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // Sole npm SDK entry and composition root for Chat Loop Tools.
2
2
  // Modules declare named API ports. No lib module imports another lib module.
3
3
  import {randomUUID} from 'node:crypto';
4
+ import {dirname,join} from 'node:path';
4
5
  import {subscribeContextApiLog} from '@tomflow/chatloop-context';
5
6
  import {createApiAspect,subscribeTraceApiLog} from '@tomflow/chatloop-trace';
6
7
  import {providerDefinitions} from './providers.generated.mjs';
@@ -274,6 +275,14 @@ async function runtime(){
274
275
  ensurePrivateDir:control.ensurePrivateDir,ACTIONS:control.ACTIONS,
275
276
  createAdapter:adapters.createAdapter,
276
277
  createSupervisorTraceBridge:traceObservation.createSupervisorTraceBridge,
278
+ // The same owned Tunnel profile defines the MCP child's grants. Feed
279
+ // only its validated observation scopes into the Supervisor's writer;
280
+ // never export those grants into unrelated child-process environments.
281
+ readObservationGrants:()=>{
282
+ try{return releaseUpgrade.readSupervisorMcpGrants(join(
283
+ dirname(control.paths().dir),'tunnel','profiles','chat-loop.yaml'))}
284
+ catch{return {}}
285
+ },
277
286
  loadContextControlSecret:contextAuth.loadContextControlSecret,
278
287
  handleContextControl:contextRun.handleContextControl
279
288
  });
@@ -90,6 +90,39 @@ export function preservedMcpEnvironmentPrefix(command){
90
90
  return match[0]+' ';
91
91
  }
92
92
 
93
+ // The Tunnel profile is the authority for the MCP child grants. A Supervisor
94
+ // launched by an ordinary CLI may not inherit those grants; recover only the
95
+ // non-secret, single-Project observation grants from the trusted profile.
96
+ const SUPERVISOR_GRANT_KEYS=new Set([
97
+ 'CHAT_LOOP_CONTEXT_API_ENABLE','CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS',
98
+ 'CHAT_LOOP_TRACE_API_ENABLE','CHAT_LOOP_TRACE_ALLOWED_PROJECTS'
99
+ ]);
100
+ const SINGLE_PROJECT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
101
+ export function readSupervisorMcpGrants(profilePath){
102
+ const file=lstatSync(profilePath);
103
+ if(!file.isFile()||file.isSymbolicLink()||(file.mode&0o077)
104
+ ||(process.getuid&&file.uid!==process.getuid()))
105
+ throw Object.assign(Error('RELEASE_PROFILE_UNTRUSTED'),{code:'RELEASE_PROFILE_UNTRUSTED'});
106
+ const profile=JSON.parse(readFileSync(profilePath,'utf8'));
107
+ const main=profile?.mcp?.commands?.filter(x=>x.channel==='main');
108
+ if(main?.length!==1||typeof main[0].command!=='string')
109
+ throw Object.assign(Error('RELEASE_PROFILE_MCP_NOT_FOUND'),{code:'RELEASE_PROFILE_MCP_NOT_FOUND'});
110
+ const prefix=preservedMcpEnvironmentPrefix(main[0].command),grants={};
111
+ for(const [,assignment] of prefix.matchAll(/ "([^"]+)"/g)){
112
+ const offset=assignment.indexOf('='),key=assignment.slice(0,offset);
113
+ if(SUPERVISOR_GRANT_KEYS.has(key))grants[key]=assignment.slice(offset+1);
114
+ }
115
+ for(const [enabled,project] of [
116
+ ['CHAT_LOOP_CONTEXT_API_ENABLE','CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS'],
117
+ ['CHAT_LOOP_TRACE_API_ENABLE','CHAT_LOOP_TRACE_ALLOWED_PROJECTS']]){
118
+ if(grants[enabled]!==undefined&&grants[enabled]!=='1'||
119
+ grants[enabled]==='1'&&!SINGLE_PROJECT.test(grants[project]||''))
120
+ throw Object.assign(Error('RELEASE_PROFILE_GRANT_INVALID'),
121
+ {code:'RELEASE_PROFILE_GRANT_INVALID'});
122
+ }
123
+ return grants;
124
+ }
125
+
93
126
  export async function upgradeRuntime(options={}){
94
127
  if(options.args?.length)return freshResult('FAILED',{code:'INVALID_ARGUMENT'});
95
128
  const base=checkedUpgradeBase(options);
@@ -7,7 +7,8 @@ const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
7
7
  'ownerNonce','managerPid']);
8
8
 
9
9
  export function createSupervisorObservability({
10
- filePath,rotationEnabled,contextUsageGrant,contract,nonce,processId,
10
+ filePath,rotationEnabled,contextUsageGrant,observationGrants=process.env,
11
+ contract,nonce,processId,
11
12
  createSupervisorTraceBridge,createTraceWriterImpl=createTraceWriter
12
13
  }){
13
14
  const traceWriter=createTraceWriterImpl({
@@ -57,7 +58,7 @@ export function createSupervisorObservability({
57
58
  ?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
58
59
  };
59
60
  const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
60
- traceWriter,contract
61
+ traceWriter,contract,observationGrants
61
62
  });
62
63
 
63
64
  function recordApiObservation(req){
@@ -4,13 +4,13 @@ import {createServer} from 'node:net';
4
4
  import {createSupervisorObservability} from './supervisor-observability.mjs';
5
5
  // All internal dependencies are supplied as API contracts by index.mjs.
6
6
  // Private modules never import or resolve another private implementation.
7
- let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl;
7
+ let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, loadContextControlSecret, handleContextControl;
8
8
  let connected=false;
9
9
  export function configureSupervisor(ports){
10
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'])
11
+ for(const name of ['CONTRACT', 'VERSION', 'PACKAGE_VERSION', 'registry', 'paths', 'ensurePrivateDir', 'ACTIONS', 'createAdapter', 'createSupervisorTraceBridge', 'readObservationGrants', 'loadContextControlSecret', 'handleContextControl'])
12
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);
13
+ ({CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, loadContextControlSecret, handleContextControl}=ports);
14
14
  connected=true;
15
15
  }
16
16
 
@@ -37,11 +37,15 @@ function rememberRequest(id,payload,promise){
37
37
  }
38
38
  const p=paths(), nonce=randomUUID();
39
39
  const error=(code,message=code)=>({code,message});
40
+ let recoveredGrants={};
41
+ try{recoveredGrants=readObservationGrants()||{}}catch{}
42
+ const observationGrants=Object.keys(recoveredGrants).length
43
+ ?recoveredGrants:process.env;
40
44
  const observability=createSupervisorObservability({
41
45
  filePath:p.log,
42
46
  rotationEnabled:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1',
43
- contextUsageGrant:process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS,
44
- contract:CONTRACT,nonce,processId:process.pid,
47
+ contextUsageGrant:observationGrants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS,
48
+ observationGrants,contract:CONTRACT,nonce,processId:process.pid,
45
49
  createSupervisorTraceBridge,error
46
50
  });
47
51
  const {log,traceHealth,handleTraceObservation,traceNativeReceipt,
@@ -1,15 +1,16 @@
1
1
  // Internal Supervisor Trace bridge: one writer owned by the Supervisor.
2
2
  // Trace events are soft evidence; they never grant Context or Browser Owner.
3
- export function createSupervisorTraceBridge({traceWriter,contract,error}){
3
+ export function createSupervisorTraceBridge({traceWriter,contract,error,
4
+ observationGrants=process.env}){
4
5
  const CONTRACT=contract;
5
6
  const allowedTraceProjects=()=>{
6
- const entries=(process.env.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
7
+ const entries=(observationGrants.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
7
8
  .split(',').map(x=>x.trim());
8
9
  // Apply the same single-project, fail-closed boundary to log submission.
9
10
  return new Set(entries.length===1 && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(entries[0])
10
11
  ? entries : []);
11
12
  };
12
- const traceEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1';
13
+ const traceEnabled=()=>observationGrants.CHAT_LOOP_TRACE_API_ENABLE==='1';
13
14
  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
15
  function handleTraceObservation(req){
15
16
  // Internal Context audit collection uses its own exact single-project
@@ -17,8 +18,8 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
17
18
  // not become reachable merely because Context collection is active.
18
19
  const isContextApi=req?.event==='context.api';
19
20
  const form=/^form\.(prepared|rendered|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
20
- const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
21
- const contextAuthorized=process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
21
+ const contextGrant=observationGrants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
22
+ const contextAuthorized=observationGrants.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
22
23
  &&typeof contextGrant==='string'
23
24
  &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextGrant)
24
25
  &&req?.projectRef===contextGrant;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.30",
6
+ "version": "0.9.31",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -50,7 +50,7 @@ const cardSchema={type:'object',additionalProperties:false,required:REQUIRED_CAR
50
50
  }};
51
51
  const tools=[
52
52
  {name:'chat_loop_form__prepare',description:
53
- 'Render a generic single-select form with caller-defined options and optional text input. Preserve an optional caller-supplied formId or generate a UUID; return an opaque traceRef for log correlation. No business workflow or approval state is owned here.',
53
+ 'Present a generic single-select MCP App with caller-defined options and optional text input. Perform ALL document preparation, persistence, verification, and other tool calls BEFORE calling this tool. To keep the interactive form visible in the completed ChatGPT answer, call this tool LAST in the assistant turn and do not call any more tools afterwards; the host may collapse an earlier widget. Preserve an optional caller-supplied formId or generate a UUID; return an opaque traceRef for log correlation. No business workflow or approval state is owned here.',
54
54
  inputSchema:{type:'object',additionalProperties:false,required:['card'],
55
55
  properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
56
56
  annotations:{readOnlyHint:false},