or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-communication.mdconnection-management.mdindex.mdkernel-management.mdkernel-provisioning.mdkernel-specifications.mdsession-messaging.md

kernel-specifications.mddocs/

0

# Kernel Specifications

1

2

Kernel specification discovery, installation, and management system. Handles kernel.json files and kernel discovery across system and user directories, providing APIs for managing available computational kernels.

3

4

## Capabilities

5

6

### Kernel Specification Class

7

8

The `KernelSpec` class represents a kernel specification containing metadata about how to start and interact with a specific kernel type.

9

10

```python { .api }

11

class KernelSpec:

12

"""Represents a kernel specification."""

13

14

@classmethod

15

def from_resource_dir(cls, resource_dir):

16

"""

17

Create a kernel spec from a resource directory.

18

19

Parameters:

20

- resource_dir (str): Path to directory containing kernel.json

21

22

Returns:

23

KernelSpec: Kernel specification instance

24

"""

25

26

def to_dict(self):

27

"""

28

Convert kernel spec to dictionary representation.

29

30

Returns:

31

dict: Kernel specification as dictionary

32

"""

33

34

def to_json(self):

35

"""

36

Convert kernel spec to JSON string.

37

38

Returns:

39

str: Kernel specification as JSON

40

"""

41

42

# Kernel specification attributes

43

argv = [] # Command line arguments to start kernel

44

display_name = '' # Human-readable kernel name

45

language = '' # Programming language name

46

interrupt_mode = 'signal' # How to interrupt kernel ('signal' or 'message')

47

env = {} # Environment variables for kernel

48

metadata = {} # Additional kernel metadata

49

```

50

51

### Kernel Specification Manager

52

53

The `KernelSpecManager` class provides discovery, installation, and management of kernel specifications across the system.

54

55

```python { .api }

56

class KernelSpecManager:

57

"""Manages kernel specifications."""

58

59

def find_kernel_specs(self):

60

"""

61

Find all available kernel specifications.

62

63

Returns:

64

dict: Mapping of kernel names to their spec directory paths

65

"""

66

67

def get_kernel_spec(self, kernel_name):

68

"""

69

Get a specific kernel specification by name.

70

71

Parameters:

72

- kernel_name (str): Name of the kernel to retrieve

73

74

Returns:

75

KernelSpec: Kernel specification instance

76

77

Raises:

78

NoSuchKernel: If kernel specification not found

79

"""

80

81

def get_all_specs(self):

82

"""

83

Get all kernel specifications with metadata.

84

85

Returns:

86

dict: Mapping of kernel names to spec info dictionaries containing

87

'spec' (KernelSpec) and 'resource_dir' (str) keys

88

"""

89

90

def install_kernel_spec(self, source_dir, kernel_name=None, user=False,

91

replace=None, prefix=None):

92

"""

93

Install a kernel specification.

94

95

Parameters:

96

- source_dir (str): Directory containing kernel.json and resources

97

- kernel_name (str): Name for installed kernel (default: dirname)

98

- user (bool): Install in user directory if True, system if False

99

- replace (bool): Replace existing kernel if True

100

- prefix (str): Installation prefix path

101

102

Returns:

103

str: Path where kernel spec was installed

104

"""

105

106

def remove_kernel_spec(self, name):

107

"""

108

Remove an installed kernel specification.

109

110

Parameters:

111

- name (str): Name of kernel to remove

112

113

Returns:

114

str: Path of removed kernel spec directory

115

"""

116

117

def install_native_kernel_spec(self, user=False):

118

"""

119

Install the native Python kernel specification.

120

121

Parameters:

122

- user (bool): Install in user directory if True

123

124

Returns:

125

None

126

"""

127

128

# Configuration properties

129

user_kernel_dir = '' # User kernel specifications directory

130

kernel_dirs = [] # List of kernel search directories

131

```

132

133

### Kernel Specification Functions

134

135

Standalone functions for working with kernel specifications without requiring a manager instance.

136

137

```python { .api }

138

def find_kernel_specs():

139

"""

140

Find all available kernel specifications.

141

142

Returns:

143

dict: Mapping of kernel names to spec directory paths

144

"""

145

146

def get_kernel_spec(kernel_name):

147

"""

148

Get a specific kernel specification by name.

149

150

Parameters:

151

- kernel_name (str): Name of the kernel

152

153

Returns:

154

KernelSpec: Kernel specification instance

155

156

Raises:

157

NoSuchKernel: If kernel not found

158

"""

159

160

def install_kernel_spec(source_dir, kernel_name=None, user=False,

161

replace=None, prefix=None):

162

"""

163

Install a kernel specification.

164

165

Parameters:

166

- source_dir (str): Source directory with kernel.json

167

- kernel_name (str): Name for the kernel

168

- user (bool): Install in user directory

169

- replace (bool): Replace existing kernel

170

- prefix (str): Installation prefix

171

172

Returns:

173

str: Installation path

174

"""

175

176

def install_native_kernel_spec(user=False):

177

"""

178

Install native Python kernel specification.

179

180

Parameters:

181

- user (bool): Install in user directory

182

183

Returns:

184

None

185

"""

186

```

