MarqdoEXECUTABLE KNOWLEDGE

lib/foreign — foreign kernels v2ok

stdlib/foreign.mq.md

文档

怎样读这份可执行文档

正文说明意图,标记指出哪些片段会执行。遮蔽只在正文显示动作说明,实际逻辑放在侧注;阅读、展开与定位都不会运行代码。

标记阅读含义
无标记文字作者的解释,按普通 Markdown 阅读。
空行分隔叙述与结构,不是计算步骤。
# / ##一级标题声明对象或入口,更深标题声明函数;说明按钮可查看输入、返回与依据。
>调用函数;实际执行结果另有标注。
1. 递增按条件选择分支,不是普通编号说明。
-重复或遍历结构;迭代选择器只切换已有运行记录。
+ `名`兼容的显式形参;新库优先在叙述中声明参数,标题下的表格解释契约。
GFM 表未绑定的契约表是说明;绑定表按列、行和 @ 形态构成数据。
```lang代码块;绑定的外语代码与普通示例区分展示,数学公式另有公式卡片。
--- / ***分隔内容,不能把分隔线当作函数返回。
<!-- marqdo-out -->程序写回的结果,区别于作者原始正文。
`名`叙述中的参数或变量;默认值跟在名称之后。
**…**执行语句:赋值、调用或计算;不是打印,也不是返回。
*…*返回表达式;句中以返回、Return 等明确引出。
*None* / ****显式返回空值或结束当前函数。
[键](集合)正文显示描述,侧注按函数与参数、可跳转链接、结构化内容展示括号内的细节;空括号表示待补充实际逻辑。阅读不会执行调用。classic 模式保留旧链接取元。
修饰… [函数] …兼容的带修饰调用;不能把任意普通链接当作执行授权。
集合[^键]兼容的脚注取元;当前库优先用 access 读取集合。
*仅* / **说明**普通强调仍属于文字;界面按真实解析结果区分强调、语句与返回。
foreign:lib/foreign.mq.md

main

说明
返回类型说明
resultanyNone; 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 = for the next step.
函数调用Compute node
foreign.probe
lang
node
原始写法
foreign.probe(lang="node")
源码说明 · 不是运行结果
We now .
函数调用Display this step's result
print
text
ok
access
参数 1
`node`
参数 2
ok
原始写法
> print text=[ok](access(`node`, "ok"))
源码说明 · 不是运行结果
We now .
函数调用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.

code marker node
console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950));
CN¥950.00


— 40ms
We first record = for the next step.
函数调用Compute record
foreign.invoke
code
`marker`
原始写法
foreign.invoke(code=`marker`)
源码说明 · 不是运行结果
We now .
函数调用Display this step's result
print
text
ok
access
参数 1
`record`
参数 2
ok
原始写法
> print text=[ok](access(`record`, "ok"))
源码说明 · 不是运行结果
We now .
函数调用Display this step's result
print
text
stdout
access
参数 1
`record`
参数 2
stdout
原始写法
> print text=[stdout](access(`record`, "stdout"))
源码说明 · 不是运行结果
We now .
函数调用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.

code 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))));
});
"CN¥21.00"


— 40ms
We first single = for the next step.
函数调用Compute single
foreign.call
code
`format_money`
input
21
原始写法
foreign.call(code=`format_money`, input=21)
源码说明 · 不是运行结果
We now .
函数调用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.

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
原始写法
foreign.call_many(code=`format_money`, inputs=`numbers`, concurrency=4)
源码说明 · 不是运行结果
We now .
函数调用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.

We first session = for the next step.
函数调用Compute session
foreign.session_open
lang
node
原始写法
foreign.session_open(lang="node")
源码说明 · 不是运行结果
We first first = for the next step.
函数调用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\"});")
源码说明 · 不是运行结果
We first second = for the next step.
函数调用Compute second
foreign.session_eval
id
`session`
source
money.format(21)
原始写法
foreign.session_eval(id=`session`, source="money.format(21)")
源码说明 · 不是运行结果
We now .
函数调用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.

We .
函数调用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)
源码说明 · 不是运行结果
We first rate = for the next step.
函数调用Compute rate
foreign.session_get
id
`session`
name
rate
原始写法
foreign.session_get(id=`session`, name="rate")
源码说明 · 不是运行结果
We now .
函数调用Display this step's result
print
text
`rate`
原始写法
> print text=`rate`
源码说明 · 不是运行结果
After reading the copied value, we .
函数调用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:

code 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
../features/19-foreign-view-cells.mq.md打开链接 ↗
原始写法
../features/19-foreign-view-cells.mq.md
文档引用 · 阅读不会执行
---

Safety defaults.

BoundaryDefault
Executionrequires the host execution capability
Shellno shell; arguments are split explicitly
Outputbounded, with truncated
Timeoutprocess group killed on Unix / taskkill /T on Windows
CWDstarts at the granted root; the child retains normal OS authority
Parallelismcapped 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打开链接 ↗
原始写法
../../lib/foreign.mq.md
文档引用 · 阅读不会执行
跳转链接../../doc/design/foreign-kernel.md
../../doc/design/foreign-kernel.md打开链接 ↗
原始写法
../../doc/design/foreign-kernel.md
文档引用 · 阅读不会执行
Functions
Variables
  • description text
    Structured execution, JSON calls, parallel fan-out, persistent kernels and an explicit state bridge
  • first map · 16
    okTrue
    code0
    stdout
    stderr
    ms33
    langnode
    …
  • 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)))); }); ```
  • formatted_batch list · 4
    #value
    1CN¥1.00
    2CN¥2.00
    3CN¥3.00
    4CN¥4.00
  • marker code · node
    ```node console.log(new Intl.NumberFormat("en-US", {style:"currency", currency:"CNY"}).format(950)); ```
  • markup text
    occlusion
  • node map · 6
    langnode
    cmdnode -v
    path/usr/local/bin/node
    okTrue
    versionv24.22.3
    error
  • numbers list · 4
    #value
    11
    22
    33
    44
  • rate num
    0.08
  • record map · 15
    okTrue
    code0
    stdoutCN¥950.00
    stderr
    ms40
    langnode
    …
  • second map · 16
    okTrue
    code0
    stdout
    stderr
    ms0
    langnode
    …
  • session handle
    <handle>
  • single text
    CN¥21.00
  • stdin int
    21
  • title text
    lib/foreign — foreign kernels v2
