@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.
- package/README.md +117 -127
- package/bin/cli.mjs +48 -38
- package/bin/supervisor.mjs +4 -0
- package/index.mjs +238 -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 +12 -1
- package/lib/trace-observation.mjs +118 -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 -1615
- 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/index.mjs
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// Sole npm SDK entry and composition root for Chat Loop Tools.
|
|
2
|
+
// Modules declare named API ports. No lib module imports another lib module.
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {subscribeContextApiLog} from '@tomflow/chatloop-context';
|
|
5
|
+
import {subscribeTraceApiLog} from '@tomflow/chatloop-trace';
|
|
6
|
+
import {providerDefinitions} from './providers.generated.mjs';
|
|
7
|
+
import {createMcpToolRouter} from './lib/mcp-tool-router.mjs';
|
|
8
|
+
import {createCliCommandRouter} from './lib/cli-command-router.mjs';
|
|
9
|
+
import {createApiAspect} from './lib/api-aspect.mjs';
|
|
10
|
+
// One bounded SDK/CLI/MCP side channel; the Supervisor is the only writer.
|
|
11
|
+
// Cold-start observations are held until the port is composed, never on an
|
|
12
|
+
// API's business execution stack.
|
|
13
|
+
let auditPort=null;
|
|
14
|
+
const auditBacklog=[];
|
|
15
|
+
const recordApi=event=>{
|
|
16
|
+
if(!auditPort){
|
|
17
|
+
if(auditBacklog.length<1024)auditBacklog.push(event);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
try{const pending=auditPort(event);
|
|
21
|
+
if(pending&&typeof pending.then==='function')Promise.resolve(pending).catch(()=>{});
|
|
22
|
+
}catch{/* Never let telemetry alter an SDK or CLI call. */}
|
|
23
|
+
};
|
|
24
|
+
const apiAspect=createApiAspect('@tomflow/chatloop-tools',{sink:recordApi});
|
|
25
|
+
// The CLI and Supervisor executable import only this package root.
|
|
26
|
+
let runtimePromise;
|
|
27
|
+
async function runtime(){
|
|
28
|
+
if(!runtimePromise)runtimePromise=(async()=>{
|
|
29
|
+
const [control,fixture,mcpChild,tunnelAdapter,adapters,tunnel,tunnelAuth,
|
|
30
|
+
contextAuth,contextRun,extensionContract,extensionCliContract,
|
|
31
|
+
extensionProxy,contextGateway,releasePreflight,release,
|
|
32
|
+
traceGateway,traceObservation,
|
|
33
|
+
terminalPolicy,gateway,supervisor]=await Promise.all([
|
|
34
|
+
import('./lib/control.mjs'),
|
|
35
|
+
import('./lib/adapters/fixture.mjs'),
|
|
36
|
+
import('./lib/adapters/mcp-child.mjs'),
|
|
37
|
+
import('./lib/adapters/tunnel.mjs'),
|
|
38
|
+
import('./lib/adapters/index.mjs'),
|
|
39
|
+
import('./lib/tunnel.mjs'),
|
|
40
|
+
import('./lib/tunnel-auth.mjs'),
|
|
41
|
+
import('./lib/context-control-auth.mjs'),
|
|
42
|
+
import('./lib/context-control-run.mjs'),
|
|
43
|
+
import('./providers/extension.mjs'),
|
|
44
|
+
import('./lib/extension-cli-contract.mjs'),
|
|
45
|
+
import('./lib/extension-proxy.mjs'),
|
|
46
|
+
import('./lib/context-gateway.mjs'),
|
|
47
|
+
import('./lib/release-owner-preflight.mjs'),
|
|
48
|
+
import('./lib/release.mjs'),
|
|
49
|
+
import('./lib/trace-gateway.mjs'),
|
|
50
|
+
import('./lib/trace-observation.mjs'),
|
|
51
|
+
import('./lib/terminal-app-policy.mjs'),
|
|
52
|
+
import('./lib/gateway.mjs'),
|
|
53
|
+
import('./lib/supervisor-runtime.mjs')
|
|
54
|
+
]);
|
|
55
|
+
// Concrete dependencies are visible and centrally controlled here.
|
|
56
|
+
// Preserve the existing synchronous Tunnel doctor/locator contract.
|
|
57
|
+
// The SDK composition itself is already async, so resolve the optional
|
|
58
|
+
// provider root once, without touching any binary or spawning a process.
|
|
59
|
+
const currentPlatform=process.platform+'-'+process.arch;
|
|
60
|
+
let platformProvider=null,providerError=null;
|
|
61
|
+
if(['darwin-x64','darwin-arm64'].includes(currentPlatform)){
|
|
62
|
+
try{
|
|
63
|
+
platformProvider=currentPlatform==='darwin-x64'
|
|
64
|
+
?await import('@tomflow/chatloop-tunnel-darwin-x64')
|
|
65
|
+
:await import('@tomflow/chatloop-tunnel-darwin-arm64');
|
|
66
|
+
}catch(error){providerError=error;}
|
|
67
|
+
}
|
|
68
|
+
// Trace and platform carrier SDKs are independent publishers. Their
|
|
69
|
+
// non-authoritative observation ports join the existing Supervisor sink.
|
|
70
|
+
// The Trace writer's own writes must not audit themselves recursively.
|
|
71
|
+
subscribeTraceApiLog(event=>{
|
|
72
|
+
// Supervisor __ping reads Writer.health. Recording that read would
|
|
73
|
+
// ping again forever; writer methods are the audit transport itself.
|
|
74
|
+
if(['writer.record','writer.recordControl','writer.health']
|
|
75
|
+
.includes(event.api))return;
|
|
76
|
+
recordApi(event);
|
|
77
|
+
});
|
|
78
|
+
if(typeof platformProvider?.subscribeTunnelApiLog==='function')
|
|
79
|
+
platformProvider.subscribeTunnelApiLog(recordApi);
|
|
80
|
+
tunnel.configureTunnelProvider({
|
|
81
|
+
loadPlatformBundle:platform=>{
|
|
82
|
+
if(platform!==currentPlatform)
|
|
83
|
+
throw Object.assign(Error('Wrong tunnel platform'),{code:'UNSUPPORTED_PLATFORM'});
|
|
84
|
+
if(providerError)
|
|
85
|
+
throw Object.assign(Error('Tunnel npm platform provider unavailable'),
|
|
86
|
+
{code:'TUNNEL_PROVIDER_UNAVAILABLE'});
|
|
87
|
+
if(!platformProvider)
|
|
88
|
+
throw Object.assign(Error('Tunnel platform provider unavailable'),
|
|
89
|
+
{code:'TUNNEL_PROVIDER_UNAVAILABLE'});
|
|
90
|
+
return platformProvider;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
mcpChild.configureMcpChild({paths:control.paths,
|
|
94
|
+
toolCallDeadlineMs:control.toolCallDeadlineMs,
|
|
95
|
+
PACKAGE_VERSION:control.PACKAGE_VERSION});
|
|
96
|
+
tunnelAdapter.configureTunnelAdapter({paths:control.paths,
|
|
97
|
+
bundledTunnel:tunnel.bundledTunnel});
|
|
98
|
+
adapters.configureAdapterFactory({
|
|
99
|
+
createFixtureAdapter:fixture.createFixtureAdapter,
|
|
100
|
+
createMcpChildAdapter:mcpChild.createMcpChildAdapter,
|
|
101
|
+
createTunnelAdapter:tunnelAdapter.createTunnelAdapter});
|
|
102
|
+
contextAuth.configureContextControlAuth({
|
|
103
|
+
ensurePrivateDir:control.ensurePrivateDir,paths:control.paths});
|
|
104
|
+
contextRun.configureContextControlRun({
|
|
105
|
+
verifyContextEnvelope:contextAuth.verifyContextEnvelope});
|
|
106
|
+
extensionProxy.configureExtensionProxy({
|
|
107
|
+
extensionCommand:extensionContract.extensionCommand,
|
|
108
|
+
validExtensionArgs:extensionContract.validExtensionArgs,
|
|
109
|
+
isControlTool:extensionContract.isControlTool,
|
|
110
|
+
acceptExtensionCliReceipt:extensionCliContract.acceptExtensionCliReceipt,
|
|
111
|
+
extensionTools:extensionContract.extensionTools});
|
|
112
|
+
release.configureRelease({PACKAGE_VERSION:control.PACKAGE_VERSION,
|
|
113
|
+
activeDesktopCommands:releasePreflight.activeDesktopCommands,
|
|
114
|
+
awaitStopped:releasePreflight.awaitStopped});
|
|
115
|
+
traceGateway.configureTraceGateway({paths:control.paths,
|
|
116
|
+
talk:control.talk,CONTRACT:control.CONTRACT});
|
|
117
|
+
contextGateway.configureContextApiLog({
|
|
118
|
+
current:apiAspect.current,
|
|
119
|
+
record:entry=>control.talk({
|
|
120
|
+
contract:control.CONTRACT,action:'__trace_observation',...entry
|
|
121
|
+
},900)
|
|
122
|
+
});
|
|
123
|
+
// Same-process Gateway validators use the identical Context SDK hook.
|
|
124
|
+
// Child CLI events are forwarded by context-gateway after stdout settles.
|
|
125
|
+
subscribeContextApiLog(event=>contextGateway.forwardContextApiLog(event));
|
|
126
|
+
// One statically generated provider composition, shared by tools/list and
|
|
127
|
+
// tools/call. Adding an independent provider never edits this Gateway.
|
|
128
|
+
const coreToolRouter=createMcpToolRouter(providerDefinitions,{
|
|
129
|
+
control,release,terminal:terminalPolicy,context:contextGateway,
|
|
130
|
+
trace:traceGateway,
|
|
131
|
+
extension:{
|
|
132
|
+
forwardExtensionAction:extensionProxy.forwardExtensionAction,
|
|
133
|
+
observeExtensionResult:traceGateway.observeExtensionResult
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
// The same immutable MCP boundary observes every published tool,
|
|
137
|
+
// including future Provider additions. The independent sink can fail,
|
|
138
|
+
// disconnect or lag without delaying a tool reply or replaying an action.
|
|
139
|
+
auditPort=event=>control.talk({
|
|
140
|
+
contract:control.CONTRACT,action:'__api_observation',
|
|
141
|
+
requestId:randomUUID(),callId:event.callId,
|
|
142
|
+
traceId:event.traceId,spanId:event.spanId,
|
|
143
|
+
...(event.parentSpanId?{parentSpanId:event.parentSpanId}:{}),
|
|
144
|
+
apiName:event.package==='@tomflow/chatloop-trace'
|
|
145
|
+
?'trace.'+event.api
|
|
146
|
+
:event.package?.startsWith('@tomflow/chatloop-tunnel-')
|
|
147
|
+
?'tunnel.'+event.api
|
|
148
|
+
:event.surface==='mcp'?event.api
|
|
149
|
+
:'tools.'+event.surface+'.'+event.api,
|
|
150
|
+
phase:event.phase,
|
|
151
|
+
...(event.durationMs!==null?{durationMs:event.durationMs}:{}),
|
|
152
|
+
...(event.errorCode?{errorCode:event.errorCode}:{})
|
|
153
|
+
},900);
|
|
154
|
+
for(const entry of auditBacklog.splice(0))recordApi(entry);
|
|
155
|
+
const mcpAudit=createApiAspect('@tomflow/chatloop-tools',
|
|
156
|
+
{sink:recordApi});
|
|
157
|
+
const callCache=new Map();
|
|
158
|
+
const toolRouter=Object.freeze({
|
|
159
|
+
list:mcpAudit.observe('mcp.tools.list',coreToolRouter.list,'mcp'),
|
|
160
|
+
call(name,args){
|
|
161
|
+
const label=typeof name==='string'&&
|
|
162
|
+
/^[a-z][A-Za-z0-9_.:-]{1,119}$/.test(name)?name:'invalid';
|
|
163
|
+
if(!callCache.has(label))
|
|
164
|
+
callCache.set(label,mcpAudit.observe('mcp.'+label,
|
|
165
|
+
coreToolRouter.call,'mcp'));
|
|
166
|
+
return callCache.get(label)(name,args);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
gateway.configureGateway({
|
|
170
|
+
CONTRACT:control.CONTRACT,PACKAGE_VERSION:control.PACKAGE_VERSION,
|
|
171
|
+
toolRouter,
|
|
172
|
+
// MCP handshake / rejected protocol requests do not reach toolRouter.
|
|
173
|
+
// Keep them inside the same isolated Supervisor observation channel.
|
|
174
|
+
observeProtocol:(method,execute)=>{
|
|
175
|
+
const name=method==='initialize'?'initialize'
|
|
176
|
+
:method==='ping'?'ping'
|
|
177
|
+
:method==='server/discover'?'server_discover'
|
|
178
|
+
:method==='tools/list'?'tools_list_denied'
|
|
179
|
+
:method==='tools/call'?'tools_call_denied':'unknown';
|
|
180
|
+
return mcpAudit.observe('mcp.protocol.'+name,execute,'mcp')();
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
supervisor.configureSupervisor({
|
|
184
|
+
CONTRACT:control.CONTRACT,VERSION:control.VERSION,
|
|
185
|
+
PACKAGE_VERSION:control.PACKAGE_VERSION,
|
|
186
|
+
registry:control.registry,paths:control.paths,
|
|
187
|
+
ensurePrivateDir:control.ensurePrivateDir,ACTIONS:control.ACTIONS,
|
|
188
|
+
createAdapter:adapters.createAdapter,
|
|
189
|
+
createSupervisorTraceBridge:traceObservation.createSupervisorTraceBridge,
|
|
190
|
+
loadContextControlSecret:contextAuth.loadContextControlSecret,
|
|
191
|
+
handleContextControl:contextRun.handleContextControl
|
|
192
|
+
});
|
|
193
|
+
return Object.freeze({control,tunnel,tunnelAuth,release,gateway,supervisor});
|
|
194
|
+
})();
|
|
195
|
+
return runtimePromise;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Public SDK entry with explicitly separated runtime roles.
|
|
199
|
+
async function loadToolsCliCore(){
|
|
200
|
+
const {control,tunnel,tunnelAuth,release,gateway}=await runtime();
|
|
201
|
+
return apiAspect.methods(Object.freeze({
|
|
202
|
+
cliExtensions:apiAspect.methods(createCliCommandRouter(providerDefinitions),
|
|
203
|
+
'cliExtensions','cli'),
|
|
204
|
+
lifecycleDeadlineMs:control.lifecycleDeadlineMs,
|
|
205
|
+
CONTRACT:control.CONTRACT,ACTIONS:control.ACTIONS,
|
|
206
|
+
registry:control.registry,ensurePrivateDir:control.ensurePrivateDir,
|
|
207
|
+
safeFallback:control.safeFallback,
|
|
208
|
+
recoverStaleLock:control.recoverStaleLock,
|
|
209
|
+
exitCode:control.exitCode,talk:control.talk,
|
|
210
|
+
runGateway:gateway.runGateway,
|
|
211
|
+
// One CLI dispatch boundary covers built-in and Provider commands.
|
|
212
|
+
// A dispatch acknowledgement is not a successful business receipt.
|
|
213
|
+
observeCliCommand:(name,invoke)=>{
|
|
214
|
+
const label=typeof name==='string'&&/^[a-z][a-z0-9-]{0,78}$/.test(name)
|
|
215
|
+
?name:'invalid';
|
|
216
|
+
return apiAspect.observe('cli.dispatch.'+label,invoke,'cli')();
|
|
217
|
+
},
|
|
218
|
+
apiUsage:({windowMinutes=60,limit=100}={})=>control.talk({
|
|
219
|
+
contract:control.CONTRACT,action:'__api_usage',requestId:randomUUID(),
|
|
220
|
+
windowMinutes,limit
|
|
221
|
+
},9000),
|
|
222
|
+
tunnelDoctor:tunnel.tunnelDoctor,runTunnel:tunnel.runTunnel,
|
|
223
|
+
promptTunnelRuntimeKey:tunnelAuth.promptTunnelRuntimeKey,
|
|
224
|
+
storeTunnelRuntimeKey:tunnelAuth.storeTunnelRuntimeKey,
|
|
225
|
+
upgradeRuntime:release.upgradeRuntime,
|
|
226
|
+
runtimeNeedsUpgrade:release.runtimeNeedsUpgrade,
|
|
227
|
+
prepareReleaseCandidate:release.prepareReleaseCandidate
|
|
228
|
+
}), 'tools','sdk');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// SDK role for the internal Native/Supervisor executable under bin/.
|
|
232
|
+
async function runToolsSupervisorCore(){
|
|
233
|
+
const {supervisor}=await runtime();
|
|
234
|
+
return supervisor.runSupervisor();
|
|
235
|
+
}
|
|
236
|
+
export const loadToolsCli=apiAspect.observe('loadToolsCli',loadToolsCliCore);
|
|
237
|
+
export const runToolsSupervisor=apiAspect.observe('runToolsSupervisor',
|
|
238
|
+
runToolsSupervisorCore);
|
package/lib/adapters/fixture.mjs
CHANGED
|
@@ -53,9 +53,10 @@ async function launch(tool,ctx){
|
|
|
53
53
|
const startup=new Promise(resolve=>{ready=resolve;});
|
|
54
54
|
const startupLimit=limit(ctx,1400);
|
|
55
55
|
const startupTimer=setTimeout(()=>ready(false),startupLimit);
|
|
56
|
+
child.stdout.setEncoding('utf8');
|
|
56
57
|
child.stdout.on('data',chunk=>{
|
|
57
|
-
buffer+=chunk
|
|
58
|
-
if(buffer
|
|
58
|
+
buffer+=chunk;
|
|
59
|
+
if(Buffer.byteLength(buffer,'utf8')>32768){buffer='';return;}
|
|
59
60
|
let n;
|
|
60
61
|
while((n=buffer.indexOf('\n'))!==-1){
|
|
61
62
|
let msg;try{msg=JSON.parse(buffer.slice(0,n));}catch{buffer=buffer.slice(n+1);continue;}
|
package/lib/adapters/index.mjs
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
import
|
|
3
|
-
|
|
1
|
+
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
2
|
+
// Private modules never import or resolve another private implementation.
|
|
3
|
+
let createFixtureAdapter, createMcpChildAdapter, createTunnelAdapter;
|
|
4
|
+
let connected=false;
|
|
5
|
+
export function configureAdapterFactory(ports){
|
|
6
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
7
|
+
for(const name of ['createFixtureAdapter', 'createMcpChildAdapter', 'createTunnelAdapter'])
|
|
8
|
+
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
9
|
+
({createFixtureAdapter, createMcpChildAdapter, createTunnelAdapter}=ports);
|
|
10
|
+
connected=true;
|
|
11
|
+
}
|
|
12
|
+
|
|
4
13
|
|
|
5
|
-
const factories=new Map([
|
|
14
|
+
const factories=()=>new Map([
|
|
6
15
|
['fixture',createFixtureAdapter],
|
|
7
16
|
['mcp-child',createMcpChildAdapter],
|
|
8
17
|
['tunnel',createTunnelAdapter]
|
|
9
18
|
]);
|
|
10
19
|
// Register future tool kinds here; Supervisor does not know concrete tools.
|
|
11
20
|
export function createAdapter(kind,ctx){
|
|
12
|
-
const factory=factories.get(kind);
|
|
21
|
+
const factory=factories().get(kind);
|
|
13
22
|
if(!factory)throw Object.assign(new Error('No adapter for tool kind'),{code:'ADAPTER_NOT_IMPLEMENTED'});
|
|
14
23
|
return factory(ctx);
|
|
15
24
|
}
|
|
@@ -4,7 +4,18 @@ import {dirname,join,isAbsolute} from 'node:path';
|
|
|
4
4
|
import {readFileSync} from 'node:fs';
|
|
5
5
|
import {randomUUID} from 'node:crypto';
|
|
6
6
|
import {userInfo} from 'node:os';
|
|
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 paths, toolCallDeadlineMs, PACKAGE_VERSION;
|
|
10
|
+
let connected=false;
|
|
11
|
+
export function configureMcpChild(ports){
|
|
12
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
13
|
+
for(const name of ['paths', 'toolCallDeadlineMs', 'PACKAGE_VERSION'])
|
|
14
|
+
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
15
|
+
({paths, toolCallDeadlineMs, PACKAGE_VERSION}=ports);
|
|
16
|
+
connected=true;
|
|
17
|
+
}
|
|
18
|
+
|
|
8
19
|
|
|
9
20
|
const require=createRequire(import.meta.url);
|
|
10
21
|
const catalog=JSON.parse(readFileSync(new URL('../desktop-commander-tools.json',import.meta.url),'utf8'));
|
|
@@ -71,9 +82,10 @@ export function createMcpChildAdapter({records,log},options={}){
|
|
|
71
82
|
const rec={child,toolId:tool.id,pid:child.pid,state:'STARTING',exited:false,pending:new Map(),unconfirmed:new Set(),active:0};
|
|
72
83
|
records.set(tool.id,rec);
|
|
73
84
|
let buffer='';
|
|
85
|
+
child.stdout.setEncoding('utf8'); // MCP JSON may split multibyte tool results.
|
|
74
86
|
child.stdout.on('data',chunk=>{
|
|
75
|
-
buffer+=chunk
|
|
76
|
-
if(buffer
|
|
87
|
+
buffer+=chunk;
|
|
88
|
+
if(Buffer.byteLength(buffer,'utf8')>4*1024*1024){rec.state='UNKNOWN';buffer='';return;}
|
|
77
89
|
let end;
|
|
78
90
|
while((end=buffer.indexOf('\n'))>=0){
|
|
79
91
|
const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
|
|
@@ -132,10 +144,20 @@ export function createMcpChildAdapter({records,log},options={}){
|
|
|
132
144
|
})();
|
|
133
145
|
const wait=ctx.remaining();
|
|
134
146
|
if(wait<1)return result(tool,before,'STARTING','HANDSHAKE_PENDING',null,rec.pid,'MCP_INITIALIZING');
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
147
|
+
let deadlineTimer;
|
|
148
|
+
try{
|
|
149
|
+
return await Promise.race([
|
|
150
|
+
handshake,
|
|
151
|
+
new Promise(resolve=>{
|
|
152
|
+
deadlineTimer=setTimeout(()=>resolve(result(tool,before,'STARTING','HANDSHAKE_PENDING',
|
|
153
|
+
null,rec.pid,'MCP_INITIALIZING')),wait);
|
|
154
|
+
})
|
|
155
|
+
]);
|
|
156
|
+
}finally{
|
|
157
|
+
// A quick handshake must not leave a long caller timer alive. If the
|
|
158
|
+
// deadline wins, the owned child's handshake still finishes in place.
|
|
159
|
+
clearTimeout(deadlineTimer);
|
|
160
|
+
}
|
|
139
161
|
}
|
|
140
162
|
async function inspect(tool,ctx){
|
|
141
163
|
const rec=records.get(tool.id);
|
package/lib/adapters/tunnel.mjs
CHANGED
|
@@ -5,8 +5,18 @@ import {existsSync,lstatSync,mkdirSync,readFileSync,unlinkSync,writeFileSync} fr
|
|
|
5
5
|
import {request as httpRequest} from 'node:http';
|
|
6
6
|
import {homedir} from 'node:os';
|
|
7
7
|
import {join} from 'node:path';
|
|
8
|
-
|
|
9
|
-
import
|
|
8
|
+
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
9
|
+
// Private modules never import or resolve another private implementation.
|
|
10
|
+
let paths, bundledTunnel;
|
|
11
|
+
let connected=false;
|
|
12
|
+
export function configureTunnelAdapter(ports){
|
|
13
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
14
|
+
for(const name of ['paths', 'bundledTunnel'])
|
|
15
|
+
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
16
|
+
({paths, bundledTunnel}=ports);
|
|
17
|
+
connected=true;
|
|
18
|
+
}
|
|
19
|
+
|
|
10
20
|
|
|
11
21
|
const err=code=>({code});
|
|
12
22
|
const result=(t,before,after,outcome,error=null,pid=null,evidence=null,connection='UNVERIFIED')=>
|
|
@@ -98,7 +108,7 @@ export function createTunnelAdapter({records,log,onChildExit=()=>{}},options={})
|
|
|
98
108
|
if(!validProfile())return result(t,before,'FAILED','START_FAILED',err('PROFILE_NOT_FOUND'),null,'NO_PROCESS_STARTED');
|
|
99
109
|
if(ctx.remaining()<500)return result(t,before,before,'DEADLINE_EXPIRED',err('TIMEOUT'),null,'NO_PROCESS_STARTED');
|
|
100
110
|
let binary;
|
|
101
|
-
try{binary=locate().binary;}
|
|
111
|
+
try{binary=(await locate()).binary;}
|
|
102
112
|
catch(e){return result(t,before,'FAILED','START_FAILED',err(e.code||'INVALID_BUNDLE'));}
|
|
103
113
|
mkdirSync(dir,{recursive:true,mode:0o700});
|
|
104
114
|
const ds=lstatSync(dir);
|
|
@@ -123,11 +133,19 @@ export function createTunnelAdapter({records,log,onChildExit=()=>{}},options={})
|
|
|
123
133
|
const rec={child,pid:child.pid||null,nonce,exited:false,state:'STARTING'};
|
|
124
134
|
records.set(t.id,rec);
|
|
125
135
|
child.stdout?.on('data',data=>log('tunnel-output',{toolId:t.id,bytes:data.length}));
|
|
136
|
+
// An authorization message can cross arbitrary stderr chunk boundaries.
|
|
137
|
+
// Keep only a bounded, process-local suffix for matching; never log it.
|
|
138
|
+
let stderrSuffix='';
|
|
139
|
+
child.stderr?.setEncoding('utf8');
|
|
126
140
|
child.stderr?.on('data',data=>{
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
141
|
+
if(!rec.authRequired){
|
|
142
|
+
stderrSuffix=(stderrSuffix+data).slice(-128);
|
|
143
|
+
if(/CONTROL_PLANE_API_KEY|OPENAI_ADMIN_KEY|missing (?:the )?(?:api|runtime) key/i.test(stderrSuffix)){
|
|
144
|
+
rec.authRequired=true;
|
|
145
|
+
stderrSuffix='';
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
log('tunnel-stderr',{toolId:t.id,bytes:Buffer.byteLength(data,'utf8')});
|
|
131
149
|
});
|
|
132
150
|
child.once('error',e=>log('tunnel-error',{toolId:t.id,code:e.code||'ERROR'}));
|
|
133
151
|
function onExit(code,signal){
|
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Additional CLI commands are declared by each static Provider rather than
|
|
2
|
+
// a central command switch. Existing process lifecycle commands remain owned
|
|
3
|
+
// by the Tools CLI, and cannot be shadowed by a provider.
|
|
4
|
+
export const RESERVED_CLI_COMMANDS=Object.freeze([
|
|
5
|
+
'doctor','mcp','start','stop','restart','status','upgrade','tunnel','capabilities','api-usage'
|
|
6
|
+
]);
|
|
7
|
+
const fail=code=>Object.assign(Error(code),{code});
|
|
8
|
+
const valid=name=>typeof name==='string'&&/^[a-z][a-z0-9-]*$/.test(name);
|
|
9
|
+
export function createCliCommandRouter(providers){
|
|
10
|
+
const commands=new Map(),reserved=new Set(RESERVED_CLI_COMMANDS);
|
|
11
|
+
for(const provider of providers){
|
|
12
|
+
for(const cmd of provider.commands??[]){
|
|
13
|
+
if(!cmd||!valid(cmd.name)||typeof cmd.help!=='string'
|
|
14
|
+
||!cmd.help.length||typeof cmd.run!=='function'
|
|
15
|
+
||commands.has(cmd.name)||reserved.has(cmd.name))
|
|
16
|
+
throw fail('CLI_COMMAND_CONFLICT');
|
|
17
|
+
commands.set(cmd.name,cmd);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return Object.freeze({
|
|
21
|
+
names:()=>[...commands.keys()],
|
|
22
|
+
help:name=>commands.get(name)?.help??null,
|
|
23
|
+
async execute(name,args,api){
|
|
24
|
+
const command=commands.get(name);
|
|
25
|
+
if(!command)return null;
|
|
26
|
+
const outcome=await command.run({args,api});
|
|
27
|
+
if(!outcome||typeof outcome!=='object'
|
|
28
|
+
||!Number.isSafeInteger(outcome.exitCode)||outcome.exitCode<0
|
|
29
|
+
||outcome.exitCode>255||!outcome.result||typeof outcome.result!=='object')
|
|
30
|
+
throw fail('CLI_PROVIDER_RESULT_INVALID');
|
|
31
|
+
return outcome;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
@@ -3,7 +3,18 @@
|
|
|
3
3
|
import {createHmac,randomBytes,timingSafeEqual} from 'node:crypto';
|
|
4
4
|
import {existsSync,lstatSync,readFileSync,writeFileSync} from 'node:fs';
|
|
5
5
|
import {join} from 'node:path';
|
|
6
|
-
|
|
6
|
+
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
7
|
+
// Private modules never import or resolve another private implementation.
|
|
8
|
+
let ensurePrivateDir, paths;
|
|
9
|
+
let connected=false;
|
|
10
|
+
export function configureContextControlAuth(ports){
|
|
11
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
12
|
+
for(const name of ['ensurePrivateDir', 'paths'])
|
|
13
|
+
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
14
|
+
({ensurePrivateDir, paths}=ports);
|
|
15
|
+
connected=true;
|
|
16
|
+
}
|
|
17
|
+
|
|
7
18
|
const fail=code=>Object.assign(new Error(code),{code});
|
|
8
19
|
const secretPath=()=>join(paths().dir,'context-control.secret');
|
|
9
20
|
const sign=(key,payload)=>createHmac('sha256',key).update(JSON.stringify(payload)).digest('hex');
|