Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/aipoch/open-science/llms.txt

Use this file to discover all available pages before exploring further.

window.api.notebook provides full programmatic control over the Python kernel that Open Science manages for each session. The kernel persists across agent turns — variables, imports, and loaded data remain available throughout a conversation. All notebook commands are routed through typed IPC so renderer code never communicates with the local RPC server directly.

Session routing

Every notebook command requires a NotebookSessionRequest as its base, which provides the routing fields the main process uses to locate the correct kernel session:
FieldTypeRequiredDescription
sessionIdstringACP session ID that owns this notebook
workspaceCwdstringAbsolute path of the session working directory
projectNamestringProject scope; defaults to the runtime default when omitted

Methods

state(request)

Returns a snapshot of the current notebook session including kernel status, all cells, active write locks, and the full run history.
request
NotebookSessionRequest
required
Session routing fields (sessionId, workspaceCwd, projectName?).
Returns: Promise<NotebookSessionState>

beginCodeCell(request)

Starts a streamed code write into a notebook cell. Acquires an exclusive write lock — subsequent appendCodeCell and finishCodeCell calls must reference the returned writeId.
request
BeginNotebookCodeCellRequest
required
Extends NotebookSessionRequest with:
Returns: Promise<{ sessionId: string; cellId: string; writeId: string; status: string }>
sessionId
string
required
The resolved session ID.
cellId
string
required
ID of the cell that was opened for writing.
writeId
string
required
Exclusive write lock token. Pass this to every subsequent append and finish call.
status
string
required
Initial cell status (typically 'receiving-code').

appendCodeCell(request)

Appends a text delta to the cell currently held by the given write lock. Call repeatedly to stream code content incrementally.
request
AppendNotebookCodeCellRequest
required
Extends NotebookSessionRequest with:
Returns: Promise<{ sessionId: string; cellId: string; writeId: string; receivedBytes: number }>
receivedBytes
number
required
Total bytes received for this cell so far (useful for progress display).

finishCodeCell(request)

Releases the write lock after all code chunks have been appended. The cell transitions from 'receiving-code' to 'idle' and becomes ready for execution.
request
FinishNotebookCodeCellRequest
required
Extends NotebookSessionRequest with:
Returns: Promise<{ sessionId: string; cellId: string; code: string; status: string }>
code
string
required
The complete assembled code of the cell after all deltas were applied.
status
string
required
Final cell status after the lock is released.

runCell(request)

Executes an existing cell by ID in the shared Python interpreter. The cell must exist and must not currently hold a write lock.
request
RunNotebookCellRequest
required
Extends NotebookSessionRequest with:
Returns: Promise<NotebookRunSummary>

execute(request)

Convenience method that writes a temporary cell with the provided code and immediately executes it. Use this when you don’t need a persistent cell — for example, to run a single expression or a quick setup block.
request
ExecuteNotebookCodeRequest
required
Extends NotebookSessionRequest with:
Returns: Promise<NotebookRunSummary>

restart(request)

Restarts the Python kernel for the session, clearing all in-memory variables and module state. Previously written cells are preserved; only the runtime state is reset.
request
NotebookSessionRequest
required
Session routing fields.
Returns: Promise<NotebookSessionState> — the updated session state with kernelStatus: 'starting'.

shutdown(request)

Shuts down the Python kernel for the session. The kernel will be restarted automatically on the next operation that requires it.
request
NotebookSessionRequest
required
Session routing fields.
Returns: Promise<{ sessionId: string; status: 'shutdown' }>

Event listeners

onAvailable(listener)

Fired when a new notebook session becomes available (kernel started and ready). Subscribe to this to know when the notebook tab can be shown for a session.
listener
(event: NotebookAvailableEvent) => void
required
Receives a NotebookSessionReference with session routing fields.
Returns: () => void — unsubscribe function.

onChanged(listener)

Fired when the notebook session state changes (cell added, run completed, kernel status changed, etc.). Use this to refresh the notebook view without polling.
listener
(event: NotebookChangedEvent) => void
required
Receives a NotebookSessionReference with session routing fields.
Returns: () => void — unsubscribe function.

Type reference

NotebookSessionState

