codebind 0.6.18__tar.gz → 0.6.20__tar.gz
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.
- {codebind-0.6.18 → codebind-0.6.20}/PKG-INFO +5 -13
- {codebind-0.6.18 → codebind-0.6.20}/README.md +4 -12
- {codebind-0.6.18 → codebind-0.6.20}/data/share/jupyter/labextensions/codebind-jupyterlab/package.json +1 -1
- codebind-0.6.20/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.0b7494e278aa27b9.js +1 -0
- codebind-0.6.18/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.24258c9500a0850a.js → codebind-0.6.20/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.8f763ad3faac0f5a.js +1 -1
- {codebind-0.6.18 → codebind-0.6.20}/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js +2 -0
- {codebind-0.6.18 → codebind-0.6.20}/jupyterlab/src/index.ts +84 -7
- {codebind-0.6.18 → codebind-0.6.20}/pyproject.toml +1 -1
- {codebind-0.6.18 → codebind-0.6.20}/pyproject.toml.orig +1 -1
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/execution.py +8 -1
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/extension.py +14 -1
- codebind-0.6.20/src/codebind/interrupts.py +9 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/jupyter.py +3 -1
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/session.py +3 -2
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/terminal.py +198 -19
- codebind-0.6.18/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.98c719a309e23852.js +0 -1
- {codebind-0.6.18 → codebind-0.6.20}/LICENSE +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/data/share/jupyter/labextensions/codebind-jupyterlab/install.json +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/jupyterlab/.yarnrc.yml +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/jupyterlab/install.json +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/jupyterlab/package.json +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/jupyterlab/tsconfig.json +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/jupyterlab/yarn.lock +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/__init__.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/async_runtime.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/cli.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/configuration.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/context.md +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/context.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/conversation.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/display.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/images.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/instructions.md +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/model_text.py +0 -0
- {codebind-0.6.18 → codebind-0.6.20}/src/codebind/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codebind
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.20
|
|
4
4
|
Summary: A frontend-neutral model loop for persistent IPython sessions.
|
|
5
5
|
Keywords: ai,ipython,llm,repl,agents
|
|
6
6
|
Author: Giovanni Gravili
|
|
@@ -66,7 +66,7 @@ Start a new conversation:
|
|
|
66
66
|
uvx codebind
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
-
Press `Shift+Tab` to switch the prompt into Question mode; the prompt turns purple. Type a question and press `Enter` to send it.
|
|
69
|
+
Press `Shift+Tab` to switch the prompt into Question mode; the prompt turns purple. Type a question and press `Enter` to send it. `Ctrl+J` starts a new Markdown line, and so does `Shift+Enter` in terminals that report the key with modifiers (macOS Terminal does not; iTerm2, Ghostty, WezTerm, and Kitty do). `Ctrl+C` while typing returns to Python mode without interrupting the kernel. Submitting a question also returns to Python mode automatically; press `Shift+Tab` again for another question. Ordinary `Tab` completion is unchanged. Codebind leaves terminal mouse reporting off so scrollback works while editing. Move the cursor with the keyboard or a terminal-native cursor-position shortcut, if your terminal supports one.
|
|
70
70
|
|
|
71
71
|
`%context` displays a Markdown breakdown of provider-reported model calls, including input, output, cached input (as tokens and a percentage of input), and reasoning tokens. It estimates context remaining after the last call; future inputs and tool output cannot be counted exactly until the provider responds.
|
|
72
72
|
|
|
@@ -80,7 +80,7 @@ Inspect this project and tell me what to implement first.
|
|
|
80
80
|
Codebind keeps its terminal prompt and internal bookkeeping usable when a tool cell leaves an asyncio loop active on the terminal thread. This also supports sync clients that manage their own loop across tool cells, without changing IPython’s normal top-level `await` behavior.
|
|
81
81
|
|
|
82
82
|
Terminal conversations remain live for the current IPython process. Previous terminal inputs and outputs, including Python cells you ran yourself, enter the model's context when you ask a question. Durable automatic resumption belongs to notebooks, where the notebook file provides an unambiguous conversation identity.
|
|
83
|
-
Model-executed cells appear with IPython's native input counter, syntax highlighting, output prompts, streams, and tracebacks. Assistant Markdown appears before the following tool cell, and tool output appears as it is written. To keep terminal scrollback usable, Codebind previews at most three gray output lines, shortening each line after 80 characters with `...`. Further lines appear as `… N more output lines.` Full output remains in IPython history, while model-facing text is bounded and displayed images stay available as image blocks; `%output 8` opens the full text of cell 8 in IPython's pager. User-entered Python cells keep IPython's normal display behavior. Assistant Markdown is rendered through IPython's terminal MIME renderer. A terminal is a stream rather than a notebook document, so these displays are not editable notebook cells.
|
|
83
|
+
While a question runs, its cell shows `In [*]` and its tools show `In [N]`, as a notebook does. `Ctrl+C` during a question stops the whole turn: it prints a plain `KeyboardInterrupt` and returns to the prompt, whether the interrupt lands in the model stream or in a running tool cell. Model-executed cells appear with IPython's native input counter, syntax highlighting, output prompts, streams, and tracebacks. Assistant Markdown appears before the following tool cell, and tool output appears as it is written. To keep terminal scrollback usable, Codebind previews at most three gray output lines, shortening each line after 80 characters with `...`. Further lines appear as `… N more output lines.` Full output remains in IPython history, while model-facing text is bounded and displayed images stay available as image blocks; `%output 8` opens the full text of cell 8 in IPython's pager. User-entered Python cells keep IPython's normal display behavior. Assistant Markdown is rendered through IPython's terminal MIME renderer. A terminal is a stream rather than a notebook document, so these displays are not editable notebook cells.
|
|
84
84
|
|
|
85
85
|
## JupyterLab
|
|
86
86
|
|
|
@@ -88,21 +88,13 @@ Model-executed cells appear with IPython's native input counter, syntax highligh
|
|
|
88
88
|
uvx --from jupyterlab --with codebind --with 'nbconvert[webpdf]' jupyter lab
|
|
89
89
|
```
|
|
90
90
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
```console
|
|
94
|
-
JUPYTER_PATH=/path/to/codebind/data/share/jupyter \
|
|
95
|
-
uvx --refresh --from jupyterlab --with-editable /path/to/codebind \
|
|
96
|
-
--with 'nbconvert[webpdf]' jupyter-lab
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
Load Codebind in a notebook:
|
|
91
|
+
Codebind loads itself into the notebook kernel as soon as that kernel is ready, in the background and without a cell, an output, or a prompt number, so there is no loading step. In a frontend that does not run this JupyterLab extension, load it yourself:
|
|
100
92
|
|
|
101
93
|
```python
|
|
102
94
|
%load_ext codebind
|
|
103
95
|
```
|
|
104
96
|
|
|
105
|
-
|
|
97
|
+
**Question** is a native toolbar toggle, also available with `Shift+Tab`:
|
|
106
98
|
|
|
107
99
|
- Turning it on converts the selected cell into a Question and makes each newly created user cell a Question until the toggle is turned off.
|
|
108
100
|
- Turning it off returns the selected unsent Question to a Python code cell.
|
|
@@ -37,7 +37,7 @@ Start a new conversation:
|
|
|
37
37
|
uvx codebind
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
Press `Shift+Tab` to switch the prompt into Question mode; the prompt turns purple. Type a question and press `Enter` to send it.
|
|
40
|
+
Press `Shift+Tab` to switch the prompt into Question mode; the prompt turns purple. Type a question and press `Enter` to send it. `Ctrl+J` starts a new Markdown line, and so does `Shift+Enter` in terminals that report the key with modifiers (macOS Terminal does not; iTerm2, Ghostty, WezTerm, and Kitty do). `Ctrl+C` while typing returns to Python mode without interrupting the kernel. Submitting a question also returns to Python mode automatically; press `Shift+Tab` again for another question. Ordinary `Tab` completion is unchanged. Codebind leaves terminal mouse reporting off so scrollback works while editing. Move the cursor with the keyboard or a terminal-native cursor-position shortcut, if your terminal supports one.
|
|
41
41
|
|
|
42
42
|
`%context` displays a Markdown breakdown of provider-reported model calls, including input, output, cached input (as tokens and a percentage of input), and reasoning tokens. It estimates context remaining after the last call; future inputs and tool output cannot be counted exactly until the provider responds.
|
|
43
43
|
|
|
@@ -51,7 +51,7 @@ Inspect this project and tell me what to implement first.
|
|
|
51
51
|
Codebind keeps its terminal prompt and internal bookkeeping usable when a tool cell leaves an asyncio loop active on the terminal thread. This also supports sync clients that manage their own loop across tool cells, without changing IPython’s normal top-level `await` behavior.
|
|
52
52
|
|
|
53
53
|
Terminal conversations remain live for the current IPython process. Previous terminal inputs and outputs, including Python cells you ran yourself, enter the model's context when you ask a question. Durable automatic resumption belongs to notebooks, where the notebook file provides an unambiguous conversation identity.
|
|
54
|
-
Model-executed cells appear with IPython's native input counter, syntax highlighting, output prompts, streams, and tracebacks. Assistant Markdown appears before the following tool cell, and tool output appears as it is written. To keep terminal scrollback usable, Codebind previews at most three gray output lines, shortening each line after 80 characters with `...`. Further lines appear as `… N more output lines.` Full output remains in IPython history, while model-facing text is bounded and displayed images stay available as image blocks; `%output 8` opens the full text of cell 8 in IPython's pager. User-entered Python cells keep IPython's normal display behavior. Assistant Markdown is rendered through IPython's terminal MIME renderer. A terminal is a stream rather than a notebook document, so these displays are not editable notebook cells.
|
|
54
|
+
While a question runs, its cell shows `In [*]` and its tools show `In [N]`, as a notebook does. `Ctrl+C` during a question stops the whole turn: it prints a plain `KeyboardInterrupt` and returns to the prompt, whether the interrupt lands in the model stream or in a running tool cell. Model-executed cells appear with IPython's native input counter, syntax highlighting, output prompts, streams, and tracebacks. Assistant Markdown appears before the following tool cell, and tool output appears as it is written. To keep terminal scrollback usable, Codebind previews at most three gray output lines, shortening each line after 80 characters with `...`. Further lines appear as `… N more output lines.` Full output remains in IPython history, while model-facing text is bounded and displayed images stay available as image blocks; `%output 8` opens the full text of cell 8 in IPython's pager. User-entered Python cells keep IPython's normal display behavior. Assistant Markdown is rendered through IPython's terminal MIME renderer. A terminal is a stream rather than a notebook document, so these displays are not editable notebook cells.
|
|
55
55
|
|
|
56
56
|
## JupyterLab
|
|
57
57
|
|
|
@@ -59,21 +59,13 @@ Model-executed cells appear with IPython's native input counter, syntax highligh
|
|
|
59
59
|
uvx --from jupyterlab --with codebind --with 'nbconvert[webpdf]' jupyter lab
|
|
60
60
|
```
|
|
61
61
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
```console
|
|
65
|
-
JUPYTER_PATH=/path/to/codebind/data/share/jupyter \
|
|
66
|
-
uvx --refresh --from jupyterlab --with-editable /path/to/codebind \
|
|
67
|
-
--with 'nbconvert[webpdf]' jupyter-lab
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
Load Codebind in a notebook:
|
|
62
|
+
Codebind loads itself into the notebook kernel as soon as that kernel is ready, in the background and without a cell, an output, or a prompt number, so there is no loading step. In a frontend that does not run this JupyterLab extension, load it yourself:
|
|
71
63
|
|
|
72
64
|
```python
|
|
73
65
|
%load_ext codebind
|
|
74
66
|
```
|
|
75
67
|
|
|
76
|
-
|
|
68
|
+
**Question** is a native toolbar toggle, also available with `Shift+Tab`:
|
|
77
69
|
|
|
78
70
|
- Turning it on converts the selected cell into a Question and makes each newly created user cell a Question until the toggle is turned off.
|
|
79
71
|
- Turning it off returns the selected unsent Question to a Python code cell.
|
codebind-0.6.20/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.0b7494e278aa27b9.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";(self.rspackChunkcodebind_jupyterlab=self.rspackChunkcodebind_jupyterlab||[]).push([[590],{509(e,t,n){n.r(t);var o=n(511),l=n(343),d=n(99),i=n(171),r=n(241);let s="codebind:insert-question",a="codebind:toggle-question-mode",c="codebind:run-question",u="jp-CodebindQuestionCell",m=new WeakSet,p=new WeakMap,g=new WeakMap,f=new WeakMap,y=new WeakMap;function w(e){let t=e.getMetadata("codebind");return"object"!=typeof t||null===t||"question"!==t.kind?null:{kind:"question",status:"draft"===t.status?"draft":"sent"}}function _(e){let t=e.getMetadata("codebind");if("object"!=typeof t||null===t)return null;let n=t.kind;return"string"==typeof n?n:null}function b(e){let t={},n=[];for(let[o,l]of Object.entries(e))o.startsWith("text/")||["image/png","image/jpeg","image/webp","image/gif","image/svg+xml"].includes(o)||"application/json"===o||"application/vnd.jupyter.stdout"===o||"application/vnd.jupyter.stderr"===o?void 0!==l&&(t[o]=l):n.push(o);return n.length>0&&(t.omitted_mime_types=n),t}function k(e){return d.isStream(e)?{type:"stream",name:e.name,text:e.text}:d.isError(e)?{type:"error",name:e.ename,message:e.evalue,traceback:e.traceback}:d.isExecuteResult(e)?{type:"result",execution_count:e.execution_count,data:b(e.data)}:d.isDisplayData(e)?{type:"display",data:b(e.data)}:{type:e.output_type}}function h(e){return e.replace(/(^|[^\\])\\([()[\]])/g,"$1\\\\$2")}function C(e){let t=f.get(e);for(let n of e.content.widgets){let e=w(n.model);n.node.classList.toggle(u,null!==e);let o=n.node.querySelector(".jp-InputPrompt");o&&(e?(n.readOnly="sent"===e.status,o.dataset.codebindQuestion="true",o.style.color="#a855f7",o.textContent=t?.runningQuestions.has(n.model.id)?"[*]:":"[ ]:"):o.dataset.codebindQuestion&&(delete o.dataset.codebindQuestion,o.style.removeProperty("color"),o.textContent=""))}}function v(e){let t=e.content;for(let e of t.widgets)"instructions"===_(e.model)&&(e.node.hidden=!0);if(t.activeCell&&"instructions"===_(t.activeCell.model)){let e=t.widgets.findIndex(e=>"instructions"!==_(e.model));e>=0&&(t.activeCellIndex=e)}}function M(e,t){let n,o=p.get(t);if(o)return o;if(m.has(t)||(n=e.serviceManager.kernelspecs.specs?.kernelspecs?.[t.name])&&"python"!==(n.language??"").toLowerCase())return m.add(t),Promise.resolve();let l=t.requestExecute({code:"%load_ext codebind",silent:!0,store_history:!1,stop_on_error:!1}).done.then(e=>{let n=e.content;"error"===n.status?g.set(t,`${n.ename??"Error"}: ${n.evalue??"unknown"}`):m.add(t)},()=>void 0);return p.set(t,l),l}function q(e,t){let n=e.sessionContext.session?.kernel;if(!n)return;let d=f.get(e)??{comm:null,kernel:null,registeredKernel:null,connectKernel:null,disconnectKernel:null,ready:null,resolveReady:null,rejectReady:null,connectOnIdle:!1,runningQuestions:new Map,questionTimers:new Map,sessionReady:!1,cancelAcknowledged:!1,questionMode:!1,questionButton:null,knownCellIds:new Set(e.content.widgets.map(e=>e.model.id)),pendingQuestionCellIds:new Set};if(f.set(e,d),d.registeredKernel===n)return;d.disconnectKernel?.(),d.rejectReady?.(Error("The notebook kernel changed.")),d.comm?.close(),d.registeredKernel=n,d.connectKernel=null,d.disconnectKernel=null,d.ready=null,d.resolveReady=null,d.rejectReady=null,d.connectOnIdle=!1;d.kernel&&d.kernel!==n&&y.get(d.kernel)?.delete(d),d.kernel=n;let i=y.get(n);if(!i){i=new Set,y.set(n,i);let e=n.interrupt.bind(n);n.interrupt=async()=>{let t=[...i??[]].filter(e=>e.runningQuestions.size>0);for(let e of t)e.cancelAcknowledged=!1;if(t.length>0)try{let e=r.KernelMessage.createMessage({session:n.clientId,username:n.username,channel:"control",msgType:"interrupt_request",content:{}});n.sendControlMessage(e,!0).done.catch(()=>void 0)}catch{}for(let e=0;t.length>0&&e<150;e+=1){if(t.every(e=>0===e.runningQuestions.size||e.cancelAcknowledged))return;await new Promise(e=>setTimeout(e,20))}return e()}}for(let e of(i.add(d),d.comm=null,d.runningQuestions.clear(),d.questionTimers.values()))window.clearTimeout(e);d.questionTimers.clear(),d.sessionReady=!1,d.cancelAcknowledged=!1;let s=null,a=new Map,c=new Map,u=()=>{if(!s)return;let e=s;s=null,e.parentModel&&null!==e.parentExecutionCount&&(e.parentModel.executionCount=e.parentExecutionCount)},p=()=>{if(d.comm||"idle"!==n.status||!e.content.model)return;if(!m.has(n)){d.connectOnIdle=!0,M(t,n).then(()=>{"idle"!==n.status||d.comm||(d.connectOnIdle=!1,p())});return}let i=n.createComm("codebind");i.commsOverSubshells=r.CommsOverSubshells.Disabled,d.comm=i,d.sessionReady=!1,d.ready=new Promise((e,t)=>{d.resolveReady=e,d.rejectReady=t}),d.ready.catch(()=>void 0),i.onMsg=t=>{let r,m=t.content.data;if(!function(e){if("object"!=typeof e||null===e)return!1;if("markdown_cell"===e.type)return"string"==typeof e.source;if("markdown_cell_started"===e.type||"markdown_cell_updated"===e.type||"markdown_cell_finished"===e.type)return"string"==typeof e.cell_id&&"string"==typeof e.source;if("markdown_cell_cancelled"===e.type)return"string"==typeof e.cell_id;if("code_cell_started"===e.type)return"string"==typeof e.cell_id&&"string"==typeof e.source;if("code_cell_cancelled"===e.type)return"string"==typeof e.cell_id;if("code_cell_output"===e.type)return"string"==typeof e.cell_id&&"object"==typeof e.output&&null!==e.output;if("code_cell_clear"===e.type)return"string"==typeof e.cell_id&&"boolean"==typeof e.wait;if("question_finished"===e.type){let t=e.error;return"string"==typeof e.cell_id&&"boolean"==typeof e.cancelled&&(null===t||"object"==typeof t&&"string"==typeof t.type&&"string"==typeof t.message)}if("question_started"===e.type)return"string"==typeof e.cell_id;if("cancel_acknowledged"===e.type)return!0;if("session_ready"===e.type){let t=e.error;return null===t||"object"==typeof t&&"string"==typeof t.type&&"string"==typeof t.message}return"conversation_save"===e.type?"string"==typeof e.request_id&&"object"==typeof e.conversation&&null!==e.conversation:"code_cell_finished"===e.type&&"string"==typeof e.cell_id&&("number"==typeof e.execution_count||null===e.execution_count)&&Array.isArray(e.outputs)}(m))return;if("conversation_save"===m.type){let t=e.content.model;return t?(t.setMetadata("codebind",m.conversation),void e.context.save().then(()=>{i.send({type:"conversation_saved",request_id:m.request_id,error:null})},e=>{i.send({type:"conversation_saved",request_id:m.request_id,error:String(e)})})):void i.send({type:"conversation_saved",request_id:m.request_id,error:"Notebook model is unavailable."})}if("session_ready"===m.type){d.sessionReady=null===m.error,m.error?(d.rejectReady?.(Error(m.error.message)),(0,o.showErrorMessage)(`Codebind could not load: ${m.error.type}`,m.error.message)):d.resolveReady?.(),d.resolveReady=null,d.rejectReady=null;return}if("question_started"===m.type){let e=d.questionTimers.get(m.cell_id);void 0!==e&&(window.clearTimeout(e),d.questionTimers.delete(m.cell_id));return}if("cancel_acknowledged"===m.type){d.cancelAcknowledged=!0;return}if("question_finished"===m.type){let t=d.questionTimers.get(m.cell_id);void 0!==t&&(window.clearTimeout(t),d.questionTimers.delete(m.cell_id)),d.runningQuestions.delete(m.cell_id),0===d.runningQuestions.size&&(d.cancelAcknowledged=!1),C(e),u(),m.error&&!m.cancelled&&(0,o.showErrorMessage)(`Codebind question: ${m.error.type}`,m.error.message);return}if("markdown_cell_updated"===m.type||"markdown_cell_finished"===m.type){let t=c.get(m.cell_id);if(!t)return;t.sharedModel.setSource(h(m.source));let n=e.content.widgets.find(e=>e.model.id===t.id);n instanceof l.MarkdownCell&&(n.rendered=!0),"markdown_cell_finished"===m.type&&c.delete(m.cell_id);return}if("markdown_cell_cancelled"===m.type){let t=c.get(m.cell_id);if(c.delete(m.cell_id),!t)return;let n=e.content.widgets.findIndex(e=>e.model.id===t.id);n>=0&&e.content.model?.sharedModel.deleteCell(n);return}if("code_cell_output"===m.type)return void a.get(m.cell_id)?.outputs.add(m.output);if("code_cell_clear"===m.type)return void a.get(m.cell_id)?.outputs.clear(m.wait);if("code_cell_finished"===m.type){let e=a.get(m.cell_id);if(a.delete(m.cell_id),!e)return;e.outputs.fromJSON(m.outputs),e.executionCount=m.execution_count,e.executionState="idle",s&&null===s.parentExecutionCount&&null!==m.execution_count&&(s.parentExecutionCount=m.execution_count-1);return}if("code_cell_cancelled"===m.type){let e=a.get(m.cell_id);a.delete(m.cell_id),e&&(e.executionState="idle");return}if("markdown_cell_started"===m.type)r={type:"markdown_cell",source:m.source};else{if("markdown_cell"!==m.type&&"code_cell_started"!==m.type)return;r=m}(()=>{if(s)return;let t=e.content,o=t.widgets.findIndex(e=>"code"===e.model.type&&"running"===e.model.executionState);s={parentModel:o>=0?t.widgets[o].model:null,parentExecutionCount:null};let l=(e,t)=>{"idle"===t&&(n.statusChanged.disconnect(l),u())};return n.statusChanged.connect(l)})();let p=function(e,t){let n=e.content,o=n.model;if(!o)return null;let d=n.widgets.length;"code_cell_started"===t.type?o.sharedModel.insertCell(d,{cell_type:"code",source:t.source,metadata:{trusted:!0,collapsed:!0,editable:!1,deletable:!1,codebind:{kind:"tool"}},execution_count:null,outputs:[]}):o.sharedModel.insertCell(d,{cell_type:"markdown",source:h(t.source),metadata:{editable:!1,deletable:!1,codebind:{kind:"assistant"}}});let i=n.widgets[d]??null;return i&&(i.readOnly=!0),i instanceof l.MarkdownCell&&(i.rendered=!0),i?.model??null}(e,r);"code_cell_started"===m.type&&p?.type==="code"&&(p.executionState="running",a.set(m.cell_id,p)),"markdown_cell_started"===m.type&&p&&c.set(m.cell_id,p)},i.onClose=()=>{if(d.comm===i){let t=d.sessionReady;for(let e of a.values())e.executionState="idle";for(let e of(a.clear(),d.runningQuestions.clear(),d.cancelAcknowledged=!1,d.questionTimers.values()))window.clearTimeout(e);d.questionTimers.clear(),C(e),d.rejectReady?.(Error("Codebind is not loaded in this kernel. Run %load_ext codebind.")),d.comm=null,d.sessionReady=!1,d.ready=null,d.resolveReady=null,d.rejectReady=null,d.connectOnIdle=t}};let g=e.content.model?.getMetadata("codebind");i.open({conversation:"object"==typeof g&&null!==g?g:null})};d.connectKernel=p;let g=(e,t)=>{"idle"===t&&d.connectOnIdle&&(d.connectOnIdle=!1,p())},w=(e,t)=>{r.KernelMessage.isExecuteInputMsg(t)&&/(?:^|\n)\s*%(?:re)?load_ext\s+codebind(?:\s|$)/.test(t.content.code)&&(d.connectOnIdle=!0)};n.statusChanged.connect(g),n.iopubMessage.connect(w),M(t,n),d.disconnectKernel=()=>{n.statusChanged.disconnect(g),n.iopubMessage.disconnect(w)},e.context.ready.then(()=>{e.content.model?.getMetadata("codebind")&&(d.connectOnIdle=!0,p())})}function x(e){let t=e.content,n=t.model;if(!n)return;t.activeCell?"markdown"!==t.activeCell.model.type&&i.NotebookActions.changeCellType(t,"markdown"):(n.sharedModel.insertCell(0,{cell_type:"markdown",source:"",metadata:{}}),t.activeCellIndex=0);let o=t.activeCell;o&&null!==_(o.model)||(o?.model.setMetadata("codebind",{kind:"question",status:"draft"}),o instanceof l.MarkdownCell&&(o.rendered=!1),t.mode="edit",C(e),o?.editor?.focus())}function T(e){let t=f.get(e);if(!t)return;v(e);let n=e.content.widgets,o=new Set(n.map(e=>e.model.id)),l=n.filter(e=>!t.knownCellIds.has(e.model.id));for(let e of(t.knownCellIds=o,t.pendingQuestionCellIds))o.has(e)||t.pendingQuestionCellIds.delete(e);if(t.questionMode)for(let e of l)null===_(e.model)&&t.pendingQuestionCellIds.add(e.model.id);C(e),t.questionMode&&e.content.activeCell&&t.pendingQuestionCellIds.delete(e.content.activeCell.model.id)&&x(e)}function E(e){let t=f.get(e);t&&I(e,!t.questionMode)}function I(e,t){let n=f.get(e);if(n){if(n.questionMode=t,!n.questionMode){n.pendingQuestionCellIds.clear();let t=e.content.activeCell;t&&w(t.model)?.status==="draft"&&(t.model.deleteMetadata("codebind"),i.NotebookActions.changeCellType(e.content,"code"),e.content.mode="edit",e.content.activeCell?.editor?.focus())}n.questionButton&&(n.questionButton.pressed=n.questionMode),n.questionMode&&e.content.activeCell&&null===_(e.content.activeCell.model)&&x(e)}}async function Q(e,t){let n=e.content,d=n.activeCell;if(!d||!w(d.model))return;await e.sessionContext.ready,q(e,t);let i=f.get(e),r=i?.registeredKernel;if(!i||!r)return void await (0,o.showErrorMessage)("Codebind is not connected","Start the notebook kernel before sending a Question cell.");try{if("dead"===r.status)throw Error("The notebook kernel stopped.");if("idle"!==r.status&&await new Promise((e,t)=>{let n=(o,l)=>{("idle"===l||"dead"===l)&&(r.statusChanged.disconnect(n),"idle"===l?e():t(Error("The notebook kernel stopped.")))};r.statusChanged.connect(n)}),i.connectKernel?.(),i.ready||(await M(t,r),"idle"===r.status&&(i.connectOnIdle=!1,i.connectKernel?.())),!i.ready)throw Error(g.get(r)??"Run %load_ext codebind in this kernel.");await i.ready}catch(e){await (0,o.showErrorMessage)("Codebind could not load",String(e));return}if(!i.sessionReady||!i.comm)return void await (0,o.showErrorMessage)("Codebind is not connected","Run %load_ext codebind in this kernel before sending a Question cell.");if(i.runningQuestions.size>0)return void await (0,o.showErrorMessage)("Codebind is busy","Wait for the current question to finish before sending another.");let s=d.model.sharedModel.getSource().trim();if(!s)return void await (0,o.showErrorMessage)("Empty Codebind question","Write a question before sending it.");i.runningQuestions.set(d.model.id,d.model),i.cancelAcknowledged=!1,d.model.sharedModel.setSource(h(s)),d.model.setMetadata("codebind",{kind:"question",status:"sent"}),d.model.setMetadata("editable",!1),d.model.setMetadata("deletable",!1),d.readOnly=!0,C(e),d instanceof l.MarkdownCell&&(d.rendered=!0),n.mode="command";let a=window.setTimeout(()=>{i.questionTimers.has(d.model.id)&&(i.questionTimers.delete(d.model.id),i.runningQuestions.delete(d.model.id),d.model.setMetadata("codebind",{kind:"question",status:"draft"}),d.model.setMetadata("editable",!0),d.model.setMetadata("deletable",!0),d.readOnly=!1,C(e),(0,o.showErrorMessage)("Codebind did not receive the Question","The kernel did not acknowledge it. Reload Codebind and send it again."))},1e4);i.questionTimers.set(d.model.id,a),i.comm.send({type:"question",cell_id:d.model.id,question:s,notebook:function(e){let t=[];for(let n of e.content.widgets){if(null!==_(n.model))continue;let e=n.model.type;if("code"!==e&&"markdown"!==e&&"raw"!==e)continue;let o={id:n.model.id,type:e,source:n.model.sharedModel.getSource(),execution_count:null,outputs:[],attachments:{}};if("code"===e){let e=n.model.toJSON();o.execution_count=e.execution_count,o.outputs=e.outputs.map(k)}else{let e=n.model.toJSON().attachments;if(e){let t={};for(let[n,o]of Object.entries(e))o&&(t[n]=b(o));o.attachments=t}}t.push(o)}return t}(e)})}function j(e,t){let n={comm:null,kernel:null,registeredKernel:null,connectKernel:null,disconnectKernel:null,ready:null,resolveReady:null,rejectReady:null,connectOnIdle:!1,runningQuestions:new Map,questionTimers:new Map,sessionReady:!1,cancelAcknowledged:!1,questionMode:!1,questionButton:null,knownCellIds:new Set(e.content.widgets.map(e=>e.model.id)),pendingQuestionCellIds:new Set};f.set(e,n);let l=!1,d=()=>{if(!l){if(!n.kernel){n.runningQuestions.size>0&&(n.cancelAcknowledged=!1,n.comm?.send({type:"cancel"}));return}l=!0,n.kernel.interrupt().catch(e=>{n.runningQuestions.size>0&&(0,o.showErrorMessage)("Codebind could not interrupt",String(e))}).finally(()=>{l=!1})}},i=e=>{0!==n.runningQuestions.size&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),d())},r=n=>{"Tab"===n.key&&n.shiftKey&&!n.ctrlKey&&!n.altKey&&!n.metaKey&&n.target instanceof Node&&e.content.node.contains(n.target)&&(n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),E(e),t.commands.notifyCommandChanged(a))},s=o=>{0===n.runningQuestions.size||t.shell.currentWidget!==e||"c"!==o.key.toLowerCase()||!o.ctrlKey||o.altKey||o.metaKey||o.shiftKey||(o.preventDefault(),o.stopPropagation(),o.stopImmediatePropagation(),d())};e.node.addEventListener("keydown",r,!0),window.addEventListener("keydown",s,!0);let c=null,u=()=>{let t=e.toolbar.node.querySelector('[data-command="notebook:interrupt-kernel"]');t!==c&&(c?.removeEventListener("click",i,!0),c=t,c?.addEventListener("click",i,!0))},m=new MutationObserver(u);m.observe(e.toolbar.node,{childList:!0,subtree:!0});let p=new MutationObserver(()=>{window.setTimeout(()=>T(e),0)});p.observe(e.content.node,{childList:!0,subtree:!0}),u(),e.disposed.connect(()=>{for(let t of(m.disconnect(),p.disconnect(),c?.removeEventListener("click",i,!0),e.node.removeEventListener("keydown",r,!0),window.removeEventListener("keydown",s,!0),n.disconnectKernel?.(),n.rejectReady?.(Error("The notebook closed.")),n.comm?.close(),n.kernel&&y.get(n.kernel)?.delete(n),n.questionTimers.values()))window.clearTimeout(t);n.questionTimers.clear()});let g=new o.ToolbarButton({label:"Question",tooltip:"Toggle Question mode for the selected and newly created cells",onClick:()=>{I(e,g.pressed),t.commands.notifyCommandChanged(a)}});n.questionButton=g,e.toolbar.insertItem(10,"codebindQuestion",g),e.content.modelContentChanged.connect(()=>{T(e),window.setTimeout(()=>T(e),0)}),e.content.activeCellChanged.connect(()=>T(e)),e.context.ready.then(()=>{v(e),e.content.model?.cells.changed.connect(()=>{T(e),window.setTimeout(()=>T(e),0)}),T(e)}),e.sessionContext.ready.then(()=>q(e,t)),e.sessionContext.kernelChanged.connect(()=>q(e,t))}let S={id:"codebind-jupyterlab:plugin",description:"Insert Codebind executions as native notebook cells.",autoStart:!0,requires:[i.INotebookTracker],activate:(e,t)=>{e.commands.addCommand(s,{label:"Use Selected Cell as Codebind Question",execute:()=>{let e=t.currentWidget;e&&x(e)}}),e.commands.addCommand(a,{label:"Toggle Codebind Question Mode",isToggled:()=>{let e=t.currentWidget;return!!e&&(f.get(e)?.questionMode??!1)},execute:()=>{let n=t.currentWidget;n&&(E(n),e.commands.notifyCommandChanged(a))}}),e.commands.addCommand(c,{label:"Send Codebind Question",isEnabled:()=>{let e=t.currentWidget?.content.activeCell;return!!e&&null!==w(e.model)},execute:async()=>{let n=t.currentWidget;n&&await Q(n,e)}}),e.commands.addKeyBinding({command:c,keys:["Shift Enter"],selector:`.jp-Notebook.jp-mod-editMode .${u}`}),e.commands.addKeyBinding({command:c,keys:["Shift Enter"],selector:`.jp-Notebook.jp-mod-commandMode .${u}`}),e.contextMenu.addItem({command:s,selector:".jp-Notebook .jp-Cell",rank:8}),t.forEach(t=>j(t,e)),t.widgetAdded.connect((t,n)=>j(n,e))}};n.d(t,{},{default:S})}}]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _JUPYTERLAB;(()=>{"use strict";var e,n,r,t,o,i,u,a,l,c,s,f,p,d,h,g,v,y,m,b,S,k,j,w,E,x,T,M,P,V,q,A,C,O,D,_,L,N={457(e,n,r){var t={"./index":()=>r.e(590).then(()=>()=>r(509)),"./extension":()=>r.e(590).then(()=>()=>r(509))},o=function(e,n){return r.R=n,n=r.o(t,e)?t[e]():Promise.resolve().then(()=>{throw Error('Module "'+e+'" does not exist in container.')}),r.R=void 0,n},i=function(e,n){if(r.S){var t="default",o=r.S[t];if(o&&o!==e)throw Error("Container initialization failed as it has already been initialized with a different share scope");return r.S[t]=e,r.I(t,n)}};r.d(n,{get:()=>o,init:()=>i})}},$={};function z(e){var n=$[e];if(void 0!==n)return n.exports;var r=$[e]={exports:{}};return N[e](r,r.exports,z),r.exports}z.m=N,z.c=$,z.n=e=>{var n=e&&e.__esModule?()=>e.default:()=>e;return z.d(n,{a:n}),n},z.d=(e,n,r)=>{var t=(n,r)=>{for(var t in n)z.o(n,t)&&!z.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,[r]:n[t]})};t(n,"get"),t(r,"value")},z.f={},z.e=e=>Promise.all(Object.keys(z.f).reduce((n,r)=>(z.f[r](e,n),n),[])),z.u=e=>""+e+".98c719a309e23852.js?v=98c719a309e23852",z.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),z.o=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),I={},z.l=function(e,n,r,t){if(I[e])return void I[e].push(n);if(void 0!==r)for(var o,i,u=document.getElementsByTagName("script"),a=0;a<u.length;a++){var l=u[a];if(l.getAttribute("src")==e||l.getAttribute("data-rspack")=="codebind-jupyterlab:"+r){o=l;break}}o||(i=!0,(o=document.createElement("script")).timeout=120,z.nc&&o.setAttribute("nonce",z.nc),o.setAttribute("data-rspack","codebind-jupyterlab:"+r),o.src=e),I[e]=[n];var c=function(n,r){o.onerror=o.onload=null,clearTimeout(s);var t=I[e];if(delete I[e],o.parentNode&&o.parentNode.removeChild(o),t&&t.forEach(function(e){return e(r)}),n)return n(r)},s=setTimeout(c.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=c.bind(null,o.onerror),o.onload=c.bind(null,o.onload),i&&document.head.appendChild(o)},z.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},z.S={},z.initializeSharingData={scopeToSharingDataMapping:{default:[{name:"codebind-jupyterlab",version:"0.6.11",factory:()=>z.e(590).then(()=>()=>z(509)),eager:0,treeShakingMode:null}]},uniqueName:"codebind-jupyterlab"},R={},U={},z.I=function(e,n){n||(n=[]);var r=U[e];if(r||(r=U[e]={}),!(n.indexOf(r)>=0)){if(n.push(r),R[e])return R[e];z.o(z.S,e)||(z.S[e]={});var t=z.S[e],o=function(e){"u">typeof console&&console.warn&&console.warn(e)},i=z.initializeSharingData.uniqueName,u=function(e,n,r,o){var u=t[e]=t[e]||{},a=u[n];(!a||!a.loaded&&(!o!=!a.eager?o:i>a.from))&&(u[n]={get:r,from:i,eager:!!o})},a=function(r){var t=function(e){o("Initialization of sharing external failed: "+e)};try{var i=z(r);if(!i)return;var u=function(r){return r&&r.init&&r.init(z.S[e],n)};if(i.then)return l.push(i.then(u,t));var a=u(i);if(a&&a.then)return l.push(a.catch(t))}catch(e){t(e)}},l=[],c=z.initializeSharingData.scopeToSharingDataMapping;return(c[e]&&c[e].forEach(function(e){"object"==typeof e?u(e.name,e.version,e.factory,e.eager):a(e)}),l.length)?R[e]=Promise.all(l).then(function(){return R[e]=1}):R[e]=1}},z.g.importScripts&&(B=z.g.location+"");var I,R,U,B,K=z.g.document;if(!B&&K&&(K.currentScript&&"SCRIPT"===K.currentScript.tagName.toUpperCase()&&(B=K.currentScript.src),!B)){var J=K.getElementsByTagName("script");if(J.length)for(var Y=J.length-1;Y>-1&&(!B||!/^http(s?):/.test(B));)B=J[Y--].src}if(!B)throw Error("Automatic publicPath is not supported in this browser");z.p=B=B.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),z.consumesLoadingData={chunkMapping:{590:["511","343","99","171","241"]},moduleIdToConsumeDataMapping:{171:{shareScope:"default",shareKey:"@jupyterlab/notebook",import:null,requiredVersion:"^4.6.3",strictVersion:!1,singleton:!0,eager:!1,fallback:void 0,treeShakingMode:null},241:{shareScope:"default",shareKey:"@jupyterlab/services",import:null,requiredVersion:"^7.6.3",strictVersion:!1,singleton:!0,eager:!1,fallback:void 0,treeShakingMode:null},343:{shareScope:"default",shareKey:"@jupyterlab/cells",import:null,requiredVersion:"^4.6.3",strictVersion:!1,singleton:!1,eager:!1,fallback:void 0,treeShakingMode:null},511:{shareScope:"default",shareKey:"@jupyterlab/apputils",import:null,requiredVersion:"^4.7.3",strictVersion:!1,singleton:!0,eager:!1,fallback:void 0,treeShakingMode:null},99:{shareScope:"default",shareKey:"@jupyterlab/nbformat",import:null,requiredVersion:"^4.6.3",strictVersion:!1,singleton:!1,eager:!1,fallback:void 0,treeShakingMode:null}},initialConsumes:[]},e=function(e){return e.split(".").map(function(e){return+e==e?+e:e})},n=function(n){var r=function(n){var r=/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(n),t=r[1]?[0].concat(e(r[1])):[0];r[2]&&(t.length++,t.push.apply(t,e(r[2])));let o=t[t.length-1];for(;t.length&&(void 0===o||/^[*xX]$/.test(o));)t.pop(),o=t[t.length-1];return t},t=function(e){return 1===e.length?[0]:2===e.length?[1].concat(e.slice(1)):3===e.length?[2].concat(e.slice(1)):[e.length].concat(e.slice(1))},o=function(e){return[-e[0]-1].concat(e.slice(1))},i=function(e){let n=/^(\^|~|<=|<|>=|>|=|v|!)/.exec(e),i=n?n[0]:"",u=r(i.length?e.slice(i.length).trim():e.trim());switch(i){case"^":if(u.length>1&&0===u[1]){if(u.length>2&&0===u[2])return[3].concat(u.slice(1));return[2].concat(u.slice(1))}return[1].concat(u.slice(1));case"~":return[2].concat(u.slice(1));case">=":return u;case"=":case"v":case"":return t(u);case"<":return o(u);case">":return[,t(u),0,u,2];case"<=":return[,t(u),o(u),1];case"!":return[,t(u),0];default:throw Error("Unexpected start value")}},u=function(e,n){if(1===e.length)return e[0];let r=[];for(let n of e.slice().reverse())0 in n?r.push(n):r.push.apply(r,n.slice(1));return[,].concat(r,e.slice(1).map(()=>n))};return u(n.split(/\s*\|\|\s*/).map(function(e){let n=e.split(/\s+-\s+/);if(1===n.length){e=e.trim();let n=[],r=/[-0-9A-Za-z]\s+/g;for(var a,l=0;a=r.exec(e);){let r=a.index+1;n.push(i(e.slice(l,r).trim())),l=r}return n.push(i(e.slice(l).trim())),u(n,2)}let c=r(n[0]),s=r(n[1]);return[,t(s),o(s),1,c,2]}),1)},r=function(n){var r=/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(n),t=r[1]?e(r[1]):[];return r[2]&&(t.length++,t.push.apply(t,e(r[2]))),r[3]&&(t.push([]),t.push.apply(t,e(r[3]))),t},t=function(e,n){e=r(e),n=r(n);for(var t=0;;){if(t>=e.length)return t<n.length&&"u"!=(typeof n[t])[0];var o=e[t],i=(typeof o)[0];if(t>=n.length)return"u"==i;var u=n[t],a=(typeof u)[0];if(i==a){if("o"!=i&&"u"!=i&&o!=u)return o<u;t++}else{if("o"==i&&"n"==a)return!0;return"s"==a||"u"==i}}},o=function(e){var n=e[0],r="";if(1===e.length)return"*";if(n+.5){r+=0==n?">=":-1==n?"<":1==n?"^":2==n?"~":n>0?"=":"!=";for(var t=1,i=1;i<e.length;i++){var u=e[i],a=(typeof u)[0];t--,r+="u"==a?"-":(t>0?".":"")+(t=2,u)}return r}for(var l=[],i=1;i<e.length;i++){var u=e[i];l.push(0===u?"not("+c()+")":1===u?"("+c()+" || "+c()+")":2===u?l.pop()+" "+l.pop():o(u))}return c();function c(){return l.pop().replace(/^\((.+)\)$/,"$1")}},i=function(e,n){if(0 in e){n=r(n);var t=e[0],o=t<0;o&&(t=-t-1);for(var u=0,a=1,l=!0;;a++,u++){var c,s,f=a<e.length?(typeof e[a])[0]:"";if(u>=n.length||"o"==(s=(typeof(c=n[u]))[0])){if(!l)return!0;if("u"==f)return a>t&&!o;return""==f!=o}if("u"==s){if(!l||"u"!=f)return!1}else if(l)if(f==s)if(a<=t){if(c!=e[a])return!1}else{if(o?c>e[a]:c<e[a])return!1;c!=e[a]&&(l=!1)}else if("s"!=f&&"n"!=f){if(o||a<=t)return!1;l=!1,a--}else{if(a<=t||s<f!=o)return!1;l=!1}else"s"!=f&&"n"!=f&&(l=!1,a--)}}for(var p=[],d=p.pop.bind(p),u=1;u<e.length;u++){var h=e[u];p.push(1==h?d()|d():2==h?d()&d():h?i(h,n):!d())}return!!d()},u=function(e,n){var r=z.S[e];if(!r||!z.o(r,n))throw Error("Shared module "+n+" doesn't exist in shared scope "+e);return r},a=function(e,n){var r=e[n],n=Object.keys(r).reduce(function(e,n){return!e||t(e,n)?n:e},0);return n&&r[n]},l=function(e,n){var r=e[n];return Object.keys(r).reduce(function(e,n){return!e||!r[e].loaded&&t(e,n)?n:e},0)},c=function(e,n,r,t){return"Unsatisfied version "+r+" from "+(r&&e[n][r].from)+" of shared singleton module "+n+" (required "+o(t)+")"},s=function(e,n,r,t){var o=l(e,r);return m(e[r][o])},f=function(e,n,r,t){var o=l(e,r);return i(t,o)||v(c(e,r,o,t)),m(e[r][o])},p=function(e,n,r,t){var o=l(e,r);if(!i(t,o))throw Error(c(e,r,o,t));return m(e[r][o])},d=function(e,n,r){var o=e[n],n=Object.keys(o).reduce(function(e,n){return i(r,n)&&(!e||t(e,n))?n:e},0);return n&&o[n]},h=function(e,n,r,t){var i=e[r];return"No satisfying version ("+o(t)+") of shared module "+r+" found in shared scope "+n+".\nAvailable versions: "+Object.keys(i).map(function(e){return e+" from "+i[e].from}).join(", ")},g=function(e,n,r,t){var o=d(e,r,t);if(o)return m(o);throw Error(h(e,n,r,t))},v=function(e){"u">typeof console&&console.warn&&console.warn(e)},y=function(e,n,r,t){v(h(e,n,r,t))},m=function(e){return e.loaded=1,e.get()},S=(b=function(e){return function(n,r,t,o){var i=z.I(n);return i&&i.then?i.then(e.bind(e,n,z.S[n],r,t,o)):e(n,z.S[n],r,t,o)}})(function(e,n,r){return u(e,r),m(a(n,r))}),k=b(function(e,n,r,t){return n&&z.o(n,r)?m(a(n,r)):t()}),j=b(function(e,n,r,t){return u(e,r),m(d(n,r,t)||y(n,e,r,t)||a(n,r))}),w=b(function(e,n,r){return u(e,r),s(n,e,r)}),E=b(function(e,n,r,t){return u(e,r),f(n,e,r,t)}),x=b(function(e,n,r,t){return u(e,r),g(n,e,r,t)}),T=b(function(e,n,r,t){return u(e,r),p(n,e,r,t)}),M=b(function(e,n,r,t,o){return n&&z.o(n,r)?m(d(n,r,t)||y(n,e,r,t)||a(n,r)):o()}),P=b(function(e,n,r,t){return n&&z.o(n,r)?s(n,e,r):t()}),V=b(function(e,n,r,t,o){return n&&z.o(n,r)?f(n,e,r,t):o()}),q=b(function(e,n,r,t,o){var i=n&&z.o(n,r)&&d(n,r,t);return i?m(i):o()}),A=b(function(e,n,r,t,o){return n&&z.o(n,r)?p(n,e,r,t):o()}),C=function(e){var r=!1,t=!1,o=!1,i=!1,u=[e.shareScope,e.shareKey];return(e.requiredVersion?(e.strictVersion&&(r=!0),e.singleton&&(t=!0),u.push(n(e.requiredVersion)),o=!0):e.singleton&&(t=!0),e.fallback&&(i=!0,u.push(e.fallback)),r&&t&&o&&i)?function(){return A.apply(null,u)}:r&&o&&i?function(){return q.apply(null,u)}:t&&o&&i?function(){return V.apply(null,u)}:r&&t&&o?function(){return T.apply(null,u)}:t&&i?function(){return P.apply(null,u)}:o&&i?function(){return M.apply(null,u)}:r&&o?function(){return x.apply(null,u)}:t&&o?function(){return E.apply(null,u)}:t?function(){return w.apply(null,u)}:o?function(){return j.apply(null,u)}:i?function(){return k.apply(null,u)}:function(){return S.apply(null,u)}},O={},z.f.consumes=function(e,n){var r=z.consumesLoadingData.moduleIdToConsumeDataMapping,t=z.consumesLoadingData.chunkMapping;z.o(t,e)&&t[e].forEach(function(e){if(z.o(O,e))return n.push(O[e]);var t=function(n){O[e]=0,z.m[e]=function(r){delete z.c[e],r.exports=n()}},o=function(n){delete O[e],z.m[e]=function(r){throw delete z.c[e],n}};try{var i=C(r[e])();i.then?n.push(O[e]=i.then(t).catch(o)):t(i)}catch(e){o(e)}})},D={871:0},z.f.j=function(e,n){var r=z.o(D,e)?D[e]:void 0;if(0!==r)if(r)n.push(r[2]);else{var t=new Promise((n,t)=>r=D[e]=[n,t]);n.push(r[2]=t);var o=z.p+z.u(e),i=Error();z.l(o,function(n){if(z.o(D,e)&&(0!==(r=D[e])&&(D[e]=void 0),r)){var t=n&&("load"===n.type?"missing":n.type),o=n&&n.target&&n.target.src;i.message="Loading chunk "+e+" failed.\n("+t+": "+o+")",i.name="ChunkLoadError",i.type=t,i.request=o,r[1](i)}},"chunk-"+e,e)}},_=(e,n)=>{var r,t,[o,i,u]=n,a=0;if(o.some(e=>0!==D[e])){for(r in i)z.o(i,r)&&(z.m[r]=i[r]);u&&u(z)}for(e&&e(n);a<o.length;a++)t=o[a],z.o(D,t)&&D[t]&&D[t][0](),D[t]=0},(L=self.rspackChunkcodebind_jupyterlab=self.rspackChunkcodebind_jupyterlab||[]).forEach(_.bind(null,0)),L.push=_.bind(null,L.push.bind(L));var F=z(457);(_JUPYTERLAB=void 0===_JUPYTERLAB?{}:_JUPYTERLAB)["codebind-jupyterlab"]=F})();
|
|
1
|
+
var _JUPYTERLAB;(()=>{"use strict";var e,n,r,t,o,i,u,a,c,l,s,f,p,d,h,g,v,y,m,b,S,k,j,w,E,x,T,M,P,V,q,A,C,O,D,_,L,N={457(e,n,r){var t={"./index":()=>r.e(590).then(()=>()=>r(509)),"./extension":()=>r.e(590).then(()=>()=>r(509))},o=function(e,n){return r.R=n,n=r.o(t,e)?t[e]():Promise.resolve().then(()=>{throw Error('Module "'+e+'" does not exist in container.')}),r.R=void 0,n},i=function(e,n){if(r.S){var t="default",o=r.S[t];if(o&&o!==e)throw Error("Container initialization failed as it has already been initialized with a different share scope");return r.S[t]=e,r.I(t,n)}};r.d(n,{get:()=>o,init:()=>i})}},$={};function z(e){var n=$[e];if(void 0!==n)return n.exports;var r=$[e]={exports:{}};return N[e](r,r.exports,z),r.exports}z.m=N,z.c=$,z.n=e=>{var n=e&&e.__esModule?()=>e.default:()=>e;return z.d(n,{a:n}),n},z.d=(e,n,r)=>{var t=(n,r)=>{for(var t in n)z.o(n,t)&&!z.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,[r]:n[t]})};t(n,"get"),t(r,"value")},z.f={},z.e=e=>Promise.all(Object.keys(z.f).reduce((n,r)=>(z.f[r](e,n),n),[])),z.u=e=>""+e+".0b7494e278aa27b9.js?v=0b7494e278aa27b9",z.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),z.o=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),I={},z.l=function(e,n,r,t){if(I[e])return void I[e].push(n);if(void 0!==r)for(var o,i,u=document.getElementsByTagName("script"),a=0;a<u.length;a++){var c=u[a];if(c.getAttribute("src")==e||c.getAttribute("data-rspack")=="codebind-jupyterlab:"+r){o=c;break}}o||(i=!0,(o=document.createElement("script")).timeout=120,z.nc&&o.setAttribute("nonce",z.nc),o.setAttribute("data-rspack","codebind-jupyterlab:"+r),o.src=e),I[e]=[n];var l=function(n,r){o.onerror=o.onload=null,clearTimeout(s);var t=I[e];if(delete I[e],o.parentNode&&o.parentNode.removeChild(o),t&&t.forEach(function(e){return e(r)}),n)return n(r)},s=setTimeout(l.bind(null,void 0,{type:"timeout",target:o}),12e4);o.onerror=l.bind(null,o.onerror),o.onload=l.bind(null,o.onload),i&&document.head.appendChild(o)},z.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},z.S={},z.initializeSharingData={scopeToSharingDataMapping:{default:[{name:"codebind-jupyterlab",version:"0.6.11",factory:()=>z.e(590).then(()=>()=>z(509)),eager:0,treeShakingMode:null}]},uniqueName:"codebind-jupyterlab"},R={},U={},z.I=function(e,n){n||(n=[]);var r=U[e];if(r||(r=U[e]={}),!(n.indexOf(r)>=0)){if(n.push(r),R[e])return R[e];z.o(z.S,e)||(z.S[e]={});var t=z.S[e],o=function(e){"u">typeof console&&console.warn&&console.warn(e)},i=z.initializeSharingData.uniqueName,u=function(e,n,r,o){var u=t[e]=t[e]||{},a=u[n];(!a||!a.loaded&&(!o!=!a.eager?o:i>a.from))&&(u[n]={get:r,from:i,eager:!!o})},a=function(r){var t=function(e){o("Initialization of sharing external failed: "+e)};try{var i=z(r);if(!i)return;var u=function(r){return r&&r.init&&r.init(z.S[e],n)};if(i.then)return c.push(i.then(u,t));var a=u(i);if(a&&a.then)return c.push(a.catch(t))}catch(e){t(e)}},c=[],l=z.initializeSharingData.scopeToSharingDataMapping;return(l[e]&&l[e].forEach(function(e){"object"==typeof e?u(e.name,e.version,e.factory,e.eager):a(e)}),c.length)?R[e]=Promise.all(c).then(function(){return R[e]=1}):R[e]=1}},z.g.importScripts&&(B=z.g.location+"");var I,R,U,B,K=z.g.document;if(!B&&K&&(K.currentScript&&"SCRIPT"===K.currentScript.tagName.toUpperCase()&&(B=K.currentScript.src),!B)){var J=K.getElementsByTagName("script");if(J.length)for(var Y=J.length-1;Y>-1&&(!B||!/^http(s?):/.test(B));)B=J[Y--].src}if(!B)throw Error("Automatic publicPath is not supported in this browser");z.p=B=B.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),z.consumesLoadingData={chunkMapping:{590:["511","343","99","171","241"]},moduleIdToConsumeDataMapping:{171:{shareScope:"default",shareKey:"@jupyterlab/notebook",import:null,requiredVersion:"^4.6.3",strictVersion:!1,singleton:!0,eager:!1,fallback:void 0,treeShakingMode:null},241:{shareScope:"default",shareKey:"@jupyterlab/services",import:null,requiredVersion:"^7.6.3",strictVersion:!1,singleton:!0,eager:!1,fallback:void 0,treeShakingMode:null},343:{shareScope:"default",shareKey:"@jupyterlab/cells",import:null,requiredVersion:"^4.6.3",strictVersion:!1,singleton:!1,eager:!1,fallback:void 0,treeShakingMode:null},511:{shareScope:"default",shareKey:"@jupyterlab/apputils",import:null,requiredVersion:"^4.7.3",strictVersion:!1,singleton:!0,eager:!1,fallback:void 0,treeShakingMode:null},99:{shareScope:"default",shareKey:"@jupyterlab/nbformat",import:null,requiredVersion:"^4.6.3",strictVersion:!1,singleton:!1,eager:!1,fallback:void 0,treeShakingMode:null}},initialConsumes:[]},e=function(e){return e.split(".").map(function(e){return+e==e?+e:e})},n=function(n){var r=function(n){var r=/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(n),t=r[1]?[0].concat(e(r[1])):[0];r[2]&&(t.length++,t.push.apply(t,e(r[2])));let o=t[t.length-1];for(;t.length&&(void 0===o||/^[*xX]$/.test(o));)t.pop(),o=t[t.length-1];return t},t=function(e){return 1===e.length?[0]:2===e.length?[1].concat(e.slice(1)):3===e.length?[2].concat(e.slice(1)):[e.length].concat(e.slice(1))},o=function(e){return[-e[0]-1].concat(e.slice(1))},i=function(e){let n=/^(\^|~|<=|<|>=|>|=|v|!)/.exec(e),i=n?n[0]:"",u=r(i.length?e.slice(i.length).trim():e.trim());switch(i){case"^":if(u.length>1&&0===u[1]){if(u.length>2&&0===u[2])return[3].concat(u.slice(1));return[2].concat(u.slice(1))}return[1].concat(u.slice(1));case"~":return[2].concat(u.slice(1));case">=":return u;case"=":case"v":case"":return t(u);case"<":return o(u);case">":return[,t(u),0,u,2];case"<=":return[,t(u),o(u),1];case"!":return[,t(u),0];default:throw Error("Unexpected start value")}},u=function(e,n){if(1===e.length)return e[0];let r=[];for(let n of e.slice().reverse())0 in n?r.push(n):r.push.apply(r,n.slice(1));return[,].concat(r,e.slice(1).map(()=>n))};return u(n.split(/\s*\|\|\s*/).map(function(e){let n=e.split(/\s+-\s+/);if(1===n.length){e=e.trim();let n=[],r=/[-0-9A-Za-z]\s+/g;for(var a,c=0;a=r.exec(e);){let r=a.index+1;n.push(i(e.slice(c,r).trim())),c=r}return n.push(i(e.slice(c).trim())),u(n,2)}let l=r(n[0]),s=r(n[1]);return[,t(s),o(s),1,l,2]}),1)},r=function(n){var r=/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(n),t=r[1]?e(r[1]):[];return r[2]&&(t.length++,t.push.apply(t,e(r[2]))),r[3]&&(t.push([]),t.push.apply(t,e(r[3]))),t},t=function(e,n){e=r(e),n=r(n);for(var t=0;;){if(t>=e.length)return t<n.length&&"u"!=(typeof n[t])[0];var o=e[t],i=(typeof o)[0];if(t>=n.length)return"u"==i;var u=n[t],a=(typeof u)[0];if(i==a){if("o"!=i&&"u"!=i&&o!=u)return o<u;t++}else{if("o"==i&&"n"==a)return!0;return"s"==a||"u"==i}}},o=function(e){var n=e[0],r="";if(1===e.length)return"*";if(n+.5){r+=0==n?">=":-1==n?"<":1==n?"^":2==n?"~":n>0?"=":"!=";for(var t=1,i=1;i<e.length;i++){var u=e[i],a=(typeof u)[0];t--,r+="u"==a?"-":(t>0?".":"")+(t=2,u)}return r}for(var c=[],i=1;i<e.length;i++){var u=e[i];c.push(0===u?"not("+l()+")":1===u?"("+l()+" || "+l()+")":2===u?c.pop()+" "+c.pop():o(u))}return l();function l(){return c.pop().replace(/^\((.+)\)$/,"$1")}},i=function(e,n){if(0 in e){n=r(n);var t=e[0],o=t<0;o&&(t=-t-1);for(var u=0,a=1,c=!0;;a++,u++){var l,s,f=a<e.length?(typeof e[a])[0]:"";if(u>=n.length||"o"==(s=(typeof(l=n[u]))[0])){if(!c)return!0;if("u"==f)return a>t&&!o;return""==f!=o}if("u"==s){if(!c||"u"!=f)return!1}else if(c)if(f==s)if(a<=t){if(l!=e[a])return!1}else{if(o?l>e[a]:l<e[a])return!1;l!=e[a]&&(c=!1)}else if("s"!=f&&"n"!=f){if(o||a<=t)return!1;c=!1,a--}else{if(a<=t||s<f!=o)return!1;c=!1}else"s"!=f&&"n"!=f&&(c=!1,a--)}}for(var p=[],d=p.pop.bind(p),u=1;u<e.length;u++){var h=e[u];p.push(1==h?d()|d():2==h?d()&d():h?i(h,n):!d())}return!!d()},u=function(e,n){var r=z.S[e];if(!r||!z.o(r,n))throw Error("Shared module "+n+" doesn't exist in shared scope "+e);return r},a=function(e,n){var r=e[n],n=Object.keys(r).reduce(function(e,n){return!e||t(e,n)?n:e},0);return n&&r[n]},c=function(e,n){var r=e[n];return Object.keys(r).reduce(function(e,n){return!e||!r[e].loaded&&t(e,n)?n:e},0)},l=function(e,n,r,t){return"Unsatisfied version "+r+" from "+(r&&e[n][r].from)+" of shared singleton module "+n+" (required "+o(t)+")"},s=function(e,n,r,t){var o=c(e,r);return m(e[r][o])},f=function(e,n,r,t){var o=c(e,r);return i(t,o)||v(l(e,r,o,t)),m(e[r][o])},p=function(e,n,r,t){var o=c(e,r);if(!i(t,o))throw Error(l(e,r,o,t));return m(e[r][o])},d=function(e,n,r){var o=e[n],n=Object.keys(o).reduce(function(e,n){return i(r,n)&&(!e||t(e,n))?n:e},0);return n&&o[n]},h=function(e,n,r,t){var i=e[r];return"No satisfying version ("+o(t)+") of shared module "+r+" found in shared scope "+n+".\nAvailable versions: "+Object.keys(i).map(function(e){return e+" from "+i[e].from}).join(", ")},g=function(e,n,r,t){var o=d(e,r,t);if(o)return m(o);throw Error(h(e,n,r,t))},v=function(e){"u">typeof console&&console.warn&&console.warn(e)},y=function(e,n,r,t){v(h(e,n,r,t))},m=function(e){return e.loaded=1,e.get()},S=(b=function(e){return function(n,r,t,o){var i=z.I(n);return i&&i.then?i.then(e.bind(e,n,z.S[n],r,t,o)):e(n,z.S[n],r,t,o)}})(function(e,n,r){return u(e,r),m(a(n,r))}),k=b(function(e,n,r,t){return n&&z.o(n,r)?m(a(n,r)):t()}),j=b(function(e,n,r,t){return u(e,r),m(d(n,r,t)||y(n,e,r,t)||a(n,r))}),w=b(function(e,n,r){return u(e,r),s(n,e,r)}),E=b(function(e,n,r,t){return u(e,r),f(n,e,r,t)}),x=b(function(e,n,r,t){return u(e,r),g(n,e,r,t)}),T=b(function(e,n,r,t){return u(e,r),p(n,e,r,t)}),M=b(function(e,n,r,t,o){return n&&z.o(n,r)?m(d(n,r,t)||y(n,e,r,t)||a(n,r)):o()}),P=b(function(e,n,r,t){return n&&z.o(n,r)?s(n,e,r):t()}),V=b(function(e,n,r,t,o){return n&&z.o(n,r)?f(n,e,r,t):o()}),q=b(function(e,n,r,t,o){var i=n&&z.o(n,r)&&d(n,r,t);return i?m(i):o()}),A=b(function(e,n,r,t,o){return n&&z.o(n,r)?p(n,e,r,t):o()}),C=function(e){var r=!1,t=!1,o=!1,i=!1,u=[e.shareScope,e.shareKey];return(e.requiredVersion?(e.strictVersion&&(r=!0),e.singleton&&(t=!0),u.push(n(e.requiredVersion)),o=!0):e.singleton&&(t=!0),e.fallback&&(i=!0,u.push(e.fallback)),r&&t&&o&&i)?function(){return A.apply(null,u)}:r&&o&&i?function(){return q.apply(null,u)}:t&&o&&i?function(){return V.apply(null,u)}:r&&t&&o?function(){return T.apply(null,u)}:t&&i?function(){return P.apply(null,u)}:o&&i?function(){return M.apply(null,u)}:r&&o?function(){return x.apply(null,u)}:t&&o?function(){return E.apply(null,u)}:t?function(){return w.apply(null,u)}:o?function(){return j.apply(null,u)}:i?function(){return k.apply(null,u)}:function(){return S.apply(null,u)}},O={},z.f.consumes=function(e,n){var r=z.consumesLoadingData.moduleIdToConsumeDataMapping,t=z.consumesLoadingData.chunkMapping;z.o(t,e)&&t[e].forEach(function(e){if(z.o(O,e))return n.push(O[e]);var t=function(n){O[e]=0,z.m[e]=function(r){delete z.c[e],r.exports=n()}},o=function(n){delete O[e],z.m[e]=function(r){throw delete z.c[e],n}};try{var i=C(r[e])();i.then?n.push(O[e]=i.then(t).catch(o)):t(i)}catch(e){o(e)}})},D={871:0},z.f.j=function(e,n){var r=z.o(D,e)?D[e]:void 0;if(0!==r)if(r)n.push(r[2]);else{var t=new Promise((n,t)=>r=D[e]=[n,t]);n.push(r[2]=t);var o=z.p+z.u(e),i=Error();z.l(o,function(n){if(z.o(D,e)&&(0!==(r=D[e])&&(D[e]=void 0),r)){var t=n&&("load"===n.type?"missing":n.type),o=n&&n.target&&n.target.src;i.message="Loading chunk "+e+" failed.\n("+t+": "+o+")",i.name="ChunkLoadError",i.type=t,i.request=o,r[1](i)}},"chunk-"+e,e)}},_=(e,n)=>{var r,t,[o,i,u]=n,a=0;if(o.some(e=>0!==D[e])){for(r in i)z.o(i,r)&&(z.m[r]=i[r]);u&&u(z)}for(e&&e(n);a<o.length;a++)t=o[a],z.o(D,t)&&D[t]&&D[t][0](),D[t]=0},(L=self.rspackChunkcodebind_jupyterlab=self.rspackChunkcodebind_jupyterlab||[]).forEach(_.bind(null,0)),L.push=_.bind(null,L.push.bind(L));var F=z(457);(_JUPYTERLAB=void 0===_JUPYTERLAB?{}:_JUPYTERLAB)["codebind-jupyterlab"]=F})();
|
|
@@ -23,6 +23,11 @@ const RUN_QUESTION = 'codebind:run-question';
|
|
|
23
23
|
const QUESTION_CLASS = 'jp-CodebindQuestionCell';
|
|
24
24
|
const CANCEL_GRACE_MILLISECONDS = 3000;
|
|
25
25
|
|
|
26
|
+
const LOAD_EXTENSION = '%load_ext codebind';
|
|
27
|
+
const extensionLoaded = new WeakSet<Kernel.IKernelConnection>();
|
|
28
|
+
const extensionLoading = new WeakMap<Kernel.IKernelConnection, Promise<void>>();
|
|
29
|
+
const extensionErrors = new WeakMap<Kernel.IKernelConnection, string>();
|
|
30
|
+
|
|
26
31
|
interface CodeCellStartedMessage {
|
|
27
32
|
type: 'code_cell_started';
|
|
28
33
|
cell_id: string;
|
|
@@ -514,7 +519,55 @@ function hideInstructionsCells(panel: NotebookPanel): void {
|
|
|
514
519
|
}
|
|
515
520
|
}
|
|
516
521
|
|
|
517
|
-
function
|
|
522
|
+
function isPythonKernel(
|
|
523
|
+
app: JupyterFrontEnd,
|
|
524
|
+
kernel: Kernel.IKernelConnection
|
|
525
|
+
): boolean {
|
|
526
|
+
const spec = app.serviceManager.kernelspecs.specs?.kernelspecs?.[kernel.name];
|
|
527
|
+
if (!spec) {
|
|
528
|
+
return true;
|
|
529
|
+
}
|
|
530
|
+
return (spec.language ?? '').toLowerCase() === 'python';
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function loadExtension(
|
|
534
|
+
app: JupyterFrontEnd,
|
|
535
|
+
kernel: Kernel.IKernelConnection
|
|
536
|
+
): Promise<void> {
|
|
537
|
+
const loading = extensionLoading.get(kernel);
|
|
538
|
+
if (loading) {
|
|
539
|
+
return loading;
|
|
540
|
+
}
|
|
541
|
+
if (extensionLoaded.has(kernel) || !isPythonKernel(app, kernel)) {
|
|
542
|
+
extensionLoaded.add(kernel);
|
|
543
|
+
return Promise.resolve();
|
|
544
|
+
}
|
|
545
|
+
const future = kernel.requestExecute({
|
|
546
|
+
code: LOAD_EXTENSION,
|
|
547
|
+
silent: true,
|
|
548
|
+
store_history: false,
|
|
549
|
+
stop_on_error: false
|
|
550
|
+
});
|
|
551
|
+
const load = future.done.then(
|
|
552
|
+
reply => {
|
|
553
|
+
const content = reply.content;
|
|
554
|
+
if (content.status === 'error') {
|
|
555
|
+
const failure = content as { ename?: string; evalue?: string };
|
|
556
|
+
extensionErrors.set(
|
|
557
|
+
kernel,
|
|
558
|
+
`${failure.ename ?? 'Error'}: ${failure.evalue ?? 'unknown'}`
|
|
559
|
+
);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
extensionLoaded.add(kernel);
|
|
563
|
+
},
|
|
564
|
+
() => undefined
|
|
565
|
+
);
|
|
566
|
+
extensionLoading.set(kernel, load);
|
|
567
|
+
return load;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function registerKernel(panel: NotebookPanel, app: JupyterFrontEnd): void {
|
|
518
571
|
const kernel = panel.sessionContext.session?.kernel;
|
|
519
572
|
if (!kernel) {
|
|
520
573
|
return;
|
|
@@ -617,6 +670,16 @@ function registerKernel(panel: NotebookPanel): void {
|
|
|
617
670
|
if (panelState.comm || kernel.status !== 'idle' || !panel.content.model) {
|
|
618
671
|
return;
|
|
619
672
|
}
|
|
673
|
+
if (!extensionLoaded.has(kernel)) {
|
|
674
|
+
panelState.connectOnIdle = true;
|
|
675
|
+
void loadExtension(app, kernel).then(() => {
|
|
676
|
+
if (kernel.status === 'idle' && !panelState.comm) {
|
|
677
|
+
panelState.connectOnIdle = false;
|
|
678
|
+
connectKernel();
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
620
683
|
const comm = kernel.createComm(TARGET_NAME);
|
|
621
684
|
comm.commsOverSubshells = CommsOverSubshells.Disabled;
|
|
622
685
|
panelState.comm = comm;
|
|
@@ -856,6 +919,7 @@ function registerKernel(panel: NotebookPanel): void {
|
|
|
856
919
|
};
|
|
857
920
|
kernel.statusChanged.connect(onStatus);
|
|
858
921
|
kernel.iopubMessage.connect(onInput);
|
|
922
|
+
void loadExtension(app, kernel);
|
|
859
923
|
panelState.disconnectKernel = () => {
|
|
860
924
|
kernel.statusChanged.disconnect(onStatus);
|
|
861
925
|
kernel.iopubMessage.disconnect(onInput);
|
|
@@ -964,7 +1028,10 @@ function setQuestionMode(panel: NotebookPanel, enabled: boolean): void {
|
|
|
964
1028
|
}
|
|
965
1029
|
}
|
|
966
1030
|
|
|
967
|
-
async function runQuestion(
|
|
1031
|
+
async function runQuestion(
|
|
1032
|
+
panel: NotebookPanel,
|
|
1033
|
+
app: JupyterFrontEnd
|
|
1034
|
+
): Promise<void> {
|
|
968
1035
|
const notebook = panel.content;
|
|
969
1036
|
const cell = notebook.activeCell;
|
|
970
1037
|
if (!cell) {
|
|
@@ -975,7 +1042,7 @@ async function runQuestion(panel: NotebookPanel): Promise<void> {
|
|
|
975
1042
|
return;
|
|
976
1043
|
}
|
|
977
1044
|
await panel.sessionContext.ready;
|
|
978
|
-
registerKernel(panel);
|
|
1045
|
+
registerKernel(panel, app);
|
|
979
1046
|
const state = panelStates.get(panel);
|
|
980
1047
|
const kernel = state?.registeredKernel;
|
|
981
1048
|
if (!state || !kernel) {
|
|
@@ -1009,7 +1076,17 @@ async function runQuestion(panel: NotebookPanel): Promise<void> {
|
|
|
1009
1076
|
}
|
|
1010
1077
|
state.connectKernel?.();
|
|
1011
1078
|
if (!state.ready) {
|
|
1012
|
-
|
|
1079
|
+
await loadExtension(app, kernel);
|
|
1080
|
+
if (kernel.status === 'idle') {
|
|
1081
|
+
state.connectOnIdle = false;
|
|
1082
|
+
state.connectKernel?.();
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
if (!state.ready) {
|
|
1086
|
+
throw new Error(
|
|
1087
|
+
extensionErrors.get(kernel) ??
|
|
1088
|
+
'Run %load_ext codebind in this kernel.'
|
|
1089
|
+
);
|
|
1013
1090
|
}
|
|
1014
1091
|
await state.ready;
|
|
1015
1092
|
} catch (error) {
|
|
@@ -1225,8 +1302,8 @@ function connectPanel(panel: NotebookPanel, app: JupyterFrontEnd): void {
|
|
|
1225
1302
|
});
|
|
1226
1303
|
refreshQuestionMode(panel);
|
|
1227
1304
|
});
|
|
1228
|
-
void panel.sessionContext.ready.then(() => registerKernel(panel));
|
|
1229
|
-
panel.sessionContext.kernelChanged.connect(() => registerKernel(panel));
|
|
1305
|
+
void panel.sessionContext.ready.then(() => registerKernel(panel, app));
|
|
1306
|
+
panel.sessionContext.kernelChanged.connect(() => registerKernel(panel, app));
|
|
1230
1307
|
}
|
|
1231
1308
|
|
|
1232
1309
|
const plugin: JupyterFrontEndPlugin<void> = {
|
|
@@ -1267,7 +1344,7 @@ const plugin: JupyterFrontEndPlugin<void> = {
|
|
|
1267
1344
|
execute: async () => {
|
|
1268
1345
|
const panel = tracker.currentWidget;
|
|
1269
1346
|
if (panel) {
|
|
1270
|
-
await runQuestion(panel);
|
|
1347
|
+
await runQuestion(panel, app);
|
|
1271
1348
|
}
|
|
1272
1349
|
}
|
|
1273
1350
|
});
|
|
@@ -17,12 +17,16 @@ from IPython.utils.capture import capture_output
|
|
|
17
17
|
from .display import display_cell
|
|
18
18
|
from .images import PreparedImage, prepare_mime_image
|
|
19
19
|
from .model_text import bounded_text
|
|
20
|
+
from .interrupts import AgentTurnInterrupted
|
|
20
21
|
from .jupyter import JupyterLabBridge
|
|
21
22
|
from .terminal import preview_tool_output, record_tool_output, show_input
|
|
22
23
|
|
|
23
24
|
|
|
24
25
|
_MAXIMUM_IMAGES_PER_REPORT = 32
|
|
25
26
|
|
|
27
|
+
# Re-exported so the model loop can recognise a user interrupt raised here.
|
|
28
|
+
__all__ = ["AgentTurnInterrupted", "ExecutionReport", "IPythonExecutor"]
|
|
29
|
+
|
|
26
30
|
|
|
27
31
|
@dataclass(frozen=True, slots=True)
|
|
28
32
|
class ExecutionReport:
|
|
@@ -223,6 +227,9 @@ class IPythonExecutor:
|
|
|
223
227
|
show_input(self.shell, cell)
|
|
224
228
|
with preview_tool_output() as preview, record_tool_output(self.shell):
|
|
225
229
|
result = self.shell.run_cell(cell, store_history=True)
|
|
230
|
+
# A user interrupt is not a failing tool result: it stops the turn.
|
|
231
|
+
if isinstance(result.error_before_exec or result.error_in_exec, KeyboardInterrupt):
|
|
232
|
+
raise AgentTurnInterrupted
|
|
226
233
|
report = self._native_report(result)
|
|
227
234
|
preview.show_notice(report.error)
|
|
228
235
|
return report
|
|
@@ -308,7 +315,7 @@ class IPythonExecutor:
|
|
|
308
315
|
if asyncio.current_task() and asyncio.current_task().cancelling():
|
|
309
316
|
raise asyncio.CancelledError
|
|
310
317
|
if isinstance(result.error_before_exec or result.error_in_exec, KeyboardInterrupt):
|
|
311
|
-
raise
|
|
318
|
+
raise AgentTurnInterrupted
|
|
312
319
|
if bridged:
|
|
313
320
|
assert bridge is not None and cell_id is not None
|
|
314
321
|
bridge.finish_code_cell(
|
|
@@ -19,7 +19,13 @@ from .display import display_assistant
|
|
|
19
19
|
from .conversation import MemoryConversationStore, NotebookConversationStore
|
|
20
20
|
from .jupyter import JupyterLabBridge, TARGET_NAME
|
|
21
21
|
from .session import Session
|
|
22
|
-
from .terminal import
|
|
22
|
+
from .terminal import (
|
|
23
|
+
TerminalCellHistory,
|
|
24
|
+
install_markdown_renderer,
|
|
25
|
+
install_question_mode,
|
|
26
|
+
remember_question,
|
|
27
|
+
set_question_running,
|
|
28
|
+
)
|
|
23
29
|
|
|
24
30
|
|
|
25
31
|
_STATE_ATTRIBUTE = "_codebind_extension_state"
|
|
@@ -256,11 +262,18 @@ def load_ipython_extension(ipython: InteractiveShell) -> None:
|
|
|
256
262
|
state["session"] = session
|
|
257
263
|
selected = get_model()
|
|
258
264
|
terminal_history = state.get("terminal_history")
|
|
265
|
+
is_question_cell = cell is not None
|
|
266
|
+
if is_question_cell:
|
|
267
|
+
remember_question(ipython, cell)
|
|
259
268
|
history = (
|
|
260
269
|
terminal_history.snapshot()
|
|
261
270
|
if isinstance(terminal_history, TerminalCellHistory)
|
|
262
271
|
else None
|
|
263
272
|
)
|
|
273
|
+
if isinstance(ipython, TerminalInteractiveShell):
|
|
274
|
+
# Keep the running mark until the next prompt: IPython prints an
|
|
275
|
+
# interrupted question's traceback after this magic returns.
|
|
276
|
+
set_question_running(ipython, True)
|
|
264
277
|
try:
|
|
265
278
|
session.send(cell if cell is not None else line, selected, notebook=history)
|
|
266
279
|
except BaseException:
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Signals shared by the frontends that run the model loop."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AgentTurnInterrupted(BaseException):
|
|
5
|
+
"""The user pressed Ctrl+C during a question, so the whole turn must stop.
|
|
6
|
+
|
|
7
|
+
This derives from :class:`BaseException` on purpose: an interrupted question
|
|
8
|
+
is not a failing tool result, and the model loop must not turn it into one.
|
|
9
|
+
"""
|
|
@@ -7,6 +7,8 @@ from collections.abc import Awaitable, Callable
|
|
|
7
7
|
from typing import Any
|
|
8
8
|
from uuid import uuid4
|
|
9
9
|
|
|
10
|
+
from .interrupts import AgentTurnInterrupted
|
|
11
|
+
|
|
10
12
|
TARGET_NAME = "codebind"
|
|
11
13
|
_Notebook = list[dict[str, Any]]
|
|
12
14
|
_QuestionHandler = Callable[[str, _Notebook], Awaitable[None]]
|
|
@@ -270,7 +272,7 @@ class JupyterLabBridge:
|
|
|
270
272
|
if self._question_handler is None:
|
|
271
273
|
raise RuntimeError("Codebind is not ready to receive questions.")
|
|
272
274
|
await self._question_handler(question, notebook)
|
|
273
|
-
except (asyncio.CancelledError, KeyboardInterrupt):
|
|
275
|
+
except (asyncio.CancelledError, KeyboardInterrupt, AgentTurnInterrupted):
|
|
274
276
|
cancelled = True
|
|
275
277
|
except Exception as exception:
|
|
276
278
|
error = {"type": type(exception).__name__, "message": str(exception)}
|
|
@@ -31,6 +31,7 @@ from .async_runtime import run_sync
|
|
|
31
31
|
from .display import display_assistant
|
|
32
32
|
from .conversation import Conversation, ConversationStore, MemoryConversationStore
|
|
33
33
|
from .execution import ExecutionReport, IPythonExecutor
|
|
34
|
+
from .interrupts import AgentTurnInterrupted
|
|
34
35
|
from .jupyter import JupyterLabBridge
|
|
35
36
|
|
|
36
37
|
|
|
@@ -498,7 +499,7 @@ class Session:
|
|
|
498
499
|
self._tool_message(report, identifier),
|
|
499
500
|
turn_id,
|
|
500
501
|
)
|
|
501
|
-
except KeyboardInterrupt:
|
|
502
|
+
except (KeyboardInterrupt, AgentTurnInterrupted):
|
|
502
503
|
self._cancel_assistant_stream(assistant_cell_id)
|
|
503
504
|
self._seal_interrupted_calls_sync(turn_id)
|
|
504
505
|
self._append_event_sync("turn_finished", turn_id=turn_id, status="cancelled")
|
|
@@ -546,7 +547,7 @@ class Session:
|
|
|
546
547
|
self._tool_message(report, identifier),
|
|
547
548
|
turn_id,
|
|
548
549
|
)
|
|
549
|
-
except (asyncio.CancelledError, KeyboardInterrupt):
|
|
550
|
+
except (asyncio.CancelledError, KeyboardInterrupt, AgentTurnInterrupted):
|
|
550
551
|
self._cancel_assistant_stream(assistant_cell_id)
|
|
551
552
|
await self._seal_interrupted_calls(turn_id)
|
|
552
553
|
await self._append_event("turn_finished", turn_id=turn_id, status="cancelled")
|
|
@@ -13,6 +13,7 @@ from unittest.mock import patch
|
|
|
13
13
|
|
|
14
14
|
from IPython.terminal.interactiveshell import IPythonPTLexer, TerminalInteractiveShell
|
|
15
15
|
from prompt_toolkit.enums import DEFAULT_BUFFER
|
|
16
|
+
from prompt_toolkit.key_binding.key_processor import KeyPress
|
|
16
17
|
from prompt_toolkit.filters import Condition, has_focus
|
|
17
18
|
from prompt_toolkit.document import Document
|
|
18
19
|
from prompt_toolkit.formatted_text import ANSI, FormattedText, PygmentsTokens, to_formatted_text
|
|
@@ -21,11 +22,54 @@ from prompt_toolkit.styles import DynamicStyle, Style, merge_styles
|
|
|
21
22
|
from rich.console import Console
|
|
22
23
|
from rich.markdown import Markdown
|
|
23
24
|
|
|
25
|
+
from .interrupts import AgentTurnInterrupted
|
|
26
|
+
|
|
24
27
|
|
|
25
28
|
_MISSING = object()
|
|
26
29
|
_IMAGE_FORMATS = ("image/png", "image/jpeg", "image/svg+xml")
|
|
27
30
|
_MAXIMUM_VISIBLE_OUTPUT_LINES = 3
|
|
28
31
|
_MAXIMUM_VISIBLE_OUTPUT_CHARACTERS_PER_LINE = 80
|
|
32
|
+
_MODE_ATTRIBUTE = "_codebind_terminal_mode"
|
|
33
|
+
# The real stdout, while tool output is being previewed.
|
|
34
|
+
_REAL_STDOUT: dict[str, object] = {}
|
|
35
|
+
_SHIFT_ENTER_SEQUENCE = "\x1b[27;2;13~"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def terminal_mode(shell: TerminalInteractiveShell) -> dict[str, bool]:
|
|
39
|
+
"""Share one prompt's mode flags with the rest of the terminal session."""
|
|
40
|
+
mode = getattr(shell, _MODE_ATTRIBUTE, None)
|
|
41
|
+
if not isinstance(mode, dict):
|
|
42
|
+
mode = {
|
|
43
|
+
"question": False,
|
|
44
|
+
"running": False,
|
|
45
|
+
"submitted": False,
|
|
46
|
+
"submitted_count": None,
|
|
47
|
+
"active_prompt": False,
|
|
48
|
+
"interrupt_reported": False,
|
|
49
|
+
"question_text": None,
|
|
50
|
+
}
|
|
51
|
+
setattr(shell, _MODE_ATTRIBUTE, mode)
|
|
52
|
+
return mode
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def set_question_running(shell: TerminalInteractiveShell, running: bool) -> None:
|
|
56
|
+
"""Mark that a question is executing its tool cells."""
|
|
57
|
+
terminal_mode(shell)["running"] = running
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def remember_question(shell: TerminalInteractiveShell, question: str) -> None:
|
|
61
|
+
"""Record the exact question text for the cell IPython is about to run."""
|
|
62
|
+
terminal_mode(shell)["question_text"] = question
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def take_question(shell: TerminalInteractiveShell) -> str | None:
|
|
66
|
+
"""Consume the recorded question text, if one is waiting."""
|
|
67
|
+
mode = getattr(shell, _MODE_ATTRIBUTE, None)
|
|
68
|
+
if not isinstance(mode, dict):
|
|
69
|
+
return None
|
|
70
|
+
question = mode.get("question_text")
|
|
71
|
+
mode["question_text"] = None
|
|
72
|
+
return question if isinstance(question, str) else None
|
|
29
73
|
|
|
30
74
|
|
|
31
75
|
def _plain_ansi(value: str) -> str:
|
|
@@ -87,7 +131,8 @@ def _history_cell(
|
|
|
87
131
|
identifier = f"terminal-{number}"
|
|
88
132
|
magic = _magic_input(transformed)
|
|
89
133
|
if magic is not None and magic[0] == "question":
|
|
90
|
-
|
|
134
|
+
recorded = take_question(shell)
|
|
135
|
+
return {"id": identifier, "type": "markdown", "source": recorded or magic[1]}
|
|
91
136
|
if magic is not None and magic[0] in {"output", "context"}:
|
|
92
137
|
return {"id": identifier, "type": "raw", "source": source}
|
|
93
138
|
|
|
@@ -301,20 +346,40 @@ def preview_tool_output(
|
|
|
301
346
|
preview_stderr = _PreviewStream(stderr, preview)
|
|
302
347
|
sys.stdout = preview_stdout
|
|
303
348
|
sys.stderr = preview_stderr
|
|
349
|
+
_REAL_STDOUT["stream"] = stdout
|
|
304
350
|
try:
|
|
305
351
|
yield preview
|
|
306
352
|
finally:
|
|
353
|
+
_REAL_STDOUT.pop("stream", None)
|
|
307
354
|
preview_stdout.flush()
|
|
308
355
|
preview_stderr.flush()
|
|
309
356
|
sys.stdout, sys.stderr = stdout, stderr
|
|
310
357
|
|
|
311
358
|
|
|
359
|
+
def _interrupt_report(shell: TerminalInteractiveShell, value: BaseException) -> str:
|
|
360
|
+
"""Report a user interrupt the way IPython reports an interrupted cell.
|
|
361
|
+
|
|
362
|
+
Only the exception line is printed. The frames below it belong to the model
|
|
363
|
+
client, the provider, or the standard library, so naming a cell number would
|
|
364
|
+
be misleading: the interrupted cell never completed.
|
|
365
|
+
"""
|
|
366
|
+
if isinstance(value, AgentTurnInterrupted):
|
|
367
|
+
value = KeyboardInterrupt()
|
|
368
|
+
return shell.get_exception_only((KeyboardInterrupt, value, None))
|
|
369
|
+
|
|
370
|
+
|
|
312
371
|
def install_question_mode(shell: TerminalInteractiveShell) -> Callable[[], None]:
|
|
313
|
-
"""
|
|
372
|
+
"""Switch the terminal prompt between Python and Markdown questions.
|
|
373
|
+
|
|
374
|
+
Shift+Tab toggles Question mode. While it is on, Enter submits a one-line
|
|
375
|
+
question, Shift+Enter starts a new Markdown line, and Ctrl+C returns to
|
|
376
|
+
Python mode instead of interrupting the shell.
|
|
377
|
+
"""
|
|
314
378
|
prompt_session = shell.pt_app
|
|
315
379
|
if prompt_session is None:
|
|
316
380
|
return lambda: None
|
|
317
381
|
|
|
382
|
+
mode = terminal_mode(shell)
|
|
318
383
|
original_shell_mouse = shell.mouse_support
|
|
319
384
|
original_prompt_mouse = prompt_session.mouse_support
|
|
320
385
|
# Terminal mouse reporting intercepts scrollback, even if the prompt is idle.
|
|
@@ -325,14 +390,16 @@ def install_question_mode(shell: TerminalInteractiveShell) -> Callable[[], None]
|
|
|
325
390
|
had_prompt_override = "prompt_for_code" in vars(shell)
|
|
326
391
|
bindings = prompt_session.key_bindings
|
|
327
392
|
transforms = shell.input_transformer_manager.cleanup_transforms
|
|
328
|
-
question_mode = False
|
|
329
|
-
active_prompt = False
|
|
330
|
-
pending_question = False
|
|
331
393
|
prompt_worker: ThreadPoolExecutor | None = None
|
|
332
394
|
|
|
333
395
|
def prompt_for_code() -> str:
|
|
334
|
-
nonlocal
|
|
335
|
-
active_prompt = True
|
|
396
|
+
nonlocal prompt_worker
|
|
397
|
+
mode["active_prompt"] = True
|
|
398
|
+
mode["question_asked"] = False
|
|
399
|
+
mode["answered_only"] = False
|
|
400
|
+
mode["running"] = False
|
|
401
|
+
mode["submitted"] = False
|
|
402
|
+
mode["interrupt_reported"] = False
|
|
336
403
|
try:
|
|
337
404
|
try:
|
|
338
405
|
asyncio.get_running_loop()
|
|
@@ -359,28 +426,129 @@ def install_question_mode(shell: TerminalInteractiveShell) -> Callable[[], None]
|
|
|
359
426
|
pass
|
|
360
427
|
raise
|
|
361
428
|
finally:
|
|
362
|
-
active_prompt = False
|
|
363
|
-
|
|
429
|
+
mode["active_prompt"] = False
|
|
430
|
+
mode["running"] = False
|
|
431
|
+
if mode["question"] and mode["question_asked"]:
|
|
432
|
+
mode["answered_only"] = not text.strip()
|
|
433
|
+
else:
|
|
434
|
+
mode["answered_only"] = False
|
|
364
435
|
return text
|
|
365
436
|
|
|
366
437
|
def transform_question(lines: list[str]) -> list[str]:
|
|
367
|
-
|
|
368
|
-
if not
|
|
438
|
+
"""Wrap the cell the user just answered, and only that cell."""
|
|
439
|
+
if not mode["question_asked"] or mode["answered_only"]:
|
|
369
440
|
return lines
|
|
370
|
-
|
|
441
|
+
mode["question_asked"] = False
|
|
371
442
|
return ["%%question\n", *lines]
|
|
372
443
|
|
|
373
444
|
def toggle_question(event) -> None:
|
|
374
|
-
|
|
375
|
-
question_mode = not question_mode
|
|
445
|
+
mode["question"] = not mode["question"]
|
|
376
446
|
event.app.invalidate()
|
|
377
447
|
|
|
378
|
-
def
|
|
448
|
+
def enter_question(event) -> None:
|
|
449
|
+
"""Enter submits; the prompt session stays open for the next question."""
|
|
450
|
+
mode["question_asked"] = True
|
|
451
|
+
# Set before the prompt closes: the accepted line is drawn once more
|
|
452
|
+
# while this flag is still set, which is where In [N] becomes In [*].
|
|
453
|
+
# The cell number is latched, because execution_count does not change
|
|
454
|
+
# until the cell runs, so the next prompt would otherwise look marked too.
|
|
455
|
+
mode["submitted"] = True
|
|
456
|
+
mode["submitted_count"] = str(shell.execution_count)
|
|
379
457
|
event.current_buffer.validate_and_handle()
|
|
380
458
|
|
|
381
|
-
|
|
459
|
+
def newline_question(event) -> None:
|
|
460
|
+
"""Shift+Enter or Ctrl+J adds a Markdown line, as in a notebook cell."""
|
|
461
|
+
event.current_buffer.insert_text("\n")
|
|
462
|
+
event.app.invalidate()
|
|
463
|
+
|
|
464
|
+
def read_keys(_source=None):
|
|
465
|
+
"""Read Shift+Enter as a newline in terminals that report it.
|
|
466
|
+
|
|
467
|
+
prompt_toolkit maps that sequence to ControlM, exactly like a plain
|
|
468
|
+
Enter, so the raw ``KeyPress.data`` is the only way to tell them apart.
|
|
469
|
+
Apple Terminal does not report Shift+Enter at all, so Ctrl+J is the
|
|
470
|
+
newline key there; terminals that do report it get the expected behaviour.
|
|
471
|
+
"""
|
|
472
|
+
keys = original_read_keys()
|
|
473
|
+
if not mode["question"]:
|
|
474
|
+
return keys
|
|
475
|
+
rewritten = []
|
|
476
|
+
for key in keys:
|
|
477
|
+
data = getattr(key, "data", None)
|
|
478
|
+
if isinstance(data, str) and data == _SHIFT_ENTER_SEQUENCE:
|
|
479
|
+
rewritten.append(KeyPress("\n"))
|
|
480
|
+
else:
|
|
481
|
+
rewritten.append(key)
|
|
482
|
+
return rewritten
|
|
483
|
+
|
|
484
|
+
def interrupt_question(event) -> None:
|
|
485
|
+
"""Ctrl+C discards the question and returns to Python mode."""
|
|
486
|
+
buffer = event.current_buffer
|
|
487
|
+
if buffer.complete_state:
|
|
488
|
+
buffer.cancel_completion()
|
|
489
|
+
else:
|
|
490
|
+
buffer.reset()
|
|
491
|
+
mode["question"] = False
|
|
492
|
+
mode["submitted"] = False
|
|
493
|
+
event.app.invalidate()
|
|
494
|
+
|
|
495
|
+
question_active = Condition(lambda: mode["question"])
|
|
496
|
+
original_prompt_options = shell._extra_prompt_options
|
|
497
|
+
|
|
498
|
+
def prompt_options():
|
|
499
|
+
"""Let a question's own line show the running marker, In [*].
|
|
500
|
+
|
|
501
|
+
The message stays callable so the marker follows the current mode: it is
|
|
502
|
+
read when the prompt is drawn, and toggle_question redraws it.
|
|
503
|
+
"""
|
|
504
|
+
options = original_prompt_options()
|
|
505
|
+
prompt_tokens = shell.prompts.in_prompt_tokens
|
|
506
|
+
|
|
507
|
+
def message():
|
|
508
|
+
tokens = prompt_tokens()
|
|
509
|
+
counter = str(shell.execution_count)
|
|
510
|
+
if counter != mode["submitted_count"]:
|
|
511
|
+
return PygmentsTokens(tokens)
|
|
512
|
+
marked = [(token, "*" if text == counter else text) for token, text in tokens]
|
|
513
|
+
return PygmentsTokens(marked)
|
|
514
|
+
|
|
515
|
+
options["message"] = message
|
|
516
|
+
return options
|
|
517
|
+
|
|
518
|
+
shell._extra_prompt_options = prompt_options
|
|
519
|
+
original_read_keys = prompt_session.input.read_keys
|
|
520
|
+
original_showtraceback = shell.showtraceback
|
|
521
|
+
|
|
522
|
+
def showtraceback(
|
|
523
|
+
exc_tuple=None,
|
|
524
|
+
filename=None,
|
|
525
|
+
tb_offset=None,
|
|
526
|
+
exception_only=False,
|
|
527
|
+
running_compiled_code=False,
|
|
528
|
+
) -> None:
|
|
529
|
+
if mode["running"] and not exception_only:
|
|
530
|
+
_etype, value, _traceback = sys.exc_info() if exc_tuple is None else exc_tuple
|
|
531
|
+
if isinstance(value, (KeyboardInterrupt, AgentTurnInterrupted)):
|
|
532
|
+
# One interrupt can surface twice: once as the interrupted cell's
|
|
533
|
+
# KeyboardInterrupt and once as the signal that stopped the turn.
|
|
534
|
+
if not mode["interrupt_reported"]:
|
|
535
|
+
mode["interrupt_reported"] = True
|
|
536
|
+
stream = _REAL_STDOUT.get("stream") or sys.stdout
|
|
537
|
+
stream.write("\n" + _interrupt_report(shell, value))
|
|
538
|
+
return
|
|
539
|
+
original_showtraceback(
|
|
540
|
+
exc_tuple,
|
|
541
|
+
filename,
|
|
542
|
+
tb_offset,
|
|
543
|
+
exception_only,
|
|
544
|
+
running_compiled_code,
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
shell.showtraceback = showtraceback
|
|
382
548
|
bindings.add("s-tab", filter=has_focus(DEFAULT_BUFFER))(toggle_question)
|
|
383
|
-
bindings.add("enter", filter=has_focus(DEFAULT_BUFFER) & question_active)(
|
|
549
|
+
bindings.add("enter", filter=has_focus(DEFAULT_BUFFER) & question_active)(enter_question)
|
|
550
|
+
bindings.add("c-j", filter=has_focus(DEFAULT_BUFFER) & question_active)(newline_question)
|
|
551
|
+
bindings.add("c-c", filter=has_focus(DEFAULT_BUFFER) & question_active)(interrupt_question)
|
|
384
552
|
shell.prompt_for_code = prompt_for_code
|
|
385
553
|
question_style = merge_styles(
|
|
386
554
|
[
|
|
@@ -402,14 +570,20 @@ def install_question_mode(shell: TerminalInteractiveShell) -> Callable[[], None]
|
|
|
402
570
|
]
|
|
403
571
|
)
|
|
404
572
|
prompt_session.style = DynamicStyle(
|
|
405
|
-
lambda: question_style if
|
|
573
|
+
lambda: question_style if mode["question"] and mode["active_prompt"] else original_style
|
|
406
574
|
)
|
|
407
575
|
transforms.insert(0, transform_question)
|
|
576
|
+
prompt_session.input.read_keys = read_keys
|
|
408
577
|
|
|
409
578
|
def restore() -> None:
|
|
410
579
|
bindings.remove(toggle_question)
|
|
411
|
-
bindings.remove(
|
|
580
|
+
bindings.remove(enter_question)
|
|
581
|
+
bindings.remove(newline_question)
|
|
582
|
+
bindings.remove(interrupt_question)
|
|
412
583
|
transforms.remove(transform_question)
|
|
584
|
+
shell._extra_prompt_options = original_prompt_options
|
|
585
|
+
shell.showtraceback = original_showtraceback
|
|
586
|
+
prompt_session.input.read_keys = original_read_keys
|
|
413
587
|
if had_prompt_override:
|
|
414
588
|
shell.prompt_for_code = original_prompt_for_code
|
|
415
589
|
else:
|
|
@@ -502,10 +676,15 @@ def record_tool_output(shell: TerminalInteractiveShell) -> Iterator[None]:
|
|
|
502
676
|
|
|
503
677
|
|
|
504
678
|
__all__ = [
|
|
679
|
+
"AgentTurnInterrupted",
|
|
505
680
|
"TerminalCellHistory",
|
|
506
681
|
"install_markdown_renderer",
|
|
507
682
|
"install_question_mode",
|
|
508
683
|
"preview_tool_output",
|
|
509
684
|
"record_tool_output",
|
|
685
|
+
"remember_question",
|
|
686
|
+
"set_question_running",
|
|
510
687
|
"show_input",
|
|
688
|
+
"take_question",
|
|
689
|
+
"terminal_mode",
|
|
511
690
|
]
|
codebind-0.6.18/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.98c719a309e23852.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";(self.rspackChunkcodebind_jupyterlab=self.rspackChunkcodebind_jupyterlab||[]).push([[590],{509(e,t,n){n.r(t);var o=n(511),l=n(343),d=n(99),i=n(171),r=n(241);let s="codebind:insert-question",c="codebind:toggle-question-mode",a="codebind:run-question",u="jp-CodebindQuestionCell",m=new WeakMap,p=new WeakMap;function g(e){let t=e.getMetadata("codebind");return"object"!=typeof t||null===t||"question"!==t.kind?null:{kind:"question",status:"draft"===t.status?"draft":"sent"}}function f(e){let t=e.getMetadata("codebind");if("object"!=typeof t||null===t)return null;let n=t.kind;return"string"==typeof n?n:null}function y(e){let t={},n=[];for(let[o,l]of Object.entries(e))o.startsWith("text/")||["image/png","image/jpeg","image/webp","image/gif","image/svg+xml"].includes(o)||"application/json"===o||"application/vnd.jupyter.stdout"===o||"application/vnd.jupyter.stderr"===o?void 0!==l&&(t[o]=l):n.push(o);return n.length>0&&(t.omitted_mime_types=n),t}function w(e){return d.isStream(e)?{type:"stream",name:e.name,text:e.text}:d.isError(e)?{type:"error",name:e.ename,message:e.evalue,traceback:e.traceback}:d.isExecuteResult(e)?{type:"result",execution_count:e.execution_count,data:y(e.data)}:d.isDisplayData(e)?{type:"display",data:y(e.data)}:{type:e.output_type}}function _(e){return e.replace(/(^|[^\\])\\([()[\]])/g,"$1\\\\$2")}function b(e){let t=m.get(e);for(let n of e.content.widgets){let e=g(n.model);n.node.classList.toggle(u,null!==e);let o=n.node.querySelector(".jp-InputPrompt");o&&(e?(n.readOnly="sent"===e.status,o.dataset.codebindQuestion="true",o.style.color="#a855f7",o.textContent=t?.runningQuestions.has(n.model.id)?"[*]:":"[ ]:"):o.dataset.codebindQuestion&&(delete o.dataset.codebindQuestion,o.style.removeProperty("color"),o.textContent=""))}}function k(e){let t=e.content;for(let e of t.widgets)"instructions"===f(e.model)&&(e.node.hidden=!0);if(t.activeCell&&"instructions"===f(t.activeCell.model)){let e=t.widgets.findIndex(e=>"instructions"!==f(e.model));e>=0&&(t.activeCellIndex=e)}}function C(e){let t=e.sessionContext.session?.kernel;if(!t)return;let n=m.get(e)??{comm:null,kernel:null,registeredKernel:null,connectKernel:null,disconnectKernel:null,ready:null,resolveReady:null,rejectReady:null,connectOnIdle:!1,runningQuestions:new Map,questionTimers:new Map,sessionReady:!1,cancelAcknowledged:!1,questionMode:!1,questionButton:null,knownCellIds:new Set(e.content.widgets.map(e=>e.model.id)),pendingQuestionCellIds:new Set};if(m.set(e,n),n.registeredKernel===t)return;n.disconnectKernel?.(),n.rejectReady?.(Error("The notebook kernel changed.")),n.comm?.close(),n.registeredKernel=t,n.connectKernel=null,n.disconnectKernel=null,n.ready=null,n.resolveReady=null,n.rejectReady=null,n.connectOnIdle=!1;n.kernel&&n.kernel!==t&&p.get(n.kernel)?.delete(n),n.kernel=t;let d=p.get(t);if(!d){d=new Set,p.set(t,d);let e=t.interrupt.bind(t);t.interrupt=async()=>{let n=[...d??[]].filter(e=>e.runningQuestions.size>0);for(let e of n)e.cancelAcknowledged=!1;if(n.length>0)try{let e=r.KernelMessage.createMessage({session:t.clientId,username:t.username,channel:"control",msgType:"interrupt_request",content:{}});t.sendControlMessage(e,!0).done.catch(()=>void 0)}catch{}for(let e=0;n.length>0&&e<150;e+=1){if(n.every(e=>0===e.runningQuestions.size||e.cancelAcknowledged))return;await new Promise(e=>setTimeout(e,20))}return e()}}for(let e of(d.add(n),n.comm=null,n.runningQuestions.clear(),n.questionTimers.values()))window.clearTimeout(e);n.questionTimers.clear(),n.sessionReady=!1,n.cancelAcknowledged=!1;let i=null,s=new Map,c=new Map,a=()=>{if(!i)return;let e=i;i=null,e.parentModel&&null!==e.parentExecutionCount&&(e.parentModel.executionCount=e.parentExecutionCount)},u=()=>{if(n.comm||"idle"!==t.status||!e.content.model)return;let d=t.createComm("codebind");d.commsOverSubshells=r.CommsOverSubshells.Disabled,n.comm=d,n.sessionReady=!1,n.ready=new Promise((e,t)=>{n.resolveReady=e,n.rejectReady=t}),n.ready.catch(()=>void 0),d.onMsg=r=>{let u,m=r.content.data;if(!function(e){if("object"!=typeof e||null===e)return!1;if("markdown_cell"===e.type)return"string"==typeof e.source;if("markdown_cell_started"===e.type||"markdown_cell_updated"===e.type||"markdown_cell_finished"===e.type)return"string"==typeof e.cell_id&&"string"==typeof e.source;if("markdown_cell_cancelled"===e.type)return"string"==typeof e.cell_id;if("code_cell_started"===e.type)return"string"==typeof e.cell_id&&"string"==typeof e.source;if("code_cell_cancelled"===e.type)return"string"==typeof e.cell_id;if("code_cell_output"===e.type)return"string"==typeof e.cell_id&&"object"==typeof e.output&&null!==e.output;if("code_cell_clear"===e.type)return"string"==typeof e.cell_id&&"boolean"==typeof e.wait;if("question_finished"===e.type){let t=e.error;return"string"==typeof e.cell_id&&"boolean"==typeof e.cancelled&&(null===t||"object"==typeof t&&"string"==typeof t.type&&"string"==typeof t.message)}if("question_started"===e.type)return"string"==typeof e.cell_id;if("cancel_acknowledged"===e.type)return!0;if("session_ready"===e.type){let t=e.error;return null===t||"object"==typeof t&&"string"==typeof t.type&&"string"==typeof t.message}return"conversation_save"===e.type?"string"==typeof e.request_id&&"object"==typeof e.conversation&&null!==e.conversation:"code_cell_finished"===e.type&&"string"==typeof e.cell_id&&("number"==typeof e.execution_count||null===e.execution_count)&&Array.isArray(e.outputs)}(m))return;if("conversation_save"===m.type){let t=e.content.model;return t?(t.setMetadata("codebind",m.conversation),void e.context.save().then(()=>{d.send({type:"conversation_saved",request_id:m.request_id,error:null})},e=>{d.send({type:"conversation_saved",request_id:m.request_id,error:String(e)})})):void d.send({type:"conversation_saved",request_id:m.request_id,error:"Notebook model is unavailable."})}if("session_ready"===m.type){n.sessionReady=null===m.error,m.error?(n.rejectReady?.(Error(m.error.message)),(0,o.showErrorMessage)(`Codebind could not load: ${m.error.type}`,m.error.message)):n.resolveReady?.(),n.resolveReady=null,n.rejectReady=null;return}if("question_started"===m.type){let e=n.questionTimers.get(m.cell_id);void 0!==e&&(window.clearTimeout(e),n.questionTimers.delete(m.cell_id));return}if("cancel_acknowledged"===m.type){n.cancelAcknowledged=!0;return}if("question_finished"===m.type){let t=n.questionTimers.get(m.cell_id);void 0!==t&&(window.clearTimeout(t),n.questionTimers.delete(m.cell_id)),n.runningQuestions.delete(m.cell_id),0===n.runningQuestions.size&&(n.cancelAcknowledged=!1),b(e),a(),m.error&&!m.cancelled&&(0,o.showErrorMessage)(`Codebind question: ${m.error.type}`,m.error.message);return}if("markdown_cell_updated"===m.type||"markdown_cell_finished"===m.type){let t=c.get(m.cell_id);if(!t)return;t.sharedModel.setSource(_(m.source));let n=e.content.widgets.find(e=>e.model.id===t.id);n instanceof l.MarkdownCell&&(n.rendered=!0),"markdown_cell_finished"===m.type&&c.delete(m.cell_id);return}if("markdown_cell_cancelled"===m.type){let t=c.get(m.cell_id);if(c.delete(m.cell_id),!t)return;let n=e.content.widgets.findIndex(e=>e.model.id===t.id);n>=0&&e.content.model?.sharedModel.deleteCell(n);return}if("code_cell_output"===m.type)return void s.get(m.cell_id)?.outputs.add(m.output);if("code_cell_clear"===m.type)return void s.get(m.cell_id)?.outputs.clear(m.wait);if("code_cell_finished"===m.type){let e=s.get(m.cell_id);if(s.delete(m.cell_id),!e)return;e.outputs.fromJSON(m.outputs),e.executionCount=m.execution_count,e.executionState="idle",i&&null===i.parentExecutionCount&&null!==m.execution_count&&(i.parentExecutionCount=m.execution_count-1);return}if("code_cell_cancelled"===m.type){let e=s.get(m.cell_id);s.delete(m.cell_id),e&&(e.executionState="idle");return}if("markdown_cell_started"===m.type)u={type:"markdown_cell",source:m.source};else{if("markdown_cell"!==m.type&&"code_cell_started"!==m.type)return;u=m}(()=>{if(i)return;let n=e.content,o=n.widgets.findIndex(e=>"code"===e.model.type&&"running"===e.model.executionState);i={parentModel:o>=0?n.widgets[o].model:null,parentExecutionCount:null};let l=(e,n)=>{"idle"===n&&(t.statusChanged.disconnect(l),a())};return t.statusChanged.connect(l)})();let p=function(e,t){let n=e.content,o=n.model;if(!o)return null;let d=n.widgets.length;"code_cell_started"===t.type?o.sharedModel.insertCell(d,{cell_type:"code",source:t.source,metadata:{trusted:!0,collapsed:!0,editable:!1,deletable:!1,codebind:{kind:"tool"}},execution_count:null,outputs:[]}):o.sharedModel.insertCell(d,{cell_type:"markdown",source:_(t.source),metadata:{editable:!1,deletable:!1,codebind:{kind:"assistant"}}});let i=n.widgets[d]??null;return i&&(i.readOnly=!0),i instanceof l.MarkdownCell&&(i.rendered=!0),i?.model??null}(e,u);"code_cell_started"===m.type&&p?.type==="code"&&(p.executionState="running",s.set(m.cell_id,p)),"markdown_cell_started"===m.type&&p&&c.set(m.cell_id,p)},d.onClose=()=>{if(n.comm===d){let t=n.sessionReady;for(let e of s.values())e.executionState="idle";for(let e of(s.clear(),n.runningQuestions.clear(),n.cancelAcknowledged=!1,n.questionTimers.values()))window.clearTimeout(e);n.questionTimers.clear(),b(e),n.rejectReady?.(Error("Codebind is not loaded in this kernel. Run %load_ext codebind.")),n.comm=null,n.sessionReady=!1,n.ready=null,n.resolveReady=null,n.rejectReady=null,n.connectOnIdle=t}};let u=e.content.model?.getMetadata("codebind");d.open({conversation:"object"==typeof u&&null!==u?u:null})};n.connectKernel=u;let g=(e,t)=>{"idle"===t&&n.connectOnIdle&&(n.connectOnIdle=!1,u())},f=(e,t)=>{r.KernelMessage.isExecuteInputMsg(t)&&/(?:^|\n)\s*%(?:re)?load_ext\s+codebind(?:\s|$)/.test(t.content.code)&&(n.connectOnIdle=!0)};t.statusChanged.connect(g),t.iopubMessage.connect(f),n.disconnectKernel=()=>{t.statusChanged.disconnect(g),t.iopubMessage.disconnect(f)},e.context.ready.then(()=>{e.content.model?.getMetadata("codebind")&&(n.connectOnIdle=!0,u())})}function h(e){let t=e.content,n=t.model;if(!n)return;t.activeCell?"markdown"!==t.activeCell.model.type&&i.NotebookActions.changeCellType(t,"markdown"):(n.sharedModel.insertCell(0,{cell_type:"markdown",source:"",metadata:{}}),t.activeCellIndex=0);let o=t.activeCell;o&&null!==f(o.model)||(o?.model.setMetadata("codebind",{kind:"question",status:"draft"}),o instanceof l.MarkdownCell&&(o.rendered=!1),t.mode="edit",b(e),o?.editor?.focus())}function v(e){let t=m.get(e);if(!t)return;k(e);let n=e.content.widgets,o=new Set(n.map(e=>e.model.id)),l=n.filter(e=>!t.knownCellIds.has(e.model.id));for(let e of(t.knownCellIds=o,t.pendingQuestionCellIds))o.has(e)||t.pendingQuestionCellIds.delete(e);if(t.questionMode)for(let e of l)null===f(e.model)&&t.pendingQuestionCellIds.add(e.model.id);b(e),t.questionMode&&e.content.activeCell&&t.pendingQuestionCellIds.delete(e.content.activeCell.model.id)&&h(e)}function M(e){let t=m.get(e);t&&q(e,!t.questionMode)}function q(e,t){let n=m.get(e);if(n){if(n.questionMode=t,!n.questionMode){n.pendingQuestionCellIds.clear();let t=e.content.activeCell;t&&g(t.model)?.status==="draft"&&(t.model.deleteMetadata("codebind"),i.NotebookActions.changeCellType(e.content,"code"),e.content.mode="edit",e.content.activeCell?.editor?.focus())}n.questionButton&&(n.questionButton.pressed=n.questionMode),n.questionMode&&e.content.activeCell&&null===f(e.content.activeCell.model)&&h(e)}}async function x(e){let t=e.content,n=t.activeCell;if(!n||!g(n.model))return;await e.sessionContext.ready,C(e);let d=m.get(e),i=d?.registeredKernel;if(!d||!i)return void await (0,o.showErrorMessage)("Codebind is not connected","Start the notebook kernel before sending a Question cell.");try{if("dead"===i.status)throw Error("The notebook kernel stopped.");if("idle"!==i.status&&await new Promise((e,t)=>{let n=(o,l)=>{("idle"===l||"dead"===l)&&(i.statusChanged.disconnect(n),"idle"===l?e():t(Error("The notebook kernel stopped.")))};i.statusChanged.connect(n)}),d.connectKernel?.(),!d.ready)throw Error("Run %load_ext codebind in this kernel.");await d.ready}catch(e){await (0,o.showErrorMessage)("Codebind could not load",String(e));return}if(!d.sessionReady||!d.comm)return void await (0,o.showErrorMessage)("Codebind is not connected","Run %load_ext codebind in this kernel before sending a Question cell.");if(d.runningQuestions.size>0)return void await (0,o.showErrorMessage)("Codebind is busy","Wait for the current question to finish before sending another.");let r=n.model.sharedModel.getSource().trim();if(!r)return void await (0,o.showErrorMessage)("Empty Codebind question","Write a question before sending it.");d.runningQuestions.set(n.model.id,n.model),d.cancelAcknowledged=!1,n.model.sharedModel.setSource(_(r)),n.model.setMetadata("codebind",{kind:"question",status:"sent"}),n.model.setMetadata("editable",!1),n.model.setMetadata("deletable",!1),n.readOnly=!0,b(e),n instanceof l.MarkdownCell&&(n.rendered=!0),t.mode="command";let s=window.setTimeout(()=>{d.questionTimers.has(n.model.id)&&(d.questionTimers.delete(n.model.id),d.runningQuestions.delete(n.model.id),n.model.setMetadata("codebind",{kind:"question",status:"draft"}),n.model.setMetadata("editable",!0),n.model.setMetadata("deletable",!0),n.readOnly=!1,b(e),(0,o.showErrorMessage)("Codebind did not receive the Question","The kernel did not acknowledge it. Reload Codebind and send it again."))},1e4);d.questionTimers.set(n.model.id,s),d.comm.send({type:"question",cell_id:n.model.id,question:r,notebook:function(e){let t=[];for(let n of e.content.widgets){if(null!==f(n.model))continue;let e=n.model.type;if("code"!==e&&"markdown"!==e&&"raw"!==e)continue;let o={id:n.model.id,type:e,source:n.model.sharedModel.getSource(),execution_count:null,outputs:[],attachments:{}};if("code"===e){let e=n.model.toJSON();o.execution_count=e.execution_count,o.outputs=e.outputs.map(w)}else{let e=n.model.toJSON().attachments;if(e){let t={};for(let[n,o]of Object.entries(e))o&&(t[n]=y(o));o.attachments=t}}t.push(o)}return t}(e)})}function T(e,t){let n={comm:null,kernel:null,registeredKernel:null,connectKernel:null,disconnectKernel:null,ready:null,resolveReady:null,rejectReady:null,connectOnIdle:!1,runningQuestions:new Map,questionTimers:new Map,sessionReady:!1,cancelAcknowledged:!1,questionMode:!1,questionButton:null,knownCellIds:new Set(e.content.widgets.map(e=>e.model.id)),pendingQuestionCellIds:new Set};m.set(e,n);let l=!1,d=()=>{if(!l){if(!n.kernel){n.runningQuestions.size>0&&(n.cancelAcknowledged=!1,n.comm?.send({type:"cancel"}));return}l=!0,n.kernel.interrupt().catch(e=>{n.runningQuestions.size>0&&(0,o.showErrorMessage)("Codebind could not interrupt",String(e))}).finally(()=>{l=!1})}},i=e=>{0!==n.runningQuestions.size&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),d())},r=n=>{"Tab"===n.key&&n.shiftKey&&!n.ctrlKey&&!n.altKey&&!n.metaKey&&n.target instanceof Node&&e.content.node.contains(n.target)&&(n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),M(e),t.commands.notifyCommandChanged(c))},s=o=>{0===n.runningQuestions.size||t.shell.currentWidget!==e||"c"!==o.key.toLowerCase()||!o.ctrlKey||o.altKey||o.metaKey||o.shiftKey||(o.preventDefault(),o.stopPropagation(),o.stopImmediatePropagation(),d())};e.node.addEventListener("keydown",r,!0),window.addEventListener("keydown",s,!0);let a=null,u=()=>{let t=e.toolbar.node.querySelector('[data-command="notebook:interrupt-kernel"]');t!==a&&(a?.removeEventListener("click",i,!0),a=t,a?.addEventListener("click",i,!0))},g=new MutationObserver(u);g.observe(e.toolbar.node,{childList:!0,subtree:!0});let f=new MutationObserver(()=>{window.setTimeout(()=>v(e),0)});f.observe(e.content.node,{childList:!0,subtree:!0}),u(),e.disposed.connect(()=>{for(let t of(g.disconnect(),f.disconnect(),a?.removeEventListener("click",i,!0),e.node.removeEventListener("keydown",r,!0),window.removeEventListener("keydown",s,!0),n.disconnectKernel?.(),n.rejectReady?.(Error("The notebook closed.")),n.comm?.close(),n.kernel&&p.get(n.kernel)?.delete(n),n.questionTimers.values()))window.clearTimeout(t);n.questionTimers.clear()});let y=new o.ToolbarButton({label:"Question",tooltip:"Toggle Question mode for the selected and newly created cells",onClick:()=>{q(e,y.pressed),t.commands.notifyCommandChanged(c)}});n.questionButton=y,e.toolbar.insertItem(10,"codebindQuestion",y),e.content.modelContentChanged.connect(()=>{v(e),window.setTimeout(()=>v(e),0)}),e.content.activeCellChanged.connect(()=>v(e)),e.context.ready.then(()=>{k(e),e.content.model?.cells.changed.connect(()=>{v(e),window.setTimeout(()=>v(e),0)}),v(e)}),e.sessionContext.ready.then(()=>C(e)),e.sessionContext.kernelChanged.connect(()=>C(e))}let E={id:"codebind-jupyterlab:plugin",description:"Insert Codebind executions as native notebook cells.",autoStart:!0,requires:[i.INotebookTracker],activate:(e,t)=>{e.commands.addCommand(s,{label:"Use Selected Cell as Codebind Question",execute:()=>{let e=t.currentWidget;e&&h(e)}}),e.commands.addCommand(c,{label:"Toggle Codebind Question Mode",isToggled:()=>{let e=t.currentWidget;return!!e&&(m.get(e)?.questionMode??!1)},execute:()=>{let n=t.currentWidget;n&&(M(n),e.commands.notifyCommandChanged(c))}}),e.commands.addCommand(a,{label:"Send Codebind Question",isEnabled:()=>{let e=t.currentWidget?.content.activeCell;return!!e&&null!==g(e.model)},execute:async()=>{let e=t.currentWidget;e&&await x(e)}}),e.commands.addKeyBinding({command:a,keys:["Shift Enter"],selector:`.jp-Notebook.jp-mod-editMode .${u}`}),e.commands.addKeyBinding({command:a,keys:["Shift Enter"],selector:`.jp-Notebook.jp-mod-commandMode .${u}`}),e.contextMenu.addItem({command:s,selector:".jp-Notebook .jp-Cell",rank:8}),t.forEach(t=>T(t,e)),t.widgetAdded.connect((t,n)=>T(n,e))}};n.d(t,{},{default:E})}}]);
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|