codebind 0.4.3__tar.gz → 0.5.0__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.
Files changed (28) hide show
  1. {codebind-0.4.3 → codebind-0.5.0}/PKG-INFO +3 -1
  2. {codebind-0.4.3 → codebind-0.5.0}/README.md +2 -0
  3. {codebind-0.4.3 → codebind-0.5.0}/data/share/jupyter/labextensions/codebind-jupyterlab/package.json +4 -3
  4. codebind-0.5.0/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.31336058307703b3.js +23 -0
  5. codebind-0.5.0/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.bcc512bba6776143.js +1 -0
  6. {codebind-0.4.3 → codebind-0.5.0}/jupyterlab/package.json +3 -2
  7. codebind-0.5.0/jupyterlab/src/index.ts +513 -0
  8. {codebind-0.4.3 → codebind-0.5.0}/jupyterlab/yarn.lock +2 -1
  9. {codebind-0.4.3 → codebind-0.5.0}/pyproject.toml +1 -1
  10. {codebind-0.4.3 → codebind-0.5.0}/pyproject.toml.orig +1 -1
  11. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/extension.py +12 -1
  12. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/jupyter.py +42 -1
  13. codebind-0.4.3/data/share/jupyter/labextensions/codebind-jupyterlab/static/590.6544266cd73a003b.js +0 -1
  14. codebind-0.4.3/data/share/jupyter/labextensions/codebind-jupyterlab/static/remoteEntry.6f017385dfc989f1.js +0 -1
  15. codebind-0.4.3/jupyterlab/src/index.ts +0 -265
  16. {codebind-0.4.3 → codebind-0.5.0}/LICENSE +0 -0
  17. {codebind-0.4.3 → codebind-0.5.0}/data/share/jupyter/labextensions/codebind-jupyterlab/install.json +0 -0
  18. {codebind-0.4.3 → codebind-0.5.0}/data/share/jupyter/labextensions/codebind-jupyterlab/static/style.js +0 -0
  19. {codebind-0.4.3 → codebind-0.5.0}/data/share/jupyter/labextensions/codebind-jupyterlab/static/third-party-licenses.json +0 -0
  20. {codebind-0.4.3 → codebind-0.5.0}/jupyterlab/.yarnrc.yml +0 -0
  21. {codebind-0.4.3 → codebind-0.5.0}/jupyterlab/install.json +0 -0
  22. {codebind-0.4.3 → codebind-0.5.0}/jupyterlab/tsconfig.json +0 -0
  23. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/__init__.py +0 -0
  24. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/cli.py +0 -0
  25. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/display.py +0 -0
  26. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/execution.py +0 -0
  27. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/py.typed +0 -0
  28. {codebind-0.4.3 → codebind-0.5.0}/src/codebind/session.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codebind
3
- Version: 0.4.3
3
+ Version: 0.5.0
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
@@ -86,6 +86,8 @@ model = models.chat("openai/gpt-5")
86
86
  await chat.asend("Inspect the current notebook state.", model)
87
87
  ```
88
88
 
89
+ After assigning `model`, click **Question** in the notebook toolbar to insert a Question cell. Write ordinary Markdown and press `Shift+Enter`; Codebind sends the cell through `chat` using the `model` variable, renders the question as Markdown, and inserts tool executions and the assistant response beneath it. Question cells are stored as standard Markdown cells with Codebind metadata, so other notebook frontends can still read them.
90
+
89
91
  The Codebind package includes a prebuilt JupyterLab extension. In JupyterLab, each model-authored IPython execution becomes a genuine code cell with its native execution count and outputs, and the assistant response becomes a rendered Markdown cell. The cells are ordinary notebook content and are saved with the notebook.
90
92
 
91
93
  Other IPython frontends use the standard MIME display protocol instead. They still receive syntax-highlighted code, assistant Markdown, stdout, tracebacks, rich results, and native IPython history without Codebind depending on their UI.
@@ -61,6 +61,8 @@ model = models.chat("openai/gpt-5")
61
61
  await chat.asend("Inspect the current notebook state.", model)
62
62
  ```
63
63
 
64
+ After assigning `model`, click **Question** in the notebook toolbar to insert a Question cell. Write ordinary Markdown and press `Shift+Enter`; Codebind sends the cell through `chat` using the `model` variable, renders the question as Markdown, and inserts tool executions and the assistant response beneath it. Question cells are stored as standard Markdown cells with Codebind metadata, so other notebook frontends can still read them.
65
+
64
66
  The Codebind package includes a prebuilt JupyterLab extension. In JupyterLab, each model-authored IPython execution becomes a genuine code cell with its native execution count and outputs, and the assistant response becomes a rendered Markdown cell. The cells are ordinary notebook content and are saved with the notebook.
65
67
 
66
68
  Other IPython frontends use the standard MIME display protocol instead. They still receive syntax-highlighted code, assistant Markdown, stdout, tracebacks, rich results, and native IPython history without Codebind depending on their UI.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "codebind-jupyterlab",
3
- "version": "0.4.1",
4
- "description": "Native JupyterLab cells for Codebind model executions.",
3
+ "version": "0.5.0",
4
+ "description": "Native JupyterLab cells and Question cells for Codebind.",
5
5
  "license": "MIT",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@jupyterlab/application": "^4.0.0",
19
+ "@jupyterlab/apputils": "^4.0.0",
19
20
  "@jupyterlab/cells": "^4.0.0",
20
21
  "@jupyterlab/nbformat": "^4.0.0",
21
22
  "@jupyterlab/notebook": "^4.0.0",
@@ -30,7 +31,7 @@
30
31
  "extension": true,
31
32
  "outputDir": "../data/share/jupyter/labextensions/codebind-jupyterlab",
32
33
  "_build": {
33
- "load": "static/remoteEntry.6f017385dfc989f1.js",
34
+ "load": "static/remoteEntry.bcc512bba6776143.js",
34
35
  "extension": "./extension"
35
36
  }
36
37
  }
