How to stream all kernel outputs

Hello everyone, I am developing an extension interacting with a kernel. Today I’m using the following piece of code to get the result of my code executions:

const future = context.sessionContext.session.kernel!.requestExecute({ code: code });
future.onIOPub = msg => {
        if (msg.header.msg_type === 'stream') {
                const streamMsg = msg as KernelMessage.IStreamMsg;
                const output = streamMsg.content.text;
        } else if (msg.header.msg_type === 'error') {
        // Handle error messages
        const errorMsg = msg as KernelMessage.IErrorMsg; // If using TypeScript
        const errorOutput = errorMsg.content; // This contains the error details
        }
};

Question: Is there a way to just subscribe to a given Kernel and stream all the outputs (even if another extension is actually requesting the execution)?
I didn’t find relevant documentation but I may have missed it. Any guidance/links would be greatly appreciated. Thanks in advance!

Here is the method I found so far:

const kernel = this._session.session?.kernel;
    kernel.anyMessage.connect((sender, args) => {
      if (args.direction === 'recv') {
        // Filter and process kernel messages here
        // For example, args.msg.header.msg_type might be 'stream' for log messages
      }
  });
1 Like