feat(foreign): raw stdin, per-cell inputs and interrupt

Persistent Python/Node kernels receive raw program stdin per eval; foreign.session accepts an inputs table and view exposes per-cell stdin. Add session interrupt host API and view control.
This commit is contained in:
cflmy committed 2026-10-18 14:37:45 +08:00
1 parent c85f1a2829
commit 064522a338
9 files changed
+86 -2

No files matched your search

+2
View File
@@ -4,6 +4,8 @@
### Added
- **外联 v3 P0**:session eval 支持 raw stdin(Python/Node 持久内核);`foreign.session inputs=` 支持每 cell 独立 stdin;view 增加每卡 stdin 字段与 Interrupt;静态导出使用 inputs 表。
### Fixed
### Changed
+8
View File
@@ -225,6 +225,14 @@ Kill and remove a session; returns whether it existed.
*> host_foreign_session_close id=`id`*
## session_interrupt
+ `id`
Interrupt the current evaluation of a persistent kernel. The session remains
usable for the next evaluation when the worker supports interruption.
*> host_foreign_session_interrupt id=`id`*
## session_list
List live sessions with id/lang/cmd/evals/alive/started_ms.
+7
View File
@@ -205,6 +205,13 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
*> host_foreign_session_get id=`标识` name=`名称`*
## 会话中断
+ `标识`
中断持久内核当前求值;worker 支持时,会话仍可用于下一次求值。
*> host_foreign_session_interrupt id=`标识`*
## 会话变量
+ `标识`
+17 -1
View File
@@ -217,6 +217,7 @@ pub enum HostFn {
ForeignSessionNames = 208,
ForeignSessionClose = 209,
ForeignSessionList = 210,
ForeignSessionInterrupt = 211,
}
@@ -424,6 +425,7 @@ impl HostFn {
208 => Self::ForeignSessionNames,
209 => Self::ForeignSessionClose,
210 => Self::ForeignSessionList,
211 => Self::ForeignSessionInterrupt,
_ => return None,
})
}
@@ -515,6 +517,7 @@ impl HostFn {
"host_foreign_session_names" | "foreign_session_names" => Self::ForeignSessionNames,
"host_foreign_session_close" | "foreign_session_close" => Self::ForeignSessionClose,
"host_foreign_session_list" | "foreign_session_list" => Self::ForeignSessionList,
"host_foreign_session_interrupt" | "foreign_session_interrupt" => Self::ForeignSessionInterrupt,
"host_foreign_langs" => Self::ForeignLangs,
"host_dotenv_load" | "load_dotenv" => Self::DotenvLoad,
"host_http_request" | "http_request" => Self::HttpRequest,
@@ -726,6 +729,7 @@ impl HostFn {
Self::ForeignSessionNames => "host_foreign_session_names",
Self::ForeignSessionClose => "host_foreign_session_close",
Self::ForeignSessionList => "host_foreign_session_list",
Self::ForeignSessionInterrupt => "host_foreign_session_interrupt",
Self::ForeignLangs => "host_foreign_langs",
Self::DotenvLoad => "host_dotenv_load",
Self::HttpRequest => "host_http_request",
@@ -903,7 +907,8 @@ impl HostFn {
Self::ForeignSessionGet => &["id", "name"],
Self::ForeignSessionNames => &["id"],
Self::ForeignSessionClose => &["id"],
Self::ForeignSessionList => &[],
Self::ForeignSessionList => &["id"],
Self::ForeignSessionInterrupt => &["id"],
Self::ForeignLangs => &[],
Self::PluginLoad => &["path"],
Self::PluginUnload | Self::PluginList => &[],
@@ -1581,6 +1586,17 @@ pub fn call_host(
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionInterrupt => {
#[cfg(feature = "exec-host")]
{
crate::host::foreign_session::interrupt(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionList => {
#[cfg(feature = "exec-host")]
{
+14
View File
@@ -807,6 +807,20 @@ impl DocumentSession {
]))
}
pub fn interrupt(&mut self) -> Result<Value, String> {
let ids: Vec<String> = self.kernel_sessions.keys().cloned().collect();
let mut out = Vec::new();
for name in ids {
if let Some(id) = self.kernel_sessions.get(&name) {
match foreign_session::interrupt(&mut self.host, &Value::Text(id.clone())) {
Ok(_) => out.push(Value::Text(name)),
Err(e) => out.push(Value::Text(format!("{name}: {e}"))),
}
}
}
Ok(Value::List(out))
}
pub fn restart_kernel(&mut self, name: &str) -> Result<Value, String> {
if let Some(id) = self.kernel_sessions.remove(name) {
let _ = foreign_session::close(&mut self.host, &Value::Text(id));
+22
View File
@@ -652,6 +652,28 @@ fn kill_session(ctx: &mut HostContext, id: &str) {
}
}
/// Interrupt the current evaluation without destroying the kernel. Python
/// reports KeyboardInterrupt through the normal result frame.
pub fn interrupt(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
let id = as_text(id, "id")?.to_string();
let session = ctx
.foreign_sessions
.get_mut(&id)
.ok_or_else(|| format!("foreign session `{id}` not found"))?;
#[cfg(unix)]
unsafe {
libc::kill(-(session.child.id() as i32), libc::SIGINT);
}
#[cfg(windows)]
{
let _ = Command::new("taskkill")
.args(["/PID", &session.child.id().to_string(), "/T", "/F"])
.output();
session.alive = false;
}
Ok(Value::Bool(true))
}
pub fn set(
ctx: &mut HostContext,
id: &Value,
+7 -1
View File
@@ -3552,6 +3552,7 @@ body.notebook-page .wb-source-text { color: var(--nb-text); }
<button type="button" id="nb-run-all">Run All</button>
<button type="button" id="nb-restart">Restart &amp; Run All</button>
<button type="button" id="nb-step">Step</button>
<button type="button" id="nb-interrupt">Interrupt</button>
<button type="button" id="nb-state">State</button>
<button type="button" id="nb-journal">Journal</button>
<button type="button" id="nb-clear">Clear outputs</button>
@@ -3884,7 +3885,7 @@ body.notebook-page .wb-source-text { color: var(--nb-text); }
function staticNotice() {
status("静态页面无法真实执行 / static export: no live execution");
}
["nb-run-all", "nb-restart", "nb-step", "nb-state", "nb-journal",
["nb-run-all", "nb-restart", "nb-step", "nb-interrupt", "nb-state", "nb-journal",
"nb-clear", "nb-reload", "nb-debug", "exec-clear"].forEach(function (id) {
bind(id, staticNotice);
});
@@ -3908,6 +3909,11 @@ body.notebook-page .wb-source-text { color: var(--nb-text); }
document.querySelectorAll(".code-card").forEach(bindClean);
bind("nb-run-all", function () { runAll(false); });
bind("nb-restart", function () { runAll(true); });
bind("nb-interrupt", function () {
post("api/session/interrupt", {}).then(function (r) {
status(r.ok ? "interrupt sent" : (r.error || "interrupt failed"));
});
});
bind("nb-step", function () {
if (!state.persistent && Object.keys(state.cells).length === 0) {
status("no cells; Run All runs the document");
+5
View File
@@ -194,6 +194,11 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
notebook_api::api_run_document(&root.root, body)
})
}
"/api/session/interrupt" => {
return api_debug_post(request, |body| {
notebook_api::api_interrupt(&root.root, body)
})
}
"/api/session/cell/clear" => {
return api_debug_post(request, |body| {
notebook_api::api_clear_cell(&root.root, body)
+4
View File
@@ -170,6 +170,10 @@ where
}
}
pub fn api_interrupt(root: &Path, body: &str) -> serde_json::Value {
with_session(root, body, "interrupted", |s| s.interrupt())
}
pub fn api_clear_cell(root: &Path, body: &str) -> serde_json::Value {
let v = body_value(body);
let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or("");