@@ -0,0 +1,23 @@
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),i=n(171);let r="codebind:insert-question",d="codebind:run-question",s="jp-CodebindQuestionCell",u="jp-CodebindQuestionCell-running",c="jp-CodebindQuestionCell-error",a=new WeakMap;function p(e){let t=e.getMetadata("codebind");return"object"!=typeof t||null===t||"question"!==t.kind?null:{kind:"question",model:"string"==typeof t.model?t.model:"model"}}function m(e){let t=a.get(e);for(let n of e.content.widgets){let e=p(n.model);n.node.classList.toggle(s,null!==e),n.node.classList.toggle(u,t?.runningQuestions.has(n.model.id)??!1)}}function f(e){let t=e.sessionContext.session?.kernel;if(!t)return;let n=a.get(e)??{comm:null,runningQuestions:new Map};a.set(e,n),n.comm=null,n.runningQuestions.clear();let l=null,r=new Map,d=(t=!0)=>{if(!l)return;let n=e.content,o=l;if(l=null,o.parentModel&&null!==o.parentExecutionCount&&(o.parentModel.executionCount=o.parentExecutionCount),t&&o.resumeModel){let e=n.widgets.findIndex(e=>e.model===o.resumeModel);e>=0&&(n.activeCellIndex=e)}};t.registerCommTarget("codebind",(s,u)=>{s.onMsg=s=>{var u;let a,p,f=s.content.data;if(!function(e){if("object"!=typeof e||null===e)return!1;if("markdown_cell"===e.type)return"string"==typeof e.source;if("code_cell_started"===e.type)return"string"==typeof e.cell_id&&"string"==typeof e.source;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&&(null===t||"object"==typeof t&&"string"==typeof t.type&&"string"==typeof t.message)}return"code_cell_finished"===e.type&&"string"==typeof e.cell_id&&("number"==typeof e.execution_count||null===e.execution_count)&&Array.isArray(e.outputs)}(f))return;if("question_finished"===f.type){let t=n.runningQuestions.get(f.cell_id);if(n.runningQuestions.delete(f.cell_id),t){let n=e.content.widgets.find(e=>e.model===t);n?.node.classList.toggle(c,null!==f.error)}m(e),d(!1),f.error&&(0,o.showErrorMessage)(`Codebind question: ${f.error.type}`,f.error.message);return}if("code_cell_output"===f.type)return void r.get(f.cell_id)?.outputs.add(f.output);if("code_cell_clear"===f.type)return void r.get(f.cell_id)?.outputs.clear(f.wait);if("code_cell_finished"===f.type){let e=r.get(f.cell_id);if(!e)return;e.outputs.fromJSON(f.outputs),e.executionCount=f.execution_count,e.executionState="idle",l&&null===l.parentExecutionCount&&null!==f.execution_count&&(l.parentExecutionCount=f.execution_count-1);return}let g=(()=>{if(l)return l;let n=e.content,o=n.widgets.findIndex(e=>"code"===e.model.type&&"running"===e.model.executionState);l={parentModel:o>=0?n.widgets[o].model:null,parentExecutionCount:null,resumeModel:n.activeCell?.model??null,nextIndex:o>=0?o+1:n.activeCell?n.activeCellIndex+1:0};let i=(e,n)=>{"idle"===n&&(t.statusChanged.disconnect(i),d())};return t.statusChanged.connect(i),l})(),y=(u=g.nextIndex,(p=(a=e.content).model)?("code_cell_started"===f.type?p.sharedModel.insertCell(u,{cell_type:"code",source:f.source,metadata:{trusted:!0},execution_count:null,outputs:[]}):p.sharedModel.insertCell(u,{cell_type:"markdown",source:f.source,metadata:{}}),a.activeCellIndex=u,a.deselectAll(),"markdown_cell"===f.type&&i.NotebookActions.run(a),a.scrollToItem(u),a.widgets[u]?.model??null):null);"code_cell_started"===f.type&&y?.type==="code"&&(y.executionState="running",r.set(f.cell_id,y)),g.nextIndex+=1},n.comm=s,s.onClose=()=>{n.comm===s&&(n.comm=null)},s.send({type:"ready"})})}async function g(e){let t=e.content,n=t.activeCell;if(!n)return;let i=p(n.model);if(!i)return;let r=a.get(e);if(!r?.comm)return void await (0,o.showErrorMessage)("Codebind is not connected","Run %load_ext codebind in this kernel before sending a Question cell.");if(r.runningQuestions.size>0)return void await (0,o.showErrorMessage)("Codebind is busy","Wait for the current question to finish before sending another.");let d=n.model.sharedModel.getSource().trim();d?(n.node.classList.remove(c),r.runningQuestions.set(n.model.id,n.model),m(e),n instanceof l.MarkdownCell&&(n.rendered=!0),t.mode="command",r.comm.send({type:"question",cell_id:n.model.id,question:d,model:i.model})):await (0,o.showErrorMessage)("Empty Codebind question","Write a question before sending it.")}function y(e,t){a.set(e,{comm:null,runningQuestions:new Map}),e.toolbar.insertItem(10,"codebindQuestion",new o.ToolbarButton({label:"Question",tooltip:"Insert a Codebind Question cell",onClick:()=>{t.commands.execute(r)}})),e.content.modelContentChanged.connect(()=>m(e)),e.context.ready.then(()=>m(e)),e.sessionContext.ready.then(()=>f(e)),e.sessionContext.kernelChanged.connect(()=>f(e))}let b={id:"codebind-jupyterlab:plugin",description:"Insert Codebind executions as native notebook cells.",autoStart:!0,requires:[i.INotebookTracker],activate:(e,t)=>{!function(){if(document.getElementById("codebind-question-styles"))return;let e=document.createElement("style");e.id="codebind-question-styles",e.textContent=`
2
+ .${s} {
3
+ border-left: 3px solid var(--jp-brand-color1);
4
+ background: color-mix(in srgb, var(--jp-brand-color1) 6%, transparent);
5
+ }
6
+ .${s} .jp-Cell-inputWrapper::before {
7
+ content: "Question";
8
+ display: block;
9
+ padding: 4px 10px 0;
10
+ color: var(--jp-brand-color1);
11
+ font-size: var(--jp-ui-font-size0);
12
+ font-weight: 600;
13
+ letter-spacing: 0.04em;
14
+ text-transform: uppercase;
15
+ }
16
+ .${u} {
17
+ border-left-color: var(--jp-warn-color1);
18
+ opacity: 0.78;
19
+ }
20
+ .${c} {
21
+ border-left-color: var(--jp-error-color1);
22
+ }
23
+ `,document.head.appendChild(e)}(),e.commands.addCommand(r,{label:"Insert Codebind Question",execute:()=>{let e=t.currentWidget;e&&function(e){let t=e.content,n=t.model;if(!n)return;let o=t.activeCell?t.activeCellIndex+1:0;n.sharedModel.insertCell(o,{cell_type:"markdown",source:"",metadata:{codebind:{kind:"question",model:"model"}}}),t.activeCellIndex=o,t.deselectAll();let i=t.widgets[o];i instanceof l.MarkdownCell&&(i.rendered=!1),t.mode="edit",m(e),i?.editor?.focus()}(e)}}),e.commands.addCommand(d,{label:"Send Codebind Question",isEnabled:()=>{let e=t.currentWidget?.content.activeCell;return!!e&&null!==p(e.model)},execute:async()=>{let e=t.currentWidget;e&&await g(e)}}),e.commands.addKeyBinding({command:d,keys:["Shift Enter"],selector:`.jp-Notebook .${s}`}),e.contextMenu.addItem({command:r,selector:".jp-Notebook .jp-Cell",rank:8}),t.forEach(t=>y(t,e)),t.widgetAdded.connect((t,n)=>y(n,e))}};n.d(t,{},{default:b})}}]);
@@ -0,0 +1 @@
1
+ var _JUPYTERLAB;(()=>{"use strict";var e,n,r,t,o,i,u,a,c,l,f,s,p,d,h,g,v,y,m,b,S,k,j,w,E,x,T,M,P,A,C,O,D,_,q,L,V,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+".31336058307703b3.js?v=31336058307703b3",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(f);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)},f=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.5.0",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,J=z.g.document;if(!B&&J&&(J.currentScript&&"SCRIPT"===J.currentScript.tagName.toUpperCase()&&(B=J.currentScript.src),!B)){var K=J.getElementsByTagName("script");if(K.length)for(var Y=K.length-1;Y>-1&&(!B||!/^http(s?):/.test(B));)B=K[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","171"]},moduleIdToConsumeDataMapping:{171:{shareScope:"default",shareKey:"@jupyterlab/notebook",import:null,requiredVersion:"^4.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}},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]),f=r(n[1]);return[,t(f),o(f),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,f,s=a<e.length?(typeof e[a])[0]:"";if(u>=n.length||"o"==(f=(typeof(l=n[u]))[0])){if(!c)return!0;if("u"==s)return a>t&&!o;return""==s!=o}if("u"==f){if(!c||"u"!=s)return!1}else if(c)if(s==f)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"!=s&&"n"!=s){if(o||a<=t)return!1;c=!1,a--}else{if(a<=t||f<s!=o)return!1;c=!1}else"s"!=s&&"n"!=s&&(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)+")"},f=function(e,n,r,t){var o=c(e,r);return m(e[r][o])},s=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),f(n,e,r)}),E=b(function(e,n,r,t){return u(e,r),s(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)?f(n,e,r):t()}),A=b(function(e,n,r,t,o){return n&&z.o(n,r)?s(n,e,r,t):o()}),C=b(function(e,n,r,t,o){var i=n&&z.o(n,r)&&d(n,r,t);return i?m(i):o()}),O=b(function(e,n,r,t,o){return n&&z.o(n,r)?p(n,e,r,t):o()}),D=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 O.apply(null,u)}:r&&o&&i?function(){return C.apply(null,u)}:t&&o&&i?function(){return A.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)}},_={},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(_,e))return n.push(_[e]);var t=function(n){_[e]=0,z.m[e]=function(r){delete z.c[e],r.exports=n()}},o=function(n){delete _[e],z.m[e]=function(r){throw delete z.c[e],n}};try{var i=D(r[e])();i.then?n.push(_[e]=i.then(t).catch(o)):t(i)}catch(e){o(e)}})},q={871:0},z.f.j=function(e,n){var r=z.o(q,e)?q[e]:void 0;if(0!==r)if(r)n.push(r[2]);else{var t=new Promise((n,t)=>r=q[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(q,e)&&(0!==(r=q[e])&&(q[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)}},L=(e,n)=>{var r,t,[o,i,u]=n,a=0;if(o.some(e=>0!==q[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(q,t)&&q[t]&&q[t][0](),q[t]=0},(V=self.rspackChunkcodebind_jupyterlab=self.rspackChunkcodebind_jupyterlab||[]).forEach(L.bind(null,0)),V.push=L.bind(null,V.push.bind(V));var F=z(457);(_JUPYTERLAB=void 0===_JUPYTERLAB?{}:_JUPYTERLAB)["codebind-jupyterlab"]=F})();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "codebind-jupyterlab",
3
- "version": "0.4.1",
4
- "description": "Native JupyterLab cells for Codebind model executions.",
3
+ "version": "0.5.0",
4
+ "description": "Native JupyterLab cells and Question cells for Codebind.",
5
5
  "license": "MIT",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@jupyterlab/application": "^4.0.0",
19
+ "@jupyterlab/apputils": "^4.0.0",
19
20
  "@jupyterlab/cells": "^4.0.0",
20
21
  "@jupyterlab/nbformat": "^4.0.0",
21
22
  "@jupyterlab/notebook": "^4.0.0",
@@ -0,0 +1,513 @@
1
+ import {
2
+ JupyterFrontEnd,
3
+ JupyterFrontEndPlugin
4
+ } from '@jupyterlab/application';
5
+ import { showErrorMessage, ToolbarButton } from '@jupyterlab/apputils';
6
+ import { ICellModel, ICodeCellModel, MarkdownCell } from '@jupyterlab/cells';
7
+ import * as nbformat from '@jupyterlab/nbformat';
8
+ import {
9
+ INotebookTracker,
10
+ NotebookActions,
11
+ NotebookPanel
12
+ } from '@jupyterlab/notebook';
13
+ import { Kernel, KernelMessage } from '@jupyterlab/services';
14
+
15
+ const TARGET_NAME = 'codebind';
16
+ const INSERT_QUESTION = 'codebind:insert-question';
17
+ const RUN_QUESTION = 'codebind:run-question';
18
+ const QUESTION_CLASS = 'jp-CodebindQuestionCell';
19
+ const QUESTION_RUNNING_CLASS = 'jp-CodebindQuestionCell-running';
20
+ const QUESTION_ERROR_CLASS = 'jp-CodebindQuestionCell-error';
21
+
22
+ interface CodeCellStartedMessage {
23
+ type: 'code_cell_started';
24
+ cell_id: string;
25
+ source: string;
26
+ }
27
+
28
+ interface CodeCellFinishedMessage {
29
+ type: 'code_cell_finished';
30
+ cell_id: string;
31
+ execution_count: number | null;
32
+ outputs: nbformat.IOutput[];
33
+ }
34
+
35
+ interface CodeCellOutputMessage {
36
+ type: 'code_cell_output';
37
+ cell_id: string;
38
+ output: nbformat.IOutput;
39
+ }
40
+
41
+ interface CodeCellClearMessage {
42
+ type: 'code_cell_clear';
43
+ cell_id: string;
44
+ wait: boolean;
45
+ }
46
+
47
+ interface MarkdownCellMessage {
48
+ type: 'markdown_cell';
49
+ source: string;
50
+ }
51
+
52
+ interface QuestionFinishedMessage {
53
+ type: 'question_finished';
54
+ cell_id: string;
55
+ error: { type: string; message: string } | null;
56
+ }
57
+
58
+ type CodebindMessage =
59
+ | CodeCellStartedMessage
60
+ | CodeCellFinishedMessage
61
+ | CodeCellOutputMessage
62
+ | CodeCellClearMessage
63
+ | MarkdownCellMessage
64
+ | QuestionFinishedMessage;
65
+ type InsertMessage = CodeCellStartedMessage | MarkdownCellMessage;
66
+
67
+ interface TurnState {
68
+ parentModel: ICodeCellModel | null;
69
+ parentExecutionCount: number | null;
70
+ resumeModel: ICellModel | null;
71
+ nextIndex: number;
72
+ }
73
+
74
+ interface PanelState {
75
+ comm: Kernel.IComm | null;
76
+ runningQuestions: Map<string, ICellModel>;
77
+ }
78
+
79
+ interface QuestionMetadata {
80
+ kind: 'question';
81
+ model: string;
82
+ }
83
+
84
+ const panelStates = new WeakMap<NotebookPanel, PanelState>();
85
+
86
+ function isCodebindMessage(value: unknown): value is CodebindMessage {
87
+ if (typeof value !== 'object' || value === null) {
88
+ return false;
89
+ }
90
+ const message = value as Record<string, unknown>;
91
+ if (message.type === 'markdown_cell') {
92
+ return typeof message.source === 'string';
93
+ }
94
+ if (message.type === 'code_cell_started') {
95
+ return (
96
+ typeof message.cell_id === 'string' &&
97
+ typeof message.source === 'string'
98
+ );
99
+ }
100
+ if (message.type === 'code_cell_output') {
101
+ return (
102
+ typeof message.cell_id === 'string' &&
103
+ typeof message.output === 'object' &&
104
+ message.output !== null
105
+ );
106
+ }
107
+ if (message.type === 'code_cell_clear') {
108
+ return typeof message.cell_id === 'string' && typeof message.wait === 'boolean';
109
+ }
110
+ if (message.type === 'question_finished') {
111
+ const error = message.error;
112
+ return (
113
+ typeof message.cell_id === 'string' &&
114
+ (error === null ||
115
+ (typeof error === 'object' &&
116
+ typeof (error as Record<string, unknown>).type === 'string' &&
117
+ typeof (error as Record<string, unknown>).message === 'string'))
118
+ );
119
+ }
120
+ return (
121
+ message.type === 'code_cell_finished' &&
122
+ typeof message.cell_id === 'string' &&
123
+ (typeof message.execution_count === 'number' ||
124
+ message.execution_count === null) &&
125
+ Array.isArray(message.outputs)
126
+ );
127
+ }
128
+
129
+ function questionMetadata(model: ICellModel): QuestionMetadata | null {
130
+ const value = model.getMetadata('codebind');
131
+ if (typeof value !== 'object' || value === null) {
132
+ return null;
133
+ }
134
+ const metadata = value as Record<string, unknown>;
135
+ if (metadata.kind !== 'question') {
136
+ return null;
137
+ }
138
+ return {
139
+ kind: 'question',
140
+ model: typeof metadata.model === 'string' ? metadata.model : 'model'
141
+ };
142
+ }
143
+
144
+ function refreshQuestionCells(panel: NotebookPanel): void {
145
+ const state = panelStates.get(panel);
146
+ for (const cell of panel.content.widgets) {
147
+ const question = questionMetadata(cell.model);
148
+ cell.node.classList.toggle(QUESTION_CLASS, question !== null);
149
+ cell.node.classList.toggle(
150
+ QUESTION_RUNNING_CLASS,
151
+ state?.runningQuestions.has(cell.model.id) ?? false
152
+ );
153
+ }
154
+ }
155
+
156
+ function ensureStyles(): void {
157
+ if (document.getElementById('codebind-question-styles')) {
158
+ return;
159
+ }
160
+ const style = document.createElement('style');
161
+ style.id = 'codebind-question-styles';
162
+ style.textContent = `
163
+ .${QUESTION_CLASS} {
164
+ border-left: 3px solid var(--jp-brand-color1);
165
+ background: color-mix(in srgb, var(--jp-brand-color1) 6%, transparent);
166
+ }
167
+ .${QUESTION_CLASS} .jp-Cell-inputWrapper::before {
168
+ content: "Question";
169
+ display: block;
170
+ padding: 4px 10px 0;
171
+ color: var(--jp-brand-color1);
172
+ font-size: var(--jp-ui-font-size0);
173
+ font-weight: 600;
174
+ letter-spacing: 0.04em;
175
+ text-transform: uppercase;
176
+ }
177
+ .${QUESTION_RUNNING_CLASS} {
178
+ border-left-color: var(--jp-warn-color1);
179
+ opacity: 0.78;
180
+ }
181
+ .${QUESTION_ERROR_CLASS} {
182
+ border-left-color: var(--jp-error-color1);
183
+ }
184
+ `;
185
+ document.head.appendChild(style);
186
+ }
187
+
188
+ function insertCell(
189
+ panel: NotebookPanel,
190
+ message: InsertMessage,
191
+ index: number
192
+ ): ICellModel | null {
193
+ const notebook = panel.content;
194
+ const model = notebook.model;
195
+ if (!model) {
196
+ return null;
197
+ }
198
+
199
+ if (message.type === 'code_cell_started') {
200
+ model.sharedModel.insertCell(index, {
201
+ cell_type: 'code',
202
+ source: message.source,
203
+ metadata: { trusted: true },
204
+ execution_count: null,
205
+ outputs: []
206
+ });
207
+ } else {
208
+ model.sharedModel.insertCell(index, {
209
+ cell_type: 'markdown',
210
+ source: message.source,
211
+ metadata: {}
212
+ });
213
+ }
214
+
215
+ notebook.activeCellIndex = index;
216
+ notebook.deselectAll();
217
+ if (message.type === 'markdown_cell') {
218
+ void NotebookActions.run(notebook);
219
+ }
220
+ void notebook.scrollToItem(index);
221
+ return notebook.widgets[index]?.model ?? null;
222
+ }
223
+
224
+ function registerKernel(panel: NotebookPanel): void {
225
+ const kernel = panel.sessionContext.session?.kernel;
226
+ if (!kernel) {
227
+ return;
228
+ }
229
+
230
+ const panelState = panelStates.get(panel) ?? {
231
+ comm: null,
232
+ runningQuestions: new Map<string, ICellModel>()
233
+ };
234
+ panelStates.set(panel, panelState);
235
+ panelState.comm = null;
236
+ panelState.runningQuestions.clear();
237
+
238
+ let turn: TurnState | null = null;
239
+ const codeCells = new Map<string, ICodeCellModel>();
240
+
241
+ const finishTurn = (restoreSelection = true): void => {
242
+ if (!turn) {
243
+ return;
244
+ }
245
+ const notebook = panel.content;
246
+ const completed = turn;
247
+ turn = null;
248
+ if (
249
+ completed.parentModel &&
250
+ completed.parentExecutionCount !== null
251
+ ) {
252
+ completed.parentModel.executionCount = completed.parentExecutionCount;
253
+ }
254
+ if (restoreSelection && completed.resumeModel) {
255
+ const index = notebook.widgets.findIndex(
256
+ widget => widget.model === completed.resumeModel
257
+ );
258
+ if (index >= 0) {
259
+ notebook.activeCellIndex = index;
260
+ }
261
+ }
262
+ };
263
+
264
+ const beginTurn = (): TurnState => {
265
+ if (turn) {
266
+ return turn;
267
+ }
268
+ const notebook = panel.content;
269
+ const parentIndex = notebook.widgets.findIndex(
270
+ widget =>
271
+ widget.model.type === 'code' &&
272
+ (widget.model as ICodeCellModel).executionState === 'running'
273
+ );
274
+ const parentModel =
275
+ parentIndex >= 0
276
+ ? (notebook.widgets[parentIndex].model as ICodeCellModel)
277
+ : null;
278
+ turn = {
279
+ parentModel,
280
+ parentExecutionCount: null,
281
+ resumeModel: notebook.activeCell?.model ?? null,
282
+ nextIndex:
283
+ parentIndex >= 0
284
+ ? parentIndex + 1
285
+ : notebook.activeCell
286
+ ? notebook.activeCellIndex + 1
287
+ : 0
288
+ };
289
+
290
+ const onStatus = (
291
+ _sender: Kernel.IKernelConnection,
292
+ status: Kernel.Status
293
+ ): void => {
294
+ if (status === 'idle') {
295
+ kernel.statusChanged.disconnect(onStatus);
296
+ finishTurn();
297
+ }
298
+ };
299
+ kernel.statusChanged.connect(onStatus);
300
+ return turn;
301
+ };
302
+
303
+ kernel.registerCommTarget(
304
+ TARGET_NAME,
305
+ (comm: Kernel.IComm, _message: KernelMessage.ICommOpenMsg) => {
306
+ comm.onMsg = (message: KernelMessage.ICommMsgMsg) => {
307
+ const data = message.content.data;
308
+ if (!isCodebindMessage(data)) {
309
+ return;
310
+ }
311
+ if (data.type === 'question_finished') {
312
+ const model = panelState.runningQuestions.get(data.cell_id);
313
+ panelState.runningQuestions.delete(data.cell_id);
314
+ if (model) {
315
+ const widget = panel.content.widgets.find(cell => cell.model === model);
316
+ widget?.node.classList.toggle(
317
+ QUESTION_ERROR_CLASS,
318
+ data.error !== null
319
+ );
320
+ }
321
+ refreshQuestionCells(panel);
322
+ finishTurn(false);
323
+ if (data.error) {
324
+ void showErrorMessage(
325
+ `Codebind question: ${data.error.type}`,
326
+ data.error.message
327
+ );
328
+ }
329
+ return;
330
+ }
331
+ if (data.type === 'code_cell_output') {
332
+ codeCells.get(data.cell_id)?.outputs.add(data.output);
333
+ return;
334
+ }
335
+ if (data.type === 'code_cell_clear') {
336
+ codeCells.get(data.cell_id)?.outputs.clear(data.wait);
337
+ return;
338
+ }
339
+ if (data.type === 'code_cell_finished') {
340
+ const model = codeCells.get(data.cell_id);
341
+ if (!model) {
342
+ return;
343
+ }
344
+ model.outputs.fromJSON(data.outputs);
345
+ model.executionCount = data.execution_count;
346
+ model.executionState = 'idle';
347
+ if (
348
+ turn &&
349
+ turn.parentExecutionCount === null &&
350
+ data.execution_count !== null
351
+ ) {
352
+ turn.parentExecutionCount = data.execution_count - 1;
353
+ }
354
+ return;
355
+ }
356
+
357
+ const activeTurn = beginTurn();
358
+ const model = insertCell(panel, data, activeTurn.nextIndex);
359
+ if (data.type === 'code_cell_started' && model?.type === 'code') {
360
+ const code = model as ICodeCellModel;
361
+ code.executionState = 'running';
362
+ codeCells.set(data.cell_id, code);
363
+ }
364
+ activeTurn.nextIndex += 1;
365
+ };
366
+ panelState.comm = comm;
367
+ comm.onClose = () => {
368
+ if (panelState.comm === comm) {
369
+ panelState.comm = null;
370
+ }
371
+ };
372
+ comm.send({ type: 'ready' });
373
+ }
374
+ );
375
+ }
376
+
377
+ function insertQuestion(panel: NotebookPanel): void {
378
+ const notebook = panel.content;
379
+ const model = notebook.model;
380
+ if (!model) {
381
+ return;
382
+ }
383
+ const index = notebook.activeCell ? notebook.activeCellIndex + 1 : 0;
384
+ model.sharedModel.insertCell(index, {
385
+ cell_type: 'markdown',
386
+ source: '',
387
+ metadata: {
388
+ codebind: { kind: 'question', model: 'model' }
389
+ }
390
+ });
391
+ notebook.activeCellIndex = index;
392
+ notebook.deselectAll();
393
+ const cell = notebook.widgets[index];
394
+ if (cell instanceof MarkdownCell) {
395
+ cell.rendered = false;
396
+ }
397
+ notebook.mode = 'edit';
398
+ refreshQuestionCells(panel);
399
+ cell?.editor?.focus();
400
+ }
401
+
402
+ async function runQuestion(panel: NotebookPanel): Promise<void> {
403
+ const notebook = panel.content;
404
+ const cell = notebook.activeCell;
405
+ if (!cell) {
406
+ return;
407
+ }
408
+ const metadata = questionMetadata(cell.model);
409
+ if (!metadata) {
410
+ return;
411
+ }
412
+ const state = panelStates.get(panel);
413
+ if (!state?.comm) {
414
+ await showErrorMessage(
415
+ 'Codebind is not connected',
416
+ 'Run %load_ext codebind in this kernel before sending a Question cell.'
417
+ );
418
+ return;
419
+ }
420
+ if (state.runningQuestions.size > 0) {
421
+ await showErrorMessage(
422
+ 'Codebind is busy',
423
+ 'Wait for the current question to finish before sending another.'
424
+ );
425
+ return;
426
+ }
427
+ const question = cell.model.sharedModel.getSource().trim();
428
+ if (!question) {
429
+ await showErrorMessage('Empty Codebind question', 'Write a question before sending it.');
430
+ return;
431
+ }
432
+ cell.node.classList.remove(QUESTION_ERROR_CLASS);
433
+ state.runningQuestions.set(cell.model.id, cell.model);
434
+ refreshQuestionCells(panel);
435
+ if (cell instanceof MarkdownCell) {
436
+ cell.rendered = true;
437
+ }
438
+ notebook.mode = 'command';
439
+ state.comm.send({
440
+ type: 'question',
441
+ cell_id: cell.model.id,
442
+ question,
443
+ model: metadata.model
444
+ });
445
+ }
446
+
447
+ function connectPanel(panel: NotebookPanel, app: JupyterFrontEnd): void {
448
+ panelStates.set(panel, {
449
+ comm: null,
450
+ runningQuestions: new Map<string, ICellModel>()
451
+ });
452
+ panel.toolbar.insertItem(
453
+ 10,
454
+ 'codebindQuestion',
455
+ new ToolbarButton({
456
+ label: 'Question',
457
+ tooltip: 'Insert a Codebind Question cell',
458
+ onClick: () => {
459
+ void app.commands.execute(INSERT_QUESTION);
460
+ }
461
+ })
462
+ );
463
+ panel.content.modelContentChanged.connect(() => refreshQuestionCells(panel));
464
+ void panel.context.ready.then(() => refreshQuestionCells(panel));
465
+ void panel.sessionContext.ready.then(() => registerKernel(panel));
466
+ panel.sessionContext.kernelChanged.connect(() => registerKernel(panel));
467
+ }
468
+
469
+ const plugin: JupyterFrontEndPlugin<void> = {
470
+ id: 'codebind-jupyterlab:plugin',
471
+ description: 'Insert Codebind executions as native notebook cells.',
472
+ autoStart: true,
473
+ requires: [INotebookTracker],
474
+ activate: (app: JupyterFrontEnd, tracker: INotebookTracker): void => {
475
+ ensureStyles();
476
+ app.commands.addCommand(INSERT_QUESTION, {
477
+ label: 'Insert Codebind Question',
478
+ execute: () => {
479
+ const panel = tracker.currentWidget;
480
+ if (panel) {
481
+ insertQuestion(panel);
482
+ }
483
+ }
484
+ });
485
+ app.commands.addCommand(RUN_QUESTION, {
486
+ label: 'Send Codebind Question',
487
+ isEnabled: () => {
488
+ const cell = tracker.currentWidget?.content.activeCell;
489
+ return cell ? questionMetadata(cell.model) !== null : false;
490
+ },
491
+ execute: async () => {
492
+ const panel = tracker.currentWidget;
493
+ if (panel) {
494
+ await runQuestion(panel);
495
+ }
496
+ }
497
+ });
498
+ app.commands.addKeyBinding({
499
+ command: RUN_QUESTION,
500
+ keys: ['Shift Enter'],
501
+ selector: `.jp-Notebook .${QUESTION_CLASS}`
502
+ });
503
+ app.contextMenu.addItem({
504
+ command: INSERT_QUESTION,
505
+ selector: '.jp-Notebook .jp-Cell',
506
+ rank: 8
507
+ });
508
+ tracker.forEach(panel => connectPanel(panel, app));
509
+ tracker.widgetAdded.connect((_tracker, panel) => connectPanel(panel, app));
510
+ }
511
+ };
512
+
513
+ export default plugin;
@@ -426,7 +426,7 @@ __metadata:
426
426
  languageName: node
427
427
  linkType: hard
428
428
 
429
- "@jupyterlab/apputils@npm:^4.7.3":
429
+ "@jupyterlab/apputils@npm:^4.0.0, @jupyterlab/apputils@npm:^4.7.3":
430
430
  version: 4.7.3
431
431
  resolution: "@jupyterlab/apputils@npm:4.7.3"
432
432
  dependencies:
@@ -2024,6 +2024,7 @@ __metadata:
2024
2024
  dependencies:
2025
2025
  "@jupyter/builder": ^1.2.0
2026
2026
  "@jupyterlab/application": ^4.0.0
2027
+ "@jupyterlab/apputils": ^4.0.0
2027
2028
  "@jupyterlab/cells": ^4.0.0
2028
2029
  "@jupyterlab/nbformat": ^4.0.0
2029
2030
  "@jupyterlab/notebook": ^4.0.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codebind"
3
- version = "0.4.3"
3
+ version = "0.5.0"
4
4
  description = "A frontend-neutral model loop for persistent IPython sessions."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codebind"
3
- version = "0.4.3"
3
+ version = "0.5.0"
4
4
  description = "A frontend-neutral model loop for persistent IPython sessions."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -8,6 +8,7 @@ from pathlib import Path
8
8
  from typing import Any
9
9
 
10
10
  from IPython.core.interactiveshell import InteractiveShell
11
+ from langchain_core.language_models import BaseChatModel
11
12
  from models_provider import Models
12
13
 
13
14
  from .jupyter import JupyterLabBridge
@@ -46,8 +47,18 @@ def load_ipython_extension(ipython: InteractiveShell) -> None:
46
47
  previous_chat.bridge.close()
47
48
  ipython.drop_by_id(previous)
48
49
  bridge = JupyterLabBridge.connect(ipython)
50
+ chat = Session(shell=ipython, bridge=bridge)
51
+ if bridge is not None:
52
+
53
+ async def answer_question(question: str, model_name: str) -> None:
54
+ model = ipython.user_ns.get(model_name)
55
+ if not isinstance(model, BaseChatModel):
56
+ raise NameError(f"{model_name!r} is not a chat model in the IPython namespace")
57
+ await chat.asend(question, model)
58
+
59
+ bridge.handle_questions(answer_question)
49
60
  namespace: dict[str, Any] = {
50
- "chat": Session(shell=ipython, bridge=bridge),
61
+ "chat": chat,
51
62
  "Models": Models,
52
63
  "models": models,
53
64
  }
@@ -2,6 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
6
+ from collections.abc import Awaitable, Callable
5
7
  from typing import Any
6
8
  from uuid import uuid4
7
9
 
@@ -9,6 +11,7 @@ from IPython.core.interactiveshell import InteractiveShell
9
11
 
10
12
 
11
13
  _TARGET_NAME = "codebind"
14
+ _QuestionHandler = Callable[[str, str], Awaitable[None]]
12
15
 
13
16
 
14
17
  class JupyterLabBridge:
@@ -16,6 +19,8 @@ class JupyterLabBridge:
16
19
 
17
20
  def __init__(self, comm: Any) -> None:
18
21
  self._comm = comm
22
+ self._question_handler: _QuestionHandler | None = None
23
+ self._tasks: set[asyncio.Task[None]] = set()
19
24
  self.ready = False
20
25
  comm.on_msg(self._on_message)
21
26
 
@@ -34,9 +39,16 @@ class JupyterLabBridge:
34
39
 
35
40
  def close(self) -> None:
36
41
  """Close the frontend connection."""
42
+ for task in self._tasks:
43
+ task.cancel()
44
+ self._tasks.clear()
37
45
  self._comm.close()
38
46
  self.ready = False
39
47
 
48
+ def handle_questions(self, handler: _QuestionHandler) -> None:
49
+ """Handle questions submitted by Codebind cells."""
50
+ self._question_handler = handler
51
+
40
52
  def start_code_cell(self, source: str) -> str | None:
41
53
  """Insert a running code cell before its execution begins."""
42
54
  if not self.ready:
@@ -105,5 +117,34 @@ class JupyterLabBridge:
105
117
 
106
118
  def _on_message(self, message: dict[str, Any]) -> None:
107
119
  data = message.get("content", {}).get("data", {})
108
- if isinstance(data, dict) and data.get("type") == "ready":
120
+ if not isinstance(data, dict):
121
+ return
122
+ if data.get("type") == "ready":
109
123
  self.ready = True
124
+ return
125
+ if data.get("type") != "question":
126
+ return
127
+ cell_id = data.get("cell_id")
128
+ question = data.get("question")
129
+ model = data.get("model", "model")
130
+ if not all(isinstance(value, str) for value in (cell_id, question, model)):
131
+ return
132
+ task = asyncio.create_task(self._answer_question(cell_id, question, model))
133
+ self._tasks.add(task)
134
+ task.add_done_callback(self._tasks.discard)
135
+
136
+ async def _answer_question(self, cell_id: str, question: str, model: str) -> None:
137
+ error: dict[str, str] | None = None
138
+ try:
139
+ if self._question_handler is None:
140
+ raise RuntimeError("Codebind is not ready to receive questions.")
141
+ await self._question_handler(question, model)
142
+ except Exception as exception:
143
+ error = {"type": type(exception).__name__, "message": str(exception)}
144
+ self._comm.send(
145
+ {
146
+ "type": "question_finished",
147
+ "cell_id": cell_id,
148
+ "error": error,
149
+ }
150
+ )
@@ -1 +0,0 @@
1
- "use strict";(self.rspackChunkcodebind_jupyterlab=self.rspackChunkcodebind_jupyterlab||[]).push([[590],{509(e,t,n){n.r(t);var o=n(171);function l(e){let t=e.sessionContext.session?.kernel;if(!t)return;let n=null,l=new Map;t.registerCommTarget("codebind",(u,c)=>{u.onMsg=u=>{var c;let d,i,r=u.content.data;if(!("object"==typeof r&&null!==r&&("markdown_cell"===r.type?"string"==typeof r.source:"code_cell_started"===r.type?"string"==typeof r.cell_id&&"string"==typeof r.source:"code_cell_output"===r.type?"string"==typeof r.cell_id&&"object"==typeof r.output&&null!==r.output:"code_cell_clear"===r.type?"string"==typeof r.cell_id&&"boolean"==typeof r.wait:"code_cell_finished"===r.type&&"string"==typeof r.cell_id&&("number"==typeof r.execution_count||null===r.execution_count)&&Array.isArray(r.outputs))))return;if("code_cell_output"===r.type)return void l.get(r.cell_id)?.outputs.add(r.output);if("code_cell_clear"===r.type)return void l.get(r.cell_id)?.outputs.clear(r.wait);if("code_cell_finished"===r.type){let e=l.get(r.cell_id);if(!e)return;e.outputs.fromJSON(r.outputs),e.executionCount=r.execution_count,e.executionState="idle",n&&null===n.parentExecutionCount&&null!==r.execution_count&&(n.parentExecutionCount=r.execution_count-1);return}let s=(()=>{if(n)return n;let o=e.content,l=o.widgets.findIndex(e=>"code"===e.model.type&&"running"===e.model.executionState);n={parentModel:l>=0?o.widgets[l].model:null,parentExecutionCount:null,resumeModel:o.activeCell?.model??null,nextIndex:l>=0?l+1:o.activeCell?o.activeCellIndex+1:0};let u=(o,l)=>{"idle"===l&&(t.statusChanged.disconnect(u),(()=>{if(!n)return;let t=e.content,o=n;if(n=null,o.parentModel&&null!==o.parentExecutionCount&&(o.parentModel.executionCount=o.parentExecutionCount),o.resumeModel){let e=t.widgets.findIndex(e=>e.model===o.resumeModel);e>=0&&(t.activeCellIndex=e)}})())};return t.statusChanged.connect(u),n})(),a=(c=s.nextIndex,(i=(d=e.content).model)?("code_cell_started"===r.type?i.sharedModel.insertCell(c,{cell_type:"code",source:r.source,metadata:{trusted:!0},execution_count:null,outputs:[]}):i.sharedModel.insertCell(c,{cell_type:"markdown",source:r.source,metadata:{}}),d.activeCellIndex=c,d.deselectAll(),"markdown_cell"===r.type&&o.NotebookActions.run(d),d.scrollToItem(c),d.widgets[c]?.model??null):null);"code_cell_started"===r.type&&a?.type==="code"&&(a.executionState="running",l.set(r.cell_id,a)),s.nextIndex+=1},u.send({type:"ready"})})}function u(e){e.sessionContext.ready.then(()=>l(e)),e.sessionContext.kernelChanged.connect(()=>l(e))}let c={id:"codebind-jupyterlab:plugin",description:"Insert Codebind executions as native notebook cells.",autoStart:!0,requires:[o.INotebookTracker],activate:(e,t)=>{t.forEach(u),t.widgetAdded.connect((e,t)=>u(t))}};n.d(t,{},{default:c})}}]);
@@ -1 +0,0 @@
1
- var _JUPYTERLAB;(()=>{"use strict";var e,n,r,t,o,i,u,a,c,l,f,s,p,d,h,v,g,m,y,b,S,j,k,w,E,x,T,P,M,A,C,O,D,_,L,N,$,q={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})}},z={};function I(e){var n=z[e];if(void 0!==n)return n.exports;var r=z[e]={exports:{}};return q[e](r,r.exports,I),r.exports}I.m=q,I.c=z,I.n=e=>{var n=e&&e.__esModule?()=>e.default:()=>e;return I.d(n,{a:n}),n},I.d=(e,n,r)=>{var t=(n,r)=>{for(var t in n)I.o(n,t)&&!I.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,[r]:n[t]})};t(n,"get"),t(r,"value")},I.f={},I.e=e=>Promise.all(Object.keys(I.f).reduce((n,r)=>(I.f[r](e,n),n),[])),I.u=e=>""+e+".6544266cd73a003b.js?v=6544266cd73a003b",I.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),I.o=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),R={},I.l=function(e,n,r,t){if(R[e])return void R[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,I.nc&&o.setAttribute("nonce",I.nc),o.setAttribute("data-rspack","codebind-jupyterlab:"+r),o.src=e),R[e]=[n];var l=function(n,r){o.onerror=o.onload=null,clearTimeout(f);var t=R[e];if(delete R[e],o.parentNode&&o.parentNode.removeChild(o),t&&t.forEach(function(e){return e(r)}),n)return n(r)},f=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)},I.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},I.S={},I.initializeSharingData={scopeToSharingDataMapping:{default:[{name:"codebind-jupyterlab",version:"0.4.1",factory:()=>I.e(590).then(()=>()=>I(509)),eager:0,treeShakingMode:null}]},uniqueName:"codebind-jupyterlab"},U={},B={},I.I=function(e,n){n||(n=[]);var r=B[e];if(r||(r=B[e]={}),!(n.indexOf(r)>=0)){if(n.push(r),U[e])return U[e];I.o(I.S,e)||(I.S[e]={});var t=I.S[e],o=function(e){"u">typeof console&&console.warn&&console.warn(e)},i=I.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=I(r);if(!i)return;var u=function(r){return r&&r.init&&r.init(I.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=I.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)?U[e]=Promise.all(c).then(function(){return U[e]=1}):U[e]=1}},I.g.importScripts&&(V=I.g.location+"");var R,U,B,V,J=I.g.document;if(!V&&J&&(J.currentScript&&"SCRIPT"===J.currentScript.tagName.toUpperCase()&&(V=J.currentScript.src),!V)){var Y=J.getElementsByTagName("script");if(Y.length)for(var K=Y.length-1;K>-1&&(!V||!/^http(s?):/.test(V));)V=Y[K--].src}if(!V)throw Error("Automatic publicPath is not supported in this browser");I.p=V=V.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),I.consumesLoadingData={chunkMapping:{590:["171"]},moduleIdToConsumeDataMapping:{171:{shareScope:"default",shareKey:"@jupyterlab/notebook",import:null,requiredVersion:"^4.6.3",strictVersion:!1,singleton:!0,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]),f=r(n[1]);return[,t(f),o(f),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,f,s=a<e.length?(typeof e[a])[0]:"";if(u>=n.length||"o"==(f=(typeof(l=n[u]))[0])){if(!c)return!0;if("u"==s)return a>t&&!o;return""==s!=o}if("u"==f){if(!c||"u"!=s)return!1}else if(c)if(s==f)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"!=s&&"n"!=s){if(o||a<=t)return!1;c=!1,a--}else{if(a<=t||f<s!=o)return!1;c=!1}else"s"!=s&&"n"!=s&&(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=I.S[e];if(!r||!I.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)+")"},f=function(e,n,r,t){var o=c(e,r);return y(e[r][o])},s=function(e,n,r,t){var o=c(e,r);return i(t,o)||g(l(e,r,o,t)),y(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 y(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(", ")},v=function(e,n,r,t){var o=d(e,r,t);if(o)return y(o);throw Error(h(e,n,r,t))},g=function(e){"u">typeof console&&console.warn&&console.warn(e)},m=function(e,n,r,t){g(h(e,n,r,t))},y=function(e){return e.loaded=1,e.get()},S=(b=function(e){return function(n,r,t,o){var i=I.I(n);return i&&i.then?i.then(e.bind(e,n,I.S[n],r,t,o)):e(n,I.S[n],r,t,o)}})(function(e,n,r){return u(e,r),y(a(n,r))}),j=b(function(e,n,r,t){return n&&I.o(n,r)?y(a(n,r)):t()}),k=b(function(e,n,r,t){return u(e,r),y(d(n,r,t)||m(n,e,r,t)||a(n,r))}),w=b(function(e,n,r){return u(e,r),f(n,e,r)}),E=b(function(e,n,r,t){return u(e,r),s(n,e,r,t)}),x=b(function(e,n,r,t){return u(e,r),v(n,e,r,t)}),T=b(function(e,n,r,t){return u(e,r),p(n,e,r,t)}),P=b(function(e,n,r,t,o){return n&&I.o(n,r)?y(d(n,r,t)||m(n,e,r,t)||a(n,r)):o()}),M=b(function(e,n,r,t){return n&&I.o(n,r)?f(n,e,r):t()}),A=b(function(e,n,r,t,o){return n&&I.o(n,r)?s(n,e,r,t):o()}),C=b(function(e,n,r,t,o){var i=n&&I.o(n,r)&&d(n,r,t);return i?y(i):o()}),O=b(function(e,n,r,t,o){return n&&I.o(n,r)?p(n,e,r,t):o()}),D=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 O.apply(null,u)}:r&&o&&i?function(){return C.apply(null,u)}:t&&o&&i?function(){return A.apply(null,u)}:r&&t&&o?function(){return T.apply(null,u)}:t&&i?function(){return M.apply(null,u)}:o&&i?function(){return P.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 k.apply(null,u)}:i?function(){return j.apply(null,u)}:function(){return S.apply(null,u)}},_={},I.f.consumes=function(e,n){var r=I.consumesLoadingData.moduleIdToConsumeDataMapping,t=I.consumesLoadingData.chunkMapping;I.o(t,e)&&t[e].forEach(function(e){if(I.o(_,e))return n.push(_[e]);var t=function(n){_[e]=0,I.m[e]=function(r){delete I.c[e],r.exports=n()}},o=function(n){delete _[e],I.m[e]=function(r){throw delete I.c[e],n}};try{var i=D(r[e])();i.then?n.push(_[e]=i.then(t).catch(o)):t(i)}catch(e){o(e)}})},L={871:0},I.f.j=function(e,n){var r=I.o(L,e)?L[e]:void 0;if(0!==r)if(r)n.push(r[2]);else{var t=new Promise((n,t)=>r=L[e]=[n,t]);n.push(r[2]=t);var o=I.p+I.u(e),i=Error();I.l(o,function(n){if(I.o(L,e)&&(0!==(r=L[e])&&(L[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)}},N=(e,n)=>{var r,t,[o,i,u]=n,a=0;if(o.some(e=>0!==L[e])){for(r in i)I.o(i,r)&&(I.m[r]=i[r]);u&&u(I)}for(e&&e(n);a<o.length;a++)t=o[a],I.o(L,t)&&L[t]&&L[t][0](),L[t]=0},($=self.rspackChunkcodebind_jupyterlab=self.rspackChunkcodebind_jupyterlab||[]).forEach(N.bind(null,0)),$.push=N.bind(null,$.push.bind($));var F=I(457);(_JUPYTERLAB=void 0===_JUPYTERLAB?{}:_JUPYTERLAB)["codebind-jupyterlab"]=F})();
@@ -1,265 +0,0 @@
1
- import {
2
- JupyterFrontEnd,
3
- JupyterFrontEndPlugin
4
- } from '@jupyterlab/application';
5
- import { ICellModel, ICodeCellModel } from '@jupyterlab/cells';
6
- import * as nbformat from '@jupyterlab/nbformat';
7
- import {
8
- INotebookTracker,
9
- NotebookActions,
10
- NotebookPanel
11
- } from '@jupyterlab/notebook';
12
- import { Kernel, KernelMessage } from '@jupyterlab/services';
13
-
14
- const TARGET_NAME = 'codebind';
15
-
16
- interface CodeCellStartedMessage {
17
- type: 'code_cell_started';
18
- cell_id: string;
19
- source: string;
20
- }
21
-
22
- interface CodeCellFinishedMessage {
23
- type: 'code_cell_finished';
24
- cell_id: string;
25
- execution_count: number | null;
26
- outputs: nbformat.IOutput[];
27
- }
28
-
29
- interface CodeCellOutputMessage {
30
- type: 'code_cell_output';
31
- cell_id: string;
32
- output: nbformat.IOutput;
33
- }
34
-
35
- interface CodeCellClearMessage {
36
- type: 'code_cell_clear';
37
- cell_id: string;
38
- wait: boolean;
39
- }
40
-
41
- interface MarkdownCellMessage {
42
- type: 'markdown_cell';
43
- source: string;
44
- }
45
-
46
- type CodebindMessage =
47
- | CodeCellStartedMessage
48
- | CodeCellFinishedMessage
49
- | CodeCellOutputMessage
50
- | CodeCellClearMessage
51
- | MarkdownCellMessage;
52
- type InsertMessage = CodeCellStartedMessage | MarkdownCellMessage;
53
-
54
- interface TurnState {
55
- parentModel: ICodeCellModel | null;
56
- parentExecutionCount: number | null;
57
- resumeModel: ICellModel | null;
58
- nextIndex: number;
59
- }
60
-
61
- function isCodebindMessage(value: unknown): value is CodebindMessage {
62
- if (typeof value !== 'object' || value === null) {
63
- return false;
64
- }
65
- const message = value as Record<string, unknown>;
66
- if (message.type === 'markdown_cell') {
67
- return typeof message.source === 'string';
68
- }
69
- if (message.type === 'code_cell_started') {
70
- return (
71
- typeof message.cell_id === 'string' &&
72
- typeof message.source === 'string'
73
- );
74
- }
75
- if (message.type === 'code_cell_output') {
76
- return (
77
- typeof message.cell_id === 'string' &&
78
- typeof message.output === 'object' &&
79
- message.output !== null
80
- );
81
- }
82
- if (message.type === 'code_cell_clear') {
83
- return typeof message.cell_id === 'string' && typeof message.wait === 'boolean';
84
- }
85
- return (
86
- message.type === 'code_cell_finished' &&
87
- typeof message.cell_id === 'string' &&
88
- (typeof message.execution_count === 'number' ||
89
- message.execution_count === null) &&
90
- Array.isArray(message.outputs)
91
- );
92
- }
93
-
94
- function insertCell(
95
- panel: NotebookPanel,
96
- message: InsertMessage,
97
- index: number
98
- ): ICellModel | null {
99
- const notebook = panel.content;
100
- const model = notebook.model;
101
- if (!model) {
102
- return null;
103
- }
104
-
105
- if (message.type === 'code_cell_started') {
106
- model.sharedModel.insertCell(index, {
107
- cell_type: 'code',
108
- source: message.source,
109
- metadata: { trusted: true },
110
- execution_count: null,
111
- outputs: []
112
- });
113
- } else {
114
- model.sharedModel.insertCell(index, {
115
- cell_type: 'markdown',
116
- source: message.source,
117
- metadata: {}
118
- });
119
- }
120
-
121
- notebook.activeCellIndex = index;
122
- notebook.deselectAll();
123
- if (message.type === 'markdown_cell') {
124
- void NotebookActions.run(notebook);
125
- }
126
- void notebook.scrollToItem(index);
127
- return notebook.widgets[index]?.model ?? null;
128
- }
129
-
130
- function registerKernel(panel: NotebookPanel): void {
131
- const kernel = panel.sessionContext.session?.kernel;
132
- if (!kernel) {
133
- return;
134
- }
135
-
136
- let turn: TurnState | null = null;
137
- const codeCells = new Map<string, ICodeCellModel>();
138
-
139
- const finishTurn = (): void => {
140
- if (!turn) {
141
- return;
142
- }
143
- const notebook = panel.content;
144
- const completed = turn;
145
- turn = null;
146
- if (
147
- completed.parentModel &&
148
- completed.parentExecutionCount !== null
149
- ) {
150
- completed.parentModel.executionCount = completed.parentExecutionCount;
151
- }
152
- if (completed.resumeModel) {
153
- const index = notebook.widgets.findIndex(
154
- widget => widget.model === completed.resumeModel
155
- );
156
- if (index >= 0) {
157
- notebook.activeCellIndex = index;
158
- }
159
- }
160
- };
161
-
162
- const beginTurn = (): TurnState => {
163
- if (turn) {
164
- return turn;
165
- }
166
- const notebook = panel.content;
167
- const parentIndex = notebook.widgets.findIndex(
168
- widget =>
169
- widget.model.type === 'code' &&
170
- (widget.model as ICodeCellModel).executionState === 'running'
171
- );
172
- const parentModel =
173
- parentIndex >= 0
174
- ? (notebook.widgets[parentIndex].model as ICodeCellModel)
175
- : null;
176
- turn = {
177
- parentModel,
178
- parentExecutionCount: null,
179
- resumeModel: notebook.activeCell?.model ?? null,
180
- nextIndex:
181
- parentIndex >= 0
182
- ? parentIndex + 1
183
- : notebook.activeCell
184
- ? notebook.activeCellIndex + 1
185
- : 0
186
- };
187
-
188
- const onStatus = (
189
- _sender: Kernel.IKernelConnection,
190
- status: Kernel.Status
191
- ): void => {
192
- if (status === 'idle') {
193
- kernel.statusChanged.disconnect(onStatus);
194
- finishTurn();
195
- }
196
- };
197
- kernel.statusChanged.connect(onStatus);
198
- return turn;
199
- };
200
-
201
- kernel.registerCommTarget(
202
- TARGET_NAME,
203
- (comm: Kernel.IComm, _message: KernelMessage.ICommOpenMsg) => {
204
- comm.onMsg = (message: KernelMessage.ICommMsgMsg) => {
205
- const data = message.content.data;
206
- if (!isCodebindMessage(data)) {
207
- return;
208
- }
209
- if (data.type === 'code_cell_output') {
210
- codeCells.get(data.cell_id)?.outputs.add(data.output);
211
- return;
212
- }
213
- if (data.type === 'code_cell_clear') {
214
- codeCells.get(data.cell_id)?.outputs.clear(data.wait);
215
- return;
216
- }
217
- if (data.type === 'code_cell_finished') {
218
- const model = codeCells.get(data.cell_id);
219
- if (!model) {
220
- return;
221
- }
222
- model.outputs.fromJSON(data.outputs);
223
- model.executionCount = data.execution_count;
224
- model.executionState = 'idle';
225
- if (
226
- turn &&
227
- turn.parentExecutionCount === null &&
228
- data.execution_count !== null
229
- ) {
230
- turn.parentExecutionCount = data.execution_count - 1;
231
- }
232
- return;
233
- }
234
-
235
- const activeTurn = beginTurn();
236
- const model = insertCell(panel, data, activeTurn.nextIndex);
237
- if (data.type === 'code_cell_started' && model?.type === 'code') {
238
- const code = model as ICodeCellModel;
239
- code.executionState = 'running';
240
- codeCells.set(data.cell_id, code);
241
- }
242
- activeTurn.nextIndex += 1;
243
- };
244
- comm.send({ type: 'ready' });
245
- }
246
- );
247
- }
248
-
249
- function connectPanel(panel: NotebookPanel): void {
250
- void panel.sessionContext.ready.then(() => registerKernel(panel));
251
- panel.sessionContext.kernelChanged.connect(() => registerKernel(panel));
252
- }
253
-
254
- const plugin: JupyterFrontEndPlugin<void> = {
255
- id: 'codebind-jupyterlab:plugin',
256
- description: 'Insert Codebind executions as native notebook cells.',
257
- autoStart: true,
258
- requires: [INotebookTracker],
259
- activate: (_app: JupyterFrontEnd, tracker: INotebookTracker): void => {
260
- tracker.forEach(connectPanel);
261
- tracker.widgetAdded.connect((_tracker, panel) => connectPanel(panel));
262
- }
263
- };
264
-
265
- export default plugin;
File without changes
File without changes
File without changes