可执行知识 · 输入、返回与依据

这份文档怎样成为可调用的知识

1 个知识单元 · 47 个结构步骤。先读输入、返回与调用边界,再按需查看依赖和依据。

以下来自静态分析,不代表程序已经运行、测试通过或内容已获领域确认。实际运行见正文标注与“运行与结果”。

main程序入口
回到正文 · 第 10 行

这是程序入口或对象声明。成员函数的输入输出在各自说明中列出。

源码中的返回契约

any · None; execute this page's documented steps in order and observe their output or stated effects

调用边界

输出文本、启动进程。权限由实际运行入口授予;静态副作用信息不等于运行许可。

当前有哪些依据

语法与引用
检查通过;检查通过
契约检查
尚未检查
测试记录
没有可用记录
内容来源
尚无已核验证据
领域审阅
尚未进行领域审阅
查看本单元的结构步骤

这是源码结构,不是实际执行时序;正文引用不会因阅读而执行。

  1. 调用Compute node
  2. 观察stdout
  3. 调用Display this step's result
  4. 观察code
  5. 调用Compute single
  6. 调用Display this step's result
  7. 调用Format each amount while retaining input order
  8. 调用Display this step's result
  9. 调用Compute session
  10. 调用Compute first
  11. 调用Compute second
  12. 调用Display this step's result
  13. 调用Display this step's result
  14. 观察result
  15. 调用Copy the explicit rate into the existing kernel
  16. 调用Compute rate
  17. 调用Display this step's result
  18. 调用Close this persistent formatting kernel
  19. 正文引用Compute node
  20. 正文引用Display this step's result
  21. 正文引用Display this step's result
  22. 正文引用Compute record
  23. 观察ok
  24. 正文引用Display this step's result
  25. 正文引用Display this step's result
  26. 正文引用Display this step's result
  27. 正文引用Compute single
  28. 正文引用Display this step's result
  29. 正文引用Format each amount while retaining input order
  30. 正文引用Display this step's result
  31. 正文引用Compute session
  32. 正文引用Compute first
  33. 正文引用Compute second
  34. 调用Display this step's result
  35. 正文引用Display this step's result
  36. 正文引用Copy the explicit rate into the existing kernel
  37. 正文引用Compute rate
  38. 正文引用Display this step's result
  39. 正文引用Close this persistent formatting kernel
  40. navigation`features/19-foreign-view-cells.mq.md`
  41. navigation../../lib/foreign.mq.md
  42. navigation../../doc/design/foreign-kernel.md
  43. 观察version
  44. 调用Compute record
  45. 调用Display this step's result
  46. 观察ok
  47. 调用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

运行与结果

True v24.22.3 True CN¥950.00 0 CN¥21.00 [CN¥1.00, CN¥2.00, CN¥3.00, CN¥4.00] CN¥21.00 0.08
完整源码
---
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).

Variable