187

188

### Exception Classes

189

190

```python { .api }

191

class NoSuchKernel(KeyError):

192

"""Raised when a requested kernel specification is not found."""

193

```

194

195

### Application Classes

196

197

Command-line applications for kernel specification management.

198

199

```python { .api }

200

class KernelSpecApp:

201

"""Main application for kernel specification management."""

202

203

class ListKernelSpecs:

204

"""List available kernel specifications."""

205

206

class InstallKernelSpec:

207

"""Install a kernel specification from directory."""

208

209

class RemoveKernelSpec:

210

"""Remove an installed kernel specification."""

211

212

class InstallNativeKernelSpec:

213

"""Install the native Python kernel specification."""

214

215

class ListProvisioners:

216

"""List available kernel provisioners."""

217

```

218

219

## Usage Examples

220

221

### Discovering Available Kernels

222

223

```python

224

from jupyter_client import find_kernel_specs, get_kernel_spec

225

226

# Find all available kernel specs

227

kernel_specs = find_kernel_specs()

228

print("Available kernels:")

229

for name, path in kernel_specs.items():

230

print(f" {name}: {path}")

231

232

# Get specific kernel spec

233

try:

234

python_spec = get_kernel_spec('python3')

235

print(f"Python kernel: {python_spec.display_name}")

236

print(f"Language: {python_spec.language}")

237

print(f"Command: {python_spec.argv}")

238

except NoSuchKernel:

239

print("Python3 kernel not found")

240

```

241

242

### Using Kernel Specification Manager

243

244

```python

245

from jupyter_client.kernelspec import KernelSpecManager

246

247

# Create kernel spec manager

248

ksm = KernelSpecManager()

249

250

# Get all specs with details

251

all_specs = ksm.get_all_specs()

252

for name, spec_info in all_specs.items():

253

spec = spec_info['spec']

254

resource_dir = spec_info['resource_dir']

255

print(f"Kernel: {name}")

256

print(f" Display name: {spec.display_name}")

257

print(f" Language: {spec.language}")

258

print(f" Resource dir: {resource_dir}")

259

print(f" Command: {' '.join(spec.argv)}")

260

if spec.env:

261

print(f" Environment: {spec.env}")

262

print()

263

```

264

265

### Installing Custom Kernel

266

267

```python

268

import os

269

import json

270

import tempfile

271

from jupyter_client import install_kernel_spec

272

273

# Create custom kernel specification

274

kernel_spec = {

275

"argv": ["python", "-m", "my_custom_kernel", "-f", "{connection_file}"],

276

"display_name": "My Custom Kernel",

277

"language": "python",

278

"interrupt_mode": "signal",

279

"env": {

280

"CUSTOM_KERNEL_MODE": "production"

281

},

282

"metadata": {

283

"debugger": True

284

}

285

}

286

287

# Create temporary directory with kernel.json

288

with tempfile.TemporaryDirectory() as temp_dir:

289

kernel_json_path = os.path.join(temp_dir, 'kernel.json')

290

with open(kernel_json_path, 'w') as f:

291

json.dump(kernel_spec, f, indent=2)

292

293

# Install kernel spec

294

try:

295

install_path = install_kernel_spec(

296

temp_dir,

297

kernel_name='my-custom-kernel',

298

user=True, # Install in user directory

299

replace=True # Replace if exists

300

)

301

print(f"Kernel installed at: {install_path}")

302

except Exception as e:

303

print(f"Installation failed: {e}")

304

```

305

306

### Working with Kernel Spec Objects

307

308

```python

309

from jupyter_client import get_kernel_spec

310

311

# Get kernel spec

312

spec = get_kernel_spec('python3')

313

314

# Examine kernel properties

315

print(f"Display name: {spec.display_name}")

316

print(f"Language: {spec.language}")

317

print(f"Interrupt mode: {spec.interrupt_mode}")

318

print(f"Command arguments: {spec.argv}")

319

320

# Convert to different formats

321

spec_dict = spec.to_dict()

322

print(f"As dictionary: {spec_dict}")

323

324

spec_json = spec.to_json()

325

print(f"As JSON: {spec_json}")

326

327

# Check for specific capabilities

328

if 'debugger' in spec.metadata:

329

print("Kernel supports debugging")

330

331

if spec.interrupt_mode == 'signal':

332

print("Kernel can be interrupted with signals")

333

```

334

335

### Creating Kernel Spec from Directory

336

337

