superkernels 0.9.0__py3-none-any.whl

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.
@@ -0,0 +1,25 @@
1
+ """Local Jupyter integration for Super Kernel."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ try:
8
+ __version__ = version("superkernels")
9
+ except PackageNotFoundError:
10
+ __version__ = "0.9.0"
11
+
12
+
13
+ def __getattr__(name: str):
14
+ """Load the local ipykernel only when a client explicitly requests it."""
15
+ if name == "SuperKernel":
16
+ from superkernel.kernel import SuperKernel
17
+
18
+ return SuperKernel
19
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
20
+
21
+
22
+ __all__ = [
23
+ "SuperKernel",
24
+ "__version__",
25
+ ]
superkernel/kernel.py ADDED
@@ -0,0 +1,594 @@
1
+ """Jupyter kernel runtime for the kernel-cloud SSE execution API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import re
10
+ import sys
11
+ import threading
12
+ import time
13
+ import traceback
14
+ import uuid
15
+ from collections.abc import Iterator
16
+ from pathlib import Path
17
+ from typing import Any, ClassVar, Literal
18
+
19
+ import requests
20
+ from ipykernel.kernelapp import IPKernelApp
21
+ from ipykernel.kernelbase import Kernel
22
+ from requests import Response
23
+ from requests.exceptions import (
24
+ ChunkedEncodingError,
25
+ HTTPError,
26
+ ReadTimeout,
27
+ RequestException,
28
+ Timeout,
29
+ )
30
+ from requests.exceptions import (
31
+ ConnectionError as RequestsConnectionError,
32
+ )
33
+
34
+ from superkernel import __version__
35
+ from superkernel.logfile import DEFAULT_LOG_FILE, append_log
36
+ from superkernel.schema import (
37
+ CodeExecutionRequest,
38
+ CodeExecutionResumeRequest,
39
+ ControlRequest,
40
+ ControlResponse,
41
+ )
42
+ from superkernel.state import (
43
+ _delete_runtime_status,
44
+ _normalize_gateway_url,
45
+ _read_auth_token,
46
+ _write_runtime_status,
47
+ )
48
+
49
+
50
+ class StaleSuperKernelError(RuntimeError):
51
+ """Signal that this saved local registration cannot be used anymore."""
52
+
53
+
54
+ AdmissionState = Literal["idle", "waiting", "admitting", "admitted"]
55
+
56
+
57
+ class SuperKernel(Kernel):
58
+ """Forward notebook execution to one gateway-provisioned Super Kernel."""
59
+
60
+ implementation = "superkernel"
61
+ implementation_version = __version__
62
+ language = "python"
63
+ language_version = f"{sys.version_info.major}.{sys.version_info.minor}"
64
+ language_info: ClassVar[dict[str, str]] = {
65
+ "name": "python",
66
+ "mimetype": "text/x-python",
67
+ "file_extension": ".py",
68
+ }
69
+ banner = "Super Kernel — local Jupyter kernel with remote execution"
70
+ boot: ClassVar[dict[str, Any]] = {}
71
+
72
+ @staticmethod
73
+ def _session_id_from_connection_file(connection_file: str) -> str:
74
+ """Use Jupyter's runtime connection-file ID as the notebook identity."""
75
+ filename = Path(connection_file).name
76
+ if not filename.endswith(".json"):
77
+ raise RuntimeError("Jupyter connection file is unavailable")
78
+ session_id = filename[:-5]
79
+ session_id = session_id.removeprefix("kernel-")
80
+ if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", session_id):
81
+ raise RuntimeError("Jupyter connection file has an invalid kernel ID")
82
+ return session_id
83
+
84
+ def __init__(self, **kwargs: Any) -> None:
85
+ super().__init__(**kwargs)
86
+ config = SuperKernel.boot
87
+ self.gateway_url = _normalize_gateway_url(str(config["gateway_url"]))
88
+ self.endpoint = f"{self.gateway_url}/kernel/execute"
89
+ self.control_endpoint = f"{self.gateway_url}/kernel/control"
90
+ self.remote_kernel_id = str(config["remote_kernel_id"])
91
+ self.auth_file = str(config["auth_file"])
92
+ self.timeout = float(os.getenv("SUPERKERNEL_EXECUTION_TIMEOUT", "300"))
93
+ connection_file = str(
94
+ config.get("connection_file")
95
+ or getattr(self.parent, "connection_file", "")
96
+ or getattr(IPKernelApp.instance(), "connection_file", "")
97
+ )
98
+ self.session_id = self._session_id_from_connection_file(connection_file)
99
+ self._execution_lock = threading.Lock()
100
+ self._pending_code_digest: str | None = None
101
+ self._pending_execution_id: str | None = None
102
+ self._pending_reply_id: str | None = None
103
+ self._pending_cursor_id: str | None = None
104
+ self._admission_state: AdmissionState = "idle"
105
+ self._output_runner_id: str | None = None
106
+ self._output_stream_name: str | None = None
107
+ self._output_ends_with_newline = True
108
+ self._runner_virtual_newlines: set[tuple[str, str]] = set()
109
+ log_file = config.get("log_file") or os.getenv("SUPERKERNEL_LOG_FILE")
110
+ self._log_path = Path(log_file).expanduser() if log_file else DEFAULT_LOG_FILE
111
+ self._runtime_status = "idle"
112
+ self._last_execution_at: float | None = None
113
+ self._runtime_status_lock = threading.Lock()
114
+ self._runtime_status_stop = threading.Event()
115
+ self._publish_runtime_status()
116
+ self._runtime_status_thread = threading.Thread(
117
+ target=self._runtime_status_heartbeat,
118
+ name=f"superkernel-status-{self.session_id}",
119
+ daemon=True,
120
+ )
121
+ self._runtime_status_thread.start()
122
+
123
+ for message_type in ("comm_open", "comm_msg", "comm_close"):
124
+ self.shell_handlers[message_type] = self._ignore_comm_message
125
+ self.control_handlers[message_type] = self._ignore_comm_message
126
+
127
+ def _ignore_comm_message(self, _stream: Any, _idents: Any, _msg: Any) -> None:
128
+ return None
129
+
130
+ def _write_stream(self, name: str, text: str) -> None:
131
+ self.send_response(self.iopub_socket, "stream", {"name": name, "text": text})
132
+
133
+ def _write_runner_stream(self, runner_id: str, name: str, text: str) -> None:
134
+ """Keep interleaved runner chunks readable without buffering them."""
135
+ if not text:
136
+ return
137
+ runner_stream = (runner_id, name)
138
+ if text.startswith("\n") and runner_stream in self._runner_virtual_newlines:
139
+ self._runner_virtual_newlines.remove(runner_stream)
140
+ text = text[1:]
141
+ if not text:
142
+ return
143
+ if (
144
+ self._output_runner_id is not None
145
+ and runner_id != self._output_runner_id
146
+ and not self._output_ends_with_newline
147
+ and not text.startswith("\n")
148
+ ):
149
+ previous_stream = self._output_stream_name or name
150
+ self._write_stream(previous_stream, "\n")
151
+ self._runner_virtual_newlines.add((self._output_runner_id, previous_stream))
152
+ self._write_stream(name, text)
153
+ self._output_runner_id = runner_id
154
+ self._output_stream_name = name
155
+ self._output_ends_with_newline = text.endswith("\n")
156
+
157
+ def _reset_runner_stream(self) -> None:
158
+ self._output_runner_id = None
159
+ self._output_stream_name = None
160
+ self._output_ends_with_newline = True
161
+ self._runner_virtual_newlines.clear()
162
+
163
+ def _send_display_data(self, data: dict[str, Any]) -> None:
164
+ self.send_response(
165
+ self.iopub_socket,
166
+ "display_data",
167
+ {"data": data, "metadata": {}},
168
+ )
169
+
170
+ def _log(self, message: str) -> None:
171
+ try:
172
+ append_log(message, self._log_path)
173
+ except Exception: # noqa: BLE001, S110 - logging must never break execution
174
+ pass
175
+
176
+ def _publish_runtime_status(self) -> None:
177
+ try:
178
+ with self._runtime_status_lock:
179
+ status = self._runtime_status
180
+ last_execution_at = self._last_execution_at
181
+ _write_runtime_status(
182
+ self.gateway_url,
183
+ self.remote_kernel_id,
184
+ self.session_id,
185
+ status,
186
+ last_execution_at,
187
+ )
188
+ except Exception as exc: # noqa: BLE001 - status must not break the kernel
189
+ self._log(
190
+ f"Local runtime status update failed: {type(exc).__name__}: {exc}"
191
+ )
192
+
193
+ def _set_runtime_status(self, status: str) -> None:
194
+ with self._runtime_status_lock:
195
+ self._runtime_status = status
196
+ if status == "busy":
197
+ self._last_execution_at = time.time()
198
+ self._publish_runtime_status()
199
+
200
+ def _runtime_status_heartbeat(self) -> None:
201
+ while not self._runtime_status_stop.wait(5.0):
202
+ self._publish_runtime_status()
203
+
204
+ def _execution_id(self, code: str) -> str:
205
+ digest = hashlib.sha256(code.encode("utf-8")).hexdigest()
206
+ if self._pending_code_digest == digest and self._pending_execution_id:
207
+ return self._pending_execution_id
208
+ self._pending_code_digest = digest
209
+ self._pending_execution_id = f"exec_{uuid.uuid4().hex}"
210
+ self._pending_reply_id = None
211
+ self._pending_cursor_id = None
212
+ return self._pending_execution_id
213
+
214
+ def _clear_pending_execution(self) -> None:
215
+ self._pending_code_digest = None
216
+ self._pending_execution_id = None
217
+ self._pending_reply_id = None
218
+ self._pending_cursor_id = None
219
+ self._admission_state = "idle"
220
+
221
+ @staticmethod
222
+ def _iter_sse(response: Response) -> Iterator[dict[str, str]]:
223
+ """Parse one HTTP response into SSE frames."""
224
+ response.encoding = "utf-8"
225
+ fields: dict[str, str] = {}
226
+ data_lines: list[str] = []
227
+ for line in response.iter_lines(decode_unicode=True, chunk_size=1):
228
+ if line == "":
229
+ if fields or data_lines:
230
+ fields["data"] = "\n".join(data_lines)
231
+ yield fields
232
+ fields = {}
233
+ data_lines = []
234
+ continue
235
+ if not line or line.startswith(":"):
236
+ continue
237
+ name, separator, value = line.partition(":")
238
+ if not separator:
239
+ value = ""
240
+ elif value.startswith(" "):
241
+ value = value[1:]
242
+ if name == "data":
243
+ data_lines.append(value)
244
+ else:
245
+ fields[name] = value
246
+ if fields or data_lines:
247
+ fields["data"] = "\n".join(data_lines)
248
+ yield fields
249
+
250
+ def _handle_sse_frame(self, frame: dict[str, str]) -> tuple[str | None, bool]:
251
+ """Render one SSE frame and return terminal status/error state."""
252
+ event_type = frame.get("event", "message")
253
+ try:
254
+ payload = json.loads(frame.get("data", "{}"))
255
+ except json.JSONDecodeError as exc:
256
+ raise RuntimeError(f"Gateway sent invalid SSE JSON: {exc}") from exc
257
+
258
+ if event_type in {"runner_execution_started", "runner_execution_finished"}:
259
+ return None, False
260
+
261
+ if event_type in {"result", "stream"}:
262
+ data = str(payload.get("data") or "")
263
+ if data:
264
+ stream = str(payload.get("stream") or "stdout")
265
+ self._write_runner_stream(
266
+ str(payload.get("runner_id") or ""),
267
+ "stderr" if stream == "stderr" else "stdout",
268
+ data if event_type == "stream" else data.rstrip("\n") + "\n",
269
+ )
270
+ return None, str(payload.get("status") or "success") != "success"
271
+
272
+ if event_type == "execution_finished":
273
+ succeeded = str(payload.get("status") or "") == "success"
274
+ return "completed" if succeeded else "failed", not succeeded
275
+
276
+ if event_type == "error":
277
+ return "failed", True
278
+
279
+ raise RuntimeError(f"Gateway sent unsupported SSE event: {event_type}")
280
+
281
+ def _stream_execute(self, request: CodeExecutionRequest) -> bool:
282
+ """Admit locally queued code once, then resume its stable reply stream."""
283
+ deadline = time.monotonic() + self.timeout
284
+ reply_id = self._pending_reply_id
285
+ last_event_id = self._pending_cursor_id
286
+ self._admission_state = "admitted" if reply_id is not None else "waiting"
287
+ execution_failed = False
288
+
289
+ while True:
290
+ remaining = deadline - time.monotonic()
291
+ if remaining <= 0:
292
+ raise Timeout(
293
+ "Execution did not reach a terminal status before the timeout; "
294
+ "rerun the same cell to reconnect"
295
+ )
296
+ headers = {
297
+ "Accept": "text/event-stream",
298
+ "Content-Type": "application/json",
299
+ }
300
+ access_token = _read_auth_token(self.auth_file)
301
+ headers["Authorization"] = f"Bearer {access_token}"
302
+ if last_event_id is not None:
303
+ headers["Last-Event-ID"] = str(last_event_id)
304
+ body = (
305
+ CodeExecutionResumeRequest(
306
+ kernel_id=self.remote_kernel_id,
307
+ reply_id=reply_id,
308
+ ).model_dump(mode="json")
309
+ if reply_id is not None
310
+ else request.model_dump(mode="json")
311
+ )
312
+ self._log(
313
+ f"POST {self.endpoint} remote_kernel_id={self.remote_kernel_id} "
314
+ f"execution_id={request.execution_id} reply_id={reply_id} "
315
+ f"reconnect_after={last_event_id} "
316
+ f"code_length={len(request.code)}"
317
+ )
318
+ try:
319
+ if reply_id is None:
320
+ # The Gateway may admit this request before its response
321
+ # reaches us, so interruption is remote-best-effort while
322
+ # the initial request is in flight.
323
+ self._admission_state = "admitting"
324
+ with requests.post(
325
+ self.endpoint,
326
+ headers=headers,
327
+ json=body,
328
+ stream=True,
329
+ timeout=(10.0, min(60.0, max(1.0, remaining))),
330
+ ) as response:
331
+ if response.status_code == 409:
332
+ try:
333
+ detail = str(response.json().get("detail") or "")
334
+ except (TypeError, ValueError):
335
+ detail = ""
336
+ if detail == "kernel_busy" and reply_id is None:
337
+ self._admission_state = "waiting"
338
+ retry_after = response.headers.get("Retry-After", "1")
339
+ try:
340
+ delay = min(5.0, max(0.05, float(retry_after)))
341
+ except ValueError:
342
+ delay = 1.0
343
+ time.sleep(min(delay, max(0.01, remaining)))
344
+ continue
345
+ if response.status_code in {408, 425, 429, 502, 503, 504}:
346
+ time.sleep(min(1.0, max(0.01, remaining)))
347
+ continue
348
+ response.raise_for_status()
349
+ response_reply_id = response.headers.get("SuperKernel-Reply-ID")
350
+ if not response_reply_id:
351
+ raise RuntimeError(
352
+ "Gateway omitted the execution reply identifier"
353
+ )
354
+ if reply_id is not None and response_reply_id != reply_id:
355
+ raise RuntimeError(
356
+ "Gateway changed the execution reply identifier"
357
+ )
358
+ reply_id = response_reply_id
359
+ self._pending_reply_id = reply_id
360
+ self._admission_state = "admitted"
361
+ content_type = response.headers.get("content-type", "")
362
+ if not content_type.lower().startswith("text/event-stream"):
363
+ raise RuntimeError(
364
+ f"Gateway returned {content_type or 'no content type'}; "
365
+ "expected text/event-stream"
366
+ )
367
+ for frame in self._iter_sse(response):
368
+ raw_event_id = frame.get("id")
369
+ if raw_event_id is not None:
370
+ if not raw_event_id.strip():
371
+ raise RuntimeError(
372
+ "Gateway sent an invalid SSE event ID"
373
+ )
374
+ last_event_id = raw_event_id
375
+ self._pending_cursor_id = last_event_id
376
+ status, frame_failed = self._handle_sse_frame(frame)
377
+ execution_failed = execution_failed or frame_failed
378
+ if status is not None:
379
+ # A terminal SSE frame is the execution boundary. Do not
380
+ # wait for a reverse proxy to close its HTTP connection.
381
+ return status == "completed" and not execution_failed
382
+ except HTTPError:
383
+ raise
384
+ except (ChunkedEncodingError, ReadTimeout, RequestsConnectionError):
385
+ if time.monotonic() >= deadline:
386
+ raise
387
+ self._log(
388
+ f"SSE reconnect execution_id={request.execution_id} "
389
+ f"last_event_id={last_event_id}"
390
+ )
391
+ time.sleep(0.25)
392
+
393
+ def _post_control(
394
+ self,
395
+ action: str,
396
+ execution_id: str | None = None,
397
+ ) -> ControlResponse:
398
+ payload = ControlRequest(
399
+ action=action,
400
+ kernel_id=self.remote_kernel_id,
401
+ session_id=self.session_id,
402
+ execution_id=execution_id,
403
+ )
404
+ self._log(
405
+ f"POST {self.control_endpoint} remote_kernel_id={self.remote_kernel_id} "
406
+ f"action={action} execution_id={execution_id}"
407
+ )
408
+ headers = {"Content-Type": "application/json"}
409
+ access_token = _read_auth_token(self.auth_file)
410
+ headers["Authorization"] = f"Bearer {access_token}"
411
+ response = requests.post(
412
+ self.control_endpoint,
413
+ headers=headers,
414
+ json=payload.model_dump(mode="json"),
415
+ timeout=(10.0, min(30.0, self.timeout)),
416
+ )
417
+ response.raise_for_status()
418
+ return ControlResponse.model_validate(response.json())
419
+
420
+ def _interrupt_pending_execution(self, execution_id: str) -> None:
421
+ """Cancel a local wait or best-effort interrupt possible remote work."""
422
+ if self._admission_state == "waiting":
423
+ self._log(f"Local admission wait cancelled execution_id={execution_id}")
424
+ return
425
+ try:
426
+ self._post_control("interrupt", execution_id)
427
+ except Exception as exc: # noqa: BLE001 - interruption is best effort
428
+ self._log(f"Super Kernel interrupt failed: {type(exc).__name__}: {exc}")
429
+
430
+ def do_execute(
431
+ self,
432
+ code: str,
433
+ silent: bool,
434
+ store_history: bool = True,
435
+ user_expressions: dict[str, Any] | None = None,
436
+ allow_stdin: bool = False,
437
+ ) -> dict[str, Any]:
438
+ # Keep the remote stream strictly aligned with Jupyter's local kernel.
439
+ # This also protects direct/concurrent callers outside the shell loop.
440
+ with self._execution_lock:
441
+ return self._do_execute(
442
+ code,
443
+ silent,
444
+ store_history,
445
+ user_expressions,
446
+ allow_stdin,
447
+ )
448
+
449
+ def _do_execute(
450
+ self,
451
+ code: str,
452
+ silent: bool,
453
+ store_history: bool = True,
454
+ user_expressions: dict[str, Any] | None = None,
455
+ allow_stdin: bool = False,
456
+ ) -> dict[str, Any]:
457
+ if silent or not code.strip():
458
+ return self._reply("ok")
459
+ self._set_runtime_status("busy")
460
+ self._reset_runner_stream()
461
+ execution_id = self._execution_id(code)
462
+ request = CodeExecutionRequest(
463
+ kernel_id=self.remote_kernel_id,
464
+ execution_id=execution_id,
465
+ session_id=self.session_id,
466
+ execution_count=self.execution_count,
467
+ code=code,
468
+ )
469
+ try:
470
+ succeeded = self._stream_execute(request)
471
+ except KeyboardInterrupt:
472
+ self._interrupt_pending_execution(execution_id)
473
+ self._write_stream("stderr", "[Super Kernel] Execution interrupted.\n")
474
+ self._clear_pending_execution()
475
+ self._set_runtime_status("idle")
476
+ return self._reply("abort")
477
+ except RequestException as exc:
478
+ self._log(f"Gateway request failed: {type(exc).__name__}: {exc}")
479
+ self._write_stream("stderr", "[Super Kernel] Error.\n")
480
+ self._set_runtime_status("error")
481
+ if (
482
+ isinstance(exc, HTTPError)
483
+ and exc.response is not None
484
+ and exc.response.status_code in {401, 404}
485
+ ):
486
+ return self._reply(
487
+ "error",
488
+ StaleSuperKernelError("Saved Super Kernel is unavailable"),
489
+ )
490
+ return self._reply("error", RuntimeError("Error"))
491
+ except Exception as exc: # noqa: BLE001 - kernel protocol boundary
492
+ self._log(
493
+ f"Execution failed: {type(exc).__name__}: {exc}\n"
494
+ f"{traceback.format_exc()}"
495
+ )
496
+ self._write_stream("stderr", "[Super Kernel] Error.\n")
497
+ self._set_runtime_status("error")
498
+ return self._reply("error", RuntimeError("Error"))
499
+
500
+ self._clear_pending_execution()
501
+ if succeeded:
502
+ self._set_runtime_status("idle")
503
+ return self._reply("ok")
504
+ self._write_stream("stderr", "[Super Kernel] Error.\n")
505
+ self._set_runtime_status("error")
506
+ error = RuntimeError("Error")
507
+ return self._reply("error", error)
508
+
509
+ def _reply(self, status: str, error: Exception | None = None) -> dict[str, Any]:
510
+ reply: dict[str, Any] = {
511
+ "status": status,
512
+ "execution_count": self.execution_count,
513
+ "payload": [],
514
+ "user_expressions": {},
515
+ }
516
+ if status == "error" and error is not None:
517
+ reply.update(
518
+ {
519
+ "ename": type(error).__name__,
520
+ "evalue": str(error),
521
+ "traceback": [],
522
+ }
523
+ )
524
+ return reply
525
+
526
+ def do_shutdown(self, restart: bool = False) -> dict[str, Any]:
527
+ """Reset remote session state for restart, then stop the local process."""
528
+ if restart:
529
+ try:
530
+ self._post_control("restart")
531
+ except Exception as exc: # noqa: BLE001 - shutdown must complete
532
+ self._log(f"Super Kernel restart failed: {type(exc).__name__}: {exc}")
533
+ self._clear_pending_execution()
534
+ self._runtime_status_stop.set()
535
+ try:
536
+ _delete_runtime_status(
537
+ self.gateway_url,
538
+ self.remote_kernel_id,
539
+ self.session_id,
540
+ )
541
+ except Exception as exc: # noqa: BLE001 - shutdown must complete
542
+ self._log(
543
+ f"Local runtime status cleanup failed: {type(exc).__name__}: {exc}"
544
+ )
545
+ return {"status": "ok", "restart": restart}
546
+
547
+
548
+ def _build_arg_parser() -> argparse.ArgumentParser:
549
+ parser = argparse.ArgumentParser(
550
+ prog="python -m superkernel.kernel",
551
+ description="Launch a local Jupyter kernel bound to one Super Kernel ID.",
552
+ )
553
+ parser.add_argument("--gateway-url", required=True)
554
+ parser.add_argument("--remote-kernel-id", required=True)
555
+ parser.add_argument(
556
+ "--auth-file",
557
+ required=True,
558
+ help="Private UI-managed auth.json file",
559
+ )
560
+ return parser
561
+
562
+
563
+ def _connection_file_argument(argv: list[str]) -> str:
564
+ """Return the runtime connection file selected by Jupyter."""
565
+ for index, argument in enumerate(argv):
566
+ if argument in {"-f", "--IPKernelApp.connection_file"}:
567
+ if index + 1 >= len(argv):
568
+ break
569
+ return argv[index + 1]
570
+ for prefix in ("--f=", "--IPKernelApp.connection_file="):
571
+ if argument.startswith(prefix):
572
+ return argument[len(prefix) :]
573
+ raise SystemExit("Jupyter connection file is required")
574
+
575
+
576
+ def main(argv: list[str] | None = None) -> None:
577
+ args, remaining = _build_arg_parser().parse_known_args(
578
+ argv if argv is not None else sys.argv[1:]
579
+ )
580
+ try:
581
+ _read_auth_token(args.auth_file)
582
+ except RuntimeError as exc:
583
+ raise SystemExit(str(exc)) from exc
584
+ SuperKernel.boot = {
585
+ "gateway_url": args.gateway_url,
586
+ "remote_kernel_id": args.remote_kernel_id,
587
+ "auth_file": args.auth_file,
588
+ "connection_file": _connection_file_argument(remaining),
589
+ }
590
+ IPKernelApp.launch_instance(kernel_class=SuperKernel, argv=remaining)
591
+
592
+
593
+ if __name__ == "__main__":
594
+ main()
superkernel/logfile.py ADDED
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ import datetime as dt
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ DEFAULT_LOG_FILE = Path("/var/superkernel.log")
8
+
9
+ PathLike = str | Path
10
+
11
+
12
+ def append_log(message: str, log_path: PathLike | None = DEFAULT_LOG_FILE) -> None:
13
+ """
14
+ Append a timestamped message to the log file.
15
+ Silently ignores filesystem errors so logging never breaks core flows.
16
+ """
17
+ if log_path is None:
18
+ log_path = DEFAULT_LOG_FILE
19
+ path = Path(log_path).expanduser()
20
+ try:
21
+ path.parent.mkdir(parents=True, exist_ok=True)
22
+ stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="milliseconds")
23
+ with path.open("a", encoding="utf-8") as fh:
24
+ fh.write(f"[{stamp}] {message}\n")
25
+ except OSError as exc:
26
+ sys.stderr.write(f"[Super Kernel] Failed to write log entry: {exc}\n")
superkernel/schema.py ADDED
@@ -0,0 +1,179 @@
1
+ """Shared models for the Super Kernel Gateway contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ from typing import Any, Literal
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+ KernelType = Literal["base", "mpi", "torch"]
11
+
12
+
13
+ class AuthRequest(BaseModel):
14
+ """API-key login request sent only to ``POST /auth``."""
15
+
16
+ model_config = ConfigDict(extra="forbid")
17
+
18
+ method: Literal["api_key"] = "api_key"
19
+
20
+
21
+ class AuthResponse(BaseModel):
22
+ """Reusable Gateway session shared by infrastructure and kernel calls."""
23
+
24
+ model_config = ConfigDict(extra="forbid")
25
+
26
+ access_token: str = Field(min_length=1)
27
+ token_type: Literal["Bearer"] = "Bearer"
28
+ auth_method: Literal["api_key"] = "api_key"
29
+ user_id: str = Field(min_length=1, max_length=320)
30
+ expires_at: dt.datetime
31
+
32
+
33
+ class RuntimeDescriptor(BaseModel):
34
+ """One runtime image available through ``POST /infra/status``."""
35
+
36
+ model_config = ConfigDict(extra="forbid")
37
+
38
+ type: KernelType
39
+ name: str = Field(min_length=1, max_length=64)
40
+
41
+
42
+ class ResourceAmount(BaseModel):
43
+ """One resource limit and its current reservation."""
44
+
45
+ model_config = ConfigDict(extra="forbid")
46
+
47
+ limit: int = Field(ge=0)
48
+ used: int = Field(ge=0)
49
+ available: int = Field(ge=0)
50
+ unit: Literal["count", "bytes"]
51
+
52
+
53
+ class UserResourceResponse(BaseModel):
54
+ """Authenticated user's resource limits and reservations."""
55
+
56
+ model_config = ConfigDict(extra="forbid")
57
+
58
+ vcpu: ResourceAmount
59
+ memory: ResourceAmount | None = None
60
+ gpu: ResourceAmount
61
+ block: ResourceAmount
62
+ bucket: ResourceAmount
63
+
64
+
65
+ class InfraKernelCreateRequest(BaseModel):
66
+ """Idempotent kernel specification for ``POST /infra/kernel/create``."""
67
+
68
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
69
+
70
+ request_id: str = Field(min_length=1, max_length=128)
71
+ name: str = Field(min_length=1, max_length=128)
72
+ kernel_type: KernelType = Field(alias="type")
73
+ runtime: str = Field(min_length=1, max_length=64)
74
+ nodes: int = Field(default=1, ge=1, le=32)
75
+ vcpu_per_node: int = Field(default=1, ge=1, le=64)
76
+ memory_per_vcpu_gb: int = Field(default=1, ge=1, le=128)
77
+
78
+
79
+ class InfraKernelActionRequest(BaseModel):
80
+ """Kernel identity for one infrastructure lifecycle mutation."""
81
+
82
+ model_config = ConfigDict(extra="forbid")
83
+
84
+ kernel_id: str = Field(min_length=1, max_length=128)
85
+
86
+
87
+ class InfraKernelResponse(BaseModel):
88
+ """Infrastructure create/start/stop/delete result."""
89
+
90
+ model_config = ConfigDict(extra="forbid")
91
+
92
+ kernel_id: str = Field(min_length=1)
93
+ status: Literal["ready", "paused", "deleted"]
94
+ metadata: dict[str, Any] = Field(default_factory=dict)
95
+
96
+
97
+ class InfraKernelStatus(BaseModel):
98
+ """One owned kernel returned in the infrastructure status snapshot."""
99
+
100
+ model_config = ConfigDict(extra="forbid")
101
+
102
+ kernel_id: str = Field(min_length=1)
103
+ request_id: str = Field(min_length=1)
104
+ name: str = Field(min_length=1)
105
+ type: KernelType
106
+ runtime: str = Field(min_length=1)
107
+ nodes: int = Field(ge=1)
108
+ vcpu_per_node: int = Field(ge=1)
109
+ memory_per_vcpu_gb: int = Field(ge=1)
110
+ status: Literal["idle", "busy", "degraded", "unavailable", "paused"]
111
+ generation: int = Field(ge=1)
112
+ healthy_runners: int = Field(ge=0)
113
+ busy_runners: int = Field(ge=0)
114
+ idle_runners: int = Field(ge=0)
115
+ expected_runners: int = Field(ge=1)
116
+
117
+
118
+ class InfraStatusResponse(BaseModel):
119
+ """Complete plugin-facing Gateway snapshot."""
120
+
121
+ model_config = ConfigDict(extra="forbid")
122
+
123
+ user_id: str = Field(min_length=1, max_length=320)
124
+ resources: UserResourceResponse
125
+ runtimes: list[RuntimeDescriptor]
126
+ kernels: list[InfraKernelStatus]
127
+ updated_at: dt.datetime
128
+
129
+
130
+ class CodeExecutionRequest(BaseModel):
131
+ """Initial cell admission sent to ``POST /kernel/execute``."""
132
+
133
+ model_config = ConfigDict(extra="forbid")
134
+
135
+ mode: Literal["execute"] = "execute"
136
+ kernel_id: str = Field(min_length=1, max_length=128)
137
+ execution_id: str = Field(min_length=1, max_length=128)
138
+ code: str = Field(min_length=1, max_length=1_000_000)
139
+ execution_count: int | None = None
140
+ session_id: str = Field(min_length=1, max_length=128)
141
+ metadata: dict[str, Any] = Field(default_factory=dict)
142
+
143
+ def require_code(self) -> str:
144
+ """Return non-empty code for the execution handler."""
145
+ if not self.code.strip():
146
+ raise ValueError("code cannot be empty")
147
+ return self.code
148
+
149
+
150
+ class CodeExecutionResumeRequest(BaseModel):
151
+ """SSE replay attachment for one already-admitted execution."""
152
+
153
+ model_config = ConfigDict(extra="forbid")
154
+
155
+ mode: Literal["resume"] = "resume"
156
+ kernel_id: str = Field(min_length=1, max_length=128)
157
+ reply_id: str = Field(pattern=r"^skr_[A-Za-z0-9_-]{16,128}$")
158
+
159
+
160
+ class ControlRequest(BaseModel):
161
+ """Body sent by ``superkernel.kernel`` to ``POST /kernel/control``."""
162
+
163
+ model_config = ConfigDict(extra="forbid")
164
+
165
+ action: Literal["interrupt", "restart"]
166
+ kernel_id: str = Field(min_length=1, max_length=128)
167
+ session_id: str | None = Field(default=None, min_length=1, max_length=128)
168
+ execution_id: str | None = Field(default=None, min_length=1, max_length=128)
169
+
170
+
171
+ class ControlResponse(BaseModel):
172
+ """Synchronous kernel-control result."""
173
+
174
+ model_config = ConfigDict(extra="forbid")
175
+
176
+ kernel_id: str
177
+ action: Literal["interrupt", "restart"]
178
+ status: Literal["interrupted", "idle", "restarted"]
179
+ execution_id: str | None = None
superkernel/state.py ADDED
@@ -0,0 +1,150 @@
1
+ """Private local state access required by the SuperKernel runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import stat
10
+ import time
11
+ from pathlib import Path
12
+ from urllib.parse import urlsplit, urlunsplit
13
+
14
+ REMOTE_KERNEL_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
15
+ LOCAL_SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9._-]{1,128}$")
16
+
17
+
18
+ def _shared_state_dir() -> Path:
19
+ configured = os.getenv("SUPERKERNEL_HOME", "").strip()
20
+ return Path(configured).expanduser() if configured else Path.home() / ".superkernel"
21
+
22
+
23
+ def _normalize_gateway_url(value: str) -> str:
24
+ parsed = urlsplit(value.strip())
25
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
26
+ raise RuntimeError("Invalid Super Kernel Gateway URL")
27
+ if parsed.username or parsed.password or parsed.query or parsed.fragment:
28
+ raise RuntimeError("Invalid Super Kernel Gateway URL")
29
+ path = parsed.path.rstrip("/")
30
+ return urlunsplit((parsed.scheme.lower(), parsed.netloc.lower(), path, "", ""))
31
+
32
+
33
+ def _gateway_id(gateway_url: str) -> str:
34
+ normalized = _normalize_gateway_url(gateway_url)
35
+ return f"gw_{hashlib.sha256(normalized.encode()).hexdigest()[:16]}"
36
+
37
+
38
+ def _validate_remote_kernel_id(remote_kernel_id: str) -> str:
39
+ if not REMOTE_KERNEL_ID_PATTERN.fullmatch(remote_kernel_id):
40
+ raise RuntimeError("Invalid remote Super Kernel ID")
41
+ return remote_kernel_id
42
+
43
+
44
+ def _ensure_private_directory(path: Path) -> Path:
45
+ try:
46
+ details = path.lstat()
47
+ except FileNotFoundError:
48
+ path.mkdir(parents=True, exist_ok=False, mode=0o700)
49
+ details = path.lstat()
50
+ if (
51
+ not stat.S_ISDIR(details.st_mode)
52
+ or stat.S_ISLNK(details.st_mode)
53
+ or details.st_uid != os.geteuid()
54
+ ):
55
+ raise RuntimeError("Unsafe Super Kernel state directory")
56
+ path.chmod(0o700)
57
+ return path
58
+
59
+
60
+ def _read_auth_token(auth_file: str) -> str:
61
+ """Read the current UI-provisioned Gateway session without caching it."""
62
+ path = Path(auth_file).expanduser()
63
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
64
+ try:
65
+ descriptor = os.open(path, flags)
66
+ except FileNotFoundError as exc:
67
+ raise RuntimeError("Super Kernel authentication is unavailable") from exc
68
+ try:
69
+ details = os.fstat(descriptor)
70
+ if not stat.S_ISREG(details.st_mode):
71
+ raise RuntimeError("Invalid Super Kernel auth file")
72
+ if details.st_uid != os.geteuid() or stat.S_IMODE(details.st_mode) & 0o077:
73
+ raise RuntimeError("Unsafe Super Kernel auth file permissions")
74
+ with os.fdopen(descriptor, encoding="utf-8") as stream:
75
+ descriptor = -1
76
+ payload = json.load(stream)
77
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
78
+ raise RuntimeError("Cannot read Super Kernel authentication") from exc
79
+ finally:
80
+ if descriptor >= 0:
81
+ os.close(descriptor)
82
+ token = payload.get("access_token") if isinstance(payload, dict) else None
83
+ if not isinstance(token, str) or not token:
84
+ raise RuntimeError("Super Kernel authentication is unavailable")
85
+ return token
86
+
87
+
88
+ def _runtime_status_file(
89
+ gateway_url: str,
90
+ remote_kernel_id: str,
91
+ session_id: str,
92
+ ) -> Path:
93
+ if not LOCAL_SESSION_ID_PATTERN.fullmatch(session_id):
94
+ raise RuntimeError("Invalid local Super Kernel session ID")
95
+ return (
96
+ _shared_state_dir()
97
+ / _gateway_id(gateway_url)
98
+ / "runtime"
99
+ / _validate_remote_kernel_id(remote_kernel_id)
100
+ / f"{session_id}.json"
101
+ )
102
+
103
+
104
+ def _write_runtime_status(
105
+ gateway_url: str,
106
+ remote_kernel_id: str,
107
+ session_id: str,
108
+ status: str,
109
+ last_execution_at: float | None = None,
110
+ ) -> None:
111
+ """Publish a non-secret runtime observation for both plugin UIs."""
112
+ if status not in {"idle", "busy", "error"}:
113
+ raise RuntimeError("Invalid local Super Kernel status")
114
+ root = _ensure_private_directory(_shared_state_dir())
115
+ gateway_dir = _ensure_private_directory(root / _gateway_id(gateway_url))
116
+ runtime_dir = _ensure_private_directory(gateway_dir / "runtime")
117
+ kernel_dir = _ensure_private_directory(
118
+ runtime_dir / _validate_remote_kernel_id(remote_kernel_id)
119
+ )
120
+ status_file = _runtime_status_file(gateway_url, remote_kernel_id, session_id)
121
+ temporary = kernel_dir / (f".{status_file.name}.{os.getpid()}.{time.time_ns()}.tmp")
122
+ temporary.write_text(
123
+ json.dumps(
124
+ {
125
+ "version": 1,
126
+ "gateway_url": _normalize_gateway_url(gateway_url),
127
+ "remote_kernel_id": remote_kernel_id,
128
+ "session_id": session_id,
129
+ "status": status,
130
+ "updated_at": time.time(),
131
+ "last_execution_at": last_execution_at,
132
+ "pid": os.getpid(),
133
+ }
134
+ ),
135
+ encoding="utf-8",
136
+ )
137
+ temporary.chmod(0o600)
138
+ os.replace(temporary, status_file)
139
+ status_file.chmod(0o600)
140
+
141
+
142
+ def _delete_runtime_status(
143
+ gateway_url: str,
144
+ remote_kernel_id: str,
145
+ session_id: str,
146
+ ) -> None:
147
+ try:
148
+ _runtime_status_file(gateway_url, remote_kernel_id, session_id).unlink()
149
+ except FileNotFoundError:
150
+ pass
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: superkernels
3
+ Version: 0.9.0
4
+ Summary: A local ipykernel adapter for remote Super Kernel runtimes.
5
+ Author-email: Leo Li <leoustc@icloud.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://superkernel.leoustc.com
8
+ Project-URL: Source, https://github.com/leoustc/collection-pip/tree/main/jupyter-superkernel/superkernel
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Framework :: Jupyter
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: ipykernel>=6.29
18
+ Requires-Dist: pydantic>=2.7
19
+ Requires-Dist: requests>=2.31
20
+ Dynamic: license-file
21
+
22
+ # SuperKernel
23
+
24
+ SuperKernel brings remote compute into your daily notebook.
25
+
26
+ It is a Jupyter-compatible Python kernel that connects a local notebook to a
27
+ configured SuperKernel runtime. Your existing Jupyter tools continue to manage
28
+ the notebook connection while code runs on the selected remote Python, MPI, or
29
+ PyTorch environment.
30
+
31
+ ## Features
32
+
33
+ - Works as a standard Jupyter kernel in JupyterLab and VS Code.
34
+ - Streams remote output back to notebook cells as it is produced.
35
+ - Preserves a separate Python namespace for each notebook session.
36
+ - Executes cells sequentially and supports interrupt and restart actions.
37
+ - Reconnects interrupted output streams without submitting the cell twice.
38
+ - Keeps authentication tokens out of Jupyter kernelspecs and command-line
39
+ arguments.
40
+
41
+ ## Installation
42
+
43
+ SuperKernel requires Python 3.10 or newer.
44
+
45
+ ```bash
46
+ uv pip install superkernels
47
+ ```
48
+
49
+ The JupyterLab or VS Code SuperKernel integration normally installs and
50
+ configures the notebook kernels for you. A configured kernel can then be
51
+ selected from the standard Jupyter kernel picker like any other kernel.
52
+
53
+ This package contains the notebook runtime only. Gateway login, remote runtime
54
+ creation, and local kernel registration are handled by a compatible
55
+ SuperKernel client integration.
56
+
57
+ The PyPI distribution is named `superkernels`. The Python import remains
58
+ `superkernel`.
59
+
60
+ ## Python API
61
+
62
+ The kernel class is available for integrations that need to inspect or extend
63
+ the local runtime:
64
+
65
+ ```python
66
+ from superkernel import SuperKernel
67
+ ```
68
+
69
+ The supported process entry point for a configured Jupyter kernelspec is:
70
+
71
+ ```text
72
+ python -m superkernel.kernel
73
+ ```
74
+
75
+ Its connection and authentication arguments are generated by the client
76
+ integration and are not intended to be entered manually.
77
+
78
+ ## Security
79
+
80
+ SuperKernel reads authentication from a client-managed local file immediately
81
+ before each remote request. Credentials are not embedded in the kernelspec,
82
+ stored by this package, or passed directly on the process command line. The
83
+ runtime fails closed when its authentication file is missing or invalid.
84
+
85
+ ## Project status
86
+
87
+ Version 0.9.0 is the first public alpha release. The package is suitable for
88
+ evaluation, but its integration contract may still evolve before 1.0.
89
+
90
+ Learn more at [superkernel.leoustc.com](https://superkernel.leoustc.com).
@@ -0,0 +1,10 @@
1
+ superkernel/__init__.py,sha256=J9gqF-jcfCsofgV1LuzrnLfJRmorzFLD3FqTS7Y_fNk,597
2
+ superkernel/kernel.py,sha256=zHee5CmxM24NR7itbg7fAAp-vmSo7DhjzZ7wMh5yceA,24119
3
+ superkernel/logfile.py,sha256=X5Aj9YJZ22mQefRTcn5Ytt-NRTV5scfHexxBq3_l1go,847
4
+ superkernel/schema.py,sha256=pX3teOE6Ge43ghXjs_wA8zbOqmlXvmY-hSE8lreK1o8,5493
5
+ superkernel/state.py,sha256=ochWHDg1CZaH5lTVRvcJYP11_25DVbE5RU22X5ZfMXs,5264
6
+ superkernels-0.9.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
7
+ superkernels-0.9.0.dist-info/METADATA,sha256=yqk0F8PlGcLqh1_tv5nDoRIov1278JJaaDB87AfyfKo,3123
8
+ superkernels-0.9.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
9
+ superkernels-0.9.0.dist-info/top_level.txt,sha256=HNX5XkyXWdMgpGp6Vfe7_jC1za5Hr6v6E7qmT_juWl4,12
10
+ superkernels-0.9.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ superkernel