lib/foreign — foreign kernels v2ok
文档
怎样读这份可执行文档
正文说明意图,标记指出哪些片段会执行。遮蔽只在正文显示动作说明,实际逻辑放在侧注;阅读、展开与定位都不会运行代码。
| 标记 | 阅读含义 |
|---|---|
无标记文字 | 作者的解释,按普通 Markdown 阅读。 |
空行 | 分隔叙述与结构,不是计算步骤。 |
# / ## | 一级标题声明对象或入口,更深标题声明函数;说明按钮可查看输入、返回与依据。 |
> | 调用函数;实际执行结果另有标注。 |
1. 递增 | 按条件选择分支,不是普通编号说明。 |
- | 重复或遍历结构;迭代选择器只切换已有运行记录。 |
+ `名` | 兼容的显式形参;新库优先在叙述中声明参数,标题下的表格解释契约。 |
GFM 表 | 未绑定的契约表是说明;绑定表按列、行和 @ 形态构成数据。 |
```lang | 代码块;绑定的外语代码与普通示例区分展示,数学公式另有公式卡片。 |
--- / *** | 分隔内容,不能把分隔线当作函数返回。 |
<!-- marqdo-out --> | 程序写回的结果,区别于作者原始正文。 |
`名` | 叙述中的参数或变量;默认值跟在名称之后。 |
**…** | 执行语句:赋值、调用或计算;不是打印,也不是返回。 |
*…* | 返回表达式;句中以返回、Return 等明确引出。 |
*None* / **** | 显式返回空值或结束当前函数。 |
[键](集合) | 正文显示描述,侧注按函数与参数、可跳转链接、结构化内容展示括号内的细节;空括号表示待补充实际逻辑。阅读不会执行调用。classic 模式保留旧链接取元。 |
修饰… [函数] … | 兼容的带修饰调用;不能把任意普通链接当作执行授权。 |
集合[^键] | 兼容的脚注取元;当前库优先用 access 读取集合。 |
*仅* / **说明** | 普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。 |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | None; execute this page's documented steps in order and observe their output or stated effects |
lib/foreign runs code fences and inline sources with local interpreters. v2 keeps the Markdown surface unchanged while adding structured records, JSON in/out, parallel fan-out, persistent Python/Node kernels and an explicit state bridge.
The same file is still a document: a bound fence is readable Markdown, and foreign.* turns it into an executable unit.
Probe before you run.
函数调用Compute node
foreign.probe- lang
- node
原始写法
foreign.probe(lang="node")函数调用Display this step's result
print- text
- ok
access- 参数 1
`node`- 参数 2
- ok
原始写法
> print text=[ok](access(`node`, "ok"))函数调用Display this step's result
print- text
- version
access- 参数 1
`node`- 参数 2
- version
原始写法
> print text=[version](access(`node`, "version"))probe returns {lang, cmd, path, ok, version, error}. Omit lang to inspect every known language.
A structured record, not just stdout.
console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950));
CN¥950.00 — 40ms
函数调用Compute record
foreign.invoke- code
`marker`
原始写法
foreign.invoke(code=`marker`)函数调用Display this step's result
print- text
- ok
access- 参数 1
`record`- 参数 2
- ok
原始写法
> print text=[ok](access(`record`, "ok"))函数调用Display this step's result
print- text
- stdout
access- 参数 1
`record`- 参数 2
- stdout
原始写法
> print text=[stdout](access(`record`, "stdout"))函数调用Display this step's result
print- text
- code
access- 参数 1
`record`- 参数 2
- code
原始写法
> print text=[code](access(`record`, "code"))invoke never throws on a process failure. Read ok, code, stdout, stderr, ms, timed_out, truncated, result and error from one record.
JSON in, JSON out.
let input = "";
process.stdin.on("data", chunk => { input += chunk; });
process.stdin.on("end", () => {
console.log(JSON.stringify(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(JSON.parse(input))));
});
"CN¥21.00" — 40ms
函数调用Compute single
foreign.call- code
`format_money`- input
21
原始写法
foreign.call(code=`format_money`, input=21)函数调用Display this step's result
print- text
`single`
原始写法
> print text=`single`The input is encoded as JSON on stdin; the last stdout value is parsed as JSON. Use output="json" with invoke when you also want the raw record.
Parallel fan-out.
| value |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
This single-column bound table is a native list of numbers, ready for the batch call.
函数调用Format each amount while retaining input order
foreign.call_many- code
`format_money`- inputs
`numbers`- concurrency
4
原始写法
foreign.call_many(code=`format_money`, inputs=`numbers`, concurrency=4)函数调用Display this step's result
print- text
`formatted_batch`
原始写法
> print text=`formatted_batch`call_many applies one program to every input, runs independently, preserves input order, and returns parsed JSON results. run_many does the same for full invoke-option maps.
A persistent kernel.
函数调用Compute session
foreign.session_open- lang
- node
原始写法
foreign.session_open(lang="node")函数调用Compute first
foreign.session_eval- id
`session`- source
- var money = new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"});
原始写法
foreign.session_eval(id=`session`, source="var money = new Intl.NumberFormat(\"en-US\", {style:\"currency\", currency:\"CNY\"});")函数调用Compute second
foreign.session_eval- id
`session`- source
- money.format(21)
原始写法
foreign.session_eval(id=`session`, source="money.format(21)")函数调用Display this step's result
print- text
- result
access- 参数 1
`second`- 参数 2
- result
原始写法
> print text=[result](access(`second`, "result"))Variables created in the first evaluation survive into the second. The kernel is not a shell: use session_eval, session_get, session_names, then session_close.
The explicit state bridge.
函数调用Copy the explicit rate into the existing kernel
foreign.session_set- id
`session`- name
- rate
- value
0.08
原始写法
foreign.session_set(id=`session`, name="rate", value=0.08)函数调用Compute rate
foreign.session_get- id
`session`- name
- rate
原始写法
foreign.session_get(id=`session`, name="rate")函数调用Display this step's result
print- text
`rate`
原始写法
> print text=`rate`函数调用Close this persistent formatting kernel
foreign.session_close- id
`session`
原始写法
foreign.session_close(id=`session`)This is a JSON copy, not shared memory. The kernel receives a value; Marqdo receives a value. There is no implicit mirroring and no hidden global namespace.
Cells in view.
foreign.session owns the document's kernel state. The kernel and cell order are ordinary tables passed as arguments; the names are free:
`分析内核` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | node | | shared analysis |
| 复核 | node | | isolated review |
`分析单元` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | write state |
| 计算指标 | 分析 | read state |
| 独立复核 | 复核 | isolated kernel |
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
view consumes the 会话 handle and adds Run All, Step, kernel switching, a journal and per-cell state. Without 会话, view cells are stateless one-shot runs: same shell, no persistent kernel. There is no second CLI mode. See the native-first Intl workflow in features/19-foreign-view-cells.mq.md.
跳转链接features/19-foreign-view-cells.mq.md
原始写法
../features/19-foreign-view-cells.mq.mdSafety defaults.
| Boundary | Default |
|---|---|
| Execution | requires the host execution capability |
| Shell | no shell; arguments are split explicitly |
| Output | bounded, with truncated |
| Timeout | process group killed on Unix / taskkill /T on Windows |
| CWD | starts at the granted root; the child retains normal OS authority |
| Parallelism | capped fan-out; each item isolated |
Read the full API in ../../lib/foreign.mq.md and the design in ../../doc/design/foreign-kernel.md.
跳转链接../../lib/foreign.mq.md
原始写法
../../lib/foreign.mq.md跳转链接../../doc/design/foreign-kernel.md
原始写法
../../doc/design/foreign-kernel.mdFunctions
Variables
-
description textStructured execution, JSON calls, parallel fan-out, persistent kernels and an explicit state bridgeStructured execution, JSON calls, parallel fan-out, persistent kernels and an explicit state bridge
-
first map · 16
ok True code 0 stdout stderr ms 33 lang node … key value ok True code 0 stdout stderr ms 33 lang node cmd node timed_out False truncated False result None result_error error script cached False alive True id s1 -
format_money code · node```node let input = ""; process.stdin.on("data", chunk => { input += chunk; }); process.stdin.on("end", () => { console.log(JSON.stringify(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(JSON.parse(input)))); }); ``````node let input = ""; process.stdin.on("data", chunk => { input += chunk; }); process.stdin.on("end", () => { console.log(JSON.stringify(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(JSON.parse(input)))); }); ```
-
formatted_batch list · 4
# value 1 CN¥1.00 2 CN¥2.00 3 CN¥3.00 4 CN¥4.00 # value 1 CN¥1.00 2 CN¥2.00 3 CN¥3.00 4 CN¥4.00 -
marker code · node```node console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950)); ``````node console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950)); ```
-
markup textocclusionocclusion
-
node map · 6
lang node cmd node -v path /usr/local/bin/node ok True version v24.22.3 error key value lang node cmd node -v path /usr/local/bin/node ok True version v24.22.3 error -
numbers list · 4
# value 1 1 2 2 3 3 4 4 # value 1 1 2 2 3 3 4 4 -
rate num0.080.08
-
record map · 15
ok True code 0 stdout CN¥950.00 stderr ms 40 lang node … key value ok True code 0 stdout CN¥950.00 stderr ms 40 lang node cmd node /home/runner/work/marqdo/marqdo/public/.marqdo/tmp/marqdo-foreign-5198-1794999077235731668.js timed_out False truncated False result None result_error error script diagnostic_source /home/runner/work/marqdo/marqdo/public/.marqdo/tmp/marqdo-foreign-5198-1794999077235731668.js cached False -
second map · 16
ok True code 0 stdout stderr ms 0 lang node … key value ok True code 0 stdout stderr ms 0 lang node cmd node timed_out False truncated False result CN¥21.00 result_error error script cached False alive True id s1 -
session handle<handle><handle>
-
single textCN¥21.00CN¥21.00
-
stdin int2121
-
title textlib/foreign — foreign kernels v2lib/foreign — foreign kernels v2
可执行知识 · 输入、返回与依据
这份文档怎样成为可调用的知识
1 个知识单元 · 47 个结构步骤。先读输入、返回与调用边界,再按需查看依赖和依据。
以下来自静态分析,不代表程序已经运行、测试通过或内容已获领域确认。实际运行见正文标注与“运行与结果”。
main程序入口
这是程序入口或对象声明。成员函数的输入输出在各自说明中列出。
源码中的返回契约
any · None; execute this page's documented steps in order and observe their output or stated effects
调用边界
输出文本、启动进程。权限由实际运行入口授予;静态副作用信息不等于运行许可。
当前有哪些依据
- 语法与引用
- 检查通过;检查通过
- 契约检查
- 尚未检查
- 测试记录
- 没有可用记录
- 内容来源
- 尚无已核验证据
- 领域审阅
- 尚未进行领域审阅
查看本单元的结构步骤
这是源码结构,不是实际执行时序;正文引用不会因阅读而执行。
- 调用Compute node
- 观察stdout
- 调用Display this step's result
- 观察code
- 调用Compute single
- 调用Display this step's result
- 调用Format each amount while retaining input order
- 调用Display this step's result
- 调用Compute session
- 调用Compute first
- 调用Compute second
- 调用Display this step's result
- 调用Display this step's result
- 观察result
- 调用Copy the explicit rate into the existing kernel
- 调用Compute rate
- 调用Display this step's result
- 调用Close this persistent formatting kernel
- 正文引用Compute node
- 正文引用Display this step's result
- 正文引用Display this step's result
- 正文引用Compute record
- 观察ok
- 正文引用Display this step's result
- 正文引用Display this step's result
- 正文引用Display this step's result
- 正文引用Compute single
- 正文引用Display this step's result
- 正文引用Format each amount while retaining input order
- 正文引用Display this step's result
- 正文引用Compute session
- 正文引用Compute first
- 正文引用Compute second
- 调用Display this step's result
- 正文引用Display this step's result
- 正文引用Copy the explicit rate into the existing kernel
- 正文引用Compute rate
- 正文引用Display this step's result
- 正文引用Close this persistent formatting kernel
- navigation`features/19-foreign-view-cells.mq.md`
- navigation../../lib/foreign.mq.md
- navigation../../doc/design/foreign-kernel.md
- 观察version
- 调用Compute record
- 调用Display this step's result
- 观察ok
- 调用Display this step's result
技术详情:身份、摘要与原始状态
- 目标标识
mq://public/stdlib%2Fforeign/type/main- 制品摘要(未检查锁定状态)
sha256:b47994f62fece70cc124f21b44544bf24071ba72e11a1f1510feaf7b7ddbfa7e- 依赖标识
- 原始验证状态
parse: passed; resolve: passed; contract: unchecked; execution: not_run; tests: unknown; evidence: unverified; domain: unreviewed
运行与结果
完整源码
---
markup: occlusion
title: lib/foreign — foreign kernels v2
description: Structured execution, JSON calls, parallel fan-out, persistent kernels and an explicit state bridge
import:
foreign: lib/foreign.mq.md
stdin: 21
---
# main
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | None; execute this page's documented steps in order and observe their output or stated effects |
`lib/foreign` runs code fences and inline sources with local interpreters. v2 keeps the Markdown surface unchanged while adding structured records, JSON in/out, parallel fan-out, persistent Python/Node kernels and an explicit state bridge.
The same file is still a document: a bound fence is readable Markdown, and `foreign.*` turns it into an executable unit.
---
Probe before you run.
We first **node = [Compute node](foreign.probe(lang="node"))** for the next step.
We now **[Display this step's result](> print text=[ok](access(`node`, "ok")))**.
We now **[Display this step's result](> print text=[version](access(`node`, "version")))**.
`probe` returns `{lang, cmd, path, ok, version, error}`. Omit `lang` to inspect every known language.
---
A structured record, not just stdout.
`marker` =
```node
console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950));
```
We first **record = [Compute record](foreign.invoke(code=`marker`))** for the next step.
We now **[Display this step's result](> print text=[ok](access(`record`, "ok")))**.
We now **[Display this step's result](> print text=[stdout](access(`record`, "stdout")))**.
We now **[Display this step's result](> print text=[code](access(`record`, "code")))**.
`invoke` never throws on a process failure. Read `ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result` and `error` from one record.
---
JSON in, JSON out.
`format_money` =
```node
let input = "";
process.stdin.on("data", chunk => { input += chunk; });
process.stdin.on("end", () => {
console.log(JSON.stringify(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(JSON.parse(input))));
});
```
We first **single = [Compute single](foreign.call(code=`format_money`, input=21))** for the next step.
We now **[Display this step's result](> print text=`single`)**.
The input is encoded as JSON on stdin; the last stdout value is parsed as JSON. Use `output="json"` with `invoke` when you also want the raw record.
---
Parallel fan-out.
`numbers` =
| value |
|-------|
| 1 |
| 2 |
| 3 |
| 4 |
This single-column bound table is a native list of numbers, ready for the batch call.
We **formatted_batch = [Format each amount while retaining input order](foreign.call_many(code=`format_money`, inputs=`numbers`, concurrency=4))**.
We now **[Display this step's result](> print text=`formatted_batch`)**.
`call_many` applies one program to every input, runs independently, preserves input order, and returns parsed JSON results. `run_many` does the same for full invoke-option maps.
---
A persistent kernel.
We first **session = [Compute session](foreign.session_open(lang="node"))** for the next step.
We first **first = [Compute first](foreign.session_eval(id=`session`, source="var money = new Intl.NumberFormat(\"en-US\", {style:\"currency\", currency:\"CNY\"});"))** for the next step.
We first **second = [Compute second](foreign.session_eval(id=`session`, source="money.format(21)"))** for the next step.
We now **[Display this step's result](> print text=[result](access(`second`, "result")))**.
Variables created in the first evaluation survive into the second. The kernel is not a shell: use `session_eval`, `session_get`, `session_names`, then `session_close`.
---
The explicit state bridge.
We **[Copy the explicit rate into the existing kernel](foreign.session_set(id=`session`, name="rate", value=0.08))**.
We first **rate = [Compute rate](foreign.session_get(id=`session`, name="rate"))** for the next step.
We now **[Display this step's result](> print text=`rate`)**.
After reading the copied value, we **[Close this persistent formatting kernel](foreign.session_close(id=`session`))**.
This is a JSON copy, not shared memory. The kernel receives a value; Marqdo receives a value. There is no implicit mirroring and no hidden global namespace.
---
Cells in view.
`foreign.session` owns the document's kernel state. The kernel and cell order are ordinary tables passed as arguments; the names are free:
```text
`分析内核` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | node | | shared analysis |
| 复核 | node | | isolated review |
`分析单元` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | write state |
| 计算指标 | 分析 | read state |
| 独立复核 | 复核 | isolated kernel |
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
```
`view` consumes the `会话` handle and adds Run All, Step, kernel switching, a journal and per-cell state. Without `会话`, view cells are stateless one-shot runs: same shell, no persistent kernel. There is no second CLI mode. See the native-first Intl workflow in [`features/19-foreign-view-cells.mq.md`](../features/19-foreign-view-cells.mq.md).
---
Safety defaults.
| Boundary | Default |
|---|---|
| Execution | requires the host execution capability |
| Shell | no shell; arguments are split explicitly |
| Output | bounded, with truncated |
| Timeout | process group killed on Unix / taskkill /T on Windows |
| CWD | starts at the granted root; the child retains normal OS authority |
| Parallelism | capped fan-out; each item isolated |
Read the full API in [../../lib/foreign.mq.md](../../lib/foreign.mq.md) and the design in [../../doc/design/foreign-kernel.md](../../doc/design/foreign-kernel.md).