```python

338

import os

339

import tempfile

340

import json

341

from jupyter_client.kernelspec import KernelSpec

342

343

# Create kernel spec directory structure

344

with tempfile.TemporaryDirectory() as temp_dir:

345

# Create kernel.json

346

kernel_json = {

347

"argv": ["R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],

348

"display_name": "R",

349

"language": "R"

350

}

351

352

kernel_json_path = os.path.join(temp_dir, 'kernel.json')

353

with open(kernel_json_path, 'w') as f:

354

json.dump(kernel_json, f)

355

356

# Create logo files (optional)

357

logo_32_path = os.path.join(temp_dir, 'logo-32x32.png')

358

logo_64_path = os.path.join(temp_dir, 'logo-64x64.png')

359

# Would create actual logo files here

360

361

# Load kernel spec from directory

362

spec = KernelSpec.from_resource_dir(temp_dir)

363

print(f"Loaded spec: {spec.display_name}")

364

print(f"Language: {spec.language}")

365

```

366

367

### Managing Multiple Kernel Installations

368

369

```python

370

from jupyter_client.kernelspec import KernelSpecManager

371

372

ksm = KernelSpecManager()

373

374

def list_kernels():

375

"""List all installed kernels with details."""

376

specs = ksm.get_all_specs()

377

print(f"Found {len(specs)} kernel specifications:")

378

379

for name, spec_info in specs.items():

380

spec = spec_info['spec']

381

print(f"\n{name}:")

382

print(f" Display Name: {spec.display_name}")

383

print(f" Language: {spec.language}")

384

print(f" Location: {spec_info['resource_dir']}")

385

386

def remove_kernel(kernel_name):

387

"""Remove a kernel specification."""

388

try:

389

removed_path = ksm.remove_kernel_spec(kernel_name)

390

print(f"Removed kernel '{kernel_name}' from {removed_path}")

391

except Exception as e:

392

print(f"Failed to remove kernel '{kernel_name}': {e}")

393

394

def install_native_python():

395

"""Install native Python kernel."""

396

ksm.install_native_kernel_spec(user=True)

397

print("Installed native Python kernel spec")

398

399

# Use the functions

400

list_kernels()

401

# remove_kernel('old-kernel')

402

# install_native_python()

403

```

404

405

### Programmatic Kernel Discovery

406

407

```python

408

from jupyter_client.kernelspec import KernelSpecManager

409

import os

410

411

class KernelDiscovery:

412

def __init__(self):

413

self.ksm = KernelSpecManager()

414

415

def find_kernels_by_language(self, language):

416

"""Find all kernels for a specific language."""

417

matching_kernels = []

418

419

for name, spec_info in self.ksm.get_all_specs().items():

420

spec = spec_info['spec']

421

if spec.language.lower() == language.lower():

422

matching_kernels.append({

423

'name': name,

424

'display_name': spec.display_name,

425

'resource_dir': spec_info['resource_dir']

426

})

427

428

return matching_kernels

429

430

def get_kernel_capabilities(self, kernel_name):

431

"""Get capabilities of a specific kernel."""

432

try:

433

spec = self.ksm.get_kernel_spec(kernel_name)

434

capabilities = {

435

'language': spec.language,

436

'interrupt_mode': spec.interrupt_mode,

437

'has_debugger': spec.metadata.get('debugger', False),

438

'environment_vars': list(spec.env.keys()),

439

'command': spec.argv[0] if spec.argv else None

440

}

441

return capabilities

442

except NoSuchKernel:

443

return None

444

445

def validate_kernel_installation(self, kernel_name):

446

"""Check if a kernel is properly installed."""

447

try:

448

spec = self.ksm.get_kernel_spec(kernel_name)

449

450

# Check if command exists

451

if spec.argv:

452

command = spec.argv[0]

453

if not any(os.path.isfile(os.path.join(path, command))

454

for path in os.environ.get('PATH', '').split(os.pathsep)):

455

return False, f"Command '{command}' not found in PATH"

456

457

return True, "Kernel installation is valid"

458

except NoSuchKernel:

459

return False, "Kernel specification not found"

460

461

# Use the discovery class

462

discovery = KernelDiscovery()

463

464

# Find Python kernels

465

python_kernels = discovery.find_kernels_by_language('Python')

466

print(f"Found {len(python_kernels)} Python kernels:")

467

for kernel in python_kernels:

468

print(f" {kernel['name']}: {kernel['display_name']}")

469

470

# Check capabilities

471

if python_kernels:

472

kernel_name = python_kernels[0]['name']

473

capabilities = discovery.get_kernel_capabilities(kernel_name)

474

print(f"\nCapabilities of {kernel_name}:")

475

for key, value in capabilities.items():

476

print(f" {key}: {value}")

477

478

# Validate installation

479

valid, message = discovery.validate_kernel_installation(kernel_name)

480

print(f"\nValidation: {message}")

481

```