kernel.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import { IIterator } from '@phosphor/algorithm';
  4. import { JSONObject, JSONValue } from '@phosphor/coreutils';
  5. import { IDisposable } from '@phosphor/disposable';
  6. import { ISignal } from '@phosphor/signaling';
  7. import { ServerConnection } from '..';
  8. import { DefaultKernel } from './default';
  9. import { KernelMessage } from './messages';
  10. /**
  11. * A namespace for kernel types, interfaces, and type checker functions.
  12. */
  13. export namespace Kernel {
  14. /**
  15. * Interface of a Kernel connection that is managed by a session.
  16. *
  17. * #### Notes
  18. * The Kernel object is tied to the lifetime of the Kernel id, which is a
  19. * unique id for the Kernel session on the server. The Kernel object manages
  20. * a websocket connection internally, and will auto-restart if the websocket
  21. * temporarily loses connection. Restarting creates a new Kernel process on
  22. * the server, but preserves the Kernel id.
  23. */
  24. export interface IKernelConnection extends IDisposable {
  25. /**
  26. * The id of the server-side kernel.
  27. */
  28. readonly id: string;
  29. /**
  30. * The name of the server-side kernel.
  31. */
  32. readonly name: string;
  33. /**
  34. * The model associated with the kernel.
  35. */
  36. readonly model: Kernel.IModel;
  37. /**
  38. * The client username.
  39. */
  40. readonly username: string;
  41. /**
  42. * The client unique id.
  43. *
  44. * #### Notes
  45. * This should be unique for a particular kernel connection object.
  46. */
  47. readonly clientId: string;
  48. /**
  49. * The current status of the kernel.
  50. */
  51. readonly status: Kernel.Status;
  52. /**
  53. * The cached kernel info.
  54. *
  55. * #### Notes
  56. * This value will be null until the kernel is ready.
  57. */
  58. readonly info: KernelMessage.IInfoReply | null;
  59. /**
  60. * Test whether the kernel is ready.
  61. *
  62. * #### Notes
  63. * A kernel is ready when the communication channel is active and we have
  64. * cached the kernel info.
  65. */
  66. readonly isReady: boolean;
  67. /**
  68. * A promise that resolves when the kernel is initially ready after a start
  69. * or restart.
  70. *
  71. * #### Notes
  72. * A kernel is ready when the communication channel is active and we have
  73. * cached the kernel info.
  74. */
  75. readonly ready: Promise<void>;
  76. /**
  77. * Get the kernel spec.
  78. *
  79. * @returns A promise that resolves with the kernel spec for this kernel.
  80. */
  81. getSpec(): Promise<Kernel.ISpecModel>;
  82. /**
  83. * Send a shell message to the kernel.
  84. *
  85. * @param msg - The fully-formed shell message to send.
  86. *
  87. * @param expectReply - Whether to expect a shell reply message.
  88. *
  89. * @param disposeOnDone - Whether to dispose of the future when done.
  90. *
  91. * #### Notes
  92. * Send a message to the kernel's shell channel, yielding a future object
  93. * for accepting replies.
  94. *
  95. * If `expectReply` is given and `true`, the future is done when both a
  96. * shell reply and an idle status message are received with the appropriate
  97. * parent header, in which case the `.done` promise resolves to the reply.
  98. * If `expectReply` is not given or is `false`, the future is done when an
  99. * idle status message with the appropriate parent header is received, in
  100. * which case the `.done` promise resolves to `undefined`.
  101. *
  102. * If `disposeOnDone` is given and `false`, the future will not be disposed
  103. * of when the future is done, instead relying on the caller to dispose of
  104. * it. This allows for the handling of out-of-order output from ill-behaved
  105. * kernels.
  106. *
  107. * All replies are validated as valid kernel messages.
  108. *
  109. * If the kernel status is `'dead'`, this will throw an error.
  110. */
  111. sendShellMessage<T extends KernelMessage.ShellMessageType>(
  112. msg: KernelMessage.IShellMessage<T>,
  113. expectReply?: boolean,
  114. disposeOnDone?: boolean
  115. ): Kernel.IShellFuture<KernelMessage.IShellMessage<T>>;
  116. sendControlMessage<T extends KernelMessage.ControlMessageType>(
  117. msg: KernelMessage.IControlMessage<T>,
  118. expectReply?: boolean,
  119. disposeOnDone?: boolean
  120. ): Kernel.IControlFuture<KernelMessage.IControlMessage<T>>;
  121. /**
  122. * Reconnect to a disconnected kernel.
  123. *
  124. * @returns A promise that resolves when the kernel has reconnected.
  125. *
  126. * #### Notes
  127. * This just refreshes the connection to an existing kernel, and does not
  128. * perform an HTTP request to the server or restart the kernel.
  129. */
  130. reconnect(): Promise<void>;
  131. /**
  132. * Interrupt a kernel.
  133. *
  134. * @returns A promise that resolves when the kernel has interrupted.
  135. *
  136. * #### Notes
  137. * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
  138. *
  139. * The promise is fulfilled on a valid response and rejected otherwise.
  140. *
  141. * It is assumed that the API call does not mutate the kernel id or name.
  142. *
  143. * The promise will be rejected if the kernel status is `'dead'` or if the
  144. * request fails or the response is invalid.
  145. */
  146. interrupt(): Promise<void>;
  147. /**
  148. * Restart a kernel.
  149. *
  150. * @returns A promise that resolves when the kernel has restarted.
  151. *
  152. * #### Notes
  153. * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
  154. *
  155. * Any existing Future or Comm objects are cleared.
  156. *
  157. * It is assumed that the API call does not mutate the kernel id or name.
  158. *
  159. * The promise will be rejected if the kernel status is `'dead'` or if the
  160. * request fails or the response is invalid.
  161. */
  162. restart(): Promise<void>;
  163. /**
  164. * Send a `kernel_info_request` message.
  165. *
  166. * @param content - The content of the request.
  167. *
  168. * @returns A promise that resolves with the response message.
  169. *
  170. * #### Notes
  171. * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).
  172. *
  173. * Fulfills with the `kernel_info_response` content when the shell reply is
  174. * received and validated.
  175. */
  176. requestKernelInfo(): Promise<KernelMessage.IInfoReplyMsg>;
  177. /**
  178. * Send a `complete_request` message.
  179. *
  180. * @param content - The content of the request.
  181. *
  182. * @returns A promise that resolves with the response message.
  183. *
  184. * #### Notes
  185. * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).
  186. *
  187. * Fulfills with the `complete_reply` content when the shell reply is
  188. * received and validated.
  189. */
  190. requestComplete(
  191. content: KernelMessage.ICompleteRequestMsg['content']
  192. ): Promise<KernelMessage.ICompleteReplyMsg>;
  193. /**
  194. * Send an `inspect_request` message.
  195. *
  196. * @param content - The content of the request.
  197. *
  198. * @returns A promise that resolves with the response message.
  199. *
  200. * #### Notes
  201. * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).
  202. *
  203. * Fulfills with the `inspect_reply` content when the shell reply is
  204. * received and validated.
  205. */
  206. requestInspect(
  207. content: KernelMessage.IInspectRequestMsg['content']
  208. ): Promise<KernelMessage.IInspectReplyMsg>;
  209. /**
  210. * Send a `history_request` message.
  211. *
  212. * @param content - The content of the request.
  213. *
  214. * @returns A promise that resolves with the response message.
  215. *
  216. * #### Notes
  217. * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).
  218. *
  219. * Fulfills with the `history_reply` content when the shell reply is
  220. * received and validated.
  221. */
  222. requestHistory(
  223. content: KernelMessage.IHistoryRequestMsg['content']
  224. ): Promise<KernelMessage.IHistoryReplyMsg>;
  225. /**
  226. * Send an `execute_request` message.
  227. *
  228. * @param content - The content of the request.
  229. *
  230. * @param disposeOnDone - Whether to dispose of the future when done.
  231. *
  232. * @returns A kernel future.
  233. *
  234. * #### Notes
  235. * See [Messaging in
  236. * Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).
  237. *
  238. * This method returns a kernel future, rather than a promise, since execution may
  239. * have many response messages (for example, many iopub display messages).
  240. *
  241. * Future `onReply` is called with the `execute_reply` content when the
  242. * shell reply is received and validated.
  243. *
  244. * **See also:** [[IExecuteReply]]
  245. */
  246. requestExecute(
  247. content: KernelMessage.IExecuteRequestMsg['content'],
  248. disposeOnDone?: boolean,
  249. metadata?: JSONObject
  250. ): Kernel.IShellFuture<
  251. KernelMessage.IExecuteRequestMsg,
  252. KernelMessage.IExecuteReplyMsg
  253. >;
  254. /**
  255. * Send an `is_complete_request` message.
  256. *
  257. * @param content - The content of the request.
  258. *
  259. * @returns A promise that resolves with the response message.
  260. *
  261. * #### Notes
  262. * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).
  263. *
  264. * Fulfills with the `is_complete_response` content when the shell reply is
  265. * received and validated.
  266. */
  267. requestIsComplete(
  268. content: KernelMessage.IIsCompleteRequestMsg['content']
  269. ): Promise<KernelMessage.IIsCompleteReplyMsg>;
  270. /**
  271. * Send a `comm_info_request` message.
  272. *
  273. * @param content - The content of the request.
  274. *
  275. * @returns A promise that resolves with the response message.
  276. *
  277. * #### Notes
  278. * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#comm_info).
  279. *
  280. * Fulfills with the `comm_info_reply` content when the shell reply is
  281. * received and validated.
  282. */
  283. requestCommInfo(
  284. content: KernelMessage.ICommInfoRequestMsg['content']
  285. ): Promise<KernelMessage.ICommInfoReplyMsg>;
  286. /**
  287. * Send an `input_reply` message.
  288. *
  289. * @param content - The content of the reply.
  290. *
  291. * #### Notes
  292. * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).
  293. */
  294. sendInputReply(content: KernelMessage.IInputReplyMsg['content']): void;
  295. /**
  296. * Connect to a comm, or create a new one.
  297. *
  298. * @param targetName - The name of the comm target.
  299. *
  300. * @param id - The comm id.
  301. *
  302. * @returns A comm instance.
  303. */
  304. connectToComm(targetName: string, commId?: string): Kernel.IComm;
  305. /**
  306. * Register a comm target handler.
  307. *
  308. * @param targetName - The name of the comm target.
  309. *
  310. * @param callback - The callback invoked for a comm open message.
  311. *
  312. * #### Notes
  313. * Only one comm target can be registered to a target name at a time, an
  314. * existing callback for the same target name will be overridden. A registered
  315. * comm target handler will take precedence over a comm which specifies a
  316. * `target_module`.
  317. *
  318. * If the callback returns a promise, kernel message processing will pause
  319. * until the returned promise is fulfilled.
  320. */
  321. registerCommTarget(
  322. targetName: string,
  323. callback: (
  324. comm: Kernel.IComm,
  325. msg: KernelMessage.ICommOpenMsg
  326. ) => void | PromiseLike<void>
  327. ): void;
  328. /**
  329. * Remove a comm target handler.
  330. *
  331. * @param targetName - The name of the comm target to remove.
  332. *
  333. * @param callback - The callback to remove.
  334. *
  335. * #### Notes
  336. * The comm target is only removed if it matches the callback argument.
  337. */
  338. removeCommTarget(
  339. targetName: string,
  340. callback: (
  341. comm: Kernel.IComm,
  342. msg: KernelMessage.ICommOpenMsg
  343. ) => void | PromiseLike<void>
  344. ): void;
  345. /**
  346. * Register an IOPub message hook.
  347. *
  348. * @param msg_id - The parent_header message id in messages the hook should
  349. * intercept.
  350. *
  351. * @param hook - The callback invoked for the message.
  352. *
  353. * #### Notes
  354. * The IOPub hook system allows you to preempt the handlers for IOPub
  355. * messages with a given parent_header message id. The most recently
  356. * registered hook is run first. If a hook return value resolves to false,
  357. * any later hooks and the future's onIOPub handler will not run. If a hook
  358. * throws an error, the error is logged to the console and the next hook is
  359. * run. If a hook is registered during the hook processing, it will not run
  360. * until the next message. If a hook is disposed during the hook processing,
  361. * it will be deactivated immediately.
  362. *
  363. * See also [[IFuture.registerMessageHook]].
  364. */
  365. registerMessageHook(
  366. msgId: string,
  367. hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>
  368. ): void;
  369. /**
  370. * Remove an IOPub message hook.
  371. *
  372. * @param msg_id - The parent_header message id the hook intercepted.
  373. *
  374. * @param hook - The callback invoked for the message.
  375. *
  376. */
  377. removeMessageHook(
  378. msgId: string,
  379. hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>
  380. ): void;
  381. }
  382. /**
  383. * The full interface of a kernel.
  384. */
  385. export interface IKernel extends IKernelConnection {
  386. /**
  387. * A signal emitted when the kernel is shut down.
  388. */
  389. terminated: ISignal<this, void>;
  390. /**
  391. * A signal emitted when the kernel status changes.
  392. */
  393. statusChanged: ISignal<this, Kernel.Status>;
  394. /**
  395. * A signal emitted after an iopub kernel message is handled.
  396. */
  397. iopubMessage: ISignal<this, KernelMessage.IIOPubMessage>;
  398. /**
  399. * A signal emitted for unhandled non-iopub kernel messages that claimed to
  400. * be responses for messages we sent using this kernel object.
  401. */
  402. unhandledMessage: ISignal<this, KernelMessage.IMessage>;
  403. /**
  404. * A signal emitted when any kernel message is sent or received.
  405. *
  406. * #### Notes
  407. * This signal is emitted before any message handling has happened. The
  408. * message should be treated as read-only.
  409. */
  410. anyMessage: ISignal<this, IAnyMessageArgs>;
  411. /**
  412. * The server settings for the kernel.
  413. */
  414. readonly serverSettings: ServerConnection.ISettings;
  415. /**
  416. * Shutdown a kernel.
  417. *
  418. * @returns A promise that resolves when the kernel has shut down.
  419. *
  420. * #### Notes
  421. * Uses the [Jupyter Notebook
  422. * API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
  423. *
  424. * On a valid response, closes the websocket, emits the [[terminated]]
  425. * signal, disposes of the kernel object, and fulfills the promise.
  426. *
  427. * The promise will be rejected if the kernel status is `'dead'`, the
  428. * request fails, or the response is invalid.
  429. */
  430. shutdown(): Promise<void>;
  431. }
  432. /**
  433. * Find a kernel by id.
  434. *
  435. * @param id - The id of the kernel of interest.
  436. *
  437. * @param settings - The optional server settings.
  438. *
  439. * @returns A promise that resolves with the model for the kernel.
  440. *
  441. * #### Notes
  442. * If the kernel was already started via `startNewKernel`, we return its
  443. * `Kernel.IModel`. Otherwise, we attempt to find the existing kernel. The
  444. * promise is fulfilled when the kernel is found, otherwise the promise is
  445. * rejected.
  446. */
  447. export function findById(
  448. id: string,
  449. settings?: ServerConnection.ISettings
  450. ): Promise<IModel> {
  451. return DefaultKernel.findById(id, settings);
  452. }
  453. /**
  454. * Fetch all of the kernel specs.
  455. *
  456. * @param settings - The optional server settings.
  457. *
  458. * @returns A promise that resolves with the kernel specs.
  459. *
  460. * #### Notes
  461. * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs).
  462. */
  463. export function getSpecs(
  464. settings?: ServerConnection.ISettings
  465. ): Promise<Kernel.ISpecModels> {
  466. return DefaultKernel.getSpecs(settings);
  467. }
  468. /**
  469. * Fetch the running kernels.
  470. *
  471. * @param settings - The optional server settings.
  472. *
  473. * @returns A promise that resolves with the list of running kernels.
  474. *
  475. * #### Notes
  476. * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
  477. *
  478. * The promise is fulfilled on a valid response and rejected otherwise.
  479. */
  480. export function listRunning(
  481. settings?: ServerConnection.ISettings
  482. ): Promise<Kernel.IModel[]> {
  483. return DefaultKernel.listRunning(settings);
  484. }
  485. /**
  486. * Start a new kernel.
  487. *
  488. * @param options - The options used to create the kernel.
  489. *
  490. * @returns A promise that resolves with a kernel object.
  491. *
  492. * #### Notes
  493. * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels) and validates the response model.
  494. *
  495. * If no options are given or the kernel name is not given, the
  496. * default kernel will by started by the server.
  497. *
  498. * Wraps the result in a Kernel object. The promise is fulfilled
  499. * when the kernel is started by the server, otherwise the promise is rejected.
  500. */
  501. export function startNew(options: Kernel.IOptions = {}): Promise<IKernel> {
  502. return DefaultKernel.startNew(options);
  503. }
  504. /**
  505. * Connect to a running kernel.
  506. *
  507. * @param model - The model of the running kernel.
  508. *
  509. * @param settings - The server settings for the request.
  510. *
  511. * @returns The kernel object.
  512. *
  513. * #### Notes
  514. * If the kernel was already started via `startNewKernel`, the existing
  515. * Kernel object info is used to create another instance.
  516. */
  517. export function connectTo(
  518. model: Kernel.IModel,
  519. settings?: ServerConnection.ISettings
  520. ): IKernel {
  521. return DefaultKernel.connectTo(model, settings);
  522. }
  523. /**
  524. * Shut down a kernel by id.
  525. *
  526. * @param id - The id of the running kernel.
  527. *
  528. * @param settings - The server settings for the request.
  529. *
  530. * @returns A promise that resolves when the kernel is shut down.
  531. */
  532. export function shutdown(
  533. id: string,
  534. settings?: ServerConnection.ISettings
  535. ): Promise<void> {
  536. return DefaultKernel.shutdown(id, settings);
  537. }
  538. /**
  539. * Shut down all kernels.
  540. *
  541. * @returns A promise that resolves when all of the kernels are shut down.
  542. */
  543. export function shutdownAll(
  544. settings?: ServerConnection.ISettings
  545. ): Promise<void> {
  546. return DefaultKernel.shutdownAll(settings);
  547. }
  548. /**
  549. * The options object used to initialize a kernel.
  550. */
  551. export interface IOptions {
  552. /**
  553. * The kernel type (e.g. python3).
  554. */
  555. name?: string;
  556. /**
  557. * The server settings for the kernel.
  558. */
  559. serverSettings?: ServerConnection.ISettings;
  560. /**
  561. * The username of the kernel client.
  562. */
  563. username?: string;
  564. /**
  565. * The unique identifier for the kernel client.
  566. */
  567. clientId?: string;
  568. }
  569. /**
  570. * Object which manages kernel instances for a given base url.
  571. *
  572. * #### Notes
  573. * The manager is responsible for maintaining the state of running
  574. * kernels and the initial fetch of kernel specs.
  575. */
  576. export interface IManager extends IDisposable {
  577. /**
  578. * A signal emitted when the kernel specs change.
  579. */
  580. specsChanged: ISignal<IManager, ISpecModels>;
  581. /**
  582. * A signal emitted when the running kernels change.
  583. */
  584. runningChanged: ISignal<IManager, IModel[]>;
  585. /**
  586. * A signal emitted when there is a connection failure.
  587. */
  588. connectionFailure: ISignal<IManager, ServerConnection.NetworkError>;
  589. /**
  590. * The server settings for the manager.
  591. */
  592. serverSettings?: ServerConnection.ISettings;
  593. /**
  594. * The kernel spec models.
  595. *
  596. * #### Notes
  597. * The value will be null until the manager is ready.
  598. */
  599. readonly specs: Kernel.ISpecModels | null;
  600. /**
  601. * Whether the manager is ready.
  602. */
  603. readonly isReady: boolean;
  604. /**
  605. * A promise that resolves when the manager is initially ready.
  606. */
  607. readonly ready: Promise<void>;
  608. /**
  609. * Create an iterator over the known running kernels.
  610. *
  611. * @returns A new iterator over the running kernels.
  612. */
  613. running(): IIterator<IModel>;
  614. /**
  615. * Force a refresh of the specs from the server.
  616. *
  617. * @returns A promise that resolves when the specs are fetched.
  618. *
  619. * #### Notes
  620. * This is intended to be called only in response to a user action,
  621. * since the manager maintains its internal state.
  622. */
  623. refreshSpecs(): Promise<void>;
  624. /**
  625. * Force a refresh of the running kernels.
  626. *
  627. * @returns A promise that resolves when the models are refreshed.
  628. *
  629. * #### Notes
  630. * This is intended to be called only in response to a user action,
  631. * since the manager maintains its internal state.
  632. */
  633. refreshRunning(): Promise<void>;
  634. /**
  635. * Start a new kernel.
  636. *
  637. * @param options - The kernel options to use.
  638. *
  639. * @returns A promise that resolves with the kernel instance.
  640. *
  641. * #### Notes
  642. * The manager `serverSettings` will be always be used.
  643. */
  644. startNew(options?: IOptions): Promise<IKernel>;
  645. /**
  646. * Find a kernel by id.
  647. *
  648. * @param id - The id of the target kernel.
  649. *
  650. * @returns A promise that resolves with the kernel's model.
  651. */
  652. findById(id: string): Promise<IModel>;
  653. /**
  654. * Connect to an existing kernel.
  655. *
  656. * @param model - The model of the target kernel.
  657. *
  658. * @returns A promise that resolves with the new kernel instance.
  659. */
  660. connectTo(model: Kernel.IModel): IKernel;
  661. /**
  662. * Shut down a kernel by id.
  663. *
  664. * @param id - The id of the target kernel.
  665. *
  666. * @returns A promise that resolves when the operation is complete.
  667. */
  668. shutdown(id: string): Promise<void>;
  669. /**
  670. * Shut down all kernels.
  671. *
  672. * @returns A promise that resolves when all of the kernels are shut down.
  673. */
  674. shutdownAll(): Promise<void>;
  675. }
  676. /**
  677. * A Future interface for responses from the kernel.
  678. *
  679. * When a message is sent to a kernel, a Future is created to handle any
  680. * responses that may come from the kernel.
  681. */
  682. export interface IFuture<
  683. REQUEST extends KernelMessage.IShellControlMessage,
  684. REPLY extends KernelMessage.IShellControlMessage
  685. > extends IDisposable {
  686. /**
  687. * The original outgoing message.
  688. */
  689. readonly msg: REQUEST;
  690. /**
  691. * A promise that resolves when the future is done.
  692. *
  693. * #### Notes
  694. * The future is done when there are no more responses expected from the
  695. * kernel.
  696. *
  697. * The `done` promise resolves to the reply message if there is one,
  698. * otherwise it resolves to `undefined`.
  699. */
  700. readonly done: Promise<REPLY | undefined>;
  701. /**
  702. * The reply handler for the kernel future.
  703. *
  704. * #### Notes
  705. * If the handler returns a promise, all kernel message processing pauses
  706. * until the promise is resolved. If there is a reply message, the future
  707. * `done` promise also resolves to the reply message after this handler has
  708. * been called.
  709. */
  710. onReply: (msg: REPLY) => void | PromiseLike<void>;
  711. /**
  712. * The iopub handler for the kernel future.
  713. *
  714. * #### Notes
  715. * If the handler returns a promise, all kernel message processing pauses
  716. * until the promise is resolved.
  717. */
  718. onIOPub: (msg: KernelMessage.IIOPubMessage) => void | PromiseLike<void>;
  719. /**
  720. * The stdin handler for the kernel future.
  721. *
  722. * #### Notes
  723. * If the handler returns a promise, all kernel message processing pauses
  724. * until the promise is resolved.
  725. */
  726. onStdin: (msg: KernelMessage.IStdinMessage) => void | PromiseLike<void>;
  727. /**
  728. * Register hook for IOPub messages.
  729. *
  730. * @param hook - The callback invoked for an IOPub message.
  731. *
  732. * #### Notes
  733. * The IOPub hook system allows you to preempt the handlers for IOPub
  734. * messages handled by the future.
  735. *
  736. * The most recently registered hook is run first. A hook can return a
  737. * boolean or a promise to a boolean, in which case all kernel message
  738. * processing pauses until the promise is fulfilled. If a hook return value
  739. * resolves to false, any later hooks will not run and the function will
  740. * return a promise resolving to false. If a hook throws an error, the error
  741. * is logged to the console and the next hook is run. If a hook is
  742. * registered during the hook processing, it will not run until the next
  743. * message. If a hook is removed during the hook processing, it will be
  744. * deactivated immediately.
  745. */
  746. registerMessageHook(
  747. hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>
  748. ): void;
  749. /**
  750. * Remove a hook for IOPub messages.
  751. *
  752. * @param hook - The hook to remove.
  753. *
  754. * #### Notes
  755. * If a hook is removed during the hook processing, it will be deactivated immediately.
  756. */
  757. removeMessageHook(
  758. hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>
  759. ): void;
  760. /**
  761. * Send an `input_reply` message.
  762. */
  763. sendInputReply(content: KernelMessage.IInputReplyMsg['content']): void;
  764. }
  765. export interface IShellFuture<
  766. REQUEST extends KernelMessage.IShellMessage = KernelMessage.IShellMessage,
  767. REPLY extends KernelMessage.IShellMessage = KernelMessage.IShellMessage
  768. > extends IFuture<REQUEST, REPLY> {}
  769. export interface IControlFuture<
  770. REQUEST extends KernelMessage.IControlMessage = KernelMessage.IControlMessage,
  771. REPLY extends KernelMessage.IControlMessage = KernelMessage.IControlMessage
  772. > extends IFuture<REQUEST, REPLY> {}
  773. /**
  774. * A client side Comm interface.
  775. */
  776. export interface IComm extends IDisposable {
  777. /**
  778. * The unique id for the comm channel.
  779. */
  780. readonly commId: string;
  781. /**
  782. * The target name for the comm channel.
  783. */
  784. readonly targetName: string;
  785. /**
  786. * Callback for a comm close event.
  787. *
  788. * #### Notes
  789. * This is called when the comm is closed from either the server or client.
  790. * If this is called in response to a kernel message and the handler returns
  791. * a promise, all kernel message processing pauses until the promise is
  792. * resolved.
  793. */
  794. onClose: (msg: KernelMessage.ICommCloseMsg) => void | PromiseLike<void>;
  795. /**
  796. * Callback for a comm message received event.
  797. *
  798. * #### Notes
  799. * If the handler returns a promise, all kernel message processing pauses
  800. * until the promise is resolved.
  801. */
  802. onMsg: (msg: KernelMessage.ICommMsgMsg) => void | PromiseLike<void>;
  803. /**
  804. * Open a comm with optional data and metadata.
  805. *
  806. * @param data - The data to send to the server on opening.
  807. *
  808. * @param metadata - Additional metatada for the message.
  809. *
  810. * @returns A future for the generated message.
  811. *
  812. * #### Notes
  813. * This sends a `comm_open` message to the server.
  814. */
  815. open(
  816. data?: JSONValue,
  817. metadata?: JSONObject,
  818. buffers?: (ArrayBuffer | ArrayBufferView)[]
  819. ): IShellFuture;
  820. /**
  821. * Send a `comm_msg` message to the kernel.
  822. *
  823. * @param data - The data to send to the server on opening.
  824. *
  825. * @param metadata - Additional metatada for the message.
  826. *
  827. * @param buffers - Optional buffer data.
  828. *
  829. * @param disposeOnDone - Whether to dispose of the future when done.
  830. *
  831. * @returns A future for the generated message.
  832. *
  833. * #### Notes
  834. * This is a no-op if the comm has been closed.
  835. */
  836. send(
  837. data: JSONValue,
  838. metadata?: JSONObject,
  839. buffers?: (ArrayBuffer | ArrayBufferView)[],
  840. disposeOnDone?: boolean
  841. ): IShellFuture;
  842. /**
  843. * Close the comm.
  844. *
  845. * @param data - The data to send to the server on opening.
  846. *
  847. * @param metadata - Additional metatada for the message.
  848. *
  849. * @returns A future for the generated message.
  850. *
  851. * #### Notes
  852. * This will send a `comm_close` message to the kernel, and call the
  853. * `onClose` callback if set.
  854. *
  855. * This is a no-op if the comm is already closed.
  856. */
  857. close(
  858. data?: JSONValue,
  859. metadata?: JSONObject,
  860. buffers?: (ArrayBuffer | ArrayBufferView)[]
  861. ): IShellFuture;
  862. }
  863. /**
  864. * The valid Kernel status states.
  865. */
  866. export type Status =
  867. | 'unknown'
  868. | 'starting'
  869. | 'reconnecting'
  870. | 'idle'
  871. | 'busy'
  872. | 'restarting'
  873. | 'autorestarting'
  874. | 'dead'
  875. | 'connected';
  876. /**
  877. * The kernel model provided by the server.
  878. *
  879. * #### Notes
  880. * See the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
  881. */
  882. export interface IModel extends JSONObject {
  883. /**
  884. * Unique identifier of the kernel server session.
  885. */
  886. readonly id: string;
  887. /**
  888. * The name of the kernel.
  889. */
  890. readonly name: string;
  891. }
  892. /**
  893. * Kernel Spec interface.
  894. *
  895. * #### Notes
  896. * See [Kernel specs](https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs).
  897. */
  898. export interface ISpecModel extends JSONObject {
  899. /**
  900. * The name of the kernel spec.
  901. */
  902. readonly name: string;
  903. /**
  904. * The name of the language of the kernel.
  905. */
  906. readonly language: string;
  907. /**
  908. * A list of command line arguments used to start the kernel.
  909. */
  910. readonly argv: string[];
  911. /**
  912. * The kernel’s name as it should be displayed in the UI.
  913. */
  914. readonly display_name: string;
  915. /**
  916. * A dictionary of environment variables to set for the kernel.
  917. */
  918. readonly env?: JSONObject;
  919. /**
  920. * A mapping of resource file name to download path.
  921. */
  922. readonly resources: { [key: string]: string };
  923. }
  924. /**
  925. * The available kernelSpec models.
  926. *
  927. * #### Notes
  928. * See the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernelspecs).
  929. */
  930. export interface ISpecModels extends JSONObject {
  931. /**
  932. * The name of the default kernel spec.
  933. */
  934. default: string;
  935. /**
  936. * A mapping of kernel spec name to spec.
  937. */
  938. readonly kernelspecs: { [key: string]: ISpecModel };
  939. }
  940. /**
  941. * Arguments interface for the anyMessage signal.
  942. */
  943. export interface IAnyMessageArgs {
  944. /**
  945. * The message that is being signaled.
  946. */
  947. msg: Readonly<KernelMessage.IMessage>;
  948. /**
  949. * The direction of the message.
  950. */
  951. direction: 'send' | 'recv';
  952. }
  953. }