The full renderer-facing snapshot of one shared notebook interpreter session.
id
string
required
Internal session record ID.
sessionId
string
required
ACP session ID that owns this notebook.
artifactSessionId
string
Artifact session scope when set by the agent.
cwd
string
required
Current working directory of the kernel process.
notebookSessionRoot
string
required
Root directory for this notebook session’s persistent files.
dataRoot
string
required
Root directory for session data files.
runtimeRoot
string
required
Root directory for the Python runtime environment.
pythonPath
string
Absolute path to the Python executable.
kernelStatus
string
required
Current kernel status: 'idle' | 'starting' | 'running' | 'error' | 'shutdown'
runJsonPath
string
required
Path to the run.json file that persists run history.
cells
NotebookCell[]
required
All notebook cells in creation order.
activeWrite
NotebookWriteLock
The currently held write lock, if any.
activeRunId
string
ID of the currently executing run, if any.
runs
NotebookRunRecord[]
required
Full run history for this session.
recentRuns
NotebookRunRecord[]
required
A bounded subset of recent runs for fast UI rendering.

NotebookRunSummary

Extends NotebookRunRecord with workspace root paths so the agent can decide what to do next.
runId
string
required
Unique run identifier.
cellId
string
required
Cell that was executed.
script
string
required
The Python code that was executed.
status
NotebookRunStatus
required
Final execution status.
startedAt
number
required
Start time (epoch milliseconds).
endedAt
number
End time (epoch milliseconds).
executionCount
number
Kernel execution counter.
text
NotebookTextOutput
required
Structured stdout, stderr, traceback, and plain-text projection.
outputs
NotebookOutput[]
required
Rich output items (stream, error, text, JSON).
artifacts
ArtifactFile[]
required
Files generated during this run.
notebookSessionRoot
string
required
Notebook session root (from NotebookRunSummary extension).
dataRoot
string
required
Data root.
runtimeRoot
string
required
Python runtime root.
kernelName
string
required
Kernel display name.

NotebookRunStatus values

ValueDescription
'queued'Execution is scheduled but has not started
'running'Kernel is currently executing the cell
'completed'Execution finished successfully
'failed'Execution raised an unhandled exception
'timeout'Execution exceeded timeoutMs
'interrupted'Execution was cancelled by a kernel restart or explicit interrupt

NotebookRunInputKind values

ValueDescription
'cell'Code originated from a notebook cell (default)
'terminal'Code submitted from the user terminal panel

Usage example

import type {
  NotebookSessionState,
  NotebookRunSummary
} from '../../../../shared/notebook'

async function runAnalysis(sessionId: string, workspaceCwd: string) {
  const sessionRequest = { sessionId, workspaceCwd }

  // Subscribe to change events before querying state
  const unsubChanged = window.api.notebook.onChanged((event) => {
    console.log('Notebook changed for session:', event.sessionId)
  })

  // Query current state
  const state: NotebookSessionState = await window.api.notebook.state(sessionRequest)
  console.log('Kernel status:', state.kernelStatus)
  console.log('Existing cells:', state.cells.length)

  // Execute code directly (no persistent cell needed)
  const result: NotebookRunSummary = await window.api.notebook.execute({
    ...sessionRequest,
    code: `
import pandas as pd
df = pd.read_csv('data.csv')
print(df.describe())
    `,
    timeoutMs: 30_000
  })

  console.log('Status:', result.status)
  console.log('Output:', result.text.plain.join('\n'))

  if (result.status === 'failed') {
    console.error('Traceback:', result.text.traceback)
  }

  if (result.artifacts.length > 0) {
    console.log('Generated files:', result.artifacts.map((a) => a.name))
  }

  // Stream a multi-chunk cell write
  const { writeId, cellId } = await window.api.notebook.beginCodeCell(sessionRequest)

  await window.api.notebook.appendCodeCell({
    ...sessionRequest,
    writeId,
    cellId,
    delta: 'import matplotlib.pyplot as plt\n'
  })
  await window.api.notebook.appendCodeCell({
    ...sessionRequest,
    writeId,
    cellId,
    delta: 'plt.plot([1, 2, 3])\nplt.savefig("plot.png")\n'
  })
  await window.api.notebook.finishCodeCell({ ...sessionRequest, writeId, cellId })

  // Run the assembled cell
  const plotResult: NotebookRunSummary = await window.api.notebook.runCell({
    ...sessionRequest,
    cellId
  })
  console.log('Plot run status:', plotResult.status)

  return () => unsubChanged()
}

Build docs developers (and LLMs) love