@tomflow/chatloop-tools 0.4.34 → 0.9.4
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 +120 -127
- package/bin/cli.mjs +48 -38
- package/bin/supervisor.mjs +4 -0
- package/index.mjs +269 -0
- package/lib/adapters/fixture.mjs +3 -2
- package/lib/adapters/index.mjs +14 -5
- package/lib/adapters/mcp-child.mjs +29 -7
- package/lib/adapters/tunnel.mjs +25 -7
- package/lib/api-aspect.mjs +190 -0
- package/lib/cli-command-router.mjs +34 -0
- package/lib/context-control-auth.mjs +12 -1
- package/lib/context-control-run.mjs +17 -79
- package/lib/context-gateway.mjs +108 -15
- package/lib/control.mjs +3 -2
- package/lib/extension-cli-contract.mjs +22 -0
- package/lib/extension-proxy.mjs +48 -19
- package/lib/gateway.mjs +46 -176
- package/lib/mcp-tool-router.mjs +60 -0
- package/lib/release-owner-preflight.mjs +41 -0
- package/lib/release.mjs +94 -49
- package/lib/{supervisor.mjs → supervisor-runtime.mjs} +143 -80
- package/lib/trace-gateway.mjs +25 -7
- package/lib/trace-observation.mjs +123 -0
- package/lib/tunnel.mjs +17 -29
- package/package.json +20 -14
- package/providers/context.mjs +20 -0
- package/providers/desktop.mjs +80 -0
- package/{lib/extension-contract.mjs → providers/extension.mjs} +36 -0
- package/providers/runtime.mjs +32 -0
- package/providers/trace.mjs +25 -0
- package/providers.generated.mjs +8 -0
- package/scripts/build-providers.mjs +69 -0
- package/lib/context-cli.mjs +0 -2
- package/lib/context-migration.mjs +0 -2
- package/lib/context-protocol.mjs +0 -2
- package/lib/task-registry-managed.mjs +0 -38
- package/lib/task-registry.mjs +0 -221
- package/node_modules/@tomflow/chatloop-context/README.md +0 -271
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -273
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -301
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -272
- package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +0 -1617
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -264
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -219
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -455
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -159
- package/node_modules/@tomflow/chatloop-context/package.json +0 -21
- package/node_modules/@tomflow/chatloop-trace/README.md +0 -13
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -259
- package/node_modules/@tomflow/chatloop-trace/package.json +0 -11
package/lib/gateway.mjs
CHANGED
|
@@ -1,88 +1,31 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
// by tools/call either; runtime/admin/onboarding controls are not agent tools.
|
|
16
|
-
const hiddenDesktopTools=new Set([
|
|
17
|
-
'set_config_value','get_usage_stats','get_recent_tool_calls',
|
|
18
|
-
'give_feedback_to_desktop_commander','get_prompts'
|
|
19
|
-
]);
|
|
20
|
-
// The vendor descriptions contain long onboarding instructions and even
|
|
21
|
-
// directives to start unnecessary REPLs. Keep the exact vendor inputSchema,
|
|
22
|
-
// but describe the supported API succinctly at this single MCP boundary.
|
|
23
|
-
const desktopDescriptions={
|
|
24
|
-
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.',
|
|
25
|
-
read_multiple_files:'Read several authorized absolute file paths in one request. Returns each result with its source path.',
|
|
26
|
-
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.',
|
|
27
|
-
write_pdf:'Create or modify a PDF with markdown/operations. Use a new outputPath for modifications; never silently overwrite the original.',
|
|
28
|
-
list_directory:'List files and folders under an authorized absolute path; depth limits recursion and output.',
|
|
29
|
-
start_search:'Search filenames (searchType=files) or file contents (searchType=content) from an authorized root. Returns a session for paginated results.',
|
|
30
|
-
get_more_search_results:'Get additional results from an existing search session using sessionId and pagination.',
|
|
31
|
-
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.',
|
|
32
|
-
start_process:'Run CLI commands through the MCP process, never launch macOS Terminal/iTerm apps. A PID is not completion; read its output.',
|
|
33
|
-
read_process_output:'Read output of an already-started PID with optional offset/length/timeout_ms. Does not start the command again.',
|
|
34
|
-
interact_with_process:'Send input to an existing interactive PID and obtain output. Do not repeat commands with unknown side effects.',
|
|
35
|
-
get_config:'Read Desktop Commander configuration/allowed directories for diagnosis; does not grant or change permissions.'
|
|
36
|
-
};
|
|
37
|
-
const desktopTools=JSON.parse(readFileSync(
|
|
38
|
-
new URL('./desktop-commander-tools.json',import.meta.url),'utf8'))
|
|
39
|
-
.filter(t=>!hiddenDesktopTools.has(t.name))
|
|
40
|
-
.map(t=>({...t,description:desktopDescriptions[t.name]||t.description.trim()}));
|
|
41
|
-
const fixtureTool={name:'ping',description:'Inert lifecycle test health check',
|
|
42
|
-
inputSchema:{type:'object',properties:{},additionalProperties:false}};
|
|
43
|
-
const toolsFor=t=>t.kind==='mcp-child'?desktopTools:t.kind==='fixture'?[fixtureTool]:[];
|
|
44
|
-
const prefix=id=>id.replaceAll('-','_')+'__';
|
|
45
|
-
// The pinned child's UI metadata advertises resources this tools-only Gateway does not serve.
|
|
46
|
-
// Do not expose those references until resources/read is explicitly supported.
|
|
47
|
-
const extEnabled=()=>process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES!=='1';
|
|
48
|
-
// The only extra Gateway-owned API: read an existing operation receipt.
|
|
49
|
-
// Its identifier is always a generated UUID, never an arbitrary selector.
|
|
50
|
-
const RECEIPT_ID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
51
|
-
const receiptTool={name:'chat_loop_runtime__operation_status',
|
|
52
|
-
description:'Read a previously timed-out MCP request receipt without replaying its side effects.',
|
|
53
|
-
inputSchema:{type:'object',required:['requestId'],additionalProperties:false,
|
|
54
|
-
properties:{requestId:{type:'string',pattern:RECEIPT_ID.source}}}};
|
|
55
|
-
const published=()=>[
|
|
56
|
-
...registry().filter(t=>t.enabled).flatMap(t=>
|
|
57
|
-
toolsFor(t).map(({_meta,...x})=>({...x,name:prefix(t.id)+x.name}))),
|
|
58
|
-
...(extEnabled()?extensionTools.map(t=>({...t,name:'chat_loop_extension__'+t.name})):[]),
|
|
59
|
-
receiptTool,
|
|
60
|
-
taskRegistryTool,
|
|
61
|
-
...(contextGatewayEnabled()?contextGatewayTools:[]),
|
|
62
|
-
...(traceGatewayEnabled()?[traceDiagnoseTool,traceStageTool]:[])
|
|
63
|
-
];
|
|
64
|
-
function resolveTool(name){
|
|
65
|
-
if(extEnabled()&&typeof name==='string'&&name.startsWith('chat_loop_extension__')){
|
|
66
|
-
const original=name.slice('chat_loop_extension__'.length);
|
|
67
|
-
if(extensionTools.some(t=>t.name===original))
|
|
68
|
-
return {toolId:'chat-loop-extension',name:original};
|
|
69
|
-
}
|
|
70
|
-
for(const t of registry().filter(x=>x.enabled)){
|
|
71
|
-
const p=prefix(t.id);
|
|
72
|
-
if(typeof name==='string'&&name.startsWith(p)){
|
|
73
|
-
const original=name.slice(p.length);
|
|
74
|
-
if(toolsFor(t).some(x=>x.name===original))return {toolId:t.id,name:original};
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
return null;
|
|
1
|
+
// One MCP transport: all tools/list and tools/call routes come from the
|
|
2
|
+
// compiled Provider registry, never from per-provider branches here.
|
|
3
|
+
let CONTRACT,PACKAGE_VERSION,toolRouter,observeProtocol;
|
|
4
|
+
let configured=false;
|
|
5
|
+
export function configureGateway(ports){
|
|
6
|
+
if(configured)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
7
|
+
for(const key of ['CONTRACT','PACKAGE_VERSION','toolRouter','observeProtocol'])
|
|
8
|
+
if(ports?.[key]===undefined)throw Error('TOOLS_PORT_MISSING:'+key);
|
|
9
|
+
({CONTRACT,PACKAGE_VERSION,toolRouter,observeProtocol}=ports);
|
|
10
|
+
if(typeof toolRouter.list!=='function'||typeof toolRouter.call!=='function')
|
|
11
|
+
throw Error('TOOLS_PORT_INVALID:toolRouter');
|
|
12
|
+
if(typeof observeProtocol!=='function')
|
|
13
|
+
throw Error('TOOLS_PORT_INVALID:observeProtocol');
|
|
14
|
+
configured=true;
|
|
78
15
|
}
|
|
79
16
|
const failure=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
80
17
|
const rpcError=(code,message)=>({code,message});
|
|
81
18
|
export function runGateway(){
|
|
82
19
|
let buf='',connected=false;
|
|
83
20
|
const write=message=>process.stdout.write(JSON.stringify(message)+'\n');
|
|
84
|
-
const reply=(id,result)=>
|
|
85
|
-
|
|
21
|
+
const reply=(id,result)=>{
|
|
22
|
+
write({jsonrpc:'2.0',id,result});
|
|
23
|
+
return {isError:false}; // soft outcome only, not a second MCP response
|
|
24
|
+
};
|
|
25
|
+
const reject=(id,code,message)=>{
|
|
26
|
+
write({jsonrpc:'2.0',id,error:rpcError(code,message)});
|
|
27
|
+
return {isError:true}; // AOP must record actual rejected protocol requests
|
|
28
|
+
};
|
|
86
29
|
const processMessage=async m=>{
|
|
87
30
|
if(!m||m.jsonrpc!=='2.0'||m.id===undefined)return;
|
|
88
31
|
if(m.method==='initialize'){
|
|
@@ -93,116 +36,43 @@ export function runGateway(){
|
|
|
93
36
|
return reply(m.id,{protocolVersion:m.params.protocolVersion,
|
|
94
37
|
capabilities:{tools:{}},serverInfo:{name:'chat-loop-local-tools',version:PACKAGE_VERSION}});
|
|
95
38
|
}
|
|
96
|
-
// A modern MCP client probes discovery before falling back to legacy initialize.
|
|
97
|
-
// We only implement the legacy handshake era, so report unsupported method.
|
|
98
39
|
if(m.method==='server/discover')return reject(m.id,-32601,'METHOD_NOT_FOUND');
|
|
99
40
|
if(!connected)return reject(m.id,-32002,'NOT_INITIALIZED');
|
|
100
41
|
if(m.method==='ping')return reply(m.id,{});
|
|
101
|
-
if(m.method==='tools/list')
|
|
42
|
+
if(m.method==='tools/list'){
|
|
43
|
+
try{return reply(m.id,{tools:toolRouter.list()})}
|
|
44
|
+
catch{return reject(m.id,-32603,'PROVIDER_CATALOG_INVALID')}
|
|
45
|
+
}
|
|
102
46
|
if(m.method==='tools/call'){
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
|
|
107
|
-
}catch(e){return reply(m.id,failure(e.code||'TRACE_STAGE_FAILED'))}
|
|
108
|
-
}
|
|
109
|
-
if(traceGatewayEnabled()&&m.params?.name===traceDiagnoseTool.name){
|
|
110
|
-
try{
|
|
111
|
-
const result=await runTraceDiagnose(m.params.arguments);
|
|
112
|
-
return reply(m.id,{content:[{type:'text',text:JSON.stringify(result)}]});
|
|
113
|
-
}catch(e){return reply(m.id,failure(e.code||'TRACE_DIAGNOSE_FAILED'))}
|
|
114
|
-
}
|
|
115
|
-
if(m.params?.name===taskRegistryTool.name){
|
|
116
|
-
try{
|
|
117
|
-
// Opting into managed Context must never silently revive JSON
|
|
118
|
-
// Registry writes when its SDK, Node runtime or binding is absent.
|
|
119
|
-
if(process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'&&!contextGatewayEnabled())
|
|
120
|
-
throw Error('CONTEXT_GATEWAY_UNAVAILABLE');
|
|
121
|
-
let value;
|
|
122
|
-
// Authority is the durable SourceUnit migration record, never a
|
|
123
|
-
// process-local env flag that could go stale after cutover.
|
|
124
|
-
if(contextGatewayEnabled()){
|
|
125
|
-
const args=m.params.arguments||{},projectId=args.projectId;
|
|
126
|
-
const authority=await runContextGateway('chat_loop_context_get',{
|
|
127
|
-
operation:'project.registryAuthority',projectId});
|
|
128
|
-
if(authority==='RESTORED_DIAGNOSTIC')
|
|
129
|
-
throw Error('REGISTRY_RESTORE_READ_ONLY');
|
|
130
|
-
if(authority==='CUTOVER_FENCED')
|
|
131
|
-
throw Error('REGISTRY_CUTOVER_FENCED');
|
|
132
|
-
if(!['LEGACY_RW','MANAGED_RW'].includes(authority))
|
|
133
|
-
throw Error('REGISTRY_AUTHORITY_UNKNOWN');
|
|
134
|
-
if(authority==='MANAGED_RW'){
|
|
135
|
-
// The legacy registry is a read-only projection through the
|
|
136
|
-
// independent Context SDK, not a second SQLite client.
|
|
137
|
-
if(args.action==='list'){
|
|
138
|
-
const tasks=await runContextGateway('chat_loop_context_get',{
|
|
139
|
-
operation:'task.list',projectId});
|
|
140
|
-
value=managedTaskRegistry({taskList:()=>tasks},args);
|
|
141
|
-
}else if(args.action==='get'){
|
|
142
|
-
const task=await runContextGateway('chat_loop_context_get',{
|
|
143
|
-
operation:'task.get',projectId,taskId:args.taskId});
|
|
144
|
-
value=managedTaskRegistry({get:()=>task},args);
|
|
145
|
-
}else throw Error('REGISTRY_MANAGED_USE_CONTEXT_MUTATE');
|
|
146
|
-
}else value=runTaskRegistry(args);
|
|
147
|
-
}else value=runTaskRegistry(m.params.arguments);
|
|
148
|
-
return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
|
|
149
|
-
}catch(e){return reply(m.id,failure(e.code||e.message||'TASK_REGISTRY_FAILED'));}
|
|
150
|
-
}
|
|
151
|
-
if(contextGatewayEnabled()&&contextGatewayTools.some(t=>t.name===m.params?.name)){
|
|
152
|
-
try{
|
|
153
|
-
const value=await runContextGateway(m.params.name,m.params.arguments);
|
|
154
|
-
return reply(m.id,{content:[{type:'text',text:JSON.stringify(value)}]});
|
|
155
|
-
}catch(e){return reply(m.id,failure(e.code||e.message||'CONTEXT_OPERATION_FAILED'));}
|
|
156
|
-
}
|
|
157
|
-
const routed=m.params?.name===receiptTool.name?
|
|
158
|
-
{toolId:'runtime',name:'operation_status'}:resolveTool(m.params?.name);
|
|
159
|
-
if(!routed)return reply(m.id,failure('UNKNOWN_TOOL'));
|
|
160
|
-
const args=m.params?.arguments??{};
|
|
161
|
-
if(args===null||typeof args!=='object'||Array.isArray(args))
|
|
162
|
-
return reply(m.id,failure('INVALID_ARGUMENT'));
|
|
163
|
-
if(routed.toolId==='desktop-commander'&&
|
|
164
|
-
isGraphicalTerminalCommand(routed.name,args))
|
|
165
|
-
return reply(m.id,failure('GUI_TERMINAL_LAUNCH_PROHIBITED'));
|
|
166
|
-
try{
|
|
167
|
-
if(routed.toolId==='runtime'){
|
|
168
|
-
if(Object.keys(args).length!==1 || typeof args.requestId!=='string'
|
|
169
|
-
||!RECEIPT_ID.test(args.requestId))
|
|
170
|
-
return reply(m.id,failure('INVALID_ARGUMENT'));
|
|
171
|
-
const res=await talk({contract:CONTRACT,action:'receipt',requestId:randomUUID(),
|
|
172
|
-
targetRequestId:args.requestId},4000);
|
|
173
|
-
return reply(m.id,res.status==='OK'?{operation:res.operation}:failure('RECEIPT_UNAVAILABLE'));
|
|
174
|
-
}
|
|
175
|
-
if(routed.toolId!=='chat-loop-extension'&&
|
|
176
|
-
!process.env.CHAT_LOOP_LOCAL_TOOLS_STATE_DIR&&
|
|
177
|
-
!process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES&&runtimeNeedsUpgrade())
|
|
178
|
-
return reply(m.id,failure('RUNTIME_UPGRADE_REQUIRED'));
|
|
179
|
-
if(routed.toolId==='chat-loop-extension'){
|
|
180
|
-
const result=await forwardExtensionAction(routed.name,args);
|
|
181
|
-
await observeExtensionResult(routed.name,args,result);
|
|
182
|
-
return reply(m.id,result);
|
|
183
|
-
}
|
|
184
|
-
const deadlineMs=toolCallDeadlineMs(args),requestId=randomUUID();
|
|
185
|
-
const res=await talk({contract:CONTRACT,requestId,action:'call',
|
|
186
|
-
scope:'tool',toolId:routed.toolId,name:routed.name,args,deadlineMs},deadlineMs+2000);
|
|
187
|
-
if(res.status!=='OK')return reply(m.id,failure(res.error?.code==='TIMEOUT'?
|
|
188
|
-
'OPERATION_UNCONFIRMED:'+requestId:res.error?.code||'TOOL_UNAVAILABLE'));
|
|
189
|
-
return reply(m.id,res.result);
|
|
190
|
-
}catch(e){
|
|
191
|
-
return reply(m.id,failure(['ENOENT','ECONNREFUSED'].includes(e.code)?'TOOL_UNAVAILABLE':
|
|
192
|
-
e.code||'MANAGER_UNAVAILABLE'));
|
|
193
|
-
}
|
|
47
|
+
try{return reply(m.id,await toolRouter.call(m.params?.name,m.params?.arguments))}
|
|
48
|
+
catch(e){return reply(m.id,failure(['ENOENT','ECONNREFUSED'].includes(e.code)
|
|
49
|
+
?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE'))}
|
|
194
50
|
}
|
|
195
51
|
return reject(m.id,-32601,'METHOD_NOT_FOUND');
|
|
196
52
|
};
|
|
197
53
|
process.stdin.setEncoding('utf8');
|
|
198
54
|
process.stdin.on('data',chunk=>{
|
|
199
55
|
buf+=chunk;
|
|
200
|
-
|
|
56
|
+
// MCP input limits are transport bytes, not UTF-16 code units;
|
|
57
|
+
// otherwise a large multibyte payload bypasses the 1 MiB boundary.
|
|
58
|
+
if(Buffer.byteLength(buf,'utf8')>1024*1024){
|
|
59
|
+
process.stderr.write('MCP frame too large\n');
|
|
60
|
+
process.exitCode=1;process.stdin.pause();return;
|
|
61
|
+
}
|
|
201
62
|
let n;
|
|
202
63
|
while((n=buf.indexOf('\n'))>=0){
|
|
203
64
|
const line=buf.slice(0,n);buf=buf.slice(n+1);
|
|
204
|
-
let m;try{m=JSON.parse(line)
|
|
205
|
-
|
|
65
|
+
let m;try{m=JSON.parse(line)}catch{continue}
|
|
66
|
+
if(m?.id===undefined)continue; // MCP notifications have no call receipt.
|
|
67
|
+
// tools/list and tools/call already have their own runtime API spans;
|
|
68
|
+
// every other addressed protocol request must also leave a trace.
|
|
69
|
+
const handledByRouter=connected&&
|
|
70
|
+
(m.method==='tools/list'||m.method==='tools/call');
|
|
71
|
+
const invoke=()=>processMessage(m);
|
|
72
|
+
const task=handledByRouter?invoke():observeProtocol(m.method,invoke);
|
|
73
|
+
void Promise.resolve(task).catch(()=>{
|
|
74
|
+
reject(m.id,-32603,'INTERNAL_ERROR');
|
|
75
|
+
});
|
|
206
76
|
}
|
|
207
77
|
});
|
|
208
78
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Statically composed MCP provider routing. Runtime never discovers modules,
|
|
2
|
+
// executable paths, tools, or schemas from filesystem/user-controlled inputs.
|
|
3
|
+
const failure=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
4
|
+
const fail=code=>Object.assign(Error(code),{code});
|
|
5
|
+
const validName=name=>typeof name==='string'
|
|
6
|
+
&&/^[a-z][a-z0-9_]*__[a-z][a-z0-9_]*$|^chat_loop_(?:context_get|context_mutate|trace_diagnose|trace_stage)$/.test(name);
|
|
7
|
+
|
|
8
|
+
export function createMcpToolRouter(definitions,services={}){
|
|
9
|
+
if(!Array.isArray(definitions)||!definitions.length)throw fail('MCP_PROVIDERS_MISSING');
|
|
10
|
+
const owners=new Map(),ids=new Set(),instances=[];
|
|
11
|
+
for(const def of definitions){
|
|
12
|
+
if(!def||typeof def.id!=='string'||ids.has(def.id)
|
|
13
|
+
||!Array.isArray(def.names)
|
|
14
|
+
||!(def.names.length||(Array.isArray(def.commands)&&def.commands.length))
|
|
15
|
+
||(def.names.length>0&&typeof def.create!=='function'))
|
|
16
|
+
throw fail('MCP_PROVIDER_INVALID');
|
|
17
|
+
ids.add(def.id);
|
|
18
|
+
for(const name of def.names){
|
|
19
|
+
if(!validName(name))throw fail('MCP_TOOL_NAME_INVALID');
|
|
20
|
+
if(owners.has(name))throw fail('MCP_TOOL_CONFLICT:'+name);
|
|
21
|
+
owners.set(name,def.id);
|
|
22
|
+
}
|
|
23
|
+
// A CLI-only Provider has no MCP tools and needs no dummy MCP adapter.
|
|
24
|
+
if(!def.names.length)continue;
|
|
25
|
+
const instance=def.create(services);
|
|
26
|
+
if(!instance||typeof instance.tools!=='function'
|
|
27
|
+
||typeof instance.call!=='function')throw fail('MCP_PROVIDER_INVALID');
|
|
28
|
+
instances.push({id:def.id,instance});
|
|
29
|
+
}
|
|
30
|
+
const active=()=>{
|
|
31
|
+
const byName=new Map(),listed=[];
|
|
32
|
+
for(const {id,instance} of instances){
|
|
33
|
+
const tools=instance.tools();
|
|
34
|
+
if(!Array.isArray(tools))throw fail('MCP_TOOL_LIST_INVALID');
|
|
35
|
+
const localNames=new Set();
|
|
36
|
+
for(const tool of tools){
|
|
37
|
+
if(!tool||!validName(tool.name)||owners.get(tool.name)!==id
|
|
38
|
+
||localNames.has(tool.name)||byName.has(tool.name)
|
|
39
|
+
||!tool.inputSchema||typeof tool.description!=='string'
|
|
40
|
+
||Object.hasOwn(tool,'_meta'))
|
|
41
|
+
throw fail('MCP_TOOL_LIST_INVALID');
|
|
42
|
+
localNames.add(tool.name);
|
|
43
|
+
byName.set(tool.name,instance);
|
|
44
|
+
listed.push(tool);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return {listed,byName};
|
|
48
|
+
};
|
|
49
|
+
return Object.freeze({
|
|
50
|
+
list(){return active().listed;},
|
|
51
|
+
async call(name,args){
|
|
52
|
+
const instance=active().byName.get(name);
|
|
53
|
+
if(!instance)return failure('UNKNOWN_TOOL');
|
|
54
|
+
const value=await instance.call(name,args);
|
|
55
|
+
if(!value||typeof value!=='object'||!Array.isArray(value.content))
|
|
56
|
+
throw fail('MCP_PROVIDER_RESULT_INVALID');
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Owner-liveness checks belong to the release safety boundary, not to
|
|
2
|
+
// install staging or npm metadata. No service is started by these probes.
|
|
3
|
+
import {spawnSync} from 'node:child_process';
|
|
4
|
+
import {existsSync} from 'node:fs';
|
|
5
|
+
const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
6
|
+
|
|
7
|
+
// The manager's RUNNING status is not sufficient for a safe cutover:
|
|
8
|
+
// Desktop Commander may still own long-running shell sessions. Never stop
|
|
9
|
+
// the old Supervisor while its tool process has live child commands.
|
|
10
|
+
export function activeDesktopCommands(oldStatus){
|
|
11
|
+
const dc=oldStatus?.results?.find(x=>x.toolId==='desktop-commander');
|
|
12
|
+
if(!dc?.pid){
|
|
13
|
+
// Release tests use a fake old CLI; production must provide real PID.
|
|
14
|
+
if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return [];
|
|
15
|
+
throw Object.assign(Error('TOOL_PROCESS_ID_UNVERIFIED'),
|
|
16
|
+
{code:'TOOL_PROCESS_ID_UNVERIFIED'});
|
|
17
|
+
}
|
|
18
|
+
if(!Number.isSafeInteger(dc.pid)||dc.pid<=1)
|
|
19
|
+
throw Object.assign(Error('TOOL_PROCESS_ID_UNVERIFIED'),
|
|
20
|
+
{code:'TOOL_PROCESS_ID_UNVERIFIED'});
|
|
21
|
+
if(process.platform==='win32')
|
|
22
|
+
throw Object.assign(Error('ACTIVE_COMMAND_PREFLIGHT_UNSUPPORTED'),
|
|
23
|
+
{code:'ACTIVE_COMMAND_PREFLIGHT_UNSUPPORTED'});
|
|
24
|
+
const check=spawnSync('ps',['-axo','pid=,ppid=,stat='],
|
|
25
|
+
{encoding:'utf8',timeout:4500,maxBuffer:3*1024*1024});
|
|
26
|
+
if(check.error||check.status!==0)
|
|
27
|
+
throw Object.assign(Error('ACTIVE_COMMAND_PREFLIGHT_UNVERIFIED'),
|
|
28
|
+
{code:'ACTIVE_COMMAND_PREFLIGHT_UNVERIFIED'});
|
|
29
|
+
return check.stdout.split('\n').map(line=>line.trim().split(/\s+/))
|
|
30
|
+
.filter(x=>x.length===3&&Number(x[1])===dc.pid&&!x[2].startsWith('Z'))
|
|
31
|
+
.map(x=>Number(x[0]));
|
|
32
|
+
}
|
|
33
|
+
export async function awaitStopped(entry,opts={}){
|
|
34
|
+
// A completed stop is verified by the former owner's lock disappearing.
|
|
35
|
+
const p=opts.lockPath;
|
|
36
|
+
for(let i=0;i<80;i++){
|
|
37
|
+
if(!existsSync(p))return;
|
|
38
|
+
await delay(100);
|
|
39
|
+
}
|
|
40
|
+
throw Object.assign(Error('OWNER_STILL_RUNNING'),{code:'OWNER_STILL_RUNNING'});
|
|
41
|
+
}
|
package/lib/release.mjs
CHANGED
|
@@ -1,12 +1,94 @@
|
|
|
1
1
|
// Owner-verified stop-and-start upgrade. Failure is reported, never auto-rolled back.
|
|
2
|
-
import {spawn
|
|
2
|
+
import {spawn} from 'node:child_process';
|
|
3
3
|
import {randomUUID,createHash} from 'node:crypto';
|
|
4
|
-
import {existsSync,readFileSync,writeFileSync,openSync,closeSync,unlinkSync,mkdirSync,renameSync,lstatSync,rmSync} from 'node:fs';
|
|
4
|
+
import {existsSync,readFileSync,readdirSync,writeFileSync,openSync,closeSync,unlinkSync,mkdirSync,renameSync,lstatSync,rmSync} from 'node:fs';
|
|
5
5
|
import {homedir,userInfo} from 'node:os';
|
|
6
6
|
import {join,dirname,delimiter} from 'node:path';
|
|
7
|
-
|
|
7
|
+
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
8
|
+
// Private modules never import or resolve another private implementation.
|
|
9
|
+
let PACKAGE_VERSION, activeDesktopCommands, awaitStopped;
|
|
10
|
+
let connected=false;
|
|
11
|
+
export function configureRelease(ports){
|
|
12
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
13
|
+
for(const name of ['PACKAGE_VERSION', 'activeDesktopCommands', 'awaitStopped'])
|
|
14
|
+
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
15
|
+
({PACKAGE_VERSION, activeDesktopCommands, awaitStopped}=ports);
|
|
16
|
+
connected=true;
|
|
17
|
+
}
|
|
18
|
+
|
|
8
19
|
|
|
9
20
|
const name='@tomflow/chatloop-tools';
|
|
21
|
+
// Every file owned by the candidate Tools package is fingerprinted, so a
|
|
22
|
+
// Provider can import its own helper modules without updating this list.
|
|
23
|
+
// Bundled dependencies retain independent identity/entrypoint checks.
|
|
24
|
+
const BUNDLED_SDK_FINGERPRINT_FILES=Object.freeze([
|
|
25
|
+
'node_modules/@tomflow/chatloop-context/bin/cli.mjs',
|
|
26
|
+
'node_modules/@tomflow/chatloop-context/index.mjs',
|
|
27
|
+
'node_modules/@tomflow/chatloop-trace/index.mjs'
|
|
28
|
+
]);
|
|
29
|
+
function packageSourceFiles(installed){
|
|
30
|
+
const files=[];
|
|
31
|
+
const scan=prefix=>{
|
|
32
|
+
for(const entry of readdirSync(join(installed,prefix)).sort()){
|
|
33
|
+
if(!prefix&&entry==='node_modules')continue;
|
|
34
|
+
const relative=prefix?prefix+'/'+entry:entry;
|
|
35
|
+
const state=lstatSync(join(installed,relative));
|
|
36
|
+
if(state.isSymbolicLink()||!state.isFile()&&!state.isDirectory())
|
|
37
|
+
throw Object.assign(Error('RELEASE_SOURCE_UNTRUSTED'),{
|
|
38
|
+
code:'RELEASE_SOURCE_UNTRUSTED'});
|
|
39
|
+
if(state.isDirectory())scan(relative);
|
|
40
|
+
else files.push(relative);
|
|
41
|
+
if(files.length>1000)
|
|
42
|
+
throw Object.assign(Error('RELEASE_SOURCE_TOO_LARGE'),{
|
|
43
|
+
code:'RELEASE_SOURCE_TOO_LARGE'});
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
scan('');
|
|
47
|
+
if(!files.includes('index.mjs')||!files.includes('bin/cli.mjs')||
|
|
48
|
+
!files.includes('bin/supervisor.mjs')||
|
|
49
|
+
!files.includes('providers.generated.mjs')||
|
|
50
|
+
!files.includes('lib/mcp-tool-router.mjs')||
|
|
51
|
+
!files.includes('lib/gateway.mjs'))
|
|
52
|
+
throw Object.assign(Error('RELEASE_SOURCE_INCOMPLETE'),{
|
|
53
|
+
code:'RELEASE_SOURCE_INCOMPLETE'});
|
|
54
|
+
return files;
|
|
55
|
+
}
|
|
56
|
+
// A candidate can contain NEW providers absent from the currently running
|
|
57
|
+
// Tools version. Derive the fingerprint inventory from the staged candidate,
|
|
58
|
+
// never from the old process's own Provider manifest.
|
|
59
|
+
function releaseFingerprintFiles(installed){
|
|
60
|
+
const manifest=readFileSync(join(installed,'providers.generated.mjs'),'utf8');
|
|
61
|
+
if(manifest.length>32768)
|
|
62
|
+
throw Object.assign(Error('RELEASE_PROVIDER_MANIFEST_INVALID'),{
|
|
63
|
+
code:'RELEASE_PROVIDER_MANIFEST_INVALID'});
|
|
64
|
+
const match=manifest.match(/^export const providerFiles=Object\.freeze\((\[[^\r\n]*\])\);$/m);
|
|
65
|
+
let files;
|
|
66
|
+
try{files=JSON.parse(match?.[1]||'null')}catch{}
|
|
67
|
+
if(!Array.isArray(files)||files.length<1||files.length>128||
|
|
68
|
+
files.some(path=>typeof path!=='string'||
|
|
69
|
+
!/^providers\/[a-z][a-z0-9-]*\.mjs$/.test(path))||
|
|
70
|
+
new Set(files).size!==files.length)
|
|
71
|
+
throw Object.assign(Error('RELEASE_PROVIDER_MANIFEST_INVALID'),{
|
|
72
|
+
code:'RELEASE_PROVIDER_MANIFEST_INVALID'});
|
|
73
|
+
// This exact compiler format ensures the declared files are precisely the
|
|
74
|
+
// modules the staged code will import. No additional executable imports.
|
|
75
|
+
const relativeImportPrefix='.'+'/';
|
|
76
|
+
const expected='// GENERATED by scripts/build-providers.mjs — never edit.\n'+
|
|
77
|
+
files.map((file,i)=>"import {provider as p"+i+"} from '"+
|
|
78
|
+
relativeImportPrefix+file+"';")
|
|
79
|
+
.join('\n')+
|
|
80
|
+
'\nexport const providerDefinitions=Object.freeze(['+
|
|
81
|
+
files.map((_,i)=>'p'+i).join(',')+']);\n'+
|
|
82
|
+
'export const providerFiles=Object.freeze('+JSON.stringify(files)+');\n';
|
|
83
|
+
if(manifest!==expected)
|
|
84
|
+
throw Object.assign(Error('RELEASE_PROVIDER_MANIFEST_INVALID'),{
|
|
85
|
+
code:'RELEASE_PROVIDER_MANIFEST_INVALID'});
|
|
86
|
+
const sourceFiles=packageSourceFiles(installed);
|
|
87
|
+
if(files.some(file=>!sourceFiles.includes(file)))
|
|
88
|
+
throw Object.assign(Error('RELEASE_PROVIDER_MISSING'),{
|
|
89
|
+
code:'RELEASE_PROVIDER_MISSING'});
|
|
90
|
+
return [...sourceFiles,...BUNDLED_SDK_FINGERPRINT_FILES];
|
|
91
|
+
}
|
|
10
92
|
const entryIn=prefix=>join(prefix,'node_modules','@tomflow','chatloop-tools','bin','cli.mjs');
|
|
11
93
|
const runtimeRoot=()=>join(homedir(),'.chat-loop');
|
|
12
94
|
// An external MCP or test shell may still inherit an isolated HOME. The
|
|
@@ -27,7 +109,6 @@ function checkedUpgradeBase(options){
|
|
|
27
109
|
}catch{return null}
|
|
28
110
|
}
|
|
29
111
|
const readJson=path=>JSON.parse(readFileSync(path,'utf8'));
|
|
30
|
-
const delay=ms=>new Promise(r=>setTimeout(r,ms));
|
|
31
112
|
const safeVersion=v=>/^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?$/.test(v);
|
|
32
113
|
const quote=s=>JSON.stringify(s);
|
|
33
114
|
const freshResult=(status,extra={})=>({command:'upgrade',status,version:PACKAGE_VERSION,...extra});
|
|
@@ -61,8 +142,10 @@ function run(bin,args,opts={}){
|
|
|
61
142
|
return new Promise((resolve,reject)=>{
|
|
62
143
|
const child=spawn(bin,args,{env:opts.env||process.env,stdio:['ignore','pipe','pipe'],windowsHide:true});
|
|
63
144
|
let stdout='',stderr='';
|
|
64
|
-
child.stdout.
|
|
65
|
-
child.stderr.
|
|
145
|
+
child.stdout.setEncoding('utf8');
|
|
146
|
+
child.stderr.setEncoding('utf8');
|
|
147
|
+
child.stdout.on('data',x=>stdout+=x);
|
|
148
|
+
child.stderr.on('data',x=>stderr+=x.slice(0,2048));
|
|
66
149
|
child.once('error',reject);
|
|
67
150
|
child.once('close',code=>code===0?resolve(stdout):reject(Object.assign(Error('COMMAND_FAILED'),{
|
|
68
151
|
code:'COMMAND_FAILED',command:args[0],status:code,stdout,detail:stderr.slice(-300)})));
|
|
@@ -75,41 +158,6 @@ async function cli(entry,action,opts={}){
|
|
|
75
158
|
try{return JSON.parse(raw.trim());}
|
|
76
159
|
catch{throw Object.assign(Error('INVALID_CLI_REPLY'),{code:'INVALID_CLI_REPLY'});}
|
|
77
160
|
}
|
|
78
|
-
// The manager's RUNNING status is not sufficient for a safe cutover:
|
|
79
|
-
// Desktop Commander may still own long-running shell sessions. Never stop
|
|
80
|
-
// the old Supervisor while its tool process has live child commands.
|
|
81
|
-
function activeDesktopCommands(oldStatus){
|
|
82
|
-
const dc=oldStatus?.results?.find(x=>x.toolId==='desktop-commander');
|
|
83
|
-
if(!dc?.pid){
|
|
84
|
-
// Release tests use a fake old CLI; production must provide real PID.
|
|
85
|
-
if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return [];
|
|
86
|
-
throw Object.assign(Error('TOOL_PROCESS_ID_UNVERIFIED'),
|
|
87
|
-
{code:'TOOL_PROCESS_ID_UNVERIFIED'});
|
|
88
|
-
}
|
|
89
|
-
if(!Number.isSafeInteger(dc.pid)||dc.pid<=1)
|
|
90
|
-
throw Object.assign(Error('TOOL_PROCESS_ID_UNVERIFIED'),
|
|
91
|
-
{code:'TOOL_PROCESS_ID_UNVERIFIED'});
|
|
92
|
-
if(process.platform==='win32')
|
|
93
|
-
throw Object.assign(Error('ACTIVE_COMMAND_PREFLIGHT_UNSUPPORTED'),
|
|
94
|
-
{code:'ACTIVE_COMMAND_PREFLIGHT_UNSUPPORTED'});
|
|
95
|
-
const check=spawnSync('ps',['-axo','pid=,ppid=,stat='],
|
|
96
|
-
{encoding:'utf8',timeout:4500,maxBuffer:3*1024*1024});
|
|
97
|
-
if(check.error||check.status!==0)
|
|
98
|
-
throw Object.assign(Error('ACTIVE_COMMAND_PREFLIGHT_UNVERIFIED'),
|
|
99
|
-
{code:'ACTIVE_COMMAND_PREFLIGHT_UNVERIFIED'});
|
|
100
|
-
return check.stdout.split('\n').map(line=>line.trim().split(/\s+/))
|
|
101
|
-
.filter(x=>x.length===3&&Number(x[1])===dc.pid&&!x[2].startsWith('Z'))
|
|
102
|
-
.map(x=>Number(x[0]));
|
|
103
|
-
}
|
|
104
|
-
async function awaitStopped(entry,opts={}){
|
|
105
|
-
// A completed stop is verified by the former owner's lock disappearing.
|
|
106
|
-
const p=opts.lockPath;
|
|
107
|
-
for(let i=0;i<80;i++){
|
|
108
|
-
if(!existsSync(p))return;
|
|
109
|
-
await delay(100);
|
|
110
|
-
}
|
|
111
|
-
throw Object.assign(Error('OWNER_STILL_RUNNING'),{code:'OWNER_STILL_RUNNING'});
|
|
112
|
-
}
|
|
113
161
|
export function runtimeNeedsUpgrade(base=runtimeRoot(),version=PACKAGE_VERSION){
|
|
114
162
|
const p=upgradeLayout(base,version);
|
|
115
163
|
const runtime=existsSync(p.current)?readJson(p.current):null;
|
|
@@ -195,14 +243,8 @@ export async function prepareReleaseCandidate(options={}){
|
|
|
195
243
|
const tunnel=await cli(proposedEntry,['tunnel','doctor']);
|
|
196
244
|
if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
|
|
197
245
|
return freshResult('BLOCKED',{code:'STAGE_TUNNEL_NOT_READY'});
|
|
198
|
-
const files=[
|
|
199
|
-
'bin/cli.mjs','lib/supervisor.mjs','lib/context-gateway.mjs',
|
|
200
|
-
'node_modules/@tomflow/chatloop-context/bin/cli.mjs',
|
|
201
|
-
'node_modules/@tomflow/chatloop-context/lib/operations.mjs',
|
|
202
|
-
'node_modules/@tomflow/chatloop-trace/lib/trace.mjs'
|
|
203
|
-
];
|
|
204
246
|
const fingerprints={};
|
|
205
|
-
for(const name of
|
|
247
|
+
for(const name of releaseFingerprintFiles(installed)){
|
|
206
248
|
const file=join(installed,name),st=lstatSync(file);
|
|
207
249
|
if(!st.isFile()||st.isSymbolicLink())
|
|
208
250
|
return freshResult('BLOCKED',{code:'STAGE_FILE_UNTRUSTED'});
|
|
@@ -243,7 +285,10 @@ export function verifyPreparedRelease(base,version=PACKAGE_VERSION){
|
|
|
243
285
|
if(manifest.name!==name||manifest.version!==p.version)
|
|
244
286
|
return {ok:false,code:'STAGE_VERSION_MISMATCH'};
|
|
245
287
|
const entries=Object.entries(evidence.fingerprints??{});
|
|
246
|
-
|
|
288
|
+
const required=releaseFingerprintFiles(installed);
|
|
289
|
+
if(entries.length!==required.length
|
|
290
|
+
||!required.every(relative=>Object.hasOwn(evidence.fingerprints,relative)))
|
|
291
|
+
return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'};
|
|
247
292
|
for(const [relative,sha] of entries){
|
|
248
293
|
if(!/^[a-f0-9]{64}$/.test(sha)||relative.startsWith('/')||
|
|
249
294
|
relative.split('/').includes('..'))
|